Toplevel.cs 32 KB

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