Toplevel.cs 32 KB

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