Core.cs 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549
  1. //
  2. // Core.cs: The core engine for gui.cs
  3. //
  4. // Authors:
  5. // Miguel de Icaza ([email protected])
  6. //
  7. // Pending:
  8. // - Check for NeedDisplay on the hierarchy and repaint
  9. // - Layout support
  10. // - "Colors" type or "Attributes" type?
  11. // - What to surface as "BackgroundCOlor" when clearing a window, an attribute or colors?
  12. //
  13. // Optimziations
  14. // - Add rendering limitation to the exposed area
  15. using System;
  16. using System.Collections;
  17. using System.Collections.Generic;
  18. using System.Threading;
  19. using System.Linq;
  20. using NStack;
  21. namespace Terminal.Gui {
  22. public class Responder {
  23. public virtual bool CanFocus { get; set; }
  24. public virtual bool HasFocus { get; internal set; }
  25. // Key handling
  26. /// <summary>
  27. /// This method can be overwritten by view that
  28. /// want to provide accelerator functionality
  29. /// (Alt-key for example).
  30. /// </summary>
  31. /// <remarks>
  32. /// <para>
  33. /// Before keys are sent to the subview on the
  34. /// current view, all the views are
  35. /// processed and the key is passed to the widgets
  36. /// to allow some of them to process the keystroke
  37. /// as a hot-key. </para>
  38. /// <para>
  39. /// For example, if you implement a button that
  40. /// has a hotkey ok "o", you would catch the
  41. /// combination Alt-o here. If the event is
  42. /// caught, you must return true to stop the
  43. /// keystroke from being dispatched to other
  44. /// views.
  45. /// </para>
  46. /// </remarks>
  47. public virtual bool ProcessHotKey (KeyEvent kb)
  48. {
  49. return false;
  50. }
  51. /// <summary>
  52. /// If the view is focused, gives the view a
  53. /// chance to process the keystroke.
  54. /// </summary>
  55. /// <remarks>
  56. /// <para>
  57. /// Views can override this method if they are
  58. /// interested in processing the given keystroke.
  59. /// If they consume the keystroke, they must
  60. /// return true to stop the keystroke from being
  61. /// processed by other widgets or consumed by the
  62. /// widget engine. If they return false, the
  63. /// keystroke will be passed using the ProcessColdKey
  64. /// method to other views to process.
  65. /// </para>
  66. /// <para>
  67. /// The View implementation does nothing but return false,
  68. /// so it is not necessary to call base.ProcessKey if you
  69. /// derive directly from View, but you should if you derive
  70. /// other View subclasses.
  71. /// </para>
  72. /// </remarks>
  73. public virtual bool ProcessKey (KeyEvent kb)
  74. {
  75. return false;
  76. }
  77. /// <summary>
  78. /// This method can be overwritten by views that
  79. /// want to provide accelerator functionality
  80. /// (Alt-key for example), but without
  81. /// interefering with normal ProcessKey behavior.
  82. /// </summary>
  83. /// <remarks>
  84. /// <para>
  85. /// After keys are sent to the subviews on the
  86. /// current view, all the view are
  87. /// processed and the key is passed to the views
  88. /// to allow some of them to process the keystroke
  89. /// as a cold-key. </para>
  90. /// <para>
  91. /// This functionality is used, for example, by
  92. /// default buttons to act on the enter key.
  93. /// Processing this as a hot-key would prevent
  94. /// non-default buttons from consuming the enter
  95. /// keypress when they have the focus.
  96. /// </para>
  97. /// </remarks>
  98. public virtual bool ProcessColdKey (KeyEvent kb)
  99. {
  100. return false;
  101. }
  102. /// <summary>
  103. /// Method invoked when a mouse event is generated
  104. /// </summary>
  105. /// <returns><c>true</c>, if the event was handled, <c>false</c> otherwise.</returns>
  106. /// <param name="me">Me.</param>
  107. public virtual bool MouseEvent (MouseEvent me)
  108. {
  109. return false;
  110. }
  111. }
  112. /// <summary>
  113. /// View is the base class for all views on the screen and represents a visible element that can render itself and contains zero or more nested views.
  114. /// </summary>
  115. /// <remarks>
  116. /// <para>
  117. /// The View defines the base functionality for user interface elements in Terminal/gui.cs. Views
  118. /// can contain one or more subviews, can respond to user input and render themselves on the screen.
  119. /// </para>
  120. /// <para>
  121. /// Views are created with a specified rectangle region (the frame) that is relative to the container
  122. /// that they are added into.
  123. /// </para>
  124. /// <para>
  125. /// Subviews can be added to a View by calling the Add method. The container of a view is the
  126. /// Superview.
  127. /// </para>
  128. /// <para>
  129. /// Developers can call the SetNeedsDisplay method on the view to flag a region or the entire view
  130. /// as requiring to be redrawn.
  131. /// </para>
  132. /// <para>
  133. /// Views have a ColorScheme property that defines the default colors that subviews
  134. /// should use for rendering. This ensures that the views fit in the context where
  135. /// they are being used, and allows for themes to be plugged in. For example, the
  136. /// default colors for windows and toplevels uses a blue background, while it uses
  137. /// a white background for dialog boxes and a red background for errors.
  138. /// </para>
  139. /// <para>
  140. /// If a ColorScheme is not set on a view, the result of the ColorScheme is the
  141. /// value of the SuperView and the value might only be valid once a view has been
  142. /// added to a SuperView, so your subclasses should not rely on ColorScheme being
  143. /// set at construction time.
  144. /// </para>
  145. /// <para>
  146. /// Using ColorSchemes has the advantage that your application will work both
  147. /// in color as well as black and white displays.
  148. /// </para>
  149. /// <para>
  150. /// Views that are focusable should implement the PositionCursor to make sure that
  151. /// the cursor is placed in a location that makes sense. Unix terminals do not have
  152. /// a way of hiding the cursor, so it can be distracting to have the cursor left at
  153. /// the last focused view. So views should make sure that they place the cursor
  154. /// in a visually sensible place.
  155. /// </para>
  156. /// </remarks>
  157. public class View : Responder, IEnumerable {
  158. View container = null;
  159. View focused = null;
  160. /// <summary>
  161. /// Points to the current driver in use by the view, it is a convenience property
  162. /// for simplifying the development of new views.
  163. /// </summary>
  164. public static ConsoleDriver Driver = Application.Driver;
  165. static IList<View> empty = new List<View> (0).AsReadOnly ();
  166. List<View> subviews;
  167. /// <summary>
  168. /// This returns a list of the subviews contained by this view.
  169. /// </summary>
  170. /// <value>The subviews.</value>
  171. public IList<View> Subviews => subviews == null ? empty : subviews.AsReadOnly ();
  172. internal Rect NeedDisplay { get; private set; } = Rect.Empty;
  173. // The frame for the object
  174. Rect frame;
  175. /// <summary>
  176. /// Gets or sets an identifier for the view;
  177. /// </summary>
  178. /// <value>The identifier.</value>
  179. public ustring Id { get; set; } = "";
  180. /// <summary>
  181. /// Gets or sets a value indicating whether this <see cref="T:Terminal.Gui.View"/> want mouse position reports.
  182. /// </summary>
  183. /// <value><c>true</c> if want mouse position reports; otherwise, <c>false</c>.</value>
  184. public virtual bool WantMousePositionReports { get; set; } = false;
  185. /// <summary>
  186. /// Gets or sets the frame for the view.
  187. /// </summary>
  188. /// <value>The frame.</value>
  189. /// <remarks>
  190. /// Altering the Frame of a view will trigger the redrawing of the
  191. /// view as well as the redrawing of the affected regions in the superview.
  192. /// </remarks>
  193. public Rect Frame {
  194. get => frame;
  195. set {
  196. if (SuperView != null) {
  197. SuperView.SetNeedsDisplay (frame);
  198. SuperView.SetNeedsDisplay (value);
  199. }
  200. frame = value;
  201. SetNeedsDisplay (frame);
  202. }
  203. }
  204. /// <summary>
  205. /// Gets an enumerator that enumerates the subviews in this view.
  206. /// </summary>
  207. /// <returns>The enumerator.</returns>
  208. public IEnumerator GetEnumerator ()
  209. {
  210. foreach (var v in subviews)
  211. yield return v;
  212. }
  213. /// <summary>
  214. /// The bounds represent the View-relative rectangle used for this view. Updates to the Bounds update the Frame, and has the same side effects as updating the frame.
  215. /// </summary>
  216. /// <value>The bounds.</value>
  217. public Rect Bounds {
  218. get => new Rect (Point.Empty, Frame.Size);
  219. set {
  220. Frame = new Rect (frame.Location, value.Size);
  221. }
  222. }
  223. /// <summary>
  224. /// Returns the container for this view, or null if this view has not been added to a container.
  225. /// </summary>
  226. /// <value>The super view.</value>
  227. public View SuperView => container;
  228. /// <summary>
  229. /// Initializes a new instance of the <see cref="T:Terminal.Gui.View"/> class with the specified frame. This is the default constructor.
  230. /// </summary>
  231. /// <param name="frame">The region covered by this view.</param>
  232. public View (Rect frame)
  233. {
  234. this.Frame = frame;
  235. CanFocus = false;
  236. }
  237. /// <summary>
  238. /// Invoke to flag that this view needs to be redisplayed, by any code
  239. /// that alters the state of the view.
  240. /// </summary>
  241. public void SetNeedsDisplay ()
  242. {
  243. SetNeedsDisplay (Bounds);
  244. }
  245. /// <summary>
  246. /// Flags the specified rectangle region on this view as needing to be repainted.
  247. /// </summary>
  248. /// <param name="region">The region that must be flagged for repaint.</param>
  249. public void SetNeedsDisplay (Rect region)
  250. {
  251. if (NeedDisplay.IsEmpty)
  252. NeedDisplay = region;
  253. else {
  254. var x = Math.Min (NeedDisplay.X, region.X);
  255. var y = Math.Min (NeedDisplay.Y, region.Y);
  256. var w = Math.Max (NeedDisplay.Width, region.Width);
  257. var h = Math.Max (NeedDisplay.Height, region.Height);
  258. NeedDisplay = new Rect (x, y, w, h);
  259. }
  260. if (container != null)
  261. container.ChildNeedsDisplay ();
  262. if (subviews == null)
  263. return;
  264. foreach (var view in subviews)
  265. if (view.Frame.IntersectsWith (region)) {
  266. var childRegion = Rect.Intersect (view.Frame, region);
  267. childRegion.X -= view.Frame.X;
  268. childRegion.Y -= view.Frame.Y;
  269. view.SetNeedsDisplay (childRegion);
  270. }
  271. }
  272. internal bool childNeedsDisplay;
  273. /// <summary>
  274. /// Flags this view for requiring the children views to be repainted.
  275. /// </summary>
  276. public void ChildNeedsDisplay ()
  277. {
  278. childNeedsDisplay = true;
  279. if (container != null)
  280. container.ChildNeedsDisplay ();
  281. }
  282. /// <summary>
  283. /// Adds a subview to this view.
  284. /// </summary>
  285. /// <remarks>
  286. /// </remarks>
  287. public virtual void Add (View view)
  288. {
  289. if (view == null)
  290. return;
  291. if (subviews == null)
  292. subviews = new List<View> ();
  293. subviews.Add (view);
  294. view.container = this;
  295. if (view.CanFocus)
  296. CanFocus = true;
  297. SetNeedsDisplay ();
  298. }
  299. /// <summary>
  300. /// Adds the specified views to the view.
  301. /// </summary>
  302. /// <param name="views">Array of one or more views (can be optional parameter).</param>
  303. public void Add (params View [] views)
  304. {
  305. if (views == null)
  306. return;
  307. foreach (var view in views)
  308. Add (view);
  309. }
  310. /// <summary>
  311. /// Removes all the widgets from this container.
  312. /// </summary>
  313. /// <remarks>
  314. /// </remarks>
  315. public virtual void RemoveAll ()
  316. {
  317. if (subviews == null)
  318. return;
  319. while (subviews.Count > 0) {
  320. var view = subviews [0];
  321. Remove (view);
  322. subviews.RemoveAt (0);
  323. }
  324. }
  325. /// <summary>
  326. /// Removes a widget from this container.
  327. /// </summary>
  328. /// <remarks>
  329. /// </remarks>
  330. public virtual void Remove (View view)
  331. {
  332. if (view == null)
  333. return;
  334. SetNeedsDisplay ();
  335. var touched = view.Frame;
  336. subviews.Remove (view);
  337. view.container = null;
  338. if (subviews.Count < 1)
  339. this.CanFocus = false;
  340. foreach (var v in subviews) {
  341. if (v.Frame.IntersectsWith (touched))
  342. view.SetNeedsDisplay ();
  343. }
  344. }
  345. /// <summary>
  346. /// Clears the view region with the current color.
  347. /// </summary>
  348. /// <remarks>
  349. /// <para>
  350. /// This clears the entire region used by this view.
  351. /// </para>
  352. /// </remarks>
  353. public void Clear ()
  354. {
  355. var h = Frame.Height;
  356. var w = Frame.Width;
  357. for (int line = 0; line < h; line++) {
  358. Move (0, line);
  359. for (int col = 0; col < w; col++)
  360. Driver.AddRune (' ');
  361. }
  362. }
  363. /// <summary>
  364. /// Clears the specfied rectangular region with the current color
  365. /// </summary>
  366. public void Clear (Rect r)
  367. {
  368. var h = r.Height;
  369. var w = r.Width;
  370. for (int line = 0; line < h; line++) {
  371. Move (0, line);
  372. for (int col = 0; col < w; col++)
  373. Driver.AddRune (' ');
  374. }
  375. }
  376. /// <summary>
  377. /// Converts the (col,row) position from the view into a screen (col,row). The values are clamped to (0..ScreenDim-1)
  378. /// </summary>
  379. /// <param name="col">View-based column.</param>
  380. /// <param name="row">View-based row.</param>
  381. /// <param name="rcol">Absolute column, display relative.</param>
  382. /// <param name="rrow">Absolute row, display relative.</param>
  383. /// <param name="clipped">Whether to clip the result of the ViewToScreen method, if set to true, the rcol, rrow values are clamped to the screen dimensions.</param>
  384. internal void ViewToScreen (int col, int row, out int rcol, out int rrow, bool clipped = true)
  385. {
  386. // Computes the real row, col relative to the screen.
  387. rrow = row + frame.Y;
  388. rcol = col + frame.X;
  389. var ccontainer = container;
  390. while (ccontainer != null) {
  391. rrow += ccontainer.frame.Y;
  392. rcol += ccontainer.frame.X;
  393. ccontainer = ccontainer.container;
  394. }
  395. // The following ensures that the cursor is always in the screen boundaries.
  396. if (clipped) {
  397. rrow = Math.Max (0, Math.Min (rrow, Driver.Rows - 1));
  398. rcol = Math.Max (0, Math.Min (rcol, Driver.Cols - 1));
  399. }
  400. }
  401. /// <summary>
  402. /// Converts a point from screen coordinates into the view coordinate space.
  403. /// </summary>
  404. /// <returns>The mapped point.</returns>
  405. /// <param name="x">X screen-coordinate point.</param>
  406. /// <param name="y">Y screen-coordinate point.</param>
  407. public Point ScreenToView (int x, int y)
  408. {
  409. if (SuperView == null) {
  410. return new Point (x - Frame.X, y - frame.Y);
  411. } else {
  412. var parent = SuperView.ScreenToView (x, y);
  413. return new Point (parent.X - frame.X, parent.Y - frame.Y);
  414. }
  415. }
  416. // Converts a rectangle in view coordinates to screen coordinates.
  417. Rect RectToScreen (Rect rect)
  418. {
  419. ViewToScreen (rect.X, rect.Y, out var x, out var y, clipped: false);
  420. return new Rect (x, y, rect.Width, rect.Height);
  421. }
  422. // Clips a rectangle in screen coordinates to the dimensions currently available on the screen
  423. Rect ScreenClip (Rect rect)
  424. {
  425. var x = rect.X < 0 ? 0 : rect.X;
  426. var y = rect.Y < 0 ? 0 : rect.Y;
  427. var w = rect.X + rect.Width >= Driver.Cols ? Driver.Cols - rect.X : rect.Width;
  428. var h = rect.Y + rect.Height >= Driver.Rows ? Driver.Rows - rect.Y : rect.Height;
  429. return new Rect (x, y, w, h);
  430. }
  431. /// <summary>
  432. /// Sets the Console driver's clip region to the current View's Bounds.
  433. /// </summary>
  434. /// <returns>The existing driver's Clip region, which can be then set by setting the Driver.Clip property.</returns>
  435. public Rect ClipToBounds ()
  436. {
  437. return SetClip (Bounds);
  438. }
  439. /// <summary>
  440. /// Sets the clipping region to the specified region, the region is view-relative
  441. /// </summary>
  442. /// <returns>The previous clip region.</returns>
  443. /// <param name="rect">Rectangle region to clip into, the region is view-relative.</param>
  444. public Rect SetClip (Rect rect)
  445. {
  446. var bscreen = RectToScreen (rect);
  447. var previous = Driver.Clip;
  448. Driver.Clip = ScreenClip (RectToScreen (Bounds));
  449. return previous;
  450. }
  451. /// <summary>
  452. /// Draws a frame in the current view, clipped by the boundary of this view
  453. /// </summary>
  454. /// <param name="rect">Rectangular region for the frame to be drawn.</param>
  455. /// <param name="padding">The padding to add to the drawn frame.</param>
  456. /// <param name="fill">If set to <c>true</c> it fill will the contents.</param>
  457. public void DrawFrame (Rect rect, int padding = 0, bool fill = false)
  458. {
  459. var scrRect = RectToScreen (rect);
  460. var savedClip = Driver.Clip;
  461. Driver.Clip = ScreenClip (RectToScreen (Bounds));
  462. Driver.DrawFrame (scrRect, padding, fill);
  463. Driver.Clip = savedClip;
  464. }
  465. /// <summary>
  466. /// Utility function to draw strings that contain a hotkey
  467. /// </summary>
  468. /// <param name="text">String to display, the underscoore before a letter flags the next letter as the hotkey.</param>
  469. /// <param name="hotColor">Hot color.</param>
  470. /// <param name="normalColor">Normal color.</param>
  471. public void DrawHotString (ustring text, Attribute hotColor, Attribute normalColor)
  472. {
  473. Driver.SetAttribute (normalColor);
  474. foreach (var rune in text) {
  475. if (rune == '_') {
  476. Driver.SetAttribute (hotColor);
  477. continue;
  478. }
  479. Driver.AddRune (rune);
  480. Driver.SetAttribute (normalColor);
  481. }
  482. }
  483. /// <summary>
  484. /// Utility function to draw strings that contains a hotkey using a colorscheme and the "focused" state.
  485. /// </summary>
  486. /// <param name="text">String to display, the underscoore before a letter flags the next letter as the hotkey.</param>
  487. /// <param name="focused">If set to <c>true</c> this uses the focused colors from the color scheme, otherwise the regular ones.</param>
  488. /// <param name="scheme">The color scheme to use.</param>
  489. public void DrawHotString (ustring text, bool focused, ColorScheme scheme)
  490. {
  491. if (focused)
  492. DrawHotString (text, scheme.HotFocus, scheme.Focus);
  493. else
  494. DrawHotString (text, scheme.HotNormal, scheme.Normal);
  495. }
  496. /// <summary>
  497. /// This moves the cursor to the specified column and row in the view.
  498. /// </summary>
  499. /// <returns>The move.</returns>
  500. /// <param name="col">Col.</param>
  501. /// <param name="row">Row.</param>
  502. public void Move (int col, int row)
  503. {
  504. ViewToScreen (col, row, out var rcol, out var rrow);
  505. Driver.Move (rcol, rrow);
  506. }
  507. /// <summary>
  508. /// Positions the cursor in the right position based on the currently focused view in the chain.
  509. /// </summary>
  510. public virtual void PositionCursor ()
  511. {
  512. if (focused != null)
  513. focused.PositionCursor ();
  514. else
  515. Move (frame.X, frame.Y);
  516. }
  517. /// <summary>
  518. /// Gets or sets a value indicating whether this <see cref="T:Terminal.Gui.View"/> has focus.
  519. /// </summary>
  520. /// <value><c>true</c> if has focus; otherwise, <c>false</c>.</value>
  521. public override bool HasFocus {
  522. get {
  523. return base.HasFocus;
  524. }
  525. internal set {
  526. if (base.HasFocus != value)
  527. SetNeedsDisplay ();
  528. base.HasFocus = value;
  529. }
  530. }
  531. /// <summary>
  532. /// Returns the currently focused view inside this view, or null if nothing is focused.
  533. /// </summary>
  534. /// <value>The focused.</value>
  535. public View Focused => focused;
  536. /// <summary>
  537. /// Returns the most focused view in the chain of subviews (the leaf view that has the focus).
  538. /// </summary>
  539. /// <value>The most focused.</value>
  540. public View MostFocused {
  541. get {
  542. if (Focused == null)
  543. return null;
  544. var most = Focused.MostFocused;
  545. if (most != null)
  546. return most;
  547. return Focused;
  548. }
  549. }
  550. /// <summary>
  551. /// The color scheme for this view, if it is not defined, it returns the parent's
  552. /// color scheme.
  553. /// </summary>
  554. public ColorScheme ColorScheme {
  555. get {
  556. if (colorScheme == null)
  557. return SuperView?.ColorScheme;
  558. return colorScheme;
  559. }
  560. set {
  561. colorScheme = value;
  562. }
  563. }
  564. ColorScheme colorScheme;
  565. /// <summary>
  566. /// Displays the specified character in the specified column and row.
  567. /// </summary>
  568. /// <param name="col">Col.</param>
  569. /// <param name="row">Row.</param>
  570. /// <param name="ch">Ch.</param>
  571. public void AddRune (int col, int row, Rune ch)
  572. {
  573. if (row < 0 || col < 0)
  574. return;
  575. if (row > frame.Height - 1 || col > frame.Width - 1)
  576. return;
  577. Move (col, row);
  578. Driver.AddRune (ch);
  579. }
  580. /// <summary>
  581. /// Removes the SetNeedsDisplay and the ChildNeedsDisplay setting on this view.
  582. /// </summary>
  583. protected void ClearNeedsDisplay ()
  584. {
  585. NeedDisplay = Rect.Empty;
  586. childNeedsDisplay = false;
  587. }
  588. /// <summary>
  589. /// Performs a redraw of this view and its subviews, only redraws the views that have been flagged for a re-display.
  590. /// </summary>
  591. /// <param name="region">The region to redraw, this is relative to the view itself.</param>
  592. /// <remarks>
  593. /// <para>
  594. /// Views should set the color that they want to use on entry, as otherwise this will inherit
  595. /// the last color that was set globaly on the driver.
  596. /// </para>
  597. /// </remarks>
  598. public virtual void Redraw (Rect region)
  599. {
  600. var clipRect = new Rect (Point.Empty, frame.Size);
  601. if (subviews != null) {
  602. foreach (var view in subviews) {
  603. if (!view.NeedDisplay.IsEmpty || view.childNeedsDisplay) {
  604. if (view.Frame.IntersectsWith (clipRect) && view.Frame.IntersectsWith (region)) {
  605. // TODO: optimize this by computing the intersection of region and view.Bounds
  606. view.Redraw (view.Bounds);
  607. }
  608. view.NeedDisplay = Rect.Empty;
  609. view.childNeedsDisplay = false;
  610. }
  611. }
  612. }
  613. ClearNeedsDisplay ();
  614. }
  615. /// <summary>
  616. /// Focuses the specified sub-view.
  617. /// </summary>
  618. /// <param name="view">View.</param>
  619. public void SetFocus (View view)
  620. {
  621. if (view == null)
  622. return;
  623. //Console.WriteLine ($"Request to focus {view}");
  624. if (!view.CanFocus)
  625. return;
  626. if (focused == view)
  627. return;
  628. // Make sure that this view is a subview
  629. View c;
  630. for (c = view.container; c != null; c = c.container)
  631. if (c == this)
  632. break;
  633. if (c == null)
  634. throw new ArgumentException ("the specified view is not part of the hierarchy of this view");
  635. if (focused != null)
  636. focused.HasFocus = false;
  637. focused = view;
  638. focused.HasFocus = true;
  639. focused.EnsureFocus ();
  640. }
  641. public override bool ProcessKey (KeyEvent kb)
  642. {
  643. if (Focused?.ProcessKey (kb) == true)
  644. return true;
  645. return false;
  646. }
  647. public override bool ProcessHotKey (KeyEvent kb)
  648. {
  649. if (subviews == null || subviews.Count == 0)
  650. return false;
  651. foreach (var view in subviews)
  652. if (view.ProcessHotKey (kb))
  653. return true;
  654. return false;
  655. }
  656. public override bool ProcessColdKey (KeyEvent kb)
  657. {
  658. if (subviews == null || subviews.Count == 0)
  659. return false;
  660. foreach (var view in subviews)
  661. if (view.ProcessColdKey (kb))
  662. return true;
  663. return false;
  664. }
  665. /// <summary>
  666. /// Finds the first view in the hierarchy that wants to get the focus if nothing is currently focused, otherwise, it does nothing.
  667. /// </summary>
  668. public void EnsureFocus ()
  669. {
  670. if (focused == null)
  671. FocusFirst ();
  672. }
  673. /// <summary>
  674. /// Focuses the first focusable subview if one exists.
  675. /// </summary>
  676. public void FocusFirst ()
  677. {
  678. if (subviews == null) {
  679. SuperView.SetFocus (this);
  680. return;
  681. }
  682. foreach (var view in subviews) {
  683. if (view.CanFocus) {
  684. SetFocus (view);
  685. return;
  686. }
  687. }
  688. }
  689. /// <summary>
  690. /// Focuses the last focusable subview if one exists.
  691. /// </summary>
  692. public void FocusLast ()
  693. {
  694. if (subviews == null)
  695. return;
  696. for (int i = subviews.Count; i > 0;) {
  697. i--;
  698. View v = subviews [i];
  699. if (v.CanFocus) {
  700. SetFocus (v);
  701. return;
  702. }
  703. }
  704. }
  705. /// <summary>
  706. /// Focuses the previous view.
  707. /// </summary>
  708. /// <returns><c>true</c>, if previous was focused, <c>false</c> otherwise.</returns>
  709. public bool FocusPrev ()
  710. {
  711. if (subviews == null || subviews.Count == 0)
  712. return false;
  713. if (focused == null) {
  714. FocusLast ();
  715. return true;
  716. }
  717. int focused_idx = -1;
  718. for (int i = subviews.Count; i > 0;) {
  719. i--;
  720. View w = subviews [i];
  721. if (w.HasFocus) {
  722. if (w.FocusPrev ())
  723. return true;
  724. focused_idx = i;
  725. continue;
  726. }
  727. if (w.CanFocus && focused_idx != -1) {
  728. focused.HasFocus = false;
  729. if (w.CanFocus)
  730. w.FocusLast ();
  731. SetFocus (w);
  732. return true;
  733. }
  734. }
  735. if (focused_idx != -1) {
  736. FocusLast ();
  737. return true;
  738. }
  739. if (focused != null) {
  740. focused.HasFocus = false;
  741. focused = null;
  742. }
  743. return false;
  744. }
  745. /// <summary>
  746. /// Focuses the next view.
  747. /// </summary>
  748. /// <returns><c>true</c>, if next was focused, <c>false</c> otherwise.</returns>
  749. public bool FocusNext ()
  750. {
  751. if (subviews == null || subviews.Count == 0)
  752. return false;
  753. if (focused == null) {
  754. FocusFirst ();
  755. return focused != null;
  756. }
  757. int n = subviews.Count;
  758. int focused_idx = -1;
  759. for (int i = 0; i < n; i++) {
  760. View w = subviews [i];
  761. if (w.HasFocus) {
  762. if (w.FocusNext ())
  763. return true;
  764. focused_idx = i;
  765. continue;
  766. }
  767. if (w.CanFocus && focused_idx != -1) {
  768. focused.HasFocus = false;
  769. if (w != null && w.CanFocus)
  770. w.FocusFirst ();
  771. SetFocus (w);
  772. return true;
  773. }
  774. }
  775. if (focused != null) {
  776. focused.HasFocus = false;
  777. focused = null;
  778. }
  779. return false;
  780. }
  781. /// <summary>
  782. /// This virtual method is invoked when a view starts executing or
  783. /// when the dimensions of the view have changed, for example in
  784. /// response to the container view or terminal resizing.
  785. /// </summary>
  786. public virtual void LayoutSubviews ()
  787. {
  788. }
  789. /// <summary>
  790. /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:Terminal.Gui.View"/>.
  791. /// </summary>
  792. /// <returns>A <see cref="T:System.String"/> that represents the current <see cref="T:Terminal.Gui.View"/>.</returns>
  793. public override string ToString ()
  794. {
  795. return $"{GetType ().Name}({Id})({Frame})";
  796. }
  797. }
  798. /// <summary>
  799. /// Toplevel views can be modally executed.
  800. /// </summary>
  801. /// <remarks>
  802. /// <para>
  803. /// Toplevels can be modally executing views, and they return control
  804. /// to the caller when the "Running" property is set to false.
  805. /// </para>
  806. /// </remarks>
  807. public class Toplevel : View {
  808. /// <summary>
  809. /// This flag is checked on each iteration of the mainloop and it continues
  810. /// running until this flag is set to false.
  811. /// </summary>
  812. public bool Running;
  813. /// <summary>
  814. /// Initializes a new instance of the <see cref="T:Terminal.Gui.Toplevel"/> class.
  815. /// </summary>
  816. /// <param name="frame">Frame.</param>
  817. public Toplevel (Rect frame) : base (frame)
  818. {
  819. ColorScheme = Colors.Base;
  820. }
  821. /// <summary>
  822. /// Convenience factory method that creates a new toplevel with the current terminal dimensions.
  823. /// </summary>
  824. /// <returns>The create.</returns>
  825. public static Toplevel Create ()
  826. {
  827. return new Toplevel (new Rect (0, 0, Driver.Cols, Driver.Rows));
  828. }
  829. public override bool CanFocus {
  830. get => true;
  831. }
  832. public override bool ProcessKey (KeyEvent kb)
  833. {
  834. if (base.ProcessKey (kb))
  835. return true;
  836. switch (kb.Key) {
  837. case Key.ControlC:
  838. // TODO: stop current execution of this container
  839. break;
  840. case Key.ControlZ:
  841. Driver.Suspend ();
  842. return true;
  843. #if false
  844. case Key.F5:
  845. Application.DebugDrawBounds = !Application.DebugDrawBounds;
  846. SetNeedsDisplay ();
  847. return true;
  848. #endif
  849. case Key.Tab:
  850. case Key.CursorRight:
  851. case Key.CursorDown:
  852. var old = Focused;
  853. if (!FocusNext ())
  854. FocusNext ();
  855. if (old != Focused) {
  856. old?.SetNeedsDisplay ();
  857. Focused?.SetNeedsDisplay ();
  858. }
  859. return true;
  860. case Key.CursorLeft:
  861. case Key.CursorUp:
  862. case Key.BackTab:
  863. old = Focused;
  864. if (!FocusPrev ())
  865. FocusPrev ();
  866. if (old != Focused) {
  867. old?.SetNeedsDisplay ();
  868. Focused?.SetNeedsDisplay ();
  869. }
  870. return true;
  871. case Key.ControlL:
  872. Application.Refresh ();
  873. return true;
  874. }
  875. return false;
  876. }
  877. }
  878. /// <summary>
  879. /// A toplevel view that draws a frame around its region and has a "ContentView" subview where the contents are added.
  880. /// </summary>
  881. public class Window : Toplevel, IEnumerable {
  882. View contentView;
  883. ustring title;
  884. /// <summary>
  885. /// The title to be displayed for this window.
  886. /// </summary>
  887. /// <value>The title.</value>
  888. public ustring Title {
  889. get => title;
  890. set {
  891. title = value;
  892. SetNeedsDisplay ();
  893. }
  894. }
  895. class ContentView : View {
  896. public ContentView (Rect frame) : base (frame) { }
  897. }
  898. /// <summary>
  899. /// Initializes a new instance of the <see cref="T:Terminal.Gui.Gui.Window"/> class with an optioanl title
  900. /// </summary>
  901. /// <param name="frame">Frame.</param>
  902. /// <param name="title">Title.</param>
  903. public Window (Rect frame, ustring title = null) : this (frame, title, padding: 0)
  904. {
  905. }
  906. int padding;
  907. /// <summary>
  908. /// Initializes a new instance of the <see cref="T:Terminal.Gui.Window"/> with
  909. /// the specified frame for its location, with the specified border
  910. /// an optional title.
  911. /// </summary>
  912. /// <param name="frame">Frame.</param>
  913. /// <param name="padding">Number of characters to use for padding of the drawn frame.</param>
  914. /// <param name="title">Title.</param>
  915. public Window (Rect frame, ustring title = null, int padding = 0) : base (frame)
  916. {
  917. this.Title = title;
  918. int wb = 2 * (1 + padding);
  919. this.padding = padding;
  920. var cFrame = new Rect (1 + padding, 1 + padding, frame.Width - wb, frame.Height - wb);
  921. contentView = new ContentView (cFrame);
  922. base.Add (contentView);
  923. }
  924. /// <summary>
  925. /// Enumerates the various views in the ContentView.
  926. /// </summary>
  927. /// <returns>The enumerator.</returns>
  928. public new IEnumerator GetEnumerator ()
  929. {
  930. return contentView.GetEnumerator ();
  931. }
  932. void DrawFrame ()
  933. {
  934. DrawFrame (new Rect (0, 0, Frame.Width, Frame.Height), padding, fill: true);
  935. }
  936. /// <summary>
  937. /// Add the specified view to the ContentView.
  938. /// </summary>
  939. /// <param name="view">View to add to the window.</param>
  940. public override void Add (View view)
  941. {
  942. contentView.Add (view);
  943. if (view.CanFocus)
  944. CanFocus = true;
  945. }
  946. /// <summary>
  947. /// Removes a widget from this container.
  948. /// </summary>
  949. /// <remarks>
  950. /// </remarks>
  951. public virtual void Remove (View view)
  952. {
  953. if (view == null)
  954. return;
  955. SetNeedsDisplay ();
  956. var touched = view.Frame;
  957. contentView.Remove (view);
  958. if (contentView.Subviews.Count < 1)
  959. this.CanFocus = false;
  960. }
  961. public override void Redraw (Rect bounds)
  962. {
  963. if (!NeedDisplay.IsEmpty) {
  964. Driver.SetAttribute (ColorScheme.Normal);
  965. DrawFrame ();
  966. if (HasFocus)
  967. Driver.SetAttribute (ColorScheme.Normal);
  968. var width = Frame.Width;
  969. if (Title != null && width > 4) {
  970. Move (1+padding, padding);
  971. Driver.AddRune (' ');
  972. var str = Title.Length > width ? Title [0, width-4] : Title;
  973. Driver.AddStr (str);
  974. Driver.AddRune (' ');
  975. }
  976. Driver.SetAttribute (ColorScheme.Normal);
  977. }
  978. contentView.Redraw (contentView.Bounds);
  979. ClearNeedsDisplay ();
  980. }
  981. #if false
  982. //
  983. // It does not look like the event is raised on clicked-drag
  984. // need to figure that out.
  985. //
  986. Point? dragPosition;
  987. public override bool MouseEvent(MouseEvent me)
  988. {
  989. if (me.Flags == MouseFlags.Button1Pressed){
  990. if (dragPosition.HasValue) {
  991. var dx = me.X - dragPosition.Value.X;
  992. var dy = me.Y - dragPosition.Value.Y;
  993. var nx = Frame.X + dx;
  994. var ny = Frame.Y + dy;
  995. if (nx < 0)
  996. nx = 0;
  997. if (ny < 0)
  998. ny = 0;
  999. Demo.ml2.Text = $"{dx},{dy}";
  1000. dragPosition = new Point (me.X, me.Y);
  1001. // TODO: optimize, only SetNeedsDisplay on the before/after regions.
  1002. if (SuperView == null)
  1003. Application.Refresh ();
  1004. else
  1005. SuperView.SetNeedsDisplay ();
  1006. Frame = new Rect (nx, ny, Frame.Width, Frame.Height);
  1007. SetNeedsDisplay ();
  1008. return true;
  1009. } else {
  1010. dragPosition = new Point (me.X, me.Y);
  1011. Application.GrabMouse (this);
  1012. Demo.ml2.Text = $"Starting at {dragPosition}";
  1013. return true;
  1014. }
  1015. }
  1016. if (me.Flags == MouseFlags.Button1Released) {
  1017. Application.UngrabMouse ();
  1018. dragPosition = null;
  1019. //Driver.StopReportingMouseMoves ();
  1020. }
  1021. Demo.ml.Text = me.ToString ();
  1022. return false;
  1023. }
  1024. #endif
  1025. }
  1026. /// <summary>
  1027. /// The application driver for gui.cs
  1028. /// </summary>
  1029. /// <remarks>
  1030. /// <para>
  1031. /// You can hook up to the Iteration event to have your method
  1032. /// invoked on each iteration of the mainloop.
  1033. /// </para>
  1034. /// <para>
  1035. /// Creates a mainloop to process input events, handle timers and
  1036. /// other sources of data. It is accessible via the MainLoop property.
  1037. /// </para>
  1038. /// <para>
  1039. /// When invoked sets the SynchronizationContext to one that is tied
  1040. /// to the mainloop, allowing user code to use async/await.
  1041. /// </para>
  1042. /// </remarks>
  1043. public class Application {
  1044. /// <summary>
  1045. /// The current Console Driver in use.
  1046. /// </summary>
  1047. public static ConsoleDriver Driver = new CursesDriver ();
  1048. /// <summary>
  1049. /// The Toplevel object used for the application on startup.
  1050. /// </summary>
  1051. /// <value>The top.</value>
  1052. public static Toplevel Top { get; private set; }
  1053. /// <summary>
  1054. /// The current toplevel object. This is updated when Application.Run enters and leaves and points to the current toplevel.
  1055. /// </summary>
  1056. /// <value>The current.</value>
  1057. public static Toplevel Current { get; private set; }
  1058. /// <summary>
  1059. /// The mainloop driver for the applicaiton
  1060. /// </summary>
  1061. /// <value>The main loop.</value>
  1062. public static Mono.Terminal.MainLoop MainLoop { get; private set; }
  1063. static Stack<Toplevel> toplevels = new Stack<Toplevel> ();
  1064. /// <summary>
  1065. /// This event is raised on each iteration of the
  1066. /// main loop.
  1067. /// </summary>
  1068. /// <remarks>
  1069. /// See also <see cref="Timeout"/>
  1070. /// </remarks>
  1071. static public event EventHandler Iteration;
  1072. /// <summary>
  1073. /// Returns a rectangle that is centered in the screen for the provided size.
  1074. /// </summary>
  1075. /// <returns>The centered rect.</returns>
  1076. /// <param name="size">Size for the rectangle.</param>
  1077. public static Rect MakeCenteredRect (Size size)
  1078. {
  1079. return new Rect (new Point ((Driver.Cols - size.Width) / 2, (Driver.Rows - size.Height) / 2), size);
  1080. }
  1081. //
  1082. // provides the sync context set while executing code in gui.cs, to let
  1083. // users use async/await on their code
  1084. //
  1085. class MainLoopSyncContext : SynchronizationContext {
  1086. Mono.Terminal.MainLoop mainLoop;
  1087. public MainLoopSyncContext (Mono.Terminal.MainLoop mainLoop)
  1088. {
  1089. this.mainLoop = mainLoop;
  1090. }
  1091. public override SynchronizationContext CreateCopy ()
  1092. {
  1093. return new MainLoopSyncContext (MainLoop);
  1094. }
  1095. public override void Post (SendOrPostCallback d, object state)
  1096. {
  1097. mainLoop.AddIdle (() => {
  1098. d (state);
  1099. return false;
  1100. });
  1101. }
  1102. public override void Send (SendOrPostCallback d, object state)
  1103. {
  1104. mainLoop.Invoke (() => {
  1105. d (state);
  1106. });
  1107. }
  1108. }
  1109. /// <summary>
  1110. /// Initializes the Application
  1111. /// </summary>
  1112. public static void Init ()
  1113. {
  1114. if (Top != null)
  1115. return;
  1116. Driver.Init (TerminalResized);
  1117. MainLoop = new Mono.Terminal.MainLoop ();
  1118. SynchronizationContext.SetSynchronizationContext (new MainLoopSyncContext (MainLoop));
  1119. Top = Toplevel.Create ();
  1120. Current = Top;
  1121. }
  1122. /// <summary>
  1123. /// Captures the execution state for the provided TopLevel view.
  1124. /// </summary>
  1125. public class RunState : IDisposable {
  1126. internal RunState (Toplevel view)
  1127. {
  1128. Toplevel = view;
  1129. }
  1130. internal Toplevel Toplevel;
  1131. /// <summary>
  1132. /// Releases all resource used by the <see cref="T:Terminal.Gui.Application.RunState"/> object.
  1133. /// </summary>
  1134. /// <remarks>Call <see cref="Dispose"/> when you are finished using the <see cref="T:Terminal.Gui.Application.RunState"/>. The
  1135. /// <see cref="Dispose"/> method leaves the <see cref="T:Terminal.Gui.Application.RunState"/> in an unusable state. After
  1136. /// calling <see cref="Dispose"/>, you must release all references to the
  1137. /// <see cref="T:Terminal.Gui.Application.RunState"/> so the garbage collector can reclaim the memory that the
  1138. /// <see cref="T:Terminal.Gui.Application.RunState"/> was occupying.</remarks>
  1139. public void Dispose ()
  1140. {
  1141. Dispose (true);
  1142. GC.SuppressFinalize (this);
  1143. }
  1144. /// <summary>
  1145. /// Dispose the specified disposing.
  1146. /// </summary>
  1147. /// <returns>The dispose.</returns>
  1148. /// <param name="disposing">If set to <c>true</c> disposing.</param>
  1149. public virtual void Dispose (bool disposing)
  1150. {
  1151. if (Toplevel != null) {
  1152. Application.End (Toplevel);
  1153. Toplevel = null;
  1154. }
  1155. }
  1156. }
  1157. static void ProcessKeyEvent (KeyEvent ke)
  1158. {
  1159. if (Current.ProcessHotKey (ke))
  1160. return;
  1161. if (Current.ProcessKey (ke))
  1162. return;
  1163. // Process the key normally
  1164. if (Current.ProcessColdKey (ke))
  1165. return;
  1166. }
  1167. static View FindDeepestView (View start, int x, int y, out int resx, out int resy)
  1168. {
  1169. var startFrame = start.Frame;
  1170. if (!startFrame.Contains (x, y)) {
  1171. resx = 0;
  1172. resy = 0;
  1173. return null;
  1174. }
  1175. if (start.Subviews != null){
  1176. int count = start.Subviews.Count;
  1177. if (count > 0) {
  1178. var rx = x - startFrame.X;
  1179. var ry = y - startFrame.Y;
  1180. for (int i = count - 1; i >= 0; i--) {
  1181. View v = start.Subviews [i];
  1182. if (v.Frame.Contains (rx, ry)) {
  1183. var deep = FindDeepestView (v, rx, ry, out resx, out resy);
  1184. if (deep == null)
  1185. return v;
  1186. return deep;
  1187. }
  1188. }
  1189. }
  1190. }
  1191. resx = x-startFrame.X;
  1192. resy = y-startFrame.Y;
  1193. return start;
  1194. }
  1195. static View mouseGrabView;
  1196. /// <summary>
  1197. /// Grabs the mouse, forcing all mouse events to be routed to the specified view until UngrabMouse is called.
  1198. /// </summary>
  1199. /// <returns>The grab.</returns>
  1200. /// <param name="view">View that will receive all mouse events until UngrabMouse is invoked.</param>
  1201. public static void GrabMouse (View view)
  1202. {
  1203. if (view == null)
  1204. return;
  1205. mouseGrabView = view;
  1206. }
  1207. /// <summary>
  1208. /// Releases the mouse grab, so mouse events will be routed to the view on which the mouse is.
  1209. /// </summary>
  1210. public static void UngrabMouse ()
  1211. {
  1212. mouseGrabView = null;
  1213. }
  1214. /// <summary>
  1215. /// Merely a debugging aid to see the raw mouse events
  1216. /// </summary>
  1217. static public Action<MouseEvent> RootMouseEvent;
  1218. static void ProcessMouseEvent (MouseEvent me)
  1219. {
  1220. RootMouseEvent?.Invoke (me);
  1221. if (mouseGrabView != null) {
  1222. var newxy = mouseGrabView.ScreenToView (me.X, me.Y);
  1223. var nme = new MouseEvent () {
  1224. X = newxy.X,
  1225. Y = newxy.Y,
  1226. Flags = me.Flags
  1227. };
  1228. mouseGrabView.MouseEvent (me);
  1229. return;
  1230. }
  1231. int rx, ry;
  1232. var view = FindDeepestView (Current, me.X, me.Y, out rx, out ry);
  1233. if (view != null) {
  1234. if (!view.WantMousePositionReports && me.Flags == MouseFlags.ReportMousePosition)
  1235. return;
  1236. var nme = new MouseEvent () {
  1237. X = rx,
  1238. Y = ry,
  1239. Flags = me.Flags
  1240. };
  1241. // Should we bubbled up the event, if it is not handled?
  1242. view.MouseEvent (nme);
  1243. }
  1244. }
  1245. static public RunState Begin (Toplevel toplevel)
  1246. {
  1247. if (toplevel == null)
  1248. throw new ArgumentNullException (nameof (toplevel));
  1249. var rs = new RunState (toplevel);
  1250. Init ();
  1251. toplevels.Push (toplevel);
  1252. Current = toplevel;
  1253. Driver.PrepareToRun (MainLoop, ProcessKeyEvent, ProcessMouseEvent);
  1254. toplevel.LayoutSubviews ();
  1255. toplevel.FocusFirst ();
  1256. Redraw (toplevel);
  1257. toplevel.PositionCursor ();
  1258. Driver.Refresh ();
  1259. return rs;
  1260. }
  1261. static public void End (RunState rs)
  1262. {
  1263. if (rs == null)
  1264. throw new ArgumentNullException (nameof (rs));
  1265. rs.Dispose ();
  1266. }
  1267. static void Shutdown ()
  1268. {
  1269. Driver.End ();
  1270. }
  1271. static void Redraw (View view)
  1272. {
  1273. view.Redraw (view.Bounds);
  1274. Driver.Refresh ();
  1275. }
  1276. static void Refresh (View view)
  1277. {
  1278. view.Redraw (view.Bounds);
  1279. Driver.Refresh ();
  1280. }
  1281. /// <summary>
  1282. /// Triggers a refresh of the entire display.
  1283. /// </summary>
  1284. public static void Refresh ()
  1285. {
  1286. Driver.RedrawTop ();
  1287. View last = null;
  1288. foreach (var v in toplevels.Reverse ()) {
  1289. v.SetNeedsDisplay ();
  1290. v.Redraw (v.Bounds);
  1291. last = v;
  1292. }
  1293. last?.PositionCursor ();
  1294. Driver.Refresh ();
  1295. }
  1296. internal static void End (View view)
  1297. {
  1298. if (toplevels.Peek () != view)
  1299. throw new ArgumentException ("The view that you end with must be balanced");
  1300. toplevels.Pop ();
  1301. if (toplevels.Count == 0)
  1302. Shutdown ();
  1303. else {
  1304. Current = toplevels.Peek () as Toplevel;
  1305. Refresh ();
  1306. }
  1307. }
  1308. /// <summary>
  1309. /// Runs the main loop for the created dialog
  1310. /// </summary>
  1311. /// <remarks>
  1312. /// Use the wait parameter to control whether this is a
  1313. /// blocking or non-blocking call.
  1314. /// </remarks>
  1315. public static void RunLoop (RunState state, bool wait = true)
  1316. {
  1317. if (state == null)
  1318. throw new ArgumentNullException (nameof (state));
  1319. if (state.Toplevel == null)
  1320. throw new ObjectDisposedException ("state");
  1321. for (state.Toplevel.Running = true; state.Toplevel.Running;) {
  1322. if (MainLoop.EventsPending (wait)) {
  1323. MainLoop.MainIteration ();
  1324. if (Iteration != null)
  1325. Iteration (null, EventArgs.Empty);
  1326. } else if (wait == false)
  1327. return;
  1328. if (!state.Toplevel.NeedDisplay.IsEmpty || state.Toplevel.childNeedsDisplay) {
  1329. state.Toplevel.Redraw (state.Toplevel.Bounds);
  1330. if (DebugDrawBounds)
  1331. DrawBounds (state.Toplevel);
  1332. state.Toplevel.PositionCursor ();
  1333. Driver.Refresh ();
  1334. }
  1335. }
  1336. }
  1337. internal static bool DebugDrawBounds;
  1338. // Need to look into why this does not work properly.
  1339. static void DrawBounds (View v)
  1340. {
  1341. v.DrawFrame (v.Frame, padding: 0, fill: false);
  1342. if (v.Subviews != null && v.Subviews.Count > 0)
  1343. foreach (var sub in v.Subviews)
  1344. DrawBounds (sub);
  1345. }
  1346. /// <summary>
  1347. /// Runs the application with the built-in toplevel view
  1348. /// </summary>
  1349. public static void Run ()
  1350. {
  1351. Run (Top);
  1352. }
  1353. /// <summary>
  1354. /// Runs the main loop on the given container.
  1355. /// </summary>
  1356. /// <remarks>
  1357. /// <para>
  1358. /// This method is used to start processing events
  1359. /// for the main application, but it is also used to
  1360. /// run modal dialog boxes.
  1361. /// </para>
  1362. /// <para>
  1363. /// To make a toplevel stop execution, set the "Running"
  1364. /// property to false.
  1365. /// </para>
  1366. /// </remarks>
  1367. public static void Run (Toplevel view)
  1368. {
  1369. var runToken = Begin (view);
  1370. RunLoop (runToken);
  1371. End (runToken);
  1372. }
  1373. /// <summary>
  1374. /// Stops running the most recent toplevel
  1375. /// </summary>
  1376. public static void RequestStop ()
  1377. {
  1378. var ct = Current as Toplevel;
  1379. Current.Running = false;
  1380. }
  1381. static void TerminalResized ()
  1382. {
  1383. foreach (var t in toplevels) {
  1384. t.Frame = new Rect (0, 0, Driver.Cols, Driver.Rows);
  1385. }
  1386. }
  1387. }
  1388. }