Core.cs 41 KB

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