Toplevel.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  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. MouseClick += Toplevel_MouseClick;
  35. }
  36. #region Keyboard & Mouse
  37. // TODO: IRunnable: Re-implement - Modal means IRunnable, ViewArrangement.Overlapped where modalView.Z > allOtherViews.Max (v = v.Z), and exclusive key/mouse input.
  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. private void Toplevel_MouseClick (object sender, MouseEventEventArgs e) { e.Handled = InvokeCommand (Command.HotKey) == true; }
  60. #endregion
  61. #region Subviews
  62. // TODO: Deprecate - Any view can host a menubar in v2
  63. /// <summary>Gets or sets the menu for this Toplevel.</summary>
  64. public virtual MenuBar MenuBar { get; set; }
  65. // TODO: Deprecate - Any view can host a statusbar in v2
  66. /// <summary>Gets or sets the status bar for this Toplevel.</summary>
  67. public virtual StatusBar StatusBar { get; set; }
  68. /// <inheritdoc/>
  69. public override View Add (View view)
  70. {
  71. CanFocus = true;
  72. AddMenuStatusBar (view);
  73. return base.Add (view);
  74. }
  75. /// <inheritdoc/>
  76. public override View Remove (View view)
  77. {
  78. if (this is Toplevel { MenuBar: { } })
  79. {
  80. RemoveMenuStatusBar (view);
  81. }
  82. return base.Remove (view);
  83. }
  84. /// <inheritdoc/>
  85. public override void RemoveAll ()
  86. {
  87. if (this == Application.Top)
  88. {
  89. MenuBar?.Dispose ();
  90. MenuBar = null;
  91. StatusBar?.Dispose ();
  92. StatusBar = null;
  93. }
  94. base.RemoveAll ();
  95. }
  96. internal void AddMenuStatusBar (View view)
  97. {
  98. if (view is MenuBar)
  99. {
  100. MenuBar = view as MenuBar;
  101. }
  102. if (view is StatusBar)
  103. {
  104. StatusBar = view as StatusBar;
  105. }
  106. }
  107. internal void RemoveMenuStatusBar (View view)
  108. {
  109. if (view is MenuBar)
  110. {
  111. MenuBar?.Dispose ();
  112. MenuBar = null;
  113. }
  114. if (view is StatusBar)
  115. {
  116. StatusBar?.Dispose ();
  117. StatusBar = null;
  118. }
  119. }
  120. // TODO: Overlapped - Rename to AllSubviewsClosed - Move to View?
  121. /// <summary>
  122. /// Invoked when the last child of the Toplevel <see cref="RunState"/> is closed from by
  123. /// <see cref="Application.End(RunState)"/>.
  124. /// </summary>
  125. public event EventHandler AllChildClosed;
  126. // TODO: Overlapped - Rename to *Subviews* - Move to View?
  127. /// <summary>
  128. /// Invoked when a child of the Toplevel <see cref="RunState"/> is closed by
  129. /// <see cref="Application.End(RunState)"/>.
  130. /// </summary>
  131. public event EventHandler<ToplevelEventArgs> ChildClosed;
  132. // TODO: Overlapped - Rename to *Subviews* - Move to View?
  133. /// <summary>Invoked when a child Toplevel's <see cref="RunState"/> has been loaded.</summary>
  134. public event EventHandler<ToplevelEventArgs> ChildLoaded;
  135. // TODO: Overlapped - Rename to *Subviews* - Move to View?
  136. /// <summary>Invoked when a cjhild Toplevel's <see cref="RunState"/> has been unloaded.</summary>
  137. public event EventHandler<ToplevelEventArgs> ChildUnloaded;
  138. #endregion
  139. #region Life Cycle
  140. // TODO: IRunnable: Re-implement as a property on IRunnable
  141. /// <summary>Gets or sets whether the main loop for this <see cref="Toplevel"/> is running or not.</summary>
  142. /// <remarks>Setting this property directly is discouraged. Use <see cref="Application.RequestStop"/> instead.</remarks>
  143. public bool Running { get; set; }
  144. // TODO: IRunnable: Re-implement in IRunnable
  145. /// <summary>
  146. /// <see langword="true"/> if was already loaded by the <see cref="Application.Begin(Toplevel)"/>
  147. /// <see langword="false"/>, otherwise.
  148. /// </summary>
  149. public bool IsLoaded { get; private set; }
  150. // TODO: IRunnable: Re-implement as an event on IRunnable; IRunnable.Activating/Activate
  151. /// <summary>Invoked when the Toplevel <see cref="RunState"/> becomes the <see cref="Application.Current"/> Toplevel.</summary>
  152. public event EventHandler<ToplevelEventArgs> Activate;
  153. // TODO: IRunnable: Re-implement as an event on IRunnable; IRunnable.Deactivating/Deactivate?
  154. /// <summary>Invoked when the Toplevel<see cref="RunState"/> ceases to be the <see cref="Application.Current"/> Toplevel.</summary>
  155. public event EventHandler<ToplevelEventArgs> Deactivate;
  156. /// <summary>Invoked when the Toplevel's <see cref="RunState"/> is closed by <see cref="Application.End(RunState)"/>.</summary>
  157. public event EventHandler<ToplevelEventArgs> Closed;
  158. /// <summary>
  159. /// Invoked when the Toplevel's <see cref="RunState"/> is being closed by
  160. /// <see cref="Application.RequestStop(Toplevel)"/>.
  161. /// </summary>
  162. public event EventHandler<ToplevelClosingEventArgs> Closing;
  163. /// <summary>
  164. /// Invoked when the <see cref="Toplevel"/> <see cref="RunState"/> has begun to be loaded. A Loaded event handler
  165. /// is a good place to finalize initialization before calling <see cref="Application.RunLoop(RunState)"/>.
  166. /// </summary>
  167. public event EventHandler Loaded;
  168. /// <summary>
  169. /// Called from <see cref="Application.Begin(Toplevel)"/> before the <see cref="Toplevel"/> redraws for the first
  170. /// time.
  171. /// </summary>
  172. /// <remarks>
  173. /// Overrides must call base.OnLoaded() to ensure any Toplevel subviews are initialized properly and the
  174. /// <see cref="Loaded"/> event is raised.
  175. /// </remarks>
  176. public virtual void OnLoaded ()
  177. {
  178. IsLoaded = true;
  179. foreach (Toplevel tl in Subviews.Where (v => v is Toplevel))
  180. {
  181. tl.OnLoaded ();
  182. }
  183. Loaded?.Invoke (this, EventArgs.Empty);
  184. }
  185. /// <summary>
  186. /// Invoked when the <see cref="Toplevel"/> main loop has started it's first iteration. Subscribe to this event to
  187. /// perform tasks when the <see cref="Toplevel"/> has been laid out and focus has been set. changes.
  188. /// <para>
  189. /// A Ready event handler is a good place to finalize initialization after calling
  190. /// <see cref="Application.Run(Toplevel, Func{Exception, bool})"/> on this <see cref="Toplevel"/>.
  191. /// </para>
  192. /// </summary>
  193. public event EventHandler Ready;
  194. /// <summary>
  195. /// Stops and closes this <see cref="Toplevel"/>. If this Toplevel is the top-most Toplevel,
  196. /// <see cref="Application.RequestStop(Toplevel)"/> will be called, causing the application to exit.
  197. /// </summary>
  198. public virtual void RequestStop ()
  199. {
  200. if (IsOverlappedContainer
  201. && Running
  202. && (Application.Current == this
  203. || Application.Current?.Modal == false
  204. || (Application.Current?.Modal == true && Application.Current?.Running == false)))
  205. {
  206. foreach (Toplevel child in ApplicationOverlapped.OverlappedChildren!)
  207. {
  208. var ev = new ToplevelClosingEventArgs (this);
  209. if (child.OnClosing (ev))
  210. {
  211. return;
  212. }
  213. child.Running = false;
  214. Application.RequestStop (child);
  215. }
  216. Running = false;
  217. Application.RequestStop (this);
  218. }
  219. else if (IsOverlappedContainer && Running && Application.Current?.Modal == true && Application.Current?.Running == true)
  220. {
  221. var ev = new ToplevelClosingEventArgs (Application.Current);
  222. if (OnClosing (ev))
  223. {
  224. return;
  225. }
  226. Application.RequestStop (Application.Current);
  227. }
  228. else if (!IsOverlappedContainer && Running && (!Modal || (Modal && Application.Current != this)))
  229. {
  230. var ev = new ToplevelClosingEventArgs (this);
  231. if (OnClosing (ev))
  232. {
  233. return;
  234. }
  235. Running = false;
  236. Application.RequestStop (this);
  237. }
  238. else
  239. {
  240. Application.RequestStop (Application.Current);
  241. }
  242. }
  243. /// <summary>
  244. /// Invoked when the Toplevel <see cref="RunState"/> has been unloaded. A Unloaded event handler is a good place
  245. /// to dispose objects after calling <see cref="Application.End(RunState)"/>.
  246. /// </summary>
  247. public event EventHandler Unloaded;
  248. internal virtual void OnActivate (Toplevel deactivated) { Activate?.Invoke (this, new (deactivated)); }
  249. /// <summary>
  250. /// Stops and closes the <see cref="Toplevel"/> specified by <paramref name="top"/>. If <paramref name="top"/> is
  251. /// the top-most Toplevel, <see cref="Application.RequestStop(Toplevel)"/> will be called, causing the application to
  252. /// exit.
  253. /// </summary>
  254. /// <param name="top">The Toplevel to request stop.</param>
  255. public virtual void RequestStop (Toplevel top) { top.RequestStop (); }
  256. internal virtual void OnAllChildClosed () { AllChildClosed?.Invoke (this, EventArgs.Empty); }
  257. internal virtual void OnChildClosed (Toplevel top)
  258. {
  259. if (IsOverlappedContainer)
  260. {
  261. SetSubViewNeedsDisplay ();
  262. }
  263. ChildClosed?.Invoke (this, new (top));
  264. }
  265. internal virtual void OnChildLoaded (Toplevel top) { ChildLoaded?.Invoke (this, new (top)); }
  266. internal virtual void OnChildUnloaded (Toplevel top) { ChildUnloaded?.Invoke (this, new (top)); }
  267. internal virtual void OnClosed (Toplevel top) { Closed?.Invoke (this, new (top)); }
  268. internal virtual bool OnClosing (ToplevelClosingEventArgs ev)
  269. {
  270. Closing?.Invoke (this, ev);
  271. return ev.Cancel;
  272. }
  273. internal virtual void OnDeactivate (Toplevel activated) { Deactivate?.Invoke (this, new (activated)); }
  274. /// <summary>
  275. /// Called from <see cref="Application.RunLoop"/> after the <see cref="Toplevel"/> has entered the first iteration
  276. /// of the loop.
  277. /// </summary>
  278. internal virtual void OnReady ()
  279. {
  280. foreach (Toplevel tl in Subviews.Where (v => v is Toplevel))
  281. {
  282. tl.OnReady ();
  283. }
  284. Ready?.Invoke (this, EventArgs.Empty);
  285. }
  286. /// <summary>Called from <see cref="Application.End(RunState)"/> before the <see cref="Toplevel"/> is disposed.</summary>
  287. internal virtual void OnUnloaded ()
  288. {
  289. foreach (Toplevel tl in Subviews.Where (v => v is Toplevel))
  290. {
  291. tl.OnUnloaded ();
  292. }
  293. Unloaded?.Invoke (this, EventArgs.Empty);
  294. }
  295. #endregion
  296. #region Draw
  297. /// <inheritdoc/>
  298. public override void OnDrawContent (Rectangle viewport)
  299. {
  300. if (!Visible)
  301. {
  302. return;
  303. }
  304. if (NeedsDisplay || SubViewNeedsDisplay /*|| LayoutNeeded*/)
  305. {
  306. Clear ();
  307. //LayoutSubviews ();
  308. PositionToplevels ();
  309. if (this == ApplicationOverlapped.OverlappedTop)
  310. {
  311. // This enables correct draw behavior when switching between overlapped subviews
  312. foreach (Toplevel top in ApplicationOverlapped.OverlappedChildren!.AsEnumerable ().Reverse ())
  313. {
  314. if (top.Frame.IntersectsWith (Viewport))
  315. {
  316. if (top != this && !top.IsCurrentTop && !OutsideTopFrame (top) && top.Visible)
  317. {
  318. top.SetNeedsLayout ();
  319. top.SetNeedsDisplay (top.Viewport);
  320. top.Draw ();
  321. top.OnRenderLineCanvas ();
  322. }
  323. }
  324. }
  325. }
  326. // BUGBUG: This appears to be a hack to get ScrollBarViews to render correctly.
  327. foreach (View view in Subviews)
  328. {
  329. if (view.Frame.IntersectsWith (Viewport) && !OutsideTopFrame (this))
  330. {
  331. //view.SetNeedsLayout ();
  332. view.SetNeedsDisplay ();
  333. view.SetSubViewNeedsDisplay ();
  334. }
  335. }
  336. base.OnDrawContent (viewport);
  337. }
  338. }
  339. #endregion
  340. #region Navigation
  341. /// <inheritdoc/>
  342. public override bool OnEnter (View view) { return MostFocused?.OnEnter (view) ?? base.OnEnter (view); }
  343. /// <inheritdoc/>
  344. public override bool OnLeave (View view) { return MostFocused?.OnLeave (view) ?? base.OnLeave (view); }
  345. #endregion
  346. #region Size / Position Management
  347. // TODO: Make cancelable?
  348. internal virtual void OnSizeChanging (SizeChangedEventArgs size) { SizeChanging?.Invoke (this, size); }
  349. /// <inheritdoc/>
  350. public override Point? PositionCursor ()
  351. {
  352. if (!IsOverlappedContainer)
  353. {
  354. if (Focused is null)
  355. {
  356. EnsureFocus ();
  357. }
  358. return null;
  359. }
  360. // This code path only happens when the Toplevel is an Overlapped container
  361. if (Focused is null)
  362. {
  363. // TODO: this is an Overlapped hack
  364. foreach (Toplevel top in ApplicationOverlapped.OverlappedChildren!)
  365. {
  366. if (top != this && top.Visible)
  367. {
  368. top.SetFocus ();
  369. return null;
  370. }
  371. }
  372. }
  373. Point? cursor2 = base.PositionCursor ();
  374. return null;
  375. }
  376. /// <summary>
  377. /// Adjusts the location and size of <paramref name="top"/> within this Toplevel. Virtual method enabling
  378. /// implementation of specific positions for inherited <see cref="Toplevel"/> views.
  379. /// </summary>
  380. /// <param name="top">The Toplevel to adjust.</param>
  381. public virtual void PositionToplevel (Toplevel top)
  382. {
  383. View superView = GetLocationEnsuringFullVisibility (
  384. top,
  385. top.Frame.X,
  386. top.Frame.Y,
  387. out int nx,
  388. out int ny,
  389. out StatusBar sb
  390. );
  391. if (superView is null)
  392. {
  393. return;
  394. }
  395. var layoutSubviews = false;
  396. var maxWidth = 0;
  397. if (superView.Margin is { } && superView == top.SuperView)
  398. {
  399. maxWidth -= superView.GetAdornmentsThickness ().Left + superView.GetAdornmentsThickness ().Right;
  400. }
  401. if ((superView != top || top?.SuperView is { } || (top != Application.Top && top.Modal) || (top?.SuperView is null && top.IsOverlapped))
  402. && (top.Frame.X + top.Frame.Width > maxWidth || ny > top.Frame.Y))
  403. {
  404. if ((top.X is null || top.X is PosAbsolute) && top.Frame.X != nx)
  405. {
  406. top.X = nx;
  407. layoutSubviews = true;
  408. }
  409. if ((top.Y is null || top.Y is PosAbsolute) && top.Frame.Y != ny)
  410. {
  411. top.Y = ny;
  412. layoutSubviews = true;
  413. }
  414. }
  415. // TODO: v2 - This is a hack to get the StatusBar to be positioned correctly.
  416. if (sb != null
  417. && !top.Subviews.Contains (sb)
  418. && ny + top.Frame.Height != superView.Frame.Height - (sb.Visible ? 1 : 0)
  419. && top.Height is DimFill
  420. && -top.Height.GetAnchor (0) < 1)
  421. {
  422. top.Height = Dim.Fill (sb.Visible ? 1 : 0);
  423. layoutSubviews = true;
  424. }
  425. if (superView.LayoutNeeded || layoutSubviews)
  426. {
  427. superView.LayoutSubviews ();
  428. }
  429. if (LayoutNeeded)
  430. {
  431. LayoutSubviews ();
  432. }
  433. }
  434. /// <summary>Invoked when the terminal has been resized. The new <see cref="Size"/> of the terminal is provided.</summary>
  435. public event EventHandler<SizeChangedEventArgs> SizeChanging;
  436. private bool OutsideTopFrame (Toplevel top)
  437. {
  438. if (top.Frame.X > Driver.Cols || top.Frame.Y > Driver.Rows)
  439. {
  440. return true;
  441. }
  442. return false;
  443. }
  444. // TODO: v2 - Not sure this is needed anymore.
  445. internal void PositionToplevels ()
  446. {
  447. PositionToplevel (this);
  448. foreach (View top in Subviews)
  449. {
  450. if (top is Toplevel)
  451. {
  452. PositionToplevel ((Toplevel)top);
  453. }
  454. }
  455. }
  456. #endregion
  457. }
  458. /// <summary>
  459. /// Implements the <see cref="IEqualityComparer{T}"/> for comparing two <see cref="Toplevel"/>s used by
  460. /// <see cref="StackExtensions"/>.
  461. /// </summary>
  462. public class ToplevelEqualityComparer : IEqualityComparer<Toplevel>
  463. {
  464. /// <summary>Determines whether the specified objects are equal.</summary>
  465. /// <param name="x">The first object of type <see cref="Toplevel"/> to compare.</param>
  466. /// <param name="y">The second object of type <see cref="Toplevel"/> to compare.</param>
  467. /// <returns><see langword="true"/> if the specified objects are equal; otherwise, <see langword="false"/>.</returns>
  468. public bool Equals (Toplevel x, Toplevel y)
  469. {
  470. if (y is null && x is null)
  471. {
  472. return true;
  473. }
  474. if (x is null || y is null)
  475. {
  476. return false;
  477. }
  478. if (x.Id == y.Id)
  479. {
  480. return true;
  481. }
  482. return false;
  483. }
  484. /// <summary>Returns a hash code for the specified object.</summary>
  485. /// <param name="obj">The <see cref="Toplevel"/> for which a hash code is to be returned.</param>
  486. /// <returns>A hash code for the specified object.</returns>
  487. /// <exception cref="ArgumentNullException">
  488. /// The type of <paramref name="obj"/> is a reference type and
  489. /// <paramref name="obj"/> is <see langword="null"/>.
  490. /// </exception>
  491. public int GetHashCode (Toplevel obj)
  492. {
  493. if (obj is null)
  494. {
  495. throw new ArgumentNullException ();
  496. }
  497. var hCode = 0;
  498. if (int.TryParse (obj.Id, out int result))
  499. {
  500. hCode = result;
  501. }
  502. return hCode.GetHashCode ();
  503. }
  504. }
  505. /// <summary>
  506. /// Implements the <see cref="IComparer{T}"/> to sort the <see cref="Toplevel"/> from the
  507. /// <see cref="ApplicationOverlapped.OverlappedChildren"/> if needed.
  508. /// </summary>
  509. public sealed class ToplevelComparer : IComparer<Toplevel>
  510. {
  511. /// <summary>
  512. /// Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the
  513. /// other.
  514. /// </summary>
  515. /// <param name="x">The first object to compare.</param>
  516. /// <param name="y">The second object to compare.</param>
  517. /// <returns>
  518. /// A signed integer that indicates the relative values of <paramref name="x"/> and <paramref name="y"/>, as shown
  519. /// in the following table.Value Meaning Less than zero <paramref name="x"/> is less than <paramref name="y"/>.Zero
  520. /// <paramref name="x"/> equals <paramref name="y"/> .Greater than zero <paramref name="x"/> is greater than
  521. /// <paramref name="y"/>.
  522. /// </returns>
  523. public int Compare (Toplevel x, Toplevel y)
  524. {
  525. if (ReferenceEquals (x, y))
  526. {
  527. return 0;
  528. }
  529. if (x is null)
  530. {
  531. return -1;
  532. }
  533. if (y is null)
  534. {
  535. return 1;
  536. }
  537. return string.Compare (x.Id, y.Id);
  538. }
  539. }