Toplevel.cs 35 KB

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