Toplevel.cs 33 KB

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