Toplevel.cs 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  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, IMainLoopDriver)"/>.
  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 <see cref="MainLoop"/> 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="Application.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(Application.RunState, bool)"/>.
  35. /// </summary>
  36. public event EventHandler Loaded;
  37. /// <summary>
  38. /// Invoked when the <see cref="Toplevel"/> <see cref="MainLoop"/> 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="Application.RunState"/> has been unloaded.
  47. /// A Unloaded event handler is a good place to dispose objects after calling <see cref="Application.End(Application.RunState)"/>.
  48. /// </summary>
  49. public event EventHandler Unloaded;
  50. /// <summary>
  51. /// Invoked when the Toplevel <see cref="Application.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="Application.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="Application.RunState"/> is closed by
  60. /// <see cref="Application.End(Application.RunState)"/>.
  61. /// </summary>
  62. public event EventHandler<ToplevelEventArgs> ChildClosed;
  63. /// <summary>
  64. /// Invoked when the last child of the Toplevel <see cref="Application.RunState"/> is closed from
  65. /// by <see cref="Application.End(Application.RunState)"/>.
  66. /// </summary>
  67. public event EventHandler AllChildClosed;
  68. /// <summary>
  69. /// Invoked when the Toplevel's <see cref="Application.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="Application.RunState"/> is closed by <see cref="Application.End(Application.RunState)"/>.
  75. /// </summary>
  76. public event EventHandler<ToplevelEventArgs> Closed;
  77. /// <summary>
  78. /// Invoked when a child Toplevel's <see cref="Application.RunState"/> has been loaded.
  79. /// </summary>
  80. public event EventHandler<ToplevelEventArgs> ChildLoaded;
  81. /// <summary>
  82. /// Invoked when a cjhild Toplevel's <see cref="Application.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> TerminalResized;
  89. internal virtual void OnTerminalResized (SizeChangedEventArgs size)
  90. {
  91. TerminalResized?.Invoke (this, size);
  92. }
  93. internal virtual void OnChildUnloaded (Toplevel top)
  94. {
  95. ChildUnloaded?.Invoke (this, new ToplevelEventArgs (top));
  96. }
  97. internal virtual void OnChildLoaded (Toplevel top)
  98. {
  99. ChildLoaded?.Invoke (this, new ToplevelEventArgs (top));
  100. }
  101. internal virtual void OnClosed (Toplevel top)
  102. {
  103. Closed?.Invoke (this, new ToplevelEventArgs (top));
  104. }
  105. internal virtual bool OnClosing (ToplevelClosingEventArgs ev)
  106. {
  107. Closing?.Invoke (this, ev);
  108. return ev.Cancel;
  109. }
  110. internal virtual void OnAllChildClosed ()
  111. {
  112. AllChildClosed?.Invoke (this, EventArgs.Empty);
  113. }
  114. internal virtual void OnChildClosed (Toplevel top)
  115. {
  116. if (IsOverlappedContainer) {
  117. SetSubViewNeedsDisplay ();
  118. }
  119. ChildClosed?.Invoke (this, new ToplevelEventArgs (top));
  120. }
  121. internal virtual void OnDeactivate (Toplevel activated)
  122. {
  123. Deactivate?.Invoke (this, new ToplevelEventArgs (activated));
  124. }
  125. internal virtual void OnActivate (Toplevel deactivated)
  126. {
  127. Activate?.Invoke (this, new ToplevelEventArgs (deactivated));
  128. }
  129. /// <summary>
  130. /// Called from <see cref="Application.Begin(Toplevel)"/> before the <see cref="Toplevel"/> redraws for the first time.
  131. /// </summary>
  132. virtual public void OnLoaded ()
  133. {
  134. IsLoaded = true;
  135. foreach (Toplevel tl in Subviews.Where (v => v is Toplevel)) {
  136. tl.OnLoaded ();
  137. }
  138. Loaded?.Invoke (this, EventArgs.Empty);
  139. }
  140. /// <summary>
  141. /// Called from <see cref="Application.RunLoop"/> after the <see cref="Toplevel"/> has entered the
  142. /// first iteration of the loop.
  143. /// </summary>
  144. internal virtual void OnReady ()
  145. {
  146. foreach (Toplevel tl in Subviews.Where (v => v is Toplevel)) {
  147. tl.OnReady ();
  148. }
  149. Ready?.Invoke (this, EventArgs.Empty);
  150. }
  151. /// <summary>
  152. /// Called from <see cref="Application.End(Application.RunState)"/> before the <see cref="Toplevel"/> is disposed.
  153. /// </summary>
  154. internal virtual void OnUnloaded ()
  155. {
  156. foreach (Toplevel tl in Subviews.Where (v => v is Toplevel)) {
  157. tl.OnUnloaded ();
  158. }
  159. Unloaded?.Invoke (this, EventArgs.Empty);
  160. }
  161. /// <summary>
  162. /// Initializes a new instance of the <see cref="Toplevel"/> class with the specified <see cref="LayoutStyle.Absolute"/> layout.
  163. /// </summary>
  164. /// <param name="frame">A Superview-relative rectangle specifying the location and size for the new Toplevel</param>
  165. public Toplevel (Rect frame) : base (frame)
  166. {
  167. SetInitialProperties ();
  168. }
  169. /// <summary>
  170. /// Initializes a new instance of the <see cref="Toplevel"/> class with <see cref="LayoutStyle.Computed"/> layout,
  171. /// defaulting to full screen.
  172. /// </summary>
  173. public Toplevel () : base ()
  174. {
  175. SetInitialProperties ();
  176. Width = Dim.Fill ();
  177. Height = Dim.Fill ();
  178. }
  179. void SetInitialProperties ()
  180. {
  181. ColorScheme = Colors.TopLevel;
  182. Application.GrabbingMouse += Application_GrabbingMouse;
  183. Application.UnGrabbingMouse += Application_UnGrabbingMouse;
  184. // TODO: v2 - ALL Views (Responders??!?!) should support the commands related to
  185. // - Focus
  186. // Move the appropriate AddCommand calls to `Responder`
  187. // Things this view knows how to do
  188. AddCommand (Command.QuitToplevel, () => { QuitToplevel (); return true; });
  189. AddCommand (Command.Suspend, () => { Driver.Suspend (); ; return true; });
  190. AddCommand (Command.NextView, () => { MoveNextView (); return true; });
  191. AddCommand (Command.PreviousView, () => { MovePreviousView (); return true; });
  192. AddCommand (Command.NextViewOrTop, () => { MoveNextViewOrTop (); return true; });
  193. AddCommand (Command.PreviousViewOrTop, () => { MovePreviousViewOrTop (); return true; });
  194. AddCommand (Command.Refresh, () => { Application.Refresh (); return true; });
  195. // Default keybindings for this view
  196. AddKeyBinding (Application.QuitKey, Command.QuitToplevel);
  197. AddKeyBinding (Key.Z | Key.CtrlMask, Command.Suspend);
  198. AddKeyBinding (Key.Tab, Command.NextView);
  199. AddKeyBinding (Key.CursorRight, Command.NextView);
  200. AddKeyBinding (Key.F | Key.CtrlMask, Command.NextView);
  201. AddKeyBinding (Key.CursorDown, Command.NextView);
  202. AddKeyBinding (Key.I | Key.CtrlMask, Command.NextView); // Unix
  203. AddKeyBinding (Key.BackTab | Key.ShiftMask, Command.PreviousView);
  204. AddKeyBinding (Key.CursorLeft, Command.PreviousView);
  205. AddKeyBinding (Key.CursorUp, Command.PreviousView);
  206. AddKeyBinding (Key.B | Key.CtrlMask, Command.PreviousView);
  207. AddKeyBinding (Key.Tab | Key.CtrlMask, Command.NextViewOrTop);
  208. AddKeyBinding (Application.AlternateForwardKey, Command.NextViewOrTop); // Needed on Unix
  209. AddKeyBinding (Key.Tab | Key.ShiftMask | Key.CtrlMask, Command.PreviousViewOrTop);
  210. AddKeyBinding (Application.AlternateBackwardKey, Command.PreviousViewOrTop); // Needed on Unix
  211. AddKeyBinding (Key.L | Key.CtrlMask, Command.Refresh);
  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. ReplaceKeyBinding (e.OldKey, 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. ReplaceKeyBinding (e.OldKey, 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. ReplaceKeyBinding (e.OldKey, 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="ProcessKey(KeyEvent)"/> 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="ProcessKey(KeyEvent)"/> events will NOT propogate 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. ///<inheritdoc/>
  318. public override bool OnKeyDown (KeyEvent keyEvent)
  319. {
  320. if (base.OnKeyDown (keyEvent)) {
  321. return true;
  322. }
  323. switch (keyEvent.Key) {
  324. case Key.AltMask:
  325. case Key.AltMask | Key.Space:
  326. case Key.CtrlMask | Key.Space:
  327. case Key _ when (keyEvent.Key & Key.AltMask) == Key.AltMask:
  328. return MenuBar != null && MenuBar.OnKeyDown (keyEvent);
  329. }
  330. return false;
  331. }
  332. ///<inheritdoc/>
  333. public override bool OnKeyUp (KeyEvent keyEvent)
  334. {
  335. if (base.OnKeyUp (keyEvent)) {
  336. return true;
  337. }
  338. switch (keyEvent.Key) {
  339. case Key.AltMask:
  340. case Key.AltMask | Key.Space:
  341. case Key.CtrlMask | Key.Space:
  342. if (MenuBar != null && MenuBar.OnKeyUp (keyEvent)) {
  343. return true;
  344. }
  345. break;
  346. }
  347. return false;
  348. }
  349. ///<inheritdoc/>
  350. public override bool ProcessKey (KeyEvent keyEvent)
  351. {
  352. if (base.ProcessKey (keyEvent))
  353. return true;
  354. var result = InvokeKeybindings (new KeyEvent (ShortcutHelper.GetModifiersKey (keyEvent),
  355. new KeyModifiers () { Alt = keyEvent.IsAlt, Ctrl = keyEvent.IsCtrl, Shift = keyEvent.IsShift }));
  356. if (result != null)
  357. return (bool)result;
  358. #if false
  359. if (keyEvent.Key == Key.F5) {
  360. Application.DebugDrawBounds = !Application.DebugDrawBounds;
  361. SetNeedsDisplay ();
  362. return true;
  363. }
  364. #endif
  365. return false;
  366. }
  367. private void MovePreviousViewOrTop ()
  368. {
  369. if (Application.OverlappedTop == null) {
  370. var top = Modal ? this : Application.Top;
  371. top.FocusPrev ();
  372. if (top.Focused == null) {
  373. top.FocusPrev ();
  374. }
  375. top.SetNeedsDisplay ();
  376. Application.BringOverlappedTopToFront ();
  377. } else {
  378. Application.OverlappedMovePrevious ();
  379. }
  380. }
  381. private void MoveNextViewOrTop ()
  382. {
  383. if (Application.OverlappedTop == null) {
  384. var top = Modal ? this : Application.Top;
  385. top.FocusNext ();
  386. if (top.Focused == null) {
  387. top.FocusNext ();
  388. }
  389. top.SetNeedsDisplay ();
  390. Application.BringOverlappedTopToFront ();
  391. } else {
  392. Application.OverlappedMoveNext ();
  393. }
  394. }
  395. private void MovePreviousView ()
  396. {
  397. var old = GetDeepestFocusedSubview (Focused);
  398. if (!FocusPrev ())
  399. FocusPrev ();
  400. if (old != Focused && old != Focused?.Focused) {
  401. old?.SetNeedsDisplay ();
  402. Focused?.SetNeedsDisplay ();
  403. } else {
  404. FocusNearestView (SuperView?.TabIndexes?.Reverse (), Direction.Backward);
  405. }
  406. }
  407. private void MoveNextView ()
  408. {
  409. var old = GetDeepestFocusedSubview (Focused);
  410. if (!FocusNext ())
  411. FocusNext ();
  412. if (old != Focused && old != Focused?.Focused) {
  413. old?.SetNeedsDisplay ();
  414. Focused?.SetNeedsDisplay ();
  415. } else {
  416. FocusNearestView (SuperView?.TabIndexes, Direction.Forward);
  417. }
  418. }
  419. private void QuitToplevel ()
  420. {
  421. if (Application.OverlappedTop != null) {
  422. Application.OverlappedTop.RequestStop ();
  423. } else {
  424. Application.RequestStop ();
  425. }
  426. }
  427. ///<inheritdoc/>
  428. public override bool ProcessColdKey (KeyEvent keyEvent)
  429. {
  430. if (base.ProcessColdKey (keyEvent)) {
  431. return true;
  432. }
  433. if (ShortcutHelper.FindAndOpenByShortcut (keyEvent, this)) {
  434. return true;
  435. }
  436. return false;
  437. }
  438. View GetDeepestFocusedSubview (View view)
  439. {
  440. if (view == null) {
  441. return null;
  442. }
  443. foreach (var v in view.Subviews) {
  444. if (v.HasFocus) {
  445. return GetDeepestFocusedSubview (v);
  446. }
  447. }
  448. return view;
  449. }
  450. void FocusNearestView (IEnumerable<View> views, Direction direction)
  451. {
  452. if (views == null) {
  453. return;
  454. }
  455. bool found = false;
  456. bool focusProcessed = false;
  457. int idx = 0;
  458. foreach (var v in views) {
  459. if (v == this) {
  460. found = true;
  461. }
  462. if (found && v != this) {
  463. if (direction == Direction.Forward) {
  464. SuperView?.FocusNext ();
  465. } else {
  466. SuperView?.FocusPrev ();
  467. }
  468. focusProcessed = true;
  469. if (SuperView.Focused != null && SuperView.Focused != this) {
  470. return;
  471. }
  472. } else if (found && !focusProcessed && idx == views.Count () - 1) {
  473. views.ToList () [0].SetFocus ();
  474. }
  475. idx++;
  476. }
  477. }
  478. ///<inheritdoc/>
  479. public override void Add (View view)
  480. {
  481. AddMenuStatusBar (view);
  482. base.Add (view);
  483. }
  484. internal void AddMenuStatusBar (View view)
  485. {
  486. if (view is MenuBar) {
  487. MenuBar = view as MenuBar;
  488. }
  489. if (view is StatusBar) {
  490. StatusBar = view as StatusBar;
  491. }
  492. }
  493. ///<inheritdoc/>
  494. public override void Remove (View view)
  495. {
  496. if (this is Toplevel Toplevel && Toplevel.MenuBar != null) {
  497. RemoveMenuStatusBar (view);
  498. }
  499. base.Remove (view);
  500. }
  501. ///<inheritdoc/>
  502. public override void RemoveAll ()
  503. {
  504. if (this == Application.Top) {
  505. MenuBar?.Dispose ();
  506. MenuBar = null;
  507. StatusBar?.Dispose ();
  508. StatusBar = null;
  509. }
  510. base.RemoveAll ();
  511. }
  512. internal void RemoveMenuStatusBar (View view)
  513. {
  514. if (view is MenuBar) {
  515. MenuBar?.Dispose ();
  516. MenuBar = null;
  517. }
  518. if (view is StatusBar) {
  519. StatusBar?.Dispose ();
  520. StatusBar = null;
  521. }
  522. }
  523. /// <summary>
  524. /// Gets a new location of the <see cref="Toplevel"/> that is within the Bounds of the <paramref name="top"/>'s
  525. /// <see cref="View.SuperView"/> (e.g. for dragging a Window).
  526. /// The `out` parameters are the new X and Y coordinates.
  527. /// </summary>
  528. /// <remarks>
  529. /// If <paramref name="top"/> does not have a <see cref="View.SuperView"/> or it's SuperView is not <see cref="Application.Top"/>
  530. /// the position will be bound by the <see cref="ConsoleDriver.Cols"/> and <see cref="ConsoleDriver.Rows"/>.
  531. /// </remarks>
  532. /// <param name="top">The Toplevel that is to be moved.</param>
  533. /// <param name="targetX">The target x location.</param>
  534. /// <param name="targetY">The target y location.</param>
  535. /// <param name="nx">The x location that will ensure <paramref name="top"/> will be visible.</param>
  536. /// <param name="ny">The y location that will ensure <paramref name="top"/> will be visible.</param>
  537. /// <param name="menuBar">The new top most menuBar</param>
  538. /// <param name="statusBar">The new top most statusBar</param>
  539. /// <returns>
  540. /// Either <see cref="Application.Top"/> (if <paramref name="top"/> does not have a Super View) or
  541. /// <paramref name="top"/>'s SuperView. This can be used to ensure LayoutSubviews is called on the correct View.
  542. /// </returns>
  543. internal View GetLocationThatFits (Toplevel top, int targetX, int targetY,
  544. out int nx, out int ny, out MenuBar menuBar, out StatusBar statusBar)
  545. {
  546. int maxWidth;
  547. View superView;
  548. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  549. maxWidth = Driver.Cols;
  550. superView = Application.Top;
  551. } else {
  552. // Use the SuperView's Bounds, not Frame
  553. maxWidth = top.SuperView.Bounds.Width;
  554. superView = top.SuperView;
  555. }
  556. // BUGBUG: v2 hack for now
  557. var mfLength = top.Border?.Thickness.Top > 0 ? 2 : 1;
  558. if (top.Frame.Width <= maxWidth) {
  559. nx = Math.Max (targetX, 0);
  560. nx = nx + top.Frame.Width > maxWidth ? Math.Max (maxWidth - top.Frame.Width, 0) : nx;
  561. if (nx + mfLength > top.Frame.X + top.Frame.Width) {
  562. nx = Math.Max (top.Frame.Right - mfLength, 0);
  563. }
  564. } else {
  565. nx = targetX;
  566. }
  567. //System.Diagnostics.Debug.WriteLine ($"nx:{nx}, rWidth:{rWidth}");
  568. bool menuVisible, statusVisible;
  569. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  570. menuVisible = Application.Top.MenuBar?.Visible == true;
  571. menuBar = Application.Top.MenuBar;
  572. } else {
  573. var t = top.SuperView;
  574. while (t is not Toplevel) {
  575. t = t.SuperView;
  576. }
  577. menuVisible = ((Toplevel)t).MenuBar?.Visible == true;
  578. menuBar = ((Toplevel)t).MenuBar;
  579. }
  580. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  581. maxWidth = menuVisible ? 1 : 0;
  582. } else {
  583. maxWidth = 0;
  584. }
  585. ny = Math.Max (targetY, maxWidth);
  586. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  587. statusVisible = Application.Top.StatusBar?.Visible == true;
  588. statusBar = Application.Top.StatusBar;
  589. } else {
  590. var t = top.SuperView;
  591. while (t is not Toplevel) {
  592. t = t.SuperView;
  593. }
  594. statusVisible = ((Toplevel)t).StatusBar?.Visible == true;
  595. statusBar = ((Toplevel)t).StatusBar;
  596. }
  597. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  598. maxWidth = statusVisible ? Driver.Rows - 1 : Driver.Rows;
  599. } else {
  600. maxWidth = statusVisible ? top.SuperView.Frame.Height - 1 : top.SuperView.Frame.Height;
  601. }
  602. ny = Math.Min (ny, maxWidth);
  603. if (top.Frame.Height <= maxWidth) {
  604. ny = ny + top.Frame.Height >= maxWidth ? Math.Max (maxWidth - top.Frame.Height, menuVisible ? 1 : 0) : ny;
  605. if (ny + mfLength > top.Frame.Y + top.Frame.Height) {
  606. ny = Math.Max (top.Frame.Bottom - mfLength, 0);
  607. }
  608. }
  609. //System.Diagnostics.Debug.WriteLine ($"ny:{ny}, rHeight:{rHeight}");
  610. return superView;
  611. }
  612. // TODO: v2 - Not sure this is needed anymore.
  613. internal void PositionToplevels ()
  614. {
  615. PositionToplevel (this);
  616. foreach (var top in Subviews) {
  617. if (top is Toplevel) {
  618. PositionToplevel ((Toplevel)top);
  619. }
  620. }
  621. }
  622. /// <summary>
  623. /// Adjusts the location and size of <paramref name="top"/> within this Toplevel.
  624. /// Virtual method enabling implementation of specific positions for inherited <see cref="Toplevel"/> views.
  625. /// </summary>
  626. /// <param name="top">The Toplevel to adjust.</param>
  627. public virtual void PositionToplevel (Toplevel top)
  628. {
  629. var superView = GetLocationThatFits (top, top.Frame.X, top.Frame.Y,
  630. out int nx, out int ny, out _, out StatusBar sb);
  631. bool layoutSubviews = false;
  632. if ((superView != top || top?.SuperView != null || (top != Application.Top && top.Modal)
  633. || (top?.SuperView == null && top.IsOverlapped))
  634. && (top.Frame.X + top.Frame.Width > Driver.Cols || ny > top.Frame.Y) && top.LayoutStyle == LayoutStyle.Computed) {
  635. if ((top.X == null || top.X is Pos.PosAbsolute) && top.Frame.X != nx) {
  636. top.X = nx;
  637. layoutSubviews = true;
  638. }
  639. if ((top.Y == null || top.Y is Pos.PosAbsolute) && top.Frame.Y != ny) {
  640. top.Y = ny;
  641. layoutSubviews = true;
  642. }
  643. }
  644. // TODO: v2 - This is a hack to get the StatusBar to be positioned correctly.
  645. if (sb != null && !top.Subviews.Contains (sb) && ny + top.Frame.Height != superView.Frame.Height - (sb.Visible ? 1 : 0)
  646. && top.Height is Dim.DimFill && -top.Height.Anchor (0) < 1) {
  647. top.Height = Dim.Fill (sb.Visible ? 1 : 0);
  648. layoutSubviews = true;
  649. }
  650. if (superView.LayoutNeeded || layoutSubviews) {
  651. superView.LayoutSubviews ();
  652. }
  653. if (LayoutNeeded) {
  654. LayoutSubviews ();
  655. }
  656. }
  657. ///<inheritdoc/>
  658. public override void Redraw (Rect bounds)
  659. {
  660. if (!Visible) {
  661. return;
  662. }
  663. if (!_needsDisplay.IsEmpty || _childNeedsDisplay || LayoutNeeded) {
  664. Driver.SetAttribute (GetNormalColor ());
  665. Clear (ViewToScreen (bounds));
  666. LayoutSubviews ();
  667. PositionToplevels ();
  668. if (this == Application.OverlappedTop) {
  669. foreach (var top in Application.OverlappedChildren.AsEnumerable ().Reverse ()) {
  670. if (top.Frame.IntersectsWith (bounds)) {
  671. if (top != this && !top.IsCurrentTop && !OutsideTopFrame (top) && top.Visible) {
  672. top.SetNeedsLayout ();
  673. top.SetNeedsDisplay (top.Bounds);
  674. top.Redraw (top.Bounds);
  675. top.OnRenderLineCanvas ();
  676. }
  677. }
  678. }
  679. }
  680. foreach (var view in Subviews) {
  681. if (view.Frame.IntersectsWith (bounds) && !OutsideTopFrame (this)) {
  682. view.SetNeedsLayout ();
  683. view.SetNeedsDisplay (view.Bounds);
  684. }
  685. }
  686. base.Redraw (Bounds);
  687. if (this.MenuBar != null && this.MenuBar.IsMenuOpen && this.MenuBar.openMenu != null) {
  688. // TODO: Hack until we can get compositing working right.
  689. this.MenuBar.openMenu.Redraw (this.MenuBar.openMenu.Bounds);
  690. }
  691. }
  692. }
  693. bool OutsideTopFrame (Toplevel top)
  694. {
  695. if (top.Frame.X > Driver.Cols || top.Frame.Y > Driver.Rows) {
  696. return true;
  697. }
  698. return false;
  699. }
  700. internal static Point? _dragPosition;
  701. Point _startGrabPoint;
  702. ///<inheritdoc/>
  703. public override bool MouseEvent (MouseEvent mouseEvent)
  704. {
  705. if (!CanFocus) {
  706. return true;
  707. }
  708. //System.Diagnostics.Debug.WriteLine ($"dragPosition before: {dragPosition.HasValue}");
  709. int nx, ny;
  710. if (!_dragPosition.HasValue && (mouseEvent.Flags == MouseFlags.Button1Pressed
  711. || mouseEvent.Flags == MouseFlags.Button2Pressed
  712. || mouseEvent.Flags == MouseFlags.Button3Pressed)) {
  713. SetFocus ();
  714. Application.BringOverlappedTopToFront ();
  715. // Only start grabbing if the user clicks on the title bar.
  716. if (mouseEvent.Y == 0 && mouseEvent.Flags == MouseFlags.Button1Pressed) {
  717. _startGrabPoint = new Point (mouseEvent.X, mouseEvent.Y);
  718. _dragPosition = new Point ();
  719. nx = mouseEvent.X - mouseEvent.OfX;
  720. ny = mouseEvent.Y - mouseEvent.OfY;
  721. _dragPosition = new Point (nx, ny);
  722. Application.GrabMouse (this);
  723. }
  724. //System.Diagnostics.Debug.WriteLine ($"Starting at {dragPosition}");
  725. return true;
  726. } else if (mouseEvent.Flags == (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) ||
  727. mouseEvent.Flags == MouseFlags.Button3Pressed) {
  728. if (_dragPosition.HasValue) {
  729. if (SuperView == null) {
  730. // Redraw the entire app window using just our Frame. Since we are
  731. // Application.Top, and our Frame always == our Bounds (Location is always (0,0))
  732. // our Frame is actually view-relative (which is what Redraw takes).
  733. // We need to pass all the view bounds because since the windows was
  734. // moved around, we don't know exactly what was the affected region.
  735. Application.Top.SetNeedsDisplay ();
  736. } else {
  737. SuperView.SetNeedsDisplay ();
  738. }
  739. GetLocationThatFits (this, mouseEvent.X + (SuperView == null ? mouseEvent.OfX - _startGrabPoint.X : Frame.X - _startGrabPoint.X),
  740. mouseEvent.Y + (SuperView == null ? mouseEvent.OfY - _startGrabPoint.Y : Frame.Y - _startGrabPoint.Y),
  741. out nx, out ny, out _, out _);
  742. _dragPosition = new Point (nx, ny);
  743. X = nx;
  744. Y = ny;
  745. //System.Diagnostics.Debug.WriteLine ($"Drag: nx:{nx},ny:{ny}");
  746. SetNeedsDisplay ();
  747. return true;
  748. }
  749. }
  750. if (mouseEvent.Flags.HasFlag (MouseFlags.Button1Released) && _dragPosition.HasValue) {
  751. _dragPosition = null;
  752. Application.UngrabMouse ();
  753. }
  754. //System.Diagnostics.Debug.WriteLine ($"dragPosition after: {dragPosition.HasValue}");
  755. //System.Diagnostics.Debug.WriteLine ($"Toplevel: {mouseEvent}");
  756. return false;
  757. }
  758. /// <summary>
  759. /// Stops and closes this <see cref="Toplevel"/>. If this Toplevel is the top-most Toplevel,
  760. /// <see cref="Application.RequestStop(Toplevel)"/> will be called, causing the application to exit.
  761. /// </summary>
  762. public virtual void RequestStop ()
  763. {
  764. if (IsOverlappedContainer && Running
  765. && (Application.Current == this
  766. || Application.Current?.Modal == false
  767. || Application.Current?.Modal == true && Application.Current?.Running == false)) {
  768. foreach (var child in Application.OverlappedChildren) {
  769. var ev = new ToplevelClosingEventArgs (this);
  770. if (child.OnClosing (ev)) {
  771. return;
  772. }
  773. child.Running = false;
  774. Application.RequestStop (child);
  775. }
  776. Running = false;
  777. Application.RequestStop (this);
  778. } else if (IsOverlappedContainer && Running && Application.Current?.Modal == true && Application.Current?.Running == true) {
  779. var ev = new ToplevelClosingEventArgs (Application.Current);
  780. if (OnClosing (ev)) {
  781. return;
  782. }
  783. Application.RequestStop (Application.Current);
  784. } else if (!IsOverlappedContainer && Running && (!Modal || (Modal && Application.Current != this))) {
  785. var ev = new ToplevelClosingEventArgs (this);
  786. if (OnClosing (ev)) {
  787. return;
  788. }
  789. Running = false;
  790. Application.RequestStop (this);
  791. } else {
  792. Application.RequestStop (Application.Current);
  793. }
  794. }
  795. /// <summary>
  796. /// Stops and closes the <see cref="Toplevel"/> specified by <paramref name="top"/>. If <paramref name="top"/> is the top-most Toplevel,
  797. /// <see cref="Application.RequestStop(Toplevel)"/> will be called, causing the application to exit.
  798. /// </summary>
  799. /// <param name="top">The Toplevel to request stop.</param>
  800. public virtual void RequestStop (Toplevel top)
  801. {
  802. top.RequestStop ();
  803. }
  804. ///<inheritdoc/>
  805. public override void PositionCursor ()
  806. {
  807. if (!IsOverlappedContainer) {
  808. base.PositionCursor ();
  809. if (Focused == null) {
  810. EnsureFocus ();
  811. if (Focused == null) {
  812. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  813. }
  814. }
  815. return;
  816. }
  817. if (Focused == null) {
  818. foreach (var top in Application.OverlappedChildren) {
  819. if (top != this && top.Visible) {
  820. top.SetFocus ();
  821. return;
  822. }
  823. }
  824. }
  825. base.PositionCursor ();
  826. if (Focused == null) {
  827. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  828. }
  829. }
  830. ///<inheritdoc/>
  831. public override bool OnEnter (View view)
  832. {
  833. return MostFocused?.OnEnter (view) ?? base.OnEnter (view);
  834. }
  835. ///<inheritdoc/>
  836. public override bool OnLeave (View view)
  837. {
  838. return MostFocused?.OnLeave (view) ?? base.OnLeave (view);
  839. }
  840. ///<inheritdoc/>
  841. protected override void Dispose (bool disposing)
  842. {
  843. _dragPosition = null;
  844. base.Dispose (disposing);
  845. }
  846. }
  847. /// <summary>
  848. /// Implements the <see cref="IEqualityComparer{T}"/> for comparing two <see cref="Toplevel"/>s
  849. /// used by <see cref="StackExtensions"/>.
  850. /// </summary>
  851. public class ToplevelEqualityComparer : IEqualityComparer<Toplevel> {
  852. /// <summary>Determines whether the specified objects are equal.</summary>
  853. /// <param name="x">The first object of type <see cref="Toplevel" /> to compare.</param>
  854. /// <param name="y">The second object of type <see cref="Toplevel" /> to compare.</param>
  855. /// <returns>
  856. /// <see langword="true" /> if the specified objects are equal; otherwise, <see langword="false" />.</returns>
  857. public bool Equals (Toplevel x, Toplevel y)
  858. {
  859. if (y == null && x == null)
  860. return true;
  861. else if (x == null || y == null)
  862. return false;
  863. else if (x.Id == y.Id)
  864. return true;
  865. else
  866. return false;
  867. }
  868. /// <summary>Returns a hash code for the specified object.</summary>
  869. /// <param name="obj">The <see cref="Toplevel" /> for which a hash code is to be returned.</param>
  870. /// <returns>A hash code for the specified object.</returns>
  871. /// <exception cref="ArgumentNullException">The type of <paramref name="obj" />
  872. /// is a reference type and <paramref name="obj" /> is <see langword="null" />.</exception>
  873. public int GetHashCode (Toplevel obj)
  874. {
  875. if (obj == null)
  876. throw new ArgumentNullException ();
  877. int hCode = 0;
  878. if (int.TryParse (obj.Id.ToString (), out int result)) {
  879. hCode = result;
  880. }
  881. return hCode.GetHashCode ();
  882. }
  883. }
  884. /// <summary>
  885. /// Implements the <see cref="IComparer{T}"/> to sort the <see cref="Toplevel"/>
  886. /// from the <see cref="Application.OverlappedChildren"/> if needed.
  887. /// </summary>
  888. public sealed class ToplevelComparer : IComparer<Toplevel> {
  889. /// <summary>Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.</summary>
  890. /// <param name="x">The first object to compare.</param>
  891. /// <param name="y">The second object to compare.</param>
  892. /// <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
  893. /// <paramref name="x" /> is less than <paramref name="y" />.Zero
  894. /// <paramref name="x" /> equals <paramref name="y" />.Greater than zero
  895. /// <paramref name="x" /> is greater than <paramref name="y" />.</returns>
  896. public int Compare (Toplevel x, Toplevel y)
  897. {
  898. if (ReferenceEquals (x, y))
  899. return 0;
  900. else if (x == null)
  901. return -1;
  902. else if (y == null)
  903. return 1;
  904. else
  905. return string.Compare (x.Id.ToString (), y.Id.ToString ());
  906. }
  907. }
  908. }