Toplevel.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  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 partial 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 <see cref="Toplevel"/> <see cref="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(RunState)"/>.
  35. /// </summary>
  36. public event EventHandler Loaded;
  37. /// <summary>
  38. /// Invoked when the <see cref="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 <see cref="Toplevel"/>.</para>
  43. /// </summary>
  44. public event EventHandler Ready;
  45. /// <summary>
  46. /// Invoked when the Toplevel <see cref="RunState"/> has been unloaded.
  47. /// A Unloaded event handler is a good place to dispose objects after calling <see cref="Application.End(RunState)"/>.
  48. /// </summary>
  49. public event EventHandler Unloaded;
  50. /// <summary>
  51. /// Invoked when the Toplevel <see cref="RunState"/> becomes the <see cref="Application.Current"/> Toplevel.
  52. /// </summary>
  53. public event EventHandler<ToplevelEventArgs> Activate;
  54. /// <summary>
  55. /// Invoked when the Toplevel<see cref="RunState"/> ceases to be the <see cref="Application.Current"/> Toplevel.
  56. /// </summary>
  57. public event EventHandler<ToplevelEventArgs> Deactivate;
  58. /// <summary>
  59. /// Invoked when a child of the Toplevel <see cref="RunState"/> is closed by
  60. /// <see cref="Application.End(RunState)"/>.
  61. /// </summary>
  62. public event EventHandler<ToplevelEventArgs> ChildClosed;
  63. /// <summary>
  64. /// Invoked when the last child of the Toplevel <see cref="RunState"/> is closed from
  65. /// by <see cref="Application.End(RunState)"/>.
  66. /// </summary>
  67. public event EventHandler AllChildClosed;
  68. /// <summary>
  69. /// Invoked when the Toplevel's <see cref="RunState"/> is being closed by
  70. /// <see cref="Application.RequestStop(Toplevel)"/>.
  71. /// </summary>
  72. public event EventHandler<ToplevelClosingEventArgs> Closing;
  73. /// <summary>
  74. /// Invoked when the Toplevel's <see cref="RunState"/> is closed by <see cref="Application.End(RunState)"/>.
  75. /// </summary>
  76. public event EventHandler<ToplevelEventArgs> Closed;
  77. /// <summary>
  78. /// Invoked when a child Toplevel's <see cref="RunState"/> has been loaded.
  79. /// </summary>
  80. public event EventHandler<ToplevelEventArgs> ChildLoaded;
  81. /// <summary>
  82. /// Invoked when a cjhild Toplevel's <see cref="RunState"/> has been unloaded.
  83. /// </summary>
  84. public event EventHandler<ToplevelEventArgs> 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 EventHandler<SizeChangedEventArgs> TerminalResized;
  89. internal virtual void OnTerminalResized (SizeChangedEventArgs size)
  90. {
  91. TerminalResized?.Invoke (this, size);
  92. }
  93. internal virtual void OnChildUnloaded (Toplevel top)
  94. {
  95. ChildUnloaded?.Invoke (this, new ToplevelEventArgs (top));
  96. }
  97. internal virtual void OnChildLoaded (Toplevel top)
  98. {
  99. ChildLoaded?.Invoke (this, new ToplevelEventArgs (top));
  100. }
  101. internal virtual void OnClosed (Toplevel top)
  102. {
  103. Closed?.Invoke (this, new ToplevelEventArgs (top));
  104. }
  105. internal virtual bool OnClosing (ToplevelClosingEventArgs ev)
  106. {
  107. Closing?.Invoke (this, ev);
  108. return ev.Cancel;
  109. }
  110. internal virtual void OnAllChildClosed ()
  111. {
  112. AllChildClosed?.Invoke (this, EventArgs.Empty);
  113. }
  114. internal virtual void OnChildClosed (Toplevel top)
  115. {
  116. if (IsOverlappedContainer) {
  117. SetSubViewNeedsDisplay ();
  118. }
  119. ChildClosed?.Invoke (this, new ToplevelEventArgs (top));
  120. }
  121. internal virtual void OnDeactivate (Toplevel activated)
  122. {
  123. Deactivate?.Invoke (this, new ToplevelEventArgs (activated));
  124. }
  125. internal virtual void OnActivate (Toplevel deactivated)
  126. {
  127. Activate?.Invoke (this, new ToplevelEventArgs (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 (this, EventArgs.Empty);
  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 (this, EventArgs.Empty);
  150. }
  151. /// <summary>
  152. /// Called from <see cref="Application.End(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 (this, EventArgs.Empty);
  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. SetInitialProperties ();
  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. SetInitialProperties ();
  176. Width = Dim.Fill ();
  177. Height = Dim.Fill ();
  178. }
  179. void SetInitialProperties ()
  180. {
  181. ColorScheme = Colors.TopLevel;
  182. Application.GrabbingMouse += Application_GrabbingMouse;
  183. Application.UnGrabbingMouse += Application_UnGrabbingMouse;
  184. // TODO: v2 - ALL Views (Responders??!?!) should support the commands related to
  185. // - Focus
  186. // Move the appropriate AddCommand calls to `Responder`
  187. // Things this view knows how to do
  188. AddCommand (Command.QuitToplevel, () => { QuitToplevel (); return true; });
  189. AddCommand (Command.Suspend, () => { Driver.Suspend (); ; return true; });
  190. AddCommand (Command.NextView, () => { MoveNextView (); return true; });
  191. AddCommand (Command.PreviousView, () => { MovePreviousView (); return true; });
  192. AddCommand (Command.NextViewOrTop, () => { MoveNextViewOrTop (); return true; });
  193. AddCommand (Command.PreviousViewOrTop, () => { MovePreviousViewOrTop (); return true; });
  194. AddCommand (Command.Refresh, () => { Application.Refresh (); return true; });
  195. // Default keybindings for this view
  196. AddKeyBinding (Application.QuitKey, Command.QuitToplevel);
  197. AddKeyBinding (Key.Z | Key.CtrlMask, Command.Suspend);
  198. AddKeyBinding (Key.Tab, Command.NextView);
  199. AddKeyBinding (Key.CursorRight, Command.NextView);
  200. AddKeyBinding (Key.F | Key.CtrlMask, Command.NextView);
  201. AddKeyBinding (Key.CursorDown, Command.NextView);
  202. AddKeyBinding (Key.I | Key.CtrlMask, Command.NextView); // Unix
  203. AddKeyBinding (Key.BackTab | Key.ShiftMask, Command.PreviousView);
  204. AddKeyBinding (Key.CursorLeft, Command.PreviousView);
  205. AddKeyBinding (Key.CursorUp, Command.PreviousView);
  206. AddKeyBinding (Key.B | Key.CtrlMask, Command.PreviousView);
  207. AddKeyBinding (Key.Tab | Key.CtrlMask, Command.NextViewOrTop);
  208. AddKeyBinding (Application.AlternateForwardKey, Command.NextViewOrTop); // Needed on Unix
  209. AddKeyBinding (Key.Tab | Key.ShiftMask | Key.CtrlMask, Command.PreviousViewOrTop);
  210. AddKeyBinding (Application.AlternateBackwardKey, Command.PreviousViewOrTop); // Needed on Unix
  211. AddKeyBinding (Key.L | Key.CtrlMask, Command.Refresh);
  212. }
  213. private void Application_UnGrabbingMouse (object sender, GrabMouseEventArgs e)
  214. {
  215. if (Application.MouseGrabView == this && _dragPosition.HasValue) {
  216. e.Cancel = true;
  217. }
  218. }
  219. private void Application_GrabbingMouse (object sender, GrabMouseEventArgs e)
  220. {
  221. if (Application.MouseGrabView == this && _dragPosition.HasValue) {
  222. e.Cancel = true;
  223. }
  224. }
  225. /// <summary>
  226. /// Invoked when the <see cref="Application.AlternateForwardKey"/> is changed.
  227. /// </summary>
  228. public event EventHandler<KeyChangedEventArgs> AlternateForwardKeyChanged;
  229. /// <summary>
  230. /// Virtual method to invoke the <see cref="AlternateForwardKeyChanged"/> event.
  231. /// </summary>
  232. /// <param name="e"></param>
  233. public virtual void OnAlternateForwardKeyChanged (KeyChangedEventArgs e)
  234. {
  235. ReplaceKeyBinding (e.OldKey, e.NewKey);
  236. AlternateForwardKeyChanged?.Invoke (this, e);
  237. }
  238. /// <summary>
  239. /// Invoked when the <see cref="Application.AlternateBackwardKey"/> is changed.
  240. /// </summary>
  241. public event EventHandler<KeyChangedEventArgs> AlternateBackwardKeyChanged;
  242. /// <summary>
  243. /// Virtual method to invoke the <see cref="AlternateBackwardKeyChanged"/> event.
  244. /// </summary>
  245. /// <param name="e"></param>
  246. public virtual void OnAlternateBackwardKeyChanged (KeyChangedEventArgs e)
  247. {
  248. ReplaceKeyBinding (e.OldKey, e.NewKey);
  249. AlternateBackwardKeyChanged?.Invoke (this, e);
  250. }
  251. /// <summary>
  252. /// Invoked when the <see cref="Application.QuitKey"/> is changed.
  253. /// </summary>
  254. public event EventHandler<KeyChangedEventArgs> QuitKeyChanged;
  255. /// <summary>
  256. /// Virtual method to invoke the <see cref="QuitKeyChanged"/> event.
  257. /// </summary>
  258. /// <param name="e"></param>
  259. public virtual void OnQuitKeyChanged (KeyChangedEventArgs e)
  260. {
  261. ReplaceKeyBinding (e.OldKey, e.NewKey);
  262. QuitKeyChanged?.Invoke (this, e);
  263. }
  264. /// <summary>
  265. /// Convenience factory method that creates a new Toplevel with the current terminal dimensions.
  266. /// </summary>
  267. /// <returns>The created Toplevel.</returns>
  268. public static Toplevel Create ()
  269. {
  270. return new Toplevel (new Rect (0, 0, Driver.Cols, Driver.Rows));
  271. }
  272. /// <summary>
  273. /// Gets or sets a value indicating whether this <see cref="Toplevel"/> can focus.
  274. /// </summary>
  275. /// <value><c>true</c> if can focus; otherwise, <c>false</c>.</value>
  276. public override bool CanFocus {
  277. get => SuperView == null ? true : base.CanFocus;
  278. }
  279. /// <summary>
  280. /// Determines whether the <see cref="Toplevel"/> is modal or not.
  281. /// If set to <c>false</c> (the default):
  282. ///
  283. /// <list type="bullet">
  284. /// <item>
  285. /// <description><see cref="ProcessKey(KeyEvent)"/> events will propagate keys upwards.</description>
  286. /// </item>
  287. /// <item>
  288. /// <description>The Toplevel will act as an embedded view (not a modal/pop-up).</description>
  289. /// </item>
  290. /// </list>
  291. ///
  292. /// If set to <c>true</c>:
  293. ///
  294. /// <list type="bullet">
  295. /// <item>
  296. /// <description><see cref="ProcessKey(KeyEvent)"/> events will NOT propogate keys upwards.</description>
  297. /// </item>
  298. /// <item>
  299. /// <description>The Toplevel will and look like a modal (pop-up) (e.g. see <see cref="Dialog"/>.</description>
  300. /// </item>
  301. /// </list>
  302. /// </summary>
  303. public bool Modal { get; set; }
  304. /// <summary>
  305. /// Gets or sets the menu for this Toplevel.
  306. /// </summary>
  307. public virtual MenuBar MenuBar { get; set; }
  308. /// <summary>
  309. /// Gets or sets the status bar for this Toplevel.
  310. /// </summary>
  311. public virtual StatusBar StatusBar { get; set; }
  312. /// <summary>
  313. /// <see langword="true"/> if was already loaded by the <see cref="Application.Begin(Toplevel)"/>
  314. /// <see langword="false"/>, otherwise.
  315. /// </summary>
  316. public bool IsLoaded { get; private set; }
  317. ///<inheritdoc/>
  318. public override bool OnKeyDown (KeyEvent keyEvent)
  319. {
  320. if (base.OnKeyDown (keyEvent)) {
  321. return true;
  322. }
  323. switch (keyEvent.Key) {
  324. case Key.AltMask:
  325. case Key.AltMask | Key.Space:
  326. case Key.CtrlMask | Key.Space:
  327. case Key _ when (keyEvent.Key & Key.AltMask) == Key.AltMask:
  328. return MenuBar != null && MenuBar.OnKeyDown (keyEvent);
  329. }
  330. return false;
  331. }
  332. ///<inheritdoc/>
  333. public override bool OnKeyUp (KeyEvent keyEvent)
  334. {
  335. if (base.OnKeyUp (keyEvent)) {
  336. return true;
  337. }
  338. switch (keyEvent.Key) {
  339. case Key.AltMask:
  340. case Key.AltMask | Key.Space:
  341. case Key.CtrlMask | Key.Space:
  342. if (MenuBar != null && MenuBar.OnKeyUp (keyEvent)) {
  343. return true;
  344. }
  345. break;
  346. }
  347. return false;
  348. }
  349. ///<inheritdoc/>
  350. public override bool ProcessKey (KeyEvent keyEvent)
  351. {
  352. if (base.ProcessKey (keyEvent))
  353. return true;
  354. var result = InvokeKeybindings (new KeyEvent (ShortcutHelper.GetModifiersKey (keyEvent),
  355. new KeyModifiers () { Alt = keyEvent.IsAlt, Ctrl = keyEvent.IsCtrl, Shift = keyEvent.IsShift }));
  356. if (result != null)
  357. return (bool)result;
  358. #if false
  359. if (keyEvent.Key == Key.F5) {
  360. Application.DebugDrawBounds = !Application.DebugDrawBounds;
  361. SetNeedsDisplay ();
  362. return true;
  363. }
  364. #endif
  365. return false;
  366. }
  367. private void MovePreviousViewOrTop ()
  368. {
  369. if (Application.OverlappedTop == null) {
  370. var top = Modal ? this : Application.Top;
  371. top.FocusPrev ();
  372. if (top.Focused == null) {
  373. top.FocusPrev ();
  374. }
  375. top.SetNeedsDisplay ();
  376. Application.BringOverlappedTopToFront ();
  377. } else {
  378. Application.OverlappedMovePrevious ();
  379. }
  380. }
  381. private void MoveNextViewOrTop ()
  382. {
  383. if (Application.OverlappedTop == null) {
  384. var top = Modal ? this : Application.Top;
  385. top.FocusNext ();
  386. if (top.Focused == null) {
  387. top.FocusNext ();
  388. }
  389. top.SetNeedsDisplay ();
  390. Application.BringOverlappedTopToFront ();
  391. } else {
  392. Application.OverlappedMoveNext ();
  393. }
  394. }
  395. private void MovePreviousView ()
  396. {
  397. var old = GetDeepestFocusedSubview (Focused);
  398. if (!FocusPrev ())
  399. FocusPrev ();
  400. if (old != Focused && old != Focused?.Focused) {
  401. old?.SetNeedsDisplay ();
  402. Focused?.SetNeedsDisplay ();
  403. } else {
  404. FocusNearestView (SuperView?.TabIndexes?.Reverse (), Direction.Backward);
  405. }
  406. }
  407. private void MoveNextView ()
  408. {
  409. var old = GetDeepestFocusedSubview (Focused);
  410. if (!FocusNext ())
  411. FocusNext ();
  412. if (old != Focused && old != Focused?.Focused) {
  413. old?.SetNeedsDisplay ();
  414. Focused?.SetNeedsDisplay ();
  415. } else {
  416. FocusNearestView (SuperView?.TabIndexes, Direction.Forward);
  417. }
  418. }
  419. private void QuitToplevel ()
  420. {
  421. if (Application.OverlappedTop != null) {
  422. Application.OverlappedTop.RequestStop ();
  423. } else {
  424. Application.RequestStop ();
  425. }
  426. }
  427. ///<inheritdoc/>
  428. public override bool ProcessColdKey (KeyEvent keyEvent)
  429. {
  430. if (base.ProcessColdKey (keyEvent)) {
  431. return true;
  432. }
  433. if (ShortcutHelper.FindAndOpenByShortcut (keyEvent, this)) {
  434. return true;
  435. }
  436. return false;
  437. }
  438. View GetDeepestFocusedSubview (View view)
  439. {
  440. if (view == null) {
  441. return null;
  442. }
  443. foreach (var v in view.Subviews) {
  444. if (v.HasFocus) {
  445. return GetDeepestFocusedSubview (v);
  446. }
  447. }
  448. return view;
  449. }
  450. void FocusNearestView (IEnumerable<View> views, Direction direction)
  451. {
  452. if (views == null) {
  453. return;
  454. }
  455. bool found = false;
  456. bool focusProcessed = false;
  457. int idx = 0;
  458. foreach (var v in views) {
  459. if (v == this) {
  460. found = true;
  461. }
  462. if (found && v != this) {
  463. if (direction == Direction.Forward) {
  464. SuperView?.FocusNext ();
  465. } else {
  466. SuperView?.FocusPrev ();
  467. }
  468. focusProcessed = true;
  469. if (SuperView.Focused != null && SuperView.Focused != this) {
  470. return;
  471. }
  472. } else if (found && !focusProcessed && idx == views.Count () - 1) {
  473. views.ToList () [0].SetFocus ();
  474. }
  475. idx++;
  476. }
  477. }
  478. ///<inheritdoc/>
  479. public override void Add (View view)
  480. {
  481. CanFocus = true;
  482. AddMenuStatusBar (view);
  483. base.Add (view);
  484. }
  485. internal void AddMenuStatusBar (View view)
  486. {
  487. if (view is MenuBar) {
  488. MenuBar = view as MenuBar;
  489. }
  490. if (view is StatusBar) {
  491. StatusBar = view as StatusBar;
  492. }
  493. }
  494. ///<inheritdoc/>
  495. public override void Remove (View view)
  496. {
  497. if (this is Toplevel Toplevel && Toplevel.MenuBar != null) {
  498. RemoveMenuStatusBar (view);
  499. }
  500. base.Remove (view);
  501. }
  502. ///<inheritdoc/>
  503. public override void RemoveAll ()
  504. {
  505. if (this == Application.Top) {
  506. MenuBar?.Dispose ();
  507. MenuBar = null;
  508. StatusBar?.Dispose ();
  509. StatusBar = null;
  510. }
  511. base.RemoveAll ();
  512. }
  513. internal void RemoveMenuStatusBar (View view)
  514. {
  515. if (view is MenuBar) {
  516. MenuBar?.Dispose ();
  517. MenuBar = null;
  518. }
  519. if (view is StatusBar) {
  520. StatusBar?.Dispose ();
  521. StatusBar = null;
  522. }
  523. }
  524. /// <summary>
  525. /// Gets a new location of the <see cref="Toplevel"/> that is within the Bounds of the <paramref name="top"/>'s
  526. /// <see cref="View.SuperView"/> (e.g. for dragging a Window).
  527. /// The `out` parameters are the new X and Y coordinates.
  528. /// </summary>
  529. /// <remarks>
  530. /// If <paramref name="top"/> does not have a <see cref="View.SuperView"/> or it's SuperView is not <see cref="Application.Top"/>
  531. /// the position will be bound by the <see cref="ConsoleDriver.Cols"/> and <see cref="ConsoleDriver.Rows"/>.
  532. /// </remarks>
  533. /// <param name="top">The Toplevel that is to be moved.</param>
  534. /// <param name="targetX">The target x location.</param>
  535. /// <param name="targetY">The target y location.</param>
  536. /// <param name="nx">The x location that will ensure <paramref name="top"/> will be visible.</param>
  537. /// <param name="ny">The y location that will ensure <paramref name="top"/> will be visible.</param>
  538. /// <param name="menuBar">The new top most menuBar</param>
  539. /// <param name="statusBar">The new top most statusBar</param>
  540. /// <returns>
  541. /// Either <see cref="Application.Top"/> (if <paramref name="top"/> does not have a Super View) or
  542. /// <paramref name="top"/>'s SuperView. This can be used to ensure LayoutSubviews is called on the correct View.
  543. /// </returns>
  544. internal View GetLocationThatFits (Toplevel top, int targetX, int targetY,
  545. out int nx, out int ny, out MenuBar menuBar, out StatusBar statusBar)
  546. {
  547. int maxWidth;
  548. View superView;
  549. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  550. maxWidth = Driver.Cols;
  551. superView = Application.Top;
  552. } else {
  553. // Use the SuperView's Bounds, not Frame
  554. maxWidth = top.SuperView.Bounds.Width;
  555. superView = top.SuperView;
  556. }
  557. if (superView.Margin != null && superView == top.SuperView) {
  558. maxWidth -= superView.GetFramesThickness ().Left + superView.GetFramesThickness ().Right;
  559. }
  560. if (top.Frame.Width <= maxWidth) {
  561. nx = Math.Max (targetX, 0);
  562. nx = nx + top.Frame.Width > maxWidth ? Math.Max (maxWidth - top.Frame.Width, 0) : nx;
  563. if (nx > top.Frame.X + top.Frame.Width) {
  564. nx = Math.Max (top.Frame.Right, 0);
  565. }
  566. } else {
  567. nx = targetX;
  568. }
  569. //System.Diagnostics.Debug.WriteLine ($"nx:{nx}, rWidth:{rWidth}");
  570. bool menuVisible, statusVisible;
  571. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  572. menuVisible = Application.Top.MenuBar?.Visible == true;
  573. menuBar = Application.Top.MenuBar;
  574. } else {
  575. var t = top.SuperView;
  576. while (t is not Toplevel) {
  577. t = t.SuperView;
  578. }
  579. menuVisible = ((Toplevel)t).MenuBar?.Visible == true;
  580. menuBar = ((Toplevel)t).MenuBar;
  581. }
  582. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  583. maxWidth = menuVisible ? 1 : 0;
  584. } else {
  585. maxWidth = 0;
  586. }
  587. ny = Math.Max (targetY, maxWidth);
  588. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  589. statusVisible = Application.Top.StatusBar?.Visible == true;
  590. statusBar = Application.Top.StatusBar;
  591. } else {
  592. var t = top.SuperView;
  593. while (t is not Toplevel) {
  594. t = t.SuperView;
  595. }
  596. statusVisible = ((Toplevel)t).StatusBar?.Visible == true;
  597. statusBar = ((Toplevel)t).StatusBar;
  598. }
  599. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  600. maxWidth = statusVisible ? Driver.Rows - 1 : Driver.Rows;
  601. } else {
  602. maxWidth = statusVisible ? top.SuperView.Frame.Height - 1 : top.SuperView.Frame.Height;
  603. }
  604. if (superView.Margin != null && superView == top.SuperView) {
  605. maxWidth -= superView.GetFramesThickness ().Top + superView.GetFramesThickness ().Bottom;
  606. }
  607. ny = Math.Min (ny, maxWidth);
  608. if (top.Frame.Height <= maxWidth) {
  609. ny = ny + top.Frame.Height > maxWidth ? Math.Max (maxWidth - top.Frame.Height, menuVisible ? 1 : 0) : ny;
  610. if (ny > top.Frame.Y + top.Frame.Height) {
  611. ny = Math.Max (top.Frame.Bottom, 0);
  612. }
  613. }
  614. //System.Diagnostics.Debug.WriteLine ($"ny:{ny}, rHeight:{rHeight}");
  615. return superView;
  616. }
  617. // TODO: v2 - Not sure this is needed anymore.
  618. internal void PositionToplevels ()
  619. {
  620. PositionToplevel (this);
  621. foreach (var top in Subviews) {
  622. if (top is Toplevel) {
  623. PositionToplevel ((Toplevel)top);
  624. }
  625. }
  626. }
  627. /// <summary>
  628. /// Adjusts the location and size of <paramref name="top"/> within this Toplevel.
  629. /// Virtual method enabling implementation of specific positions for inherited <see cref="Toplevel"/> views.
  630. /// </summary>
  631. /// <param name="top">The Toplevel to adjust.</param>
  632. public virtual void PositionToplevel (Toplevel top)
  633. {
  634. var superView = GetLocationThatFits (top, top.Frame.X, top.Frame.Y,
  635. out int nx, out int ny, out _, out StatusBar sb);
  636. bool layoutSubviews = false;
  637. var maxWidth = 0;
  638. if (superView.Margin != null && superView == top.SuperView) {
  639. maxWidth -= superView.GetFramesThickness ().Left + superView.GetFramesThickness ().Right;
  640. }
  641. if ((superView != top || top?.SuperView != null || (top != Application.Top && top.Modal)
  642. || (top?.SuperView == null && top.IsOverlapped))
  643. && (top.Frame.X + top.Frame.Width > maxWidth || ny > top.Frame.Y) && top.LayoutStyle == LayoutStyle.Computed) {
  644. if ((top.X == null || top.X is Pos.PosAbsolute) && top.Frame.X != nx) {
  645. top.X = nx;
  646. layoutSubviews = true;
  647. }
  648. if ((top.Y == null || top.Y is Pos.PosAbsolute) && top.Frame.Y != ny) {
  649. top.Y = ny;
  650. layoutSubviews = true;
  651. }
  652. }
  653. // TODO: v2 - This is a hack to get the StatusBar to be positioned correctly.
  654. if (sb != null && !top.Subviews.Contains (sb) && ny + top.Frame.Height != superView.Frame.Height - (sb.Visible ? 1 : 0)
  655. && top.Height is Dim.DimFill && -top.Height.Anchor (0) < 1) {
  656. top.Height = Dim.Fill (sb.Visible ? 1 : 0);
  657. layoutSubviews = true;
  658. }
  659. if (superView.LayoutNeeded || layoutSubviews) {
  660. superView.LayoutSubviews ();
  661. }
  662. if (LayoutNeeded) {
  663. LayoutSubviews ();
  664. }
  665. }
  666. ///<inheritdoc/>
  667. public override void OnDrawContent (Rect contentArea)
  668. {
  669. if (!Visible) {
  670. return;
  671. }
  672. if (NeedsDisplay || SubViewNeedsDisplay || LayoutNeeded) {
  673. //Driver.SetAttribute (GetNormalColor ());
  674. // TODO: It's bad practice for views to always clear. Defeats the purpose of clipping etc...
  675. Clear ();
  676. LayoutSubviews ();
  677. PositionToplevels ();
  678. if (this == Application.OverlappedTop) {
  679. foreach (var top in Application.OverlappedChildren.AsEnumerable ().Reverse ()) {
  680. if (top.Frame.IntersectsWith (Bounds)) {
  681. if (top != this && !top.IsCurrentTop && !OutsideTopFrame (top) && top.Visible) {
  682. top.SetNeedsLayout ();
  683. top.SetNeedsDisplay (top.Bounds);
  684. top.Draw ();
  685. top.OnRenderLineCanvas ();
  686. }
  687. }
  688. }
  689. }
  690. // This should not be here, but in base
  691. foreach (var view in Subviews) {
  692. if (view.Frame.IntersectsWith (Bounds) && !OutsideTopFrame (this)) {
  693. //view.SetNeedsLayout ();
  694. view.SetNeedsDisplay (view.Bounds);
  695. view.SetSubViewNeedsDisplay ();
  696. }
  697. }
  698. base.OnDrawContent (contentArea);
  699. // This is causing the menus drawn incorrectly if UseSubMenusSingleFrame is true
  700. //if (this.MenuBar != null && this.MenuBar.IsMenuOpen && this.MenuBar.openMenu != null) {
  701. // // TODO: Hack until we can get compositing working right.
  702. // this.MenuBar.openMenu.Redraw (this.MenuBar.openMenu.Bounds);
  703. //}
  704. }
  705. }
  706. bool OutsideTopFrame (Toplevel top)
  707. {
  708. if (top.Frame.X > Driver.Cols || top.Frame.Y > Driver.Rows) {
  709. return true;
  710. }
  711. return false;
  712. }
  713. internal static Point? _dragPosition;
  714. Point _startGrabPoint;
  715. ///<inheritdoc/>
  716. public override bool MouseEvent (MouseEvent mouseEvent)
  717. {
  718. if (!CanFocus) {
  719. return true;
  720. }
  721. //System.Diagnostics.Debug.WriteLine ($"dragPosition before: {dragPosition.HasValue}");
  722. int nx, ny;
  723. if (!_dragPosition.HasValue && (mouseEvent.Flags == MouseFlags.Button1Pressed
  724. || mouseEvent.Flags == MouseFlags.Button2Pressed
  725. || mouseEvent.Flags == MouseFlags.Button3Pressed)) {
  726. SetFocus ();
  727. Application.BringOverlappedTopToFront ();
  728. // Only start grabbing if the user clicks on the title bar.
  729. if (mouseEvent.Y == 0 && mouseEvent.Flags == MouseFlags.Button1Pressed) {
  730. _startGrabPoint = new Point (mouseEvent.X, mouseEvent.Y);
  731. _dragPosition = new Point ();
  732. nx = mouseEvent.X - mouseEvent.OfX;
  733. ny = mouseEvent.Y - mouseEvent.OfY;
  734. _dragPosition = new Point (nx, ny);
  735. Application.GrabMouse (this);
  736. }
  737. //System.Diagnostics.Debug.WriteLine ($"Starting at {dragPosition}");
  738. return true;
  739. } else if (mouseEvent.Flags == (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) ||
  740. mouseEvent.Flags == MouseFlags.Button3Pressed) {
  741. if (_dragPosition.HasValue) {
  742. if (SuperView == null) {
  743. // Redraw the entire app window using just our Frame. Since we are
  744. // Application.Top, and our Frame always == our Bounds (Location is always (0,0))
  745. // our Frame is actually view-relative (which is what Redraw takes).
  746. // We need to pass all the view bounds because since the windows was
  747. // moved around, we don't know exactly what was the affected region.
  748. Application.Top.SetNeedsDisplay ();
  749. } else {
  750. SuperView.SetNeedsDisplay ();
  751. }
  752. GetLocationThatFits (this, mouseEvent.X + (SuperView == null ? mouseEvent.OfX - _startGrabPoint.X : Frame.X - _startGrabPoint.X),
  753. mouseEvent.Y + (SuperView == null ? mouseEvent.OfY - _startGrabPoint.Y : Frame.Y - _startGrabPoint.Y),
  754. out nx, out ny, out _, out _);
  755. _dragPosition = new Point (nx, ny);
  756. X = nx;
  757. Y = ny;
  758. //System.Diagnostics.Debug.WriteLine ($"Drag: nx:{nx},ny:{ny}");
  759. SetNeedsDisplay ();
  760. return true;
  761. }
  762. }
  763. if (mouseEvent.Flags.HasFlag (MouseFlags.Button1Released) && _dragPosition.HasValue) {
  764. _dragPosition = null;
  765. Application.UngrabMouse ();
  766. }
  767. //System.Diagnostics.Debug.WriteLine ($"dragPosition after: {dragPosition.HasValue}");
  768. //System.Diagnostics.Debug.WriteLine ($"Toplevel: {mouseEvent}");
  769. return false;
  770. }
  771. /// <summary>
  772. /// Stops and closes this <see cref="Toplevel"/>. If this Toplevel is the top-most Toplevel,
  773. /// <see cref="Application.RequestStop(Toplevel)"/> will be called, causing the application to exit.
  774. /// </summary>
  775. public virtual void RequestStop ()
  776. {
  777. if (IsOverlappedContainer && Running
  778. && (Application.Current == this
  779. || Application.Current?.Modal == false
  780. || Application.Current?.Modal == true && Application.Current?.Running == false)) {
  781. foreach (var child in Application.OverlappedChildren) {
  782. var ev = new ToplevelClosingEventArgs (this);
  783. if (child.OnClosing (ev)) {
  784. return;
  785. }
  786. child.Running = false;
  787. Application.RequestStop (child);
  788. }
  789. Running = false;
  790. Application.RequestStop (this);
  791. } else if (IsOverlappedContainer && Running && Application.Current?.Modal == true && Application.Current?.Running == true) {
  792. var ev = new ToplevelClosingEventArgs (Application.Current);
  793. if (OnClosing (ev)) {
  794. return;
  795. }
  796. Application.RequestStop (Application.Current);
  797. } else if (!IsOverlappedContainer && Running && (!Modal || (Modal && Application.Current != this))) {
  798. var ev = new ToplevelClosingEventArgs (this);
  799. if (OnClosing (ev)) {
  800. return;
  801. }
  802. Running = false;
  803. Application.RequestStop (this);
  804. } else {
  805. Application.RequestStop (Application.Current);
  806. }
  807. }
  808. /// <summary>
  809. /// Stops and closes the <see cref="Toplevel"/> specified by <paramref name="top"/>. If <paramref name="top"/> is the top-most Toplevel,
  810. /// <see cref="Application.RequestStop(Toplevel)"/> will be called, causing the application to exit.
  811. /// </summary>
  812. /// <param name="top">The Toplevel to request stop.</param>
  813. public virtual void RequestStop (Toplevel top)
  814. {
  815. top.RequestStop ();
  816. }
  817. ///<inheritdoc/>
  818. public override void PositionCursor ()
  819. {
  820. if (!IsOverlappedContainer) {
  821. base.PositionCursor ();
  822. if (Focused == null) {
  823. EnsureFocus ();
  824. if (Focused == null) {
  825. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  826. }
  827. }
  828. return;
  829. }
  830. if (Focused == null) {
  831. foreach (var top in Application.OverlappedChildren) {
  832. if (top != this && top.Visible) {
  833. top.SetFocus ();
  834. return;
  835. }
  836. }
  837. }
  838. base.PositionCursor ();
  839. if (Focused == null) {
  840. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  841. }
  842. }
  843. ///<inheritdoc/>
  844. public override bool OnEnter (View view)
  845. {
  846. return MostFocused?.OnEnter (view) ?? base.OnEnter (view);
  847. }
  848. ///<inheritdoc/>
  849. public override bool OnLeave (View view)
  850. {
  851. return MostFocused?.OnLeave (view) ?? base.OnLeave (view);
  852. }
  853. ///<inheritdoc/>
  854. protected override void Dispose (bool disposing)
  855. {
  856. Application.GrabbingMouse -= Application_GrabbingMouse;
  857. Application.UnGrabbingMouse -= Application_UnGrabbingMouse;
  858. _dragPosition = null;
  859. base.Dispose (disposing);
  860. }
  861. }
  862. /// <summary>
  863. /// Implements the <see cref="IEqualityComparer{T}"/> for comparing two <see cref="Toplevel"/>s
  864. /// used by <see cref="StackExtensions"/>.
  865. /// </summary>
  866. public class ToplevelEqualityComparer : IEqualityComparer<Toplevel> {
  867. /// <summary>Determines whether the specified objects are equal.</summary>
  868. /// <param name="x">The first object of type <see cref="Toplevel" /> to compare.</param>
  869. /// <param name="y">The second object of type <see cref="Toplevel" /> to compare.</param>
  870. /// <returns>
  871. /// <see langword="true" /> if the specified objects are equal; otherwise, <see langword="false" />.</returns>
  872. public bool Equals (Toplevel x, Toplevel y)
  873. {
  874. if (y == null && x == null)
  875. return true;
  876. else if (x == null || y == null)
  877. return false;
  878. else if (x.Id == y.Id)
  879. return true;
  880. else
  881. return false;
  882. }
  883. /// <summary>Returns a hash code for the specified object.</summary>
  884. /// <param name="obj">The <see cref="Toplevel" /> for which a hash code is to be returned.</param>
  885. /// <returns>A hash code for the specified object.</returns>
  886. /// <exception cref="ArgumentNullException">The type of <paramref name="obj" />
  887. /// is a reference type and <paramref name="obj" /> is <see langword="null" />.</exception>
  888. public int GetHashCode (Toplevel obj)
  889. {
  890. if (obj == null)
  891. throw new ArgumentNullException ();
  892. int hCode = 0;
  893. if (int.TryParse (obj.Id, out int result)) {
  894. hCode = result;
  895. }
  896. return hCode.GetHashCode ();
  897. }
  898. }
  899. /// <summary>
  900. /// Implements the <see cref="IComparer{T}"/> to sort the <see cref="Toplevel"/>
  901. /// from the <see cref="Application.OverlappedChildren"/> if needed.
  902. /// </summary>
  903. public sealed class ToplevelComparer : IComparer<Toplevel> {
  904. /// <summary>Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.</summary>
  905. /// <param name="x">The first object to compare.</param>
  906. /// <param name="y">The second object to compare.</param>
  907. /// <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
  908. /// <paramref name="x" /> is less than <paramref name="y" />.Zero
  909. /// <paramref name="x" /> equals <paramref name="y" />.Greater than zero
  910. /// <paramref name="x" /> is greater than <paramref name="y" />.</returns>
  911. public int Compare (Toplevel x, Toplevel y)
  912. {
  913. if (ReferenceEquals (x, y))
  914. return 0;
  915. else if (x == null)
  916. return -1;
  917. else if (y == null)
  918. return 1;
  919. else
  920. return string.Compare (x.Id, y.Id);
  921. }
  922. }
  923. }