Core.cs 42 KB

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