Toplevel.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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. Application.RequestStop (Application.Top);
  152. }
  153. /// <summary>
  154. /// Invoked when the Toplevel <see cref="RunState"/> has been unloaded. A Unloaded event handler is a good place
  155. /// to dispose objects after calling <see cref="Application.End(RunState)"/>.
  156. /// </summary>
  157. public event EventHandler? Unloaded;
  158. internal virtual void OnActivate (Toplevel deactivated) { Activate?.Invoke (this, new (deactivated)); }
  159. /// <summary>
  160. /// Stops and closes the <see cref="Toplevel"/> specified by <paramref name="top"/>. If <paramref name="top"/> is
  161. /// the top-most Toplevel, <see cref="Application.RequestStop(Toplevel)"/> will be called, causing the application to
  162. /// exit.
  163. /// </summary>
  164. /// <param name="top">The Toplevel to request stop.</param>
  165. public virtual void RequestStop (Toplevel top) { top.RequestStop (); }
  166. internal virtual void OnAllChildClosed () { AllChildClosed?.Invoke (this, EventArgs.Empty); }
  167. internal virtual void OnChildClosed (Toplevel top)
  168. {
  169. ChildClosed?.Invoke (this, new (top));
  170. }
  171. internal virtual void OnChildLoaded (Toplevel top) { ChildLoaded?.Invoke (this, new (top)); }
  172. internal virtual void OnChildUnloaded (Toplevel top) { ChildUnloaded?.Invoke (this, new (top)); }
  173. internal virtual void OnClosed (Toplevel top) { Closed?.Invoke (this, new (top)); }
  174. internal virtual bool OnClosing (ToplevelClosingEventArgs ev)
  175. {
  176. Closing?.Invoke (this, ev);
  177. return ev.Cancel;
  178. }
  179. internal virtual void OnDeactivate (Toplevel activated) { Deactivate?.Invoke (this, new (activated)); }
  180. /// <summary>
  181. /// Called from <see cref="Application.RunLoop"/> after the <see cref="Toplevel"/> has entered the first iteration
  182. /// of the loop.
  183. /// </summary>
  184. internal virtual void OnReady ()
  185. {
  186. foreach (var view in Subviews.Where (v => v is Toplevel))
  187. {
  188. var tl = (Toplevel)view;
  189. tl.OnReady ();
  190. }
  191. Ready?.Invoke (this, EventArgs.Empty);
  192. }
  193. /// <summary>Called from <see cref="Application.End(RunState)"/> before the <see cref="Toplevel"/> is disposed.</summary>
  194. internal virtual void OnUnloaded ()
  195. {
  196. foreach (var view in Subviews.Where (v => v is Toplevel))
  197. {
  198. var tl = (Toplevel)view;
  199. tl.OnUnloaded ();
  200. }
  201. Unloaded?.Invoke (this, EventArgs.Empty);
  202. }
  203. #endregion
  204. #region Draw
  205. /// <inheritdoc/>
  206. public override void OnDrawContent (Rectangle viewport)
  207. {
  208. if (!Visible)
  209. {
  210. return;
  211. }
  212. if (NeedsDisplay || SubViewNeedsDisplay /*|| LayoutNeeded*/)
  213. {
  214. Clear ();
  215. //LayoutSubviews ();
  216. //PositionToplevels ();
  217. // BUGBUG: This appears to be a hack to get ScrollBarViews to render correctly.
  218. foreach (View view in Subviews)
  219. {
  220. if (view.Frame.IntersectsWith (Viewport) && !OutsideTopFrame (this))
  221. {
  222. //view.SetNeedsLayout ();
  223. view.SetNeedsDisplay ();
  224. view.SetSubViewNeedsDisplay ();
  225. }
  226. }
  227. base.OnDrawContent (viewport);
  228. }
  229. }
  230. #endregion
  231. #region Size / Position Management
  232. // TODO: Make cancelable?
  233. internal virtual void OnSizeChanging (SizeChangedEventArgs size) { SizeChanging?.Invoke (this, size); }
  234. /// <summary>
  235. /// Adjusts the location and size of <paramref name="top"/> within this Toplevel. Virtual method enabling
  236. /// implementation of specific positions for inherited <see cref="Toplevel"/> views.
  237. /// </summary>
  238. /// <param name="top">The Toplevel to adjust.</param>
  239. public virtual void PositionToplevel (Toplevel? top)
  240. {
  241. if (top is null)
  242. {
  243. return;
  244. }
  245. View? superView = GetLocationEnsuringFullVisibility (
  246. top,
  247. top.Frame.X,
  248. top.Frame.Y,
  249. out int nx,
  250. out int ny,
  251. out StatusBar? sb
  252. );
  253. if (superView is null)
  254. {
  255. return;
  256. }
  257. var layoutSubviews = false;
  258. var maxWidth = 0;
  259. if (superView.Margin is { } && superView == top.SuperView)
  260. {
  261. maxWidth -= superView.GetAdornmentsThickness ().Left + superView.GetAdornmentsThickness ().Right;
  262. }
  263. // BUGBUG: The && true is a temp hack
  264. if ((superView != top || top?.SuperView is { } || (top != Application.Top && top!.Modal) || (top == Application.Top && top?.SuperView is null))
  265. && (top!.Frame.X + top.Frame.Width > maxWidth || ny > top.Frame.Y))
  266. {
  267. if (top?.X is null or PosAbsolute && top?.Frame.X != nx)
  268. {
  269. top!.X = nx;
  270. layoutSubviews = true;
  271. }
  272. if (top?.Y is null or PosAbsolute && top?.Frame.Y != ny)
  273. {
  274. top!.Y = ny;
  275. layoutSubviews = true;
  276. }
  277. }
  278. // TODO: v2 - This is a hack to get the StatusBar to be positioned correctly.
  279. if (sb != null
  280. && !top!.Subviews.Contains (sb)
  281. && ny + top.Frame.Height != superView.Frame.Height - (sb.Visible ? 1 : 0)
  282. && top.Height is DimFill
  283. && -top.Height.GetAnchor (0) < 1)
  284. {
  285. top.Height = Dim.Fill (sb.Visible ? 1 : 0);
  286. layoutSubviews = true;
  287. }
  288. if (superView.LayoutNeeded || layoutSubviews)
  289. {
  290. superView.LayoutSubviews ();
  291. }
  292. if (LayoutNeeded)
  293. {
  294. LayoutSubviews ();
  295. }
  296. }
  297. /// <summary>Invoked when the terminal has been resized. The new <see cref="Size"/> of the terminal is provided.</summary>
  298. public event EventHandler<SizeChangedEventArgs>? SizeChanging;
  299. private bool OutsideTopFrame (Toplevel top)
  300. {
  301. if (top.Frame.X > Driver.Cols || top.Frame.Y > Driver.Rows)
  302. {
  303. return true;
  304. }
  305. return false;
  306. }
  307. // TODO: v2 - Not sure this is needed anymore.
  308. internal void PositionToplevels ()
  309. {
  310. return;
  311. PositionToplevel (this);
  312. foreach (View top in Subviews)
  313. {
  314. if (top is Toplevel)
  315. {
  316. PositionToplevel ((Toplevel)top);
  317. }
  318. }
  319. }
  320. #endregion
  321. }
  322. /// <summary>
  323. /// Implements the <see cref="IEqualityComparer{T}"/> for comparing two <see cref="Toplevel"/>s used by
  324. /// <see cref="StackExtensions"/>.
  325. /// </summary>
  326. public class ToplevelEqualityComparer : IEqualityComparer<Toplevel>
  327. {
  328. /// <summary>Determines whether the specified objects are equal.</summary>
  329. /// <param name="x">The first object of type <see cref="Toplevel"/> to compare.</param>
  330. /// <param name="y">The second object of type <see cref="Toplevel"/> to compare.</param>
  331. /// <returns><see langword="true"/> if the specified objects are equal; otherwise, <see langword="false"/>.</returns>
  332. public bool Equals (Toplevel? x, Toplevel? y)
  333. {
  334. if (y is null && x is null)
  335. {
  336. return true;
  337. }
  338. if (x is null || y is null)
  339. {
  340. return false;
  341. }
  342. if (x.Id == y.Id)
  343. {
  344. return true;
  345. }
  346. return false;
  347. }
  348. /// <summary>Returns a hash code for the specified object.</summary>
  349. /// <param name="obj">The <see cref="Toplevel"/> for which a hash code is to be returned.</param>
  350. /// <returns>A hash code for the specified object.</returns>
  351. /// <exception cref="ArgumentNullException">
  352. /// The type of <paramref name="obj"/> is a reference type and
  353. /// <paramref name="obj"/> is <see langword="null"/>.
  354. /// </exception>
  355. public int GetHashCode (Toplevel obj)
  356. {
  357. if (obj is null)
  358. {
  359. throw new ArgumentNullException ();
  360. }
  361. var hCode = 0;
  362. if (int.TryParse (obj.Id, out int result))
  363. {
  364. hCode = result;
  365. }
  366. return hCode.GetHashCode ();
  367. }
  368. }
  369. /// <summary>
  370. /// Implements the <see cref="IComparer{T}"/> to sort the <see cref="Toplevel"/> from the
  371. /// <see cref="ApplicationOverlapped.OverlappedChildren"/> if needed.
  372. /// </summary>
  373. public sealed class ToplevelComparer : IComparer<Toplevel>
  374. {
  375. /// <summary>
  376. /// Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the
  377. /// other.
  378. /// </summary>
  379. /// <param name="x">The first object to compare.</param>
  380. /// <param name="y">The second object to compare.</param>
  381. /// <returns>
  382. /// A signed integer that indicates the relative values of <paramref name="x"/> and <paramref name="y"/>, as shown
  383. /// in the following table.Value Meaning Less than zero <paramref name="x"/> is less than <paramref name="y"/>.Zero
  384. /// <paramref name="x"/> equals <paramref name="y"/> .Greater than zero <paramref name="x"/> is greater than
  385. /// <paramref name="y"/>.
  386. /// </returns>
  387. public int Compare (Toplevel? x, Toplevel? y)
  388. {
  389. if (ReferenceEquals (x, y))
  390. {
  391. return 0;
  392. }
  393. if (x is null)
  394. {
  395. return -1;
  396. }
  397. if (y is null)
  398. {
  399. return 1;
  400. }
  401. return string.CompareOrdinal (x.Id, y.Id);
  402. }
  403. }