Toplevel.cs 39 KB

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