Toplevel.cs 21 KB

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