Toplevel.cs 28 KB

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