Toplevel.cs 32 KB

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