Toplevel.cs 34 KB

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