Core.cs 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619
  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 static 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. 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. {
  1360. Current = toplevels.Peek();
  1361. Refresh ();
  1362. }
  1363. }
  1364. /// <summary>
  1365. /// Building block API: Runs the main loop for the created dialog
  1366. /// </summary>
  1367. /// <remarks>
  1368. /// Use the wait parameter to control whether this is a
  1369. /// blocking or non-blocking call.
  1370. /// </remarks>
  1371. /// <param name="state">The state returned by the Begin method.</param>
  1372. /// <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>
  1373. public static void RunLoop (RunState state, bool wait = true)
  1374. {
  1375. if (state == null)
  1376. throw new ArgumentNullException (nameof (state));
  1377. if (state.Toplevel == null)
  1378. throw new ObjectDisposedException ("state");
  1379. for (state.Toplevel.Running = true; state.Toplevel.Running;) {
  1380. if (MainLoop.EventsPending (wait)) {
  1381. MainLoop.MainIteration ();
  1382. if (Iteration != null)
  1383. Iteration (null, EventArgs.Empty);
  1384. } else if (wait == false)
  1385. return;
  1386. if (!state.Toplevel.NeedDisplay.IsEmpty || state.Toplevel.childNeedsDisplay) {
  1387. state.Toplevel.Redraw (state.Toplevel.Bounds);
  1388. if (DebugDrawBounds)
  1389. DrawBounds (state.Toplevel);
  1390. state.Toplevel.PositionCursor ();
  1391. Driver.Refresh ();
  1392. } else
  1393. Driver.UpdateCursor ();
  1394. }
  1395. }
  1396. internal static bool DebugDrawBounds;
  1397. // Need to look into why this does not work properly.
  1398. static void DrawBounds (View v)
  1399. {
  1400. v.DrawFrame (v.Frame, padding: 0, fill: false);
  1401. if (v.Subviews != null && v.Subviews.Count > 0)
  1402. foreach (var sub in v.Subviews)
  1403. DrawBounds (sub);
  1404. }
  1405. /// <summary>
  1406. /// Runs the application with the built-in toplevel view
  1407. /// </summary>
  1408. public static void Run ()
  1409. {
  1410. Run (Top);
  1411. }
  1412. /// <summary>
  1413. /// Runs the main loop on the given container.
  1414. /// </summary>
  1415. /// <remarks>
  1416. /// <para>
  1417. /// This method is used to start processing events
  1418. /// for the main application, but it is also used to
  1419. /// run modal dialog boxes.
  1420. /// </para>
  1421. /// <para>
  1422. /// To make a toplevel stop execution, set the "Running"
  1423. /// property to false.
  1424. /// </para>
  1425. /// <para>
  1426. /// This is equivalent to calling Begin on the toplevel view, followed by RunLoop with the
  1427. /// returned value, and then calling end on the return value.
  1428. /// </para>
  1429. /// <para>
  1430. /// Alternatively, if your program needs to control the main loop and needs to
  1431. /// process events manually, you can invoke Begin to set things up manually and then
  1432. /// repeatedly call RunLoop with the wait parameter set to false. By doing this
  1433. /// the RunLoop method will only process any pending events, timers, idle handlers and
  1434. /// then return control immediately.
  1435. /// </para>
  1436. /// </remarks>
  1437. public static void Run (Toplevel view)
  1438. {
  1439. var runToken = Begin (view);
  1440. RunLoop (runToken);
  1441. End (runToken);
  1442. }
  1443. /// <summary>
  1444. /// Stops running the most recent toplevel
  1445. /// </summary>
  1446. public static void RequestStop ()
  1447. {
  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. }