Toplevel.cs 32 KB

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