Toplevel.cs 31 KB

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