Toplevel.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. namespace Terminal.Gui.Views;
  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="IApplication.Run(Toplevel, Func{Exception, bool})"/>. They return control to the caller when
  10. /// <see cref="IApplication.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="IApplication.Init"/>.
  15. /// The application Toplevel can be accessed via <see cref="IApplication.TopRunnable"/>. 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="IApplication.Run(Toplevel, Func{Exception, bool})"/>.
  18. /// </para>
  19. /// <para>
  20. /// <b>Phase 2:</b> <see cref="Toplevel"/> now implements <see cref="IRunnable"/> as an adapter pattern for
  21. /// backward compatibility. The lifecycle events (<see cref="Activate"/>, <see cref="Deactivate"/>,
  22. /// <see cref="Closing"/>, <see cref="Closed"/>) are bridged to the new IRunnable events
  23. /// (<see cref="IRunnable.IsModalChanging"/>, <see cref="IRunnable.IsModalChanged"/>,
  24. /// <see cref="IRunnable.IsRunningChanging"/>, <see cref="IRunnable.IsRunningChanged"/>).
  25. /// </para>
  26. /// </remarks>
  27. public partial class Toplevel : View, IRunnable
  28. {
  29. /// <summary>
  30. /// Initializes a new instance of the <see cref="Toplevel"/> class,
  31. /// defaulting to full screen. The <see cref="View.Width"/> and <see cref="View.Height"/> properties will be set to the
  32. /// dimensions of the terminal using <see cref="Dim.Fill(Dim)"/>.
  33. /// </summary>
  34. public Toplevel ()
  35. {
  36. CanFocus = true;
  37. TabStop = TabBehavior.TabGroup;
  38. Arrangement = ViewArrangement.Overlapped;
  39. Width = Dim.Fill ();
  40. Height = Dim.Fill ();
  41. SchemeName = SchemeManager.SchemesToSchemeName (Schemes.Toplevel);
  42. MouseClick += Toplevel_MouseClick;
  43. }
  44. #region Keyboard & Mouse
  45. // TODO: IRunnable: Re-implement - Modal means IRunnable, ViewArrangement.Overlapped where modalView.Z > allOtherViews.Max (v = v.Z), and exclusive key/mouse input.
  46. /// <summary>
  47. /// Determines whether the <see cref="Toplevel"/> is modal or not. If set to <c>false</c> (the default):
  48. /// <list type="bullet">
  49. /// <item>
  50. /// <description><see cref="View.OnKeyDown"/> events will propagate keys upwards.</description>
  51. /// </item>
  52. /// <item>
  53. /// <description>The Toplevel will act as an embedded view (not a modal/pop-up).</description>
  54. /// </item>
  55. /// </list>
  56. /// If set to <c>true</c>:
  57. /// <list type="bullet">
  58. /// <item>
  59. /// <description><see cref="View.OnKeyDown"/> events will NOT propagate keys upwards.</description>
  60. /// </item>
  61. /// <item>
  62. /// <description>The Toplevel will and look like a modal (pop-up) (e.g. see <see cref="Dialog"/>.</description>
  63. /// </item>
  64. /// </list>
  65. /// </summary>
  66. public bool Modal { get; set; }
  67. private void Toplevel_MouseClick (object? sender, MouseEventArgs e) { e.Handled = InvokeCommand (Command.HotKey) == true; }
  68. #endregion
  69. #region SubViews
  70. //// TODO: Deprecate - Any view can host a menubar in v2
  71. ///// <summary>Gets the latest <see cref="MenuBar"/> added into this Toplevel.</summary>
  72. //public MenuBar? MenuBar => (MenuBar?)SubViews?.LastOrDefault (s => s is MenuBar);
  73. #endregion
  74. #region Life Cycle
  75. // TODO: IRunnable: Re-implement as a property on IRunnable
  76. /// <summary>Gets or sets whether the main loop for this <see cref="Toplevel"/> is running or not.</summary>
  77. /// <remarks>Setting this property directly is discouraged. Use <see cref="IApplication.RequestStop()"/> instead.</remarks>
  78. public bool Running { get; set; }
  79. // TODO: Deprecate. Other than a few tests, this is not used anywhere.
  80. /// <summary>
  81. /// <see langword="true"/> if was already loaded by the <see cref="IApplication.Begin(Toplevel)"/>
  82. /// <see langword="false"/>, otherwise.
  83. /// </summary>
  84. public bool IsLoaded { get; private set; }
  85. // TODO: IRunnable: Re-implement as an event on IRunnable; IRunnable.Activating/Activate
  86. /// <summary>Invoked when the Toplevel <see cref="SessionToken"/> active.</summary>
  87. public event EventHandler<ToplevelEventArgs>? Activate;
  88. // TODO: IRunnable: Re-implement as an event on IRunnable; IRunnable.Deactivating/Deactivate?
  89. /// <summary>Invoked when the Toplevel<see cref="SessionToken"/> ceases to be active.</summary>
  90. public event EventHandler<ToplevelEventArgs>? Deactivate;
  91. /// <summary>Invoked when the Toplevel's <see cref="SessionToken"/> is closed by <see cref="IApplication.End(SessionToken)"/>.</summary>
  92. public event EventHandler<ToplevelEventArgs>? Closed;
  93. /// <summary>
  94. /// Invoked when the Toplevel's <see cref="SessionToken"/> is being closed by
  95. /// <see cref="IApplication.RequestStop(Toplevel)"/>.
  96. /// </summary>
  97. public event EventHandler<ToplevelClosingEventArgs>? Closing;
  98. /// <summary>
  99. /// Invoked when the <see cref="Toplevel"/> <see cref="SessionToken"/> has begun to be loaded. A Loaded event handler
  100. /// is a good place to finalize initialization before calling Run.
  101. /// </summary>
  102. public event EventHandler? Loaded;
  103. /// <summary>
  104. /// Called from <see cref="IApplication.Begin(Toplevel)"/> before the <see cref="Toplevel"/> redraws for the first
  105. /// time.
  106. /// </summary>
  107. /// <remarks>
  108. /// Overrides must call base.OnLoaded() to ensure any Toplevel subviews are initialized properly and the
  109. /// <see cref="Loaded"/> event is raised.
  110. /// </remarks>
  111. public virtual void OnLoaded ()
  112. {
  113. IsLoaded = true;
  114. foreach (var view in SubViews.Where (v => v is Toplevel))
  115. {
  116. var tl = (Toplevel)view;
  117. tl.OnLoaded ();
  118. }
  119. Loaded?.Invoke (this, EventArgs.Empty);
  120. }
  121. /// <summary>
  122. /// Invoked when the <see cref="Toplevel"/> main loop has started it's first iteration. Subscribe to this event to
  123. /// perform tasks when the <see cref="Toplevel"/> has been laid out and focus has been set. changes.
  124. /// <para>
  125. /// A Ready event handler is a good place to finalize initialization after calling
  126. /// <see cref="IApplication.Run(Toplevel, Func{Exception, bool})"/> on this <see cref="Toplevel"/>.
  127. /// </para>
  128. /// </summary>
  129. public event EventHandler? Ready;
  130. /// <summary>
  131. /// Stops and closes this <see cref="Toplevel"/>. If this Toplevel is the top-most Toplevel,
  132. /// <see cref="IApplication.RequestStop(Toplevel)"/> will be called, causing the application to exit.
  133. /// </summary>
  134. public virtual void RequestStop ()
  135. {
  136. App?.RequestStop (App?.TopRunnable);
  137. }
  138. /// <summary>
  139. /// Invoked when the Toplevel <see cref="SessionToken"/> has been unloaded. A Unloaded event handler is a good place
  140. /// to dispose objects after calling <see cref="IApplication.End(SessionToken)"/>.
  141. /// </summary>
  142. public event EventHandler? Unloaded;
  143. internal virtual void OnActivate (Toplevel deactivated) { Activate?.Invoke (this, new (deactivated)); }
  144. internal virtual void OnClosed (Toplevel top) { Closed?.Invoke (this, new (top)); }
  145. internal virtual bool OnClosing (ToplevelClosingEventArgs ev)
  146. {
  147. Closing?.Invoke (this, ev);
  148. return ev.Cancel;
  149. }
  150. internal virtual void OnDeactivate (Toplevel activated) { Deactivate?.Invoke (this, new (activated)); }
  151. /// <summary>
  152. /// Called from run loop after the <see cref="Toplevel"/> has entered the first iteration
  153. /// of the loop.
  154. /// </summary>
  155. internal virtual void OnReady ()
  156. {
  157. foreach (var view in SubViews.Where (v => v is Toplevel))
  158. {
  159. var tl = (Toplevel)view;
  160. tl.OnReady ();
  161. }
  162. Ready?.Invoke (this, EventArgs.Empty);
  163. }
  164. /// <summary>Called from <see cref="IApplication.End(SessionToken)"/> before the <see cref="Toplevel"/> is disposed.</summary>
  165. internal virtual void OnUnloaded ()
  166. {
  167. foreach (var view in SubViews.Where (v => v is Toplevel))
  168. {
  169. var tl = (Toplevel)view;
  170. tl.OnUnloaded ();
  171. }
  172. Unloaded?.Invoke (this, EventArgs.Empty);
  173. }
  174. #endregion
  175. #region IRunnable Implementation - Adapter Pattern for Backward Compatibility
  176. /// <inheritdoc/>
  177. bool IRunnable.IsRunning => App?.RunnableSessionStack?.Any (token => token.Runnable == this) ?? false;
  178. /// <inheritdoc/>
  179. bool IRunnable.RaiseIsRunningChanging (bool oldIsRunning, bool newIsRunning)
  180. {
  181. // Bridge to legacy Closing event when stopping
  182. if (!newIsRunning && oldIsRunning)
  183. {
  184. ToplevelClosingEventArgs args = new (this);
  185. if (OnClosing (args))
  186. {
  187. return true; // Canceled
  188. }
  189. }
  190. return false;
  191. }
  192. /// <inheritdoc/>
  193. event EventHandler<CancelEventArgs<bool>>? IRunnable.IsRunningChanging
  194. {
  195. add { }
  196. remove { }
  197. }
  198. /// <inheritdoc/>
  199. void IRunnable.RaiseIsRunningChangedEvent (bool newIsRunning)
  200. {
  201. // Update Running property to maintain backward compatibility
  202. Running = newIsRunning;
  203. // Bridge to legacy events
  204. if (newIsRunning)
  205. {
  206. OnLoaded ();
  207. }
  208. else
  209. {
  210. OnClosed (this);
  211. OnUnloaded ();
  212. }
  213. }
  214. /// <inheritdoc/>
  215. event EventHandler<EventArgs<bool>>? IRunnable.IsRunningChanged
  216. {
  217. add { }
  218. remove { }
  219. }
  220. /// <inheritdoc/>
  221. bool IRunnable.IsModal
  222. {
  223. get
  224. {
  225. if (App is null)
  226. {
  227. return false;
  228. }
  229. // Check if this toplevel is at the top of the RunnableSessionStack
  230. if (App.RunnableSessionStack is { } && App.RunnableSessionStack.TryPeek (out RunnableSessionToken? topToken))
  231. {
  232. return topToken?.Runnable == this;
  233. }
  234. // Fallback: Check if this is the TopRunnable
  235. return App.TopRunnable == this;
  236. }
  237. }
  238. /// <inheritdoc/>
  239. bool IRunnable.RaiseIsModalChanging (bool oldIsModal, bool newIsModal)
  240. {
  241. // No cancellation for modal changes in legacy Toplevel
  242. return false;
  243. }
  244. /// <inheritdoc/>
  245. event EventHandler<CancelEventArgs<bool>>? IRunnable.IsModalChanging
  246. {
  247. add { }
  248. remove { }
  249. }
  250. /// <inheritdoc/>
  251. void IRunnable.RaiseIsModalChangedEvent (bool newIsModal)
  252. {
  253. // Bridge to legacy Activate/Deactivate events
  254. if (newIsModal)
  255. {
  256. OnActivate (App?.TopRunnable as Toplevel ?? this);
  257. }
  258. else
  259. {
  260. OnDeactivate (App?.TopRunnable as Toplevel ?? this);
  261. }
  262. }
  263. /// <inheritdoc/>
  264. event EventHandler<EventArgs<bool>>? IRunnable.IsModalChanged
  265. {
  266. add { }
  267. remove { }
  268. }
  269. #endregion
  270. #region Size / Position Management
  271. // TODO: Make cancelable?
  272. internal void OnSizeChanging (SizeChangedEventArgs size) { SizeChanging?.Invoke (this, size); }
  273. /// <summary>
  274. /// Adjusts the location and size of <paramref name="top"/> within this Toplevel. Virtual method enabling
  275. /// implementation of specific positions for inherited <see cref="Toplevel"/> views.
  276. /// </summary>
  277. /// <param name="top">The Toplevel to adjust.</param>
  278. public virtual void PositionToplevel (Toplevel? top)
  279. {
  280. if (top is null)
  281. {
  282. return;
  283. }
  284. View? superView = GetLocationEnsuringFullVisibility (
  285. top,
  286. top.Frame.X,
  287. top.Frame.Y,
  288. out int nx,
  289. out int ny
  290. //,
  291. // out StatusBar? sb
  292. );
  293. if (superView is null)
  294. {
  295. return;
  296. }
  297. //var layoutSubViews = false;
  298. var maxWidth = 0;
  299. if (superView.Margin is { } && superView == top.SuperView)
  300. {
  301. maxWidth -= superView.GetAdornmentsThickness ().Left + superView.GetAdornmentsThickness ().Right;
  302. }
  303. // BUGBUG: The && true is a temp hack
  304. if ((superView != top || top?.SuperView is { } || (top != App?.TopRunnable && top!.Modal) || (top == App?.TopRunnable && top?.SuperView is null))
  305. && (top!.Frame.X + top.Frame.Width > maxWidth || ny > top.Frame.Y))
  306. {
  307. if (top?.X is null or PosAbsolute && top?.Frame.X != nx)
  308. {
  309. top!.X = nx;
  310. //layoutSubViews = true;
  311. }
  312. if (top?.Y is null or PosAbsolute && top?.Frame.Y != ny)
  313. {
  314. top!.Y = ny;
  315. //layoutSubViews = true;
  316. }
  317. }
  318. //if (superView.IsLayoutNeeded () || layoutSubViews)
  319. //{
  320. // superView.LayoutSubViews ();
  321. //}
  322. //if (IsLayoutNeeded ())
  323. //{
  324. // LayoutSubViews ();
  325. //}
  326. }
  327. /// <summary>Invoked when the terminal has been resized. The new <see cref="Size"/> of the terminal is provided.</summary>
  328. public event EventHandler<SizeChangedEventArgs>? SizeChanging;
  329. #endregion
  330. }
  331. /// <summary>
  332. /// Implements the <see cref="IEqualityComparer{T}"/> for comparing two <see cref="Toplevel"/>s used by
  333. /// <see cref="StackExtensions"/>.
  334. /// </summary>
  335. public class ToplevelEqualityComparer : IEqualityComparer<Toplevel>
  336. {
  337. /// <summary>Determines whether the specified objects are equal.</summary>
  338. /// <param name="x">The first object of type <see cref="Toplevel"/> to compare.</param>
  339. /// <param name="y">The second object of type <see cref="Toplevel"/> to compare.</param>
  340. /// <returns><see langword="true"/> if the specified objects are equal; otherwise, <see langword="false"/>.</returns>
  341. public bool Equals (Toplevel? x, Toplevel? y)
  342. {
  343. if (y is null && x is null)
  344. {
  345. return true;
  346. }
  347. if (x is null || y is null)
  348. {
  349. return false;
  350. }
  351. if (x.Id == y.Id)
  352. {
  353. return true;
  354. }
  355. return false;
  356. }
  357. /// <summary>Returns a hash code for the specified object.</summary>
  358. /// <param name="obj">The <see cref="Toplevel"/> for which a hash code is to be returned.</param>
  359. /// <returns>A hash code for the specified object.</returns>
  360. /// <exception cref="ArgumentNullException">
  361. /// The type of <paramref name="obj"/> is a reference type and
  362. /// <paramref name="obj"/> is <see langword="null"/>.
  363. /// </exception>
  364. public int GetHashCode (Toplevel obj)
  365. {
  366. if (obj is null)
  367. {
  368. throw new ArgumentNullException ();
  369. }
  370. var hCode = 0;
  371. if (int.TryParse (obj.Id, out int result))
  372. {
  373. hCode = result;
  374. }
  375. return hCode.GetHashCode ();
  376. }
  377. }