Toplevel.cs 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  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="RunState"/> has begun to be loaded.
  33. /// A Loaded event handler is a good place to finalize initialization before calling
  34. /// <see cref="Application.RunLoop(RunState, 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="RunState"/> has been unloaded.
  47. /// A Unloaded event handler is a good place to dispose objects after calling <see cref="Application.End(RunState)"/>.
  48. /// </summary>
  49. public event EventHandler Unloaded;
  50. /// <summary>
  51. /// Invoked when the Toplevel <see cref="RunState"/> becomes the <see cref="Application.Current"/> Toplevel.
  52. /// </summary>
  53. public event EventHandler<ToplevelEventArgs> Activate;
  54. /// <summary>
  55. /// Invoked when the Toplevel<see cref="RunState"/> ceases to be the <see cref="Application.Current"/> Toplevel.
  56. /// </summary>
  57. public event EventHandler<ToplevelEventArgs> Deactivate;
  58. /// <summary>
  59. /// Invoked when a child of the Toplevel <see cref="RunState"/> is closed by
  60. /// <see cref="Application.End(RunState)"/>.
  61. /// </summary>
  62. public event EventHandler<ToplevelEventArgs> ChildClosed;
  63. /// <summary>
  64. /// Invoked when the last child of the Toplevel <see cref="RunState"/> is closed from
  65. /// by <see cref="Application.End(RunState)"/>.
  66. /// </summary>
  67. public event EventHandler AllChildClosed;
  68. /// <summary>
  69. /// Invoked when the Toplevel's <see cref="RunState"/> is being closed by
  70. /// <see cref="Application.RequestStop(Toplevel)"/>.
  71. /// </summary>
  72. public event EventHandler<ToplevelClosingEventArgs> Closing;
  73. /// <summary>
  74. /// Invoked when the Toplevel's <see cref="RunState"/> is closed by <see cref="Application.End(RunState)"/>.
  75. /// </summary>
  76. public event EventHandler<ToplevelEventArgs> Closed;
  77. /// <summary>
  78. /// Invoked when a child Toplevel's <see cref="RunState"/> has been loaded.
  79. /// </summary>
  80. public event EventHandler<ToplevelEventArgs> ChildLoaded;
  81. /// <summary>
  82. /// Invoked when a cjhild Toplevel's <see cref="RunState"/> has been unloaded.
  83. /// </summary>
  84. public event EventHandler<ToplevelEventArgs> ChildUnloaded;
  85. /// <summary>
  86. /// Invoked when the terminal has been resized. The new <see cref="Size"/> of the terminal is provided.
  87. /// </summary>
  88. public event EventHandler<SizeChangedEventArgs> 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(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. if (superView.Margin != null && superView == top.SuperView) {
  557. maxWidth -= superView.GetFramesThickness ().Left + superView.GetFramesThickness ().Right;
  558. }
  559. if (top.Frame.Width <= maxWidth) {
  560. nx = Math.Max (targetX, 0);
  561. nx = nx + top.Frame.Width > maxWidth ? Math.Max (maxWidth - top.Frame.Width, 0) : nx;
  562. if (nx > top.Frame.X + top.Frame.Width) {
  563. nx = Math.Max (top.Frame.Right, 0);
  564. }
  565. } else {
  566. nx = targetX;
  567. }
  568. //System.Diagnostics.Debug.WriteLine ($"nx:{nx}, rWidth:{rWidth}");
  569. bool menuVisible, statusVisible;
  570. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  571. menuVisible = Application.Top.MenuBar?.Visible == true;
  572. menuBar = Application.Top.MenuBar;
  573. } else {
  574. var t = top.SuperView;
  575. while (t is not Toplevel) {
  576. t = t.SuperView;
  577. }
  578. menuVisible = ((Toplevel)t).MenuBar?.Visible == true;
  579. menuBar = ((Toplevel)t).MenuBar;
  580. }
  581. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  582. maxWidth = menuVisible ? 1 : 0;
  583. } else {
  584. maxWidth = 0;
  585. }
  586. ny = Math.Max (targetY, maxWidth);
  587. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  588. statusVisible = Application.Top.StatusBar?.Visible == true;
  589. statusBar = Application.Top.StatusBar;
  590. } else {
  591. var t = top.SuperView;
  592. while (t is not Toplevel) {
  593. t = t.SuperView;
  594. }
  595. statusVisible = ((Toplevel)t).StatusBar?.Visible == true;
  596. statusBar = ((Toplevel)t).StatusBar;
  597. }
  598. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  599. maxWidth = statusVisible ? Driver.Rows - 1 : Driver.Rows;
  600. } else {
  601. maxWidth = statusVisible ? top.SuperView.Frame.Height - 1 : top.SuperView.Frame.Height;
  602. }
  603. if (superView.Margin != null && superView == top.SuperView) {
  604. maxWidth -= superView.GetFramesThickness ().Top + superView.GetFramesThickness ().Bottom;
  605. }
  606. ny = Math.Min (ny, maxWidth);
  607. if (top.Frame.Height <= maxWidth) {
  608. ny = ny + top.Frame.Height > maxWidth ? Math.Max (maxWidth - top.Frame.Height, menuVisible ? 1 : 0) : ny;
  609. if (ny > top.Frame.Y + top.Frame.Height) {
  610. ny = Math.Max (top.Frame.Bottom, 0);
  611. }
  612. }
  613. //System.Diagnostics.Debug.WriteLine ($"ny:{ny}, rHeight:{rHeight}");
  614. return superView;
  615. }
  616. // TODO: v2 - Not sure this is needed anymore.
  617. internal void PositionToplevels ()
  618. {
  619. PositionToplevel (this);
  620. foreach (var top in Subviews) {
  621. if (top is Toplevel) {
  622. PositionToplevel ((Toplevel)top);
  623. }
  624. }
  625. }
  626. /// <summary>
  627. /// Adjusts the location and size of <paramref name="top"/> within this Toplevel.
  628. /// Virtual method enabling implementation of specific positions for inherited <see cref="Toplevel"/> views.
  629. /// </summary>
  630. /// <param name="top">The Toplevel to adjust.</param>
  631. public virtual void PositionToplevel (Toplevel top)
  632. {
  633. var superView = GetLocationThatFits (top, top.Frame.X, top.Frame.Y,
  634. out int nx, out int ny, out _, out StatusBar sb);
  635. bool layoutSubviews = false;
  636. var maxWidth = 0;
  637. if (superView.Margin != null && superView == top.SuperView) {
  638. maxWidth -= superView.GetFramesThickness ().Left + superView.GetFramesThickness ().Right;
  639. }
  640. if ((superView != top || top?.SuperView != null || (top != Application.Top && top.Modal)
  641. || (top?.SuperView == null && top.IsOverlapped))
  642. && (top.Frame.X + top.Frame.Width > maxWidth || ny > top.Frame.Y) && top.LayoutStyle == LayoutStyle.Computed) {
  643. if ((top.X == null || top.X is Pos.PosAbsolute) && top.Frame.X != nx) {
  644. top.X = nx;
  645. layoutSubviews = true;
  646. }
  647. if ((top.Y == null || top.Y is Pos.PosAbsolute) && top.Frame.Y != ny) {
  648. top.Y = ny;
  649. layoutSubviews = true;
  650. }
  651. }
  652. // TODO: v2 - This is a hack to get the StatusBar to be positioned correctly.
  653. if (sb != null && !top.Subviews.Contains (sb) && ny + top.Frame.Height != superView.Frame.Height - (sb.Visible ? 1 : 0)
  654. && top.Height is Dim.DimFill && -top.Height.Anchor (0) < 1) {
  655. top.Height = Dim.Fill (sb.Visible ? 1 : 0);
  656. layoutSubviews = true;
  657. }
  658. if (superView.LayoutNeeded || layoutSubviews) {
  659. superView.LayoutSubviews ();
  660. }
  661. if (LayoutNeeded) {
  662. LayoutSubviews ();
  663. }
  664. }
  665. ///<inheritdoc/>
  666. public override void OnDrawContent (Rect contentArea)
  667. {
  668. if (!Visible) {
  669. return;
  670. }
  671. if (NeedsDisplay || SubViewNeedsDisplay || LayoutNeeded) {
  672. //Driver.SetAttribute (GetNormalColor ());
  673. // TODO: It's bad practice for views to always clear. Defeats the purpose of clipping etc...
  674. Clear ();
  675. LayoutSubviews ();
  676. PositionToplevels ();
  677. if (this == Application.OverlappedTop) {
  678. foreach (var top in Application.OverlappedChildren.AsEnumerable ().Reverse ()) {
  679. if (top.Frame.IntersectsWith (Bounds)) {
  680. if (top != this && !top.IsCurrentTop && !OutsideTopFrame (top) && top.Visible) {
  681. top.SetNeedsLayout ();
  682. top.SetNeedsDisplay (top.Bounds);
  683. top.Draw ();
  684. top.OnRenderLineCanvas ();
  685. }
  686. }
  687. }
  688. }
  689. // This should not be here, but in base
  690. foreach (var view in Subviews) {
  691. if (view.Frame.IntersectsWith (Bounds) && !OutsideTopFrame (this)) {
  692. //view.SetNeedsLayout ();
  693. view.SetNeedsDisplay (view.Bounds);
  694. view.SetSubViewNeedsDisplay ();
  695. }
  696. }
  697. base.OnDrawContent (contentArea);
  698. // This is causing the menus drawn incorrectly if UseSubMenusSingleFrame is true
  699. //if (this.MenuBar != null && this.MenuBar.IsMenuOpen && this.MenuBar.openMenu != null) {
  700. // // TODO: Hack until we can get compositing working right.
  701. // this.MenuBar.openMenu.Redraw (this.MenuBar.openMenu.Bounds);
  702. //}
  703. }
  704. }
  705. bool OutsideTopFrame (Toplevel top)
  706. {
  707. if (top.Frame.X > Driver.Cols || top.Frame.Y > Driver.Rows) {
  708. return true;
  709. }
  710. return false;
  711. }
  712. internal static Point? _dragPosition;
  713. Point _startGrabPoint;
  714. ///<inheritdoc/>
  715. public override bool MouseEvent (MouseEvent mouseEvent)
  716. {
  717. if (!CanFocus) {
  718. return true;
  719. }
  720. //System.Diagnostics.Debug.WriteLine ($"dragPosition before: {dragPosition.HasValue}");
  721. int nx, ny;
  722. if (!_dragPosition.HasValue && (mouseEvent.Flags == MouseFlags.Button1Pressed
  723. || mouseEvent.Flags == MouseFlags.Button2Pressed
  724. || mouseEvent.Flags == MouseFlags.Button3Pressed)) {
  725. SetFocus ();
  726. Application.BringOverlappedTopToFront ();
  727. // Only start grabbing if the user clicks on the title bar.
  728. if (mouseEvent.Y == 0 && mouseEvent.Flags == MouseFlags.Button1Pressed) {
  729. _startGrabPoint = new Point (mouseEvent.X, mouseEvent.Y);
  730. _dragPosition = new Point ();
  731. nx = mouseEvent.X - mouseEvent.OfX;
  732. ny = mouseEvent.Y - mouseEvent.OfY;
  733. _dragPosition = new Point (nx, ny);
  734. Application.GrabMouse (this);
  735. }
  736. //System.Diagnostics.Debug.WriteLine ($"Starting at {dragPosition}");
  737. return true;
  738. } else if (mouseEvent.Flags == (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) ||
  739. mouseEvent.Flags == MouseFlags.Button3Pressed) {
  740. if (_dragPosition.HasValue) {
  741. if (SuperView == null) {
  742. // Redraw the entire app window using just our Frame. Since we are
  743. // Application.Top, and our Frame always == our Bounds (Location is always (0,0))
  744. // our Frame is actually view-relative (which is what Redraw takes).
  745. // We need to pass all the view bounds because since the windows was
  746. // moved around, we don't know exactly what was the affected region.
  747. Application.Top.SetNeedsDisplay ();
  748. } else {
  749. SuperView.SetNeedsDisplay ();
  750. }
  751. GetLocationThatFits (this, mouseEvent.X + (SuperView == null ? mouseEvent.OfX - _startGrabPoint.X : Frame.X - _startGrabPoint.X),
  752. mouseEvent.Y + (SuperView == null ? mouseEvent.OfY - _startGrabPoint.Y : Frame.Y - _startGrabPoint.Y),
  753. out nx, out ny, out _, out _);
  754. _dragPosition = new Point (nx, ny);
  755. X = nx;
  756. Y = ny;
  757. //System.Diagnostics.Debug.WriteLine ($"Drag: nx:{nx},ny:{ny}");
  758. SetNeedsDisplay ();
  759. return true;
  760. }
  761. }
  762. if (mouseEvent.Flags.HasFlag (MouseFlags.Button1Released) && _dragPosition.HasValue) {
  763. _dragPosition = null;
  764. Application.UngrabMouse ();
  765. }
  766. //System.Diagnostics.Debug.WriteLine ($"dragPosition after: {dragPosition.HasValue}");
  767. //System.Diagnostics.Debug.WriteLine ($"Toplevel: {mouseEvent}");
  768. return false;
  769. }
  770. /// <summary>
  771. /// Stops and closes this <see cref="Toplevel"/>. If this Toplevel is the top-most Toplevel,
  772. /// <see cref="Application.RequestStop(Toplevel)"/> will be called, causing the application to exit.
  773. /// </summary>
  774. public virtual void RequestStop ()
  775. {
  776. if (IsOverlappedContainer && Running
  777. && (Application.Current == this
  778. || Application.Current?.Modal == false
  779. || Application.Current?.Modal == true && Application.Current?.Running == false)) {
  780. foreach (var child in Application.OverlappedChildren) {
  781. var ev = new ToplevelClosingEventArgs (this);
  782. if (child.OnClosing (ev)) {
  783. return;
  784. }
  785. child.Running = false;
  786. Application.RequestStop (child);
  787. }
  788. Running = false;
  789. Application.RequestStop (this);
  790. } else if (IsOverlappedContainer && Running && Application.Current?.Modal == true && Application.Current?.Running == true) {
  791. var ev = new ToplevelClosingEventArgs (Application.Current);
  792. if (OnClosing (ev)) {
  793. return;
  794. }
  795. Application.RequestStop (Application.Current);
  796. } else if (!IsOverlappedContainer && Running && (!Modal || (Modal && Application.Current != this))) {
  797. var ev = new ToplevelClosingEventArgs (this);
  798. if (OnClosing (ev)) {
  799. return;
  800. }
  801. Running = false;
  802. Application.RequestStop (this);
  803. } else {
  804. Application.RequestStop (Application.Current);
  805. }
  806. }
  807. /// <summary>
  808. /// Stops and closes the <see cref="Toplevel"/> specified by <paramref name="top"/>. If <paramref name="top"/> is the top-most Toplevel,
  809. /// <see cref="Application.RequestStop(Toplevel)"/> will be called, causing the application to exit.
  810. /// </summary>
  811. /// <param name="top">The Toplevel to request stop.</param>
  812. public virtual void RequestStop (Toplevel top)
  813. {
  814. top.RequestStop ();
  815. }
  816. ///<inheritdoc/>
  817. public override void PositionCursor ()
  818. {
  819. if (!IsOverlappedContainer) {
  820. base.PositionCursor ();
  821. if (Focused == null) {
  822. EnsureFocus ();
  823. if (Focused == null) {
  824. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  825. }
  826. }
  827. return;
  828. }
  829. if (Focused == null) {
  830. foreach (var top in Application.OverlappedChildren) {
  831. if (top != this && top.Visible) {
  832. top.SetFocus ();
  833. return;
  834. }
  835. }
  836. }
  837. base.PositionCursor ();
  838. if (Focused == null) {
  839. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  840. }
  841. }
  842. ///<inheritdoc/>
  843. public override bool OnEnter (View view)
  844. {
  845. return MostFocused?.OnEnter (view) ?? base.OnEnter (view);
  846. }
  847. ///<inheritdoc/>
  848. public override bool OnLeave (View view)
  849. {
  850. return MostFocused?.OnLeave (view) ?? base.OnLeave (view);
  851. }
  852. ///<inheritdoc/>
  853. protected override void Dispose (bool disposing)
  854. {
  855. _dragPosition = null;
  856. base.Dispose (disposing);
  857. }
  858. }
  859. /// <summary>
  860. /// Implements the <see cref="IEqualityComparer{T}"/> for comparing two <see cref="Toplevel"/>s
  861. /// used by <see cref="StackExtensions"/>.
  862. /// </summary>
  863. public class ToplevelEqualityComparer : IEqualityComparer<Toplevel> {
  864. /// <summary>Determines whether the specified objects are equal.</summary>
  865. /// <param name="x">The first object of type <see cref="Toplevel" /> to compare.</param>
  866. /// <param name="y">The second object of type <see cref="Toplevel" /> to compare.</param>
  867. /// <returns>
  868. /// <see langword="true" /> if the specified objects are equal; otherwise, <see langword="false" />.</returns>
  869. public bool Equals (Toplevel x, Toplevel y)
  870. {
  871. if (y == null && x == null)
  872. return true;
  873. else if (x == null || y == null)
  874. return false;
  875. else if (x.Id == y.Id)
  876. return true;
  877. else
  878. return false;
  879. }
  880. /// <summary>Returns a hash code for the specified object.</summary>
  881. /// <param name="obj">The <see cref="Toplevel" /> for which a hash code is to be returned.</param>
  882. /// <returns>A hash code for the specified object.</returns>
  883. /// <exception cref="ArgumentNullException">The type of <paramref name="obj" />
  884. /// is a reference type and <paramref name="obj" /> is <see langword="null" />.</exception>
  885. public int GetHashCode (Toplevel obj)
  886. {
  887. if (obj == null)
  888. throw new ArgumentNullException ();
  889. int hCode = 0;
  890. if (int.TryParse (obj.Id, out int result)) {
  891. hCode = result;
  892. }
  893. return hCode.GetHashCode ();
  894. }
  895. }
  896. /// <summary>
  897. /// Implements the <see cref="IComparer{T}"/> to sort the <see cref="Toplevel"/>
  898. /// from the <see cref="Application.OverlappedChildren"/> if needed.
  899. /// </summary>
  900. public sealed class ToplevelComparer : IComparer<Toplevel> {
  901. /// <summary>Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.</summary>
  902. /// <param name="x">The first object to compare.</param>
  903. /// <param name="y">The second object to compare.</param>
  904. /// <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
  905. /// <paramref name="x" /> is less than <paramref name="y" />.Zero
  906. /// <paramref name="x" /> equals <paramref name="y" />.Greater than zero
  907. /// <paramref name="x" /> is greater than <paramref name="y" />.</returns>
  908. public int Compare (Toplevel x, Toplevel y)
  909. {
  910. if (ReferenceEquals (x, y))
  911. return 0;
  912. else if (x == null)
  913. return -1;
  914. else if (y == null)
  915. return 1;
  916. else
  917. return string.Compare (x.Id, y.Id);
  918. }
  919. }
  920. }