Toplevel.cs 30 KB

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