Toplevel.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928
  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 => true;
  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.Q | Key.CtrlMask:
  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. Application.Top.FocusNext ();
  304. if (Application.Top.Focused == null) {
  305. Application.Top.FocusNext ();
  306. }
  307. Application.Top.SetNeedsDisplay ();
  308. } else {
  309. MoveNext ();
  310. }
  311. return true;
  312. case Key.Tab | Key.ShiftMask | Key.CtrlMask:
  313. case Key key when key == Application.AlternateBackwardKey: // Needed on Unix
  314. if (Application.MdiTop == null) {
  315. Application.Top.FocusPrev ();
  316. if (Application.Top.Focused == null) {
  317. Application.Top.FocusPrev ();
  318. }
  319. Application.Top.SetNeedsDisplay ();
  320. } else {
  321. MovePrevious ();
  322. }
  323. return true;
  324. case Key.L | Key.CtrlMask:
  325. Application.Refresh ();
  326. return true;
  327. }
  328. return false;
  329. }
  330. ///<inheritdoc/>
  331. public override bool ProcessColdKey (KeyEvent keyEvent)
  332. {
  333. if (base.ProcessColdKey (keyEvent)) {
  334. return true;
  335. }
  336. if (ShortcutHelper.FindAndOpenByShortcut (keyEvent, this)) {
  337. return true;
  338. }
  339. return false;
  340. }
  341. View GetDeepestFocusedSubview (View view)
  342. {
  343. if (view == null) {
  344. return null;
  345. }
  346. foreach (var v in view.Subviews) {
  347. if (v.HasFocus) {
  348. return GetDeepestFocusedSubview (v);
  349. }
  350. }
  351. return view;
  352. }
  353. void FocusNearestView (IEnumerable<View> views, Direction direction)
  354. {
  355. if (views == null) {
  356. return;
  357. }
  358. bool found = false;
  359. bool focusProcessed = false;
  360. int idx = 0;
  361. foreach (var v in views) {
  362. if (v == this) {
  363. found = true;
  364. }
  365. if (found && v != this) {
  366. if (direction == Direction.Forward) {
  367. SuperView?.FocusNext ();
  368. } else {
  369. SuperView?.FocusPrev ();
  370. }
  371. focusProcessed = true;
  372. if (SuperView.Focused != null && SuperView.Focused != this) {
  373. return;
  374. }
  375. } else if (found && !focusProcessed && idx == views.Count () - 1) {
  376. views.ToList () [0].SetFocus ();
  377. }
  378. idx++;
  379. }
  380. }
  381. ///<inheritdoc/>
  382. public override void Add (View view)
  383. {
  384. AddMenuStatusBar (view);
  385. base.Add (view);
  386. }
  387. internal void AddMenuStatusBar (View view)
  388. {
  389. if (view is MenuBar) {
  390. MenuBar = view as MenuBar;
  391. }
  392. if (view is StatusBar) {
  393. StatusBar = view as StatusBar;
  394. }
  395. }
  396. ///<inheritdoc/>
  397. public override void Remove (View view)
  398. {
  399. if (this is Toplevel toplevel && toplevel.MenuBar != null) {
  400. RemoveMenuStatusBar (view);
  401. }
  402. base.Remove (view);
  403. }
  404. ///<inheritdoc/>
  405. public override void RemoveAll ()
  406. {
  407. if (this == Application.Top) {
  408. MenuBar?.Dispose ();
  409. MenuBar = null;
  410. StatusBar?.Dispose ();
  411. StatusBar = null;
  412. }
  413. base.RemoveAll ();
  414. }
  415. internal void RemoveMenuStatusBar (View view)
  416. {
  417. if (view is MenuBar) {
  418. MenuBar?.Dispose ();
  419. MenuBar = null;
  420. }
  421. if (view is StatusBar) {
  422. StatusBar?.Dispose ();
  423. StatusBar = null;
  424. }
  425. }
  426. internal View EnsureVisibleBounds (Toplevel top, int x, int y,
  427. out int nx, out int ny, out View mb, out View sb)
  428. {
  429. int l;
  430. View superView;
  431. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  432. l = Driver.Cols;
  433. superView = Application.Top;
  434. } else {
  435. l = top.SuperView.Frame.Width;
  436. superView = top.SuperView;
  437. }
  438. nx = Math.Max (x, 0);
  439. nx = nx + top.Frame.Width > l ? Math.Max (l - top.Frame.Width, 0) : nx;
  440. SetWidth (top.Frame.Width, out int rWidth);
  441. if (rWidth < 0 && nx >= top.Frame.X) {
  442. nx = Math.Max (top.Frame.Right - 2, 0);
  443. }
  444. //System.Diagnostics.Debug.WriteLine ($"nx:{nx}, rWidth:{rWidth}");
  445. bool m, s;
  446. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  447. m = Application.Top.MenuBar?.Visible == true;
  448. mb = Application.Top.MenuBar;
  449. } else {
  450. var t = top.SuperView;
  451. while (!(t is Toplevel)) {
  452. t = t.SuperView;
  453. }
  454. m = ((Toplevel)t).MenuBar?.Visible == true;
  455. mb = ((Toplevel)t).MenuBar;
  456. }
  457. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  458. l = m ? 1 : 0;
  459. } else {
  460. l = 0;
  461. }
  462. ny = Math.Max (y, l);
  463. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  464. s = Application.Top.StatusBar?.Visible == true;
  465. sb = Application.Top.StatusBar;
  466. } else {
  467. var t = top.SuperView;
  468. while (!(t is Toplevel)) {
  469. t = t.SuperView;
  470. }
  471. s = ((Toplevel)t).StatusBar?.Visible == true;
  472. sb = ((Toplevel)t).StatusBar;
  473. }
  474. if (top?.SuperView == null || top == Application.Top || top?.SuperView == Application.Top) {
  475. l = s ? Driver.Rows - 1 : Driver.Rows;
  476. } else {
  477. l = s ? top.SuperView.Frame.Height - 1 : top.SuperView.Frame.Height;
  478. }
  479. ny = Math.Min (ny, l);
  480. ny = ny + top.Frame.Height >= l ? Math.Max (l - top.Frame.Height, m ? 1 : 0) : ny;
  481. SetHeight (top.Frame.Height, out int rHeight);
  482. if (rHeight < 0 && ny >= top.Frame.Y) {
  483. ny = Math.Max (top.Frame.Bottom - 2, 0);
  484. }
  485. //System.Diagnostics.Debug.WriteLine ($"ny:{ny}, rHeight:{rHeight}");
  486. return superView;
  487. }
  488. internal void PositionToplevels ()
  489. {
  490. PositionToplevel (this);
  491. foreach (var top in Subviews) {
  492. if (top is Toplevel) {
  493. PositionToplevel ((Toplevel)top);
  494. }
  495. }
  496. }
  497. /// <summary>
  498. /// Virtual method which allow to be overridden to implement specific positions for inherited <see cref="Toplevel"/>.
  499. /// </summary>
  500. /// <param name="top">The toplevel.</param>
  501. public virtual void PositionToplevel (Toplevel top)
  502. {
  503. var superView = EnsureVisibleBounds (top, top.Frame.X, top.Frame.Y,
  504. out int nx, out int ny, out _, out View sb);
  505. bool layoutSubviews = false;
  506. if ((top?.SuperView != null || (top != Application.Top && top.Modal)
  507. || (top?.SuperView == null && top.IsMdiChild))
  508. && (nx > top.Frame.X || ny > top.Frame.Y) && top.LayoutStyle == LayoutStyle.Computed) {
  509. if ((top.X == null || top.X is Pos.PosAbsolute) && top.Bounds.X != nx) {
  510. top.X = nx;
  511. layoutSubviews = true;
  512. }
  513. if ((top.Y == null || top.Y is Pos.PosAbsolute) && top.Bounds.Y != ny) {
  514. top.Y = ny;
  515. layoutSubviews = true;
  516. }
  517. }
  518. if (sb != null && ny + top.Frame.Height != superView.Frame.Height - (sb.Visible ? 1 : 0)
  519. && top.Height is Dim.DimFill) {
  520. top.Height = Dim.Fill (sb.Visible ? 1 : 0);
  521. layoutSubviews = true;
  522. }
  523. if (layoutSubviews) {
  524. superView.LayoutSubviews ();
  525. }
  526. }
  527. ///<inheritdoc/>
  528. public override void Redraw (Rect bounds)
  529. {
  530. if (!Visible) {
  531. return;
  532. }
  533. if (!NeedDisplay.IsEmpty || ChildNeedsDisplay || LayoutNeeded) {
  534. Driver.SetAttribute (GetNormalColor ());
  535. // This is the Application.Top. Clear just the region we're being asked to redraw
  536. // (the bounds passed to us).
  537. Clear ();
  538. Driver.SetAttribute (Enabled ? Colors.Base.Normal : Colors.Base.Disabled);
  539. LayoutSubviews ();
  540. PositionToplevels ();
  541. if (this == Application.MdiTop) {
  542. foreach (var top in Application.MdiChildes.AsEnumerable ().Reverse ()) {
  543. if (top.Frame.IntersectsWith (bounds)) {
  544. if (top != this && !top.IsCurrentTop && !OutsideTopFrame (top) && top.Visible) {
  545. top.SetNeedsLayout ();
  546. top.SetNeedsDisplay (top.Bounds);
  547. top.Redraw (top.Bounds);
  548. }
  549. }
  550. }
  551. }
  552. foreach (var view in Subviews) {
  553. if (view.Frame.IntersectsWith (bounds) && !OutsideTopFrame (this)) {
  554. view.SetNeedsLayout ();
  555. view.SetNeedsDisplay (view.Bounds);
  556. //view.Redraw (view.Bounds);
  557. }
  558. }
  559. ClearLayoutNeeded ();
  560. ClearNeedsDisplay ();
  561. }
  562. base.Redraw (Bounds);
  563. }
  564. bool OutsideTopFrame (Toplevel top)
  565. {
  566. if (top.Frame.X > Driver.Cols || top.Frame.Y > Driver.Rows) {
  567. return true;
  568. }
  569. return false;
  570. }
  571. //
  572. // FIXED:It does not look like the event is raised on clicked-drag
  573. // need to figure that out.
  574. //
  575. internal static Point? dragPosition;
  576. Point start;
  577. ///<inheritdoc/>
  578. public override bool MouseEvent (MouseEvent mouseEvent)
  579. {
  580. // FIXED:The code is currently disabled, because the
  581. // Driver.UncookMouse does not seem to have an effect if there is
  582. // a pending mouse event activated.
  583. int nx, ny;
  584. if (!dragPosition.HasValue && mouseEvent.Flags == (MouseFlags.Button1Pressed)) {
  585. // Only start grabbing if the user clicks on the title bar.
  586. if (mouseEvent.Y == 0) {
  587. start = new Point (mouseEvent.X, mouseEvent.Y);
  588. dragPosition = new Point ();
  589. nx = mouseEvent.X - mouseEvent.OfX;
  590. ny = mouseEvent.Y - mouseEvent.OfY;
  591. dragPosition = new Point (nx, ny);
  592. Application.GrabMouse (this);
  593. }
  594. //System.Diagnostics.Debug.WriteLine ($"Starting at {dragPosition}");
  595. return true;
  596. } else if (mouseEvent.Flags == (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) ||
  597. mouseEvent.Flags == MouseFlags.Button3Pressed) {
  598. if (dragPosition.HasValue) {
  599. if (SuperView == null) {
  600. // Redraw the entire app window using just our Frame. Since we are
  601. // Application.Top, and our Frame always == our Bounds (Location is always (0,0))
  602. // our Frame is actually view-relative (which is what Redraw takes).
  603. // We need to pass all the view bounds because since the windows was
  604. // moved around, we don't know exactly what was the affected region.
  605. Application.Top.SetNeedsDisplay ();
  606. } else {
  607. SuperView.SetNeedsDisplay ();
  608. }
  609. EnsureVisibleBounds (this, mouseEvent.X + (SuperView == null ? mouseEvent.OfX - start.X : Frame.X - start.X),
  610. mouseEvent.Y + (SuperView == null ? mouseEvent.OfY : Frame.Y),
  611. out nx, out ny, out _, out _);
  612. dragPosition = new Point (nx, ny);
  613. LayoutSubviews ();
  614. Frame = new Rect (nx, ny, Frame.Width, Frame.Height);
  615. if (X == null || X is Pos.PosAbsolute) {
  616. X = nx;
  617. }
  618. if (Y == null || Y is Pos.PosAbsolute) {
  619. Y = ny;
  620. }
  621. //System.Diagnostics.Debug.WriteLine ($"nx:{nx},ny:{ny}");
  622. // FIXED: optimize, only SetNeedsDisplay on the before/after regions.
  623. SetNeedsDisplay ();
  624. return true;
  625. }
  626. }
  627. if (mouseEvent.Flags == MouseFlags.Button1Released && dragPosition.HasValue) {
  628. Application.UngrabMouse ();
  629. Driver.UncookMouse ();
  630. dragPosition = null;
  631. }
  632. //System.Diagnostics.Debug.WriteLine (mouseEvent.ToString ());
  633. return false;
  634. }
  635. /// <summary>
  636. /// Invoked by <see cref="Application.Begin"/> as part of the <see cref="Application.Run(Toplevel, Func{Exception, bool})"/> after
  637. /// the views have been laid out, and before the views are drawn for the first time.
  638. /// </summary>
  639. public virtual void WillPresent ()
  640. {
  641. FocusFirst ();
  642. }
  643. /// <summary>
  644. /// Move to the next Mdi child from the <see cref="Application.MdiTop"/>.
  645. /// </summary>
  646. public virtual void MoveNext ()
  647. {
  648. Application.MoveNext ();
  649. }
  650. /// <summary>
  651. /// Move to the previous Mdi child from the <see cref="Application.MdiTop"/>.
  652. /// </summary>
  653. public virtual void MovePrevious ()
  654. {
  655. Application.MovePrevious ();
  656. }
  657. /// <summary>
  658. /// Stops running this <see cref="Toplevel"/>.
  659. /// </summary>
  660. public virtual void RequestStop ()
  661. {
  662. if (IsMdiContainer && Running
  663. && (Application.Current == this
  664. || Application.Current?.Modal == false
  665. || Application.Current?.Modal == true && Application.Current?.Running == false)) {
  666. foreach (var child in Application.MdiChildes) {
  667. var ev = new ToplevelClosingEventArgs (this);
  668. if (child.OnClosing (ev)) {
  669. return;
  670. }
  671. child.Running = false;
  672. Application.RequestStop (child);
  673. }
  674. Running = false;
  675. Application.RequestStop (this);
  676. } else if (IsMdiContainer && Running && Application.Current?.Modal == true && Application.Current?.Running == true) {
  677. var ev = new ToplevelClosingEventArgs (Application.Current);
  678. if (OnClosing (ev)) {
  679. return;
  680. }
  681. Application.RequestStop (Application.Current);
  682. } else if (!IsMdiContainer && Running && (!Modal || (Modal && Application.Current != this))) {
  683. var ev = new ToplevelClosingEventArgs (this);
  684. if (OnClosing (ev)) {
  685. return;
  686. }
  687. Running = false;
  688. Application.RequestStop (this);
  689. } else {
  690. Application.RequestStop (Application.Current);
  691. }
  692. }
  693. /// <summary>
  694. /// Stops running the <paramref name="top"/> <see cref="Toplevel"/>.
  695. /// </summary>
  696. /// <param name="top">The toplevel to request stop.</param>
  697. public virtual void RequestStop (Toplevel top)
  698. {
  699. top.RequestStop ();
  700. }
  701. ///<inheritdoc/>
  702. public override void PositionCursor ()
  703. {
  704. if (!IsMdiContainer) {
  705. base.PositionCursor ();
  706. return;
  707. }
  708. if (Focused == null) {
  709. foreach (var top in Application.MdiChildes) {
  710. if (top != this && top.Visible) {
  711. top.SetFocus ();
  712. return;
  713. }
  714. }
  715. }
  716. base.PositionCursor ();
  717. }
  718. /// <summary>
  719. /// Gets the current visible toplevel Mdi child that match the arguments pattern.
  720. /// </summary>
  721. /// <param name="type">The type.</param>
  722. /// <param name="exclude">The strings to exclude.</param>
  723. /// <returns>The matched view.</returns>
  724. public View GetTopMdiChild (Type type = null, string [] exclude = null)
  725. {
  726. if (Application.MdiTop == null) {
  727. return null;
  728. }
  729. foreach (var top in Application.MdiChildes) {
  730. if (type != null && top.GetType () == type
  731. && exclude?.Contains (top.Data.ToString ()) == false) {
  732. return top;
  733. } else if ((type != null && top.GetType () != type)
  734. || (exclude?.Contains (top.Data.ToString ()) == true)) {
  735. continue;
  736. }
  737. return top;
  738. }
  739. return null;
  740. }
  741. /// <summary>
  742. /// Shows the Mdi child indicated by the <paramref name="top"/> setting as <see cref="Application.Current"/>.
  743. /// </summary>
  744. /// <param name="top">The toplevel.</param>
  745. /// <returns><see langword="true"/> if the toplevel can be showed.<see langword="false"/> otherwise.</returns>
  746. public virtual bool ShowChild (Toplevel top = null)
  747. {
  748. if (Application.MdiTop != null) {
  749. return Application.ShowChild (top == null ? this : top);
  750. }
  751. return false;
  752. }
  753. }
  754. /// <summary>
  755. /// Implements the <see cref="IEqualityComparer{T}"/> to comparing two <see cref="Toplevel"/> used by <see cref="StackExtensions"/>.
  756. /// </summary>
  757. public class ToplevelEqualityComparer : IEqualityComparer<Toplevel> {
  758. /// <summary>Determines whether the specified objects are equal.</summary>
  759. /// <param name="x">The first object of type <see cref="Toplevel" /> to compare.</param>
  760. /// <param name="y">The second object of type <see cref="Toplevel" /> to compare.</param>
  761. /// <returns>
  762. /// <see langword="true" /> if the specified objects are equal; otherwise, <see langword="false" />.</returns>
  763. public bool Equals (Toplevel x, Toplevel y)
  764. {
  765. if (y == null && x == null)
  766. return true;
  767. else if (x == null || y == null)
  768. return false;
  769. else if (x.Id == y.Id)
  770. return true;
  771. else
  772. return false;
  773. }
  774. /// <summary>Returns a hash code for the specified object.</summary>
  775. /// <param name="obj">The <see cref="Toplevel" /> for which a hash code is to be returned.</param>
  776. /// <returns>A hash code for the specified object.</returns>
  777. /// <exception cref="ArgumentNullException">The type of <paramref name="obj" /> is a reference type and <paramref name="obj" /> is <see langword="null" />.</exception>
  778. public int GetHashCode (Toplevel obj)
  779. {
  780. if (obj == null)
  781. throw new ArgumentNullException ();
  782. int hCode = 0;
  783. if (int.TryParse (obj.Id.ToString (), out int result)) {
  784. hCode = result;
  785. }
  786. return hCode.GetHashCode ();
  787. }
  788. }
  789. /// <summary>
  790. /// Implements the <see cref="IComparer{T}"/> to sort the <see cref="Toplevel"/> from the <see cref="Application.MdiChildes"/> if needed.
  791. /// </summary>
  792. public sealed class ToplevelComparer : IComparer<Toplevel> {
  793. /// <summary>Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.</summary>
  794. /// <param name="x">The first object to compare.</param>
  795. /// <param name="y">The second object to compare.</param>
  796. /// <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
  797. /// <paramref name="x" /> is less than <paramref name="y" />.Zero
  798. /// <paramref name="x" /> equals <paramref name="y" />.Greater than zero
  799. /// <paramref name="x" /> is greater than <paramref name="y" />.</returns>
  800. public int Compare (Toplevel x, Toplevel y)
  801. {
  802. if (ReferenceEquals (x, y))
  803. return 0;
  804. else if (x == null)
  805. return -1;
  806. else if (y == null)
  807. return 1;
  808. else
  809. return string.Compare (x.Id.ToString (), y.Id.ToString ());
  810. }
  811. }
  812. /// <summary>
  813. /// <see cref="EventArgs"/> implementation for the <see cref="Toplevel.Closing"/> event.
  814. /// </summary>
  815. public class ToplevelClosingEventArgs : EventArgs {
  816. /// <summary>
  817. /// The toplevel requesting stop.
  818. /// </summary>
  819. public View RequestingTop { get; }
  820. /// <summary>
  821. /// Provides an event cancellation option.
  822. /// </summary>
  823. public bool Cancel { get; set; }
  824. /// <summary>
  825. /// Initializes the event arguments with the requesting toplevel.
  826. /// </summary>
  827. /// <param name="requestingTop">The <see cref="RequestingTop"/>.</param>
  828. public ToplevelClosingEventArgs (Toplevel requestingTop)
  829. {
  830. RequestingTop = requestingTop;
  831. }
  832. }
  833. }