Toplevel.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Linq;
  5. namespace Terminal.Gui {
  6. /// <summary>
  7. /// Toplevel views can be modally executed. They are used for both an application's main view (filling the entire screeN and
  8. /// for pop-up views such as <see cref="Dialog"/>, <see cref="MessageBox"/>, and <see cref="Wizard"/>.
  9. /// </summary>
  10. /// <remarks>
  11. /// <para>
  12. /// Toplevels can be modally executing views, started by calling <see cref="Application.Run(Toplevel, Func{Exception, bool})"/>.
  13. /// They return control to the caller when <see cref="Application.RequestStop(Toplevel)"/> has
  14. /// been called (which sets the <see cref="Toplevel.Running"/> property to <c>false</c>).
  15. /// </para>
  16. /// <para>
  17. /// A Toplevel is created when an application initializes Terminal.Gui by calling <see cref="Application.Init(ConsoleDriver)"/>.
  18. /// The application Toplevel can be accessed via <see cref="Application.Top"/>. Additional Toplevels can be created
  19. /// and run (e.g. <see cref="Dialog"/>s. To run a Toplevel, create the <see cref="Toplevel"/> and
  20. /// call <see cref="Application.Run(Toplevel, Func{Exception, bool})"/>.
  21. /// </para>
  22. /// </remarks>
  23. public partial class Toplevel : View {
  24. /// <summary>
  25. /// Gets or sets whether the main loop for this <see cref="Toplevel"/> is running or not.
  26. /// </summary>
  27. /// <remarks>
  28. /// Setting this property directly is discouraged. Use <see cref="Application.RequestStop"/> instead.
  29. /// </remarks>
  30. public bool Running { get; set; }
  31. /// <summary>
  32. /// Invoked when the <see cref="Toplevel"/> <see cref="RunState"/> has begun to be loaded.
  33. /// A Loaded event handler is a good place to finalize initialization before calling
  34. /// <see cref="Application.RunLoop(RunState)"/>.
  35. /// </summary>
  36. public event EventHandler Loaded;
  37. /// <summary>
  38. /// Invoked when the <see cref="Toplevel"/> main loop has started it's first iteration.
  39. /// Subscribe to this event to perform tasks when the <see cref="Toplevel"/> has been laid out and focus has been set.
  40. /// changes.
  41. /// <para>A Ready event handler is a good place to finalize initialization after calling
  42. /// <see cref="Application.Run(Func{Exception, bool})"/> on this <see cref="Toplevel"/>.</para>
  43. /// </summary>
  44. public event EventHandler Ready;
  45. /// <summary>
  46. /// Invoked when the Toplevel <see cref="RunState"/> has been unloaded.
  47. /// A Unloaded event handler is a good place to dispose objects after calling <see cref="Application.End(RunState)"/>.
  48. /// </summary>
  49. public event EventHandler Unloaded;
  50. /// <summary>
  51. /// Invoked when the Toplevel <see cref="RunState"/> becomes the <see cref="Application.Current"/> Toplevel.
  52. /// </summary>
  53. public event EventHandler<ToplevelEventArgs> Activate;
  54. /// <summary>
  55. /// Invoked when the Toplevel<see cref="RunState"/> ceases to be the <see cref="Application.Current"/> Toplevel.
  56. /// </summary>
  57. public event EventHandler<ToplevelEventArgs> Deactivate;
  58. /// <summary>
  59. /// Invoked when a child of the Toplevel <see cref="RunState"/> is closed by
  60. /// <see cref="Application.End(RunState)"/>.
  61. /// </summary>
  62. public event EventHandler<ToplevelEventArgs> ChildClosed;
  63. /// <summary>
  64. /// Invoked when the last child of the Toplevel <see cref="RunState"/> is closed from
  65. /// by <see cref="Application.End(RunState)"/>.
  66. /// </summary>
  67. public event EventHandler AllChildClosed;
  68. /// <summary>
  69. /// Invoked when the Toplevel's <see cref="RunState"/> is being closed by
  70. /// <see cref="Application.RequestStop(Toplevel)"/>.
  71. /// </summary>
  72. public event EventHandler<ToplevelClosingEventArgs> Closing;
  73. /// <summary>
  74. /// Invoked when the Toplevel's <see cref="RunState"/> is closed by <see cref="Application.End(RunState)"/>.
  75. /// </summary>
  76. public event EventHandler<ToplevelEventArgs> Closed;
  77. /// <summary>
  78. /// Invoked when a child Toplevel's <see cref="RunState"/> has been loaded.
  79. /// </summary>
  80. public event EventHandler<ToplevelEventArgs> ChildLoaded;
  81. /// <summary>
  82. /// Invoked when a cjhild Toplevel's <see cref="RunState"/> has been unloaded.
  83. /// </summary>
  84. public event EventHandler<ToplevelEventArgs> ChildUnloaded;
  85. /// <summary>
  86. /// Invoked when the terminal has been resized. The new <see cref="Size"/> of the terminal is provided.
  87. /// </summary>
  88. public event EventHandler<SizeChangedEventArgs> SizeChanging;
  89. // TODO: Make cancelable?
  90. internal virtual void OnSizeChanging (SizeChangedEventArgs size) => SizeChanging?.Invoke (this, size);
  91. internal virtual void OnChildUnloaded (Toplevel top) => ChildUnloaded?.Invoke (this, new ToplevelEventArgs (top));
  92. internal virtual void OnChildLoaded (Toplevel top) => ChildLoaded?.Invoke (this, new ToplevelEventArgs (top));
  93. internal virtual void OnClosed (Toplevel top) => Closed?.Invoke (this, new ToplevelEventArgs (top));
  94. internal virtual bool OnClosing (ToplevelClosingEventArgs ev)
  95. {
  96. Closing?.Invoke (this, ev);
  97. return ev.Cancel;
  98. }
  99. internal virtual void OnAllChildClosed () => AllChildClosed?.Invoke (this, EventArgs.Empty);
  100. internal virtual void OnChildClosed (Toplevel top)
  101. {
  102. if (IsOverlappedContainer) {
  103. SetSubViewNeedsDisplay ();
  104. }
  105. ChildClosed?.Invoke (this, new ToplevelEventArgs (top));
  106. }
  107. internal virtual void OnDeactivate (Toplevel activated)
  108. {
  109. Deactivate?.Invoke (this, new ToplevelEventArgs (activated));
  110. }
  111. internal virtual void OnActivate (Toplevel deactivated)
  112. {
  113. Activate?.Invoke (this, new ToplevelEventArgs (deactivated));
  114. }
  115. /// <summary>
  116. /// Called from <see cref="Application.Begin(Toplevel)"/> before the <see cref="Toplevel"/> redraws for the first time.
  117. /// </summary>
  118. public virtual void OnLoaded ()
  119. {
  120. IsLoaded = true;
  121. foreach (Toplevel tl in Subviews.Where (v => v is Toplevel)) {
  122. tl.OnLoaded ();
  123. }
  124. Loaded?.Invoke (this, EventArgs.Empty);
  125. }
  126. /// <summary>
  127. /// Called from <see cref="Application.RunLoop"/> after the <see cref="Toplevel"/> has entered the
  128. /// first iteration of the loop.
  129. /// </summary>
  130. internal virtual void OnReady ()
  131. {
  132. foreach (Toplevel tl in Subviews.Where (v => v is Toplevel)) {
  133. tl.OnReady ();
  134. }
  135. Ready?.Invoke (this, EventArgs.Empty);
  136. }
  137. /// <summary>
  138. /// Called from <see cref="Application.End(RunState)"/> before the <see cref="Toplevel"/> is disposed.
  139. /// </summary>
  140. internal virtual void OnUnloaded ()
  141. {
  142. foreach (Toplevel tl in Subviews.Where (v => v is Toplevel)) {
  143. tl.OnUnloaded ();
  144. }
  145. Unloaded?.Invoke (this, EventArgs.Empty);
  146. }
  147. /// <summary>
  148. /// Initializes a new instance of the <see cref="Toplevel"/> class with the specified <see cref="LayoutStyle.Absolute"/> layout.
  149. /// </summary>
  150. /// <param name="frame">A Superview-relative rectangle specifying the location and size for the new Toplevel</param>
  151. public Toplevel (Rect frame) : base (frame)
  152. {
  153. SetInitialProperties ();
  154. }
  155. /// <summary>
  156. /// Initializes a new instance of the <see cref="Toplevel"/> class with <see cref="LayoutStyle.Computed"/> layout,
  157. /// defaulting to full screen.
  158. /// </summary>
  159. public Toplevel () : base ()
  160. {
  161. SetInitialProperties ();
  162. Width = Dim.Fill ();
  163. Height = Dim.Fill ();
  164. }
  165. void SetInitialProperties ()
  166. {
  167. ColorScheme = Colors.TopLevel;
  168. Application.GrabbingMouse += Application_GrabbingMouse;
  169. Application.UnGrabbingMouse += Application_UnGrabbingMouse;
  170. // TODO: v2 - ALL Views (Responders??!?!) should support the commands related to
  171. // - Focus
  172. // Move the appropriate AddCommand calls to `Responder`
  173. // Things this view knows how to do
  174. AddCommand (Command.QuitToplevel, () => { QuitToplevel (); return true; });
  175. AddCommand (Command.Suspend, () => { Driver.Suspend (); ; return true; });
  176. AddCommand (Command.NextView, () => { MoveNextView (); return true; });
  177. AddCommand (Command.PreviousView, () => { MovePreviousView (); return true; });
  178. AddCommand (Command.NextViewOrTop, () => { MoveNextViewOrTop (); return true; });
  179. AddCommand (Command.PreviousViewOrTop, () => { MovePreviousViewOrTop (); return true; });
  180. AddCommand (Command.Refresh, () => { Application.Refresh (); return true; });
  181. AddCommand (Command.Accept, () => {
  182. // TODO: Perhaps all views should support the concept of being default?
  183. // TODO: It's bad that Toplevel is tightly coupled with Button
  184. if (Subviews.FirstOrDefault(v => v is Button && ((Button)v).IsDefault && ((Button)v).Enabled) is Button defaultBtn) {
  185. defaultBtn.InvokeCommand (Command.Accept);
  186. return true;
  187. }
  188. return false;
  189. });
  190. // Default keybindings for this view
  191. KeyBindings.Add ((KeyCode)Application.QuitKey, Command.QuitToplevel);
  192. KeyBindings.Add (KeyCode.CursorRight, Command.NextView);
  193. KeyBindings.Add (KeyCode.CursorDown, Command.NextView);
  194. KeyBindings.Add (KeyCode.CursorLeft, Command.PreviousView);
  195. KeyBindings.Add (KeyCode.CursorUp, Command.PreviousView);
  196. KeyBindings.Add (KeyCode.Tab, Command.NextView);
  197. KeyBindings.Add (KeyCode.Tab | KeyCode.ShiftMask, Command.PreviousView);
  198. KeyBindings.Add (KeyCode.Tab | KeyCode.CtrlMask, Command.NextViewOrTop);
  199. KeyBindings.Add (KeyCode.Tab | KeyCode.ShiftMask | KeyCode.CtrlMask, Command.PreviousViewOrTop);
  200. KeyBindings.Add (KeyCode.F5, Command.Refresh);
  201. KeyBindings.Add ((KeyCode)Application.AlternateForwardKey, Command.NextViewOrTop); // Needed on Unix
  202. KeyBindings.Add ((KeyCode)Application.AlternateBackwardKey, Command.PreviousViewOrTop); // Needed on Unix
  203. #if UNIX_KEY_BINDINGS
  204. KeyBindings.Add (Key.Z | Key.CtrlMask, Command.Suspend);
  205. KeyBindings.Add (Key.L | Key.CtrlMask, Command.Refresh);// Unix
  206. KeyBindings.Add (Key.F | Key.CtrlMask, Command.NextView);// Unix
  207. KeyBindings.Add (Key.I | Key.CtrlMask, Command.NextView); // Unix
  208. KeyBindings.Add (Key.B | Key.CtrlMask, Command.PreviousView);// Unix
  209. #endif
  210. // This enables the default button to be activated by the Enter key.
  211. KeyBindings.Add (KeyCode.Enter, Command.Accept);
  212. }
  213. private void Application_UnGrabbingMouse (object sender, GrabMouseEventArgs e)
  214. {
  215. if (Application.MouseGrabView == this && _dragPosition.HasValue) {
  216. e.Cancel = true;
  217. }
  218. }
  219. private void Application_GrabbingMouse (object sender, GrabMouseEventArgs e)
  220. {
  221. if (Application.MouseGrabView == this && _dragPosition.HasValue) {
  222. e.Cancel = true;
  223. }
  224. }
  225. /// <summary>
  226. /// Invoked when the <see cref="Application.AlternateForwardKey"/> is changed.
  227. /// </summary>
  228. public event EventHandler<KeyChangedEventArgs> AlternateForwardKeyChanged;
  229. /// <summary>
  230. /// Virtual method to invoke the <see cref="AlternateForwardKeyChanged"/> event.
  231. /// </summary>
  232. /// <param name="e"></param>
  233. public virtual void OnAlternateForwardKeyChanged (KeyChangedEventArgs e)
  234. {
  235. KeyBindings.Replace ((KeyCode)e.OldKey, (KeyCode)e.NewKey);
  236. AlternateForwardKeyChanged?.Invoke (this, e);
  237. }
  238. /// <summary>
  239. /// Invoked when the <see cref="Application.AlternateBackwardKey"/> is changed.
  240. /// </summary>
  241. public event EventHandler<KeyChangedEventArgs> AlternateBackwardKeyChanged;
  242. /// <summary>
  243. /// Virtual method to invoke the <see cref="AlternateBackwardKeyChanged"/> event.
  244. /// </summary>
  245. /// <param name="e"></param>
  246. public virtual void OnAlternateBackwardKeyChanged (KeyChangedEventArgs e)
  247. {
  248. KeyBindings.Replace ((KeyCode)e.OldKey, (KeyCode)e.NewKey);
  249. AlternateBackwardKeyChanged?.Invoke (this, e);
  250. }
  251. /// <summary>
  252. /// Invoked when the <see cref="Application.QuitKey"/> is changed.
  253. /// </summary>
  254. public event EventHandler<KeyChangedEventArgs> QuitKeyChanged;
  255. /// <summary>
  256. /// Virtual method to invoke the <see cref="QuitKeyChanged"/> event.
  257. /// </summary>
  258. /// <param name="e"></param>
  259. public virtual void OnQuitKeyChanged (KeyChangedEventArgs e)
  260. {
  261. KeyBindings.Replace ((KeyCode)e.OldKey, (KeyCode)e.NewKey);
  262. QuitKeyChanged?.Invoke (this, e);
  263. }
  264. /// <summary>
  265. /// Convenience factory method that creates a new Toplevel with the current terminal dimensions.
  266. /// </summary>
  267. /// <returns>The created Toplevel.</returns>
  268. public static Toplevel Create ()
  269. {
  270. return new Toplevel (new Rect (0, 0, Driver.Cols, Driver.Rows));
  271. }
  272. /// <summary>
  273. /// Gets or sets a value indicating whether this <see cref="Toplevel"/> can focus.
  274. /// </summary>
  275. /// <value><c>true</c> if can focus; otherwise, <c>false</c>.</value>
  276. public override bool CanFocus {
  277. get => SuperView == null ? true : base.CanFocus;
  278. }
  279. /// <summary>
  280. /// Determines whether the <see cref="Toplevel"/> is modal or not.
  281. /// If set to <c>false</c> (the default):
  282. ///
  283. /// <list type="bullet">
  284. /// <item>
  285. /// <description><see cref="View.OnKeyDown"/> events will propagate keys upwards.</description>
  286. /// </item>
  287. /// <item>
  288. /// <description>The Toplevel will act as an embedded view (not a modal/pop-up).</description>
  289. /// </item>
  290. /// </list>
  291. ///
  292. /// If set to <c>true</c>:
  293. ///
  294. /// <list type="bullet">
  295. /// <item>
  296. /// <description><see cref="View.OnKeyDown"/> events will NOT propagate keys upwards.</description>
  297. /// </item>
  298. /// <item>
  299. /// <description>The Toplevel will and look like a modal (pop-up) (e.g. see <see cref="Dialog"/>.</description>
  300. /// </item>
  301. /// </list>
  302. /// </summary>
  303. public bool Modal { get; set; }
  304. /// <summary>
  305. /// Gets or sets the menu for this Toplevel.
  306. /// </summary>
  307. public virtual MenuBar MenuBar { get; set; }
  308. /// <summary>
  309. /// Gets or sets the status bar for this Toplevel.
  310. /// </summary>
  311. public virtual StatusBar StatusBar { get; set; }
  312. /// <summary>
  313. /// <see langword="true"/> if was already loaded by the <see cref="Application.Begin(Toplevel)"/>
  314. /// <see langword="false"/>, otherwise.
  315. /// </summary>
  316. public bool IsLoaded { get; private set; }
  317. private void MovePreviousViewOrTop ()
  318. {
  319. if (Application.OverlappedTop == null) {
  320. var top = Modal ? this : Application.Top;
  321. top.FocusPrev ();
  322. if (top.Focused == null) {
  323. top.FocusPrev ();
  324. }
  325. top.SetNeedsDisplay ();
  326. Application.BringOverlappedTopToFront ();
  327. } else {
  328. Application.OverlappedMovePrevious ();
  329. }
  330. }
  331. private void MoveNextViewOrTop ()
  332. {
  333. if (Application.OverlappedTop == null) {
  334. var top = Modal ? this : Application.Top;
  335. top.FocusNext ();
  336. if (top.Focused == null) {
  337. top.FocusNext ();
  338. }
  339. top.SetNeedsDisplay ();
  340. Application.BringOverlappedTopToFront ();
  341. } else {
  342. Application.OverlappedMoveNext ();
  343. }
  344. }
  345. private void MovePreviousView ()
  346. {
  347. var old = GetDeepestFocusedSubview (Focused);
  348. if (!FocusPrev ())
  349. FocusPrev ();
  350. if (old != Focused && old != Focused?.Focused) {
  351. old?.SetNeedsDisplay ();
  352. Focused?.SetNeedsDisplay ();
  353. } else {
  354. FocusNearestView (SuperView?.TabIndexes?.Reverse (), Direction.Backward);
  355. }
  356. }
  357. private void MoveNextView ()
  358. {
  359. var old = GetDeepestFocusedSubview (Focused);
  360. if (!FocusNext ())
  361. FocusNext ();
  362. if (old != Focused && old != Focused?.Focused) {
  363. old?.SetNeedsDisplay ();
  364. Focused?.SetNeedsDisplay ();
  365. } else {
  366. FocusNearestView (SuperView?.TabIndexes, Direction.Forward);
  367. }
  368. }
  369. private 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.GetFramesThickness ().Left + superView.GetFramesThickness ().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.GetFramesThickness ().Top + superView.GetFramesThickness ().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 StatusBar sb);
  575. bool layoutSubviews = false;
  576. var maxWidth = 0;
  577. if (superView.Margin != null && superView == top.SuperView) {
  578. maxWidth -= superView.GetFramesThickness ().Left + superView.GetFramesThickness ().Right;
  579. }
  580. if ((superView != top || top?.SuperView != null || (top != Application.Top && top.Modal)
  581. || (top?.SuperView == null && top.IsOverlapped))
  582. && (top.Frame.X + top.Frame.Width > maxWidth || ny > top.Frame.Y) && top.LayoutStyle == LayoutStyle.Computed) {
  583. if ((top.X == null || top.X is Pos.PosAbsolute) && top.Frame.X != nx) {
  584. top.X = nx;
  585. layoutSubviews = true;
  586. }
  587. if ((top.Y == null || top.Y is Pos.PosAbsolute) && top.Frame.Y != ny) {
  588. top.Y = ny;
  589. layoutSubviews = true;
  590. }
  591. }
  592. // TODO: v2 - This is a hack to get the StatusBar to be positioned correctly.
  593. if (sb != null && !top.Subviews.Contains (sb) && ny + top.Frame.Height != superView.Frame.Height - (sb.Visible ? 1 : 0)
  594. && 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. ///<inheritdoc/>
  655. public override bool MouseEvent (MouseEvent mouseEvent)
  656. {
  657. if (!CanFocus) {
  658. return true;
  659. }
  660. //System.Diagnostics.Debug.WriteLine ($"dragPosition before: {dragPosition.HasValue}");
  661. int nx, ny;
  662. if (!_dragPosition.HasValue && (mouseEvent.Flags == MouseFlags.Button1Pressed
  663. || mouseEvent.Flags == MouseFlags.Button2Pressed
  664. || mouseEvent.Flags == MouseFlags.Button3Pressed)) {
  665. SetFocus ();
  666. Application.BringOverlappedTopToFront ();
  667. // Only start grabbing if the user clicks on the title bar.
  668. // BUGBUG: Assumes Frame == Border and Title is always at Y == 0
  669. if (mouseEvent.Y == 0 && mouseEvent.Flags == MouseFlags.Button1Pressed) {
  670. _startGrabPoint = new Point (mouseEvent.X, mouseEvent.Y);
  671. _dragPosition = new Point ();
  672. nx = mouseEvent.X - mouseEvent.OfX;
  673. ny = mouseEvent.Y - mouseEvent.OfY;
  674. _dragPosition = new Point (nx, ny);
  675. Application.GrabMouse (this);
  676. }
  677. //System.Diagnostics.Debug.WriteLine ($"Starting at {dragPosition}");
  678. return true;
  679. } else if (mouseEvent.Flags == (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) ||
  680. mouseEvent.Flags == MouseFlags.Button3Pressed) {
  681. if (_dragPosition.HasValue) {
  682. if (SuperView == null) {
  683. // Redraw the entire app window using just our Frame. Since we are
  684. // Application.Top, and our Frame always == our Bounds (Location is always (0,0))
  685. // our Frame is actually view-relative (which is what Redraw takes).
  686. // We need to pass all the view bounds because since the windows was
  687. // moved around, we don't know exactly what was the affected region.
  688. Application.Top.SetNeedsDisplay ();
  689. } else {
  690. SuperView.SetNeedsDisplay ();
  691. }
  692. // BUGBUG: Assumes Frame == Border?
  693. GetLocationThatFits (this, mouseEvent.X + (SuperView == null ? mouseEvent.OfX - _startGrabPoint.X : Frame.X - _startGrabPoint.X),
  694. mouseEvent.Y + (SuperView == null ? mouseEvent.OfY - _startGrabPoint.Y : Frame.Y - _startGrabPoint.Y),
  695. out nx, out ny, out _, out _);
  696. _dragPosition = new Point (nx, ny);
  697. X = nx;
  698. Y = ny;
  699. //System.Diagnostics.Debug.WriteLine ($"Drag: nx:{nx},ny:{ny}");
  700. SetNeedsDisplay ();
  701. return true;
  702. }
  703. }
  704. if (mouseEvent.Flags.HasFlag (MouseFlags.Button1Released) && _dragPosition.HasValue) {
  705. _dragPosition = null;
  706. Application.UngrabMouse ();
  707. }
  708. //System.Diagnostics.Debug.WriteLine ($"dragPosition after: {dragPosition.HasValue}");
  709. //System.Diagnostics.Debug.WriteLine ($"Toplevel: {mouseEvent}");
  710. return false;
  711. }
  712. /// <summary>
  713. /// Stops and closes this <see cref="Toplevel"/>. If this Toplevel is the top-most Toplevel,
  714. /// <see cref="Application.RequestStop(Toplevel)"/> will be called, causing the application to exit.
  715. /// </summary>
  716. public virtual void RequestStop ()
  717. {
  718. if (IsOverlappedContainer && Running
  719. && (Application.Current == this
  720. || Application.Current?.Modal == false
  721. || Application.Current?.Modal == true && Application.Current?.Running == false)) {
  722. foreach (var child in Application.OverlappedChildren) {
  723. var ev = new ToplevelClosingEventArgs (this);
  724. if (child.OnClosing (ev)) {
  725. return;
  726. }
  727. child.Running = false;
  728. Application.RequestStop (child);
  729. }
  730. Running = false;
  731. Application.RequestStop (this);
  732. } else if (IsOverlappedContainer && Running && Application.Current?.Modal == true && Application.Current?.Running == true) {
  733. var ev = new ToplevelClosingEventArgs (Application.Current);
  734. if (OnClosing (ev)) {
  735. return;
  736. }
  737. Application.RequestStop (Application.Current);
  738. } else if (!IsOverlappedContainer && Running && (!Modal || (Modal && Application.Current != this))) {
  739. var ev = new ToplevelClosingEventArgs (this);
  740. if (OnClosing (ev)) {
  741. return;
  742. }
  743. Running = false;
  744. Application.RequestStop (this);
  745. } else {
  746. Application.RequestStop (Application.Current);
  747. }
  748. }
  749. /// <summary>
  750. /// Stops and closes the <see cref="Toplevel"/> specified by <paramref name="top"/>. If <paramref name="top"/> is the top-most Toplevel,
  751. /// <see cref="Application.RequestStop(Toplevel)"/> will be called, causing the application to exit.
  752. /// </summary>
  753. /// <param name="top">The Toplevel to request stop.</param>
  754. public virtual void RequestStop (Toplevel top)
  755. {
  756. top.RequestStop ();
  757. }
  758. ///<inheritdoc/>
  759. public override void PositionCursor ()
  760. {
  761. if (!IsOverlappedContainer) {
  762. base.PositionCursor ();
  763. if (Focused == null) {
  764. EnsureFocus ();
  765. if (Focused == null) {
  766. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  767. }
  768. }
  769. return;
  770. }
  771. if (Focused == null) {
  772. foreach (var top in Application.OverlappedChildren) {
  773. if (top != this && top.Visible) {
  774. top.SetFocus ();
  775. return;
  776. }
  777. }
  778. }
  779. base.PositionCursor ();
  780. if (Focused == null) {
  781. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  782. }
  783. }
  784. ///<inheritdoc/>
  785. public override bool OnEnter (View view)
  786. {
  787. return MostFocused?.OnEnter (view) ?? base.OnEnter (view);
  788. }
  789. ///<inheritdoc/>
  790. public override bool OnLeave (View view)
  791. {
  792. return MostFocused?.OnLeave (view) ?? base.OnLeave (view);
  793. }
  794. ///<inheritdoc/>
  795. protected override void Dispose (bool disposing)
  796. {
  797. Application.GrabbingMouse -= Application_GrabbingMouse;
  798. Application.UnGrabbingMouse -= Application_UnGrabbingMouse;
  799. _dragPosition = null;
  800. base.Dispose (disposing);
  801. }
  802. }
  803. /// <summary>
  804. /// Implements the <see cref="IEqualityComparer{T}"/> for comparing two <see cref="Toplevel"/>s
  805. /// used by <see cref="StackExtensions"/>.
  806. /// </summary>
  807. public class ToplevelEqualityComparer : IEqualityComparer<Toplevel> {
  808. /// <summary>Determines whether the specified objects are equal.</summary>
  809. /// <param name="x">The first object of type <see cref="Toplevel" /> to compare.</param>
  810. /// <param name="y">The second object of type <see cref="Toplevel" /> to compare.</param>
  811. /// <returns>
  812. /// <see langword="true" /> if the specified objects are equal; otherwise, <see langword="false" />.</returns>
  813. public bool Equals (Toplevel x, Toplevel y)
  814. {
  815. if (y == null && x == null)
  816. return true;
  817. else if (x == null || y == null)
  818. return false;
  819. else if (x.Id == y.Id)
  820. return true;
  821. else
  822. return false;
  823. }
  824. /// <summary>Returns a hash code for the specified object.</summary>
  825. /// <param name="obj">The <see cref="Toplevel" /> for which a hash code is to be returned.</param>
  826. /// <returns>A hash code for the specified object.</returns>
  827. /// <exception cref="ArgumentNullException">The type of <paramref name="obj" />
  828. /// is a reference type and <paramref name="obj" /> is <see langword="null" />.</exception>
  829. public int GetHashCode (Toplevel obj)
  830. {
  831. if (obj == null)
  832. throw new ArgumentNullException ();
  833. int hCode = 0;
  834. if (int.TryParse (obj.Id, out int result)) {
  835. hCode = result;
  836. }
  837. return hCode.GetHashCode ();
  838. }
  839. }
  840. /// <summary>
  841. /// Implements the <see cref="IComparer{T}"/> to sort the <see cref="Toplevel"/>
  842. /// from the <see cref="Application.OverlappedChildren"/> if needed.
  843. /// </summary>
  844. public sealed class ToplevelComparer : IComparer<Toplevel> {
  845. /// <summary>Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.</summary>
  846. /// <param name="x">The first object to compare.</param>
  847. /// <param name="y">The second object to compare.</param>
  848. /// <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
  849. /// <paramref name="x" /> is less than <paramref name="y" />.Zero
  850. /// <paramref name="x" /> equals <paramref name="y" />.Greater than zero
  851. /// <paramref name="x" /> is greater than <paramref name="y" />.</returns>
  852. public int Compare (Toplevel x, Toplevel y)
  853. {
  854. if (ReferenceEquals (x, y))
  855. return 0;
  856. else if (x == null)
  857. return -1;
  858. else if (y == null)
  859. return 1;
  860. else
  861. return string.Compare (x.Id, y.Id);
  862. }
  863. }
  864. }