Toplevel.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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.Base;
  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 MenuBar MenuBar { get; set; }
  132. /// <summary>
  133. /// Gets or sets the status bar for this Toplevel
  134. /// </summary>
  135. public 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. if (this == Application.Top) {
  291. AddMenuStatusBar (view);
  292. }
  293. base.Add (view);
  294. }
  295. internal void AddMenuStatusBar (View view)
  296. {
  297. if (view is MenuBar) {
  298. MenuBar = view as MenuBar;
  299. }
  300. if (view is StatusBar) {
  301. StatusBar = view as StatusBar;
  302. }
  303. }
  304. ///<inheritdoc/>
  305. public override void Remove (View view)
  306. {
  307. if (this is Toplevel toplevel && toplevel.MenuBar != null) {
  308. RemoveMenuStatusBar (view);
  309. }
  310. base.Remove (view);
  311. }
  312. ///<inheritdoc/>
  313. public override void RemoveAll ()
  314. {
  315. if (this == Application.Top) {
  316. MenuBar?.Dispose ();
  317. MenuBar = null;
  318. StatusBar?.Dispose ();
  319. StatusBar = null;
  320. }
  321. base.RemoveAll ();
  322. }
  323. internal void RemoveMenuStatusBar (View view)
  324. {
  325. if (view is MenuBar) {
  326. MenuBar?.Dispose ();
  327. MenuBar = null;
  328. }
  329. if (view is StatusBar) {
  330. StatusBar?.Dispose ();
  331. StatusBar = null;
  332. }
  333. }
  334. internal void EnsureVisibleBounds (Toplevel top, int x, int y, out int nx, out int ny)
  335. {
  336. nx = Math.Max (x, 0);
  337. int l;
  338. if (SuperView == null || SuperView is Toplevel) {
  339. l = Driver.Cols;
  340. } else {
  341. l = SuperView.Frame.Width;
  342. }
  343. nx = nx + top.Frame.Width > l ? Math.Max (l - top.Frame.Width, 0) : nx;
  344. SetWidth (top.Frame.Width, out int rWidth);
  345. if (rWidth < 0 && nx >= top.Frame.X) {
  346. nx = Math.Max (top.Frame.Right - 2, 0);
  347. }
  348. //System.Diagnostics.Debug.WriteLine ($"nx:{nx}, rWidth:{rWidth}");
  349. bool m, s;
  350. if (SuperView == null || SuperView.GetType () != typeof (Toplevel)) {
  351. m = Application.Top.MenuBar != null;
  352. } else {
  353. m = ((Toplevel)SuperView).MenuBar != null;
  354. }
  355. if (SuperView == null || SuperView is Toplevel) {
  356. l = m ? 1 : 0;
  357. } else {
  358. l = 0;
  359. }
  360. ny = Math.Max (y, l);
  361. if (SuperView == null || SuperView.GetType () != typeof (Toplevel)) {
  362. s = Application.Top.StatusBar != null && Application.Top.StatusBar.Visible;
  363. } else {
  364. s = ((Toplevel)SuperView).StatusBar != null && ((Toplevel)SuperView).StatusBar.Visible;
  365. }
  366. if (SuperView == null || SuperView is Toplevel) {
  367. l = s ? Driver.Rows - 1 : Driver.Rows;
  368. } else {
  369. l = s ? SuperView.Frame.Height - 1 : SuperView.Frame.Height;
  370. }
  371. ny = Math.Min (ny, l);
  372. ny = ny + top.Frame.Height > l ? Math.Max (l - top.Frame.Height, m ? 1 : 0) : ny;
  373. SetHeight (top.Frame.Height, out int rHeight);
  374. if (rHeight < 0 && ny >= top.Frame.Y) {
  375. ny = Math.Max (top.Frame.Bottom - 2, 0);
  376. }
  377. //System.Diagnostics.Debug.WriteLine ($"ny:{ny}, rHeight:{rHeight}");
  378. }
  379. internal void PositionToplevels ()
  380. {
  381. PositionToplevel (this);
  382. foreach (var top in Subviews) {
  383. if (top is Toplevel) {
  384. PositionToplevel ((Toplevel)top);
  385. }
  386. }
  387. }
  388. private void PositionToplevel (Toplevel top)
  389. {
  390. EnsureVisibleBounds (top, top.Frame.X, top.Frame.Y, out int nx, out int ny);
  391. if ((nx != top.Frame.X || ny != top.Frame.Y) && top.LayoutStyle == LayoutStyle.Computed) {
  392. if ((top.X == null || top.X is Pos.PosAbsolute) && top.Bounds.X != nx) {
  393. top.X = nx;
  394. }
  395. if ((top.Y == null || top.Y is Pos.PosAbsolute) && top.Bounds.Y != ny) {
  396. top.Y = ny;
  397. }
  398. }
  399. if (top.StatusBar != null) {
  400. if (ny + top.Frame.Height > top.Frame.Height - (top.StatusBar.Visible ? 1 : 0)) {
  401. if (top.Height is Dim.DimFill)
  402. top.Height = Dim.Fill () - (top.StatusBar.Visible ? 1 : 0);
  403. }
  404. if (top.StatusBar.Frame.Y != top.Frame.Height - (top.StatusBar.Visible ? 1 : 0)) {
  405. top.StatusBar.Y = top.Frame.Height - (top.StatusBar.Visible ? 1 : 0);
  406. top.LayoutSubviews ();
  407. }
  408. top.BringSubviewToFront (top.StatusBar);
  409. }
  410. }
  411. ///<inheritdoc/>
  412. public override void Redraw (Rect bounds)
  413. {
  414. if (IsCurrentTop || this == Application.Top) {
  415. if (!NeedDisplay.IsEmpty || LayoutNeeded) {
  416. Driver.SetAttribute (Colors.TopLevel.Normal);
  417. // This is the Application.Top. Clear just the region we're being asked to redraw
  418. // (the bounds passed to us).
  419. Clear (bounds);
  420. Driver.SetAttribute (Colors.Base.Normal);
  421. PositionToplevels ();
  422. foreach (var view in Subviews) {
  423. if (view.Frame.IntersectsWith (bounds)) {
  424. view.SetNeedsLayout ();
  425. view.SetNeedsDisplay (view.Bounds);
  426. }
  427. }
  428. ClearLayoutNeeded ();
  429. ClearNeedsDisplay ();
  430. }
  431. }
  432. base.Redraw (base.Bounds);
  433. }
  434. /// <summary>
  435. /// Invoked by <see cref="Application.Begin"/> as part of the <see cref="Application.Run(Toplevel, Func{Exception, bool})"/> after
  436. /// the views have been laid out, and before the views are drawn for the first time.
  437. /// </summary>
  438. public virtual void WillPresent ()
  439. {
  440. FocusFirst ();
  441. }
  442. }
  443. }