Toplevel.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098
  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. /// <para>
  23. /// Toplevels can also opt-in to more sophisticated initialization
  24. /// by implementing <see cref="ISupportInitialize"/>. When they do
  25. /// so, the <see cref="ISupportInitialize.BeginInit"/> and
  26. /// <see cref="ISupportInitialize.EndInit"/> methods will be called
  27. /// before running the view.
  28. /// If first-run-only initialization is preferred, the <see cref="ISupportInitializeNotification"/>
  29. /// can be implemented too, in which case the <see cref="ISupportInitialize"/>
  30. /// methods will only be called if <see cref="ISupportInitializeNotification.IsInitialized"/>
  31. /// is <see langword="false"/>. This allows proper <see cref="View"/> inheritance hierarchies
  32. /// to override base class layout code optimally by doing so only on first run,
  33. /// instead of on every run.
  34. /// </para>
  35. /// </remarks>
  36. public class Toplevel : View {
  37. /// <summary>
  38. /// Gets or sets whether the <see cref="MainLoop"/> for this <see cref="Toplevel"/> is running or not.
  39. /// </summary>
  40. /// <remarks>
  41. /// Setting this property directly is discouraged. Use <see cref="Application.RequestStop"/> instead.
  42. /// </remarks>
  43. public bool Running { get; set; }
  44. /// <summary>
  45. /// Invoked when the Toplevel <see cref="Application.RunState"/> has begun to be loaded.
  46. /// A Loaded event handler is a good place to finalize initialization before calling
  47. /// <see cref="Application.RunLoop(Application.RunState, bool)"/>.
  48. /// </summary>
  49. public event Action Loaded;
  50. /// <summary>
  51. /// Invoked when the Toplevel <see cref="MainLoop"/> has started it's first iteration.
  52. /// Subscribe to this event to perform tasks when the <see cref="Toplevel"/> has been laid out and focus has been set.
  53. /// changes.
  54. /// <para>A Ready event handler is a good place to finalize initialization after calling
  55. /// <see cref="Application.Run(Func{Exception, bool})"/> on this Toplevel.</para>
  56. /// </summary>
  57. public event Action Ready;
  58. /// <summary>
  59. /// Invoked when the Toplevel <see cref="Application.RunState"/> has been unloaded.
  60. /// A Unloaded event handler is a good place to dispose objects after calling <see cref="Application.End(Application.RunState)"/>.
  61. /// </summary>
  62. public event Action Unloaded;
  63. /// <summary>
  64. /// Invoked when the Toplevel <see cref="Application.RunState"/> becomes the <see cref="Application.Current"/> Toplevel.
  65. /// </summary>
  66. public event Action<Toplevel> Activate;
  67. /// <summary>
  68. /// Invoked when the Toplevel<see cref="Application.RunState"/> ceases to be the <see cref="Application.Current"/> Toplevel.
  69. /// </summary>
  70. public event Action<Toplevel> Deactivate;
  71. /// <summary>
  72. /// Invoked when a child of the Toplevel <see cref="Application.RunState"/> is closed by
  73. /// <see cref="Application.End(Application.RunState)"/>.
  74. /// </summary>
  75. public event Action<Toplevel> ChildClosed;
  76. /// <summary>
  77. /// Invoked when the last child of the Toplevel <see cref="Application.RunState"/> is closed from
  78. /// by <see cref="Application.End(Application.RunState)"/>.
  79. /// </summary>
  80. public event Action AllChildClosed;
  81. /// <summary>
  82. /// Invoked when the Toplevel's <see cref="Application.RunState"/> is being closed by
  83. /// <see cref="Application.RequestStop(Toplevel)"/>.
  84. /// </summary>
  85. public event Action<ToplevelClosingEventArgs> Closing;
  86. /// <summary>
  87. /// Invoked when the Toplevel's <see cref="Application.RunState"/> is closed by <see cref="Application.End(Application.RunState)"/>.
  88. /// </summary>
  89. public event Action<Toplevel> Closed;
  90. /// <summary>
  91. /// Invoked when a child Toplevel's <see cref="Application.RunState"/> has been loaded.
  92. /// </summary>
  93. public event Action<Toplevel> ChildLoaded;
  94. /// <summary>
  95. /// Invoked when a cjhild Toplevel's <see cref="Application.RunState"/> has been unloaded.
  96. /// </summary>
  97. public event Action<Toplevel> ChildUnloaded;
  98. /// <summary>
  99. /// Invoked when the terminal has been resized. The new <see cref="Size"/> of the terminal is provided.
  100. /// </summary>
  101. public event Action<Size> Resized;
  102. internal virtual void OnResized (Size size)
  103. {
  104. Resized?.Invoke (size);
  105. }
  106. internal virtual void OnChildUnloaded (Toplevel top)
  107. {
  108. ChildUnloaded?.Invoke (top);
  109. }
  110. internal virtual void OnChildLoaded (Toplevel top)
  111. {
  112. ChildLoaded?.Invoke (top);
  113. }
  114. internal virtual void OnClosed (Toplevel top)
  115. {
  116. Closed?.Invoke (top);
  117. }
  118. internal virtual bool OnClosing (ToplevelClosingEventArgs ev)
  119. {
  120. Closing?.Invoke (ev);
  121. return ev.Cancel;
  122. }
  123. internal virtual void OnAllChildClosed ()
  124. {
  125. AllChildClosed?.Invoke ();
  126. }
  127. internal virtual void OnChildClosed (Toplevel top)
  128. {
  129. if (IsMdiContainer) {
  130. SetSubViewNeedsDisplay ();
  131. }
  132. ChildClosed?.Invoke (top);
  133. }
  134. internal virtual void OnDeactivate (Toplevel activated)
  135. {
  136. Deactivate?.Invoke (activated);
  137. }
  138. internal virtual void OnActivate (Toplevel deactivated)
  139. {
  140. Activate?.Invoke (deactivated);
  141. }
  142. /// <summary>
  143. /// Called from <see cref="Application.Begin(Toplevel)"/> before the <see cref="Toplevel"/> redraws for the first time.
  144. /// </summary>
  145. virtual public void OnLoaded ()
  146. {
  147. IsLoaded = true;
  148. foreach (Toplevel tl in Subviews.Where (v => v is Toplevel)) {
  149. tl.OnLoaded ();
  150. }
  151. Loaded?.Invoke ();
  152. }
  153. /// <summary>
  154. /// Called from <see cref="Application.RunLoop"/> after the <see cref="Toplevel"/> has entered the
  155. /// first iteration of the loop.
  156. /// </summary>
  157. internal virtual void OnReady ()
  158. {
  159. foreach (Toplevel tl in Subviews.Where (v => v is Toplevel)) {
  160. tl.OnReady ();
  161. }
  162. Ready?.Invoke ();
  163. }
  164. /// <summary>
  165. /// Called from <see cref="Application.End(Application.RunState)"/> before the <see cref="Toplevel"/> is disposed.
  166. /// </summary>
  167. internal virtual void OnUnloaded ()
  168. {
  169. foreach (Toplevel tl in Subviews.Where (v => v is Toplevel)) {
  170. tl.OnUnloaded ();
  171. }
  172. Unloaded?.Invoke ();
  173. }
  174. /// <summary>
  175. /// Initializes a new instance of the <see cref="Toplevel"/> class with the specified <see cref="LayoutStyle.Absolute"/> layout.
  176. /// </summary>
  177. /// <param name="frame">A superview-relative rectangle specifying the location and size for the new Toplevel</param>
  178. public Toplevel (Rect frame) : base (frame)
  179. {
  180. Initialize ();
  181. }
  182. /// <summary>
  183. /// Initializes a new instance of the <see cref="Toplevel"/> class with <see cref="LayoutStyle.Computed"/> layout,
  184. /// defaulting to full screen.
  185. /// </summary>
  186. public Toplevel () : base ()
  187. {
  188. Initialize ();
  189. Width = Dim.Fill ();
  190. Height = Dim.Fill ();
  191. }
  192. void Initialize ()
  193. {
  194. ColorScheme = Colors.TopLevel;
  195. // TODO: v2 - ALL Views (Responders??!?!) should support the commands related to
  196. // - Focus
  197. // Move the appropriate AddCommand calls to `Responder`
  198. // Things this view knows how to do
  199. AddCommand (Command.QuitToplevel, () => { QuitToplevel (); return true; });
  200. AddCommand (Command.Suspend, () => { Driver.Suspend (); ; return true; });
  201. AddCommand (Command.NextView, () => { MoveNextView (); return true; });
  202. AddCommand (Command.PreviousView, () => { MovePreviousView (); return true; });
  203. AddCommand (Command.NextViewOrTop, () => { MoveNextViewOrTop (); return true; });
  204. AddCommand (Command.PreviousViewOrTop, () => { MovePreviousViewOrTop (); return true; });
  205. AddCommand (Command.Refresh, () => { Application.Refresh (); return true; });
  206. // Default keybindings for this view
  207. AddKeyBinding (Application.QuitKey, Command.QuitToplevel);
  208. AddKeyBinding (Key.Z | Key.CtrlMask, Command.Suspend);
  209. AddKeyBinding (Key.Tab, Command.NextView);
  210. AddKeyBinding (Key.CursorRight, Command.NextView);
  211. AddKeyBinding (Key.F | Key.CtrlMask, Command.NextView);
  212. AddKeyBinding (Key.CursorDown, Command.NextView);
  213. AddKeyBinding (Key.I | Key.CtrlMask, Command.NextView); // Unix
  214. AddKeyBinding (Key.BackTab | Key.ShiftMask, Command.PreviousView);
  215. AddKeyBinding (Key.CursorLeft, Command.PreviousView);
  216. AddKeyBinding (Key.CursorUp, Command.PreviousView);
  217. AddKeyBinding (Key.B | Key.CtrlMask, Command.PreviousView);
  218. AddKeyBinding (Key.Tab | Key.CtrlMask, Command.NextViewOrTop);
  219. AddKeyBinding (Application.AlternateForwardKey, Command.NextViewOrTop); // Needed on Unix
  220. AddKeyBinding (Key.Tab | Key.ShiftMask | Key.CtrlMask, Command.PreviousViewOrTop);
  221. AddKeyBinding (Application.AlternateBackwardKey, Command.PreviousViewOrTop); // Needed on Unix
  222. AddKeyBinding (Key.L | Key.CtrlMask, Command.Refresh);
  223. }
  224. /// <summary>
  225. /// Invoked when the <see cref="Application.AlternateForwardKey"/> is changed.
  226. /// </summary>
  227. public event Action<Key> AlternateForwardKeyChanged;
  228. /// <summary>
  229. /// Virtual method to invoke the <see cref="AlternateForwardKeyChanged"/> event.
  230. /// </summary>
  231. /// <param name="oldKey"></param>
  232. public virtual void OnAlternateForwardKeyChanged (Key oldKey)
  233. {
  234. ReplaceKeyBinding (oldKey, Application.AlternateForwardKey);
  235. AlternateForwardKeyChanged?.Invoke (oldKey);
  236. }
  237. /// <summary>
  238. /// Invoked when the <see cref="Application.AlternateBackwardKey"/> is changed.
  239. /// </summary>
  240. public event Action<Key> AlternateBackwardKeyChanged;
  241. /// <summary>
  242. /// Virtual method to invoke the <see cref="AlternateBackwardKeyChanged"/> event.
  243. /// </summary>
  244. /// <param name="oldKey"></param>
  245. public virtual void OnAlternateBackwardKeyChanged (Key oldKey)
  246. {
  247. ReplaceKeyBinding (oldKey, Application.AlternateBackwardKey);
  248. AlternateBackwardKeyChanged?.Invoke (oldKey);
  249. }
  250. /// <summary>
  251. /// Invoked when the <see cref="Application.QuitKey"/> is changed.
  252. /// </summary>
  253. public event Action<Key> QuitKeyChanged;
  254. /// <summary>
  255. /// Virtual method to invoke the <see cref="QuitKeyChanged"/> event.
  256. /// </summary>
  257. /// <param name="oldKey"></param>
  258. public virtual void OnQuitKeyChanged (Key oldKey)
  259. {
  260. ReplaceKeyBinding (oldKey, Application.QuitKey);
  261. QuitKeyChanged?.Invoke (oldKey);
  262. }
  263. /// <summary>
  264. /// Convenience factory method that creates a new Toplevel with the current terminal dimensions.
  265. /// </summary>
  266. /// <returns>The created Toplevel.</returns>
  267. public static Toplevel Create ()
  268. {
  269. return new Toplevel (new Rect (0, 0, Driver.Cols, Driver.Rows));
  270. }
  271. /// <summary>
  272. /// Gets or sets a value indicating whether this <see cref="Toplevel"/> can focus.
  273. /// </summary>
  274. /// <value><c>true</c> if can focus; otherwise, <c>false</c>.</value>
  275. public override bool CanFocus {
  276. get => SuperView == null ? true : base.CanFocus;
  277. }
  278. /// <summary>
  279. /// Determines whether the <see cref="Toplevel"/> is modal or not.
  280. /// If set to <c>false</c> (the default):
  281. ///
  282. /// <list type="bullet">
  283. /// <item>
  284. /// <description><see cref="ProcessKey(KeyEvent)"/> events will propagate keys upwards.</description>
  285. /// </item>
  286. /// <item>
  287. /// <description>The Toplevel will act as an embedded view (not a modal/pop-up).</description>
  288. /// </item>
  289. /// </list>
  290. ///
  291. /// If set to <c>true</c>:
  292. ///
  293. /// <list type="bullet">
  294. /// <item>
  295. /// <description><see cref="ProcessKey(KeyEvent)"/> events will NOT propogate keys upwards.</description>
  296. /// </item>
  297. /// <item>
  298. /// <description>The Toplevel will and look like a modal (pop-up) (e.g. see <see cref="Dialog"/>.</description>
  299. /// </item>
  300. /// </list>
  301. /// </summary>
  302. public bool Modal { get; set; }
  303. /// <summary>
  304. /// Gets or sets the menu for this Toplevel.
  305. /// </summary>
  306. public virtual MenuBar MenuBar { get; set; }
  307. /// <summary>
  308. /// Gets or sets the status bar for this Toplevel.
  309. /// </summary>
  310. public virtual StatusBar StatusBar { get; set; }
  311. /// <summary>
  312. /// Gets or sets if this Toplevel is a Mdi container.
  313. /// </summary>
  314. public bool IsMdiContainer { get; set; }
  315. /// <summary>
  316. /// Gets or sets if this Toplevel is a Mdi child.
  317. /// </summary>
  318. public bool IsMdiChild {
  319. get {
  320. return Application.MdiTop != null && Application.MdiTop != this && !Modal;
  321. }
  322. }
  323. /// <summary>
  324. /// <see langword="true"/> if was already loaded by the <see cref="Application.Begin(Toplevel)"/>
  325. /// <see langword="false"/>, otherwise. This is used to avoid the <see cref="View._needsDisplay"/>
  326. /// having wrong values while this was not yet loaded.
  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. /// Ensures the new position of the <see cref="Toplevel"/> is within the bounds of the screen (e.g. for dragging a Window).
  537. /// The `out` parameters are the new X and Y coordinates.
  538. /// </summary>
  539. /// <param name="top">The Toplevel that is to be moved.</param>
  540. /// <param name="x">The target x location.</param>
  541. /// <param name="y">The target y location.</param>
  542. /// <param name="nx">The x location after ensuring <paramref name="top"/> will remain visible.</param>
  543. /// <param name="ny">The y location after ensuring <paramref name="top"/> will remain visible.</param>
  544. /// <param name="menuBar">The new top most menuBar</param>
  545. /// <param name="statusBar">The new top most statusBar</param>
  546. /// <returns>The <see cref="Toplevel"/> that is Application.Top</returns>
  547. internal View EnsureVisibleBounds (Toplevel top, int x, int y,
  548. out int nx, out int ny, out MenuBar menuBar, out StatusBar statusBar)
  549. {
  550. int maxWidth;
  551. View superView;
  552. var isTopTop = top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top;
  553. if (isTopTop) {
  554. maxWidth = Driver.Cols;
  555. superView = Application.Top;
  556. } else {
  557. maxWidth = top.SuperView.Frame.Width;
  558. // BUGBUG: v2 - No code ever uses the return of this function if `top` is not Application.Top
  559. superView = top.SuperView;
  560. }
  561. nx = Math.Max (x, 0);
  562. nx = nx + top.Frame.Width > maxWidth ? Math.Max (maxWidth - top.Frame.Width, 0) : nx;
  563. var mfLength = top.Border?.DrawMarginFrame == true ? 2 : 1;
  564. if (nx + mfLength > top.Frame.X + top.Frame.Width) {
  565. nx = Math.Max (top.Frame.Right - mfLength, 0);
  566. }
  567. //System.Diagnostics.Debug.WriteLine ($"nx:{nx}, rWidth:{rWidth}");
  568. bool isMenuBarVisible, isStatusBarVisible;
  569. if (isTopTop) {
  570. isMenuBarVisible = Application.Top.MenuBar?.Visible == true;
  571. menuBar = Application.Top.MenuBar;
  572. } else {
  573. var t = top.SuperView;
  574. while (!(t is Toplevel)) {
  575. t = t.SuperView;
  576. }
  577. isMenuBarVisible = ((Toplevel)t).MenuBar?.Visible == true;
  578. menuBar = ((Toplevel)t).MenuBar;
  579. }
  580. if (isTopTop) {
  581. maxWidth = isMenuBarVisible ? 1 : 0;
  582. } else {
  583. maxWidth = 0;
  584. }
  585. ny = Math.Max (y, maxWidth);
  586. if (isTopTop) {
  587. isStatusBarVisible = Application.Top.StatusBar?.Visible == true;
  588. statusBar = Application.Top.StatusBar;
  589. } else {
  590. var t = top.SuperView;
  591. while (!(t is Toplevel)) {
  592. t = t.SuperView;
  593. }
  594. isStatusBarVisible = ((Toplevel)t).StatusBar?.Visible == true;
  595. statusBar = ((Toplevel)t).StatusBar;
  596. }
  597. if (isTopTop) {
  598. maxWidth = isStatusBarVisible ? Driver.Rows - 1 : Driver.Rows;
  599. } else {
  600. maxWidth = isStatusBarVisible ? top.SuperView.Frame.Height - 1 : top.SuperView.Frame.Height;
  601. }
  602. ny = Math.Min (ny, maxWidth);
  603. ny = ny + top.Frame.Height >= maxWidth ? Math.Max (maxWidth - top.Frame.Height, isMenuBarVisible ? 1 : 0) : ny;
  604. if (ny + mfLength > top.Frame.Y + top.Frame.Height) {
  605. ny = Math.Max (top.Frame.Bottom - mfLength, 0);
  606. }
  607. //System.Diagnostics.Debug.WriteLine ($"ny:{ny}, rHeight:{rHeight}");
  608. return superView;
  609. }
  610. // TODO: v2 - Not sure this is needed anymore.
  611. internal void PositionToplevels ()
  612. {
  613. PositionToplevel (this);
  614. foreach (var top in Subviews) {
  615. if (top is Toplevel) {
  616. PositionToplevel ((Toplevel)top);
  617. }
  618. }
  619. }
  620. /// <summary>
  621. /// Adjusts the location and size of <paramref name="top"/> within this Toplevel.
  622. /// Virtual method enabling implementation of specific positions for inherited <see cref="Toplevel"/> views.
  623. /// </summary>
  624. /// <param name="top">The Toplevel to adjust.</param>
  625. public virtual void PositionToplevel (Toplevel top)
  626. {
  627. var superView = EnsureVisibleBounds (top, top.Frame.X, top.Frame.Y,
  628. out int nx, out int ny, out _, out StatusBar sb);
  629. bool layoutSubviews = false;
  630. if ((top?.SuperView != null || (top != Application.Top && top.Modal)
  631. || (top?.SuperView == null && top.IsMdiChild))
  632. && (nx > top.Frame.X || ny > top.Frame.Y) && top.LayoutStyle == LayoutStyle.Computed) {
  633. if ((top.X == null || top.X is Pos.PosAbsolute) && top.Bounds.X != nx) {
  634. top.X = nx;
  635. layoutSubviews = true;
  636. }
  637. if ((top.Y == null || top.Y is Pos.PosAbsolute) && top.Bounds.Y != ny) {
  638. top.Y = ny;
  639. layoutSubviews = true;
  640. }
  641. }
  642. // TODO: v2 - This is a hack to get the StatusBar to be positioned correctly.
  643. if (sb != null && ny + top.Frame.Height != superView.Frame.Height - (sb.Visible ? 1 : 0)
  644. && top.Height is Dim.DimFill && -top.Height.Anchor (0) < 1) {
  645. top.Height = Dim.Fill (sb.Visible ? 1 : 0);
  646. layoutSubviews = true;
  647. }
  648. if (layoutSubviews) {
  649. superView.LayoutSubviews ();
  650. }
  651. }
  652. ///<inheritdoc/>
  653. public override void Redraw (Rect bounds)
  654. {
  655. if (!Visible) {
  656. return;
  657. }
  658. if (!_needsDisplay.IsEmpty || _childNeedsDisplay || LayoutNeeded) {
  659. Driver.SetAttribute (GetNormalColor ());
  660. // This is the Application.Top. Clear just the region we're being asked to redraw
  661. // (the bounds passed to us).
  662. Clear ();
  663. Driver.SetAttribute (Enabled ? Colors.Base.Normal : Colors.Base.Disabled);
  664. LayoutSubviews ();
  665. PositionToplevels ();
  666. if (this == Application.MdiTop) {
  667. foreach (var top in Application.MdiChildes.AsEnumerable ().Reverse ()) {
  668. if (top.Frame.IntersectsWith (bounds)) {
  669. if (top != this && !top.IsCurrentTop && !OutsideTopFrame (top) && top.Visible) {
  670. top.SetNeedsLayout ();
  671. top.SetNeedsDisplay (top.Bounds);
  672. top.Redraw (top.Bounds);
  673. }
  674. }
  675. }
  676. }
  677. foreach (var view in Subviews) {
  678. if (view.Frame.IntersectsWith (bounds) && !OutsideTopFrame (this)) {
  679. view.SetNeedsLayout ();
  680. view.SetNeedsDisplay (view.Bounds);
  681. }
  682. }
  683. // BUGBUG: shouldn't we just return here? the call to base.Redraw below is redundant
  684. }
  685. base.Redraw (Bounds);
  686. }
  687. bool OutsideTopFrame (Toplevel top)
  688. {
  689. if (top.Frame.X > Driver.Cols || top.Frame.Y > Driver.Rows) {
  690. return true;
  691. }
  692. return false;
  693. }
  694. internal static Point? dragPosition;
  695. Point start;
  696. ///<inheritdoc/>
  697. public override bool MouseEvent (MouseEvent mouseEvent)
  698. {
  699. if (!CanFocus) {
  700. return true;
  701. }
  702. //System.Diagnostics.Debug.WriteLine ($"dragPosition before: {dragPosition.HasValue}");
  703. int nx, ny;
  704. if (!dragPosition.HasValue && (mouseEvent.Flags == MouseFlags.Button1Pressed
  705. || mouseEvent.Flags == MouseFlags.Button2Pressed
  706. || mouseEvent.Flags == MouseFlags.Button3Pressed)) {
  707. SetFocus ();
  708. Application.EnsuresTopOnFront ();
  709. // Only start grabbing if the user clicks on the title bar.
  710. if (mouseEvent.Y == 0 && mouseEvent.Flags == MouseFlags.Button1Pressed) {
  711. start = new Point (mouseEvent.X, mouseEvent.Y);
  712. dragPosition = new Point ();
  713. nx = mouseEvent.X - mouseEvent.OfX;
  714. ny = mouseEvent.Y - mouseEvent.OfY;
  715. dragPosition = new Point (nx, ny);
  716. Application.GrabMouse (this);
  717. }
  718. //System.Diagnostics.Debug.WriteLine ($"Starting at {dragPosition}");
  719. return true;
  720. } else if (mouseEvent.Flags == (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) ||
  721. mouseEvent.Flags == MouseFlags.Button3Pressed) {
  722. if (dragPosition.HasValue) {
  723. if (SuperView == null) {
  724. // Redraw the entire app window using just our Frame. Since we are
  725. // Application.Top, and our Frame always == our Bounds (Location is always (0,0))
  726. // our Frame is actually view-relative (which is what Redraw takes).
  727. // We need to pass all the view bounds because since the windows was
  728. // moved around, we don't know exactly what was the affected region.
  729. Application.Top.SetNeedsDisplay ();
  730. } else {
  731. SuperView.SetNeedsDisplay ();
  732. }
  733. EnsureVisibleBounds (this, mouseEvent.X + (SuperView == null ? mouseEvent.OfX - start.X : Frame.X - start.X),
  734. mouseEvent.Y + (SuperView == null ? mouseEvent.OfY - start.Y : Frame.Y - start.Y),
  735. out nx, out ny, out _, out _);
  736. dragPosition = new Point (nx, ny);
  737. X = nx;
  738. Y = ny;
  739. //System.Diagnostics.Debug.WriteLine ($"Drag: nx:{nx},ny:{ny}");
  740. SetNeedsDisplay ();
  741. return true;
  742. }
  743. }
  744. if (mouseEvent.Flags.HasFlag (MouseFlags.Button1Released) && dragPosition.HasValue) {
  745. Application.UngrabMouse ();
  746. dragPosition = null;
  747. }
  748. //System.Diagnostics.Debug.WriteLine ($"dragPosition after: {dragPosition.HasValue}");
  749. //System.Diagnostics.Debug.WriteLine ($"Toplevel: {mouseEvent}");
  750. return false;
  751. }
  752. /// <summary>
  753. /// Invoked by <see cref="Application.Begin"/> as part of <see cref="Application.Run(Toplevel, Func{Exception, bool})"/>
  754. /// after the views have been laid out, and before the views are drawn for the first time.
  755. /// </summary>
  756. public virtual void WillPresent ()
  757. {
  758. FocusFirst ();
  759. }
  760. /// <summary>
  761. /// Move to the next Mdi child from the <see cref="Application.MdiTop"/>.
  762. /// </summary>
  763. public virtual void MoveNext ()
  764. {
  765. Application.MoveNext ();
  766. }
  767. /// <summary>
  768. /// Move to the previous Mdi child from the <see cref="Application.MdiTop"/>.
  769. /// </summary>
  770. public virtual void MovePrevious ()
  771. {
  772. Application.MovePrevious ();
  773. }
  774. /// <summary>
  775. /// Stops and closes this <see cref="Toplevel"/>. If this Toplevel is the top-most Toplevel,
  776. /// <see cref="Application.RequestStop(Toplevel)"/> will be called, causing the application to exit.
  777. /// </summary>
  778. public virtual void RequestStop ()
  779. {
  780. if (IsMdiContainer && Running
  781. && (Application.Current == this
  782. || Application.Current?.Modal == false
  783. || Application.Current?.Modal == true && Application.Current?.Running == false)) {
  784. foreach (var child in Application.MdiChildes) {
  785. var ev = new ToplevelClosingEventArgs (this);
  786. if (child.OnClosing (ev)) {
  787. return;
  788. }
  789. child.Running = false;
  790. Application.RequestStop (child);
  791. }
  792. Running = false;
  793. Application.RequestStop (this);
  794. } else if (IsMdiContainer && Running && Application.Current?.Modal == true && Application.Current?.Running == true) {
  795. var ev = new ToplevelClosingEventArgs (Application.Current);
  796. if (OnClosing (ev)) {
  797. return;
  798. }
  799. Application.RequestStop (Application.Current);
  800. } else if (!IsMdiContainer && Running && (!Modal || (Modal && Application.Current != this))) {
  801. var ev = new ToplevelClosingEventArgs (this);
  802. if (OnClosing (ev)) {
  803. return;
  804. }
  805. Running = false;
  806. Application.RequestStop (this);
  807. } else {
  808. Application.RequestStop (Application.Current);
  809. }
  810. }
  811. /// <summary>
  812. /// Stops and closes the <see cref="Toplevel"/> specified by <paramref name="top"/>. If <paramref name="top"/> is the top-most Toplevel,
  813. /// <see cref="Application.RequestStop(Toplevel)"/> will be called, causing the application to exit.
  814. /// </summary>
  815. /// <param name="top">The toplevel to request stop.</param>
  816. public virtual void RequestStop (Toplevel top)
  817. {
  818. top.RequestStop ();
  819. }
  820. ///<inheritdoc/>
  821. public override void PositionCursor ()
  822. {
  823. if (!IsMdiContainer) {
  824. base.PositionCursor ();
  825. if (Focused == null) {
  826. EnsureFocus ();
  827. if (Focused == null) {
  828. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  829. }
  830. }
  831. return;
  832. }
  833. if (Focused == null) {
  834. foreach (var top in Application.MdiChildes) {
  835. if (top != this && top.Visible) {
  836. top.SetFocus ();
  837. return;
  838. }
  839. }
  840. }
  841. base.PositionCursor ();
  842. if (Focused == null) {
  843. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  844. }
  845. }
  846. /// <summary>
  847. /// Gets the current visible Toplevel Mdi child that matches the arguments pattern.
  848. /// </summary>
  849. /// <param name="type">The type.</param>
  850. /// <param name="exclude">The strings to exclude.</param>
  851. /// <returns>The matched view.</returns>
  852. public View GetTopMdiChild (Type type = null, string [] exclude = null)
  853. {
  854. if (Application.MdiTop == null) {
  855. return null;
  856. }
  857. foreach (var top in Application.MdiChildes) {
  858. if (type != null && top.GetType () == type
  859. && exclude?.Contains (top.Data.ToString ()) == false) {
  860. return top;
  861. } else if ((type != null && top.GetType () != type)
  862. || (exclude?.Contains (top.Data.ToString ()) == true)) {
  863. continue;
  864. }
  865. return top;
  866. }
  867. return null;
  868. }
  869. /// <summary>
  870. /// Shows the Mdi child indicated by <paramref name="top"/>, setting it as <see cref="Application.Current"/>.
  871. /// </summary>
  872. /// <param name="top">The Toplevel.</param>
  873. /// <returns><c>true</c> if the toplevel can be shown or <c>false</c> if not.</returns>
  874. public virtual bool ShowChild (Toplevel top = null)
  875. {
  876. if (Application.MdiTop != null) {
  877. return Application.ShowChild (top == null ? this : top);
  878. }
  879. return false;
  880. }
  881. ///<inheritdoc/>
  882. public override bool OnEnter (View view)
  883. {
  884. return MostFocused?.OnEnter (view) ?? base.OnEnter (view);
  885. }
  886. ///<inheritdoc/>
  887. public override bool OnLeave (View view)
  888. {
  889. return MostFocused?.OnLeave (view) ?? base.OnLeave (view);
  890. }
  891. }
  892. /// <summary>
  893. /// Implements the <see cref="IEqualityComparer{T}"/> for comparing two <see cref="Toplevel"/>s
  894. /// used by <see cref="StackExtensions"/>.
  895. /// </summary>
  896. public class ToplevelEqualityComparer : IEqualityComparer<Toplevel> {
  897. /// <summary>Determines whether the specified objects are equal.</summary>
  898. /// <param name="x">The first object of type <see cref="Toplevel" /> to compare.</param>
  899. /// <param name="y">The second object of type <see cref="Toplevel" /> to compare.</param>
  900. /// <returns>
  901. /// <see langword="true" /> if the specified objects are equal; otherwise, <see langword="false" />.</returns>
  902. public bool Equals (Toplevel x, Toplevel y)
  903. {
  904. if (y == null && x == null)
  905. return true;
  906. else if (x == null || y == null)
  907. return false;
  908. else if (x.Id == y.Id)
  909. return true;
  910. else
  911. return false;
  912. }
  913. /// <summary>Returns a hash code for the specified object.</summary>
  914. /// <param name="obj">The <see cref="Toplevel" /> for which a hash code is to be returned.</param>
  915. /// <returns>A hash code for the specified object.</returns>
  916. /// <exception cref="ArgumentNullException">The type of <paramref name="obj" />
  917. /// is a reference type and <paramref name="obj" /> is <see langword="null" />.</exception>
  918. public int GetHashCode (Toplevel obj)
  919. {
  920. if (obj == null)
  921. throw new ArgumentNullException ();
  922. int hCode = 0;
  923. if (int.TryParse (obj.Id.ToString (), out int result)) {
  924. hCode = result;
  925. }
  926. return hCode.GetHashCode ();
  927. }
  928. }
  929. /// <summary>
  930. /// Implements the <see cref="IComparer{T}"/> to sort the <see cref="Toplevel"/>
  931. /// from the <see cref="Application.MdiChildes"/> if needed.
  932. /// </summary>
  933. public sealed class ToplevelComparer : IComparer<Toplevel> {
  934. /// <summary>Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.</summary>
  935. /// <param name="x">The first object to compare.</param>
  936. /// <param name="y">The second object to compare.</param>
  937. /// <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
  938. /// <paramref name="x" /> is less than <paramref name="y" />.Zero
  939. /// <paramref name="x" /> equals <paramref name="y" />.Greater than zero
  940. /// <paramref name="x" /> is greater than <paramref name="y" />.</returns>
  941. public int Compare (Toplevel x, Toplevel y)
  942. {
  943. if (ReferenceEquals (x, y))
  944. return 0;
  945. else if (x == null)
  946. return -1;
  947. else if (y == null)
  948. return 1;
  949. else
  950. return string.Compare (x.Id.ToString (), y.Id.ToString ());
  951. }
  952. }
  953. /// <summary>
  954. /// <see cref="EventArgs"/> implementation for the <see cref="Toplevel.Closing"/> event.
  955. /// </summary>
  956. public class ToplevelClosingEventArgs : EventArgs {
  957. /// <summary>
  958. /// The toplevel requesting stop.
  959. /// </summary>
  960. public View RequestingTop { get; }
  961. /// <summary>
  962. /// Provides an event cancellation option.
  963. /// </summary>
  964. public bool Cancel { get; set; }
  965. /// <summary>
  966. /// Initializes the event arguments with the requesting toplevel.
  967. /// </summary>
  968. /// <param name="requestingTop">The <see cref="RequestingTop"/>.</param>
  969. public ToplevelClosingEventArgs (Toplevel requestingTop)
  970. {
  971. RequestingTop = requestingTop;
  972. }
  973. }
  974. }