Toplevel.cs 33 KB

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