Toplevel.cs 33 KB

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