Toplevel.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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.Current"/>. 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. /// </remarks>
  20. public partial class Toplevel : View
  21. {
  22. /// <summary>
  23. /// Initializes a new instance of the <see cref="Toplevel"/> class,
  24. /// defaulting to full screen. The <see cref="View.Width"/> and <see cref="View.Height"/> properties will be set to the
  25. /// dimensions of the terminal using <see cref="Dim.Fill(Dim)"/>.
  26. /// </summary>
  27. public Toplevel ()
  28. {
  29. CanFocus = true;
  30. TabStop = TabBehavior.TabGroup;
  31. Arrangement = ViewArrangement.Overlapped;
  32. Width = Dim.Fill ();
  33. Height = Dim.Fill ();
  34. SchemeName = SchemeManager.SchemesToSchemeName (Schemes.Toplevel);
  35. MouseClick += Toplevel_MouseClick;
  36. }
  37. #region Keyboard & Mouse
  38. // TODO: IRunnable: Re-implement - Modal means IRunnable, ViewArrangement.Overlapped where modalView.Z > allOtherViews.Max (v = v.Z), and exclusive key/mouse input.
  39. /// <summary>
  40. /// Determines whether the <see cref="Toplevel"/> is modal or not. If set to <c>false</c> (the default):
  41. /// <list type="bullet">
  42. /// <item>
  43. /// <description><see cref="View.OnKeyDown"/> events will propagate keys upwards.</description>
  44. /// </item>
  45. /// <item>
  46. /// <description>The Toplevel will act as an embedded view (not a modal/pop-up).</description>
  47. /// </item>
  48. /// </list>
  49. /// If set to <c>true</c>:
  50. /// <list type="bullet">
  51. /// <item>
  52. /// <description><see cref="View.OnKeyDown"/> events will NOT propagate keys upwards.</description>
  53. /// </item>
  54. /// <item>
  55. /// <description>The Toplevel will and look like a modal (pop-up) (e.g. see <see cref="Dialog"/>.</description>
  56. /// </item>
  57. /// </list>
  58. /// </summary>
  59. public bool Modal { get; set; }
  60. private void Toplevel_MouseClick (object? sender, MouseEventArgs e) { e.Handled = InvokeCommand (Command.HotKey) == true; }
  61. #endregion
  62. #region SubViews
  63. // TODO: Deprecate - Any view can host a menubar in v2
  64. /// <summary>Gets the latest <see cref="MenuBar"/> added into this Toplevel.</summary>
  65. public MenuBar? MenuBar => (MenuBar?)SubViews?.LastOrDefault (s => s is MenuBar);
  66. //// TODO: Deprecate - Any view can host a statusbar in v2
  67. ///// <summary>Gets the latest <see cref="StatusBar"/> added into this Toplevel.</summary>
  68. //public StatusBar? StatusBar => (StatusBar?)SubViews?.LastOrDefault (s => s is StatusBar);
  69. #endregion
  70. #region Life Cycle
  71. // TODO: IRunnable: Re-implement as a property on IRunnable
  72. /// <summary>Gets or sets whether the main loop for this <see cref="Toplevel"/> is running or not.</summary>
  73. /// <remarks>Setting this property directly is discouraged. Use <see cref="IApplication.RequestStop()"/> instead.</remarks>
  74. public bool Running { get; set; }
  75. // TODO: IRunnable: Re-implement in IRunnable
  76. /// <summary>
  77. /// <see langword="true"/> if was already loaded by the <see cref="IApplication.Begin(Toplevel)"/>
  78. /// <see langword="false"/>, otherwise.
  79. /// </summary>
  80. public bool IsLoaded { get; private set; }
  81. // TODO: IRunnable: Re-implement as an event on IRunnable; IRunnable.Activating/Activate
  82. /// <summary>Invoked when the Toplevel <see cref="SessionToken"/> active.</summary>
  83. public event EventHandler<ToplevelEventArgs>? Activate;
  84. // TODO: IRunnable: Re-implement as an event on IRunnable; IRunnable.Deactivating/Deactivate?
  85. /// <summary>Invoked when the Toplevel<see cref="SessionToken"/> ceases to be active.</summary>
  86. public event EventHandler<ToplevelEventArgs>? Deactivate;
  87. /// <summary>Invoked when the Toplevel's <see cref="SessionToken"/> is closed by <see cref="IApplication.End(SessionToken)"/>.</summary>
  88. public event EventHandler<ToplevelEventArgs>? Closed;
  89. /// <summary>
  90. /// Invoked when the Toplevel's <see cref="SessionToken"/> is being closed by
  91. /// <see cref="IApplication.RequestStop(Toplevel)"/>.
  92. /// </summary>
  93. public event EventHandler<ToplevelClosingEventArgs>? Closing;
  94. /// <summary>
  95. /// Invoked when the <see cref="Toplevel"/> <see cref="SessionToken"/> has begun to be loaded. A Loaded event handler
  96. /// is a good place to finalize initialization before calling Run.
  97. /// </summary>
  98. public event EventHandler? Loaded;
  99. /// <summary>
  100. /// Called from <see cref="IApplication.Begin(Toplevel)"/> before the <see cref="Toplevel"/> redraws for the first
  101. /// time.
  102. /// </summary>
  103. /// <remarks>
  104. /// Overrides must call base.OnLoaded() to ensure any Toplevel subviews are initialized properly and the
  105. /// <see cref="Loaded"/> event is raised.
  106. /// </remarks>
  107. public virtual void OnLoaded ()
  108. {
  109. IsLoaded = true;
  110. foreach (var view in SubViews.Where (v => v is Toplevel))
  111. {
  112. var tl = (Toplevel)view;
  113. tl.OnLoaded ();
  114. }
  115. Loaded?.Invoke (this, EventArgs.Empty);
  116. }
  117. /// <summary>
  118. /// Invoked when the <see cref="Toplevel"/> main loop has started it's first iteration. Subscribe to this event to
  119. /// perform tasks when the <see cref="Toplevel"/> has been laid out and focus has been set. changes.
  120. /// <para>
  121. /// A Ready event handler is a good place to finalize initialization after calling
  122. /// <see cref="IApplication.Run(Toplevel, Func{Exception, bool})"/> on this <see cref="Toplevel"/>.
  123. /// </para>
  124. /// </summary>
  125. public event EventHandler? Ready;
  126. /// <summary>
  127. /// Stops and closes this <see cref="Toplevel"/>. If this Toplevel is the top-most Toplevel,
  128. /// <see cref="IApplication.RequestStop(Toplevel)"/> will be called, causing the application to exit.
  129. /// </summary>
  130. public virtual void RequestStop ()
  131. {
  132. App?.RequestStop (App?.Current);
  133. }
  134. /// <summary>
  135. /// Invoked when the Toplevel <see cref="SessionToken"/> has been unloaded. A Unloaded event handler is a good place
  136. /// to dispose objects after calling <see cref="IApplication.End(SessionToken)"/>.
  137. /// </summary>
  138. public event EventHandler? Unloaded;
  139. internal virtual void OnActivate (Toplevel deactivated) { Activate?.Invoke (this, new (deactivated)); }
  140. internal virtual void OnClosed (Toplevel top) { Closed?.Invoke (this, new (top)); }
  141. internal virtual bool OnClosing (ToplevelClosingEventArgs ev)
  142. {
  143. Closing?.Invoke (this, ev);
  144. return ev.Cancel;
  145. }
  146. internal virtual void OnDeactivate (Toplevel activated) { Deactivate?.Invoke (this, new (activated)); }
  147. /// <summary>
  148. /// Called from run loop after the <see cref="Toplevel"/> has entered the first iteration
  149. /// of the loop.
  150. /// </summary>
  151. internal virtual void OnReady ()
  152. {
  153. foreach (var view in SubViews.Where (v => v is Toplevel))
  154. {
  155. var tl = (Toplevel)view;
  156. tl.OnReady ();
  157. }
  158. Ready?.Invoke (this, EventArgs.Empty);
  159. }
  160. /// <summary>Called from <see cref="IApplication.End(SessionToken)"/> before the <see cref="Toplevel"/> is disposed.</summary>
  161. internal virtual void OnUnloaded ()
  162. {
  163. foreach (var view in SubViews.Where (v => v is Toplevel))
  164. {
  165. var tl = (Toplevel)view;
  166. tl.OnUnloaded ();
  167. }
  168. Unloaded?.Invoke (this, EventArgs.Empty);
  169. }
  170. #endregion
  171. #region Size / Position Management
  172. // TODO: Make cancelable?
  173. internal void OnSizeChanging (SizeChangedEventArgs size) { SizeChanging?.Invoke (this, size); }
  174. /// <summary>
  175. /// Adjusts the location and size of <paramref name="top"/> within this Toplevel. Virtual method enabling
  176. /// implementation of specific positions for inherited <see cref="Toplevel"/> views.
  177. /// </summary>
  178. /// <param name="top">The Toplevel to adjust.</param>
  179. public virtual void PositionToplevel (Toplevel? top)
  180. {
  181. if (top is null)
  182. {
  183. return;
  184. }
  185. View? superView = GetLocationEnsuringFullVisibility (
  186. top,
  187. top.Frame.X,
  188. top.Frame.Y,
  189. out int nx,
  190. out int ny
  191. //,
  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 != App?.Current && top!.Modal) || (top == App?.Current && 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. //if (superView.IsLayoutNeeded () || layoutSubViews)
  220. //{
  221. // superView.LayoutSubViews ();
  222. //}
  223. //if (IsLayoutNeeded ())
  224. //{
  225. // LayoutSubViews ();
  226. //}
  227. }
  228. /// <summary>Invoked when the terminal has been resized. The new <see cref="Size"/> of the terminal is provided.</summary>
  229. public event EventHandler<SizeChangedEventArgs>? SizeChanging;
  230. #endregion
  231. }
  232. /// <summary>
  233. /// Implements the <see cref="IEqualityComparer{T}"/> for comparing two <see cref="Toplevel"/>s used by
  234. /// <see cref="StackExtensions"/>.
  235. /// </summary>
  236. public class ToplevelEqualityComparer : IEqualityComparer<Toplevel>
  237. {
  238. /// <summary>Determines whether the specified objects are equal.</summary>
  239. /// <param name="x">The first object of type <see cref="Toplevel"/> to compare.</param>
  240. /// <param name="y">The second object of type <see cref="Toplevel"/> to compare.</param>
  241. /// <returns><see langword="true"/> if the specified objects are equal; otherwise, <see langword="false"/>.</returns>
  242. public bool Equals (Toplevel? x, Toplevel? y)
  243. {
  244. if (y is null && x is null)
  245. {
  246. return true;
  247. }
  248. if (x is null || y is null)
  249. {
  250. return false;
  251. }
  252. if (x.Id == y.Id)
  253. {
  254. return true;
  255. }
  256. return false;
  257. }
  258. /// <summary>Returns a hash code for the specified object.</summary>
  259. /// <param name="obj">The <see cref="Toplevel"/> for which a hash code is to be returned.</param>
  260. /// <returns>A hash code for the specified object.</returns>
  261. /// <exception cref="ArgumentNullException">
  262. /// The type of <paramref name="obj"/> is a reference type and
  263. /// <paramref name="obj"/> is <see langword="null"/>.
  264. /// </exception>
  265. public int GetHashCode (Toplevel obj)
  266. {
  267. if (obj is null)
  268. {
  269. throw new ArgumentNullException ();
  270. }
  271. var hCode = 0;
  272. if (int.TryParse (obj.Id, out int result))
  273. {
  274. hCode = result;
  275. }
  276. return hCode.GetHashCode ();
  277. }
  278. }