Core.cs 45 KB

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