Toplevel.cs 31 KB

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