Toplevel.cs 31 KB

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