Toplevel.cs 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085
  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 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 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 Action Loaded;
  37. /// <summary>
  38. /// Invoked when the 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 Toplevel.</para>
  43. /// </summary>
  44. public event Action 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 Action Unloaded;
  50. /// <summary>
  51. /// Invoked when the Toplevel <see cref="Application.RunState"/> becomes the <see cref="Application.Current"/> Toplevel.
  52. /// </summary>
  53. public event Action<Toplevel> 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 Action<Toplevel> 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 Action<Toplevel> 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 Action 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 Action<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 Action<Toplevel> Closed;
  77. /// <summary>
  78. /// Invoked when a child Toplevel's <see cref="Application.RunState"/> has been loaded.
  79. /// </summary>
  80. public event Action<Toplevel> ChildLoaded;
  81. /// <summary>
  82. /// Invoked when a cjhild Toplevel's <see cref="Application.RunState"/> has been unloaded.
  83. /// </summary>
  84. public event Action<Toplevel> 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 Action<Size> Resized;
  89. internal virtual void OnResized (Size size)
  90. {
  91. Resized?.Invoke (size);
  92. }
  93. internal virtual void OnChildUnloaded (Toplevel top)
  94. {
  95. ChildUnloaded?.Invoke (top);
  96. }
  97. internal virtual void OnChildLoaded (Toplevel top)
  98. {
  99. ChildLoaded?.Invoke (top);
  100. }
  101. internal virtual void OnClosed (Toplevel top)
  102. {
  103. Closed?.Invoke (top);
  104. }
  105. internal virtual bool OnClosing (ToplevelClosingEventArgs ev)
  106. {
  107. Closing?.Invoke (ev);
  108. return ev.Cancel;
  109. }
  110. internal virtual void OnAllChildClosed ()
  111. {
  112. AllChildClosed?.Invoke ();
  113. }
  114. internal virtual void OnChildClosed (Toplevel top)
  115. {
  116. if (IsMdiContainer) {
  117. SetSubViewNeedsDisplay ();
  118. }
  119. ChildClosed?.Invoke (top);
  120. }
  121. internal virtual void OnDeactivate (Toplevel activated)
  122. {
  123. Deactivate?.Invoke (activated);
  124. }
  125. internal virtual void OnActivate (Toplevel deactivated)
  126. {
  127. Activate?.Invoke (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 ();
  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 ();
  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 ();
  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. Initialize ();
  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. Initialize ();
  176. Width = Dim.Fill ();
  177. Height = Dim.Fill ();
  178. }
  179. void Initialize ()
  180. {
  181. ColorScheme = Colors.TopLevel;
  182. // TODO: v2 - ALL Views (Responders??!?!) should support the commands related to
  183. // - Focus
  184. // Move the appropriate AddCommand calls to `Responder`
  185. // Things this view knows how to do
  186. AddCommand (Command.QuitToplevel, () => { QuitToplevel (); return true; });
  187. AddCommand (Command.Suspend, () => { Driver.Suspend (); ; return true; });
  188. AddCommand (Command.NextView, () => { MoveNextView (); return true; });
  189. AddCommand (Command.PreviousView, () => { MovePreviousView (); return true; });
  190. AddCommand (Command.NextViewOrTop, () => { MoveNextViewOrTop (); return true; });
  191. AddCommand (Command.PreviousViewOrTop, () => { MovePreviousViewOrTop (); return true; });
  192. AddCommand (Command.Refresh, () => { Application.Refresh (); return true; });
  193. // Default keybindings for this view
  194. AddKeyBinding (Application.QuitKey, Command.QuitToplevel);
  195. AddKeyBinding (Key.Z | Key.CtrlMask, Command.Suspend);
  196. AddKeyBinding (Key.Tab, Command.NextView);
  197. AddKeyBinding (Key.CursorRight, Command.NextView);
  198. AddKeyBinding (Key.F | Key.CtrlMask, Command.NextView);
  199. AddKeyBinding (Key.CursorDown, Command.NextView);
  200. AddKeyBinding (Key.I | Key.CtrlMask, Command.NextView); // Unix
  201. AddKeyBinding (Key.BackTab | Key.ShiftMask, Command.PreviousView);
  202. AddKeyBinding (Key.CursorLeft, Command.PreviousView);
  203. AddKeyBinding (Key.CursorUp, Command.PreviousView);
  204. AddKeyBinding (Key.B | Key.CtrlMask, Command.PreviousView);
  205. AddKeyBinding (Key.Tab | Key.CtrlMask, Command.NextViewOrTop);
  206. AddKeyBinding (Application.AlternateForwardKey, Command.NextViewOrTop); // Needed on Unix
  207. AddKeyBinding (Key.Tab | Key.ShiftMask | Key.CtrlMask, Command.PreviousViewOrTop);
  208. AddKeyBinding (Application.AlternateBackwardKey, Command.PreviousViewOrTop); // Needed on Unix
  209. AddKeyBinding (Key.L | Key.CtrlMask, Command.Refresh);
  210. }
  211. /// <summary>
  212. /// Invoked when the <see cref="Application.AlternateForwardKey"/> is changed.
  213. /// </summary>
  214. public event Action<Key> AlternateForwardKeyChanged;
  215. /// <summary>
  216. /// Virtual method to invoke the <see cref="AlternateForwardKeyChanged"/> event.
  217. /// </summary>
  218. /// <param name="oldKey"></param>
  219. public virtual void OnAlternateForwardKeyChanged (Key oldKey)
  220. {
  221. ReplaceKeyBinding (oldKey, Application.AlternateForwardKey);
  222. AlternateForwardKeyChanged?.Invoke (oldKey);
  223. }
  224. /// <summary>
  225. /// Invoked when the <see cref="Application.AlternateBackwardKey"/> is changed.
  226. /// </summary>
  227. public event Action<Key> AlternateBackwardKeyChanged;
  228. /// <summary>
  229. /// Virtual method to invoke the <see cref="AlternateBackwardKeyChanged"/> event.
  230. /// </summary>
  231. /// <param name="oldKey"></param>
  232. public virtual void OnAlternateBackwardKeyChanged (Key oldKey)
  233. {
  234. ReplaceKeyBinding (oldKey, Application.AlternateBackwardKey);
  235. AlternateBackwardKeyChanged?.Invoke (oldKey);
  236. }
  237. /// <summary>
  238. /// Invoked when the <see cref="Application.QuitKey"/> is changed.
  239. /// </summary>
  240. public event Action<Key> QuitKeyChanged;
  241. /// <summary>
  242. /// Virtual method to invoke the <see cref="QuitKeyChanged"/> event.
  243. /// </summary>
  244. /// <param name="oldKey"></param>
  245. public virtual void OnQuitKeyChanged (Key oldKey)
  246. {
  247. ReplaceKeyBinding (oldKey, Application.QuitKey);
  248. QuitKeyChanged?.Invoke (oldKey);
  249. }
  250. /// <summary>
  251. /// Convenience factory method that creates a new Toplevel with the current terminal dimensions.
  252. /// </summary>
  253. /// <returns>The created Toplevel.</returns>
  254. public static Toplevel Create ()
  255. {
  256. return new Toplevel (new Rect (0, 0, Driver.Cols, Driver.Rows));
  257. }
  258. /// <summary>
  259. /// Gets or sets a value indicating whether this <see cref="Toplevel"/> can focus.
  260. /// </summary>
  261. /// <value><c>true</c> if can focus; otherwise, <c>false</c>.</value>
  262. public override bool CanFocus {
  263. get => SuperView == null ? true : base.CanFocus;
  264. }
  265. /// <summary>
  266. /// Determines whether the <see cref="Toplevel"/> is modal or not.
  267. /// If set to <c>false</c> (the default):
  268. ///
  269. /// <list type="bullet">
  270. /// <item>
  271. /// <description><see cref="ProcessKey(KeyEvent)"/> events will propagate keys upwards.</description>
  272. /// </item>
  273. /// <item>
  274. /// <description>The Toplevel will act as an embedded view (not a modal/pop-up).</description>
  275. /// </item>
  276. /// </list>
  277. ///
  278. /// If set to <c>true</c>:
  279. ///
  280. /// <list type="bullet">
  281. /// <item>
  282. /// <description><see cref="ProcessKey(KeyEvent)"/> events will NOT propogate keys upwards.</description>
  283. /// </item>
  284. /// <item>
  285. /// <description>The Toplevel will and look like a modal (pop-up) (e.g. see <see cref="Dialog"/>.</description>
  286. /// </item>
  287. /// </list>
  288. /// </summary>
  289. public bool Modal { get; set; }
  290. /// <summary>
  291. /// Gets or sets the menu for this Toplevel.
  292. /// </summary>
  293. public virtual MenuBar MenuBar { get; set; }
  294. /// <summary>
  295. /// Gets or sets the status bar for this Toplevel.
  296. /// </summary>
  297. public virtual StatusBar StatusBar { get; set; }
  298. /// <summary>
  299. /// Gets or sets if this Toplevel is a Mdi container.
  300. /// </summary>
  301. public bool IsMdiContainer { get; set; }
  302. /// <summary>
  303. /// Gets or sets if this Toplevel is a Mdi child.
  304. /// </summary>
  305. public bool IsMdiChild {
  306. get {
  307. return Application.MdiTop != null && Application.MdiTop != this && !Modal;
  308. }
  309. }
  310. /// <summary>
  311. /// <see langword="true"/> if was already loaded by the <see cref="Application.Begin(Toplevel)"/>
  312. /// <see langword="false"/>, otherwise. This is used to avoid the <see cref="View._needsDisplay"/>
  313. /// having wrong values while this was not yet loaded.
  314. /// </summary>
  315. public bool IsLoaded { get; private set; }
  316. ///<inheritdoc/>
  317. public override bool OnKeyDown (KeyEvent keyEvent)
  318. {
  319. if (base.OnKeyDown (keyEvent)) {
  320. return true;
  321. }
  322. switch (keyEvent.Key) {
  323. case Key.AltMask:
  324. case Key.AltMask | Key.Space:
  325. case Key.CtrlMask | Key.Space:
  326. case Key _ when (keyEvent.Key & Key.AltMask) == Key.AltMask:
  327. return MenuBar != null && MenuBar.OnKeyDown (keyEvent);
  328. }
  329. return false;
  330. }
  331. ///<inheritdoc/>
  332. public override bool OnKeyUp (KeyEvent keyEvent)
  333. {
  334. if (base.OnKeyUp (keyEvent)) {
  335. return true;
  336. }
  337. switch (keyEvent.Key) {
  338. case Key.AltMask:
  339. case Key.AltMask | Key.Space:
  340. case Key.CtrlMask | Key.Space:
  341. if (MenuBar != null && MenuBar.OnKeyUp (keyEvent)) {
  342. return true;
  343. }
  344. break;
  345. }
  346. return false;
  347. }
  348. ///<inheritdoc/>
  349. public override bool ProcessKey (KeyEvent keyEvent)
  350. {
  351. if (base.ProcessKey (keyEvent))
  352. return true;
  353. var result = InvokeKeybindings (new KeyEvent (ShortcutHelper.GetModifiersKey (keyEvent),
  354. new KeyModifiers () { Alt = keyEvent.IsAlt, Ctrl = keyEvent.IsCtrl, Shift = keyEvent.IsShift }));
  355. if (result != null)
  356. return (bool)result;
  357. #if false
  358. if (keyEvent.Key == Key.F5) {
  359. Application.DebugDrawBounds = !Application.DebugDrawBounds;
  360. SetNeedsDisplay ();
  361. return true;
  362. }
  363. #endif
  364. return false;
  365. }
  366. private void MovePreviousViewOrTop ()
  367. {
  368. if (Application.MdiTop == null) {
  369. var top = Modal ? this : Application.Top;
  370. top.FocusPrev ();
  371. if (top.Focused == null) {
  372. top.FocusPrev ();
  373. }
  374. top.SetNeedsDisplay ();
  375. Application.EnsuresTopOnFront ();
  376. } else {
  377. MovePrevious ();
  378. }
  379. }
  380. private void MoveNextViewOrTop ()
  381. {
  382. if (Application.MdiTop == null) {
  383. var top = Modal ? this : Application.Top;
  384. top.FocusNext ();
  385. if (top.Focused == null) {
  386. top.FocusNext ();
  387. }
  388. top.SetNeedsDisplay ();
  389. Application.EnsuresTopOnFront ();
  390. } else {
  391. MoveNext ();
  392. }
  393. }
  394. private void MovePreviousView ()
  395. {
  396. var old = GetDeepestFocusedSubview (Focused);
  397. if (!FocusPrev ())
  398. FocusPrev ();
  399. if (old != Focused && old != Focused?.Focused) {
  400. old?.SetNeedsDisplay ();
  401. Focused?.SetNeedsDisplay ();
  402. } else {
  403. FocusNearestView (SuperView?.TabIndexes?.Reverse (), Direction.Backward);
  404. }
  405. }
  406. private void MoveNextView ()
  407. {
  408. var old = GetDeepestFocusedSubview (Focused);
  409. if (!FocusNext ())
  410. FocusNext ();
  411. if (old != Focused && old != Focused?.Focused) {
  412. old?.SetNeedsDisplay ();
  413. Focused?.SetNeedsDisplay ();
  414. } else {
  415. FocusNearestView (SuperView?.TabIndexes, Direction.Forward);
  416. }
  417. }
  418. private void QuitToplevel ()
  419. {
  420. if (Application.MdiTop != null) {
  421. Application.MdiTop.RequestStop ();
  422. } else {
  423. Application.RequestStop ();
  424. }
  425. }
  426. ///<inheritdoc/>
  427. public override bool ProcessColdKey (KeyEvent keyEvent)
  428. {
  429. if (base.ProcessColdKey (keyEvent)) {
  430. return true;
  431. }
  432. if (ShortcutHelper.FindAndOpenByShortcut (keyEvent, this)) {
  433. return true;
  434. }
  435. return false;
  436. }
  437. View GetDeepestFocusedSubview (View view)
  438. {
  439. if (view == null) {
  440. return null;
  441. }
  442. foreach (var v in view.Subviews) {
  443. if (v.HasFocus) {
  444. return GetDeepestFocusedSubview (v);
  445. }
  446. }
  447. return view;
  448. }
  449. void FocusNearestView (IEnumerable<View> views, Direction direction)
  450. {
  451. if (views == null) {
  452. return;
  453. }
  454. bool found = false;
  455. bool focusProcessed = false;
  456. int idx = 0;
  457. foreach (var v in views) {
  458. if (v == this) {
  459. found = true;
  460. }
  461. if (found && v != this) {
  462. if (direction == Direction.Forward) {
  463. SuperView?.FocusNext ();
  464. } else {
  465. SuperView?.FocusPrev ();
  466. }
  467. focusProcessed = true;
  468. if (SuperView.Focused != null && SuperView.Focused != this) {
  469. return;
  470. }
  471. } else if (found && !focusProcessed && idx == views.Count () - 1) {
  472. views.ToList () [0].SetFocus ();
  473. }
  474. idx++;
  475. }
  476. }
  477. ///<inheritdoc/>
  478. public override void Add (View view)
  479. {
  480. AddMenuStatusBar (view);
  481. base.Add (view);
  482. }
  483. internal void AddMenuStatusBar (View view)
  484. {
  485. if (view is MenuBar) {
  486. MenuBar = view as MenuBar;
  487. }
  488. if (view is StatusBar) {
  489. StatusBar = view as StatusBar;
  490. }
  491. }
  492. ///<inheritdoc/>
  493. public override void Remove (View view)
  494. {
  495. if (this is Toplevel toplevel && toplevel.MenuBar != null) {
  496. RemoveMenuStatusBar (view);
  497. }
  498. base.Remove (view);
  499. }
  500. ///<inheritdoc/>
  501. public override void RemoveAll ()
  502. {
  503. if (this == Application.Top) {
  504. MenuBar?.Dispose ();
  505. MenuBar = null;
  506. StatusBar?.Dispose ();
  507. StatusBar = null;
  508. }
  509. base.RemoveAll ();
  510. }
  511. internal void RemoveMenuStatusBar (View view)
  512. {
  513. if (view is MenuBar) {
  514. MenuBar?.Dispose ();
  515. MenuBar = null;
  516. }
  517. if (view is StatusBar) {
  518. StatusBar?.Dispose ();
  519. StatusBar = null;
  520. }
  521. }
  522. /// <summary>
  523. /// Ensures the new position of the <see cref="Toplevel"/> is within the bounds of the screen (e.g. for dragging a Window).
  524. /// The `out` parameters are the new X and Y coordinates.
  525. /// </summary>
  526. /// <param name="top">The Toplevel that is to be moved.</param>
  527. /// <param name="x">The target x location.</param>
  528. /// <param name="y">The target y location.</param>
  529. /// <param name="nx">The x location after ensuring <paramref name="top"/> will remain visible.</param>
  530. /// <param name="ny">The y location after ensuring <paramref name="top"/> will remain visible.</param>
  531. /// <param name="menuBar">The new top most menuBar</param>
  532. /// <param name="statusBar">The new top most statusBar</param>
  533. /// <returns>The <see cref="Toplevel"/> that is Application.Top</returns>
  534. internal View EnsureVisibleBounds (Toplevel top, int x, int y,
  535. out int nx, out int ny, out MenuBar menuBar, out StatusBar statusBar)
  536. {
  537. int maxWidth;
  538. View superView;
  539. var isTopTop = top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top;
  540. if (isTopTop) {
  541. maxWidth = Driver.Cols;
  542. superView = Application.Top;
  543. } else {
  544. maxWidth = top.SuperView.Frame.Width;
  545. // BUGBUG: v2 - No code ever uses the return of this function if `top` is not Application.Top
  546. superView = top.SuperView;
  547. }
  548. nx = Math.Max (x, 0);
  549. nx = nx + top.Frame.Width > maxWidth ? Math.Max (maxWidth - top.Frame.Width, 0) : nx;
  550. var mfLength = top.Border?.DrawMarginFrame == true ? 2 : 1;
  551. if (nx + mfLength > top.Frame.X + top.Frame.Width) {
  552. nx = Math.Max (top.Frame.Right - mfLength, 0);
  553. }
  554. //System.Diagnostics.Debug.WriteLine ($"nx:{nx}, rWidth:{rWidth}");
  555. bool isMenuBarVisible, isStatusBarVisible;
  556. if (isTopTop) {
  557. isMenuBarVisible = Application.Top.MenuBar?.Visible == true;
  558. menuBar = Application.Top.MenuBar;
  559. } else {
  560. var t = top.SuperView;
  561. while (!(t is Toplevel)) {
  562. t = t.SuperView;
  563. }
  564. isMenuBarVisible = ((Toplevel)t).MenuBar?.Visible == true;
  565. menuBar = ((Toplevel)t).MenuBar;
  566. }
  567. if (isTopTop) {
  568. maxWidth = isMenuBarVisible ? 1 : 0;
  569. } else {
  570. maxWidth = 0;
  571. }
  572. ny = Math.Max (y, maxWidth);
  573. if (isTopTop) {
  574. isStatusBarVisible = Application.Top.StatusBar?.Visible == true;
  575. statusBar = Application.Top.StatusBar;
  576. } else {
  577. var t = top.SuperView;
  578. while (!(t is Toplevel)) {
  579. t = t.SuperView;
  580. }
  581. isStatusBarVisible = ((Toplevel)t).StatusBar?.Visible == true;
  582. statusBar = ((Toplevel)t).StatusBar;
  583. }
  584. if (isTopTop) {
  585. maxWidth = isStatusBarVisible ? Driver.Rows - 1 : Driver.Rows;
  586. } else {
  587. maxWidth = isStatusBarVisible ? top.SuperView.Frame.Height - 1 : top.SuperView.Frame.Height;
  588. }
  589. ny = Math.Min (ny, maxWidth);
  590. ny = ny + top.Frame.Height >= maxWidth ? Math.Max (maxWidth - top.Frame.Height, isMenuBarVisible ? 1 : 0) : ny;
  591. if (ny + mfLength > top.Frame.Y + top.Frame.Height) {
  592. ny = Math.Max (top.Frame.Bottom - mfLength, 0);
  593. }
  594. //System.Diagnostics.Debug.WriteLine ($"ny:{ny}, rHeight:{rHeight}");
  595. return superView;
  596. }
  597. // TODO: v2 - Not sure this is needed anymore.
  598. internal void PositionToplevels ()
  599. {
  600. PositionToplevel (this);
  601. foreach (var top in Subviews) {
  602. if (top is Toplevel) {
  603. PositionToplevel ((Toplevel)top);
  604. }
  605. }
  606. }
  607. /// <summary>
  608. /// Adjusts the location and size of <paramref name="top"/> within this Toplevel.
  609. /// Virtual method enabling implementation of specific positions for inherited <see cref="Toplevel"/> views.
  610. /// </summary>
  611. /// <param name="top">The Toplevel to adjust.</param>
  612. public virtual void PositionToplevel (Toplevel top)
  613. {
  614. var superView = EnsureVisibleBounds (top, top.Frame.X, top.Frame.Y,
  615. out int nx, out int ny, out _, out StatusBar sb);
  616. bool layoutSubviews = false;
  617. if ((top?.SuperView != null || (top != Application.Top && top.Modal)
  618. || (top?.SuperView == null && top.IsMdiChild))
  619. && (nx > top.Frame.X || ny > top.Frame.Y) && top.LayoutStyle == LayoutStyle.Computed) {
  620. if ((top.X == null || top.X is Pos.PosAbsolute) && top.Bounds.X != nx) {
  621. top.X = nx;
  622. layoutSubviews = true;
  623. }
  624. if ((top.Y == null || top.Y is Pos.PosAbsolute) && top.Bounds.Y != ny) {
  625. top.Y = ny;
  626. layoutSubviews = true;
  627. }
  628. }
  629. // TODO: v2 - This is a hack to get the StatusBar to be positioned correctly.
  630. if (sb != null && ny + top.Frame.Height != superView.Frame.Height - (sb.Visible ? 1 : 0)
  631. && top.Height is Dim.DimFill && -top.Height.Anchor (0) < 1) {
  632. top.Height = Dim.Fill (sb.Visible ? 1 : 0);
  633. layoutSubviews = true;
  634. }
  635. if (layoutSubviews) {
  636. superView.LayoutSubviews ();
  637. }
  638. }
  639. ///<inheritdoc/>
  640. //public override void Redraw (Rect bounds)
  641. //{
  642. // if (!Visible) {
  643. // return;
  644. // }
  645. // if (!_needsDisplay.IsEmpty || _childNeedsDisplay || LayoutNeeded) {
  646. // Driver.SetAttribute (GetNormalColor ());
  647. // // This is the Application.Top. Clear just the region we're being asked to redraw
  648. // // (the bounds passed to us).
  649. // Clear ();
  650. // Driver.SetAttribute (Enabled ? Colors.Base.Normal : Colors.Base.Disabled);
  651. // LayoutSubviews ();
  652. // PositionToplevels ();
  653. // if (this == Application.MdiTop) {
  654. // foreach (var top in Application.MdiChildes.AsEnumerable ().Reverse ()) {
  655. // if (top.Frame.IntersectsWith (bounds)) {
  656. // if (top != this && !top.IsCurrentTop && !OutsideTopFrame (top) && top.Visible) {
  657. // top.SetNeedsLayout ();
  658. // top.SetNeedsDisplay (top.Bounds);
  659. // top.Redraw (top.Bounds);
  660. // }
  661. // }
  662. // }
  663. // }
  664. // foreach (var view in Subviews) {
  665. // if (view.Frame.IntersectsWith (bounds) && !OutsideTopFrame (this)) {
  666. // view.SetNeedsLayout ();
  667. // view.SetNeedsDisplay (view.Bounds);
  668. // }
  669. // }
  670. // // BUGBUG: shouldn't we just return here? the call to base.Redraw below is redundant
  671. // }
  672. // base.Redraw (Bounds);
  673. //}
  674. bool OutsideTopFrame (Toplevel top)
  675. {
  676. if (top.Frame.X > Driver.Cols || top.Frame.Y > Driver.Rows) {
  677. return true;
  678. }
  679. return false;
  680. }
  681. internal static Point? dragPosition;
  682. Point start;
  683. ///<inheritdoc/>
  684. public override bool MouseEvent (MouseEvent mouseEvent)
  685. {
  686. if (!CanFocus) {
  687. return true;
  688. }
  689. //System.Diagnostics.Debug.WriteLine ($"dragPosition before: {dragPosition.HasValue}");
  690. int nx, ny;
  691. if (!dragPosition.HasValue && (mouseEvent.Flags == MouseFlags.Button1Pressed
  692. || mouseEvent.Flags == MouseFlags.Button2Pressed
  693. || mouseEvent.Flags == MouseFlags.Button3Pressed)) {
  694. SetFocus ();
  695. Application.EnsuresTopOnFront ();
  696. // Only start grabbing if the user clicks on the title bar.
  697. if (mouseEvent.Y == 0 && mouseEvent.Flags == MouseFlags.Button1Pressed) {
  698. start = new Point (mouseEvent.X, mouseEvent.Y);
  699. dragPosition = new Point ();
  700. nx = mouseEvent.X - mouseEvent.OfX;
  701. ny = mouseEvent.Y - mouseEvent.OfY;
  702. dragPosition = new Point (nx, ny);
  703. Application.GrabMouse (this);
  704. }
  705. //System.Diagnostics.Debug.WriteLine ($"Starting at {dragPosition}");
  706. return true;
  707. } else if (mouseEvent.Flags == (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) ||
  708. mouseEvent.Flags == MouseFlags.Button3Pressed) {
  709. if (dragPosition.HasValue) {
  710. if (SuperView == null) {
  711. // Redraw the entire app window using just our Frame. Since we are
  712. // Application.Top, and our Frame always == our Bounds (Location is always (0,0))
  713. // our Frame is actually view-relative (which is what Redraw takes).
  714. // We need to pass all the view bounds because since the windows was
  715. // moved around, we don't know exactly what was the affected region.
  716. Application.Top.SetNeedsDisplay ();
  717. } else {
  718. SuperView.SetNeedsDisplay ();
  719. }
  720. EnsureVisibleBounds (this, mouseEvent.X + (SuperView == null ? mouseEvent.OfX - start.X : Frame.X - start.X),
  721. mouseEvent.Y + (SuperView == null ? mouseEvent.OfY - start.Y : Frame.Y - start.Y),
  722. out nx, out ny, out _, out _);
  723. dragPosition = new Point (nx, ny);
  724. X = nx;
  725. Y = ny;
  726. //System.Diagnostics.Debug.WriteLine ($"Drag: nx:{nx},ny:{ny}");
  727. SetNeedsDisplay ();
  728. return true;
  729. }
  730. }
  731. if (mouseEvent.Flags.HasFlag (MouseFlags.Button1Released) && dragPosition.HasValue) {
  732. Application.UngrabMouse ();
  733. dragPosition = null;
  734. }
  735. //System.Diagnostics.Debug.WriteLine ($"dragPosition after: {dragPosition.HasValue}");
  736. //System.Diagnostics.Debug.WriteLine ($"Toplevel: {mouseEvent}");
  737. return false;
  738. }
  739. /// <summary>
  740. /// Invoked by <see cref="Application.Begin"/> as part of <see cref="Application.Run(Toplevel, Func{Exception, bool})"/>
  741. /// after the views have been laid out, and before the views are drawn for the first time.
  742. /// </summary>
  743. public virtual void WillPresent ()
  744. {
  745. FocusFirst ();
  746. }
  747. /// <summary>
  748. /// Move to the next Mdi child from the <see cref="Application.MdiTop"/>.
  749. /// </summary>
  750. public virtual void MoveNext ()
  751. {
  752. Application.MoveNext ();
  753. }
  754. /// <summary>
  755. /// Move to the previous Mdi child from the <see cref="Application.MdiTop"/>.
  756. /// </summary>
  757. public virtual void MovePrevious ()
  758. {
  759. Application.MovePrevious ();
  760. }
  761. /// <summary>
  762. /// Stops and closes this <see cref="Toplevel"/>. If this Toplevel is the top-most Toplevel,
  763. /// <see cref="Application.RequestStop(Toplevel)"/> will be called, causing the application to exit.
  764. /// </summary>
  765. public virtual void RequestStop ()
  766. {
  767. if (IsMdiContainer && Running
  768. && (Application.Current == this
  769. || Application.Current?.Modal == false
  770. || Application.Current?.Modal == true && Application.Current?.Running == false)) {
  771. foreach (var child in Application.MdiChildes) {
  772. var ev = new ToplevelClosingEventArgs (this);
  773. if (child.OnClosing (ev)) {
  774. return;
  775. }
  776. child.Running = false;
  777. Application.RequestStop (child);
  778. }
  779. Running = false;
  780. Application.RequestStop (this);
  781. } else if (IsMdiContainer && Running && Application.Current?.Modal == true && Application.Current?.Running == true) {
  782. var ev = new ToplevelClosingEventArgs (Application.Current);
  783. if (OnClosing (ev)) {
  784. return;
  785. }
  786. Application.RequestStop (Application.Current);
  787. } else if (!IsMdiContainer && Running && (!Modal || (Modal && Application.Current != this))) {
  788. var ev = new ToplevelClosingEventArgs (this);
  789. if (OnClosing (ev)) {
  790. return;
  791. }
  792. Running = false;
  793. Application.RequestStop (this);
  794. } else {
  795. Application.RequestStop (Application.Current);
  796. }
  797. }
  798. /// <summary>
  799. /// Stops and closes the <see cref="Toplevel"/> specified by <paramref name="top"/>. If <paramref name="top"/> is the top-most Toplevel,
  800. /// <see cref="Application.RequestStop(Toplevel)"/> will be called, causing the application to exit.
  801. /// </summary>
  802. /// <param name="top">The toplevel to request stop.</param>
  803. public virtual void RequestStop (Toplevel top)
  804. {
  805. top.RequestStop ();
  806. }
  807. ///<inheritdoc/>
  808. public override void PositionCursor ()
  809. {
  810. if (!IsMdiContainer) {
  811. base.PositionCursor ();
  812. if (Focused == null) {
  813. EnsureFocus ();
  814. if (Focused == null) {
  815. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  816. }
  817. }
  818. return;
  819. }
  820. if (Focused == null) {
  821. foreach (var top in Application.MdiChildes) {
  822. if (top != this && top.Visible) {
  823. top.SetFocus ();
  824. return;
  825. }
  826. }
  827. }
  828. base.PositionCursor ();
  829. if (Focused == null) {
  830. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  831. }
  832. }
  833. /// <summary>
  834. /// Gets the current visible Toplevel Mdi child that matches the arguments pattern.
  835. /// </summary>
  836. /// <param name="type">The type.</param>
  837. /// <param name="exclude">The strings to exclude.</param>
  838. /// <returns>The matched view.</returns>
  839. public View GetTopMdiChild (Type type = null, string [] exclude = null)
  840. {
  841. if (Application.MdiTop == null) {
  842. return null;
  843. }
  844. foreach (var top in Application.MdiChildes) {
  845. if (type != null && top.GetType () == type
  846. && exclude?.Contains (top.Data.ToString ()) == false) {
  847. return top;
  848. } else if ((type != null && top.GetType () != type)
  849. || (exclude?.Contains (top.Data.ToString ()) == true)) {
  850. continue;
  851. }
  852. return top;
  853. }
  854. return null;
  855. }
  856. /// <summary>
  857. /// Shows the Mdi child indicated by <paramref name="top"/>, setting it as <see cref="Application.Current"/>.
  858. /// </summary>
  859. /// <param name="top">The Toplevel.</param>
  860. /// <returns><c>true</c> if the toplevel can be shown or <c>false</c> if not.</returns>
  861. public virtual bool ShowChild (Toplevel top = null)
  862. {
  863. if (Application.MdiTop != null) {
  864. return Application.ShowChild (top == null ? this : top);
  865. }
  866. return false;
  867. }
  868. ///<inheritdoc/>
  869. public override bool OnEnter (View view)
  870. {
  871. return MostFocused?.OnEnter (view) ?? base.OnEnter (view);
  872. }
  873. ///<inheritdoc/>
  874. public override bool OnLeave (View view)
  875. {
  876. return MostFocused?.OnLeave (view) ?? base.OnLeave (view);
  877. }
  878. }
  879. /// <summary>
  880. /// Implements the <see cref="IEqualityComparer{T}"/> for comparing two <see cref="Toplevel"/>s
  881. /// used by <see cref="StackExtensions"/>.
  882. /// </summary>
  883. public class ToplevelEqualityComparer : IEqualityComparer<Toplevel> {
  884. /// <summary>Determines whether the specified objects are equal.</summary>
  885. /// <param name="x">The first object of type <see cref="Toplevel" /> to compare.</param>
  886. /// <param name="y">The second object of type <see cref="Toplevel" /> to compare.</param>
  887. /// <returns>
  888. /// <see langword="true" /> if the specified objects are equal; otherwise, <see langword="false" />.</returns>
  889. public bool Equals (Toplevel x, Toplevel y)
  890. {
  891. if (y == null && x == null)
  892. return true;
  893. else if (x == null || y == null)
  894. return false;
  895. else if (x.Id == y.Id)
  896. return true;
  897. else
  898. return false;
  899. }
  900. /// <summary>Returns a hash code for the specified object.</summary>
  901. /// <param name="obj">The <see cref="Toplevel" /> for which a hash code is to be returned.</param>
  902. /// <returns>A hash code for the specified object.</returns>
  903. /// <exception cref="ArgumentNullException">The type of <paramref name="obj" />
  904. /// is a reference type and <paramref name="obj" /> is <see langword="null" />.</exception>
  905. public int GetHashCode (Toplevel obj)
  906. {
  907. if (obj == null)
  908. throw new ArgumentNullException ();
  909. int hCode = 0;
  910. if (int.TryParse (obj.Id.ToString (), out int result)) {
  911. hCode = result;
  912. }
  913. return hCode.GetHashCode ();
  914. }
  915. }
  916. /// <summary>
  917. /// Implements the <see cref="IComparer{T}"/> to sort the <see cref="Toplevel"/>
  918. /// from the <see cref="Application.MdiChildes"/> if needed.
  919. /// </summary>
  920. public sealed class ToplevelComparer : IComparer<Toplevel> {
  921. /// <summary>Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.</summary>
  922. /// <param name="x">The first object to compare.</param>
  923. /// <param name="y">The second object to compare.</param>
  924. /// <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
  925. /// <paramref name="x" /> is less than <paramref name="y" />.Zero
  926. /// <paramref name="x" /> equals <paramref name="y" />.Greater than zero
  927. /// <paramref name="x" /> is greater than <paramref name="y" />.</returns>
  928. public int Compare (Toplevel x, Toplevel y)
  929. {
  930. if (ReferenceEquals (x, y))
  931. return 0;
  932. else if (x == null)
  933. return -1;
  934. else if (y == null)
  935. return 1;
  936. else
  937. return string.Compare (x.Id.ToString (), y.Id.ToString ());
  938. }
  939. }
  940. /// <summary>
  941. /// <see cref="EventArgs"/> implementation for the <see cref="Toplevel.Closing"/> event.
  942. /// </summary>
  943. public class ToplevelClosingEventArgs : EventArgs {
  944. /// <summary>
  945. /// The toplevel requesting stop.
  946. /// </summary>
  947. public View RequestingTop { get; }
  948. /// <summary>
  949. /// Provides an event cancellation option.
  950. /// </summary>
  951. public bool Cancel { get; set; }
  952. /// <summary>
  953. /// Initializes the event arguments with the requesting toplevel.
  954. /// </summary>
  955. /// <param name="requestingTop">The <see cref="RequestingTop"/>.</param>
  956. public ToplevelClosingEventArgs (Toplevel requestingTop)
  957. {
  958. RequestingTop = requestingTop;
  959. }
  960. }
  961. }