Toplevel.cs 28 KB

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