Toplevel.cs 32 KB

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