Toplevel.cs 33 KB

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