Toplevel.cs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182
  1. using System.Net.Mime;
  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. /// Toplevels 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. internal static Point? _dragPosition;
  24. private Point _startGrabPoint;
  25. /// <summary>
  26. /// Initializes a new instance of the <see cref="Toplevel"/> class with <see cref="LayoutStyle.Computed"/> layout,
  27. /// defaulting to full screen. The <see cref="View.Width"/> and <see cref="View.Height"/> properties will be set to the
  28. /// dimensions of the terminal using <see cref="Dim.Fill"/>.
  29. /// </summary>
  30. public Toplevel ()
  31. {
  32. Width = Dim.Fill ();
  33. Height = Dim.Fill ();
  34. ColorScheme = Colors.ColorSchemes ["TopLevel"];
  35. Application.GrabbingMouse += Application_GrabbingMouse;
  36. Application.UnGrabbingMouse += Application_UnGrabbingMouse;
  37. // TODO: v2 - ALL Views (Responders??!?!) should support the commands related to
  38. // - Focus
  39. // Move the appropriate AddCommand calls to `Responder`
  40. // Things this view knows how to do
  41. AddCommand (
  42. Command.QuitToplevel,
  43. () =>
  44. {
  45. QuitToplevel ();
  46. return true;
  47. }
  48. );
  49. AddCommand (
  50. Command.Suspend,
  51. () =>
  52. {
  53. Driver.Suspend ();
  54. ;
  55. return true;
  56. }
  57. );
  58. AddCommand (
  59. Command.NextView,
  60. () =>
  61. {
  62. MoveNextView ();
  63. return true;
  64. }
  65. );
  66. AddCommand (
  67. Command.PreviousView,
  68. () =>
  69. {
  70. MovePreviousView ();
  71. return true;
  72. }
  73. );
  74. AddCommand (
  75. Command.NextViewOrTop,
  76. () =>
  77. {
  78. MoveNextViewOrTop ();
  79. return true;
  80. }
  81. );
  82. AddCommand (
  83. Command.PreviousViewOrTop,
  84. () =>
  85. {
  86. MovePreviousViewOrTop ();
  87. return true;
  88. }
  89. );
  90. AddCommand (
  91. Command.Refresh,
  92. () =>
  93. {
  94. Application.Refresh ();
  95. return true;
  96. }
  97. );
  98. // Default keybindings for this view
  99. KeyBindings.Add (Application.QuitKey, Command.QuitToplevel);
  100. KeyBindings.Add (Key.CursorRight, Command.NextView);
  101. KeyBindings.Add (Key.CursorDown, Command.NextView);
  102. KeyBindings.Add (Key.CursorLeft, Command.PreviousView);
  103. KeyBindings.Add (Key.CursorUp, Command.PreviousView);
  104. KeyBindings.Add (Key.Tab, Command.NextView);
  105. KeyBindings.Add (Key.Tab.WithShift, Command.PreviousView);
  106. KeyBindings.Add (Key.Tab.WithCtrl, Command.NextViewOrTop);
  107. KeyBindings.Add (Key.Tab.WithShift.WithCtrl, Command.PreviousViewOrTop);
  108. KeyBindings.Add (Key.F5, Command.Refresh);
  109. KeyBindings.Add (Application.AlternateForwardKey, Command.NextViewOrTop); // Needed on Unix
  110. KeyBindings.Add (Application.AlternateBackwardKey, Command.PreviousViewOrTop); // Needed on Unix
  111. #if UNIX_KEY_BINDINGS
  112. KeyBindings.Add (Key.Z.WithCtrl, Command.Suspend);
  113. KeyBindings.Add (Key.L.WithCtrl, Command.Refresh); // Unix
  114. KeyBindings.Add (Key.F.WithCtrl, Command.NextView); // Unix
  115. KeyBindings.Add (Key.I.WithCtrl, Command.NextView); // Unix
  116. KeyBindings.Add (Key.B.WithCtrl, Command.PreviousView); // Unix
  117. #endif
  118. }
  119. /// <summary>Gets or sets a value indicating whether this <see cref="Toplevel"/> can focus.</summary>
  120. /// <value><c>true</c> if can focus; otherwise, <c>false</c>.</value>
  121. public override bool CanFocus => SuperView is null ? true : base.CanFocus;
  122. /// <summary>
  123. /// <see langword="true"/> if was already loaded by the <see cref="Application.Begin(Toplevel)"/>
  124. /// <see langword="false"/>, otherwise.
  125. /// </summary>
  126. public bool IsLoaded { get; private set; }
  127. /// <summary>Gets or sets the menu for this Toplevel.</summary>
  128. public virtual MenuBar MenuBar { get; set; }
  129. /// <summary>
  130. /// Determines whether the <see cref="Toplevel"/> is modal or not. If set to <c>false</c> (the default):
  131. /// <list type="bullet">
  132. /// <item>
  133. /// <description><see cref="View.OnKeyDown"/> events will propagate keys upwards.</description>
  134. /// </item>
  135. /// <item>
  136. /// <description>The Toplevel will act as an embedded view (not a modal/pop-up).</description>
  137. /// </item>
  138. /// </list>
  139. /// If set to <c>true</c>:
  140. /// <list type="bullet">
  141. /// <item>
  142. /// <description><see cref="View.OnKeyDown"/> events will NOT propagate keys upwards.</description>
  143. /// </item>
  144. /// <item>
  145. /// <description>The Toplevel will and look like a modal (pop-up) (e.g. see <see cref="Dialog"/>.</description>
  146. /// </item>
  147. /// </list>
  148. /// </summary>
  149. public bool Modal { get; set; }
  150. /// <summary>Gets or sets whether the main loop for this <see cref="Toplevel"/> is running or not.</summary>
  151. /// <remarks>Setting this property directly is discouraged. Use <see cref="Application.RequestStop"/> instead.</remarks>
  152. public bool Running { get; set; }
  153. /// <summary>Gets or sets the status bar for this Toplevel.</summary>
  154. public virtual StatusBar StatusBar { get; set; }
  155. /// <summary>Invoked when the Toplevel <see cref="RunState"/> becomes the <see cref="Application.Current"/> Toplevel.</summary>
  156. public event EventHandler<ToplevelEventArgs> Activate;
  157. /// <inheritdoc/>
  158. public override void Add (View view)
  159. {
  160. CanFocus = true;
  161. AddMenuStatusBar (view);
  162. base.Add (view);
  163. }
  164. /// <summary>
  165. /// Invoked when the last child of the Toplevel <see cref="RunState"/> is closed from by
  166. /// <see cref="Application.End(RunState)"/>.
  167. /// </summary>
  168. public event EventHandler AllChildClosed;
  169. /// <summary>Invoked when the <see cref="Application.AlternateBackwardKey"/> is changed.</summary>
  170. public event EventHandler<KeyChangedEventArgs> AlternateBackwardKeyChanged;
  171. /// <summary>Invoked when the <see cref="Application.AlternateForwardKey"/> is changed.</summary>
  172. public event EventHandler<KeyChangedEventArgs> AlternateForwardKeyChanged;
  173. /// <summary>
  174. /// Invoked when a child of the Toplevel <see cref="RunState"/> is closed by
  175. /// <see cref="Application.End(RunState)"/>.
  176. /// </summary>
  177. public event EventHandler<ToplevelEventArgs> ChildClosed;
  178. /// <summary>Invoked when a child Toplevel's <see cref="RunState"/> has been loaded.</summary>
  179. public event EventHandler<ToplevelEventArgs> ChildLoaded;
  180. /// <summary>Invoked when a cjhild Toplevel's <see cref="RunState"/> has been unloaded.</summary>
  181. public event EventHandler<ToplevelEventArgs> ChildUnloaded;
  182. /// <summary>Invoked when the Toplevel's <see cref="RunState"/> is closed by <see cref="Application.End(RunState)"/>.</summary>
  183. public event EventHandler<ToplevelEventArgs> Closed;
  184. /// <summary>
  185. /// Invoked when the Toplevel's <see cref="RunState"/> is being closed by
  186. /// <see cref="Application.RequestStop(Toplevel)"/>.
  187. /// </summary>
  188. public event EventHandler<ToplevelClosingEventArgs> Closing;
  189. /// <summary>Invoked when the Toplevel<see cref="RunState"/> ceases to be the <see cref="Application.Current"/> Toplevel.</summary>
  190. public event EventHandler<ToplevelEventArgs> Deactivate;
  191. /// <summary>
  192. /// Invoked when the <see cref="Toplevel"/> <see cref="RunState"/> has begun to be loaded. A Loaded event handler
  193. /// is a good place to finalize initialization before calling <see cref="Application.RunLoop(RunState)"/>.
  194. /// </summary>
  195. public event EventHandler Loaded;
  196. /// <inheritdoc/>
  197. protected internal override bool OnMouseEvent (MouseEvent mouseEvent)
  198. {
  199. if (!CanFocus)
  200. {
  201. return true;
  202. }
  203. //System.Diagnostics.Debug.WriteLine ($"dragPosition before: {dragPosition.HasValue}");
  204. int nx, ny;
  205. if (!_dragPosition.HasValue
  206. && (mouseEvent.Flags == MouseFlags.Button1Pressed
  207. || mouseEvent.Flags == MouseFlags.Button2Pressed
  208. || mouseEvent.Flags == MouseFlags.Button3Pressed))
  209. {
  210. SetFocus ();
  211. Application.BringOverlappedTopToFront ();
  212. // Only start grabbing if the user clicks on the title bar.
  213. // BUGBUG: Assumes Frame == Border and Title is always at Y == 0
  214. if (mouseEvent.Y == 0 && mouseEvent.Flags == MouseFlags.Button1Pressed)
  215. {
  216. _startGrabPoint = new Point (mouseEvent.X, mouseEvent.Y);
  217. _dragPosition = Point.Empty;
  218. nx = mouseEvent.X - mouseEvent.OfX;
  219. ny = mouseEvent.Y - mouseEvent.OfY;
  220. _dragPosition = new Point (nx, ny);
  221. Application.GrabMouse (this);
  222. }
  223. //System.Diagnostics.Debug.WriteLine ($"Starting at {dragPosition}");
  224. return true;
  225. }
  226. if (mouseEvent.Flags == (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) || mouseEvent.Flags == MouseFlags.Button3Pressed)
  227. {
  228. if (_dragPosition.HasValue)
  229. {
  230. if (SuperView is null)
  231. {
  232. // Redraw the entire app window using just our Frame. Since we are
  233. // Application.Top, and our Frame always == our Bounds (Location is always (0,0))
  234. // our Frame is actually view-relative (which is what Redraw takes).
  235. // We need to pass all the view bounds because since the windows was
  236. // moved around, we don't know exactly what was the affected region.
  237. Application.Top.SetNeedsDisplay ();
  238. }
  239. else
  240. {
  241. SuperView.SetNeedsDisplay ();
  242. }
  243. // BUGBUG: Assumes Frame == Border?
  244. GetLocationThatFits (
  245. this,
  246. mouseEvent.X
  247. + (SuperView == null
  248. ? mouseEvent.OfX - _startGrabPoint.X
  249. : Frame.X - _startGrabPoint.X),
  250. mouseEvent.Y
  251. + (SuperView == null
  252. ? mouseEvent.OfY - _startGrabPoint.Y
  253. : Frame.Y - _startGrabPoint.Y),
  254. out nx,
  255. out ny,
  256. out _,
  257. out _
  258. );
  259. _dragPosition = new Point (nx, ny);
  260. X = nx;
  261. Y = ny;
  262. //System.Diagnostics.Debug.WriteLine ($"Drag: nx:{nx},ny:{ny}");
  263. SetNeedsDisplay ();
  264. return true;
  265. }
  266. }
  267. if (mouseEvent.Flags.HasFlag (MouseFlags.Button1Released) && _dragPosition.HasValue)
  268. {
  269. _dragPosition = null;
  270. Application.UngrabMouse ();
  271. }
  272. //System.Diagnostics.Debug.WriteLine ($"dragPosition after: {dragPosition.HasValue}");
  273. //System.Diagnostics.Debug.WriteLine ($"Toplevel: {mouseEvent}");
  274. return false;
  275. }
  276. /// <summary>Virtual method to invoke the <see cref="AlternateBackwardKeyChanged"/> event.</summary>
  277. /// <param name="e"></param>
  278. public virtual void OnAlternateBackwardKeyChanged (KeyChangedEventArgs e)
  279. {
  280. KeyBindings.Replace (e.OldKey, e.NewKey);
  281. AlternateBackwardKeyChanged?.Invoke (this, e);
  282. }
  283. /// <summary>Virtual method to invoke the <see cref="AlternateForwardKeyChanged"/> event.</summary>
  284. /// <param name="e"></param>
  285. public virtual void OnAlternateForwardKeyChanged (KeyChangedEventArgs e)
  286. {
  287. KeyBindings.Replace (e.OldKey, e.NewKey);
  288. AlternateForwardKeyChanged?.Invoke (this, e);
  289. }
  290. /// <inheritdoc/>
  291. public override void OnDrawContent (Rectangle contentArea)
  292. {
  293. if (!Visible)
  294. {
  295. return;
  296. }
  297. if (NeedsDisplay || SubViewNeedsDisplay || LayoutNeeded)
  298. {
  299. //Driver.SetAttribute (GetNormalColor ());
  300. // TODO: It's bad practice for views to always clear. Defeats the purpose of clipping etc...
  301. Clear ();
  302. LayoutSubviews ();
  303. PositionToplevels ();
  304. if (this == Application.OverlappedTop)
  305. {
  306. foreach (Toplevel top in Application.OverlappedChildren.AsEnumerable ().Reverse ())
  307. {
  308. if (top.Frame.IntersectsWith (Bounds))
  309. {
  310. if (top != this && !top.IsCurrentTop && !OutsideTopFrame (top) && top.Visible)
  311. {
  312. top.SetNeedsLayout ();
  313. top.SetNeedsDisplay (top.Bounds);
  314. top.Draw ();
  315. top.OnRenderLineCanvas ();
  316. }
  317. }
  318. }
  319. }
  320. // This should not be here, but in base
  321. foreach (View view in Subviews)
  322. {
  323. if (view.Frame.IntersectsWith (Bounds) && !OutsideTopFrame (this))
  324. {
  325. //view.SetNeedsLayout ();
  326. view.SetNeedsDisplay (view.Bounds);
  327. view.SetSubViewNeedsDisplay ();
  328. }
  329. }
  330. base.OnDrawContent (contentArea);
  331. // This is causing the menus drawn incorrectly if UseSubMenusSingleFrame is true
  332. //if (this.MenuBar is { } && this.MenuBar.IsMenuOpen && this.MenuBar.openMenu is { }) {
  333. // // TODO: Hack until we can get compositing working right.
  334. // this.MenuBar.openMenu.Redraw (this.MenuBar.openMenu.Bounds);
  335. //}
  336. }
  337. }
  338. /// <inheritdoc/>
  339. public override bool OnEnter (View view) { return MostFocused?.OnEnter (view) ?? base.OnEnter (view); }
  340. /// <inheritdoc/>
  341. public override bool OnLeave (View view) { return MostFocused?.OnLeave (view) ?? base.OnLeave (view); }
  342. /// <summary>
  343. /// Called from <see cref="Application.Begin(Toplevel)"/> before the <see cref="Toplevel"/> redraws for the first
  344. /// time.
  345. /// </summary>
  346. public virtual void OnLoaded ()
  347. {
  348. IsLoaded = true;
  349. foreach (Toplevel tl in Subviews.Where (v => v is Toplevel))
  350. {
  351. tl.OnLoaded ();
  352. }
  353. Loaded?.Invoke (this, EventArgs.Empty);
  354. }
  355. /// <summary>Virtual method to invoke the <see cref="QuitKeyChanged"/> event.</summary>
  356. /// <param name="e"></param>
  357. public virtual void OnQuitKeyChanged (KeyChangedEventArgs e)
  358. {
  359. KeyBindings.Replace (e.OldKey, e.NewKey);
  360. QuitKeyChanged?.Invoke (this, e);
  361. }
  362. /// <inheritdoc/>
  363. public override void PositionCursor ()
  364. {
  365. if (!IsOverlappedContainer)
  366. {
  367. base.PositionCursor ();
  368. if (Focused is null)
  369. {
  370. EnsureFocus ();
  371. if (Focused is null)
  372. {
  373. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  374. }
  375. }
  376. return;
  377. }
  378. if (Focused is null)
  379. {
  380. foreach (Toplevel top in Application.OverlappedChildren)
  381. {
  382. if (top != this && top.Visible)
  383. {
  384. top.SetFocus ();
  385. return;
  386. }
  387. }
  388. }
  389. base.PositionCursor ();
  390. if (Focused is null)
  391. {
  392. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  393. }
  394. }
  395. /// <summary>
  396. /// Adjusts the location and size of <paramref name="top"/> within this Toplevel. Virtual method enabling
  397. /// implementation of specific positions for inherited <see cref="Toplevel"/> views.
  398. /// </summary>
  399. /// <param name="top">The Toplevel to adjust.</param>
  400. public virtual void PositionToplevel (Toplevel top)
  401. {
  402. View superView = GetLocationThatFits (
  403. top,
  404. top.Frame.X,
  405. top.Frame.Y,
  406. out int nx,
  407. out int ny,
  408. out _,
  409. out StatusBar sb
  410. );
  411. var layoutSubviews = false;
  412. var maxWidth = 0;
  413. if (superView.Margin is { } && superView == top.SuperView)
  414. {
  415. maxWidth -= superView.GetAdornmentsThickness ().Left + superView.GetAdornmentsThickness ().Right;
  416. }
  417. if ((superView != top || top?.SuperView is { } || (top != Application.Top && top.Modal) || (top?.SuperView is null && top.IsOverlapped))
  418. // BUGBUG: Prevously PositionToplevel required LayotuStyle.Computed
  419. && (top.Frame.X + top.Frame.Width > maxWidth || ny > top.Frame.Y) /*&& top.LayoutStyle == LayoutStyle.Computed*/)
  420. {
  421. if ((top.X is null || top.X is Pos.PosAbsolute) && top.Frame.X != nx)
  422. {
  423. top.X = nx;
  424. layoutSubviews = true;
  425. }
  426. if ((top.Y is null || top.Y is Pos.PosAbsolute) && top.Frame.Y != ny)
  427. {
  428. top.Y = ny;
  429. layoutSubviews = true;
  430. }
  431. }
  432. // TODO: v2 - This is a hack to get the StatusBar to be positioned correctly.
  433. if (sb != null
  434. && !top.Subviews.Contains (sb)
  435. && ny + top.Frame.Height != superView.Frame.Height - (sb.Visible ? 1 : 0)
  436. && top.Height is Dim.DimFill
  437. && -top.Height.Anchor (0) < 1)
  438. {
  439. top.Height = Dim.Fill (sb.Visible ? 1 : 0);
  440. layoutSubviews = true;
  441. }
  442. if (superView.LayoutNeeded || layoutSubviews)
  443. {
  444. superView.LayoutSubviews ();
  445. }
  446. if (LayoutNeeded)
  447. {
  448. LayoutSubviews ();
  449. }
  450. }
  451. /// <summary>Invoked when the <see cref="Application.QuitKey"/> is changed.</summary>
  452. public event EventHandler<KeyChangedEventArgs> QuitKeyChanged;
  453. /// <summary>
  454. /// Invoked when the <see cref="Toplevel"/> main loop has started it's first iteration. Subscribe to this event to
  455. /// perform tasks when the <see cref="Toplevel"/> has been laid out and focus has been set. changes.
  456. /// <para>
  457. /// A Ready event handler is a good place to finalize initialization after calling
  458. /// <see cref="Application.Run(Func{Exception, bool})"/> on this <see cref="Toplevel"/>.
  459. /// </para>
  460. /// </summary>
  461. public event EventHandler Ready;
  462. /// <inheritdoc/>
  463. public override void Remove (View view)
  464. {
  465. if (this is Toplevel Toplevel && Toplevel.MenuBar is { })
  466. {
  467. RemoveMenuStatusBar (view);
  468. }
  469. base.Remove (view);
  470. }
  471. /// <inheritdoc/>
  472. public override void RemoveAll ()
  473. {
  474. if (this == Application.Top)
  475. {
  476. MenuBar?.Dispose ();
  477. MenuBar = null;
  478. StatusBar?.Dispose ();
  479. StatusBar = null;
  480. }
  481. base.RemoveAll ();
  482. }
  483. /// <summary>
  484. /// Stops and closes this <see cref="Toplevel"/>. If this Toplevel is the top-most Toplevel,
  485. /// <see cref="Application.RequestStop(Toplevel)"/> will be called, causing the application to exit.
  486. /// </summary>
  487. public virtual void RequestStop ()
  488. {
  489. if (IsOverlappedContainer
  490. && Running
  491. && (Application.Current == this
  492. || Application.Current?.Modal == false
  493. || (Application.Current?.Modal == true && Application.Current?.Running == false)))
  494. {
  495. foreach (Toplevel child in Application.OverlappedChildren)
  496. {
  497. var ev = new ToplevelClosingEventArgs (this);
  498. if (child.OnClosing (ev))
  499. {
  500. return;
  501. }
  502. child.Running = false;
  503. Application.RequestStop (child);
  504. }
  505. Running = false;
  506. Application.RequestStop (this);
  507. }
  508. else if (IsOverlappedContainer && Running && Application.Current?.Modal == true && Application.Current?.Running == true)
  509. {
  510. var ev = new ToplevelClosingEventArgs (Application.Current);
  511. if (OnClosing (ev))
  512. {
  513. return;
  514. }
  515. Application.RequestStop (Application.Current);
  516. }
  517. else if (!IsOverlappedContainer && Running && (!Modal || (Modal && Application.Current != this)))
  518. {
  519. var ev = new ToplevelClosingEventArgs (this);
  520. if (OnClosing (ev))
  521. {
  522. return;
  523. }
  524. Running = false;
  525. Application.RequestStop (this);
  526. }
  527. else
  528. {
  529. Application.RequestStop (Application.Current);
  530. }
  531. }
  532. /// <summary>
  533. /// Stops and closes the <see cref="Toplevel"/> specified by <paramref name="top"/>. If <paramref name="top"/> is
  534. /// the top-most Toplevel, <see cref="Application.RequestStop(Toplevel)"/> will be called, causing the application to
  535. /// exit.
  536. /// </summary>
  537. /// <param name="top">The Toplevel to request stop.</param>
  538. public virtual void RequestStop (Toplevel top) { top.RequestStop (); }
  539. /// <summary>Invoked when the terminal has been resized. The new <see cref="Size"/> of the terminal is provided.</summary>
  540. public event EventHandler<SizeChangedEventArgs> SizeChanging;
  541. /// <summary>
  542. /// Invoked when the Toplevel <see cref="RunState"/> has been unloaded. A Unloaded event handler is a good place
  543. /// to dispose objects after calling <see cref="Application.End(RunState)"/>.
  544. /// </summary>
  545. public event EventHandler Unloaded;
  546. /// <inheritdoc/>
  547. protected override void Dispose (bool disposing)
  548. {
  549. Application.GrabbingMouse -= Application_GrabbingMouse;
  550. Application.UnGrabbingMouse -= Application_UnGrabbingMouse;
  551. _dragPosition = null;
  552. base.Dispose (disposing);
  553. }
  554. internal void AddMenuStatusBar (View view)
  555. {
  556. if (view is MenuBar)
  557. {
  558. MenuBar = view as MenuBar;
  559. }
  560. if (view is StatusBar)
  561. {
  562. StatusBar = view as StatusBar;
  563. }
  564. }
  565. /// <summary>
  566. /// Gets a new location of the <see cref="Toplevel"/> that is within the Bounds of the <paramref name="top"/>'s
  567. /// <see cref="View.SuperView"/> (e.g. for dragging a Window). The `out` parameters are the new X and Y coordinates.
  568. /// </summary>
  569. /// <remarks>
  570. /// If <paramref name="top"/> does not have a <see cref="View.SuperView"/> or it's SuperView is not
  571. /// <see cref="Application.Top"/> the position will be bound by the <see cref="ConsoleDriver.Cols"/> and
  572. /// <see cref="ConsoleDriver.Rows"/>.
  573. /// </remarks>
  574. /// <param name="top">The Toplevel that is to be moved.</param>
  575. /// <param name="targetX">The target x location.</param>
  576. /// <param name="targetY">The target y location.</param>
  577. /// <param name="nx">The x location that will ensure <paramref name="top"/> will be visible.</param>
  578. /// <param name="ny">The y location that will ensure <paramref name="top"/> will be visible.</param>
  579. /// <param name="menuBar">The new top most menuBar</param>
  580. /// <param name="statusBar">The new top most statusBar</param>
  581. /// <returns>
  582. /// Either <see cref="Application.Top"/> (if <paramref name="top"/> does not have a Super View) or
  583. /// <paramref name="top"/>'s SuperView. This can be used to ensure LayoutSubviews is called on the correct View.
  584. /// </returns>
  585. internal View GetLocationThatFits (
  586. Toplevel top,
  587. int targetX,
  588. int targetY,
  589. out int nx,
  590. out int ny,
  591. out MenuBar menuBar,
  592. out StatusBar statusBar
  593. )
  594. {
  595. int maxWidth;
  596. View superView;
  597. if (top?.SuperView is null || top == Application.Top || top?.SuperView == Application.Top)
  598. {
  599. maxWidth = Driver.Cols;
  600. superView = Application.Top;
  601. }
  602. else
  603. {
  604. // Use the SuperView's Bounds, not Frame
  605. maxWidth = top.SuperView.Bounds.Width;
  606. superView = top.SuperView;
  607. }
  608. if (superView.Margin is { } && superView == top.SuperView)
  609. {
  610. maxWidth -= superView.GetAdornmentsThickness ().Left + superView.GetAdornmentsThickness ().Right;
  611. }
  612. if (top.Frame.Width <= maxWidth)
  613. {
  614. nx = Math.Max (targetX, 0);
  615. nx = nx + top.Frame.Width > maxWidth ? Math.Max (maxWidth - top.Frame.Width, 0) : nx;
  616. if (nx > top.Frame.X + top.Frame.Width)
  617. {
  618. nx = Math.Max (top.Frame.Right, 0);
  619. }
  620. }
  621. else
  622. {
  623. nx = targetX;
  624. }
  625. //System.Diagnostics.Debug.WriteLine ($"nx:{nx}, rWidth:{rWidth}");
  626. bool menuVisible, statusVisible;
  627. if (top?.SuperView is null || top == Application.Top || top?.SuperView == Application.Top)
  628. {
  629. menuVisible = Application.Top.MenuBar?.Visible == true;
  630. menuBar = Application.Top.MenuBar;
  631. }
  632. else
  633. {
  634. View t = top.SuperView;
  635. while (t is not Toplevel)
  636. {
  637. t = t.SuperView;
  638. }
  639. menuVisible = ((Toplevel)t).MenuBar?.Visible == true;
  640. menuBar = ((Toplevel)t).MenuBar;
  641. }
  642. if (top?.SuperView is null || top == Application.Top || top?.SuperView == Application.Top)
  643. {
  644. maxWidth = menuVisible ? 1 : 0;
  645. }
  646. else
  647. {
  648. maxWidth = 0;
  649. }
  650. ny = Math.Max (targetY, maxWidth);
  651. if (top?.SuperView is null || top == Application.Top || top?.SuperView == Application.Top)
  652. {
  653. statusVisible = Application.Top.StatusBar?.Visible == true;
  654. statusBar = Application.Top.StatusBar;
  655. }
  656. else
  657. {
  658. View t = top.SuperView;
  659. while (t is not Toplevel)
  660. {
  661. t = t.SuperView;
  662. }
  663. statusVisible = ((Toplevel)t).StatusBar?.Visible == true;
  664. statusBar = ((Toplevel)t).StatusBar;
  665. }
  666. if (top?.SuperView is null || top == Application.Top || top?.SuperView == Application.Top)
  667. {
  668. maxWidth = statusVisible ? Driver.Rows - 1 : Driver.Rows;
  669. }
  670. else
  671. {
  672. maxWidth = statusVisible ? top.SuperView.Frame.Height - 1 : top.SuperView.Frame.Height;
  673. }
  674. if (superView.Margin is { } && superView == top.SuperView)
  675. {
  676. maxWidth -= superView.GetAdornmentsThickness ().Top + superView.GetAdornmentsThickness ().Bottom;
  677. }
  678. ny = Math.Min (ny, maxWidth);
  679. if (top.Frame.Height <= maxWidth)
  680. {
  681. ny = ny + top.Frame.Height > maxWidth
  682. ? Math.Max (maxWidth - top.Frame.Height, menuVisible ? 1 : 0)
  683. : ny;
  684. if (ny > top.Frame.Y + top.Frame.Height)
  685. {
  686. ny = Math.Max (top.Frame.Bottom, 0);
  687. }
  688. }
  689. //System.Diagnostics.Debug.WriteLine ($"ny:{ny}, rHeight:{rHeight}");
  690. return superView;
  691. }
  692. internal virtual void OnActivate (Toplevel deactivated) { Activate?.Invoke (this, new ToplevelEventArgs (deactivated)); }
  693. internal virtual void OnAllChildClosed () { AllChildClosed?.Invoke (this, EventArgs.Empty); }
  694. internal virtual void OnChildClosed (Toplevel top)
  695. {
  696. if (IsOverlappedContainer)
  697. {
  698. SetSubViewNeedsDisplay ();
  699. }
  700. ChildClosed?.Invoke (this, new ToplevelEventArgs (top));
  701. }
  702. internal virtual void OnChildLoaded (Toplevel top) { ChildLoaded?.Invoke (this, new ToplevelEventArgs (top)); }
  703. internal virtual void OnChildUnloaded (Toplevel top) { ChildUnloaded?.Invoke (this, new ToplevelEventArgs (top)); }
  704. internal virtual void OnClosed (Toplevel top) { Closed?.Invoke (this, new ToplevelEventArgs (top)); }
  705. internal virtual bool OnClosing (ToplevelClosingEventArgs ev)
  706. {
  707. Closing?.Invoke (this, ev);
  708. return ev.Cancel;
  709. }
  710. internal virtual void OnDeactivate (Toplevel activated) { Deactivate?.Invoke (this, new ToplevelEventArgs (activated)); }
  711. /// <summary>
  712. /// Called from <see cref="Application.RunLoop"/> after the <see cref="Toplevel"/> has entered the first iteration
  713. /// of the loop.
  714. /// </summary>
  715. internal virtual void OnReady ()
  716. {
  717. foreach (Toplevel tl in Subviews.Where (v => v is Toplevel))
  718. {
  719. tl.OnReady ();
  720. }
  721. Ready?.Invoke (this, EventArgs.Empty);
  722. }
  723. // TODO: Make cancelable?
  724. internal virtual void OnSizeChanging (SizeChangedEventArgs size) { SizeChanging?.Invoke (this, size); }
  725. /// <summary>Called from <see cref="Application.End(RunState)"/> before the <see cref="Toplevel"/> is disposed.</summary>
  726. internal virtual void OnUnloaded ()
  727. {
  728. foreach (Toplevel tl in Subviews.Where (v => v is Toplevel))
  729. {
  730. tl.OnUnloaded ();
  731. }
  732. Unloaded?.Invoke (this, EventArgs.Empty);
  733. }
  734. // TODO: v2 - Not sure this is needed anymore.
  735. internal void PositionToplevels ()
  736. {
  737. PositionToplevel (this);
  738. foreach (View top in Subviews)
  739. {
  740. if (top is Toplevel)
  741. {
  742. PositionToplevel ((Toplevel)top);
  743. }
  744. }
  745. }
  746. internal void RemoveMenuStatusBar (View view)
  747. {
  748. if (view is MenuBar)
  749. {
  750. MenuBar?.Dispose ();
  751. MenuBar = null;
  752. }
  753. if (view is StatusBar)
  754. {
  755. StatusBar?.Dispose ();
  756. StatusBar = null;
  757. }
  758. }
  759. private void Application_GrabbingMouse (object sender, GrabMouseEventArgs e)
  760. {
  761. if (Application.MouseGrabView == this && _dragPosition.HasValue)
  762. {
  763. e.Cancel = true;
  764. }
  765. }
  766. private void Application_UnGrabbingMouse (object sender, GrabMouseEventArgs e)
  767. {
  768. if (Application.MouseGrabView == this && _dragPosition.HasValue)
  769. {
  770. e.Cancel = true;
  771. }
  772. }
  773. private void FocusNearestView (IEnumerable<View> views, NavigationDirection direction)
  774. {
  775. if (views is null)
  776. {
  777. return;
  778. }
  779. var found = false;
  780. var focusProcessed = false;
  781. var idx = 0;
  782. foreach (View v in views)
  783. {
  784. if (v == this)
  785. {
  786. found = true;
  787. }
  788. if (found && v != this)
  789. {
  790. if (direction == NavigationDirection.Forward)
  791. {
  792. SuperView?.FocusNext ();
  793. }
  794. else
  795. {
  796. SuperView?.FocusPrev ();
  797. }
  798. focusProcessed = true;
  799. if (SuperView.Focused is { } && SuperView.Focused != this)
  800. {
  801. return;
  802. }
  803. }
  804. else if (found && !focusProcessed && idx == views.Count () - 1)
  805. {
  806. views.ToList () [0].SetFocus ();
  807. }
  808. idx++;
  809. }
  810. }
  811. private View GetDeepestFocusedSubview (View view)
  812. {
  813. if (view is null)
  814. {
  815. return null;
  816. }
  817. foreach (View v in view.Subviews)
  818. {
  819. if (v.HasFocus)
  820. {
  821. return GetDeepestFocusedSubview (v);
  822. }
  823. }
  824. return view;
  825. }
  826. private void MoveNextView ()
  827. {
  828. View old = GetDeepestFocusedSubview (Focused);
  829. if (!FocusNext ())
  830. {
  831. FocusNext ();
  832. }
  833. if (old != Focused && old != Focused?.Focused)
  834. {
  835. old?.SetNeedsDisplay ();
  836. Focused?.SetNeedsDisplay ();
  837. }
  838. else
  839. {
  840. FocusNearestView (SuperView?.TabIndexes, NavigationDirection.Forward);
  841. }
  842. }
  843. private void MoveNextViewOrTop ()
  844. {
  845. if (Application.OverlappedTop is null)
  846. {
  847. Toplevel top = Modal ? this : Application.Top;
  848. top.FocusNext ();
  849. if (top.Focused is null)
  850. {
  851. top.FocusNext ();
  852. }
  853. top.SetNeedsDisplay ();
  854. Application.BringOverlappedTopToFront ();
  855. }
  856. else
  857. {
  858. Application.OverlappedMoveNext ();
  859. }
  860. }
  861. private void MovePreviousView ()
  862. {
  863. View old = GetDeepestFocusedSubview (Focused);
  864. if (!FocusPrev ())
  865. {
  866. FocusPrev ();
  867. }
  868. if (old != Focused && old != Focused?.Focused)
  869. {
  870. old?.SetNeedsDisplay ();
  871. Focused?.SetNeedsDisplay ();
  872. }
  873. else
  874. {
  875. FocusNearestView (SuperView?.TabIndexes?.Reverse (), NavigationDirection.Backward);
  876. }
  877. }
  878. private void MovePreviousViewOrTop ()
  879. {
  880. if (Application.OverlappedTop is null)
  881. {
  882. Toplevel top = Modal ? this : Application.Top;
  883. top.FocusPrev ();
  884. if (top.Focused is null)
  885. {
  886. top.FocusPrev ();
  887. }
  888. top.SetNeedsDisplay ();
  889. Application.BringOverlappedTopToFront ();
  890. }
  891. else
  892. {
  893. Application.OverlappedMovePrevious ();
  894. }
  895. }
  896. private bool OutsideTopFrame (Toplevel top)
  897. {
  898. if (top.Frame.X > Driver.Cols || top.Frame.Y > Driver.Rows)
  899. {
  900. return true;
  901. }
  902. return false;
  903. }
  904. private void QuitToplevel ()
  905. {
  906. if (Application.OverlappedTop is { })
  907. {
  908. Application.OverlappedTop.RequestStop ();
  909. }
  910. else
  911. {
  912. Application.RequestStop ();
  913. }
  914. }
  915. }
  916. /// <summary>
  917. /// Implements the <see cref="IEqualityComparer{T}"/> for comparing two <see cref="Toplevel"/>s used by
  918. /// <see cref="StackExtensions"/>.
  919. /// </summary>
  920. public class ToplevelEqualityComparer : IEqualityComparer<Toplevel>
  921. {
  922. /// <summary>Determines whether the specified objects are equal.</summary>
  923. /// <param name="x">The first object of type <see cref="Toplevel"/> to compare.</param>
  924. /// <param name="y">The second object of type <see cref="Toplevel"/> to compare.</param>
  925. /// <returns><see langword="true"/> if the specified objects are equal; otherwise, <see langword="false"/>.</returns>
  926. public bool Equals (Toplevel x, Toplevel y)
  927. {
  928. if (y is null && x is null)
  929. {
  930. return true;
  931. }
  932. if (x is null || y is null)
  933. {
  934. return false;
  935. }
  936. if (x.Id == y.Id)
  937. {
  938. return true;
  939. }
  940. return false;
  941. }
  942. /// <summary>Returns a hash code for the specified object.</summary>
  943. /// <param name="obj">The <see cref="Toplevel"/> for which a hash code is to be returned.</param>
  944. /// <returns>A hash code for the specified object.</returns>
  945. /// <exception cref="ArgumentNullException">
  946. /// The type of <paramref name="obj"/> is a reference type and
  947. /// <paramref name="obj"/> is <see langword="null"/>.
  948. /// </exception>
  949. public int GetHashCode (Toplevel obj)
  950. {
  951. if (obj is null)
  952. {
  953. throw new ArgumentNullException ();
  954. }
  955. var hCode = 0;
  956. if (int.TryParse (obj.Id, out int result))
  957. {
  958. hCode = result;
  959. }
  960. return hCode.GetHashCode ();
  961. }
  962. }
  963. /// <summary>
  964. /// Implements the <see cref="IComparer{T}"/> to sort the <see cref="Toplevel"/> from the
  965. /// <see cref="Application.OverlappedChildren"/> if needed.
  966. /// </summary>
  967. public sealed class ToplevelComparer : IComparer<Toplevel>
  968. {
  969. /// <summary>
  970. /// Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the
  971. /// other.
  972. /// </summary>
  973. /// <param name="x">The first object to compare.</param>
  974. /// <param name="y">The second object to compare.</param>
  975. /// <returns>
  976. /// A signed integer that indicates the relative values of <paramref name="x"/> and <paramref name="y"/>, as shown
  977. /// in the following table.Value Meaning Less than zero <paramref name="x"/> is less than <paramref name="y"/>.Zero
  978. /// <paramref name="x"/> equals <paramref name="y"/> .Greater than zero <paramref name="x"/> is greater than
  979. /// <paramref name="y"/>.
  980. /// </returns>
  981. public int Compare (Toplevel x, Toplevel y)
  982. {
  983. if (ReferenceEquals (x, y))
  984. {
  985. return 0;
  986. }
  987. if (x is null)
  988. {
  989. return -1;
  990. }
  991. if (y is null)
  992. {
  993. return 1;
  994. }
  995. return string.Compare (x.Id, y.Id);
  996. }
  997. }