Toplevel.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995
  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. var found = false;
  395. var focusProcessed = false;
  396. var 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
  465. /// <paramref name="top"/>'s
  466. /// <see cref="View.SuperView"/> (e.g. for dragging a Window).
  467. /// The `out` parameters are the new X and Y coordinates.
  468. /// </summary>
  469. /// <remarks>
  470. /// If <paramref name="top"/> does not have a <see cref="View.SuperView"/> or it's SuperView is not
  471. /// <see cref="Application.Top"/>
  472. /// the position will be bound by the <see cref="ConsoleDriver.Cols"/> and
  473. /// <see cref="ConsoleDriver.Rows"/>.
  474. /// </remarks>
  475. /// <param name="top">The Toplevel that is to be moved.</param>
  476. /// <param name="targetX">The target x location.</param>
  477. /// <param name="targetY">The target y location.</param>
  478. /// <param name="nx">The x location that will ensure <paramref name="top"/> will be visible.</param>
  479. /// <param name="ny">The y location that will ensure <paramref name="top"/> will be visible.</param>
  480. /// <param name="menuBar">The new top most menuBar</param>
  481. /// <param name="statusBar">The new top most statusBar</param>
  482. /// <returns>
  483. /// Either <see cref="Application.Top"/> (if <paramref name="top"/> does not have a Super View) or
  484. /// <paramref name="top"/>'s SuperView. This can be used to ensure LayoutSubviews is called on the
  485. /// correct View.
  486. /// </returns>
  487. internal View GetLocationThatFits (Toplevel top,
  488. int targetX,
  489. int targetY,
  490. out int nx,
  491. out int ny,
  492. out MenuBar menuBar,
  493. out StatusBar statusBar)
  494. {
  495. int maxWidth;
  496. View superView;
  497. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  498. maxWidth = Driver.Cols;
  499. superView = Application.Top;
  500. } else {
  501. // Use the SuperView's Bounds, not Frame
  502. maxWidth = top.SuperView.Bounds.Width;
  503. superView = top.SuperView;
  504. }
  505. if (superView.Margin != null && superView == top.SuperView) {
  506. maxWidth -= superView.GetAdornmentsThickness ().Left + superView.GetAdornmentsThickness ().Right;
  507. }
  508. if (top.Frame.Width <= maxWidth) {
  509. nx = Math.Max (targetX, 0);
  510. nx = nx + top.Frame.Width > maxWidth ? Math.Max (maxWidth - top.Frame.Width, 0) : nx;
  511. if (nx > top.Frame.X + top.Frame.Width) {
  512. nx = Math.Max (top.Frame.Right, 0);
  513. }
  514. } else {
  515. nx = targetX;
  516. }
  517. //System.Diagnostics.Debug.WriteLine ($"nx:{nx}, rWidth:{rWidth}");
  518. bool menuVisible, statusVisible;
  519. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  520. menuVisible = Application.Top.MenuBar?.Visible == true;
  521. menuBar = Application.Top.MenuBar;
  522. } else {
  523. var t = top.SuperView;
  524. while (t is not Toplevel) {
  525. t = t.SuperView;
  526. }
  527. menuVisible = ((Toplevel)t).MenuBar?.Visible == true;
  528. menuBar = ((Toplevel)t).MenuBar;
  529. }
  530. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  531. maxWidth = menuVisible ? 1 : 0;
  532. } else {
  533. maxWidth = 0;
  534. }
  535. ny = Math.Max (targetY, maxWidth);
  536. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  537. statusVisible = Application.Top.StatusBar?.Visible == true;
  538. statusBar = Application.Top.StatusBar;
  539. } else {
  540. var t = top.SuperView;
  541. while (t is not Toplevel) {
  542. t = t.SuperView;
  543. }
  544. statusVisible = ((Toplevel)t).StatusBar?.Visible == true;
  545. statusBar = ((Toplevel)t).StatusBar;
  546. }
  547. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  548. maxWidth = statusVisible ? Driver.Rows - 1 : Driver.Rows;
  549. } else {
  550. maxWidth = statusVisible ? top.SuperView.Frame.Height - 1 : top.SuperView.Frame.Height;
  551. }
  552. if (superView.Margin != null && superView == top.SuperView) {
  553. maxWidth -= superView.GetAdornmentsThickness ().Top + superView.GetAdornmentsThickness ().Bottom;
  554. }
  555. ny = Math.Min (ny, maxWidth);
  556. if (top.Frame.Height <= maxWidth) {
  557. ny = ny + top.Frame.Height > maxWidth ? Math.Max (maxWidth - top.Frame.Height, menuVisible ? 1 : 0) : ny;
  558. if (ny > top.Frame.Y + top.Frame.Height) {
  559. ny = Math.Max (top.Frame.Bottom, 0);
  560. }
  561. }
  562. //System.Diagnostics.Debug.WriteLine ($"ny:{ny}, rHeight:{rHeight}");
  563. return superView;
  564. }
  565. // TODO: v2 - Not sure this is needed anymore.
  566. internal void PositionToplevels ()
  567. {
  568. PositionToplevel (this);
  569. foreach (var top in Subviews) {
  570. if (top is Toplevel) {
  571. PositionToplevel ((Toplevel)top);
  572. }
  573. }
  574. }
  575. /// <summary>
  576. /// Adjusts the location and size of <paramref name="top"/> within this Toplevel.
  577. /// Virtual method enabling implementation of specific positions for inherited <see cref="Toplevel"/>
  578. /// views.
  579. /// </summary>
  580. /// <param name="top">The Toplevel to adjust.</param>
  581. public virtual void PositionToplevel (Toplevel top)
  582. {
  583. var superView = GetLocationThatFits (top, top.Frame.X, top.Frame.Y,
  584. out var nx, out var ny, out _, out var sb);
  585. var layoutSubviews = false;
  586. var maxWidth = 0;
  587. if (superView.Margin != null && superView == top.SuperView) {
  588. maxWidth -= superView.GetAdornmentsThickness ().Left + superView.GetAdornmentsThickness ().Right;
  589. }
  590. if ((superView != top || top?.SuperView != null || top != Application.Top && top.Modal || top?.SuperView == null && top.IsOverlapped)
  591. // BUGBUG: Prevously PositionToplevel required LayotuStyle.Computed
  592. &&
  593. (top.Frame.X + top.Frame.Width > maxWidth || ny > top.Frame.Y) /*&& top.LayoutStyle == LayoutStyle.Computed*/) {
  594. if ((top.X == null || top.X is Pos.PosAbsolute) && top.Frame.X != nx) {
  595. top.X = nx;
  596. layoutSubviews = true;
  597. }
  598. if ((top.Y == null || top.Y is Pos.PosAbsolute) && top.Frame.Y != ny) {
  599. top.Y = ny;
  600. layoutSubviews = true;
  601. }
  602. }
  603. // TODO: v2 - This is a hack to get the StatusBar to be positioned correctly.
  604. 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) {
  605. top.Height = Dim.Fill (sb.Visible ? 1 : 0);
  606. layoutSubviews = true;
  607. }
  608. if (superView.LayoutNeeded || layoutSubviews) {
  609. superView.LayoutSubviews ();
  610. }
  611. if (LayoutNeeded) {
  612. LayoutSubviews ();
  613. }
  614. }
  615. ///<inheritdoc/>
  616. public override void OnDrawContent (Rect contentArea)
  617. {
  618. if (!Visible) {
  619. return;
  620. }
  621. if (NeedsDisplay || SubViewNeedsDisplay || LayoutNeeded) {
  622. //Driver.SetAttribute (GetNormalColor ());
  623. // TODO: It's bad practice for views to always clear. Defeats the purpose of clipping etc...
  624. Clear ();
  625. LayoutSubviews ();
  626. PositionToplevels ();
  627. if (this == Application.OverlappedTop) {
  628. foreach (var top in Application.OverlappedChildren.AsEnumerable ().Reverse ()) {
  629. if (top.Frame.IntersectsWith (Bounds)) {
  630. if (top != this && !top.IsCurrentTop && !OutsideTopFrame (top) && top.Visible) {
  631. top.SetNeedsLayout ();
  632. top.SetNeedsDisplay (top.Bounds);
  633. top.Draw ();
  634. top.OnRenderLineCanvas ();
  635. }
  636. }
  637. }
  638. }
  639. // This should not be here, but in base
  640. foreach (var view in Subviews) {
  641. if (view.Frame.IntersectsWith (Bounds) && !OutsideTopFrame (this)) {
  642. //view.SetNeedsLayout ();
  643. view.SetNeedsDisplay (view.Bounds);
  644. view.SetSubViewNeedsDisplay ();
  645. }
  646. }
  647. base.OnDrawContent (contentArea);
  648. // This is causing the menus drawn incorrectly if UseSubMenusSingleFrame is true
  649. //if (this.MenuBar != null && this.MenuBar.IsMenuOpen && this.MenuBar.openMenu != null) {
  650. // // TODO: Hack until we can get compositing working right.
  651. // this.MenuBar.openMenu.Redraw (this.MenuBar.openMenu.Bounds);
  652. //}
  653. }
  654. }
  655. bool OutsideTopFrame (Toplevel top)
  656. {
  657. if (top.Frame.X > Driver.Cols || top.Frame.Y > Driver.Rows) {
  658. return true;
  659. }
  660. return false;
  661. }
  662. internal static Point? _dragPosition;
  663. Point _startGrabPoint;
  664. void Application_UnGrabbingMouse (object sender, GrabMouseEventArgs e)
  665. {
  666. if (Application.MouseGrabView == this && _dragPosition.HasValue) {
  667. e.Cancel = true;
  668. }
  669. }
  670. void Application_GrabbingMouse (object sender, GrabMouseEventArgs e)
  671. {
  672. if (Application.MouseGrabView == this && _dragPosition.HasValue) {
  673. e.Cancel = true;
  674. }
  675. }
  676. ///<inheritdoc/>
  677. public override bool MouseEvent (MouseEvent mouseEvent)
  678. {
  679. if (!CanFocus) {
  680. return true;
  681. }
  682. //System.Diagnostics.Debug.WriteLine ($"dragPosition before: {dragPosition.HasValue}");
  683. int nx, ny;
  684. if (!_dragPosition.HasValue && (mouseEvent.Flags == MouseFlags.Button1Pressed || mouseEvent.Flags == MouseFlags.Button2Pressed || mouseEvent.Flags == MouseFlags.Button3Pressed)) {
  685. SetFocus ();
  686. Application.BringOverlappedTopToFront ();
  687. // Only start grabbing if the user clicks on the title bar.
  688. // BUGBUG: Assumes Frame == Border and Title is always at Y == 0
  689. if (mouseEvent.Y == 0 && mouseEvent.Flags == MouseFlags.Button1Pressed) {
  690. _startGrabPoint = new Point (mouseEvent.X, mouseEvent.Y);
  691. _dragPosition = new Point ();
  692. nx = mouseEvent.X - mouseEvent.OfX;
  693. ny = mouseEvent.Y - mouseEvent.OfY;
  694. _dragPosition = new Point (nx, ny);
  695. Application.GrabMouse (this);
  696. }
  697. //System.Diagnostics.Debug.WriteLine ($"Starting at {dragPosition}");
  698. return true;
  699. }
  700. if (mouseEvent.Flags == (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) ||
  701. mouseEvent.Flags == MouseFlags.Button3Pressed) {
  702. if (_dragPosition.HasValue) {
  703. if (SuperView == null) {
  704. // Redraw the entire app window using just our Frame. Since we are
  705. // Application.Top, and our Frame always == our Bounds (Location is always (0,0))
  706. // our Frame is actually view-relative (which is what Redraw takes).
  707. // We need to pass all the view bounds because since the windows was
  708. // moved around, we don't know exactly what was the affected region.
  709. Application.Top.SetNeedsDisplay ();
  710. } else {
  711. SuperView.SetNeedsDisplay ();
  712. }
  713. // BUGBUG: Assumes Frame == Border?
  714. GetLocationThatFits (this, mouseEvent.X + (SuperView == null ? mouseEvent.OfX - _startGrabPoint.X : Frame.X - _startGrabPoint.X),
  715. mouseEvent.Y + (SuperView == null ? mouseEvent.OfY - _startGrabPoint.Y : Frame.Y - _startGrabPoint.Y),
  716. out nx, out ny, out _, out _);
  717. _dragPosition = new Point (nx, ny);
  718. X = nx;
  719. Y = ny;
  720. //System.Diagnostics.Debug.WriteLine ($"Drag: nx:{nx},ny:{ny}");
  721. SetNeedsDisplay ();
  722. return true;
  723. }
  724. }
  725. if (mouseEvent.Flags.HasFlag (MouseFlags.Button1Released) && _dragPosition.HasValue) {
  726. _dragPosition = null;
  727. Application.UngrabMouse ();
  728. }
  729. //System.Diagnostics.Debug.WriteLine ($"dragPosition after: {dragPosition.HasValue}");
  730. //System.Diagnostics.Debug.WriteLine ($"Toplevel: {mouseEvent}");
  731. return false;
  732. }
  733. /// <summary>
  734. /// Stops and closes this <see cref="Toplevel"/>. If this Toplevel is the top-most Toplevel,
  735. /// <see cref="Application.RequestStop(Toplevel)"/> will be called, causing the application to exit.
  736. /// </summary>
  737. public virtual void RequestStop ()
  738. {
  739. if (IsOverlappedContainer &&
  740. Running &&
  741. (Application.Current == this || Application.Current?.Modal == false || Application.Current?.Modal == true && Application.Current?.Running == false)) {
  742. foreach (var child in Application.OverlappedChildren) {
  743. var ev = new ToplevelClosingEventArgs (this);
  744. if (child.OnClosing (ev)) {
  745. return;
  746. }
  747. child.Running = false;
  748. Application.RequestStop (child);
  749. }
  750. Running = false;
  751. Application.RequestStop (this);
  752. } else if (IsOverlappedContainer && Running && Application.Current?.Modal == true && Application.Current?.Running == true) {
  753. var ev = new ToplevelClosingEventArgs (Application.Current);
  754. if (OnClosing (ev)) {
  755. return;
  756. }
  757. Application.RequestStop (Application.Current);
  758. } else if (!IsOverlappedContainer && Running && (!Modal || Modal && Application.Current != this)) {
  759. var ev = new ToplevelClosingEventArgs (this);
  760. if (OnClosing (ev)) {
  761. return;
  762. }
  763. Running = false;
  764. Application.RequestStop (this);
  765. } else {
  766. Application.RequestStop (Application.Current);
  767. }
  768. }
  769. /// <summary>
  770. /// Stops and closes the <see cref="Toplevel"/> specified by <paramref name="top"/>. If
  771. /// <paramref name="top"/> is the top-most Toplevel,
  772. /// <see cref="Application.RequestStop(Toplevel)"/> will be called, causing the application to exit.
  773. /// </summary>
  774. /// <param name="top">The Toplevel to request stop.</param>
  775. public virtual void RequestStop (Toplevel top) => top.RequestStop ();
  776. ///<inheritdoc/>
  777. public override void PositionCursor ()
  778. {
  779. if (!IsOverlappedContainer) {
  780. base.PositionCursor ();
  781. if (Focused == null) {
  782. EnsureFocus ();
  783. if (Focused == null) {
  784. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  785. }
  786. }
  787. return;
  788. }
  789. if (Focused == null) {
  790. foreach (var top in Application.OverlappedChildren) {
  791. if (top != this && top.Visible) {
  792. top.SetFocus ();
  793. return;
  794. }
  795. }
  796. }
  797. base.PositionCursor ();
  798. if (Focused == null) {
  799. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  800. }
  801. }
  802. ///<inheritdoc/>
  803. public override bool OnEnter (View view) => MostFocused?.OnEnter (view) ?? base.OnEnter (view);
  804. ///<inheritdoc/>
  805. public override bool OnLeave (View view) => MostFocused?.OnLeave (view) ?? base.OnLeave (view);
  806. ///<inheritdoc/>
  807. protected override void Dispose (bool disposing)
  808. {
  809. Application.GrabbingMouse -= Application_GrabbingMouse;
  810. Application.UnGrabbingMouse -= Application_UnGrabbingMouse;
  811. _dragPosition = null;
  812. base.Dispose (disposing);
  813. }
  814. }
  815. /// <summary>
  816. /// Implements the <see cref="IEqualityComparer{T}"/> for comparing two <see cref="Toplevel"/>s
  817. /// used by <see cref="StackExtensions"/>.
  818. /// </summary>
  819. public class ToplevelEqualityComparer : IEqualityComparer<Toplevel> {
  820. /// <summary>Determines whether the specified objects are equal.</summary>
  821. /// <param name="x">The first object of type <see cref="Toplevel"/> to compare.</param>
  822. /// <param name="y">The second object of type <see cref="Toplevel"/> to compare.</param>
  823. /// <returns>
  824. /// <see langword="true"/> if the specified objects are equal; otherwise, <see langword="false"/>.
  825. /// </returns>
  826. public bool Equals (Toplevel x, Toplevel y)
  827. {
  828. if (y == null && x == null) {
  829. return true;
  830. }
  831. if (x == null || y == null) {
  832. return false;
  833. }
  834. if (x.Id == y.Id) {
  835. return true;
  836. }
  837. return false;
  838. }
  839. /// <summary>Returns a hash code for the specified object.</summary>
  840. /// <param name="obj">The <see cref="Toplevel"/> for which a hash code is to be returned.</param>
  841. /// <returns>A hash code for the specified object.</returns>
  842. /// <exception cref="ArgumentNullException">
  843. /// The type of <paramref name="obj"/>
  844. /// is a reference type and <paramref name="obj"/> is <see langword="null"/>.
  845. /// </exception>
  846. public int GetHashCode (Toplevel obj)
  847. {
  848. if (obj == null) {
  849. throw new ArgumentNullException ();
  850. }
  851. var hCode = 0;
  852. if (int.TryParse (obj.Id, out var result)) {
  853. hCode = result;
  854. }
  855. return hCode.GetHashCode ();
  856. }
  857. }
  858. /// <summary>
  859. /// Implements the <see cref="IComparer{T}"/> to sort the <see cref="Toplevel"/>
  860. /// from the <see cref="Application.OverlappedChildren"/> if needed.
  861. /// </summary>
  862. public sealed class ToplevelComparer : IComparer<Toplevel> {
  863. /// <summary>
  864. /// Compares two objects and returns a value indicating whether one is less than, equal to, or
  865. /// greater than the other.
  866. /// </summary>
  867. /// <param name="x">The first object to compare.</param>
  868. /// <param name="y">The second object to compare.</param>
  869. /// <returns>
  870. /// A signed integer that indicates the relative values of <paramref name="x"/> and
  871. /// <paramref name="y"/>, as shown in the following table.Value Meaning Less than zero
  872. /// <paramref name="x"/> is less than <paramref name="y"/>.Zero
  873. /// <paramref name="x"/> equals <paramref name="y"/>.Greater than zero
  874. /// <paramref name="x"/> is greater than <paramref name="y"/>.
  875. /// </returns>
  876. public int Compare (Toplevel x, Toplevel y)
  877. {
  878. if (ReferenceEquals (x, y)) {
  879. return 0;
  880. }
  881. if (x == null) {
  882. return -1;
  883. }
  884. if (y == null) {
  885. return 1;
  886. }
  887. return string.Compare (x.Id, y.Id);
  888. }
  889. }