Toplevel.cs 33 KB

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