Toplevel.cs 36 KB

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