Core.cs 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545
  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. case Key.CursorRight:
  847. case Key.CursorDown:
  848. var old = Focused;
  849. if (!FocusNext ())
  850. FocusNext ();
  851. if (old != Focused) {
  852. old?.SetNeedsDisplay ();
  853. Focused?.SetNeedsDisplay ();
  854. }
  855. return true;
  856. case Key.CursorLeft:
  857. case Key.CursorUp:
  858. case Key.BackTab:
  859. old = Focused;
  860. if (!FocusPrev ())
  861. FocusPrev ();
  862. if (old != Focused) {
  863. old?.SetNeedsDisplay ();
  864. Focused?.SetNeedsDisplay ();
  865. }
  866. return true;
  867. case Key.ControlL:
  868. Application.Refresh ();
  869. return true;
  870. }
  871. return false;
  872. }
  873. }
  874. /// <summary>
  875. /// A toplevel view that draws a frame around its region and has a "ContentView" subview where the contents are added.
  876. /// </summary>
  877. public class Window : Toplevel, IEnumerable {
  878. View contentView;
  879. ustring title;
  880. /// <summary>
  881. /// The title to be displayed for this window.
  882. /// </summary>
  883. /// <value>The title.</value>
  884. public ustring Title {
  885. get => title;
  886. set {
  887. title = value;
  888. SetNeedsDisplay ();
  889. }
  890. }
  891. class ContentView : View {
  892. public ContentView (Rect frame) : base (frame) { }
  893. }
  894. /// <summary>
  895. /// Initializes a new instance of the <see cref="T:Terminal.Gui.Gui.Window"/> class with an optioanl title
  896. /// </summary>
  897. /// <param name="frame">Frame.</param>
  898. /// <param name="title">Title.</param>
  899. public Window (Rect frame, ustring title = null) : this (frame, title, padding: 0)
  900. {
  901. }
  902. int padding;
  903. /// <summary>
  904. /// Initializes a new instance of the <see cref="T:Terminal.Gui.Window"/> with
  905. /// the specified frame for its location, with the specified border
  906. /// an optional title.
  907. /// </summary>
  908. /// <param name="frame">Frame.</param>
  909. /// <param name="padding">Number of characters to use for padding of the drawn frame.</param>
  910. /// <param name="title">Title.</param>
  911. public Window (Rect frame, ustring title = null, int padding = 0) : base (frame)
  912. {
  913. this.Title = title;
  914. int wb = 2 * (1 + padding);
  915. this.padding = padding;
  916. var cFrame = new Rect (1 + padding, 1 + padding, frame.Width - wb, frame.Height - wb);
  917. contentView = new ContentView (cFrame);
  918. base.Add (contentView);
  919. }
  920. /// <summary>
  921. /// Enumerates the various views in the ContentView.
  922. /// </summary>
  923. /// <returns>The enumerator.</returns>
  924. public new IEnumerator GetEnumerator ()
  925. {
  926. return contentView.GetEnumerator ();
  927. }
  928. void DrawFrame ()
  929. {
  930. DrawFrame (new Rect (0, 0, Frame.Width, Frame.Height), padding, fill: true);
  931. }
  932. /// <summary>
  933. /// Add the specified view to the ContentView.
  934. /// </summary>
  935. /// <param name="view">View to add to the window.</param>
  936. public override void Add (View view)
  937. {
  938. contentView.Add (view);
  939. if (view.CanFocus)
  940. CanFocus = true;
  941. }
  942. /// <summary>
  943. /// Removes a widget from this container.
  944. /// </summary>
  945. /// <remarks>
  946. /// </remarks>
  947. public virtual void Remove (View view)
  948. {
  949. if (view == null)
  950. return;
  951. SetNeedsDisplay ();
  952. var touched = view.Frame;
  953. contentView.Remove (view);
  954. if (contentView.Subviews.Count < 1)
  955. this.CanFocus = false;
  956. }
  957. public override void Redraw (Rect bounds)
  958. {
  959. if (!NeedDisplay.IsEmpty) {
  960. Driver.SetAttribute (ColorScheme.Normal);
  961. DrawFrame ();
  962. if (HasFocus)
  963. Driver.SetAttribute (ColorScheme.Normal);
  964. var width = Frame.Width;
  965. if (Title != null && width > 4) {
  966. Move (1+padding, padding);
  967. Driver.AddRune (' ');
  968. var str = Title.Length > width ? Title [0, width-4] : Title;
  969. Driver.AddStr (str);
  970. Driver.AddRune (' ');
  971. }
  972. Driver.SetAttribute (ColorScheme.Normal);
  973. }
  974. contentView.Redraw (contentView.Bounds);
  975. ClearNeedsDisplay ();
  976. }
  977. #if false
  978. //
  979. // It does not look like the event is raised on clicked-drag
  980. // need to figure that out.
  981. //
  982. Point? dragPosition;
  983. public override bool MouseEvent(MouseEvent me)
  984. {
  985. if (me.Flags == MouseFlags.Button1Pressed){
  986. if (dragPosition.HasValue) {
  987. var dx = me.X - dragPosition.Value.X;
  988. var dy = me.Y - dragPosition.Value.Y;
  989. var nx = Frame.X + dx;
  990. var ny = Frame.Y + dy;
  991. if (nx < 0)
  992. nx = 0;
  993. if (ny < 0)
  994. ny = 0;
  995. Demo.ml2.Text = $"{dx},{dy}";
  996. dragPosition = new Point (me.X, me.Y);
  997. // TODO: optimize, only SetNeedsDisplay on the before/after regions.
  998. if (SuperView == null)
  999. Application.Refresh ();
  1000. else
  1001. SuperView.SetNeedsDisplay ();
  1002. Frame = new Rect (nx, ny, Frame.Width, Frame.Height);
  1003. SetNeedsDisplay ();
  1004. return true;
  1005. } else {
  1006. dragPosition = new Point (me.X, me.Y);
  1007. Application.GrabMouse (this);
  1008. Demo.ml2.Text = $"Starting at {dragPosition}";
  1009. return true;
  1010. }
  1011. }
  1012. if (me.Flags == MouseFlags.Button1Released) {
  1013. Application.UngrabMouse ();
  1014. dragPosition = null;
  1015. //Driver.StopReportingMouseMoves ();
  1016. }
  1017. Demo.ml.Text = me.ToString ();
  1018. return false;
  1019. }
  1020. #endif
  1021. }
  1022. /// <summary>
  1023. /// The application driver for gui.cs
  1024. /// </summary>
  1025. /// <remarks>
  1026. /// <para>
  1027. /// You can hook up to the Iteration event to have your method
  1028. /// invoked on each iteration of the mainloop.
  1029. /// </para>
  1030. /// <para>
  1031. /// Creates a mainloop to process input events, handle timers and
  1032. /// other sources of data. It is accessible via the MainLoop property.
  1033. /// </para>
  1034. /// <para>
  1035. /// When invoked sets the SynchronizationContext to one that is tied
  1036. /// to the mainloop, allowing user code to use async/await.
  1037. /// </para>
  1038. /// </remarks>
  1039. public class Application {
  1040. /// <summary>
  1041. /// The current Console Driver in use.
  1042. /// </summary>
  1043. public static ConsoleDriver Driver = new CursesDriver ();
  1044. /// <summary>
  1045. /// The Toplevel object used for the application on startup.
  1046. /// </summary>
  1047. /// <value>The top.</value>
  1048. public static Toplevel Top { get; private set; }
  1049. /// <summary>
  1050. /// The current toplevel object. This is updated when Application.Run enters and leaves and points to the current toplevel.
  1051. /// </summary>
  1052. /// <value>The current.</value>
  1053. public static Toplevel Current { get; private set; }
  1054. /// <summary>
  1055. /// The mainloop driver for the applicaiton
  1056. /// </summary>
  1057. /// <value>The main loop.</value>
  1058. public static Mono.Terminal.MainLoop MainLoop { get; private set; }
  1059. static Stack<Toplevel> toplevels = new Stack<Toplevel> ();
  1060. /// <summary>
  1061. /// This event is raised on each iteration of the
  1062. /// main loop.
  1063. /// </summary>
  1064. /// <remarks>
  1065. /// See also <see cref="Timeout"/>
  1066. /// </remarks>
  1067. static public event EventHandler Iteration;
  1068. /// <summary>
  1069. /// Returns a rectangle that is centered in the screen for the provided size.
  1070. /// </summary>
  1071. /// <returns>The centered rect.</returns>
  1072. /// <param name="size">Size for the rectangle.</param>
  1073. public static Rect MakeCenteredRect (Size size)
  1074. {
  1075. return new Rect (new Point ((Driver.Cols - size.Width) / 2, (Driver.Rows - size.Height) / 2), size);
  1076. }
  1077. //
  1078. // provides the sync context set while executing code in gui.cs, to let
  1079. // users use async/await on their code
  1080. //
  1081. class MainLoopSyncContext : SynchronizationContext {
  1082. Mono.Terminal.MainLoop mainLoop;
  1083. public MainLoopSyncContext (Mono.Terminal.MainLoop mainLoop)
  1084. {
  1085. this.mainLoop = mainLoop;
  1086. }
  1087. public override SynchronizationContext CreateCopy ()
  1088. {
  1089. return new MainLoopSyncContext (MainLoop);
  1090. }
  1091. public override void Post (SendOrPostCallback d, object state)
  1092. {
  1093. mainLoop.AddIdle (() => {
  1094. d (state);
  1095. return false;
  1096. });
  1097. }
  1098. public override void Send (SendOrPostCallback d, object state)
  1099. {
  1100. mainLoop.Invoke (() => {
  1101. d (state);
  1102. });
  1103. }
  1104. }
  1105. /// <summary>
  1106. /// Initializes the Application
  1107. /// </summary>
  1108. public static void Init ()
  1109. {
  1110. if (Top != null)
  1111. return;
  1112. Driver.Init (TerminalResized);
  1113. MainLoop = new Mono.Terminal.MainLoop ();
  1114. SynchronizationContext.SetSynchronizationContext (new MainLoopSyncContext (MainLoop));
  1115. Top = Toplevel.Create ();
  1116. Current = Top;
  1117. }
  1118. /// <summary>
  1119. /// Captures the execution state for the provided TopLevel view.
  1120. /// </summary>
  1121. public class RunState : IDisposable {
  1122. internal RunState (Toplevel view)
  1123. {
  1124. Toplevel = view;
  1125. }
  1126. internal Toplevel Toplevel;
  1127. /// <summary>
  1128. /// Releases all resource used by the <see cref="T:Terminal.Gui.Application.RunState"/> object.
  1129. /// </summary>
  1130. /// <remarks>Call <see cref="Dispose"/> when you are finished using the <see cref="T:Terminal.Gui.Application.RunState"/>. The
  1131. /// <see cref="Dispose"/> method leaves the <see cref="T:Terminal.Gui.Application.RunState"/> in an unusable state. After
  1132. /// calling <see cref="Dispose"/>, you must release all references to the
  1133. /// <see cref="T:Terminal.Gui.Application.RunState"/> so the garbage collector can reclaim the memory that the
  1134. /// <see cref="T:Terminal.Gui.Application.RunState"/> was occupying.</remarks>
  1135. public void Dispose ()
  1136. {
  1137. Dispose (true);
  1138. GC.SuppressFinalize (this);
  1139. }
  1140. /// <summary>
  1141. /// Dispose the specified disposing.
  1142. /// </summary>
  1143. /// <returns>The dispose.</returns>
  1144. /// <param name="disposing">If set to <c>true</c> disposing.</param>
  1145. public virtual void Dispose (bool disposing)
  1146. {
  1147. if (Toplevel != null) {
  1148. Application.End (Toplevel);
  1149. Toplevel = null;
  1150. }
  1151. }
  1152. }
  1153. static void ProcessKeyEvent (KeyEvent ke)
  1154. {
  1155. if (Current.ProcessHotKey (ke))
  1156. return;
  1157. if (Current.ProcessKey (ke))
  1158. return;
  1159. // Process the key normally
  1160. if (Current.ProcessColdKey (ke))
  1161. return;
  1162. }
  1163. static View FindDeepestView (View start, int x, int y, out int resx, out int resy)
  1164. {
  1165. var startFrame = start.Frame;
  1166. if (!startFrame.Contains (x, y)) {
  1167. resx = 0;
  1168. resy = 0;
  1169. return null;
  1170. }
  1171. if (start.Subviews != null){
  1172. int count = start.Subviews.Count;
  1173. if (count > 0) {
  1174. var rx = x - startFrame.X;
  1175. var ry = y - startFrame.Y;
  1176. for (int i = count - 1; i >= 0; i--) {
  1177. View v = start.Subviews [i];
  1178. if (v.Frame.Contains (rx, ry)) {
  1179. var deep = FindDeepestView (v, rx, ry, out resx, out resy);
  1180. if (deep == null)
  1181. return v;
  1182. return deep;
  1183. }
  1184. }
  1185. }
  1186. }
  1187. resx = x-startFrame.X;
  1188. resy = y-startFrame.Y;
  1189. return start;
  1190. }
  1191. static View mouseGrabView;
  1192. /// <summary>
  1193. /// Grabs the mouse, forcing all mouse events to be routed to the specified view until UngrabMouse is called.
  1194. /// </summary>
  1195. /// <returns>The grab.</returns>
  1196. /// <param name="view">View that will receive all mouse events until UngrabMouse is invoked.</param>
  1197. public static void GrabMouse (View view)
  1198. {
  1199. if (view == null)
  1200. return;
  1201. mouseGrabView = view;
  1202. }
  1203. /// <summary>
  1204. /// Releases the mouse grab, so mouse events will be routed to the view on which the mouse is.
  1205. /// </summary>
  1206. public static void UngrabMouse ()
  1207. {
  1208. mouseGrabView = null;
  1209. }
  1210. /// <summary>
  1211. /// Merely a debugging aid to see the raw mouse events
  1212. /// </summary>
  1213. static public Action<MouseEvent> RootMouseEvent;
  1214. static void ProcessMouseEvent (MouseEvent me)
  1215. {
  1216. RootMouseEvent?.Invoke (me);
  1217. if (mouseGrabView != null) {
  1218. var newxy = mouseGrabView.ScreenToView (me.X, me.Y);
  1219. var nme = new MouseEvent () {
  1220. X = newxy.X,
  1221. Y = newxy.Y,
  1222. Flags = me.Flags
  1223. };
  1224. mouseGrabView.MouseEvent (me);
  1225. return;
  1226. }
  1227. int rx, ry;
  1228. var view = FindDeepestView (Current, me.X, me.Y, out rx, out ry);
  1229. if (view != null) {
  1230. if (!view.WantMousePositionReports && me.Flags == MouseFlags.ReportMousePosition)
  1231. return;
  1232. var nme = new MouseEvent () {
  1233. X = rx,
  1234. Y = ry,
  1235. Flags = me.Flags
  1236. };
  1237. // Should we bubbled up the event, if it is not handled?
  1238. view.MouseEvent (nme);
  1239. }
  1240. }
  1241. static public RunState Begin (Toplevel toplevel)
  1242. {
  1243. if (toplevel == null)
  1244. throw new ArgumentNullException (nameof (toplevel));
  1245. var rs = new RunState (toplevel);
  1246. Init ();
  1247. toplevels.Push (toplevel);
  1248. Current = toplevel;
  1249. Driver.PrepareToRun (MainLoop, ProcessKeyEvent, ProcessMouseEvent);
  1250. toplevel.LayoutSubviews ();
  1251. toplevel.FocusFirst ();
  1252. Redraw (toplevel);
  1253. toplevel.PositionCursor ();
  1254. Driver.Refresh ();
  1255. return rs;
  1256. }
  1257. static public void End (RunState rs)
  1258. {
  1259. if (rs == null)
  1260. throw new ArgumentNullException (nameof (rs));
  1261. rs.Dispose ();
  1262. }
  1263. static void Shutdown ()
  1264. {
  1265. Driver.End ();
  1266. }
  1267. static void Redraw (View view)
  1268. {
  1269. view.Redraw (view.Bounds);
  1270. Driver.Refresh ();
  1271. }
  1272. static void Refresh (View view)
  1273. {
  1274. view.Redraw (view.Bounds);
  1275. Driver.Refresh ();
  1276. }
  1277. /// <summary>
  1278. /// Triggers a refresh of the entire display.
  1279. /// </summary>
  1280. public static void Refresh ()
  1281. {
  1282. Driver.RedrawTop ();
  1283. View last = null;
  1284. foreach (var v in toplevels.Reverse ()) {
  1285. v.SetNeedsDisplay ();
  1286. v.Redraw (v.Bounds);
  1287. last = v;
  1288. }
  1289. last?.PositionCursor ();
  1290. Driver.Refresh ();
  1291. }
  1292. internal static void End (View view)
  1293. {
  1294. if (toplevels.Peek () != view)
  1295. throw new ArgumentException ("The view that you end with must be balanced");
  1296. toplevels.Pop ();
  1297. if (toplevels.Count == 0)
  1298. Shutdown ();
  1299. else {
  1300. Current = toplevels.Peek () as Toplevel;
  1301. Refresh ();
  1302. }
  1303. }
  1304. /// <summary>
  1305. /// Runs the main loop for the created dialog
  1306. /// </summary>
  1307. /// <remarks>
  1308. /// Use the wait parameter to control whether this is a
  1309. /// blocking or non-blocking call.
  1310. /// </remarks>
  1311. public static void RunLoop (RunState state, bool wait = true)
  1312. {
  1313. if (state == null)
  1314. throw new ArgumentNullException (nameof (state));
  1315. if (state.Toplevel == null)
  1316. throw new ObjectDisposedException ("state");
  1317. for (state.Toplevel.Running = true; state.Toplevel.Running;) {
  1318. if (MainLoop.EventsPending (wait)) {
  1319. MainLoop.MainIteration ();
  1320. if (Iteration != null)
  1321. Iteration (null, EventArgs.Empty);
  1322. } else if (wait == false)
  1323. return;
  1324. if (!state.Toplevel.NeedDisplay.IsEmpty || state.Toplevel.childNeedsDisplay) {
  1325. state.Toplevel.Redraw (state.Toplevel.Bounds);
  1326. if (DebugDrawBounds)
  1327. DrawBounds (state.Toplevel);
  1328. state.Toplevel.PositionCursor ();
  1329. Driver.Refresh ();
  1330. }
  1331. }
  1332. }
  1333. internal static bool DebugDrawBounds;
  1334. // Need to look into why this does not work properly.
  1335. static void DrawBounds (View v)
  1336. {
  1337. v.DrawFrame (v.Frame, padding: 0, fill: false);
  1338. if (v.Subviews != null && v.Subviews.Count > 0)
  1339. foreach (var sub in v.Subviews)
  1340. DrawBounds (sub);
  1341. }
  1342. /// <summary>
  1343. /// Runs the application with the built-in toplevel view
  1344. /// </summary>
  1345. public static void Run ()
  1346. {
  1347. Run (Top);
  1348. }
  1349. /// <summary>
  1350. /// Runs the main loop on the given container.
  1351. /// </summary>
  1352. /// <remarks>
  1353. /// <para>
  1354. /// This method is used to start processing events
  1355. /// for the main application, but it is also used to
  1356. /// run modal dialog boxes.
  1357. /// </para>
  1358. /// <para>
  1359. /// To make a toplevel stop execution, set the "Running"
  1360. /// property to false.
  1361. /// </para>
  1362. /// </remarks>
  1363. public static void Run (Toplevel view)
  1364. {
  1365. var runToken = Begin (view);
  1366. RunLoop (runToken);
  1367. End (runToken);
  1368. }
  1369. /// <summary>
  1370. /// Stops running the most recent toplevel
  1371. /// </summary>
  1372. public static void RequestStop ()
  1373. {
  1374. var ct = Current as Toplevel;
  1375. Current.Running = false;
  1376. }
  1377. static void TerminalResized ()
  1378. {
  1379. foreach (var t in toplevels) {
  1380. t.Frame = new Rect (0, 0, Driver.Cols, Driver.Rows);
  1381. }
  1382. }
  1383. }
  1384. }