Toplevel.cs 32 KB

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