Toplevel.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032
  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. // This is the Application.Top. Clear just the region we're being asked to redraw
  608. // (the bounds passed to us).
  609. Clear ();
  610. Driver.SetAttribute (Enabled ? Colors.Base.Normal : Colors.Base.Disabled);
  611. LayoutSubviews ();
  612. PositionToplevels ();
  613. if (this == Application.MdiTop) {
  614. foreach (var top in Application.MdiChildes.AsEnumerable ().Reverse ()) {
  615. if (top.Frame.IntersectsWith (bounds)) {
  616. if (top != this && !top.IsCurrentTop && !OutsideTopFrame (top) && top.Visible) {
  617. top.SetNeedsLayout ();
  618. top.SetNeedsDisplay (top.Bounds);
  619. top.Redraw (top.Bounds);
  620. }
  621. }
  622. }
  623. }
  624. foreach (var view in Subviews) {
  625. if (view.Frame.IntersectsWith (bounds) && !OutsideTopFrame (this)) {
  626. view.SetNeedsLayout ();
  627. view.SetNeedsDisplay (view.Bounds);
  628. //view.Redraw (view.Bounds);
  629. }
  630. }
  631. ClearLayoutNeeded ();
  632. ClearNeedsDisplay ();
  633. }
  634. base.Redraw (Bounds);
  635. }
  636. bool OutsideTopFrame (Toplevel top)
  637. {
  638. if (top.Frame.X > Driver.Cols || top.Frame.Y > Driver.Rows) {
  639. return true;
  640. }
  641. return false;
  642. }
  643. //
  644. // FIXED:It does not look like the event is raised on clicked-drag
  645. // need to figure that out.
  646. //
  647. internal static Point? dragPosition;
  648. Point start;
  649. ///<inheritdoc/>
  650. public override bool MouseEvent (MouseEvent mouseEvent)
  651. {
  652. // FIXED:The code is currently disabled, because the
  653. // Driver.UncookMouse does not seem to have an effect if there is
  654. // a pending mouse event activated.
  655. if (!CanFocus) {
  656. return true;
  657. }
  658. int nx, ny;
  659. if (!dragPosition.HasValue && (mouseEvent.Flags == MouseFlags.Button1Pressed
  660. || mouseEvent.Flags == MouseFlags.Button2Pressed
  661. || mouseEvent.Flags == MouseFlags.Button3Pressed)) {
  662. SetFocus ();
  663. Application.EnsuresTopOnFront ();
  664. // Only start grabbing if the user clicks on the title bar.
  665. if (mouseEvent.Y == 0 && mouseEvent.Flags == MouseFlags.Button1Pressed) {
  666. start = new Point (mouseEvent.X, mouseEvent.Y);
  667. dragPosition = new Point ();
  668. nx = mouseEvent.X - mouseEvent.OfX;
  669. ny = mouseEvent.Y - mouseEvent.OfY;
  670. dragPosition = new Point (nx, ny);
  671. Application.GrabMouse (this);
  672. }
  673. //System.Diagnostics.Debug.WriteLine ($"Starting at {dragPosition}");
  674. return true;
  675. } else if (mouseEvent.Flags == (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) ||
  676. mouseEvent.Flags == MouseFlags.Button3Pressed) {
  677. if (dragPosition.HasValue) {
  678. if (SuperView == null) {
  679. // Redraw the entire app window using just our Frame. Since we are
  680. // Application.Top, and our Frame always == our Bounds (Location is always (0,0))
  681. // our Frame is actually view-relative (which is what Redraw takes).
  682. // We need to pass all the view bounds because since the windows was
  683. // moved around, we don't know exactly what was the affected region.
  684. Application.Top.SetNeedsDisplay ();
  685. } else {
  686. SuperView.SetNeedsDisplay ();
  687. }
  688. EnsureVisibleBounds (this, mouseEvent.X + (SuperView == null ? mouseEvent.OfX - start.X : Frame.X - start.X),
  689. mouseEvent.Y + (SuperView == null ? mouseEvent.OfY : Frame.Y),
  690. out nx, out ny, out _, out _);
  691. dragPosition = new Point (nx, ny);
  692. LayoutSubviews ();
  693. Frame = new Rect (nx, ny, Frame.Width, Frame.Height);
  694. if (X == null || X is Pos.PosAbsolute) {
  695. X = nx;
  696. }
  697. if (Y == null || Y is Pos.PosAbsolute) {
  698. Y = ny;
  699. }
  700. //System.Diagnostics.Debug.WriteLine ($"nx:{nx},ny:{ny}");
  701. // FIXED: optimize, only SetNeedsDisplay on the before/after regions.
  702. SetNeedsDisplay ();
  703. return true;
  704. }
  705. }
  706. if (mouseEvent.Flags == MouseFlags.Button1Released && dragPosition.HasValue) {
  707. Application.UngrabMouse ();
  708. Driver.UncookMouse ();
  709. dragPosition = null;
  710. }
  711. //System.Diagnostics.Debug.WriteLine (mouseEvent.ToString ());
  712. return false;
  713. }
  714. /// <summary>
  715. /// Invoked by <see cref="Application.Begin"/> as part of the <see cref="Application.Run(Toplevel, Func{Exception, bool})"/> after
  716. /// the views have been laid out, and before the views are drawn for the first time.
  717. /// </summary>
  718. public virtual void WillPresent ()
  719. {
  720. FocusFirst ();
  721. }
  722. /// <summary>
  723. /// Move to the next Mdi child from the <see cref="Application.MdiTop"/>.
  724. /// </summary>
  725. public virtual void MoveNext ()
  726. {
  727. Application.MoveNext ();
  728. }
  729. /// <summary>
  730. /// Move to the previous Mdi child from the <see cref="Application.MdiTop"/>.
  731. /// </summary>
  732. public virtual void MovePrevious ()
  733. {
  734. Application.MovePrevious ();
  735. }
  736. /// <summary>
  737. /// Stops running this <see cref="Toplevel"/>.
  738. /// </summary>
  739. public virtual void RequestStop ()
  740. {
  741. if (IsMdiContainer && Running
  742. && (Application.Current == this
  743. || Application.Current?.Modal == false
  744. || Application.Current?.Modal == true && Application.Current?.Running == false)) {
  745. foreach (var child in Application.MdiChildes) {
  746. var ev = new ToplevelClosingEventArgs (this);
  747. if (child.OnClosing (ev)) {
  748. return;
  749. }
  750. child.Running = false;
  751. Application.RequestStop (child);
  752. }
  753. Running = false;
  754. Application.RequestStop (this);
  755. } else if (IsMdiContainer && Running && Application.Current?.Modal == true && Application.Current?.Running == true) {
  756. var ev = new ToplevelClosingEventArgs (Application.Current);
  757. if (OnClosing (ev)) {
  758. return;
  759. }
  760. Application.RequestStop (Application.Current);
  761. } else if (!IsMdiContainer && Running && (!Modal || (Modal && Application.Current != this))) {
  762. var ev = new ToplevelClosingEventArgs (this);
  763. if (OnClosing (ev)) {
  764. return;
  765. }
  766. Running = false;
  767. Application.RequestStop (this);
  768. } else {
  769. Application.RequestStop (Application.Current);
  770. }
  771. }
  772. /// <summary>
  773. /// Stops running the <paramref name="top"/> <see cref="Toplevel"/>.
  774. /// </summary>
  775. /// <param name="top">The toplevel to request stop.</param>
  776. public virtual void RequestStop (Toplevel top)
  777. {
  778. top.RequestStop ();
  779. }
  780. ///<inheritdoc/>
  781. public override void PositionCursor ()
  782. {
  783. if (!IsMdiContainer) {
  784. base.PositionCursor ();
  785. return;
  786. }
  787. if (Focused == null) {
  788. foreach (var top in Application.MdiChildes) {
  789. if (top != this && top.Visible) {
  790. top.SetFocus ();
  791. return;
  792. }
  793. }
  794. }
  795. base.PositionCursor ();
  796. }
  797. /// <summary>
  798. /// Gets the current visible toplevel Mdi child that match the arguments pattern.
  799. /// </summary>
  800. /// <param name="type">The type.</param>
  801. /// <param name="exclude">The strings to exclude.</param>
  802. /// <returns>The matched view.</returns>
  803. public View GetTopMdiChild (Type type = null, string [] exclude = null)
  804. {
  805. if (Application.MdiTop == null) {
  806. return null;
  807. }
  808. foreach (var top in Application.MdiChildes) {
  809. if (type != null && top.GetType () == type
  810. && exclude?.Contains (top.Data.ToString ()) == false) {
  811. return top;
  812. } else if ((type != null && top.GetType () != type)
  813. || (exclude?.Contains (top.Data.ToString ()) == true)) {
  814. continue;
  815. }
  816. return top;
  817. }
  818. return null;
  819. }
  820. /// <summary>
  821. /// Shows the Mdi child indicated by the <paramref name="top"/> setting as <see cref="Application.Current"/>.
  822. /// </summary>
  823. /// <param name="top">The toplevel.</param>
  824. /// <returns><see langword="true"/> if the toplevel can be showed.<see langword="false"/> otherwise.</returns>
  825. public virtual bool ShowChild (Toplevel top = null)
  826. {
  827. if (Application.MdiTop != null) {
  828. return Application.ShowChild (top == null ? this : top);
  829. }
  830. return false;
  831. }
  832. }
  833. /// <summary>
  834. /// Implements the <see cref="IEqualityComparer{T}"/> to comparing two <see cref="Toplevel"/> used by <see cref="StackExtensions"/>.
  835. /// </summary>
  836. public class ToplevelEqualityComparer : IEqualityComparer<Toplevel> {
  837. /// <summary>Determines whether the specified objects are equal.</summary>
  838. /// <param name="x">The first object of type <see cref="Toplevel" /> to compare.</param>
  839. /// <param name="y">The second object of type <see cref="Toplevel" /> to compare.</param>
  840. /// <returns>
  841. /// <see langword="true" /> if the specified objects are equal; otherwise, <see langword="false" />.</returns>
  842. public bool Equals (Toplevel x, Toplevel y)
  843. {
  844. if (y == null && x == null)
  845. return true;
  846. else if (x == null || y == null)
  847. return false;
  848. else if (x.Id == y.Id)
  849. return true;
  850. else
  851. return false;
  852. }
  853. /// <summary>Returns a hash code for the specified object.</summary>
  854. /// <param name="obj">The <see cref="Toplevel" /> for which a hash code is to be returned.</param>
  855. /// <returns>A hash code for the specified object.</returns>
  856. /// <exception cref="ArgumentNullException">The type of <paramref name="obj" /> is a reference type and <paramref name="obj" /> is <see langword="null" />.</exception>
  857. public int GetHashCode (Toplevel obj)
  858. {
  859. if (obj == null)
  860. throw new ArgumentNullException ();
  861. int hCode = 0;
  862. if (int.TryParse (obj.Id.ToString (), out int result)) {
  863. hCode = result;
  864. }
  865. return hCode.GetHashCode ();
  866. }
  867. }
  868. /// <summary>
  869. /// Implements the <see cref="IComparer{T}"/> to sort the <see cref="Toplevel"/> from the <see cref="Application.MdiChildes"/> if needed.
  870. /// </summary>
  871. public sealed class ToplevelComparer : IComparer<Toplevel> {
  872. /// <summary>Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.</summary>
  873. /// <param name="x">The first object to compare.</param>
  874. /// <param name="y">The second object to compare.</param>
  875. /// <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
  876. /// <paramref name="x" /> is less than <paramref name="y" />.Zero
  877. /// <paramref name="x" /> equals <paramref name="y" />.Greater than zero
  878. /// <paramref name="x" /> is greater than <paramref name="y" />.</returns>
  879. public int Compare (Toplevel x, Toplevel y)
  880. {
  881. if (ReferenceEquals (x, y))
  882. return 0;
  883. else if (x == null)
  884. return -1;
  885. else if (y == null)
  886. return 1;
  887. else
  888. return string.Compare (x.Id.ToString (), y.Id.ToString ());
  889. }
  890. }
  891. /// <summary>
  892. /// <see cref="EventArgs"/> implementation for the <see cref="Toplevel.Closing"/> event.
  893. /// </summary>
  894. public class ToplevelClosingEventArgs : EventArgs {
  895. /// <summary>
  896. /// The toplevel requesting stop.
  897. /// </summary>
  898. public View RequestingTop { get; }
  899. /// <summary>
  900. /// Provides an event cancellation option.
  901. /// </summary>
  902. public bool Cancel { get; set; }
  903. /// <summary>
  904. /// Initializes the event arguments with the requesting toplevel.
  905. /// </summary>
  906. /// <param name="requestingTop">The <see cref="RequestingTop"/>.</param>
  907. public ToplevelClosingEventArgs (Toplevel requestingTop)
  908. {
  909. RequestingTop = requestingTop;
  910. }
  911. }
  912. }