Toplevel.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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()"/> 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 initialzies Terminal.Gui by callling <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. /// Called from <see cref="Application.Begin(Toplevel)"/> before the <see cref="Toplevel"/> is redraws for the first time.
  67. /// </summary>
  68. internal virtual void OnLoaded ()
  69. {
  70. Loaded?.Invoke ();
  71. }
  72. /// <summary>
  73. /// Called from <see cref="Application.RunLoop"/> after the <see cref="Toplevel"/> has entered it's first iteration of the loop.
  74. /// </summary>
  75. internal virtual void OnReady ()
  76. {
  77. Ready?.Invoke ();
  78. }
  79. /// <summary>
  80. /// Called from <see cref="Application.End(Application.RunState)"/> before the <see cref="Toplevel"/> is disposed.
  81. /// </summary>
  82. internal virtual void OnUnloaded ()
  83. {
  84. Unloaded?.Invoke ();
  85. }
  86. /// <summary>
  87. /// Initializes a new instance of the <see cref="Toplevel"/> class with the specified absolute layout.
  88. /// </summary>
  89. /// <param name="frame">A superview-relative rectangle specifying the location and size for the new Toplevel</param>
  90. public Toplevel (Rect frame) : base (frame)
  91. {
  92. Initialize ();
  93. }
  94. /// <summary>
  95. /// Initializes a new instance of the <see cref="Toplevel"/> class with <see cref="LayoutStyle.Computed"/> layout, defaulting to full screen.
  96. /// </summary>
  97. public Toplevel () : base ()
  98. {
  99. Initialize ();
  100. Width = Dim.Fill ();
  101. Height = Dim.Fill ();
  102. }
  103. void Initialize ()
  104. {
  105. ColorScheme = Colors.TopLevel;
  106. }
  107. /// <summary>
  108. /// Convenience factory method that creates a new Toplevel with the current terminal dimensions.
  109. /// </summary>
  110. /// <returns>The create.</returns>
  111. public static Toplevel Create ()
  112. {
  113. return new Toplevel (new Rect (0, 0, Driver.Cols, Driver.Rows));
  114. }
  115. /// <summary>
  116. /// Gets or sets a value indicating whether this <see cref="Toplevel"/> can focus.
  117. /// </summary>
  118. /// <value><c>true</c> if can focus; otherwise, <c>false</c>.</value>
  119. public override bool CanFocus {
  120. get => true;
  121. }
  122. /// <summary>
  123. /// Determines whether the <see cref="Toplevel"/> is modal or not.
  124. /// Causes <see cref="ProcessKey(KeyEvent)"/> to propagate keys upwards
  125. /// by default unless set to <see langword="true"/>.
  126. /// </summary>
  127. public bool Modal { get; set; }
  128. /// <summary>
  129. /// Gets or sets the menu for this Toplevel
  130. /// </summary>
  131. public virtual MenuBar MenuBar { get; set; }
  132. /// <summary>
  133. /// Gets or sets the status bar for this Toplevel
  134. /// </summary>
  135. public virtual StatusBar StatusBar { get; set; }
  136. ///<inheritdoc/>
  137. public override bool OnKeyDown (KeyEvent keyEvent)
  138. {
  139. if (base.OnKeyDown (keyEvent)) {
  140. return true;
  141. }
  142. switch (keyEvent.Key) {
  143. case Key.AltMask:
  144. case Key.AltMask | Key.Space:
  145. case Key.CtrlMask | Key.Space:
  146. if (MenuBar != null && MenuBar.OnKeyDown (keyEvent)) {
  147. return true;
  148. }
  149. break;
  150. }
  151. return false;
  152. }
  153. ///<inheritdoc/>
  154. public override bool OnKeyUp (KeyEvent keyEvent)
  155. {
  156. if (base.OnKeyUp (keyEvent)) {
  157. return true;
  158. }
  159. switch (keyEvent.Key) {
  160. case Key.AltMask:
  161. case Key.AltMask | Key.Space:
  162. case Key.CtrlMask | Key.Space:
  163. if (MenuBar != null && MenuBar.OnKeyUp (keyEvent)) {
  164. return true;
  165. }
  166. break;
  167. }
  168. return false;
  169. }
  170. ///<inheritdoc/>
  171. public override bool ProcessKey (KeyEvent keyEvent)
  172. {
  173. if (base.ProcessKey (keyEvent))
  174. return true;
  175. switch (ShortcutHelper.GetModifiersKey (keyEvent)) {
  176. case Key.Q | Key.CtrlMask:
  177. // FIXED: stop current execution of this container
  178. Application.RequestStop ();
  179. break;
  180. case Key.Z | Key.CtrlMask:
  181. Driver.Suspend ();
  182. return true;
  183. #if false
  184. case Key.F5:
  185. Application.DebugDrawBounds = !Application.DebugDrawBounds;
  186. SetNeedsDisplay ();
  187. return true;
  188. #endif
  189. case Key.Tab:
  190. case Key.CursorRight:
  191. case Key.CursorDown:
  192. case Key.I | Key.CtrlMask: // Unix
  193. var old = GetDeepestFocusedSubview (Focused);
  194. if (!FocusNext ())
  195. FocusNext ();
  196. if (old != Focused && old != Focused?.Focused) {
  197. old?.SetNeedsDisplay ();
  198. Focused?.SetNeedsDisplay ();
  199. } else {
  200. FocusNearestView (SuperView?.TabIndexes, Direction.Forward);
  201. }
  202. return true;
  203. case Key.BackTab | Key.ShiftMask:
  204. case Key.CursorLeft:
  205. case Key.CursorUp:
  206. old = GetDeepestFocusedSubview (Focused);
  207. if (!FocusPrev ())
  208. FocusPrev ();
  209. if (old != Focused && old != Focused?.Focused) {
  210. old?.SetNeedsDisplay ();
  211. Focused?.SetNeedsDisplay ();
  212. } else {
  213. FocusNearestView (SuperView?.TabIndexes?.Reverse (), Direction.Backward);
  214. }
  215. return true;
  216. case Key.Tab | Key.CtrlMask:
  217. case Key key when key == Application.AlternateForwardKey: // Needed on Unix
  218. Application.Top.FocusNext ();
  219. if (Application.Top.Focused == null) {
  220. Application.Top.FocusNext ();
  221. }
  222. return true;
  223. case Key.Tab | Key.ShiftMask | Key.CtrlMask:
  224. case Key key when key == Application.AlternateBackwardKey: // Needed on Unix
  225. Application.Top.FocusPrev ();
  226. if (Application.Top.Focused == null) {
  227. Application.Top.FocusPrev ();
  228. }
  229. return true;
  230. case Key.L | Key.CtrlMask:
  231. Application.Refresh ();
  232. return true;
  233. }
  234. return false;
  235. }
  236. ///<inheritdoc/>
  237. public override bool ProcessColdKey (KeyEvent keyEvent)
  238. {
  239. if (base.ProcessColdKey (keyEvent)) {
  240. return true;
  241. }
  242. if (ShortcutHelper.FindAndOpenByShortcut (keyEvent, this)) {
  243. return true;
  244. }
  245. return false;
  246. }
  247. View GetDeepestFocusedSubview (View view)
  248. {
  249. if (view == null) {
  250. return null;
  251. }
  252. foreach (var v in view.Subviews) {
  253. if (v.HasFocus) {
  254. return GetDeepestFocusedSubview (v);
  255. }
  256. }
  257. return view;
  258. }
  259. void FocusNearestView (IEnumerable<View> views, Direction direction)
  260. {
  261. if (views == null) {
  262. return;
  263. }
  264. bool found = false;
  265. bool focusProcessed = false;
  266. int idx = 0;
  267. foreach (var v in views) {
  268. if (v == this) {
  269. found = true;
  270. }
  271. if (found && v != this) {
  272. if (direction == Direction.Forward) {
  273. SuperView?.FocusNext ();
  274. } else {
  275. SuperView?.FocusPrev ();
  276. }
  277. focusProcessed = true;
  278. if (SuperView.Focused != null && SuperView.Focused != this) {
  279. return;
  280. }
  281. } else if (found && !focusProcessed && idx == views.Count () - 1) {
  282. views.ToList () [0].SetFocus ();
  283. }
  284. idx++;
  285. }
  286. }
  287. ///<inheritdoc/>
  288. public override void Add (View view)
  289. {
  290. AddMenuStatusBar (view);
  291. base.Add (view);
  292. }
  293. internal void AddMenuStatusBar (View view)
  294. {
  295. if (view is MenuBar) {
  296. MenuBar = view as MenuBar;
  297. }
  298. if (view is StatusBar) {
  299. StatusBar = view as StatusBar;
  300. }
  301. }
  302. ///<inheritdoc/>
  303. public override void Remove (View view)
  304. {
  305. if (this is Toplevel toplevel && toplevel.MenuBar != null) {
  306. RemoveMenuStatusBar (view);
  307. }
  308. base.Remove (view);
  309. }
  310. ///<inheritdoc/>
  311. public override void RemoveAll ()
  312. {
  313. if (this == Application.Top) {
  314. MenuBar?.Dispose ();
  315. MenuBar = null;
  316. StatusBar?.Dispose ();
  317. StatusBar = null;
  318. }
  319. base.RemoveAll ();
  320. }
  321. internal void RemoveMenuStatusBar (View view)
  322. {
  323. if (view is MenuBar) {
  324. MenuBar?.Dispose ();
  325. MenuBar = null;
  326. }
  327. if (view is StatusBar) {
  328. StatusBar?.Dispose ();
  329. StatusBar = null;
  330. }
  331. }
  332. internal void EnsureVisibleBounds (Toplevel top, int x, int y, out int nx, out int ny)
  333. {
  334. nx = Math.Max (x, 0);
  335. int l;
  336. if (SuperView == null || SuperView is Toplevel) {
  337. l = Driver.Cols;
  338. } else {
  339. l = SuperView.Frame.Width;
  340. }
  341. nx = nx + top.Frame.Width > l ? Math.Max (l - top.Frame.Width, 0) : nx;
  342. SetWidth (top.Frame.Width, out int rWidth);
  343. if (rWidth < 0 && nx >= top.Frame.X) {
  344. nx = Math.Max (top.Frame.Right - 2, 0);
  345. }
  346. //System.Diagnostics.Debug.WriteLine ($"nx:{nx}, rWidth:{rWidth}");
  347. bool m, s;
  348. if (SuperView == null || SuperView.GetType () != typeof (Toplevel)) {
  349. m = Application.Top.MenuBar != null;
  350. } else {
  351. m = ((Toplevel)SuperView).MenuBar != null;
  352. }
  353. if (SuperView == null || SuperView is Toplevel) {
  354. l = m ? 1 : 0;
  355. } else {
  356. l = 0;
  357. }
  358. ny = Math.Max (y, l);
  359. if (SuperView == null || SuperView.GetType () != typeof (Toplevel)) {
  360. s = Application.Top.StatusBar != null && Application.Top.StatusBar.Visible;
  361. } else {
  362. s = ((Toplevel)SuperView).StatusBar != null && ((Toplevel)SuperView).StatusBar.Visible;
  363. }
  364. if (SuperView == null || SuperView is Toplevel) {
  365. l = s ? Driver.Rows - 1 : Driver.Rows;
  366. } else {
  367. l = s ? SuperView.Frame.Height - 1 : SuperView.Frame.Height;
  368. }
  369. ny = Math.Min (ny, l);
  370. ny = ny + top.Frame.Height > l ? Math.Max (l - top.Frame.Height, m ? 1 : 0) : ny;
  371. SetHeight (top.Frame.Height, out int rHeight);
  372. if (rHeight < 0 && ny >= top.Frame.Y) {
  373. ny = Math.Max (top.Frame.Bottom - 2, 0);
  374. }
  375. //System.Diagnostics.Debug.WriteLine ($"ny:{ny}, rHeight:{rHeight}");
  376. }
  377. internal void PositionToplevels ()
  378. {
  379. PositionToplevel (this);
  380. foreach (var top in Subviews) {
  381. if (top is Toplevel) {
  382. PositionToplevel ((Toplevel)top);
  383. }
  384. }
  385. }
  386. /// <summary>
  387. /// Virtual method which allow to be overridden to implement specific positions for inherited <see cref="Toplevel"/>.
  388. /// </summary>
  389. /// <param name="top">The toplevel.</param>
  390. public virtual void PositionToplevel (Toplevel top)
  391. {
  392. EnsureVisibleBounds (top, top.Frame.X, top.Frame.Y, out int nx, out int ny);
  393. if (top?.SuperView != null && (nx != top.Frame.X || ny != top.Frame.Y) && top.LayoutStyle == LayoutStyle.Computed) {
  394. if ((top.X == null || top.X is Pos.PosAbsolute) && top.Bounds.X != nx) {
  395. top.X = nx;
  396. }
  397. if ((top.Y == null || top.Y is Pos.PosAbsolute) && top.Bounds.Y != ny) {
  398. top.Y = ny;
  399. }
  400. }
  401. var statusBar = top?.SuperView != null && top.SuperView is Toplevel toplevel
  402. ? toplevel.StatusBar : null;
  403. if (statusBar != null) {
  404. if (ny + top.Frame.Height != top.SuperView.Frame.Height - (statusBar.Visible ? 1 : 0)) {
  405. if (top.Height is Dim.DimFill) {
  406. top.Height = Dim.Fill (statusBar.Visible ? 1 : 0);
  407. }
  408. }
  409. top.SuperView.LayoutSubviews ();
  410. }
  411. if (top.StatusBar != null) {
  412. if (top.StatusBar.Frame.Y != top.Frame.Height - (top.StatusBar.Visible ? 1 : 0)) {
  413. top.StatusBar.Y = top.Frame.Height - (top.StatusBar.Visible ? 1 : 0);
  414. top.LayoutSubviews ();
  415. }
  416. top.BringSubviewToFront (top.StatusBar);
  417. }
  418. }
  419. ///<inheritdoc/>
  420. public override void Redraw (Rect bounds)
  421. {
  422. if (IsCurrentTop || this == Application.Top || Application.Current.GetType ().BaseType == typeof (Toplevel)) {
  423. if (!NeedDisplay.IsEmpty || LayoutNeeded) {
  424. Driver.SetAttribute (Colors.TopLevel.Normal);
  425. // This is the Application.Top. Clear just the region we're being asked to redraw
  426. // (the bounds passed to us).
  427. // Must be the screen-relative region to clear, not the bounds.
  428. Clear (Frame);
  429. Driver.SetAttribute (Colors.Base.Normal);
  430. PositionToplevels ();
  431. foreach (var view in Subviews) {
  432. if (view.Frame.IntersectsWith (bounds)) {
  433. view.SetNeedsLayout ();
  434. view.SetNeedsDisplay (view.Bounds);
  435. }
  436. }
  437. ClearLayoutNeeded ();
  438. ClearNeedsDisplay ();
  439. }
  440. }
  441. base.Redraw (base.Bounds);
  442. }
  443. /// <summary>
  444. /// Invoked by <see cref="Application.Begin"/> as part of the <see cref="Application.Run(Toplevel, Func{Exception, bool})"/> after
  445. /// the views have been laid out, and before the views are drawn for the first time.
  446. /// </summary>
  447. public virtual void WillPresent ()
  448. {
  449. FocusFirst ();
  450. }
  451. }
  452. }