Toplevel.cs 31 KB

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