Toplevel.cs 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091
  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 EventHandler 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 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> Resized;
  89. internal virtual void OnResized (SizeChangedEventArgs size)
  90. {
  91. Resized?.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 (IsMdiContainer) {
  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. /// Gets or sets if this Toplevel is a Mdi container.
  314. /// </summary>
  315. public bool IsMdiContainer { get; set; }
  316. /// <summary>
  317. /// Gets or sets if this Toplevel is a Mdi child.
  318. /// </summary>
  319. public bool IsMdiChild {
  320. get {
  321. return Application.MdiTop != null && Application.MdiTop != this && !Modal;
  322. }
  323. }
  324. /// <summary>
  325. /// <see langword="true"/> if was already loaded by the <see cref="Application.Begin(Toplevel)"/>
  326. /// <see langword="false"/>, otherwise.
  327. /// </summary>
  328. public bool IsLoaded { get; private set; }
  329. ///<inheritdoc/>
  330. public override bool OnKeyDown (KeyEvent keyEvent)
  331. {
  332. if (base.OnKeyDown (keyEvent)) {
  333. return true;
  334. }
  335. switch (keyEvent.Key) {
  336. case Key.AltMask:
  337. case Key.AltMask | Key.Space:
  338. case Key.CtrlMask | Key.Space:
  339. case Key _ when (keyEvent.Key & Key.AltMask) == Key.AltMask:
  340. return MenuBar != null && MenuBar.OnKeyDown (keyEvent);
  341. }
  342. return false;
  343. }
  344. ///<inheritdoc/>
  345. public override bool OnKeyUp (KeyEvent keyEvent)
  346. {
  347. if (base.OnKeyUp (keyEvent)) {
  348. return true;
  349. }
  350. switch (keyEvent.Key) {
  351. case Key.AltMask:
  352. case Key.AltMask | Key.Space:
  353. case Key.CtrlMask | Key.Space:
  354. if (MenuBar != null && MenuBar.OnKeyUp (keyEvent)) {
  355. return true;
  356. }
  357. break;
  358. }
  359. return false;
  360. }
  361. ///<inheritdoc/>
  362. public override bool ProcessKey (KeyEvent keyEvent)
  363. {
  364. if (base.ProcessKey (keyEvent))
  365. return true;
  366. var result = InvokeKeybindings (new KeyEvent (ShortcutHelper.GetModifiersKey (keyEvent),
  367. new KeyModifiers () { Alt = keyEvent.IsAlt, Ctrl = keyEvent.IsCtrl, Shift = keyEvent.IsShift }));
  368. if (result != null)
  369. return (bool)result;
  370. #if false
  371. if (keyEvent.Key == Key.F5) {
  372. Application.DebugDrawBounds = !Application.DebugDrawBounds;
  373. SetNeedsDisplay ();
  374. return true;
  375. }
  376. #endif
  377. return false;
  378. }
  379. private void MovePreviousViewOrTop ()
  380. {
  381. if (Application.MdiTop == null) {
  382. var top = Modal ? this : Application.Top;
  383. top.FocusPrev ();
  384. if (top.Focused == null) {
  385. top.FocusPrev ();
  386. }
  387. top.SetNeedsDisplay ();
  388. Application.EnsuresTopOnFront ();
  389. } else {
  390. MovePrevious ();
  391. }
  392. }
  393. private void MoveNextViewOrTop ()
  394. {
  395. if (Application.MdiTop == null) {
  396. var top = Modal ? this : Application.Top;
  397. top.FocusNext ();
  398. if (top.Focused == null) {
  399. top.FocusNext ();
  400. }
  401. top.SetNeedsDisplay ();
  402. Application.EnsuresTopOnFront ();
  403. } else {
  404. MoveNext ();
  405. }
  406. }
  407. private void MovePreviousView ()
  408. {
  409. var old = GetDeepestFocusedSubview (Focused);
  410. if (!FocusPrev ())
  411. FocusPrev ();
  412. if (old != Focused && old != Focused?.Focused) {
  413. old?.SetNeedsDisplay ();
  414. Focused?.SetNeedsDisplay ();
  415. } else {
  416. FocusNearestView (SuperView?.TabIndexes?.Reverse (), Direction.Backward);
  417. }
  418. }
  419. private void MoveNextView ()
  420. {
  421. var old = GetDeepestFocusedSubview (Focused);
  422. if (!FocusNext ())
  423. FocusNext ();
  424. if (old != Focused && old != Focused?.Focused) {
  425. old?.SetNeedsDisplay ();
  426. Focused?.SetNeedsDisplay ();
  427. } else {
  428. FocusNearestView (SuperView?.TabIndexes, Direction.Forward);
  429. }
  430. }
  431. private void QuitToplevel ()
  432. {
  433. if (Application.MdiTop != null) {
  434. Application.MdiTop.RequestStop ();
  435. } else {
  436. Application.RequestStop ();
  437. }
  438. }
  439. ///<inheritdoc/>
  440. public override bool ProcessColdKey (KeyEvent keyEvent)
  441. {
  442. if (base.ProcessColdKey (keyEvent)) {
  443. return true;
  444. }
  445. if (ShortcutHelper.FindAndOpenByShortcut (keyEvent, this)) {
  446. return true;
  447. }
  448. return false;
  449. }
  450. View GetDeepestFocusedSubview (View view)
  451. {
  452. if (view == null) {
  453. return null;
  454. }
  455. foreach (var v in view.Subviews) {
  456. if (v.HasFocus) {
  457. return GetDeepestFocusedSubview (v);
  458. }
  459. }
  460. return view;
  461. }
  462. void FocusNearestView (IEnumerable<View> views, Direction direction)
  463. {
  464. if (views == null) {
  465. return;
  466. }
  467. bool found = false;
  468. bool focusProcessed = false;
  469. int idx = 0;
  470. foreach (var v in views) {
  471. if (v == this) {
  472. found = true;
  473. }
  474. if (found && v != this) {
  475. if (direction == Direction.Forward) {
  476. SuperView?.FocusNext ();
  477. } else {
  478. SuperView?.FocusPrev ();
  479. }
  480. focusProcessed = true;
  481. if (SuperView.Focused != null && SuperView.Focused != this) {
  482. return;
  483. }
  484. } else if (found && !focusProcessed && idx == views.Count () - 1) {
  485. views.ToList () [0].SetFocus ();
  486. }
  487. idx++;
  488. }
  489. }
  490. ///<inheritdoc/>
  491. public override void Add (View view)
  492. {
  493. AddMenuStatusBar (view);
  494. base.Add (view);
  495. }
  496. internal void AddMenuStatusBar (View view)
  497. {
  498. if (view is MenuBar) {
  499. MenuBar = view as MenuBar;
  500. }
  501. if (view is StatusBar) {
  502. StatusBar = view as StatusBar;
  503. }
  504. }
  505. ///<inheritdoc/>
  506. public override void Remove (View view)
  507. {
  508. if (this is Toplevel toplevel && toplevel.MenuBar != null) {
  509. RemoveMenuStatusBar (view);
  510. }
  511. base.Remove (view);
  512. }
  513. ///<inheritdoc/>
  514. public override void RemoveAll ()
  515. {
  516. if (this == Application.Top) {
  517. MenuBar?.Dispose ();
  518. MenuBar = null;
  519. StatusBar?.Dispose ();
  520. StatusBar = null;
  521. }
  522. base.RemoveAll ();
  523. }
  524. internal void RemoveMenuStatusBar (View view)
  525. {
  526. if (view is MenuBar) {
  527. MenuBar?.Dispose ();
  528. MenuBar = null;
  529. }
  530. if (view is StatusBar) {
  531. StatusBar?.Dispose ();
  532. StatusBar = null;
  533. }
  534. }
  535. /// <summary>
  536. /// Ensures the new position of the <see cref="Toplevel"/> is within the bounds of the screen (e.g. for dragging a Window).
  537. /// The `out` parameters are the new X and Y coordinates.
  538. /// </summary>
  539. /// <param name="top">The Toplevel that is to be moved.</param>
  540. /// <param name="x">The target x location.</param>
  541. /// <param name="y">The target y location.</param>
  542. /// <param name="nx">The x location after ensuring <paramref name="top"/> will remain visible.</param>
  543. /// <param name="ny">The y location after ensuring <paramref name="top"/> will remain visible.</param>
  544. /// <param name="mb">The new top most menuBar</param>
  545. /// <param name="sb">The new top most statusBar</param>
  546. /// <returns>The <see cref="Toplevel"/> that is Application.Top</returns>
  547. internal View EnsureVisibleBounds (Toplevel top, int x, int y,
  548. out int nx, out int ny, out MenuBar mb, out StatusBar sb)
  549. {
  550. int l;
  551. View superView;
  552. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  553. l = Driver.Cols;
  554. superView = Application.Top;
  555. } else {
  556. l = top.SuperView.Frame.Width;
  557. superView = top.SuperView;
  558. }
  559. // BUGBUG: v2 hack for now
  560. var mfLength = top.BorderFrame.Thickness.Top > 0 ? 2 : 1;
  561. if (top.Frame.Width <= l) {
  562. nx = Math.Max (x, 0);
  563. nx = nx + top.Frame.Width > l ? Math.Max (l - top.Frame.Width, 0) : nx;
  564. if (nx + mfLength > top.Frame.X + top.Frame.Width) {
  565. nx = Math.Max (top.Frame.Right - mfLength, 0);
  566. }
  567. } else {
  568. nx = x;
  569. }
  570. //System.Diagnostics.Debug.WriteLine ($"nx:{nx}, rWidth:{rWidth}");
  571. bool m, s;
  572. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  573. m = Application.Top.MenuBar?.Visible == true;
  574. mb = Application.Top.MenuBar;
  575. } else {
  576. var t = top.SuperView;
  577. while (t is not Toplevel) {
  578. t = t.SuperView;
  579. }
  580. m = ((Toplevel)t).MenuBar?.Visible == true;
  581. mb = ((Toplevel)t).MenuBar;
  582. }
  583. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  584. l = m ? 1 : 0;
  585. } else {
  586. l = 0;
  587. }
  588. ny = Math.Max (y, l);
  589. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  590. s = Application.Top.StatusBar?.Visible == true;
  591. sb = Application.Top.StatusBar;
  592. } else {
  593. var t = top.SuperView;
  594. while (t is not Toplevel) {
  595. t = t.SuperView;
  596. }
  597. s = ((Toplevel)t).StatusBar?.Visible == true;
  598. sb = ((Toplevel)t).StatusBar;
  599. }
  600. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  601. l = s ? Driver.Rows - 1 : Driver.Rows;
  602. } else {
  603. l = s ? top.SuperView.Frame.Height - 1 : top.SuperView.Frame.Height;
  604. }
  605. ny = Math.Min (ny, l);
  606. if (top.Frame.Height <= l) {
  607. ny = ny + top.Frame.Height >= l ? Math.Max (l - top.Frame.Height, m ? 1 : 0) : ny;
  608. if (ny + mfLength > top.Frame.Y + top.Frame.Height) {
  609. ny = Math.Max (top.Frame.Bottom - mfLength, 0);
  610. }
  611. }
  612. //System.Diagnostics.Debug.WriteLine ($"ny:{ny}, rHeight:{rHeight}");
  613. return superView;
  614. }
  615. // TODO: v2 - Not sure this is needed anymore.
  616. internal void PositionToplevels ()
  617. {
  618. PositionToplevel (this);
  619. foreach (var top in Subviews) {
  620. if (top is Toplevel) {
  621. PositionToplevel ((Toplevel)top);
  622. }
  623. }
  624. }
  625. /// <summary>
  626. /// Adjusts the location and size of <paramref name="top"/> within this Toplevel.
  627. /// Virtual method enabling implementation of specific positions for inherited <see cref="Toplevel"/> views.
  628. /// </summary>
  629. /// <param name="top">The Toplevel to adjust.</param>
  630. public virtual void PositionToplevel (Toplevel top)
  631. {
  632. var superView = EnsureVisibleBounds (top, top.Frame.X, top.Frame.Y,
  633. out int nx, out int ny, out _, out StatusBar sb);
  634. bool layoutSubviews = false;
  635. if ((superView != top || top?.SuperView != null || (top != Application.Top && top.Modal)
  636. || (top?.SuperView == null && top.IsMdiChild))
  637. && (top.Frame.X + top.Frame.Width > Driver.Cols || ny > top.Frame.Y) && top.LayoutStyle == LayoutStyle.Computed) {
  638. if ((top.X == null || top.X is Pos.PosAbsolute) && top.Frame.X != nx) {
  639. top.X = nx;
  640. layoutSubviews = true;
  641. }
  642. if ((top.Y == null || top.Y is Pos.PosAbsolute) && top.Frame.Y != ny) {
  643. top.Y = ny;
  644. layoutSubviews = true;
  645. }
  646. }
  647. // TODO: v2 - This is a hack to get the StatusBar to be positioned correctly.
  648. if (sb != null && !top.Subviews.Contains (sb) && ny + top.Frame.Height != superView.Frame.Height - (sb.Visible ? 1 : 0)
  649. && top.Height is Dim.DimFill && -top.Height.Anchor (0) < 1) {
  650. top.Height = Dim.Fill (sb.Visible ? 1 : 0);
  651. layoutSubviews = true;
  652. }
  653. if (layoutSubviews) {
  654. superView.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. // // This is the Application.Top. Clear just the region we're being asked to redraw
  666. // // (the bounds passed to us).
  667. // Clear ();
  668. // Driver.SetAttribute (Enabled ? Colors.Base.Normal : Colors.Base.Disabled);
  669. // LayoutSubviews ();
  670. // PositionToplevels ();
  671. // if (this == Application.MdiTop) {
  672. // foreach (var top in Application.MdiChildes.AsEnumerable ().Reverse ()) {
  673. // if (top.Frame.IntersectsWith (bounds)) {
  674. // if (top != this && !top.IsCurrentTop && !OutsideTopFrame (top) && top.Visible) {
  675. // top.SetNeedsLayout ();
  676. // top.SetNeedsDisplay (top.Bounds);
  677. // top.Redraw (top.Bounds);
  678. // }
  679. // }
  680. // }
  681. // }
  682. // foreach (var view in Subviews) {
  683. // if (view.Frame.IntersectsWith (bounds) && !OutsideTopFrame (this)) {
  684. // view.SetNeedsLayout ();
  685. // view.SetNeedsDisplay (view.Bounds);
  686. // }
  687. // }
  688. // // BUGBUG: shouldn't we just return here? the call to base.Redraw below is redundant
  689. // }
  690. // base.Redraw (Bounds);
  691. //}
  692. bool OutsideTopFrame (Toplevel top)
  693. {
  694. if (top.Frame.X > Driver.Cols || top.Frame.Y > Driver.Rows) {
  695. return true;
  696. }
  697. return false;
  698. }
  699. internal static Point? dragPosition;
  700. Point start;
  701. ///<inheritdoc/>
  702. public override bool MouseEvent (MouseEvent mouseEvent)
  703. {
  704. if (!CanFocus) {
  705. return true;
  706. }
  707. //System.Diagnostics.Debug.WriteLine ($"dragPosition before: {dragPosition.HasValue}");
  708. int nx, ny;
  709. if (!dragPosition.HasValue && (mouseEvent.Flags == MouseFlags.Button1Pressed
  710. || mouseEvent.Flags == MouseFlags.Button2Pressed
  711. || mouseEvent.Flags == MouseFlags.Button3Pressed)) {
  712. SetFocus ();
  713. Application.EnsuresTopOnFront ();
  714. // Only start grabbing if the user clicks on the title bar.
  715. if (mouseEvent.Y == 0 && mouseEvent.Flags == MouseFlags.Button1Pressed) {
  716. start = new Point (mouseEvent.X, mouseEvent.Y);
  717. dragPosition = new Point ();
  718. nx = mouseEvent.X - mouseEvent.OfX;
  719. ny = mouseEvent.Y - mouseEvent.OfY;
  720. dragPosition = new Point (nx, ny);
  721. Application.GrabMouse (this);
  722. }
  723. //System.Diagnostics.Debug.WriteLine ($"Starting at {dragPosition}");
  724. return true;
  725. } else if (mouseEvent.Flags == (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) ||
  726. mouseEvent.Flags == MouseFlags.Button3Pressed) {
  727. if (dragPosition.HasValue) {
  728. if (SuperView == null) {
  729. // Redraw the entire app window using just our Frame. Since we are
  730. // Application.Top, and our Frame always == our Bounds (Location is always (0,0))
  731. // our Frame is actually view-relative (which is what Redraw takes).
  732. // We need to pass all the view bounds because since the windows was
  733. // moved around, we don't know exactly what was the affected region.
  734. Application.Top.SetNeedsDisplay ();
  735. } else {
  736. SuperView.SetNeedsDisplay ();
  737. }
  738. EnsureVisibleBounds (this, mouseEvent.X + (SuperView == null ? mouseEvent.OfX - start.X : Frame.X - start.X),
  739. mouseEvent.Y + (SuperView == null ? mouseEvent.OfY - start.Y : Frame.Y - start.Y),
  740. out nx, out ny, out _, out _);
  741. dragPosition = new Point (nx, ny);
  742. X = nx;
  743. Y = ny;
  744. //System.Diagnostics.Debug.WriteLine ($"Drag: nx:{nx},ny:{ny}");
  745. SetNeedsDisplay ();
  746. return true;
  747. }
  748. }
  749. if (mouseEvent.Flags.HasFlag (MouseFlags.Button1Released) && dragPosition.HasValue) {
  750. dragPosition = null;
  751. Application.UngrabMouse ();
  752. }
  753. //System.Diagnostics.Debug.WriteLine ($"dragPosition after: {dragPosition.HasValue}");
  754. //System.Diagnostics.Debug.WriteLine ($"Toplevel: {mouseEvent}");
  755. return false;
  756. }
  757. /// <summary>
  758. /// Invoked by <see cref="Application.Begin"/> as part of <see cref="Application.Run(Toplevel, Func{Exception, bool})"/>
  759. /// after the views have been laid out, and before the views are drawn for the first time.
  760. /// </summary>
  761. public virtual void WillPresent ()
  762. {
  763. FocusFirst ();
  764. }
  765. /// <summary>
  766. /// Move to the next Mdi child from the <see cref="Application.MdiTop"/>.
  767. /// </summary>
  768. public virtual void MoveNext ()
  769. {
  770. Application.MoveNext ();
  771. }
  772. /// <summary>
  773. /// Move to the previous Mdi child from the <see cref="Application.MdiTop"/>.
  774. /// </summary>
  775. public virtual void MovePrevious ()
  776. {
  777. Application.MovePrevious ();
  778. }
  779. /// <summary>
  780. /// Stops and closes this <see cref="Toplevel"/>. If this Toplevel is the top-most Toplevel,
  781. /// <see cref="Application.RequestStop(Toplevel)"/> will be called, causing the application to exit.
  782. /// </summary>
  783. public virtual void RequestStop ()
  784. {
  785. if (IsMdiContainer && Running
  786. && (Application.Current == this
  787. || Application.Current?.Modal == false
  788. || Application.Current?.Modal == true && Application.Current?.Running == false)) {
  789. foreach (var child in Application.MdiChildes) {
  790. var ev = new ToplevelClosingEventArgs (this);
  791. if (child.OnClosing (ev)) {
  792. return;
  793. }
  794. child.Running = false;
  795. Application.RequestStop (child);
  796. }
  797. Running = false;
  798. Application.RequestStop (this);
  799. } else if (IsMdiContainer && Running && Application.Current?.Modal == true && Application.Current?.Running == true) {
  800. var ev = new ToplevelClosingEventArgs (Application.Current);
  801. if (OnClosing (ev)) {
  802. return;
  803. }
  804. Application.RequestStop (Application.Current);
  805. } else if (!IsMdiContainer && Running && (!Modal || (Modal && Application.Current != this))) {
  806. var ev = new ToplevelClosingEventArgs (this);
  807. if (OnClosing (ev)) {
  808. return;
  809. }
  810. Running = false;
  811. Application.RequestStop (this);
  812. } else {
  813. Application.RequestStop (Application.Current);
  814. }
  815. }
  816. /// <summary>
  817. /// Stops and closes the <see cref="Toplevel"/> specified by <paramref name="top"/>. If <paramref name="top"/> is the top-most Toplevel,
  818. /// <see cref="Application.RequestStop(Toplevel)"/> will be called, causing the application to exit.
  819. /// </summary>
  820. /// <param name="top">The toplevel to request stop.</param>
  821. public virtual void RequestStop (Toplevel top)
  822. {
  823. top.RequestStop ();
  824. }
  825. ///<inheritdoc/>
  826. public override void PositionCursor ()
  827. {
  828. if (!IsMdiContainer) {
  829. base.PositionCursor ();
  830. if (Focused == null) {
  831. EnsureFocus ();
  832. if (Focused == null) {
  833. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  834. }
  835. }
  836. return;
  837. }
  838. if (Focused == null) {
  839. foreach (var top in Application.MdiChildes) {
  840. if (top != this && top.Visible) {
  841. top.SetFocus ();
  842. return;
  843. }
  844. }
  845. }
  846. base.PositionCursor ();
  847. if (Focused == null) {
  848. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  849. }
  850. }
  851. /// <summary>
  852. /// Gets the current visible Toplevel Mdi child that matches the arguments pattern.
  853. /// </summary>
  854. /// <param name="type">The type.</param>
  855. /// <param name="exclude">The strings to exclude.</param>
  856. /// <returns>The matched view.</returns>
  857. public View GetTopMdiChild (Type type = null, string [] exclude = null)
  858. {
  859. if (Application.MdiTop == null) {
  860. return null;
  861. }
  862. foreach (var top in Application.MdiChildes) {
  863. if (type != null && top.GetType () == type
  864. && exclude?.Contains (top.Data.ToString ()) == false) {
  865. return top;
  866. } else if ((type != null && top.GetType () != type)
  867. || (exclude?.Contains (top.Data.ToString ()) == true)) {
  868. continue;
  869. }
  870. return top;
  871. }
  872. return null;
  873. }
  874. /// <summary>
  875. /// Shows the Mdi child indicated by <paramref name="top"/>, setting it as <see cref="Application.Current"/>.
  876. /// </summary>
  877. /// <param name="top">The Toplevel.</param>
  878. /// <returns><c>true</c> if the toplevel can be shown or <c>false</c> if not.</returns>
  879. public virtual bool ShowChild (Toplevel top = null)
  880. {
  881. if (Application.MdiTop != null) {
  882. return Application.ShowChild (top == null ? this : top);
  883. }
  884. return false;
  885. }
  886. ///<inheritdoc/>
  887. public override bool OnEnter (View view)
  888. {
  889. return MostFocused?.OnEnter (view) ?? base.OnEnter (view);
  890. }
  891. ///<inheritdoc/>
  892. public override bool OnLeave (View view)
  893. {
  894. return MostFocused?.OnLeave (view) ?? base.OnLeave (view);
  895. }
  896. ///<inheritdoc/>
  897. protected override void Dispose (bool disposing)
  898. {
  899. dragPosition = null;
  900. base.Dispose (disposing);
  901. }
  902. }
  903. /// <summary>
  904. /// Implements the <see cref="IEqualityComparer{T}"/> for comparing two <see cref="Toplevel"/>s
  905. /// used by <see cref="StackExtensions"/>.
  906. /// </summary>
  907. public class ToplevelEqualityComparer : IEqualityComparer<Toplevel> {
  908. /// <summary>Determines whether the specified objects are equal.</summary>
  909. /// <param name="x">The first object of type <see cref="Toplevel" /> to compare.</param>
  910. /// <param name="y">The second object of type <see cref="Toplevel" /> to compare.</param>
  911. /// <returns>
  912. /// <see langword="true" /> if the specified objects are equal; otherwise, <see langword="false" />.</returns>
  913. public bool Equals (Toplevel x, Toplevel y)
  914. {
  915. if (y == null && x == null)
  916. return true;
  917. else if (x == null || y == null)
  918. return false;
  919. else if (x.Id == y.Id)
  920. return true;
  921. else
  922. return false;
  923. }
  924. /// <summary>Returns a hash code for the specified object.</summary>
  925. /// <param name="obj">The <see cref="Toplevel" /> for which a hash code is to be returned.</param>
  926. /// <returns>A hash code for the specified object.</returns>
  927. /// <exception cref="ArgumentNullException">The type of <paramref name="obj" />
  928. /// is a reference type and <paramref name="obj" /> is <see langword="null" />.</exception>
  929. public int GetHashCode (Toplevel obj)
  930. {
  931. if (obj == null)
  932. throw new ArgumentNullException ();
  933. int hCode = 0;
  934. if (int.TryParse (obj.Id.ToString (), out int result)) {
  935. hCode = result;
  936. }
  937. return hCode.GetHashCode ();
  938. }
  939. }
  940. /// <summary>
  941. /// Implements the <see cref="IComparer{T}"/> to sort the <see cref="Toplevel"/>
  942. /// from the <see cref="Application.MdiChildes"/> if needed.
  943. /// </summary>
  944. public sealed class ToplevelComparer : IComparer<Toplevel> {
  945. /// <summary>Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.</summary>
  946. /// <param name="x">The first object to compare.</param>
  947. /// <param name="y">The second object to compare.</param>
  948. /// <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
  949. /// <paramref name="x" /> is less than <paramref name="y" />.Zero
  950. /// <paramref name="x" /> equals <paramref name="y" />.Greater than zero
  951. /// <paramref name="x" /> is greater than <paramref name="y" />.</returns>
  952. public int Compare (Toplevel x, Toplevel y)
  953. {
  954. if (ReferenceEquals (x, y))
  955. return 0;
  956. else if (x == null)
  957. return -1;
  958. else if (y == null)
  959. return 1;
  960. else
  961. return string.Compare (x.Id.ToString (), y.Id.ToString ());
  962. }
  963. }
  964. }