Toplevel.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Linq;
  5. namespace Terminal.Gui {
  6. /// <summary>
  7. /// Toplevel views can be modally executed. They are used for both an application's main view (filling the entire screeN and
  8. /// for pop-up views such as <see cref="Dialog"/>, <see cref="MessageBox"/>, and <see cref="Wizard"/>.
  9. /// </summary>
  10. /// <remarks>
  11. /// <para>
  12. /// Toplevels can be modally executing views, started by calling <see cref="Application.Run(Toplevel, Func{Exception, bool})"/>.
  13. /// They return control to the caller when <see cref="Application.RequestStop(Toplevel)"/> has
  14. /// been called (which sets the <see cref="Toplevel.Running"/> property to <c>false</c>).
  15. /// </para>
  16. /// <para>
  17. /// A Toplevel is created when an application initializes Terminal.Gui by calling <see cref="Application.Init(ConsoleDriver, IMainLoopDriver)"/>.
  18. /// The application Toplevel can be accessed via <see cref="Application.Top"/>. Additional Toplevels can be created
  19. /// and run (e.g. <see cref="Dialog"/>s. To run a Toplevel, create the <see cref="Toplevel"/> and
  20. /// call <see cref="Application.Run(Toplevel, Func{Exception, bool})"/>.
  21. /// </para>
  22. /// </remarks>
  23. public class Toplevel : View {
  24. /// <summary>
  25. /// Gets or sets whether the <see cref="MainLoop"/> for this <see cref="Toplevel"/> is running or not.
  26. /// </summary>
  27. /// <remarks>
  28. /// Setting this property directly is discouraged. Use <see cref="Application.RequestStop"/> instead.
  29. /// </remarks>
  30. public bool Running { get; set; }
  31. /// <summary>
  32. /// Invoked when the Toplevel <see cref="Application.RunState"/> has begun to be loaded.
  33. /// A Loaded event handler is a good place to finalize initialization before calling
  34. /// <see cref="Application.RunLoop(Application.RunState, bool)"/>.
  35. /// </summary>
  36. public event EventHandler Loaded;
  37. /// <summary>
  38. /// Invoked when the Toplevel <see cref="MainLoop"/> has started it's first iteration.
  39. /// Subscribe to this event to perform tasks when the <see cref="Toplevel"/> has been laid out and focus has been set.
  40. /// changes.
  41. /// <para>A Ready event handler is a good place to finalize initialization after calling
  42. /// <see cref="Application.Run(Func{Exception, bool})"/> on this Toplevel.</para>
  43. /// </summary>
  44. public event EventHandler Ready;
  45. /// <summary>
  46. /// Invoked when the Toplevel <see cref="Application.RunState"/> has been unloaded.
  47. /// A Unloaded event handler is a good place to dispose objects after calling <see cref="Application.End(Application.RunState)"/>.
  48. /// </summary>
  49. public event EventHandler Unloaded;
  50. /// <summary>
  51. /// Invoked when the Toplevel <see cref="Application.RunState"/> becomes the <see cref="Application.Current"/> Toplevel.
  52. /// </summary>
  53. public event EventHandler<ToplevelEventArgs> Activate;
  54. /// <summary>
  55. /// Invoked when the Toplevel<see cref="Application.RunState"/> ceases to be the <see cref="Application.Current"/> Toplevel.
  56. /// </summary>
  57. public event EventHandler<ToplevelEventArgs> Deactivate;
  58. /// <summary>
  59. /// Invoked when a child of the Toplevel <see cref="Application.RunState"/> is closed by
  60. /// <see cref="Application.End(Application.RunState)"/>.
  61. /// </summary>
  62. public event EventHandler<ToplevelEventArgs> ChildClosed;
  63. /// <summary>
  64. /// Invoked when the last child of the Toplevel <see cref="Application.RunState"/> is closed from
  65. /// by <see cref="Application.End(Application.RunState)"/>.
  66. /// </summary>
  67. public event EventHandler AllChildClosed;
  68. /// <summary>
  69. /// Invoked when the Toplevel's <see cref="Application.RunState"/> is being closed by
  70. /// <see cref="Application.RequestStop(Toplevel)"/>.
  71. /// </summary>
  72. public event EventHandler<ToplevelClosingEventArgs> Closing;
  73. /// <summary>
  74. /// Invoked when the Toplevel's <see cref="Application.RunState"/> is closed by <see cref="Application.End(Application.RunState)"/>.
  75. /// </summary>
  76. public event EventHandler<ToplevelEventArgs> Closed;
  77. /// <summary>
  78. /// Invoked when a child Toplevel's <see cref="Application.RunState"/> has been loaded.
  79. /// </summary>
  80. public event EventHandler<ToplevelEventArgs> ChildLoaded;
  81. /// <summary>
  82. /// Invoked when a cjhild Toplevel's <see cref="Application.RunState"/> has been unloaded.
  83. /// </summary>
  84. public event EventHandler<ToplevelEventArgs> ChildUnloaded;
  85. /// <summary>
  86. /// Invoked when the terminal has been resized. The new <see cref="Size"/> of the terminal is provided.
  87. /// </summary>
  88. public event EventHandler<SizeChangedEventArgs> Resized;
  89. internal virtual void OnResized (SizeChangedEventArgs size)
  90. {
  91. Resized?.Invoke (this, size);
  92. }
  93. internal virtual void OnChildUnloaded (Toplevel top)
  94. {
  95. ChildUnloaded?.Invoke (this, new ToplevelEventArgs (top));
  96. }
  97. internal virtual void OnChildLoaded (Toplevel top)
  98. {
  99. ChildLoaded?.Invoke (this, new ToplevelEventArgs (top));
  100. }
  101. internal virtual void OnClosed (Toplevel top)
  102. {
  103. Closed?.Invoke (this, new ToplevelEventArgs (top));
  104. }
  105. internal virtual bool OnClosing (ToplevelClosingEventArgs ev)
  106. {
  107. Closing?.Invoke (this, ev);
  108. return ev.Cancel;
  109. }
  110. internal virtual void OnAllChildClosed ()
  111. {
  112. AllChildClosed?.Invoke (this, EventArgs.Empty);
  113. }
  114. internal virtual void OnChildClosed (Toplevel top)
  115. {
  116. if (IsMdiContainer) {
  117. SetSubViewNeedsDisplay ();
  118. }
  119. ChildClosed?.Invoke (this, new ToplevelEventArgs (top));
  120. }
  121. internal virtual void OnDeactivate (Toplevel activated)
  122. {
  123. Deactivate?.Invoke (this, new ToplevelEventArgs (activated));
  124. }
  125. internal virtual void OnActivate (Toplevel deactivated)
  126. {
  127. Activate?.Invoke (this, new ToplevelEventArgs (deactivated));
  128. }
  129. /// <summary>
  130. /// Called from <see cref="Application.Begin(Toplevel)"/> before the <see cref="Toplevel"/> redraws for the first time.
  131. /// </summary>
  132. virtual public void OnLoaded ()
  133. {
  134. IsLoaded = true;
  135. foreach (Toplevel tl in Subviews.Where (v => v is Toplevel)) {
  136. tl.OnLoaded ();
  137. }
  138. Loaded?.Invoke (this, EventArgs.Empty);
  139. }
  140. /// <summary>
  141. /// Called from <see cref="Application.RunLoop"/> after the <see cref="Toplevel"/> has entered the
  142. /// first iteration of the loop.
  143. /// </summary>
  144. internal virtual void OnReady ()
  145. {
  146. foreach (Toplevel tl in Subviews.Where (v => v is Toplevel)) {
  147. tl.OnReady ();
  148. }
  149. Ready?.Invoke (this, EventArgs.Empty);
  150. }
  151. /// <summary>
  152. /// Called from <see cref="Application.End(Application.RunState)"/> before the <see cref="Toplevel"/> is disposed.
  153. /// </summary>
  154. internal virtual void OnUnloaded ()
  155. {
  156. foreach (Toplevel tl in Subviews.Where (v => v is Toplevel)) {
  157. tl.OnUnloaded ();
  158. }
  159. Unloaded?.Invoke (this, EventArgs.Empty);
  160. }
  161. /// <summary>
  162. /// Initializes a new instance of the <see cref="Toplevel"/> class with the specified <see cref="LayoutStyle.Absolute"/> layout.
  163. /// </summary>
  164. /// <param name="frame">A superview-relative rectangle specifying the location and size for the new Toplevel</param>
  165. public Toplevel (Rect frame) : base (frame)
  166. {
  167. SetInitialProperties ();
  168. }
  169. /// <summary>
  170. /// Initializes a new instance of the <see cref="Toplevel"/> class with <see cref="LayoutStyle.Computed"/> layout,
  171. /// defaulting to full screen.
  172. /// </summary>
  173. public Toplevel () : base ()
  174. {
  175. SetInitialProperties ();
  176. Width = Dim.Fill ();
  177. Height = Dim.Fill ();
  178. }
  179. void SetInitialProperties ()
  180. {
  181. ColorScheme = Colors.TopLevel;
  182. Application.GrabbingMouse += Application_GrabbingMouse;
  183. Application.UnGrabbingMouse += Application_UnGrabbingMouse;
  184. // TODO: v2 - ALL Views (Responders??!?!) should support the commands related to
  185. // - Focus
  186. // Move the appropriate AddCommand calls to `Responder`
  187. // Things this view knows how to do
  188. AddCommand (Command.QuitToplevel, () => { QuitToplevel (); return true; });
  189. AddCommand (Command.Suspend, () => { Driver.Suspend (); ; return true; });
  190. AddCommand (Command.NextView, () => { MoveNextView (); return true; });
  191. AddCommand (Command.PreviousView, () => { MovePreviousView (); return true; });
  192. AddCommand (Command.NextViewOrTop, () => { MoveNextViewOrTop (); return true; });
  193. AddCommand (Command.PreviousViewOrTop, () => { MovePreviousViewOrTop (); return true; });
  194. AddCommand (Command.Refresh, () => { Application.Refresh (); return true; });
  195. // Default keybindings for this view
  196. AddKeyBinding (Application.QuitKey, Command.QuitToplevel);
  197. AddKeyBinding (Key.Z | Key.CtrlMask, Command.Suspend);
  198. AddKeyBinding (Key.Tab, Command.NextView);
  199. AddKeyBinding (Key.CursorRight, Command.NextView);
  200. AddKeyBinding (Key.F | Key.CtrlMask, Command.NextView);
  201. AddKeyBinding (Key.CursorDown, Command.NextView);
  202. AddKeyBinding (Key.I | Key.CtrlMask, Command.NextView); // Unix
  203. AddKeyBinding (Key.BackTab | Key.ShiftMask, Command.PreviousView);
  204. AddKeyBinding (Key.CursorLeft, Command.PreviousView);
  205. AddKeyBinding (Key.CursorUp, Command.PreviousView);
  206. AddKeyBinding (Key.B | Key.CtrlMask, Command.PreviousView);
  207. AddKeyBinding (Key.Tab | Key.CtrlMask, Command.NextViewOrTop);
  208. AddKeyBinding (Application.AlternateForwardKey, Command.NextViewOrTop); // Needed on Unix
  209. AddKeyBinding (Key.Tab | Key.ShiftMask | Key.CtrlMask, Command.PreviousViewOrTop);
  210. AddKeyBinding (Application.AlternateBackwardKey, Command.PreviousViewOrTop); // Needed on Unix
  211. AddKeyBinding (Key.L | Key.CtrlMask, Command.Refresh);
  212. }
  213. private void Application_UnGrabbingMouse (object sender, GrabMouseEventArgs e)
  214. {
  215. if (Application.MouseGrabView == this && dragPosition.HasValue) {
  216. e.Cancel = true;
  217. }
  218. }
  219. private void Application_GrabbingMouse (object sender, GrabMouseEventArgs e)
  220. {
  221. if (Application.MouseGrabView == this && dragPosition.HasValue) {
  222. e.Cancel = true;
  223. }
  224. }
  225. /// <summary>
  226. /// Invoked when the <see cref="Application.AlternateForwardKey"/> is changed.
  227. /// </summary>
  228. public event EventHandler<KeyChangedEventArgs> AlternateForwardKeyChanged;
  229. /// <summary>
  230. /// Virtual method to invoke the <see cref="AlternateForwardKeyChanged"/> event.
  231. /// </summary>
  232. /// <param name="e"></param>
  233. public virtual void OnAlternateForwardKeyChanged (KeyChangedEventArgs e)
  234. {
  235. ReplaceKeyBinding (e.OldKey, e.NewKey);
  236. AlternateForwardKeyChanged?.Invoke (this, e);
  237. }
  238. /// <summary>
  239. /// Invoked when the <see cref="Application.AlternateBackwardKey"/> is changed.
  240. /// </summary>
  241. public event EventHandler<KeyChangedEventArgs> AlternateBackwardKeyChanged;
  242. /// <summary>
  243. /// Virtual method to invoke the <see cref="AlternateBackwardKeyChanged"/> event.
  244. /// </summary>
  245. /// <param name="e"></param>
  246. public virtual void OnAlternateBackwardKeyChanged (KeyChangedEventArgs e)
  247. {
  248. ReplaceKeyBinding (e.OldKey, e.NewKey);
  249. AlternateBackwardKeyChanged?.Invoke (this, e);
  250. }
  251. /// <summary>
  252. /// Invoked when the <see cref="Application.QuitKey"/> is changed.
  253. /// </summary>
  254. public event EventHandler<KeyChangedEventArgs> QuitKeyChanged;
  255. /// <summary>
  256. /// Virtual method to invoke the <see cref="QuitKeyChanged"/> event.
  257. /// </summary>
  258. /// <param name="e"></param>
  259. public virtual void OnQuitKeyChanged (KeyChangedEventArgs e)
  260. {
  261. ReplaceKeyBinding (e.OldKey, e.NewKey);
  262. QuitKeyChanged?.Invoke (this, e);
  263. }
  264. /// <summary>
  265. /// Convenience factory method that creates a new Toplevel with the current terminal dimensions.
  266. /// </summary>
  267. /// <returns>The created Toplevel.</returns>
  268. public static Toplevel Create ()
  269. {
  270. return new Toplevel (new Rect (0, 0, Driver.Cols, Driver.Rows));
  271. }
  272. /// <summary>
  273. /// Gets or sets a value indicating whether this <see cref="Toplevel"/> can focus.
  274. /// </summary>
  275. /// <value><c>true</c> if can focus; otherwise, <c>false</c>.</value>
  276. public override bool CanFocus {
  277. get => SuperView == null ? true : base.CanFocus;
  278. }
  279. /// <summary>
  280. /// Determines whether the <see cref="Toplevel"/> is modal or not.
  281. /// If set to <c>false</c> (the default):
  282. ///
  283. /// <list type="bullet">
  284. /// <item>
  285. /// <description><see cref="ProcessKey(KeyEvent)"/> events will propagate keys upwards.</description>
  286. /// </item>
  287. /// <item>
  288. /// <description>The Toplevel will act as an embedded view (not a modal/pop-up).</description>
  289. /// </item>
  290. /// </list>
  291. ///
  292. /// If set to <c>true</c>:
  293. ///
  294. /// <list type="bullet">
  295. /// <item>
  296. /// <description><see cref="ProcessKey(KeyEvent)"/> events will NOT propogate keys upwards.</description>
  297. /// </item>
  298. /// <item>
  299. /// <description>The Toplevel will and look like a modal (pop-up) (e.g. see <see cref="Dialog"/>.</description>
  300. /// </item>
  301. /// </list>
  302. /// </summary>
  303. public bool Modal { get; set; }
  304. /// <summary>
  305. /// Gets or sets the menu for this Toplevel.
  306. /// </summary>
  307. public virtual MenuBar MenuBar { get; set; }
  308. /// <summary>
  309. /// Gets or sets the status bar for this Toplevel.
  310. /// </summary>
  311. public virtual StatusBar StatusBar { get; set; }
  312. /// <summary>
  313. /// Gets or sets if this Toplevel is a Mdi container.
  314. /// </summary>
  315. public bool IsMdiContainer { get; set; }
  316. /// <summary>
  317. /// Gets or sets if this Toplevel is a Mdi child.
  318. /// </summary>
  319. public bool IsMdiChild {
  320. get {
  321. return Application.MdiTop != null && Application.MdiTop != this && !Modal;
  322. }
  323. }
  324. /// <summary>
  325. /// <see langword="true"/> if was already loaded by the <see cref="Application.Begin(Toplevel)"/>
  326. /// <see langword="false"/>, otherwise.
  327. /// </summary>
  328. public bool IsLoaded { get; private set; }
  329. ///<inheritdoc/>
  330. public override bool OnKeyDown (KeyEvent keyEvent)
  331. {
  332. if (base.OnKeyDown (keyEvent)) {
  333. return true;
  334. }
  335. switch (keyEvent.Key) {
  336. case Key.AltMask:
  337. case Key.AltMask | Key.Space:
  338. case Key.CtrlMask | Key.Space:
  339. case Key _ when (keyEvent.Key & Key.AltMask) == Key.AltMask:
  340. return MenuBar != null && MenuBar.OnKeyDown (keyEvent);
  341. }
  342. return false;
  343. }
  344. ///<inheritdoc/>
  345. public override bool OnKeyUp (KeyEvent keyEvent)
  346. {
  347. if (base.OnKeyUp (keyEvent)) {
  348. return true;
  349. }
  350. switch (keyEvent.Key) {
  351. case Key.AltMask:
  352. case Key.AltMask | Key.Space:
  353. case Key.CtrlMask | Key.Space:
  354. if (MenuBar != null && MenuBar.OnKeyUp (keyEvent)) {
  355. return true;
  356. }
  357. break;
  358. }
  359. return false;
  360. }
  361. ///<inheritdoc/>
  362. public override bool ProcessKey (KeyEvent keyEvent)
  363. {
  364. if (base.ProcessKey (keyEvent))
  365. return true;
  366. var result = InvokeKeybindings (new KeyEvent (ShortcutHelper.GetModifiersKey (keyEvent),
  367. new KeyModifiers () { Alt = keyEvent.IsAlt, Ctrl = keyEvent.IsCtrl, Shift = keyEvent.IsShift }));
  368. if (result != null)
  369. return (bool)result;
  370. #if false
  371. if (keyEvent.Key == Key.F5) {
  372. Application.DebugDrawBounds = !Application.DebugDrawBounds;
  373. SetNeedsDisplay ();
  374. return true;
  375. }
  376. #endif
  377. return false;
  378. }
  379. private void MovePreviousViewOrTop ()
  380. {
  381. if (Application.MdiTop == null) {
  382. var top = Modal ? this : Application.Top;
  383. top.FocusPrev ();
  384. if (top.Focused == null) {
  385. top.FocusPrev ();
  386. }
  387. top.SetNeedsDisplay ();
  388. Application.EnsuresTopOnFront ();
  389. } else {
  390. MovePrevious ();
  391. }
  392. }
  393. private void MoveNextViewOrTop ()
  394. {
  395. if (Application.MdiTop == null) {
  396. var top = Modal ? this : Application.Top;
  397. top.FocusNext ();
  398. if (top.Focused == null) {
  399. top.FocusNext ();
  400. }
  401. top.SetNeedsDisplay ();
  402. Application.EnsuresTopOnFront ();
  403. } else {
  404. MoveNext ();
  405. }
  406. }
  407. private void MovePreviousView ()
  408. {
  409. var old = GetDeepestFocusedSubview (Focused);
  410. if (!FocusPrev ())
  411. FocusPrev ();
  412. if (old != Focused && old != Focused?.Focused) {
  413. old?.SetNeedsDisplay ();
  414. Focused?.SetNeedsDisplay ();
  415. } else {
  416. FocusNearestView (SuperView?.TabIndexes?.Reverse (), Direction.Backward);
  417. }
  418. }
  419. private void MoveNextView ()
  420. {
  421. var old = GetDeepestFocusedSubview (Focused);
  422. if (!FocusNext ())
  423. FocusNext ();
  424. if (old != Focused && old != Focused?.Focused) {
  425. old?.SetNeedsDisplay ();
  426. Focused?.SetNeedsDisplay ();
  427. } else {
  428. FocusNearestView (SuperView?.TabIndexes, Direction.Forward);
  429. }
  430. }
  431. private void QuitToplevel ()
  432. {
  433. if (Application.MdiTop != null) {
  434. Application.MdiTop.RequestStop ();
  435. } else {
  436. Application.RequestStop ();
  437. }
  438. }
  439. ///<inheritdoc/>
  440. public override bool ProcessColdKey (KeyEvent keyEvent)
  441. {
  442. if (base.ProcessColdKey (keyEvent)) {
  443. return true;
  444. }
  445. if (ShortcutHelper.FindAndOpenByShortcut (keyEvent, this)) {
  446. return true;
  447. }
  448. return false;
  449. }
  450. View GetDeepestFocusedSubview (View view)
  451. {
  452. if (view == null) {
  453. return null;
  454. }
  455. foreach (var v in view.Subviews) {
  456. if (v.HasFocus) {
  457. return GetDeepestFocusedSubview (v);
  458. }
  459. }
  460. return view;
  461. }
  462. void FocusNearestView (IEnumerable<View> views, Direction direction)
  463. {
  464. if (views == null) {
  465. return;
  466. }
  467. bool found = false;
  468. bool focusProcessed = false;
  469. int idx = 0;
  470. foreach (var v in views) {
  471. if (v == this) {
  472. found = true;
  473. }
  474. if (found && v != this) {
  475. if (direction == Direction.Forward) {
  476. SuperView?.FocusNext ();
  477. } else {
  478. SuperView?.FocusPrev ();
  479. }
  480. focusProcessed = true;
  481. if (SuperView.Focused != null && SuperView.Focused != this) {
  482. return;
  483. }
  484. } else if (found && !focusProcessed && idx == views.Count () - 1) {
  485. views.ToList () [0].SetFocus ();
  486. }
  487. idx++;
  488. }
  489. }
  490. ///<inheritdoc/>
  491. public override void Add (View view)
  492. {
  493. AddMenuStatusBar (view);
  494. base.Add (view);
  495. }
  496. internal void AddMenuStatusBar (View view)
  497. {
  498. if (view is MenuBar) {
  499. MenuBar = view as MenuBar;
  500. }
  501. if (view is StatusBar) {
  502. StatusBar = view as StatusBar;
  503. }
  504. }
  505. ///<inheritdoc/>
  506. public override void Remove (View view)
  507. {
  508. if (this is Toplevel toplevel && toplevel.MenuBar != null) {
  509. RemoveMenuStatusBar (view);
  510. }
  511. base.Remove (view);
  512. }
  513. ///<inheritdoc/>
  514. public override void RemoveAll ()
  515. {
  516. if (this == Application.Top) {
  517. MenuBar?.Dispose ();
  518. MenuBar = null;
  519. StatusBar?.Dispose ();
  520. StatusBar = null;
  521. }
  522. base.RemoveAll ();
  523. }
  524. internal void RemoveMenuStatusBar (View view)
  525. {
  526. if (view is MenuBar) {
  527. MenuBar?.Dispose ();
  528. MenuBar = null;
  529. }
  530. if (view is StatusBar) {
  531. StatusBar?.Dispose ();
  532. StatusBar = null;
  533. }
  534. }
  535. /// <summary>
  536. /// Gets a new location of the <see cref="Toplevel"/> that is within the Bounds of the <paramref name="top"/>'s
  537. /// <see cref="View.SuperView"/> (e.g. for dragging a Window).
  538. /// The `out` parameters are the new X and Y coordinates.
  539. /// </summary>
  540. /// <remarks>
  541. /// If <paramref name="top"/> does not have a <see cref="View.SuperView"/> or it's SuperView is not <see cref="Application.Top"/>
  542. /// the position will be bound by the <see cref="ConsoleDriver.Cols"/> and <see cref="ConsoleDriver.Rows"/>.
  543. /// </remarks>
  544. /// <param name="top">The Toplevel that is to be moved.</param>
  545. /// <param name="targetX">The target x location.</param>
  546. /// <param name="targetY">The target y location.</param>
  547. /// <param name="nx">The x location that will ensure <paramref name="top"/> will be visible.</param>
  548. /// <param name="ny">The y location that will ensure <paramref name="top"/> will be visible.</param>
  549. /// <param name="menuBar">The new top most menuBar</param>
  550. /// <param name="statusBar">The new top most statusBar</param>
  551. /// <returns>
  552. /// Either <see cref="Application.Top"/> (if <paramref name="top"/> does not have a Super View) or
  553. /// <paramref name="top"/>'s SuperView. This can be used to ensure LayoutSubviews is called on the correct View.
  554. /// </returns>
  555. internal View GetLocationThatFits (Toplevel top, int targetX, int targetY,
  556. out int nx, out int ny, out MenuBar menuBar, out StatusBar statusBar)
  557. {
  558. int maxWidth;
  559. View superView;
  560. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  561. maxWidth = Driver.Cols;
  562. superView = Application.Top;
  563. } else {
  564. // Use the SuperView's Bounds, not Frame
  565. maxWidth = top.SuperView.Bounds.Width;
  566. superView = top.SuperView;
  567. }
  568. // BUGBUG: v2 hack for now
  569. var mfLength = top.BorderFrame.Thickness.Top > 0 ? 2 : 1;
  570. if (top.Frame.Width <= maxWidth) {
  571. nx = Math.Max (targetX, 0);
  572. nx = nx + top.Frame.Width > maxWidth ? Math.Max (maxWidth - top.Frame.Width, 0) : nx;
  573. if (nx + mfLength > top.Frame.X + top.Frame.Width) {
  574. nx = Math.Max (top.Frame.Right - mfLength, 0);
  575. }
  576. } else {
  577. nx = targetX;
  578. }
  579. //System.Diagnostics.Debug.WriteLine ($"nx:{nx}, rWidth:{rWidth}");
  580. bool menuVisible, statusVisible;
  581. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  582. menuVisible = Application.Top.MenuBar?.Visible == true;
  583. menuBar = Application.Top.MenuBar;
  584. } else {
  585. var t = top.SuperView;
  586. while (t is not Toplevel) {
  587. t = t.SuperView;
  588. }
  589. menuVisible = ((Toplevel)t).MenuBar?.Visible == true;
  590. menuBar = ((Toplevel)t).MenuBar;
  591. }
  592. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  593. maxWidth = menuVisible ? 1 : 0;
  594. } else {
  595. maxWidth = 0;
  596. }
  597. ny = Math.Max (targetY, maxWidth);
  598. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  599. statusVisible = Application.Top.StatusBar?.Visible == true;
  600. statusBar = Application.Top.StatusBar;
  601. } else {
  602. var t = top.SuperView;
  603. while (t is not Toplevel) {
  604. t = t.SuperView;
  605. }
  606. statusVisible = ((Toplevel)t).StatusBar?.Visible == true;
  607. statusBar = ((Toplevel)t).StatusBar;
  608. }
  609. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  610. maxWidth = statusVisible ? Driver.Rows - 1 : Driver.Rows;
  611. } else {
  612. maxWidth = statusVisible ? top.SuperView.Frame.Height - 1 : top.SuperView.Frame.Height;
  613. }
  614. ny = Math.Min (ny, maxWidth);
  615. if (top.Frame.Height <= maxWidth) {
  616. ny = ny + top.Frame.Height >= maxWidth ? Math.Max (maxWidth - top.Frame.Height, menuVisible ? 1 : 0) : ny;
  617. if (ny + mfLength > top.Frame.Y + top.Frame.Height) {
  618. ny = Math.Max (top.Frame.Bottom - mfLength, 0);
  619. }
  620. }
  621. //System.Diagnostics.Debug.WriteLine ($"ny:{ny}, rHeight:{rHeight}");
  622. return superView;
  623. }
  624. // TODO: v2 - Not sure this is needed anymore.
  625. internal void PositionToplevels ()
  626. {
  627. PositionToplevel (this);
  628. foreach (var top in Subviews) {
  629. if (top is Toplevel) {
  630. PositionToplevel ((Toplevel)top);
  631. }
  632. }
  633. }
  634. /// <summary>
  635. /// Adjusts the location and size of <paramref name="top"/> within this Toplevel.
  636. /// Virtual method enabling implementation of specific positions for inherited <see cref="Toplevel"/> views.
  637. /// </summary>
  638. /// <param name="top">The Toplevel to adjust.</param>
  639. public virtual void PositionToplevel (Toplevel top)
  640. {
  641. var superView = GetLocationThatFits (top, top.Frame.X, top.Frame.Y,
  642. out int nx, out int ny, out _, out StatusBar sb);
  643. bool layoutSubviews = false;
  644. if ((superView != top || top?.SuperView != null || (top != Application.Top && top.Modal)
  645. || (top?.SuperView == null && top.IsMdiChild))
  646. && (top.Frame.X + top.Frame.Width > Driver.Cols || ny > top.Frame.Y) && top.LayoutStyle == LayoutStyle.Computed) {
  647. if ((top.X == null || top.X is Pos.PosAbsolute) && top.Frame.X != nx) {
  648. top.X = nx;
  649. layoutSubviews = true;
  650. }
  651. if ((top.Y == null || top.Y is Pos.PosAbsolute) && top.Frame.Y != ny) {
  652. top.Y = ny;
  653. layoutSubviews = true;
  654. }
  655. }
  656. // TODO: v2 - This is a hack to get the StatusBar to be positioned correctly.
  657. if (sb != null && !top.Subviews.Contains (sb) && ny + top.Frame.Height != superView.Frame.Height - (sb.Visible ? 1 : 0)
  658. && top.Height is Dim.DimFill && -top.Height.Anchor (0) < 1) {
  659. top.Height = Dim.Fill (sb.Visible ? 1 : 0);
  660. layoutSubviews = true;
  661. }
  662. if (superView.LayoutNeeded || layoutSubviews) {
  663. superView.LayoutSubviews ();
  664. }
  665. if (LayoutNeeded) {
  666. LayoutSubviews ();
  667. }
  668. }
  669. ///<inheritdoc/>
  670. public override void Redraw (Rect bounds)
  671. {
  672. if (!Visible) {
  673. return;
  674. }
  675. if (!_needsDisplay.IsEmpty || _childNeedsDisplay || LayoutNeeded) {
  676. Driver.SetAttribute (Enabled ? Colors.Base.Normal : Colors.Base.Disabled);
  677. LayoutSubviews ();
  678. PositionToplevels ();
  679. if (this == Application.MdiTop) {
  680. foreach (var top in Application.MdiChildes.AsEnumerable ().Reverse ()) {
  681. if (top.Frame.IntersectsWith (bounds)) {
  682. if (top != this && !top.IsCurrentTop && !OutsideTopFrame (top) && top.Visible) {
  683. top.SetNeedsLayout ();
  684. top.SetNeedsDisplay (top.Bounds);
  685. top.Redraw (top.Bounds);
  686. }
  687. }
  688. }
  689. }
  690. foreach (var view in Subviews) {
  691. if (view.Frame.IntersectsWith (bounds) && !OutsideTopFrame (this)) {
  692. view.SetNeedsLayout ();
  693. view.SetNeedsDisplay (view.Bounds);
  694. }
  695. }
  696. }
  697. base.Redraw (Bounds);
  698. }
  699. bool OutsideTopFrame (Toplevel top)
  700. {
  701. if (top.Frame.X > Driver.Cols || top.Frame.Y > Driver.Rows) {
  702. return true;
  703. }
  704. return false;
  705. }
  706. internal static Point? dragPosition;
  707. Point start;
  708. ///<inheritdoc/>
  709. public override bool MouseEvent (MouseEvent mouseEvent)
  710. {
  711. if (!CanFocus) {
  712. return true;
  713. }
  714. //System.Diagnostics.Debug.WriteLine ($"dragPosition before: {dragPosition.HasValue}");
  715. int nx, ny;
  716. if (!dragPosition.HasValue && (mouseEvent.Flags == MouseFlags.Button1Pressed
  717. || mouseEvent.Flags == MouseFlags.Button2Pressed
  718. || mouseEvent.Flags == MouseFlags.Button3Pressed)) {
  719. SetFocus ();
  720. Application.EnsuresTopOnFront ();
  721. // Only start grabbing if the user clicks on the title bar.
  722. if (mouseEvent.Y == 0 && mouseEvent.Flags == MouseFlags.Button1Pressed) {
  723. start = new Point (mouseEvent.X, mouseEvent.Y);
  724. dragPosition = new Point ();
  725. nx = mouseEvent.X - mouseEvent.OfX;
  726. ny = mouseEvent.Y - mouseEvent.OfY;
  727. dragPosition = new Point (nx, ny);
  728. Application.GrabMouse (this);
  729. }
  730. //System.Diagnostics.Debug.WriteLine ($"Starting at {dragPosition}");
  731. return true;
  732. } else if (mouseEvent.Flags == (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) ||
  733. mouseEvent.Flags == MouseFlags.Button3Pressed) {
  734. if (dragPosition.HasValue) {
  735. if (SuperView == null) {
  736. // Redraw the entire app window using just our Frame. Since we are
  737. // Application.Top, and our Frame always == our Bounds (Location is always (0,0))
  738. // our Frame is actually view-relative (which is what Redraw takes).
  739. // We need to pass all the view bounds because since the windows was
  740. // moved around, we don't know exactly what was the affected region.
  741. Application.Top.SetNeedsDisplay ();
  742. } else {
  743. SuperView.SetNeedsDisplay ();
  744. }
  745. GetLocationThatFits (this, mouseEvent.X + (SuperView == null ? mouseEvent.OfX - start.X : Frame.X - start.X),
  746. mouseEvent.Y + (SuperView == null ? mouseEvent.OfY - start.Y : Frame.Y - start.Y),
  747. out nx, out ny, out _, out _);
  748. dragPosition = new Point (nx, ny);
  749. X = nx;
  750. Y = ny;
  751. //System.Diagnostics.Debug.WriteLine ($"Drag: nx:{nx},ny:{ny}");
  752. SetNeedsDisplay ();
  753. return true;
  754. }
  755. }
  756. if (mouseEvent.Flags.HasFlag (MouseFlags.Button1Released) && dragPosition.HasValue) {
  757. dragPosition = null;
  758. Application.UngrabMouse ();
  759. }
  760. //System.Diagnostics.Debug.WriteLine ($"dragPosition after: {dragPosition.HasValue}");
  761. //System.Diagnostics.Debug.WriteLine ($"Toplevel: {mouseEvent}");
  762. return false;
  763. }
  764. /// <summary>
  765. /// Invoked by <see cref="Application.Begin"/> as part of <see cref="Application.Run(Toplevel, Func{Exception, bool})"/>
  766. /// after the views have been laid out, and before the views are drawn for the first time.
  767. /// </summary>
  768. public virtual void WillPresent ()
  769. {
  770. FocusFirst ();
  771. }
  772. /// <summary>
  773. /// Move to the next Mdi child from the <see cref="Application.MdiTop"/>.
  774. /// </summary>
  775. public virtual void MoveNext ()
  776. {
  777. Application.MoveNext ();
  778. }
  779. /// <summary>
  780. /// Move to the previous Mdi child from the <see cref="Application.MdiTop"/>.
  781. /// </summary>
  782. public virtual void MovePrevious ()
  783. {
  784. Application.MovePrevious ();
  785. }
  786. /// <summary>
  787. /// Stops and closes this <see cref="Toplevel"/>. If this Toplevel is the top-most Toplevel,
  788. /// <see cref="Application.RequestStop(Toplevel)"/> will be called, causing the application to exit.
  789. /// </summary>
  790. public virtual void RequestStop ()
  791. {
  792. if (IsMdiContainer && Running
  793. && (Application.Current == this
  794. || Application.Current?.Modal == false
  795. || Application.Current?.Modal == true && Application.Current?.Running == false)) {
  796. foreach (var child in Application.MdiChildes) {
  797. var ev = new ToplevelClosingEventArgs (this);
  798. if (child.OnClosing (ev)) {
  799. return;
  800. }
  801. child.Running = false;
  802. Application.RequestStop (child);
  803. }
  804. Running = false;
  805. Application.RequestStop (this);
  806. } else if (IsMdiContainer && Running && Application.Current?.Modal == true && Application.Current?.Running == true) {
  807. var ev = new ToplevelClosingEventArgs (Application.Current);
  808. if (OnClosing (ev)) {
  809. return;
  810. }
  811. Application.RequestStop (Application.Current);
  812. } else if (!IsMdiContainer && Running && (!Modal || (Modal && Application.Current != this))) {
  813. var ev = new ToplevelClosingEventArgs (this);
  814. if (OnClosing (ev)) {
  815. return;
  816. }
  817. Running = false;
  818. Application.RequestStop (this);
  819. } else {
  820. Application.RequestStop (Application.Current);
  821. }
  822. }
  823. /// <summary>
  824. /// Stops and closes the <see cref="Toplevel"/> specified by <paramref name="top"/>. If <paramref name="top"/> is the top-most Toplevel,
  825. /// <see cref="Application.RequestStop(Toplevel)"/> will be called, causing the application to exit.
  826. /// </summary>
  827. /// <param name="top">The toplevel to request stop.</param>
  828. public virtual void RequestStop (Toplevel top)
  829. {
  830. top.RequestStop ();
  831. }
  832. ///<inheritdoc/>
  833. public override void PositionCursor ()
  834. {
  835. if (!IsMdiContainer) {
  836. base.PositionCursor ();
  837. if (Focused == null) {
  838. EnsureFocus ();
  839. if (Focused == null) {
  840. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  841. }
  842. }
  843. return;
  844. }
  845. if (Focused == null) {
  846. foreach (var top in Application.MdiChildes) {
  847. if (top != this && top.Visible) {
  848. top.SetFocus ();
  849. return;
  850. }
  851. }
  852. }
  853. base.PositionCursor ();
  854. if (Focused == null) {
  855. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  856. }
  857. }
  858. /// <summary>
  859. /// Gets the current visible Toplevel Mdi child that matches the arguments pattern.
  860. /// </summary>
  861. /// <param name="type">The type.</param>
  862. /// <param name="exclude">The strings to exclude.</param>
  863. /// <returns>The matched view.</returns>
  864. public View GetTopMdiChild (Type type = null, string [] exclude = null)
  865. {
  866. if (Application.MdiTop == null) {
  867. return null;
  868. }
  869. foreach (var top in Application.MdiChildes) {
  870. if (type != null && top.GetType () == type
  871. && exclude?.Contains (top.Data.ToString ()) == false) {
  872. return top;
  873. } else if ((type != null && top.GetType () != type)
  874. || (exclude?.Contains (top.Data.ToString ()) == true)) {
  875. continue;
  876. }
  877. return top;
  878. }
  879. return null;
  880. }
  881. /// <summary>
  882. /// Shows the Mdi child indicated by <paramref name="top"/>, setting it as <see cref="Application.Current"/>.
  883. /// </summary>
  884. /// <param name="top">The Toplevel.</param>
  885. /// <returns><c>true</c> if the toplevel can be shown or <c>false</c> if not.</returns>
  886. public virtual bool ShowChild (Toplevel top = null)
  887. {
  888. if (Application.MdiTop != null) {
  889. return Application.ShowChild (top == null ? this : top);
  890. }
  891. return false;
  892. }
  893. ///<inheritdoc/>
  894. public override bool OnEnter (View view)
  895. {
  896. return MostFocused?.OnEnter (view) ?? base.OnEnter (view);
  897. }
  898. ///<inheritdoc/>
  899. public override bool OnLeave (View view)
  900. {
  901. return MostFocused?.OnLeave (view) ?? base.OnLeave (view);
  902. }
  903. ///<inheritdoc/>
  904. protected override void Dispose (bool disposing)
  905. {
  906. dragPosition = null;
  907. base.Dispose (disposing);
  908. }
  909. }
  910. /// <summary>
  911. /// Implements the <see cref="IEqualityComparer{T}"/> for comparing two <see cref="Toplevel"/>s
  912. /// used by <see cref="StackExtensions"/>.
  913. /// </summary>
  914. public class ToplevelEqualityComparer : IEqualityComparer<Toplevel> {
  915. /// <summary>Determines whether the specified objects are equal.</summary>
  916. /// <param name="x">The first object of type <see cref="Toplevel" /> to compare.</param>
  917. /// <param name="y">The second object of type <see cref="Toplevel" /> to compare.</param>
  918. /// <returns>
  919. /// <see langword="true" /> if the specified objects are equal; otherwise, <see langword="false" />.</returns>
  920. public bool Equals (Toplevel x, Toplevel y)
  921. {
  922. if (y == null && x == null)
  923. return true;
  924. else if (x == null || y == null)
  925. return false;
  926. else if (x.Id == y.Id)
  927. return true;
  928. else
  929. return false;
  930. }
  931. /// <summary>Returns a hash code for the specified object.</summary>
  932. /// <param name="obj">The <see cref="Toplevel" /> for which a hash code is to be returned.</param>
  933. /// <returns>A hash code for the specified object.</returns>
  934. /// <exception cref="ArgumentNullException">The type of <paramref name="obj" />
  935. /// is a reference type and <paramref name="obj" /> is <see langword="null" />.</exception>
  936. public int GetHashCode (Toplevel obj)
  937. {
  938. if (obj == null)
  939. throw new ArgumentNullException ();
  940. int hCode = 0;
  941. if (int.TryParse (obj.Id.ToString (), out int result)) {
  942. hCode = result;
  943. }
  944. return hCode.GetHashCode ();
  945. }
  946. }
  947. /// <summary>
  948. /// Implements the <see cref="IComparer{T}"/> to sort the <see cref="Toplevel"/>
  949. /// from the <see cref="Application.MdiChildes"/> if needed.
  950. /// </summary>
  951. public sealed class ToplevelComparer : IComparer<Toplevel> {
  952. /// <summary>Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.</summary>
  953. /// <param name="x">The first object to compare.</param>
  954. /// <param name="y">The second object to compare.</param>
  955. /// <returns>A signed integer that indicates the relative values of <paramref name="x" /> and <paramref name="y" />, as shown in the following table.Value Meaning Less than zero
  956. /// <paramref name="x" /> is less than <paramref name="y" />.Zero
  957. /// <paramref name="x" /> equals <paramref name="y" />.Greater than zero
  958. /// <paramref name="x" /> is greater than <paramref name="y" />.</returns>
  959. public int Compare (Toplevel x, Toplevel y)
  960. {
  961. if (ReferenceEquals (x, y))
  962. return 0;
  963. else if (x == null)
  964. return -1;
  965. else if (y == null)
  966. return 1;
  967. else
  968. return string.Compare (x.Id.ToString (), y.Id.ToString ());
  969. }
  970. }
  971. }