Toplevel.cs 28 KB

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