Toplevel.cs 31 KB

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