Toplevel.cs 31 KB

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