Toplevel.cs 35 KB

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