Toplevel.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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.Overlapped;
  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. #endregion
  71. #region Life Cycle
  72. // TODO: IRunnable: Re-implement as a property on IRunnable
  73. /// <summary>Gets or sets whether the main loop for this <see cref="Toplevel"/> is running or not.</summary>
  74. /// <remarks>Setting this property directly is discouraged. Use <see cref="Application.RequestStop"/> instead.</remarks>
  75. public bool Running { get; set; }
  76. // TODO: IRunnable: Re-implement in IRunnable
  77. /// <summary>
  78. /// <see langword="true"/> if was already loaded by the <see cref="Application.Begin(Toplevel)"/>
  79. /// <see langword="false"/>, otherwise.
  80. /// </summary>
  81. public bool IsLoaded { get; private set; }
  82. // TODO: IRunnable: Re-implement as an event on IRunnable; IRunnable.Activating/Activate
  83. /// <summary>Invoked when the Toplevel <see cref="RunState"/> active.</summary>
  84. public event EventHandler<ToplevelEventArgs>? Activate;
  85. // TODO: IRunnable: Re-implement as an event on IRunnable; IRunnable.Deactivating/Deactivate?
  86. /// <summary>Invoked when the Toplevel<see cref="RunState"/> ceases to be active.</summary>
  87. public event EventHandler<ToplevelEventArgs>? Deactivate;
  88. /// <summary>Invoked when the Toplevel's <see cref="RunState"/> is closed by <see cref="Application.End(RunState)"/>.</summary>
  89. public event EventHandler<ToplevelEventArgs>? Closed;
  90. /// <summary>
  91. /// Invoked when the Toplevel's <see cref="RunState"/> is being closed by
  92. /// <see cref="Application.RequestStop(Toplevel)"/>.
  93. /// </summary>
  94. public event EventHandler<ToplevelClosingEventArgs>? Closing;
  95. /// <summary>
  96. /// Invoked when the <see cref="Toplevel"/> <see cref="RunState"/> has begun to be loaded. A Loaded event handler
  97. /// is a good place to finalize initialization before calling <see cref="Application.RunLoop(RunState)"/>.
  98. /// </summary>
  99. public event EventHandler? Loaded;
  100. /// <summary>
  101. /// Called from <see cref="Application.Begin(Toplevel)"/> before the <see cref="Toplevel"/> redraws for the first
  102. /// time.
  103. /// </summary>
  104. /// <remarks>
  105. /// Overrides must call base.OnLoaded() to ensure any Toplevel subviews are initialized properly and the
  106. /// <see cref="Loaded"/> event is raised.
  107. /// </remarks>
  108. public virtual void OnLoaded ()
  109. {
  110. IsLoaded = true;
  111. foreach (var view in Subviews.Where (v => v is Toplevel))
  112. {
  113. var tl = (Toplevel)view;
  114. tl.OnLoaded ();
  115. }
  116. Loaded?.Invoke (this, EventArgs.Empty);
  117. }
  118. /// <summary>
  119. /// Invoked when the <see cref="Toplevel"/> main loop has started it's first iteration. Subscribe to this event to
  120. /// perform tasks when the <see cref="Toplevel"/> has been laid out and focus has been set. changes.
  121. /// <para>
  122. /// A Ready event handler is a good place to finalize initialization after calling
  123. /// <see cref="Application.Run(Toplevel, Func{Exception, bool})"/> on this <see cref="Toplevel"/>.
  124. /// </para>
  125. /// </summary>
  126. public event EventHandler? Ready;
  127. /// <summary>
  128. /// Stops and closes this <see cref="Toplevel"/>. If this Toplevel is the top-most Toplevel,
  129. /// <see cref="Application.RequestStop(Toplevel)"/> will be called, causing the application to exit.
  130. /// </summary>
  131. public virtual void RequestStop ()
  132. {
  133. Application.RequestStop (Application.Top);
  134. }
  135. /// <summary>
  136. /// Invoked when the Toplevel <see cref="RunState"/> has been unloaded. A Unloaded event handler is a good place
  137. /// to dispose objects after calling <see cref="Application.End(RunState)"/>.
  138. /// </summary>
  139. public event EventHandler? Unloaded;
  140. internal virtual void OnActivate (Toplevel deactivated) { Activate?.Invoke (this, new (deactivated)); }
  141. internal virtual void OnClosed (Toplevel top) { Closed?.Invoke (this, new (top)); }
  142. internal virtual bool OnClosing (ToplevelClosingEventArgs ev)
  143. {
  144. Closing?.Invoke (this, ev);
  145. return ev.Cancel;
  146. }
  147. internal virtual void OnDeactivate (Toplevel activated) { Deactivate?.Invoke (this, new (activated)); }
  148. /// <summary>
  149. /// Called from <see cref="Application.RunLoop"/> after the <see cref="Toplevel"/> has entered the first iteration
  150. /// of the loop.
  151. /// </summary>
  152. internal virtual void OnReady ()
  153. {
  154. foreach (var view in Subviews.Where (v => v is Toplevel))
  155. {
  156. var tl = (Toplevel)view;
  157. tl.OnReady ();
  158. }
  159. Ready?.Invoke (this, EventArgs.Empty);
  160. }
  161. /// <summary>Called from <see cref="Application.End(RunState)"/> before the <see cref="Toplevel"/> is disposed.</summary>
  162. internal virtual void OnUnloaded ()
  163. {
  164. foreach (var view in Subviews.Where (v => v is Toplevel))
  165. {
  166. var tl = (Toplevel)view;
  167. tl.OnUnloaded ();
  168. }
  169. Unloaded?.Invoke (this, EventArgs.Empty);
  170. }
  171. #endregion
  172. #region Size / Position Management
  173. // TODO: Make cancelable?
  174. internal void OnSizeChanging (SizeChangedEventArgs size) { SizeChanging?.Invoke (this, size); }
  175. /// <summary>
  176. /// Adjusts the location and size of <paramref name="top"/> within this Toplevel. Virtual method enabling
  177. /// implementation of specific positions for inherited <see cref="Toplevel"/> views.
  178. /// </summary>
  179. /// <param name="top">The Toplevel to adjust.</param>
  180. public virtual void PositionToplevel (Toplevel? top)
  181. {
  182. if (top is null)
  183. {
  184. return;
  185. }
  186. View? superView = GetLocationEnsuringFullVisibility (
  187. top,
  188. top.Frame.X,
  189. top.Frame.Y,
  190. out int nx,
  191. out int ny,
  192. out StatusBar? sb
  193. );
  194. if (superView is null)
  195. {
  196. return;
  197. }
  198. var layoutSubviews = false;
  199. var maxWidth = 0;
  200. if (superView.Margin is { } && superView == top.SuperView)
  201. {
  202. maxWidth -= superView.GetAdornmentsThickness ().Left + superView.GetAdornmentsThickness ().Right;
  203. }
  204. // BUGBUG: The && true is a temp hack
  205. if ((superView != top || top?.SuperView is { } || (top != Application.Top && top!.Modal) || (top == Application.Top && top?.SuperView is null))
  206. && (top!.Frame.X + top.Frame.Width > maxWidth || ny > top.Frame.Y))
  207. {
  208. if (top?.X is null or PosAbsolute && top?.Frame.X != nx)
  209. {
  210. top!.X = nx;
  211. layoutSubviews = true;
  212. }
  213. if (top?.Y is null or PosAbsolute && top?.Frame.Y != ny)
  214. {
  215. top!.Y = ny;
  216. layoutSubviews = true;
  217. }
  218. }
  219. // TODO: v2 - This is a hack to get the StatusBar to be positioned correctly.
  220. if (sb != null
  221. && !top!.Subviews.Contains (sb)
  222. && ny + top.Frame.Height != superView.Frame.Height - (sb.Visible ? 1 : 0)
  223. && top.Height is DimFill
  224. && -top.Height.GetAnchor (0) < 1)
  225. {
  226. top.Height = Dim.Fill (sb.Visible ? 1 : 0);
  227. layoutSubviews = true;
  228. }
  229. if (superView.LayoutNeeded || layoutSubviews)
  230. {
  231. superView.LayoutSubviews ();
  232. }
  233. if (LayoutNeeded)
  234. {
  235. LayoutSubviews ();
  236. }
  237. }
  238. /// <summary>Invoked when the terminal has been resized. The new <see cref="Size"/> of the terminal is provided.</summary>
  239. public event EventHandler<SizeChangedEventArgs>? SizeChanging;
  240. #endregion
  241. }
  242. /// <summary>
  243. /// Implements the <see cref="IEqualityComparer{T}"/> for comparing two <see cref="Toplevel"/>s used by
  244. /// <see cref="StackExtensions"/>.
  245. /// </summary>
  246. public class ToplevelEqualityComparer : IEqualityComparer<Toplevel>
  247. {
  248. /// <summary>Determines whether the specified objects are equal.</summary>
  249. /// <param name="x">The first object of type <see cref="Toplevel"/> to compare.</param>
  250. /// <param name="y">The second object of type <see cref="Toplevel"/> to compare.</param>
  251. /// <returns><see langword="true"/> if the specified objects are equal; otherwise, <see langword="false"/>.</returns>
  252. public bool Equals (Toplevel? x, Toplevel? y)
  253. {
  254. if (y is null && x is null)
  255. {
  256. return true;
  257. }
  258. if (x is null || y is null)
  259. {
  260. return false;
  261. }
  262. if (x.Id == y.Id)
  263. {
  264. return true;
  265. }
  266. return false;
  267. }
  268. /// <summary>Returns a hash code for the specified object.</summary>
  269. /// <param name="obj">The <see cref="Toplevel"/> for which a hash code is to be returned.</param>
  270. /// <returns>A hash code for the specified object.</returns>
  271. /// <exception cref="ArgumentNullException">
  272. /// The type of <paramref name="obj"/> is a reference type and
  273. /// <paramref name="obj"/> is <see langword="null"/>.
  274. /// </exception>
  275. public int GetHashCode (Toplevel obj)
  276. {
  277. if (obj is null)
  278. {
  279. throw new ArgumentNullException ();
  280. }
  281. var hCode = 0;
  282. if (int.TryParse (obj.Id, out int result))
  283. {
  284. hCode = result;
  285. }
  286. return hCode.GetHashCode ();
  287. }
  288. }