Toplevel.cs 32 KB

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