Toplevel.cs 21 KB

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