Core.cs 43 KB

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