Toplevel.cs 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075
  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.
  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. internal View EnsureVisibleBounds (Toplevel top, int x, int y,
  536. out int nx, out int ny, out MenuBar mb, out StatusBar sb)
  537. {
  538. int l;
  539. View superView;
  540. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  541. l = Driver.Cols;
  542. superView = Application.Top;
  543. } else {
  544. l = top.SuperView.Frame.Width;
  545. superView = top.SuperView;
  546. }
  547. var mfLength = top.Border?.DrawMarginFrame == true ? 2 : 1;
  548. if (top.Frame.Width <= l) {
  549. nx = Math.Max (x, 0);
  550. nx = nx + top.Frame.Width > l ? Math.Max (l - top.Frame.Width, 0) : nx;
  551. if (nx + mfLength > top.Frame.X + top.Frame.Width) {
  552. nx = Math.Max (top.Frame.Right - mfLength, 0);
  553. }
  554. } else {
  555. nx = x;
  556. }
  557. //System.Diagnostics.Debug.WriteLine ($"nx:{nx}, rWidth:{rWidth}");
  558. bool m, s;
  559. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  560. m = Application.Top.MenuBar?.Visible == true;
  561. mb = Application.Top.MenuBar;
  562. } else {
  563. var t = top.SuperView;
  564. while (t is not Toplevel) {
  565. t = t.SuperView;
  566. }
  567. m = ((Toplevel)t).MenuBar?.Visible == true;
  568. mb = ((Toplevel)t).MenuBar;
  569. }
  570. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  571. l = m ? 1 : 0;
  572. } else {
  573. l = 0;
  574. }
  575. ny = Math.Max (y, l);
  576. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  577. s = Application.Top.StatusBar?.Visible == true;
  578. sb = Application.Top.StatusBar;
  579. } else {
  580. var t = top.SuperView;
  581. while (t is not Toplevel) {
  582. t = t.SuperView;
  583. }
  584. s = ((Toplevel)t).StatusBar?.Visible == true;
  585. sb = ((Toplevel)t).StatusBar;
  586. }
  587. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  588. l = s ? Driver.Rows - 1 : Driver.Rows;
  589. } else {
  590. l = s ? top.SuperView.Frame.Height - 1 : top.SuperView.Frame.Height;
  591. }
  592. ny = Math.Min (ny, l);
  593. if (top.Frame.Height <= l) {
  594. ny = ny + top.Frame.Height >= l ? Math.Max (l - top.Frame.Height, m ? 1 : 0) : ny;
  595. if (ny + mfLength > top.Frame.Y + top.Frame.Height) {
  596. ny = Math.Max (top.Frame.Bottom - mfLength, 0);
  597. }
  598. }
  599. //System.Diagnostics.Debug.WriteLine ($"ny:{ny}, rHeight:{rHeight}");
  600. return superView;
  601. }
  602. internal void PositionToplevels ()
  603. {
  604. PositionToplevel (this);
  605. foreach (var top in Subviews) {
  606. if (top is Toplevel) {
  607. PositionToplevel ((Toplevel)top);
  608. }
  609. }
  610. }
  611. /// <summary>
  612. /// Adjusts the location and size of <paramref name="top"/> within this Toplevel.
  613. /// Virtual method enabling implementation of specific positions for inherited <see cref="Toplevel"/> views.
  614. /// </summary>
  615. /// <param name="top">The Toplevel to adjust.</param>
  616. public virtual void PositionToplevel (Toplevel top)
  617. {
  618. var superView = EnsureVisibleBounds (top, top.Frame.X, top.Frame.Y,
  619. out int nx, out int ny, out _, out StatusBar sb);
  620. bool layoutSubviews = false;
  621. if ((superView != top || top?.SuperView != null || (top != Application.Top && top.Modal)
  622. || (top?.SuperView == null && top.IsMdiChild))
  623. && (top.Frame.X + top.Frame.Width > Driver.Cols || ny > top.Frame.Y) && top.LayoutStyle == LayoutStyle.Computed) {
  624. if ((top.X == null || top.X is Pos.PosAbsolute) && top.Frame.X != nx) {
  625. top.X = nx;
  626. layoutSubviews = true;
  627. }
  628. if ((top.Y == null || top.Y is Pos.PosAbsolute) && top.Frame.Y != ny) {
  629. top.Y = ny;
  630. layoutSubviews = true;
  631. }
  632. }
  633. // TODO: v2 - This is a hack to get the StatusBar to be positioned correctly.
  634. if (sb != null && ny + top.Frame.Height != superView.Frame.Height - (sb.Visible ? 1 : 0)
  635. && top.Height is Dim.DimFill && -top.Height.Anchor (0) < 1) {
  636. top.Height = Dim.Fill (sb.Visible ? 1 : 0);
  637. layoutSubviews = true;
  638. }
  639. if (layoutSubviews) {
  640. superView.LayoutSubviews ();
  641. }
  642. }
  643. ///<inheritdoc/>
  644. public override void Redraw (Rect bounds)
  645. {
  646. if (!Visible) {
  647. return;
  648. }
  649. if (!NeedDisplay.IsEmpty || ChildNeedsDisplay || LayoutNeeded) {
  650. Driver.SetAttribute (GetNormalColor ());
  651. // This is the Application.Top. Clear just the region we're being asked to redraw
  652. // (the bounds passed to us).
  653. Clear ();
  654. Driver.SetAttribute (Enabled ? Colors.Base.Normal : Colors.Base.Disabled);
  655. LayoutSubviews ();
  656. PositionToplevels ();
  657. if (this == Application.MdiTop) {
  658. foreach (var top in Application.MdiChildes.AsEnumerable ().Reverse ()) {
  659. if (top.Frame.IntersectsWith (bounds)) {
  660. if (top != this && !top.IsCurrentTop && !OutsideTopFrame (top) && top.Visible) {
  661. top.SetNeedsLayout ();
  662. top.SetNeedsDisplay (top.Bounds);
  663. top.Redraw (top.Bounds);
  664. }
  665. }
  666. }
  667. }
  668. foreach (var view in Subviews) {
  669. if (view.Frame.IntersectsWith (bounds) && !OutsideTopFrame (this)) {
  670. view.SetNeedsLayout ();
  671. view.SetNeedsDisplay (view.Bounds);
  672. }
  673. }
  674. }
  675. base.Redraw (Bounds);
  676. }
  677. bool OutsideTopFrame (Toplevel top)
  678. {
  679. if (top.Frame.X > Driver.Cols || top.Frame.Y > Driver.Rows) {
  680. return true;
  681. }
  682. return false;
  683. }
  684. internal static Point? dragPosition;
  685. Point start;
  686. ///<inheritdoc/>
  687. public override bool MouseEvent (MouseEvent mouseEvent)
  688. {
  689. if (!CanFocus) {
  690. return true;
  691. }
  692. //System.Diagnostics.Debug.WriteLine ($"dragPosition before: {dragPosition.HasValue}");
  693. int nx, ny;
  694. if (!dragPosition.HasValue && (mouseEvent.Flags == MouseFlags.Button1Pressed
  695. || mouseEvent.Flags == MouseFlags.Button2Pressed
  696. || mouseEvent.Flags == MouseFlags.Button3Pressed)) {
  697. SetFocus ();
  698. Application.EnsuresTopOnFront ();
  699. // Only start grabbing if the user clicks on the title bar.
  700. if (mouseEvent.Y == 0 && mouseEvent.Flags == MouseFlags.Button1Pressed) {
  701. start = new Point (mouseEvent.X, mouseEvent.Y);
  702. dragPosition = new Point ();
  703. nx = mouseEvent.X - mouseEvent.OfX;
  704. ny = mouseEvent.Y - mouseEvent.OfY;
  705. dragPosition = new Point (nx, ny);
  706. Application.GrabMouse (this);
  707. }
  708. //System.Diagnostics.Debug.WriteLine ($"Starting at {dragPosition}");
  709. return true;
  710. } else if (mouseEvent.Flags == (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) ||
  711. mouseEvent.Flags == MouseFlags.Button3Pressed) {
  712. if (dragPosition.HasValue) {
  713. if (SuperView == null) {
  714. // Redraw the entire app window using just our Frame. Since we are
  715. // Application.Top, and our Frame always == our Bounds (Location is always (0,0))
  716. // our Frame is actually view-relative (which is what Redraw takes).
  717. // We need to pass all the view bounds because since the windows was
  718. // moved around, we don't know exactly what was the affected region.
  719. Application.Top.SetNeedsDisplay ();
  720. } else {
  721. SuperView.SetNeedsDisplay ();
  722. }
  723. EnsureVisibleBounds (this, mouseEvent.X + (SuperView == null ? mouseEvent.OfX - start.X : Frame.X - start.X),
  724. mouseEvent.Y + (SuperView == null ? mouseEvent.OfY - start.Y : Frame.Y - start.Y),
  725. out nx, out ny, out _, out _);
  726. dragPosition = new Point (nx, ny);
  727. X = nx;
  728. Y = ny;
  729. //System.Diagnostics.Debug.WriteLine ($"Drag: nx:{nx},ny:{ny}");
  730. SetNeedsDisplay ();
  731. return true;
  732. }
  733. }
  734. if (mouseEvent.Flags.HasFlag (MouseFlags.Button1Released) && dragPosition.HasValue) {
  735. dragPosition = null;
  736. Application.UngrabMouse ();
  737. }
  738. //System.Diagnostics.Debug.WriteLine ($"dragPosition after: {dragPosition.HasValue}");
  739. //System.Diagnostics.Debug.WriteLine ($"Toplevel: {mouseEvent}");
  740. return false;
  741. }
  742. /// <summary>
  743. /// Invoked by <see cref="Application.Begin"/> as part of <see cref="Application.Run(Toplevel, Func{Exception, bool})"/>
  744. /// after the views have been laid out, and before the views are drawn for the first time.
  745. /// </summary>
  746. public virtual void WillPresent ()
  747. {
  748. FocusFirst ();
  749. }
  750. /// <summary>
  751. /// Move to the next Mdi child from the <see cref="Application.MdiTop"/>.
  752. /// </summary>
  753. public virtual void MoveNext ()
  754. {
  755. Application.MoveNext ();
  756. }
  757. /// <summary>
  758. /// Move to the previous Mdi child from the <see cref="Application.MdiTop"/>.
  759. /// </summary>
  760. public virtual void MovePrevious ()
  761. {
  762. Application.MovePrevious ();
  763. }
  764. /// <summary>
  765. /// Stops and closes this <see cref="Toplevel"/>. If this Toplevel is the top-most Toplevel,
  766. /// <see cref="Application.RequestStop(Toplevel)"/> will be called, causing the application to exit.
  767. /// </summary>
  768. public virtual void RequestStop ()
  769. {
  770. if (IsMdiContainer && Running
  771. && (Application.Current == this
  772. || Application.Current?.Modal == false
  773. || Application.Current?.Modal == true && Application.Current?.Running == false)) {
  774. foreach (var child in Application.MdiChildes) {
  775. var ev = new ToplevelClosingEventArgs (this);
  776. if (child.OnClosing (ev)) {
  777. return;
  778. }
  779. child.Running = false;
  780. Application.RequestStop (child);
  781. }
  782. Running = false;
  783. Application.RequestStop (this);
  784. } else if (IsMdiContainer && Running && Application.Current?.Modal == true && Application.Current?.Running == true) {
  785. var ev = new ToplevelClosingEventArgs (Application.Current);
  786. if (OnClosing (ev)) {
  787. return;
  788. }
  789. Application.RequestStop (Application.Current);
  790. } else if (!IsMdiContainer && Running && (!Modal || (Modal && Application.Current != this))) {
  791. var ev = new ToplevelClosingEventArgs (this);
  792. if (OnClosing (ev)) {
  793. return;
  794. }
  795. Running = false;
  796. Application.RequestStop (this);
  797. } else {
  798. Application.RequestStop (Application.Current);
  799. }
  800. }
  801. /// <summary>
  802. /// Stops and closes the <see cref="Toplevel"/> specified by <paramref name="top"/>. If <paramref name="top"/> is the top-most Toplevel,
  803. /// <see cref="Application.RequestStop(Toplevel)"/> will be called, causing the application to exit.
  804. /// </summary>
  805. /// <param name="top">The toplevel to request stop.</param>
  806. public virtual void RequestStop (Toplevel top)
  807. {
  808. top.RequestStop ();
  809. }
  810. ///<inheritdoc/>
  811. public override void PositionCursor ()
  812. {
  813. if (!IsMdiContainer) {
  814. base.PositionCursor ();
  815. if (Focused == null) {
  816. EnsureFocus ();
  817. if (Focused == null) {
  818. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  819. }
  820. }
  821. return;
  822. }
  823. if (Focused == null) {
  824. foreach (var top in Application.MdiChildes) {
  825. if (top != this && top.Visible) {
  826. top.SetFocus ();
  827. return;
  828. }
  829. }
  830. }
  831. base.PositionCursor ();
  832. if (Focused == null) {
  833. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  834. }
  835. }
  836. /// <summary>
  837. /// Gets the current visible Toplevel Mdi child that matches the arguments pattern.
  838. /// </summary>
  839. /// <param name="type">The type.</param>
  840. /// <param name="exclude">The strings to exclude.</param>
  841. /// <returns>The matched view.</returns>
  842. public View GetTopMdiChild (Type type = null, string [] exclude = null)
  843. {
  844. if (Application.MdiTop == null) {
  845. return null;
  846. }
  847. foreach (var top in Application.MdiChildes) {
  848. if (type != null && top.GetType () == type
  849. && exclude?.Contains (top.Data.ToString ()) == false) {
  850. return top;
  851. } else if ((type != null && top.GetType () != type)
  852. || (exclude?.Contains (top.Data.ToString ()) == true)) {
  853. continue;
  854. }
  855. return top;
  856. }
  857. return null;
  858. }
  859. /// <summary>
  860. /// Shows the Mdi child indicated by <paramref name="top"/>, setting it as <see cref="Application.Current"/>.
  861. /// </summary>
  862. /// <param name="top">The Toplevel.</param>
  863. /// <returns><c>true</c> if the toplevel can be shown or <c>false</c> if not.</returns>
  864. public virtual bool ShowChild (Toplevel top = null)
  865. {
  866. if (Application.MdiTop != null) {
  867. return Application.ShowChild (top == null ? this : top);
  868. }
  869. return false;
  870. }
  871. ///<inheritdoc/>
  872. public override bool OnEnter (View view)
  873. {
  874. return MostFocused?.OnEnter (view) ?? base.OnEnter (view);
  875. }
  876. ///<inheritdoc/>
  877. public override bool OnLeave (View view)
  878. {
  879. return MostFocused?.OnLeave (view) ?? base.OnLeave (view);
  880. }
  881. ///<inheritdoc/>
  882. protected override void Dispose (bool disposing)
  883. {
  884. dragPosition = null;
  885. base.Dispose (disposing);
  886. }
  887. }
  888. /// <summary>
  889. /// Implements the <see cref="IEqualityComparer{T}"/> for comparing two <see cref="Toplevel"/>s
  890. /// used by <see cref="StackExtensions"/>.
  891. /// </summary>
  892. public class ToplevelEqualityComparer : IEqualityComparer<Toplevel> {
  893. /// <summary>Determines whether the specified objects are equal.</summary>
  894. /// <param name="x">The first object of type <see cref="Toplevel" /> to compare.</param>
  895. /// <param name="y">The second object of type <see cref="Toplevel" /> to compare.</param>
  896. /// <returns>
  897. /// <see langword="true" /> if the specified objects are equal; otherwise, <see langword="false" />.</returns>
  898. public bool Equals (Toplevel x, Toplevel y)
  899. {
  900. if (y == null && x == null)
  901. return true;
  902. else if (x == null || y == null)
  903. return false;
  904. else if (x.Id == y.Id)
  905. return true;
  906. else
  907. return false;
  908. }
  909. /// <summary>Returns a hash code for the specified object.</summary>
  910. /// <param name="obj">The <see cref="Toplevel" /> for which a hash code is to be returned.</param>
  911. /// <returns>A hash code for the specified object.</returns>
  912. /// <exception cref="ArgumentNullException">The type of <paramref name="obj" />
  913. /// is a reference type and <paramref name="obj" /> is <see langword="null" />.</exception>
  914. public int GetHashCode (Toplevel obj)
  915. {
  916. if (obj == null)
  917. throw new ArgumentNullException ();
  918. int hCode = 0;
  919. if (int.TryParse (obj.Id.ToString (), out int result)) {
  920. hCode = result;
  921. }
  922. return hCode.GetHashCode ();
  923. }
  924. }
  925. /// <summary>
  926. /// Implements the <see cref="IComparer{T}"/> to sort the <see cref="Toplevel"/>
  927. /// from the <see cref="Application.MdiChildes"/> if needed.
  928. /// </summary>
  929. public sealed class ToplevelComparer : IComparer<Toplevel> {
  930. /// <summary>Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.</summary>
  931. /// <param name="x">The first object to compare.</param>
  932. /// <param name="y">The second object to compare.</param>
  933. /// <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
  934. /// <paramref name="x" /> is less than <paramref name="y" />.Zero
  935. /// <paramref name="x" /> equals <paramref name="y" />.Greater than zero
  936. /// <paramref name="x" /> is greater than <paramref name="y" />.</returns>
  937. public int Compare (Toplevel x, Toplevel y)
  938. {
  939. if (ReferenceEquals (x, y))
  940. return 0;
  941. else if (x == null)
  942. return -1;
  943. else if (y == null)
  944. return 1;
  945. else
  946. return string.Compare (x.Id.ToString (), y.Id.ToString ());
  947. }
  948. }
  949. }