Toplevel.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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)"/>.
  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)"/>.
  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()"/>(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. if (MenuBar != null && MenuBar.OnKeyDown (keyEvent)) {
  145. return true;
  146. }
  147. break;
  148. }
  149. return false;
  150. }
  151. ///<inheritdoc/>
  152. public override bool OnKeyUp (KeyEvent keyEvent)
  153. {
  154. if (base.OnKeyUp (keyEvent)) {
  155. return true;
  156. }
  157. switch (keyEvent.Key) {
  158. case Key.AltMask:
  159. if (MenuBar != null && MenuBar.OnKeyUp (keyEvent)) {
  160. return true;
  161. }
  162. break;
  163. }
  164. return false;
  165. }
  166. ///<inheritdoc/>
  167. public override bool ProcessKey (KeyEvent keyEvent)
  168. {
  169. if (base.ProcessKey (keyEvent))
  170. return true;
  171. switch (keyEvent.Key) {
  172. case Key.Q | Key.CtrlMask:
  173. // FIXED: stop current execution of this container
  174. Application.RequestStop ();
  175. break;
  176. case Key.Z | Key.CtrlMask:
  177. Driver.Suspend ();
  178. return true;
  179. #if false
  180. case Key.F5:
  181. Application.DebugDrawBounds = !Application.DebugDrawBounds;
  182. SetNeedsDisplay ();
  183. return true;
  184. #endif
  185. case Key.Tab:
  186. case Key.CursorRight:
  187. case Key.CursorDown:
  188. case Key.I | Key.CtrlMask: // Unix
  189. var old = GetDeepestFocusedSubview (Focused);
  190. if (!FocusNext ())
  191. FocusNext ();
  192. if (old != Focused) {
  193. old?.SetNeedsDisplay ();
  194. Focused?.SetNeedsDisplay ();
  195. } else {
  196. FocusNearestView (GetToplevelSubviews (true));
  197. }
  198. return true;
  199. case Key.CursorLeft:
  200. case Key.CursorUp:
  201. case Key.BackTab:
  202. old = GetDeepestFocusedSubview (Focused);
  203. if (!FocusPrev ())
  204. FocusPrev ();
  205. if (old != Focused) {
  206. old?.SetNeedsDisplay ();
  207. Focused?.SetNeedsDisplay ();
  208. } else {
  209. FocusNearestView (GetToplevelSubviews (false));
  210. }
  211. return true;
  212. case Key.L | Key.CtrlMask:
  213. Application.Refresh ();
  214. return true;
  215. }
  216. return false;
  217. }
  218. ///<inheritdoc/>
  219. public override bool ProcessColdKey (KeyEvent keyEvent)
  220. {
  221. if (base.ProcessColdKey (keyEvent)) {
  222. return true;
  223. }
  224. if (ShortcutHelper.FindAndOpenByShortcut(keyEvent, this)) {
  225. return true;
  226. }
  227. return false;
  228. }
  229. View GetDeepestFocusedSubview (View view)
  230. {
  231. if (view == null) {
  232. return null;
  233. }
  234. foreach (var v in view.Subviews) {
  235. if (v.HasFocus) {
  236. return GetDeepestFocusedSubview (v);
  237. }
  238. }
  239. return view;
  240. }
  241. IEnumerable<View> GetToplevelSubviews (bool isForward)
  242. {
  243. if (SuperView == null) {
  244. return null;
  245. }
  246. HashSet<View> views = new HashSet<View> ();
  247. foreach (var v in SuperView.Subviews) {
  248. views.Add (v);
  249. }
  250. return isForward ? views : views.Reverse ();
  251. }
  252. void FocusNearestView (IEnumerable<View> views)
  253. {
  254. if (views == null) {
  255. return;
  256. }
  257. bool found = false;
  258. foreach (var v in views) {
  259. if (v == this) {
  260. found = true;
  261. }
  262. if (found && v != this) {
  263. v.EnsureFocus ();
  264. if (SuperView.Focused != null && SuperView.Focused != this) {
  265. return;
  266. }
  267. }
  268. }
  269. }
  270. ///<inheritdoc/>
  271. public override void Add (View view)
  272. {
  273. if (this == Application.Top) {
  274. AddMenuStatusBar (view);
  275. }
  276. base.Add (view);
  277. }
  278. internal void AddMenuStatusBar (View view)
  279. {
  280. if (view is MenuBar) {
  281. MenuBar = view as MenuBar;
  282. }
  283. if (view is StatusBar) {
  284. StatusBar = view as StatusBar;
  285. }
  286. }
  287. ///<inheritdoc/>
  288. public override void Remove (View view)
  289. {
  290. if (this is Toplevel toplevel && toplevel.MenuBar != null) {
  291. RemoveMenuStatusBar (view);
  292. }
  293. base.Remove (view);
  294. }
  295. ///<inheritdoc/>
  296. public override void RemoveAll ()
  297. {
  298. if (this == Application.Top) {
  299. MenuBar?.Dispose ();
  300. MenuBar = null;
  301. StatusBar?.Dispose ();
  302. StatusBar = null;
  303. }
  304. base.RemoveAll ();
  305. }
  306. internal void RemoveMenuStatusBar (View view)
  307. {
  308. if (view is MenuBar) {
  309. MenuBar?.Dispose ();
  310. MenuBar = null;
  311. }
  312. if (view is StatusBar) {
  313. StatusBar?.Dispose ();
  314. StatusBar = null;
  315. }
  316. }
  317. internal void EnsureVisibleBounds (Toplevel top, int x, int y, out int nx, out int ny)
  318. {
  319. nx = Math.Max (x, 0);
  320. nx = nx + top.Frame.Width > Driver.Cols ? Math.Max (Driver.Cols - top.Frame.Width, 0) : nx;
  321. bool m, s;
  322. if (SuperView == null || SuperView.GetType () != typeof (Toplevel)) {
  323. m = Application.Top.MenuBar != null;
  324. } else {
  325. m = ((Toplevel)SuperView).MenuBar != null;
  326. }
  327. int l;
  328. if (SuperView == null || SuperView is Toplevel) {
  329. l = m ? 1 : 0;
  330. } else {
  331. l = 0;
  332. }
  333. ny = Math.Max (y, l);
  334. if (SuperView == null || SuperView.GetType () != typeof (Toplevel)) {
  335. s = Application.Top.StatusBar != null && Application.Top.StatusBar.Visible;
  336. } else {
  337. s = ((Toplevel)SuperView).StatusBar != null && ((Toplevel)SuperView).StatusBar.Visible;
  338. }
  339. if (SuperView == null || SuperView is Toplevel) {
  340. l = s ? Driver.Rows - 1 : Driver.Rows;
  341. } else {
  342. l = s ? SuperView.Frame.Height - 1 : SuperView.Frame.Height;
  343. }
  344. ny = Math.Min (ny, l);
  345. ny = ny + top.Frame.Height > l ? Math.Max (l - top.Frame.Height, m ? 1 : 0) : ny;
  346. }
  347. internal void PositionToplevels ()
  348. {
  349. PositionToplevel (this);
  350. foreach (var top in Subviews) {
  351. if (top is Toplevel) {
  352. PositionToplevel ((Toplevel)top);
  353. }
  354. }
  355. }
  356. private void PositionToplevel (Toplevel top)
  357. {
  358. EnsureVisibleBounds (top, top.Frame.X, top.Frame.Y, out int nx, out int ny);
  359. if ((nx != top.Frame.X || ny != top.Frame.Y) && top.LayoutStyle == LayoutStyle.Computed) {
  360. if ((top.X == null || top.X is Pos.PosAbsolute) && top.Bounds.X != nx) {
  361. top.X = nx;
  362. }
  363. if ((top.Y == null || top.Y is Pos.PosAbsolute) && top.Bounds.Y != ny) {
  364. top.Y = ny;
  365. }
  366. }
  367. if (top.StatusBar != null) {
  368. if (ny + top.Frame.Height > top.Frame.Height - (top.StatusBar.Visible ? 1 : 0)) {
  369. if (top.Height is Dim.DimFill)
  370. top.Height = Dim.Fill () - (top.StatusBar.Visible ? 1 : 0);
  371. }
  372. if (top.StatusBar.Frame.Y != top.Frame.Height - (top.StatusBar.Visible ? 1 : 0)) {
  373. top.StatusBar.Y = top.Frame.Height - (top.StatusBar.Visible ? 1 : 0);
  374. top.LayoutSubviews ();
  375. }
  376. top.BringSubviewToFront (top.StatusBar);
  377. }
  378. }
  379. ///<inheritdoc/>
  380. public override void Redraw (Rect bounds)
  381. {
  382. Application.CurrentView = this;
  383. if (IsCurrentTop || this == Application.Top) {
  384. if (!NeedDisplay.IsEmpty || LayoutNeeded) {
  385. Driver.SetAttribute (Colors.TopLevel.Normal);
  386. // This is the Application.Top. Clear just the region we're being asked to redraw
  387. // (the bounds passed to us).
  388. Clear (bounds);
  389. Driver.SetAttribute (Colors.Base.Normal);
  390. PositionToplevels ();
  391. foreach (var view in Subviews) {
  392. if (view.Frame.IntersectsWith (bounds)) {
  393. view.SetNeedsLayout ();
  394. view.SetNeedsDisplay (view.Bounds);
  395. }
  396. }
  397. ClearLayoutNeeded ();
  398. ClearNeedsDisplay ();
  399. }
  400. }
  401. base.Redraw (base.Bounds);
  402. }
  403. /// <summary>
  404. /// Invoked by <see cref="Application.Begin"/> as part of the <see cref="Application.Run(Toplevel)"/> after
  405. /// the views have been laid out, and before the views are drawn for the first time.
  406. /// </summary>
  407. public virtual void WillPresent ()
  408. {
  409. FocusFirst ();
  410. }
  411. }
  412. }