Toplevel.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908
  1. namespace Terminal.Gui;
  2. /// <summary>
  3. /// Toplevel views are used for both an application's main view (filling the entire screen and for modal (pop-up)
  4. /// views such as <see cref="Dialog"/>, <see cref="MessageBox"/>, and <see cref="Wizard"/>).
  5. /// </summary>
  6. /// <remarks>
  7. /// <para>
  8. /// Toplevels can run as modal (popup) views, started by calling
  9. /// <see cref="Application.Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/>. They return control to the caller when
  10. /// <see cref="Application.RequestStop(Toplevel)"/> has been called (which sets the <see cref="Toplevel.Running"/>
  11. /// property to <c>false</c>).
  12. /// </para>
  13. /// <para>
  14. /// A Toplevel is created when an application initializes Terminal.Gui by calling <see cref="Application.Init"/>.
  15. /// The application Toplevel can be accessed via <see cref="Application.Top"/>. Additional Toplevels can be created
  16. /// and run (e.g. <see cref="Dialog"/>s. To run a Toplevel, create the <see cref="Toplevel"/> and call
  17. /// <see cref="Application.Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/>.
  18. /// </para>
  19. /// </remarks>
  20. public partial class Toplevel : View
  21. {
  22. /// <summary>
  23. /// Initializes a new instance of the <see cref="Toplevel"/> class,
  24. /// defaulting to full screen. The <see cref="View.Width"/> and <see cref="View.Height"/> properties will be set to the
  25. /// dimensions of the terminal using <see cref="Dim.Fill"/>.
  26. /// </summary>
  27. public Toplevel ()
  28. {
  29. Arrangement = ViewArrangement.Fixed;
  30. Width = Dim.Fill ();
  31. Height = Dim.Fill ();
  32. ColorScheme = Colors.ColorSchemes ["TopLevel"];
  33. // Things this view knows how to do
  34. AddCommand (
  35. Command.QuitToplevel,
  36. () =>
  37. {
  38. QuitToplevel ();
  39. return true;
  40. }
  41. );
  42. AddCommand (
  43. Command.Suspend,
  44. () =>
  45. {
  46. Driver.Suspend ();
  47. ;
  48. return true;
  49. }
  50. );
  51. AddCommand (
  52. Command.NextView,
  53. () =>
  54. {
  55. MoveNextView ();
  56. return true;
  57. }
  58. );
  59. AddCommand (
  60. Command.PreviousView,
  61. () =>
  62. {
  63. MovePreviousView ();
  64. return true;
  65. }
  66. );
  67. AddCommand (
  68. Command.NextViewOrTop,
  69. () =>
  70. {
  71. MoveNextViewOrTop ();
  72. return true;
  73. }
  74. );
  75. AddCommand (
  76. Command.PreviousViewOrTop,
  77. () =>
  78. {
  79. MovePreviousViewOrTop ();
  80. return true;
  81. }
  82. );
  83. AddCommand (
  84. Command.Refresh,
  85. () =>
  86. {
  87. Application.Refresh ();
  88. return true;
  89. }
  90. );
  91. // Default keybindings for this view
  92. KeyBindings.Add (Application.QuitKey, KeyBindingScope.Application, Command.QuitToplevel);
  93. KeyBindings.Add (Key.CursorRight, Command.NextView);
  94. KeyBindings.Add (Key.CursorDown, Command.NextView);
  95. KeyBindings.Add (Key.CursorLeft, Command.PreviousView);
  96. KeyBindings.Add (Key.CursorUp, Command.PreviousView);
  97. KeyBindings.Add (Key.Tab, Command.NextView);
  98. KeyBindings.Add (Key.Tab.WithShift, Command.PreviousView);
  99. KeyBindings.Add (Key.Tab.WithCtrl, Command.NextViewOrTop);
  100. KeyBindings.Add (Key.Tab.WithShift.WithCtrl, Command.PreviousViewOrTop);
  101. // TODO: Refresh Key should be configurable
  102. KeyBindings.Add (Key.F5, KeyBindingScope.Application, Command.Refresh);
  103. KeyBindings.Add (Application.AlternateForwardKey, Command.NextViewOrTop); // Needed on Unix
  104. KeyBindings.Add (Application.AlternateBackwardKey, Command.PreviousViewOrTop); // Needed on Unix
  105. if (Environment.OSVersion.Platform == PlatformID.Unix)
  106. {
  107. KeyBindings.Add (Key.Z.WithCtrl, Command.Suspend);
  108. }
  109. #if UNIX_KEY_BINDINGS
  110. KeyBindings.Add (Key.L.WithCtrl, Command.Refresh); // Unix
  111. KeyBindings.Add (Key.F.WithCtrl, Command.NextView); // Unix
  112. KeyBindings.Add (Key.I.WithCtrl, Command.NextView); // Unix
  113. KeyBindings.Add (Key.B.WithCtrl, Command.PreviousView); // Unix
  114. #endif
  115. MouseClick += Toplevel_MouseClick;
  116. CanFocus = true;
  117. }
  118. private void Toplevel_MouseClick (object sender, MouseEventEventArgs e)
  119. {
  120. e.Handled = InvokeCommand (Command.HotKey) == true;
  121. }
  122. /// <summary>
  123. /// <see langword="true"/> if was already loaded by the <see cref="Application.Begin(Toplevel)"/>
  124. /// <see langword="false"/>, otherwise.
  125. /// </summary>
  126. public bool IsLoaded { get; private set; }
  127. /// <summary>Gets or sets the menu for this Toplevel.</summary>
  128. public virtual MenuBar MenuBar { get; set; }
  129. /// <summary>
  130. /// Determines whether the <see cref="Toplevel"/> is modal or not. If set to <c>false</c> (the default):
  131. /// <list type="bullet">
  132. /// <item>
  133. /// <description><see cref="View.OnKeyDown"/> events will propagate keys upwards.</description>
  134. /// </item>
  135. /// <item>
  136. /// <description>The Toplevel will act as an embedded view (not a modal/pop-up).</description>
  137. /// </item>
  138. /// </list>
  139. /// If set to <c>true</c>:
  140. /// <list type="bullet">
  141. /// <item>
  142. /// <description><see cref="View.OnKeyDown"/> events will NOT propagate keys upwards.</description>
  143. /// </item>
  144. /// <item>
  145. /// <description>The Toplevel will and look like a modal (pop-up) (e.g. see <see cref="Dialog"/>.</description>
  146. /// </item>
  147. /// </list>
  148. /// </summary>
  149. public bool Modal { get; set; }
  150. /// <summary>Gets or sets whether the main loop for this <see cref="Toplevel"/> is running or not.</summary>
  151. /// <remarks>Setting this property directly is discouraged. Use <see cref="Application.RequestStop"/> instead.</remarks>
  152. public bool Running { get; set; }
  153. /// <summary>Gets or sets the status bar for this Toplevel.</summary>
  154. public virtual StatusBar StatusBar { get; set; }
  155. /// <summary>Invoked when the Toplevel <see cref="RunState"/> becomes the <see cref="Application.Current"/> Toplevel.</summary>
  156. public event EventHandler<ToplevelEventArgs> Activate;
  157. /// <inheritdoc/>
  158. public override void Add (View view)
  159. {
  160. CanFocus = true;
  161. AddMenuStatusBar (view);
  162. base.Add (view);
  163. }
  164. /// <summary>
  165. /// Invoked when the last child of the Toplevel <see cref="RunState"/> is closed from by
  166. /// <see cref="Application.End(RunState)"/>.
  167. /// </summary>
  168. public event EventHandler AllChildClosed;
  169. /// <summary>Invoked when the <see cref="Application.AlternateBackwardKey"/> is changed.</summary>
  170. public event EventHandler<KeyChangedEventArgs> AlternateBackwardKeyChanged;
  171. /// <summary>Invoked when the <see cref="Application.AlternateForwardKey"/> is changed.</summary>
  172. public event EventHandler<KeyChangedEventArgs> AlternateForwardKeyChanged;
  173. /// <summary>
  174. /// Invoked when a child of the Toplevel <see cref="RunState"/> is closed by
  175. /// <see cref="Application.End(RunState)"/>.
  176. /// </summary>
  177. public event EventHandler<ToplevelEventArgs> ChildClosed;
  178. /// <summary>Invoked when a child Toplevel's <see cref="RunState"/> has been loaded.</summary>
  179. public event EventHandler<ToplevelEventArgs> ChildLoaded;
  180. /// <summary>Invoked when a cjhild Toplevel's <see cref="RunState"/> has been unloaded.</summary>
  181. public event EventHandler<ToplevelEventArgs> ChildUnloaded;
  182. /// <summary>Invoked when the Toplevel's <see cref="RunState"/> is closed by <see cref="Application.End(RunState)"/>.</summary>
  183. public event EventHandler<ToplevelEventArgs> Closed;
  184. /// <summary>
  185. /// Invoked when the Toplevel's <see cref="RunState"/> is being closed by
  186. /// <see cref="Application.RequestStop(Toplevel)"/>.
  187. /// </summary>
  188. public event EventHandler<ToplevelClosingEventArgs> Closing;
  189. /// <summary>Invoked when the Toplevel<see cref="RunState"/> ceases to be the <see cref="Application.Current"/> Toplevel.</summary>
  190. public event EventHandler<ToplevelEventArgs> Deactivate;
  191. /// <summary>
  192. /// Invoked when the <see cref="Toplevel"/> <see cref="RunState"/> has begun to be loaded. A Loaded event handler
  193. /// is a good place to finalize initialization before calling <see cref="Application.RunLoop(RunState)"/>.
  194. /// </summary>
  195. public event EventHandler Loaded;
  196. /// <summary>Virtual method to invoke the <see cref="AlternateBackwardKeyChanged"/> event.</summary>
  197. /// <param name="e"></param>
  198. public virtual void OnAlternateBackwardKeyChanged (KeyChangedEventArgs e)
  199. {
  200. KeyBindings.Replace (e.OldKey, e.NewKey);
  201. AlternateBackwardKeyChanged?.Invoke (this, e);
  202. }
  203. /// <summary>Virtual method to invoke the <see cref="AlternateForwardKeyChanged"/> event.</summary>
  204. /// <param name="e"></param>
  205. public virtual void OnAlternateForwardKeyChanged (KeyChangedEventArgs e)
  206. {
  207. KeyBindings.Replace (e.OldKey, e.NewKey);
  208. AlternateForwardKeyChanged?.Invoke (this, e);
  209. }
  210. /// <inheritdoc/>
  211. public override void OnDrawContent (Rectangle viewport)
  212. {
  213. if (!Visible)
  214. {
  215. return;
  216. }
  217. if (NeedsDisplay || SubViewNeedsDisplay || LayoutNeeded)
  218. {
  219. //Driver.SetAttribute (GetNormalColor ());
  220. // TODO: It's bad practice for views to always clear. Defeats the purpose of clipping etc...
  221. Clear ();
  222. LayoutSubviews ();
  223. PositionToplevels ();
  224. if (this == Application.OverlappedTop)
  225. {
  226. foreach (Toplevel top in Application.OverlappedChildren.AsEnumerable ().Reverse ())
  227. {
  228. if (top.Frame.IntersectsWith (Viewport))
  229. {
  230. if (top != this && !top.IsCurrentTop && !OutsideTopFrame (top) && top.Visible)
  231. {
  232. top.SetNeedsLayout ();
  233. top.SetNeedsDisplay (top.Viewport);
  234. top.Draw ();
  235. top.OnRenderLineCanvas ();
  236. }
  237. }
  238. }
  239. }
  240. // This should not be here, but in base
  241. foreach (View view in Subviews)
  242. {
  243. if (view.Frame.IntersectsWith (Viewport) && !OutsideTopFrame (this))
  244. {
  245. //view.SetNeedsLayout ();
  246. view.SetNeedsDisplay ();
  247. view.SetSubViewNeedsDisplay ();
  248. }
  249. }
  250. base.OnDrawContent (viewport);
  251. // This is causing the menus drawn incorrectly if UseSubMenusSingleFrame is true
  252. //if (this.MenuBar is { } && this.MenuBar.IsMenuOpen && this.MenuBar.openMenu is { }) {
  253. // // TODO: Hack until we can get compositing working right.
  254. // this.MenuBar.openMenu.Redraw (this.MenuBar.openMenu.Viewport);
  255. //}
  256. }
  257. }
  258. /// <inheritdoc/>
  259. public override bool OnEnter (View view) { return MostFocused?.OnEnter (view) ?? base.OnEnter (view); }
  260. /// <inheritdoc/>
  261. public override bool OnLeave (View view) { return MostFocused?.OnLeave (view) ?? base.OnLeave (view); }
  262. /// <summary>
  263. /// Called from <see cref="Application.Begin(Toplevel)"/> before the <see cref="Toplevel"/> redraws for the first
  264. /// time.
  265. /// </summary>
  266. public virtual void OnLoaded ()
  267. {
  268. IsLoaded = true;
  269. foreach (Toplevel tl in Subviews.Where (v => v is Toplevel))
  270. {
  271. tl.OnLoaded ();
  272. }
  273. Loaded?.Invoke (this, EventArgs.Empty);
  274. }
  275. /// <summary>Virtual method to invoke the <see cref="QuitKeyChanged"/> event.</summary>
  276. /// <param name="e"></param>
  277. public virtual void OnQuitKeyChanged (KeyChangedEventArgs e)
  278. {
  279. KeyBindings.Replace (e.OldKey, e.NewKey);
  280. QuitKeyChanged?.Invoke (this, e);
  281. }
  282. /// <inheritdoc/>
  283. public override Point? PositionCursor ()
  284. {
  285. if (!IsOverlappedContainer)
  286. {
  287. if (Focused is null)
  288. {
  289. EnsureFocus ();
  290. }
  291. return null;
  292. }
  293. // This code path only happens when the Toplevel is an Overlapped container
  294. if (Focused is null)
  295. {
  296. // TODO: this is an Overlapped hack
  297. foreach (Toplevel top in Application.OverlappedChildren)
  298. {
  299. if (top != this && top.Visible)
  300. {
  301. top.SetFocus ();
  302. return null;
  303. }
  304. }
  305. }
  306. var cursor2 = base.PositionCursor ();
  307. return null;
  308. }
  309. /// <summary>
  310. /// Adjusts the location and size of <paramref name="top"/> within this Toplevel. Virtual method enabling
  311. /// implementation of specific positions for inherited <see cref="Toplevel"/> views.
  312. /// </summary>
  313. /// <param name="top">The Toplevel to adjust.</param>
  314. public virtual void PositionToplevel (Toplevel top)
  315. {
  316. View superView = GetLocationEnsuringFullVisibility (
  317. top,
  318. top.Frame.X,
  319. top.Frame.Y,
  320. out int nx,
  321. out int ny,
  322. out StatusBar sb
  323. );
  324. if (superView is null)
  325. {
  326. return;
  327. }
  328. var layoutSubviews = false;
  329. var maxWidth = 0;
  330. if (superView.Margin is { } && superView == top.SuperView)
  331. {
  332. maxWidth -= superView.GetAdornmentsThickness ().Left + superView.GetAdornmentsThickness ().Right;
  333. }
  334. if ((superView != top || top?.SuperView is { } || (top != Application.Top && top.Modal) || (top?.SuperView is null && top.IsOverlapped))
  335. && (top.Frame.X + top.Frame.Width > maxWidth || ny > top.Frame.Y))
  336. {
  337. if ((top.X is null || top.X is PosAbsolute) && top.Frame.X != nx)
  338. {
  339. top.X = nx;
  340. layoutSubviews = true;
  341. }
  342. if ((top.Y is null || top.Y is PosAbsolute) && top.Frame.Y != ny)
  343. {
  344. top.Y = ny;
  345. layoutSubviews = true;
  346. }
  347. }
  348. // TODO: v2 - This is a hack to get the StatusBar to be positioned correctly.
  349. if (sb != null
  350. && !top.Subviews.Contains (sb)
  351. && ny + top.Frame.Height != superView.Frame.Height - (sb.Visible ? 1 : 0)
  352. && top.Height is DimFill
  353. && -top.Height.GetAnchor (0) < 1)
  354. {
  355. top.Height = Dim.Fill (sb.Visible ? 1 : 0);
  356. layoutSubviews = true;
  357. }
  358. if (superView.LayoutNeeded || layoutSubviews)
  359. {
  360. superView.LayoutSubviews ();
  361. }
  362. if (LayoutNeeded)
  363. {
  364. LayoutSubviews ();
  365. }
  366. }
  367. /// <summary>Invoked when the <see cref="Application.QuitKey"/> is changed.</summary>
  368. public event EventHandler<KeyChangedEventArgs> QuitKeyChanged;
  369. /// <summary>
  370. /// Invoked when the <see cref="Toplevel"/> main loop has started it's first iteration. Subscribe to this event to
  371. /// perform tasks when the <see cref="Toplevel"/> has been laid out and focus has been set. changes.
  372. /// <para>
  373. /// A Ready event handler is a good place to finalize initialization after calling
  374. /// <see cref="Application.Run(Toplevel, Func{Exception, bool}, ConsoleDriver)"/> on this <see cref="Toplevel"/>.
  375. /// </para>
  376. /// </summary>
  377. public event EventHandler Ready;
  378. /// <inheritdoc/>
  379. public override void Remove (View view)
  380. {
  381. if (this is Toplevel { MenuBar: { } })
  382. {
  383. RemoveMenuStatusBar (view);
  384. }
  385. base.Remove (view);
  386. }
  387. /// <inheritdoc/>
  388. public override void RemoveAll ()
  389. {
  390. if (this == Application.Top)
  391. {
  392. MenuBar?.Dispose ();
  393. MenuBar = null;
  394. StatusBar?.Dispose ();
  395. StatusBar = null;
  396. }
  397. base.RemoveAll ();
  398. }
  399. /// <summary>
  400. /// Stops and closes this <see cref="Toplevel"/>. If this Toplevel is the top-most Toplevel,
  401. /// <see cref="Application.RequestStop(Toplevel)"/> will be called, causing the application to exit.
  402. /// </summary>
  403. public virtual void RequestStop ()
  404. {
  405. if (IsOverlappedContainer
  406. && Running
  407. && (Application.Current == this
  408. || Application.Current?.Modal == false
  409. || (Application.Current?.Modal == true && Application.Current?.Running == false)))
  410. {
  411. foreach (Toplevel child in Application.OverlappedChildren)
  412. {
  413. var ev = new ToplevelClosingEventArgs (this);
  414. if (child.OnClosing (ev))
  415. {
  416. return;
  417. }
  418. child.Running = false;
  419. Application.RequestStop (child);
  420. }
  421. Running = false;
  422. Application.RequestStop (this);
  423. }
  424. else if (IsOverlappedContainer && Running && Application.Current?.Modal == true && Application.Current?.Running == true)
  425. {
  426. var ev = new ToplevelClosingEventArgs (Application.Current);
  427. if (OnClosing (ev))
  428. {
  429. return;
  430. }
  431. Application.RequestStop (Application.Current);
  432. }
  433. else if (!IsOverlappedContainer && Running && (!Modal || (Modal && Application.Current != this)))
  434. {
  435. var ev = new ToplevelClosingEventArgs (this);
  436. if (OnClosing (ev))
  437. {
  438. return;
  439. }
  440. Running = false;
  441. Application.RequestStop (this);
  442. }
  443. else
  444. {
  445. Application.RequestStop (Application.Current);
  446. }
  447. }
  448. /// <summary>
  449. /// Stops and closes the <see cref="Toplevel"/> specified by <paramref name="top"/>. If <paramref name="top"/> is
  450. /// the top-most Toplevel, <see cref="Application.RequestStop(Toplevel)"/> will be called, causing the application to
  451. /// exit.
  452. /// </summary>
  453. /// <param name="top">The Toplevel to request stop.</param>
  454. public virtual void RequestStop (Toplevel top) { top.RequestStop (); }
  455. /// <summary>Invoked when the terminal has been resized. The new <see cref="Size"/> of the terminal is provided.</summary>
  456. public event EventHandler<SizeChangedEventArgs> SizeChanging;
  457. /// <summary>
  458. /// Invoked when the Toplevel <see cref="RunState"/> has been unloaded. A Unloaded event handler is a good place
  459. /// to dispose objects after calling <see cref="Application.End(RunState)"/>.
  460. /// </summary>
  461. public event EventHandler Unloaded;
  462. internal void AddMenuStatusBar (View view)
  463. {
  464. if (view is MenuBar)
  465. {
  466. MenuBar = view as MenuBar;
  467. }
  468. if (view is StatusBar)
  469. {
  470. StatusBar = view as StatusBar;
  471. }
  472. }
  473. internal virtual void OnActivate (Toplevel deactivated) { Activate?.Invoke (this, new ToplevelEventArgs (deactivated)); }
  474. internal virtual void OnAllChildClosed () { AllChildClosed?.Invoke (this, EventArgs.Empty); }
  475. internal virtual void OnChildClosed (Toplevel top)
  476. {
  477. if (IsOverlappedContainer)
  478. {
  479. SetSubViewNeedsDisplay ();
  480. }
  481. ChildClosed?.Invoke (this, new ToplevelEventArgs (top));
  482. }
  483. internal virtual void OnChildLoaded (Toplevel top) { ChildLoaded?.Invoke (this, new ToplevelEventArgs (top)); }
  484. internal virtual void OnChildUnloaded (Toplevel top) { ChildUnloaded?.Invoke (this, new ToplevelEventArgs (top)); }
  485. internal virtual void OnClosed (Toplevel top) { Closed?.Invoke (this, new ToplevelEventArgs (top)); }
  486. internal virtual bool OnClosing (ToplevelClosingEventArgs ev)
  487. {
  488. Closing?.Invoke (this, ev);
  489. return ev.Cancel;
  490. }
  491. internal virtual void OnDeactivate (Toplevel activated) { Deactivate?.Invoke (this, new ToplevelEventArgs (activated)); }
  492. /// <summary>
  493. /// Called from <see cref="Application.RunLoop"/> after the <see cref="Toplevel"/> has entered the first iteration
  494. /// of the loop.
  495. /// </summary>
  496. internal virtual void OnReady ()
  497. {
  498. foreach (Toplevel tl in Subviews.Where (v => v is Toplevel))
  499. {
  500. tl.OnReady ();
  501. }
  502. Ready?.Invoke (this, EventArgs.Empty);
  503. }
  504. // TODO: Make cancelable?
  505. internal virtual void OnSizeChanging (SizeChangedEventArgs size) { SizeChanging?.Invoke (this, size); }
  506. /// <summary>Called from <see cref="Application.End(RunState)"/> before the <see cref="Toplevel"/> is disposed.</summary>
  507. internal virtual void OnUnloaded ()
  508. {
  509. foreach (Toplevel tl in Subviews.Where (v => v is Toplevel))
  510. {
  511. tl.OnUnloaded ();
  512. }
  513. Unloaded?.Invoke (this, EventArgs.Empty);
  514. }
  515. // TODO: v2 - Not sure this is needed anymore.
  516. internal void PositionToplevels ()
  517. {
  518. PositionToplevel (this);
  519. foreach (View top in Subviews)
  520. {
  521. if (top is Toplevel)
  522. {
  523. PositionToplevel ((Toplevel)top);
  524. }
  525. }
  526. }
  527. internal void RemoveMenuStatusBar (View view)
  528. {
  529. if (view is MenuBar)
  530. {
  531. MenuBar?.Dispose ();
  532. MenuBar = null;
  533. }
  534. if (view is StatusBar)
  535. {
  536. StatusBar?.Dispose ();
  537. StatusBar = null;
  538. }
  539. }
  540. private void FocusNearestView (IEnumerable<View> views, NavigationDirection direction)
  541. {
  542. if (views is null)
  543. {
  544. return;
  545. }
  546. var found = false;
  547. var focusProcessed = false;
  548. var idx = 0;
  549. foreach (View v in views)
  550. {
  551. if (v == this)
  552. {
  553. found = true;
  554. }
  555. if (found && v != this)
  556. {
  557. if (direction == NavigationDirection.Forward)
  558. {
  559. SuperView?.FocusNext ();
  560. }
  561. else
  562. {
  563. SuperView?.FocusPrev ();
  564. }
  565. focusProcessed = true;
  566. if (SuperView.Focused is { } && SuperView.Focused != this)
  567. {
  568. return;
  569. }
  570. }
  571. else if (found && !focusProcessed && idx == views.Count () - 1)
  572. {
  573. views.ToList () [0].SetFocus ();
  574. }
  575. idx++;
  576. }
  577. }
  578. private View GetDeepestFocusedSubview (View view)
  579. {
  580. if (view is null)
  581. {
  582. return null;
  583. }
  584. foreach (View v in view.Subviews)
  585. {
  586. if (v.HasFocus)
  587. {
  588. return GetDeepestFocusedSubview (v);
  589. }
  590. }
  591. return view;
  592. }
  593. private void MoveNextView ()
  594. {
  595. View old = GetDeepestFocusedSubview (Focused);
  596. if (!FocusNext ())
  597. {
  598. FocusNext ();
  599. }
  600. if (old != Focused && old != Focused?.Focused)
  601. {
  602. old?.SetNeedsDisplay ();
  603. Focused?.SetNeedsDisplay ();
  604. }
  605. else
  606. {
  607. FocusNearestView (SuperView?.TabIndexes, NavigationDirection.Forward);
  608. }
  609. }
  610. private void MoveNextViewOrTop ()
  611. {
  612. if (Application.OverlappedTop is null)
  613. {
  614. Toplevel top = Modal ? this : Application.Top;
  615. top.FocusNext ();
  616. if (top.Focused is null)
  617. {
  618. top.FocusNext ();
  619. }
  620. top.SetNeedsDisplay ();
  621. Application.BringOverlappedTopToFront ();
  622. }
  623. else
  624. {
  625. Application.OverlappedMoveNext ();
  626. }
  627. }
  628. private void MovePreviousView ()
  629. {
  630. View old = GetDeepestFocusedSubview (Focused);
  631. if (!FocusPrev ())
  632. {
  633. FocusPrev ();
  634. }
  635. if (old != Focused && old != Focused?.Focused)
  636. {
  637. old?.SetNeedsDisplay ();
  638. Focused?.SetNeedsDisplay ();
  639. }
  640. else
  641. {
  642. FocusNearestView (SuperView?.TabIndexes?.Reverse (), NavigationDirection.Backward);
  643. }
  644. }
  645. private void MovePreviousViewOrTop ()
  646. {
  647. if (Application.OverlappedTop is null)
  648. {
  649. Toplevel top = Modal ? this : Application.Top;
  650. top.FocusPrev ();
  651. if (top.Focused is null)
  652. {
  653. top.FocusPrev ();
  654. }
  655. top.SetNeedsDisplay ();
  656. Application.BringOverlappedTopToFront ();
  657. }
  658. else
  659. {
  660. Application.OverlappedMovePrevious ();
  661. }
  662. }
  663. private bool OutsideTopFrame (Toplevel top)
  664. {
  665. if (top.Frame.X > Driver.Cols || top.Frame.Y > Driver.Rows)
  666. {
  667. return true;
  668. }
  669. return false;
  670. }
  671. private void QuitToplevel ()
  672. {
  673. if (Application.OverlappedTop is { })
  674. {
  675. RequestStop (this);
  676. }
  677. else
  678. {
  679. Application.RequestStop ();
  680. }
  681. }
  682. }
  683. /// <summary>
  684. /// Implements the <see cref="IEqualityComparer{T}"/> for comparing two <see cref="Toplevel"/>s used by
  685. /// <see cref="StackExtensions"/>.
  686. /// </summary>
  687. public class ToplevelEqualityComparer : IEqualityComparer<Toplevel>
  688. {
  689. /// <summary>Determines whether the specified objects are equal.</summary>
  690. /// <param name="x">The first object of type <see cref="Toplevel"/> to compare.</param>
  691. /// <param name="y">The second object of type <see cref="Toplevel"/> to compare.</param>
  692. /// <returns><see langword="true"/> if the specified objects are equal; otherwise, <see langword="false"/>.</returns>
  693. public bool Equals (Toplevel x, Toplevel y)
  694. {
  695. if (y is null && x is null)
  696. {
  697. return true;
  698. }
  699. if (x is null || y is null)
  700. {
  701. return false;
  702. }
  703. if (x.Id == y.Id)
  704. {
  705. return true;
  706. }
  707. return false;
  708. }
  709. /// <summary>Returns a hash code for the specified object.</summary>
  710. /// <param name="obj">The <see cref="Toplevel"/> for which a hash code is to be returned.</param>
  711. /// <returns>A hash code for the specified object.</returns>
  712. /// <exception cref="ArgumentNullException">
  713. /// The type of <paramref name="obj"/> is a reference type and
  714. /// <paramref name="obj"/> is <see langword="null"/>.
  715. /// </exception>
  716. public int GetHashCode (Toplevel obj)
  717. {
  718. if (obj is null)
  719. {
  720. throw new ArgumentNullException ();
  721. }
  722. var hCode = 0;
  723. if (int.TryParse (obj.Id, out int result))
  724. {
  725. hCode = result;
  726. }
  727. return hCode.GetHashCode ();
  728. }
  729. }
  730. /// <summary>
  731. /// Implements the <see cref="IComparer{T}"/> to sort the <see cref="Toplevel"/> from the
  732. /// <see cref="Application.OverlappedChildren"/> if needed.
  733. /// </summary>
  734. public sealed class ToplevelComparer : IComparer<Toplevel>
  735. {
  736. /// <summary>
  737. /// Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the
  738. /// other.
  739. /// </summary>
  740. /// <param name="x">The first object to compare.</param>
  741. /// <param name="y">The second object to compare.</param>
  742. /// <returns>
  743. /// A signed integer that indicates the relative values of <paramref name="x"/> and <paramref name="y"/>, as shown
  744. /// in the following table.Value Meaning Less than zero <paramref name="x"/> is less than <paramref name="y"/>.Zero
  745. /// <paramref name="x"/> equals <paramref name="y"/> .Greater than zero <paramref name="x"/> is greater than
  746. /// <paramref name="y"/>.
  747. /// </returns>
  748. public int Compare (Toplevel x, Toplevel y)
  749. {
  750. if (ReferenceEquals (x, y))
  751. {
  752. return 0;
  753. }
  754. if (x is null)
  755. {
  756. return -1;
  757. }
  758. if (y is null)
  759. {
  760. return 1;
  761. }
  762. return string.Compare (x.Id, y.Id);
  763. }
  764. }