Toplevel.cs 21 KB

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