Toplevel.cs 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063
  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. Initialize ();
  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. Initialize ();
  176. Width = Dim.Fill ();
  177. Height = Dim.Fill ();
  178. }
  179. void Initialize ()
  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. This is used to avoid the <see cref="View._needsDisplay"/>
  327. /// having wrong values while this was not yet loaded.
  328. /// </summary>
  329. public bool IsLoaded { get; private set; }
  330. ///<inheritdoc/>
  331. public override bool OnKeyDown (KeyEvent keyEvent)
  332. {
  333. if (base.OnKeyDown (keyEvent)) {
  334. return true;
  335. }
  336. switch (keyEvent.Key) {
  337. case Key.AltMask:
  338. case Key.AltMask | Key.Space:
  339. case Key.CtrlMask | Key.Space:
  340. case Key _ when (keyEvent.Key & Key.AltMask) == Key.AltMask:
  341. return MenuBar != null && MenuBar.OnKeyDown (keyEvent);
  342. }
  343. return false;
  344. }
  345. ///<inheritdoc/>
  346. public override bool OnKeyUp (KeyEvent keyEvent)
  347. {
  348. if (base.OnKeyUp (keyEvent)) {
  349. return true;
  350. }
  351. switch (keyEvent.Key) {
  352. case Key.AltMask:
  353. case Key.AltMask | Key.Space:
  354. case Key.CtrlMask | Key.Space:
  355. if (MenuBar != null && MenuBar.OnKeyUp (keyEvent)) {
  356. return true;
  357. }
  358. break;
  359. }
  360. return false;
  361. }
  362. ///<inheritdoc/>
  363. public override bool ProcessKey (KeyEvent keyEvent)
  364. {
  365. if (base.ProcessKey (keyEvent))
  366. return true;
  367. var result = InvokeKeybindings (new KeyEvent (ShortcutHelper.GetModifiersKey (keyEvent),
  368. new KeyModifiers () { Alt = keyEvent.IsAlt, Ctrl = keyEvent.IsCtrl, Shift = keyEvent.IsShift }));
  369. if (result != null)
  370. return (bool)result;
  371. #if false
  372. if (keyEvent.Key == Key.F5) {
  373. Application.DebugDrawBounds = !Application.DebugDrawBounds;
  374. SetNeedsDisplay ();
  375. return true;
  376. }
  377. #endif
  378. return false;
  379. }
  380. private void MovePreviousViewOrTop ()
  381. {
  382. if (Application.MdiTop == null) {
  383. var top = Modal ? this : Application.Top;
  384. top.FocusPrev ();
  385. if (top.Focused == null) {
  386. top.FocusPrev ();
  387. }
  388. top.SetNeedsDisplay ();
  389. Application.EnsuresTopOnFront ();
  390. } else {
  391. MovePrevious ();
  392. }
  393. }
  394. private void MoveNextViewOrTop ()
  395. {
  396. if (Application.MdiTop == null) {
  397. var top = Modal ? this : Application.Top;
  398. top.FocusNext ();
  399. if (top.Focused == null) {
  400. top.FocusNext ();
  401. }
  402. top.SetNeedsDisplay ();
  403. Application.EnsuresTopOnFront ();
  404. } else {
  405. MoveNext ();
  406. }
  407. }
  408. private void MovePreviousView ()
  409. {
  410. var old = GetDeepestFocusedSubview (Focused);
  411. if (!FocusPrev ())
  412. FocusPrev ();
  413. if (old != Focused && old != Focused?.Focused) {
  414. old?.SetNeedsDisplay ();
  415. Focused?.SetNeedsDisplay ();
  416. } else {
  417. FocusNearestView (SuperView?.TabIndexes?.Reverse (), Direction.Backward);
  418. }
  419. }
  420. private void MoveNextView ()
  421. {
  422. var old = GetDeepestFocusedSubview (Focused);
  423. if (!FocusNext ())
  424. FocusNext ();
  425. if (old != Focused && old != Focused?.Focused) {
  426. old?.SetNeedsDisplay ();
  427. Focused?.SetNeedsDisplay ();
  428. } else {
  429. FocusNearestView (SuperView?.TabIndexes, Direction.Forward);
  430. }
  431. }
  432. private void QuitToplevel ()
  433. {
  434. if (Application.MdiTop != null) {
  435. Application.MdiTop.RequestStop ();
  436. } else {
  437. Application.RequestStop ();
  438. }
  439. }
  440. ///<inheritdoc/>
  441. public override bool ProcessColdKey (KeyEvent keyEvent)
  442. {
  443. if (base.ProcessColdKey (keyEvent)) {
  444. return true;
  445. }
  446. if (ShortcutHelper.FindAndOpenByShortcut (keyEvent, this)) {
  447. return true;
  448. }
  449. return false;
  450. }
  451. View GetDeepestFocusedSubview (View view)
  452. {
  453. if (view == null) {
  454. return null;
  455. }
  456. foreach (var v in view.Subviews) {
  457. if (v.HasFocus) {
  458. return GetDeepestFocusedSubview (v);
  459. }
  460. }
  461. return view;
  462. }
  463. void FocusNearestView (IEnumerable<View> views, Direction direction)
  464. {
  465. if (views == null) {
  466. return;
  467. }
  468. bool found = false;
  469. bool focusProcessed = false;
  470. int idx = 0;
  471. foreach (var v in views) {
  472. if (v == this) {
  473. found = true;
  474. }
  475. if (found && v != this) {
  476. if (direction == Direction.Forward) {
  477. SuperView?.FocusNext ();
  478. } else {
  479. SuperView?.FocusPrev ();
  480. }
  481. focusProcessed = true;
  482. if (SuperView.Focused != null && SuperView.Focused != this) {
  483. return;
  484. }
  485. } else if (found && !focusProcessed && idx == views.Count () - 1) {
  486. views.ToList () [0].SetFocus ();
  487. }
  488. idx++;
  489. }
  490. }
  491. ///<inheritdoc/>
  492. public override void Add (View view)
  493. {
  494. AddMenuStatusBar (view);
  495. base.Add (view);
  496. }
  497. internal void AddMenuStatusBar (View view)
  498. {
  499. if (view is MenuBar) {
  500. MenuBar = view as MenuBar;
  501. }
  502. if (view is StatusBar) {
  503. StatusBar = view as StatusBar;
  504. }
  505. }
  506. ///<inheritdoc/>
  507. public override void Remove (View view)
  508. {
  509. if (this is Toplevel toplevel && toplevel.MenuBar != null) {
  510. RemoveMenuStatusBar (view);
  511. }
  512. base.Remove (view);
  513. }
  514. ///<inheritdoc/>
  515. public override void RemoveAll ()
  516. {
  517. if (this == Application.Top) {
  518. MenuBar?.Dispose ();
  519. MenuBar = null;
  520. StatusBar?.Dispose ();
  521. StatusBar = null;
  522. }
  523. base.RemoveAll ();
  524. }
  525. internal void RemoveMenuStatusBar (View view)
  526. {
  527. if (view is MenuBar) {
  528. MenuBar?.Dispose ();
  529. MenuBar = null;
  530. }
  531. if (view is StatusBar) {
  532. StatusBar?.Dispose ();
  533. StatusBar = null;
  534. }
  535. }
  536. internal View EnsureVisibleBounds (Toplevel top, int x, int y,
  537. out int nx, out int ny, out MenuBar mb, out StatusBar sb)
  538. {
  539. int l;
  540. View superView;
  541. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  542. l = Driver.Cols;
  543. superView = Application.Top;
  544. } else {
  545. l = top.SuperView.Frame.Width;
  546. superView = top.SuperView;
  547. }
  548. nx = Math.Max (x, 0);
  549. nx = nx + top.Frame.Width > l ? Math.Max (l - top.Frame.Width, 0) : nx;
  550. var mfLength = top.Border?.DrawMarginFrame == true ? 2 : 1;
  551. if (nx + mfLength > top.Frame.X + top.Frame.Width) {
  552. nx = Math.Max (top.Frame.Right - mfLength, 0);
  553. }
  554. //System.Diagnostics.Debug.WriteLine ($"nx:{nx}, rWidth:{rWidth}");
  555. bool m, s;
  556. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  557. m = Application.Top.MenuBar?.Visible == true;
  558. mb = Application.Top.MenuBar;
  559. } else {
  560. var t = top.SuperView;
  561. while (!(t is Toplevel)) {
  562. t = t.SuperView;
  563. }
  564. m = ((Toplevel)t).MenuBar?.Visible == true;
  565. mb = ((Toplevel)t).MenuBar;
  566. }
  567. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  568. l = m ? 1 : 0;
  569. } else {
  570. l = 0;
  571. }
  572. ny = Math.Max (y, l);
  573. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  574. s = Application.Top.StatusBar?.Visible == true;
  575. sb = Application.Top.StatusBar;
  576. } else {
  577. var t = top.SuperView;
  578. while (!(t is Toplevel)) {
  579. t = t.SuperView;
  580. }
  581. s = ((Toplevel)t).StatusBar?.Visible == true;
  582. sb = ((Toplevel)t).StatusBar;
  583. }
  584. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  585. l = s ? Driver.Rows - 1 : Driver.Rows;
  586. } else {
  587. l = s ? top.SuperView.Frame.Height - 1 : top.SuperView.Frame.Height;
  588. }
  589. ny = Math.Min (ny, l);
  590. ny = ny + top.Frame.Height >= l ? Math.Max (l - top.Frame.Height, m ? 1 : 0) : ny;
  591. if (ny + mfLength > top.Frame.Y + top.Frame.Height) {
  592. ny = Math.Max (top.Frame.Bottom - mfLength, 0);
  593. }
  594. //System.Diagnostics.Debug.WriteLine ($"ny:{ny}, rHeight:{rHeight}");
  595. return superView;
  596. }
  597. internal void PositionToplevels ()
  598. {
  599. PositionToplevel (this);
  600. foreach (var top in Subviews) {
  601. if (top is Toplevel) {
  602. PositionToplevel ((Toplevel)top);
  603. }
  604. }
  605. }
  606. /// <summary>
  607. /// Adjusts the location and size of <paramref name="top"/> within this Toplevel.
  608. /// Virtual method enabling implementation of specific positions for inherited <see cref="Toplevel"/> views.
  609. /// </summary>
  610. /// <param name="top">The Toplevel to adjust.</param>
  611. public virtual void PositionToplevel (Toplevel top)
  612. {
  613. var superView = EnsureVisibleBounds (top, top.Frame.X, top.Frame.Y,
  614. out int nx, out int ny, out _, out StatusBar sb);
  615. bool layoutSubviews = false;
  616. if ((top?.SuperView != null || (top != Application.Top && top.Modal)
  617. || (top?.SuperView == null && top.IsMdiChild))
  618. && (nx > top.Frame.X || ny > top.Frame.Y) && top.LayoutStyle == LayoutStyle.Computed) {
  619. if ((top.X == null || top.X is Pos.PosAbsolute) && top.Bounds.X != nx) {
  620. top.X = nx;
  621. layoutSubviews = true;
  622. }
  623. if ((top.Y == null || top.Y is Pos.PosAbsolute) && top.Bounds.Y != ny) {
  624. top.Y = ny;
  625. layoutSubviews = true;
  626. }
  627. }
  628. // TODO: v2 - This is a hack to get the StatusBar to be positioned correctly.
  629. if (sb != null && ny + top.Frame.Height != superView.Frame.Height - (sb.Visible ? 1 : 0)
  630. && top.Height is Dim.DimFill && -top.Height.Anchor (0) < 1) {
  631. top.Height = Dim.Fill (sb.Visible ? 1 : 0);
  632. layoutSubviews = true;
  633. }
  634. if (layoutSubviews) {
  635. superView.LayoutSubviews ();
  636. }
  637. }
  638. ///<inheritdoc/>
  639. public override void Redraw (Rect bounds)
  640. {
  641. if (!Visible) {
  642. return;
  643. }
  644. if (!NeedDisplay.IsEmpty || ChildNeedsDisplay || LayoutNeeded) {
  645. Driver.SetAttribute (GetNormalColor ());
  646. // This is the Application.Top. Clear just the region we're being asked to redraw
  647. // (the bounds passed to us).
  648. Clear ();
  649. Driver.SetAttribute (Enabled ? Colors.Base.Normal : Colors.Base.Disabled);
  650. LayoutSubviews ();
  651. PositionToplevels ();
  652. if (this == Application.MdiTop) {
  653. foreach (var top in Application.MdiChildes.AsEnumerable ().Reverse ()) {
  654. if (top.Frame.IntersectsWith (bounds)) {
  655. if (top != this && !top.IsCurrentTop && !OutsideTopFrame (top) && top.Visible) {
  656. top.SetNeedsLayout ();
  657. top.SetNeedsDisplay (top.Bounds);
  658. top.Redraw (top.Bounds);
  659. }
  660. }
  661. }
  662. }
  663. foreach (var view in Subviews) {
  664. if (view.Frame.IntersectsWith (bounds) && !OutsideTopFrame (this)) {
  665. view.SetNeedsLayout ();
  666. view.SetNeedsDisplay (view.Bounds);
  667. }
  668. }
  669. }
  670. base.Redraw (Bounds);
  671. }
  672. bool OutsideTopFrame (Toplevel top)
  673. {
  674. if (top.Frame.X > Driver.Cols || top.Frame.Y > Driver.Rows) {
  675. return true;
  676. }
  677. return false;
  678. }
  679. internal static Point? dragPosition;
  680. Point start;
  681. ///<inheritdoc/>
  682. public override bool MouseEvent (MouseEvent mouseEvent)
  683. {
  684. if (!CanFocus) {
  685. return true;
  686. }
  687. //System.Diagnostics.Debug.WriteLine ($"dragPosition before: {dragPosition.HasValue}");
  688. int nx, ny;
  689. if (!dragPosition.HasValue && (mouseEvent.Flags == MouseFlags.Button1Pressed
  690. || mouseEvent.Flags == MouseFlags.Button2Pressed
  691. || mouseEvent.Flags == MouseFlags.Button3Pressed)) {
  692. SetFocus ();
  693. Application.EnsuresTopOnFront ();
  694. // Only start grabbing if the user clicks on the title bar.
  695. if (mouseEvent.Y == 0 && mouseEvent.Flags == MouseFlags.Button1Pressed) {
  696. start = new Point (mouseEvent.X, mouseEvent.Y);
  697. dragPosition = new Point ();
  698. nx = mouseEvent.X - mouseEvent.OfX;
  699. ny = mouseEvent.Y - mouseEvent.OfY;
  700. dragPosition = new Point (nx, ny);
  701. Application.GrabMouse (this);
  702. }
  703. //System.Diagnostics.Debug.WriteLine ($"Starting at {dragPosition}");
  704. return true;
  705. } else if (mouseEvent.Flags == (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) ||
  706. mouseEvent.Flags == MouseFlags.Button3Pressed) {
  707. if (dragPosition.HasValue) {
  708. if (SuperView == null) {
  709. // Redraw the entire app window using just our Frame. Since we are
  710. // Application.Top, and our Frame always == our Bounds (Location is always (0,0))
  711. // our Frame is actually view-relative (which is what Redraw takes).
  712. // We need to pass all the view bounds because since the windows was
  713. // moved around, we don't know exactly what was the affected region.
  714. Application.Top.SetNeedsDisplay ();
  715. } else {
  716. SuperView.SetNeedsDisplay ();
  717. }
  718. EnsureVisibleBounds (this, mouseEvent.X + (SuperView == null ? mouseEvent.OfX - start.X : Frame.X - start.X),
  719. mouseEvent.Y + (SuperView == null ? mouseEvent.OfY - start.Y : Frame.Y - start.Y),
  720. out nx, out ny, out _, out _);
  721. dragPosition = new Point (nx, ny);
  722. X = nx;
  723. Y = ny;
  724. //System.Diagnostics.Debug.WriteLine ($"Drag: nx:{nx},ny:{ny}");
  725. SetNeedsDisplay ();
  726. return true;
  727. }
  728. }
  729. if (mouseEvent.Flags.HasFlag (MouseFlags.Button1Released) && dragPosition.HasValue) {
  730. dragPosition = null;
  731. Application.UngrabMouse ();
  732. }
  733. //System.Diagnostics.Debug.WriteLine ($"dragPosition after: {dragPosition.HasValue}");
  734. //System.Diagnostics.Debug.WriteLine ($"Toplevel: {mouseEvent}");
  735. return false;
  736. }
  737. /// <summary>
  738. /// Invoked by <see cref="Application.Begin"/> as part of <see cref="Application.Run(Toplevel, Func{Exception, bool})"/>
  739. /// after the views have been laid out, and before the views are drawn for the first time.
  740. /// </summary>
  741. public virtual void WillPresent ()
  742. {
  743. FocusFirst ();
  744. }
  745. /// <summary>
  746. /// Move to the next Mdi child from the <see cref="Application.MdiTop"/>.
  747. /// </summary>
  748. public virtual void MoveNext ()
  749. {
  750. Application.MoveNext ();
  751. }
  752. /// <summary>
  753. /// Move to the previous Mdi child from the <see cref="Application.MdiTop"/>.
  754. /// </summary>
  755. public virtual void MovePrevious ()
  756. {
  757. Application.MovePrevious ();
  758. }
  759. /// <summary>
  760. /// Stops and closes this <see cref="Toplevel"/>. If this Toplevel is the top-most Toplevel,
  761. /// <see cref="Application.RequestStop(Toplevel)"/> will be called, causing the application to exit.
  762. /// </summary>
  763. public virtual void RequestStop ()
  764. {
  765. if (IsMdiContainer && Running
  766. && (Application.Current == this
  767. || Application.Current?.Modal == false
  768. || Application.Current?.Modal == true && Application.Current?.Running == false)) {
  769. foreach (var child in Application.MdiChildes) {
  770. var ev = new ToplevelClosingEventArgs (this);
  771. if (child.OnClosing (ev)) {
  772. return;
  773. }
  774. child.Running = false;
  775. Application.RequestStop (child);
  776. }
  777. Running = false;
  778. Application.RequestStop (this);
  779. } else if (IsMdiContainer && Running && Application.Current?.Modal == true && Application.Current?.Running == true) {
  780. var ev = new ToplevelClosingEventArgs (Application.Current);
  781. if (OnClosing (ev)) {
  782. return;
  783. }
  784. Application.RequestStop (Application.Current);
  785. } else if (!IsMdiContainer && Running && (!Modal || (Modal && Application.Current != this))) {
  786. var ev = new ToplevelClosingEventArgs (this);
  787. if (OnClosing (ev)) {
  788. return;
  789. }
  790. Running = false;
  791. Application.RequestStop (this);
  792. } else {
  793. Application.RequestStop (Application.Current);
  794. }
  795. }
  796. /// <summary>
  797. /// Stops and closes the <see cref="Toplevel"/> specified by <paramref name="top"/>. If <paramref name="top"/> is the top-most Toplevel,
  798. /// <see cref="Application.RequestStop(Toplevel)"/> will be called, causing the application to exit.
  799. /// </summary>
  800. /// <param name="top">The toplevel to request stop.</param>
  801. public virtual void RequestStop (Toplevel top)
  802. {
  803. top.RequestStop ();
  804. }
  805. ///<inheritdoc/>
  806. public override void PositionCursor ()
  807. {
  808. if (!IsMdiContainer) {
  809. base.PositionCursor ();
  810. if (Focused == null) {
  811. EnsureFocus ();
  812. if (Focused == null) {
  813. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  814. }
  815. }
  816. return;
  817. }
  818. if (Focused == null) {
  819. foreach (var top in Application.MdiChildes) {
  820. if (top != this && top.Visible) {
  821. top.SetFocus ();
  822. return;
  823. }
  824. }
  825. }
  826. base.PositionCursor ();
  827. if (Focused == null) {
  828. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  829. }
  830. }
  831. /// <summary>
  832. /// Gets the current visible Toplevel Mdi child that matches the arguments pattern.
  833. /// </summary>
  834. /// <param name="type">The type.</param>
  835. /// <param name="exclude">The strings to exclude.</param>
  836. /// <returns>The matched view.</returns>
  837. public View GetTopMdiChild (Type type = null, string [] exclude = null)
  838. {
  839. if (Application.MdiTop == null) {
  840. return null;
  841. }
  842. foreach (var top in Application.MdiChildes) {
  843. if (type != null && top.GetType () == type
  844. && exclude?.Contains (top.Data.ToString ()) == false) {
  845. return top;
  846. } else if ((type != null && top.GetType () != type)
  847. || (exclude?.Contains (top.Data.ToString ()) == true)) {
  848. continue;
  849. }
  850. return top;
  851. }
  852. return null;
  853. }
  854. /// <summary>
  855. /// Shows the Mdi child indicated by <paramref name="top"/>, setting it as <see cref="Application.Current"/>.
  856. /// </summary>
  857. /// <param name="top">The Toplevel.</param>
  858. /// <returns><c>true</c> if the toplevel can be shown or <c>false</c> if not.</returns>
  859. public virtual bool ShowChild (Toplevel top = null)
  860. {
  861. if (Application.MdiTop != null) {
  862. return Application.ShowChild (top == null ? this : top);
  863. }
  864. return false;
  865. }
  866. ///<inheritdoc/>
  867. public override bool OnEnter (View view)
  868. {
  869. return MostFocused?.OnEnter (view) ?? base.OnEnter (view);
  870. }
  871. ///<inheritdoc/>
  872. public override bool OnLeave (View view)
  873. {
  874. return MostFocused?.OnLeave (view) ?? base.OnLeave (view);
  875. }
  876. }
  877. /// <summary>
  878. /// Implements the <see cref="IEqualityComparer{T}"/> for comparing two <see cref="Toplevel"/>s
  879. /// used by <see cref="StackExtensions"/>.
  880. /// </summary>
  881. public class ToplevelEqualityComparer : IEqualityComparer<Toplevel> {
  882. /// <summary>Determines whether the specified objects are equal.</summary>
  883. /// <param name="x">The first object of type <see cref="Toplevel" /> to compare.</param>
  884. /// <param name="y">The second object of type <see cref="Toplevel" /> to compare.</param>
  885. /// <returns>
  886. /// <see langword="true" /> if the specified objects are equal; otherwise, <see langword="false" />.</returns>
  887. public bool Equals (Toplevel x, Toplevel y)
  888. {
  889. if (y == null && x == null)
  890. return true;
  891. else if (x == null || y == null)
  892. return false;
  893. else if (x.Id == y.Id)
  894. return true;
  895. else
  896. return false;
  897. }
  898. /// <summary>Returns a hash code for the specified object.</summary>
  899. /// <param name="obj">The <see cref="Toplevel" /> for which a hash code is to be returned.</param>
  900. /// <returns>A hash code for the specified object.</returns>
  901. /// <exception cref="ArgumentNullException">The type of <paramref name="obj" />
  902. /// is a reference type and <paramref name="obj" /> is <see langword="null" />.</exception>
  903. public int GetHashCode (Toplevel obj)
  904. {
  905. if (obj == null)
  906. throw new ArgumentNullException ();
  907. int hCode = 0;
  908. if (int.TryParse (obj.Id.ToString (), out int result)) {
  909. hCode = result;
  910. }
  911. return hCode.GetHashCode ();
  912. }
  913. }
  914. /// <summary>
  915. /// Implements the <see cref="IComparer{T}"/> to sort the <see cref="Toplevel"/>
  916. /// from the <see cref="Application.MdiChildes"/> if needed.
  917. /// </summary>
  918. public sealed class ToplevelComparer : IComparer<Toplevel> {
  919. /// <summary>Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.</summary>
  920. /// <param name="x">The first object to compare.</param>
  921. /// <param name="y">The second object to compare.</param>
  922. /// <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
  923. /// <paramref name="x" /> is less than <paramref name="y" />.Zero
  924. /// <paramref name="x" /> equals <paramref name="y" />.Greater than zero
  925. /// <paramref name="x" /> is greater than <paramref name="y" />.</returns>
  926. public int Compare (Toplevel x, Toplevel y)
  927. {
  928. if (ReferenceEquals (x, y))
  929. return 0;
  930. else if (x == null)
  931. return -1;
  932. else if (y == null)
  933. return 1;
  934. else
  935. return string.Compare (x.Id.ToString (), y.Id.ToString ());
  936. }
  937. }
  938. }