Toplevel.cs 33 KB

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