Toplevel.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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. Application.Top.FocusNext ();
  218. return true;
  219. case Key.Tab | Key.ShiftMask | Key.CtrlMask:
  220. Application.Top.FocusPrev ();
  221. return true;
  222. case Key.L | Key.CtrlMask:
  223. Application.Refresh ();
  224. return true;
  225. }
  226. return false;
  227. }
  228. ///<inheritdoc/>
  229. public override bool ProcessColdKey (KeyEvent keyEvent)
  230. {
  231. if (base.ProcessColdKey (keyEvent)) {
  232. return true;
  233. }
  234. if (ShortcutHelper.FindAndOpenByShortcut(keyEvent, this)) {
  235. return true;
  236. }
  237. return false;
  238. }
  239. View GetDeepestFocusedSubview (View view)
  240. {
  241. if (view == null) {
  242. return null;
  243. }
  244. foreach (var v in view.Subviews) {
  245. if (v.HasFocus) {
  246. return GetDeepestFocusedSubview (v);
  247. }
  248. }
  249. return view;
  250. }
  251. void FocusNearestView (IEnumerable<View> views, Direction direction)
  252. {
  253. if (views == null) {
  254. return;
  255. }
  256. bool found = false;
  257. bool focusProcessed = false;
  258. int idx = 0;
  259. foreach (var v in views) {
  260. if (v == this) {
  261. found = true;
  262. }
  263. if (found && v != this) {
  264. if (direction == Direction.Forward) {
  265. SuperView?.FocusNext ();
  266. } else {
  267. SuperView?.FocusPrev ();
  268. }
  269. focusProcessed = true;
  270. if (SuperView.Focused != null && SuperView.Focused != this) {
  271. return;
  272. }
  273. } else if (found && !focusProcessed && idx == views.Count () - 1) {
  274. views.ToList () [0].SetFocus ();
  275. }
  276. idx++;
  277. }
  278. }
  279. ///<inheritdoc/>
  280. public override void Add (View view)
  281. {
  282. if (this == Application.Top) {
  283. AddMenuStatusBar (view);
  284. }
  285. base.Add (view);
  286. }
  287. internal void AddMenuStatusBar (View view)
  288. {
  289. if (view is MenuBar) {
  290. MenuBar = view as MenuBar;
  291. }
  292. if (view is StatusBar) {
  293. StatusBar = view as StatusBar;
  294. }
  295. }
  296. ///<inheritdoc/>
  297. public override void Remove (View view)
  298. {
  299. if (this is Toplevel toplevel && toplevel.MenuBar != null) {
  300. RemoveMenuStatusBar (view);
  301. }
  302. base.Remove (view);
  303. }
  304. ///<inheritdoc/>
  305. public override void RemoveAll ()
  306. {
  307. if (this == Application.Top) {
  308. MenuBar?.Dispose ();
  309. MenuBar = null;
  310. StatusBar?.Dispose ();
  311. StatusBar = null;
  312. }
  313. base.RemoveAll ();
  314. }
  315. internal void RemoveMenuStatusBar (View view)
  316. {
  317. if (view is MenuBar) {
  318. MenuBar?.Dispose ();
  319. MenuBar = null;
  320. }
  321. if (view is StatusBar) {
  322. StatusBar?.Dispose ();
  323. StatusBar = null;
  324. }
  325. }
  326. internal void EnsureVisibleBounds (Toplevel top, int x, int y, out int nx, out int ny)
  327. {
  328. nx = Math.Max (x, 0);
  329. int l;
  330. if (SuperView == null || SuperView is Toplevel) {
  331. l = Driver.Cols;
  332. } else {
  333. l = SuperView.Frame.Width;
  334. }
  335. nx = nx + top.Frame.Width > l ? Math.Max (l - top.Frame.Width, 0) : nx;
  336. SetWidth (top.Frame.Width, out int rWidth);
  337. if (rWidth < 0 && nx >= top.Frame.X) {
  338. nx = Math.Max (top.Frame.Right - 2, 0);
  339. }
  340. //System.Diagnostics.Debug.WriteLine ($"nx:{nx}, rWidth:{rWidth}");
  341. bool m, s;
  342. if (SuperView == null || SuperView.GetType () != typeof (Toplevel)) {
  343. m = Application.Top.MenuBar != null;
  344. } else {
  345. m = ((Toplevel)SuperView).MenuBar != null;
  346. }
  347. if (SuperView == null || SuperView is Toplevel) {
  348. l = m ? 1 : 0;
  349. } else {
  350. l = 0;
  351. }
  352. ny = Math.Max (y, l);
  353. if (SuperView == null || SuperView.GetType () != typeof (Toplevel)) {
  354. s = Application.Top.StatusBar != null && Application.Top.StatusBar.Visible;
  355. } else {
  356. s = ((Toplevel)SuperView).StatusBar != null && ((Toplevel)SuperView).StatusBar.Visible;
  357. }
  358. if (SuperView == null || SuperView is Toplevel) {
  359. l = s ? Driver.Rows - 1 : Driver.Rows;
  360. } else {
  361. l = s ? SuperView.Frame.Height - 1 : SuperView.Frame.Height;
  362. }
  363. ny = Math.Min (ny, l);
  364. ny = ny + top.Frame.Height > l ? Math.Max (l - top.Frame.Height, m ? 1 : 0) : ny;
  365. SetHeight (top.Frame.Height, out int rHeight);
  366. if (rHeight < 0 && ny >= top.Frame.Y) {
  367. ny = Math.Max (top.Frame.Bottom - 2, 0);
  368. }
  369. //System.Diagnostics.Debug.WriteLine ($"ny:{ny}, rHeight:{rHeight}");
  370. }
  371. internal void PositionToplevels ()
  372. {
  373. PositionToplevel (this);
  374. foreach (var top in Subviews) {
  375. if (top is Toplevel) {
  376. PositionToplevel ((Toplevel)top);
  377. }
  378. }
  379. }
  380. private void PositionToplevel (Toplevel top)
  381. {
  382. EnsureVisibleBounds (top, top.Frame.X, top.Frame.Y, out int nx, out int ny);
  383. if ((nx != top.Frame.X || ny != top.Frame.Y) && top.LayoutStyle == LayoutStyle.Computed) {
  384. if ((top.X == null || top.X is Pos.PosAbsolute) && top.Bounds.X != nx) {
  385. top.X = nx;
  386. }
  387. if ((top.Y == null || top.Y is Pos.PosAbsolute) && top.Bounds.Y != ny) {
  388. top.Y = ny;
  389. }
  390. }
  391. if (top.StatusBar != null) {
  392. if (ny + top.Frame.Height > top.Frame.Height - (top.StatusBar.Visible ? 1 : 0)) {
  393. if (top.Height is Dim.DimFill)
  394. top.Height = Dim.Fill () - (top.StatusBar.Visible ? 1 : 0);
  395. }
  396. if (top.StatusBar.Frame.Y != top.Frame.Height - (top.StatusBar.Visible ? 1 : 0)) {
  397. top.StatusBar.Y = top.Frame.Height - (top.StatusBar.Visible ? 1 : 0);
  398. top.LayoutSubviews ();
  399. }
  400. top.BringSubviewToFront (top.StatusBar);
  401. }
  402. }
  403. ///<inheritdoc/>
  404. public override void Redraw (Rect bounds)
  405. {
  406. if (IsCurrentTop || this == Application.Top) {
  407. if (!NeedDisplay.IsEmpty || LayoutNeeded) {
  408. Driver.SetAttribute (Colors.TopLevel.Normal);
  409. // This is the Application.Top. Clear just the region we're being asked to redraw
  410. // (the bounds passed to us).
  411. Clear (bounds);
  412. Driver.SetAttribute (Colors.Base.Normal);
  413. PositionToplevels ();
  414. foreach (var view in Subviews) {
  415. if (view.Frame.IntersectsWith (bounds)) {
  416. view.SetNeedsLayout ();
  417. view.SetNeedsDisplay (view.Bounds);
  418. }
  419. }
  420. ClearLayoutNeeded ();
  421. ClearNeedsDisplay ();
  422. }
  423. }
  424. base.Redraw (base.Bounds);
  425. }
  426. /// <summary>
  427. /// Invoked by <see cref="Application.Begin"/> as part of the <see cref="Application.Run(Toplevel, Func{Exception, bool})"/> after
  428. /// the views have been laid out, and before the views are drawn for the first time.
  429. /// </summary>
  430. public virtual void WillPresent ()
  431. {
  432. FocusFirst ();
  433. }
  434. }
  435. }