Core.cs 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099
  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. /// <summary>
  23. /// Responder base class implemented by objects that want to participate on keyboard and mouse input.
  24. /// </summary>
  25. public class Responder {
  26. /// <summary>
  27. /// Gets or sets a value indicating whether this <see cref="T:Terminal.Gui.Responder"/> can focus.
  28. /// </summary>
  29. /// <value><c>true</c> if can focus; otherwise, <c>false</c>.</value>
  30. public virtual bool CanFocus { get; set; }
  31. /// <summary>
  32. /// Gets or sets a value indicating whether this <see cref="T:Terminal.Gui.Responder"/> has focus.
  33. /// </summary>
  34. /// <value><c>true</c> if has focus; otherwise, <c>false</c>.</value>
  35. public virtual bool HasFocus { get; internal set; }
  36. // Key handling
  37. /// <summary>
  38. /// This method can be overwritten by view that
  39. /// want to provide accelerator functionality
  40. /// (Alt-key for example).
  41. /// </summary>
  42. /// <remarks>
  43. /// <para>
  44. /// Before keys are sent to the subview on the
  45. /// current view, all the views are
  46. /// processed and the key is passed to the widgets
  47. /// to allow some of them to process the keystroke
  48. /// as a hot-key. </para>
  49. /// <para>
  50. /// For example, if you implement a button that
  51. /// has a hotkey ok "o", you would catch the
  52. /// combination Alt-o here. If the event is
  53. /// caught, you must return true to stop the
  54. /// keystroke from being dispatched to other
  55. /// views.
  56. /// </para>
  57. /// </remarks>
  58. public virtual bool ProcessHotKey (KeyEvent kb)
  59. {
  60. return false;
  61. }
  62. /// <summary>
  63. /// If the view is focused, gives the view a
  64. /// chance to process the keystroke.
  65. /// </summary>
  66. /// <remarks>
  67. /// <para>
  68. /// Views can override this method if they are
  69. /// interested in processing the given keystroke.
  70. /// If they consume the keystroke, they must
  71. /// return true to stop the keystroke from being
  72. /// processed by other widgets or consumed by the
  73. /// widget engine. If they return false, the
  74. /// keystroke will be passed using the ProcessColdKey
  75. /// method to other views to process.
  76. /// </para>
  77. /// <para>
  78. /// The View implementation does nothing but return false,
  79. /// so it is not necessary to call base.ProcessKey if you
  80. /// derive directly from View, but you should if you derive
  81. /// other View subclasses.
  82. /// </para>
  83. /// </remarks>
  84. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  85. public virtual bool ProcessKey (KeyEvent keyEvent)
  86. {
  87. return false;
  88. }
  89. /// <summary>
  90. /// This method can be overwritten by views that
  91. /// want to provide accelerator functionality
  92. /// (Alt-key for example), but without
  93. /// interefering with normal ProcessKey behavior.
  94. /// </summary>
  95. /// <remarks>
  96. /// <para>
  97. /// After keys are sent to the subviews on the
  98. /// current view, all the view are
  99. /// processed and the key is passed to the views
  100. /// to allow some of them to process the keystroke
  101. /// as a cold-key. </para>
  102. /// <para>
  103. /// This functionality is used, for example, by
  104. /// default buttons to act on the enter key.
  105. /// Processing this as a hot-key would prevent
  106. /// non-default buttons from consuming the enter
  107. /// keypress when they have the focus.
  108. /// </para>
  109. /// </remarks>
  110. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  111. public virtual bool ProcessColdKey (KeyEvent keyEvent)
  112. {
  113. return false;
  114. }
  115. /// <summary>
  116. /// Method invoked when a mouse event is generated
  117. /// </summary>
  118. /// <returns><c>true</c>, if the event was handled, <c>false</c> otherwise.</returns>
  119. /// <param name="mouseEvent">Contains the details about the mouse event.</param>
  120. public virtual bool MouseEvent (MouseEvent mouseEvent)
  121. {
  122. return false;
  123. }
  124. }
  125. /// <summary>
  126. /// Determines the LayoutStyle for a view, if Absolute, during LayoutSubviews, the
  127. /// value from the Frame will be used, if the value is Computer, then the Frame
  128. /// will be updated from the X, Y Pos objets and the Width and Heigh Dim objects.
  129. /// </summary>
  130. public enum LayoutStyle {
  131. /// <summary>
  132. /// The position and size of the view are based on the Frame value.
  133. /// </summary>
  134. Absolute,
  135. /// <summary>
  136. /// The position and size of the view will be computed based on the
  137. /// X, Y, Width and Height properties and set on the Frame.
  138. /// </summary>
  139. Computed
  140. }
  141. /// <summary>
  142. /// 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.
  143. /// </summary>
  144. /// <remarks>
  145. /// <para>
  146. /// The View defines the base functionality for user interface elements in Terminal/gui.cs. Views
  147. /// can contain one or more subviews, can respond to user input and render themselves on the screen.
  148. /// </para>
  149. /// <para>
  150. /// Views can either be created with an absolute position, by calling the constructor that takes a
  151. /// Rect parameter to specify the absolute position and size (the Frame of the View) or by setting the
  152. /// X, Y, Width and Height properties on the view. Both approaches use coordinates that are relative
  153. /// to the container they are being added to.
  154. /// </para>
  155. /// <para>
  156. /// When you do not specify a Rect frame you can use the more flexible
  157. /// Dim and Pos objects that can dynamically update the position of a view.
  158. /// The X and Y properties are of type <see cref="T:Terminal.Gui.Pos"/>
  159. /// and you can use either absolute positions, percentages or anchor
  160. /// points. The Width and Height properties are of type
  161. /// <see cref="T:Terminal.Gui.Dim"/> and can use absolute position,
  162. /// percentages and anchors. These are useful as they will take
  163. /// care of repositioning your views if your view's frames are resized
  164. /// or if the terminal size changes.
  165. /// </para>
  166. /// <para>
  167. /// When you specify the Rect parameter to a view, you are setting the LayoutStyle to Absolute, and the
  168. /// view will always stay in the position that you placed it. To change the position change the
  169. /// Frame property to the new position.
  170. /// </para>
  171. /// <para>
  172. /// Subviews can be added to a View by calling the Add method. The container of a view is the
  173. /// Superview.
  174. /// </para>
  175. /// <para>
  176. /// Developers can call the SetNeedsDisplay method on the view to flag a region or the entire view
  177. /// as requiring to be redrawn.
  178. /// </para>
  179. /// <para>
  180. /// Views have a ColorScheme property that defines the default colors that subviews
  181. /// should use for rendering. This ensures that the views fit in the context where
  182. /// they are being used, and allows for themes to be plugged in. For example, the
  183. /// default colors for windows and toplevels uses a blue background, while it uses
  184. /// a white background for dialog boxes and a red background for errors.
  185. /// </para>
  186. /// <para>
  187. /// If a ColorScheme is not set on a view, the result of the ColorScheme is the
  188. /// value of the SuperView and the value might only be valid once a view has been
  189. /// added to a SuperView, so your subclasses should not rely on ColorScheme being
  190. /// set at construction time.
  191. /// </para>
  192. /// <para>
  193. /// Using ColorSchemes has the advantage that your application will work both
  194. /// in color as well as black and white displays.
  195. /// </para>
  196. /// <para>
  197. /// Views that are focusable should implement the PositionCursor to make sure that
  198. /// the cursor is placed in a location that makes sense. Unix terminals do not have
  199. /// a way of hiding the cursor, so it can be distracting to have the cursor left at
  200. /// the last focused view. So views should make sure that they place the cursor
  201. /// in a visually sensible place.
  202. /// </para>
  203. /// <para>
  204. /// The metnod LayoutSubviews is invoked when the size or layout of a view has
  205. /// changed. The default processing system will keep the size and dimensions
  206. /// for views that use the LayoutKind.Absolute, and will recompute the
  207. /// frames for the vies that use LayoutKind.Computed.
  208. /// </para>
  209. /// </remarks>
  210. public class View : Responder, IEnumerable {
  211. internal enum Direction {
  212. Forward,
  213. Backward
  214. }
  215. View container = null;
  216. View focused = null;
  217. Direction focusDirection;
  218. internal Direction FocusDirection {
  219. get => SuperView?.FocusDirection ?? focusDirection;
  220. set {
  221. if (SuperView != null)
  222. SuperView.FocusDirection = value;
  223. else
  224. focusDirection = value;
  225. }
  226. }
  227. /// <summary>
  228. /// Points to the current driver in use by the view, it is a convenience property
  229. /// for simplifying the development of new views.
  230. /// </summary>
  231. public static ConsoleDriver Driver = Application.Driver;
  232. static IList<View> empty = new List<View> (0).AsReadOnly ();
  233. // This is null, and allocated on demand.
  234. List<View> subviews;
  235. /// <summary>
  236. /// This returns a list of the subviews contained by this view.
  237. /// </summary>
  238. /// <value>The subviews.</value>
  239. public IList<View> Subviews => subviews == null ? empty : subviews.AsReadOnly ();
  240. // Internally, we use InternalSubviews rather than subviews, as we do not expect us
  241. // to make the same mistakes our users make when they poke at the Subviews.
  242. internal IList<View> InternalSubviews => subviews ?? empty;
  243. internal Rect NeedDisplay { get; private set; } = Rect.Empty;
  244. // The frame for the object
  245. Rect frame;
  246. /// <summary>
  247. /// Gets or sets an identifier for the view;
  248. /// </summary>
  249. /// <value>The identifier.</value>
  250. public ustring Id { get; set; } = "";
  251. /// <summary>
  252. /// Gets or sets a value indicating whether this <see cref="T:Terminal.Gui.View"/> want mouse position reports.
  253. /// </summary>
  254. /// <value><c>true</c> if want mouse position reports; otherwise, <c>false</c>.</value>
  255. public virtual bool WantMousePositionReports { get; set; } = false;
  256. /// <summary>
  257. /// Gets or sets the frame for the view.
  258. /// </summary>
  259. /// <value>The frame.</value>
  260. /// <remarks>
  261. /// Altering the Frame of a view will trigger the redrawing of the
  262. /// view as well as the redrawing of the affected regions in the superview.
  263. /// </remarks>
  264. public virtual Rect Frame {
  265. get => frame;
  266. set {
  267. if (SuperView != null) {
  268. SuperView.SetNeedsDisplay (frame);
  269. SuperView.SetNeedsDisplay (value);
  270. }
  271. frame = value;
  272. SetNeedsLayout ();
  273. SetNeedsDisplay (frame);
  274. }
  275. }
  276. /// <summary>
  277. /// Gets an enumerator that enumerates the subviews in this view.
  278. /// </summary>
  279. /// <returns>The enumerator.</returns>
  280. public IEnumerator GetEnumerator ()
  281. {
  282. foreach (var v in InternalSubviews)
  283. yield return v;
  284. }
  285. LayoutStyle layoutStyle;
  286. /// <summary>
  287. /// Controls how the view's Frame is computed during the LayoutSubviews method, if Absolute, then
  288. /// LayoutSubviews does not change the Frame properties, otherwise the Frame is updated from the
  289. /// values in X, Y, Width and Height properties.
  290. /// </summary>
  291. /// <value>The layout style.</value>
  292. public LayoutStyle LayoutStyle {
  293. get => layoutStyle;
  294. set {
  295. layoutStyle = value;
  296. SetNeedsLayout ();
  297. }
  298. }
  299. /// <summary>
  300. /// 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.
  301. /// </summary>
  302. /// <value>The bounds.</value>
  303. public Rect Bounds {
  304. get => new Rect (Point.Empty, Frame.Size);
  305. set {
  306. Frame = new Rect (frame.Location, value.Size);
  307. }
  308. }
  309. Pos x, y;
  310. /// <summary>
  311. /// Gets or sets the X position for the view (the column). This is only used when the LayoutStyle is Computed, if the
  312. /// LayoutStyle is set to Absolute, this value is ignored.
  313. /// </summary>
  314. /// <value>The X Position.</value>
  315. public Pos X {
  316. get => x;
  317. set {
  318. x = value;
  319. SetNeedsLayout ();
  320. }
  321. }
  322. /// <summary>
  323. /// Gets or sets the Y position for the view (line). This is only used when the LayoutStyle is Computed, if the
  324. /// LayoutStyle is set to Absolute, this value is ignored.
  325. /// </summary>
  326. /// <value>The y position (line).</value>
  327. public Pos Y {
  328. get => y;
  329. set {
  330. y = value;
  331. SetNeedsLayout ();
  332. }
  333. }
  334. Dim width, height;
  335. /// <summary>
  336. /// Gets or sets the width for the view. This is only used when the LayoutStyle is Computed, if the
  337. /// LayoutStyle is set to Absolute, this value is ignored.
  338. /// </summary>
  339. /// <value>The width.</value>
  340. public Dim Width {
  341. get => width;
  342. set {
  343. width = value;
  344. SetNeedsLayout ();
  345. }
  346. }
  347. /// <summary>
  348. /// Gets or sets the height for the view. This is only used when the LayoutStyle is Computed, if the
  349. /// LayoutStyle is set to Absolute, this value is ignored.
  350. /// </summary>
  351. /// <value>The height.</value>
  352. public Dim Height {
  353. get => height;
  354. set {
  355. height = value;
  356. SetNeedsLayout ();
  357. }
  358. }
  359. /// <summary>
  360. /// Returns the container for this view, or null if this view has not been added to a container.
  361. /// </summary>
  362. /// <value>The super view.</value>
  363. public View SuperView => container;
  364. /// <summary>
  365. /// Initializes a new instance of the <see cref="T:Terminal.Gui.View"/> class with the absolute
  366. /// dimensions specified in the frame. If you want to have Views that can be positioned with
  367. /// Pos and Dim properties on X, Y, Width and Height, use the empty constructor.
  368. /// </summary>
  369. /// <param name="frame">The region covered by this view.</param>
  370. public View (Rect frame)
  371. {
  372. this.Frame = frame;
  373. CanFocus = false;
  374. LayoutStyle = LayoutStyle.Absolute;
  375. }
  376. /// <summary>
  377. /// Initializes a new instance of the <see cref="T:Terminal.Gui.View"/> class and sets the
  378. /// view up for Computed layout, which will use the values in X, Y, Width and Height to
  379. /// compute the View's Frame.
  380. /// </summary>
  381. public View ()
  382. {
  383. CanFocus = false;
  384. LayoutStyle = LayoutStyle.Computed;
  385. }
  386. /// <summary>
  387. /// Invoke to flag that this view needs to be redisplayed, by any code
  388. /// that alters the state of the view.
  389. /// </summary>
  390. public void SetNeedsDisplay ()
  391. {
  392. SetNeedsDisplay (Bounds);
  393. }
  394. bool layoutNeeded = true;
  395. internal void SetNeedsLayout ()
  396. {
  397. if (layoutNeeded)
  398. return;
  399. layoutNeeded = true;
  400. if (SuperView == null)
  401. return;
  402. SuperView.layoutNeeded = true;
  403. }
  404. /// <summary>
  405. /// Flags the specified rectangle region on this view as needing to be repainted.
  406. /// </summary>
  407. /// <param name="region">The region that must be flagged for repaint.</param>
  408. public void SetNeedsDisplay (Rect region)
  409. {
  410. if (NeedDisplay.IsEmpty)
  411. NeedDisplay = region;
  412. else {
  413. var x = Math.Min (NeedDisplay.X, region.X);
  414. var y = Math.Min (NeedDisplay.Y, region.Y);
  415. var w = Math.Max (NeedDisplay.Width, region.Width);
  416. var h = Math.Max (NeedDisplay.Height, region.Height);
  417. NeedDisplay = new Rect (x, y, w, h);
  418. }
  419. if (container != null)
  420. container.ChildNeedsDisplay ();
  421. if (subviews == null)
  422. return;
  423. foreach (var view in subviews)
  424. if (view.Frame.IntersectsWith (region)) {
  425. var childRegion = Rect.Intersect (view.Frame, region);
  426. childRegion.X -= view.Frame.X;
  427. childRegion.Y -= view.Frame.Y;
  428. view.SetNeedsDisplay (childRegion);
  429. }
  430. }
  431. internal bool childNeedsDisplay;
  432. /// <summary>
  433. /// Flags this view for requiring the children views to be repainted.
  434. /// </summary>
  435. public void ChildNeedsDisplay ()
  436. {
  437. childNeedsDisplay = true;
  438. if (container != null)
  439. container.ChildNeedsDisplay ();
  440. }
  441. /// <summary>
  442. /// Adds a subview to this view.
  443. /// </summary>
  444. /// <remarks>
  445. /// </remarks>
  446. public virtual void Add (View view)
  447. {
  448. if (view == null)
  449. return;
  450. if (subviews == null)
  451. subviews = new List<View> ();
  452. subviews.Add (view);
  453. view.container = this;
  454. if (view.CanFocus)
  455. CanFocus = true;
  456. SetNeedsLayout ();
  457. SetNeedsDisplay ();
  458. }
  459. /// <summary>
  460. /// Adds the specified views to the view.
  461. /// </summary>
  462. /// <param name="views">Array of one or more views (can be optional parameter).</param>
  463. public void Add (params View [] views)
  464. {
  465. if (views == null)
  466. return;
  467. foreach (var view in views)
  468. Add (view);
  469. }
  470. /// <summary>
  471. /// Removes all the widgets from this container.
  472. /// </summary>
  473. /// <remarks>
  474. /// </remarks>
  475. public virtual void RemoveAll ()
  476. {
  477. if (subviews == null)
  478. return;
  479. while (subviews.Count > 0) {
  480. Remove (subviews[0]);
  481. }
  482. }
  483. /// <summary>
  484. /// Removes a widget from this container.
  485. /// </summary>
  486. /// <remarks>
  487. /// </remarks>
  488. public virtual void Remove (View view)
  489. {
  490. if (view == null || subviews == null)
  491. return;
  492. SetNeedsLayout ();
  493. SetNeedsDisplay ();
  494. var touched = view.Frame;
  495. subviews.Remove (view);
  496. view.container = null;
  497. if (subviews.Count < 1)
  498. this.CanFocus = false;
  499. foreach (var v in subviews) {
  500. if (v.Frame.IntersectsWith (touched))
  501. view.SetNeedsDisplay ();
  502. }
  503. }
  504. void PerformActionForSubview (View subview, Action<View> action)
  505. {
  506. if (subviews.Contains (subview)) {
  507. action (subview);
  508. }
  509. SetNeedsDisplay ();
  510. subview.SetNeedsDisplay ();
  511. }
  512. /// <summary>
  513. /// Brings the specified subview to the front so it is drawn on top of any other views.
  514. /// </summary>
  515. /// <param name="subview">The subview to send to the front</param>
  516. /// <remarks>
  517. /// <seealso cref="SendSubviewToBack"/>.
  518. /// </remarks>
  519. public void BringSubviewToFront (View subview)
  520. {
  521. PerformActionForSubview (subview, x => {
  522. subviews.Remove (x);
  523. subviews.Add (x);
  524. });
  525. }
  526. /// <summary>
  527. /// Sends the specified subview to the front so it is the first view drawn
  528. /// </summary>
  529. /// <param name="subview">The subview to send to the front</param>
  530. /// <remarks>
  531. /// <seealso cref="BringSubviewToFront(View)"/>.
  532. /// </remarks>
  533. public void SendSubviewToBack (View subview)
  534. {
  535. PerformActionForSubview (subview, x => {
  536. subviews.Remove (x);
  537. subviews.Insert (0, subview);
  538. });
  539. }
  540. /// <summary>
  541. /// Moves the subview backwards in the hierarchy, only one step
  542. /// </summary>
  543. /// <param name="subview">The subview to send backwards</param>
  544. /// <remarks>
  545. /// If you want to send the view all the way to the back use SendSubviewToBack.
  546. /// </remarks>
  547. public void SendSubviewBackwards (View subview)
  548. {
  549. PerformActionForSubview (subview, x => {
  550. var idx = subviews.IndexOf (x);
  551. if (idx > 0) {
  552. subviews.Remove (x);
  553. subviews.Insert (idx - 1, x);
  554. }
  555. });
  556. }
  557. /// <summary>
  558. /// Moves the subview backwards in the hierarchy, only one step
  559. /// </summary>
  560. /// <param name="subview">The subview to send backwards</param>
  561. /// <remarks>
  562. /// If you want to send the view all the way to the back use SendSubviewToBack.
  563. /// </remarks>
  564. public void BringSubviewForward (View subview)
  565. {
  566. PerformActionForSubview (subview, x => {
  567. var idx = subviews.IndexOf (x);
  568. if (idx+1 < subviews.Count) {
  569. subviews.Remove (x);
  570. subviews.Insert (idx+1, x);
  571. }
  572. });
  573. }
  574. /// <summary>
  575. /// Clears the view region with the current color.
  576. /// </summary>
  577. /// <remarks>
  578. /// <para>
  579. /// This clears the entire region used by this view.
  580. /// </para>
  581. /// </remarks>
  582. public void Clear ()
  583. {
  584. var h = Frame.Height;
  585. var w = Frame.Width;
  586. for (int line = 0; line < h; line++) {
  587. Move (0, line);
  588. for (int col = 0; col < w; col++)
  589. Driver.AddRune (' ');
  590. }
  591. }
  592. /// <summary>
  593. /// Clears the specfied rectangular region with the current color
  594. /// </summary>
  595. public void Clear (Rect r)
  596. {
  597. var h = r.Height;
  598. var w = r.Width;
  599. for (int line = 0; line < h; line++) {
  600. Move (0, line);
  601. for (int col = 0; col < w; col++)
  602. Driver.AddRune (' ');
  603. }
  604. }
  605. /// <summary>
  606. /// Converts the (col,row) position from the view into a screen (col,row). The values are clamped to (0..ScreenDim-1)
  607. /// </summary>
  608. /// <param name="col">View-based column.</param>
  609. /// <param name="row">View-based row.</param>
  610. /// <param name="rcol">Absolute column, display relative.</param>
  611. /// <param name="rrow">Absolute row, display relative.</param>
  612. /// <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>
  613. internal void ViewToScreen (int col, int row, out int rcol, out int rrow, bool clipped = true)
  614. {
  615. // Computes the real row, col relative to the screen.
  616. rrow = row + frame.Y;
  617. rcol = col + frame.X;
  618. var ccontainer = container;
  619. while (ccontainer != null) {
  620. rrow += ccontainer.frame.Y;
  621. rcol += ccontainer.frame.X;
  622. ccontainer = ccontainer.container;
  623. }
  624. // The following ensures that the cursor is always in the screen boundaries.
  625. if (clipped) {
  626. rrow = Math.Max (0, Math.Min (rrow, Driver.Rows - 1));
  627. rcol = Math.Max (0, Math.Min (rcol, Driver.Cols - 1));
  628. }
  629. }
  630. /// <summary>
  631. /// Converts a point from screen coordinates into the view coordinate space.
  632. /// </summary>
  633. /// <returns>The mapped point.</returns>
  634. /// <param name="x">X screen-coordinate point.</param>
  635. /// <param name="y">Y screen-coordinate point.</param>
  636. public Point ScreenToView (int x, int y)
  637. {
  638. if (SuperView == null) {
  639. return new Point (x - Frame.X, y - frame.Y);
  640. } else {
  641. var parent = SuperView.ScreenToView (x, y);
  642. return new Point (parent.X - frame.X, parent.Y - frame.Y);
  643. }
  644. }
  645. // Converts a rectangle in view coordinates to screen coordinates.
  646. Rect RectToScreen (Rect rect)
  647. {
  648. ViewToScreen (rect.X, rect.Y, out var x, out var y, clipped: false);
  649. return new Rect (x, y, rect.Width, rect.Height);
  650. }
  651. // Clips a rectangle in screen coordinates to the dimensions currently available on the screen
  652. Rect ScreenClip (Rect rect)
  653. {
  654. var x = rect.X < 0 ? 0 : rect.X;
  655. var y = rect.Y < 0 ? 0 : rect.Y;
  656. var w = rect.X + rect.Width >= Driver.Cols ? Driver.Cols - rect.X : rect.Width;
  657. var h = rect.Y + rect.Height >= Driver.Rows ? Driver.Rows - rect.Y : rect.Height;
  658. return new Rect (x, y, w, h);
  659. }
  660. /// <summary>
  661. /// Sets the Console driver's clip region to the current View's Bounds.
  662. /// </summary>
  663. /// <returns>The existing driver's Clip region, which can be then set by setting the Driver.Clip property.</returns>
  664. public Rect ClipToBounds ()
  665. {
  666. return SetClip (Bounds);
  667. }
  668. /// <summary>
  669. /// Sets the clipping region to the specified region, the region is view-relative
  670. /// </summary>
  671. /// <returns>The previous clip region.</returns>
  672. /// <param name="rect">Rectangle region to clip into, the region is view-relative.</param>
  673. public Rect SetClip (Rect rect)
  674. {
  675. var bscreen = RectToScreen (rect);
  676. var previous = Driver.Clip;
  677. Driver.Clip = ScreenClip (RectToScreen (Bounds));
  678. return previous;
  679. }
  680. /// <summary>
  681. /// Draws a frame in the current view, clipped by the boundary of this view
  682. /// </summary>
  683. /// <param name="rect">Rectangular region for the frame to be drawn.</param>
  684. /// <param name="padding">The padding to add to the drawn frame.</param>
  685. /// <param name="fill">If set to <c>true</c> it fill will the contents.</param>
  686. public void DrawFrame (Rect rect, int padding = 0, bool fill = false)
  687. {
  688. var scrRect = RectToScreen (rect);
  689. var savedClip = Driver.Clip;
  690. Driver.Clip = ScreenClip (RectToScreen (Bounds));
  691. Driver.DrawFrame (scrRect, padding, fill);
  692. Driver.Clip = savedClip;
  693. }
  694. /// <summary>
  695. /// Utility function to draw strings that contain a hotkey
  696. /// </summary>
  697. /// <param name="text">String to display, the underscoore before a letter flags the next letter as the hotkey.</param>
  698. /// <param name="hotColor">Hot color.</param>
  699. /// <param name="normalColor">Normal color.</param>
  700. public void DrawHotString (ustring text, Attribute hotColor, Attribute normalColor)
  701. {
  702. Driver.SetAttribute (normalColor);
  703. foreach (var rune in text) {
  704. if (rune == '_') {
  705. Driver.SetAttribute (hotColor);
  706. continue;
  707. }
  708. Driver.AddRune (rune);
  709. Driver.SetAttribute (normalColor);
  710. }
  711. }
  712. /// <summary>
  713. /// Utility function to draw strings that contains a hotkey using a colorscheme and the "focused" state.
  714. /// </summary>
  715. /// <param name="text">String to display, the underscoore before a letter flags the next letter as the hotkey.</param>
  716. /// <param name="focused">If set to <c>true</c> this uses the focused colors from the color scheme, otherwise the regular ones.</param>
  717. /// <param name="scheme">The color scheme to use.</param>
  718. public void DrawHotString (ustring text, bool focused, ColorScheme scheme)
  719. {
  720. if (focused)
  721. DrawHotString (text, scheme.HotFocus, scheme.Focus);
  722. else
  723. DrawHotString (text, scheme.HotNormal, scheme.Normal);
  724. }
  725. /// <summary>
  726. /// This moves the cursor to the specified column and row in the view.
  727. /// </summary>
  728. /// <returns>The move.</returns>
  729. /// <param name="col">Col.</param>
  730. /// <param name="row">Row.</param>
  731. public void Move (int col, int row)
  732. {
  733. ViewToScreen (col, row, out var rcol, out var rrow);
  734. Driver.Move (rcol, rrow);
  735. }
  736. /// <summary>
  737. /// Positions the cursor in the right position based on the currently focused view in the chain.
  738. /// </summary>
  739. public virtual void PositionCursor ()
  740. {
  741. if (focused != null)
  742. focused.PositionCursor ();
  743. else
  744. Move (frame.X, frame.Y);
  745. }
  746. /// <summary>
  747. /// Gets or sets a value indicating whether this <see cref="T:Terminal.Gui.View"/> has focus.
  748. /// </summary>
  749. /// <value><c>true</c> if has focus; otherwise, <c>false</c>.</value>
  750. public override bool HasFocus {
  751. get {
  752. return base.HasFocus;
  753. }
  754. internal set {
  755. if (base.HasFocus != value)
  756. SetNeedsDisplay ();
  757. base.HasFocus = value;
  758. // Remove focus down the chain of subviews if focus is removed
  759. if (value == false && focused != null) {
  760. focused.HasFocus = false;
  761. focused = null;
  762. }
  763. }
  764. }
  765. /// <summary>
  766. /// Returns the currently focused view inside this view, or null if nothing is focused.
  767. /// </summary>
  768. /// <value>The focused.</value>
  769. public View Focused => focused;
  770. /// <summary>
  771. /// Returns the most focused view in the chain of subviews (the leaf view that has the focus).
  772. /// </summary>
  773. /// <value>The most focused.</value>
  774. public View MostFocused {
  775. get {
  776. if (Focused == null)
  777. return null;
  778. var most = Focused.MostFocused;
  779. if (most != null)
  780. return most;
  781. return Focused;
  782. }
  783. }
  784. /// <summary>
  785. /// The color scheme for this view, if it is not defined, it returns the parent's
  786. /// color scheme.
  787. /// </summary>
  788. public ColorScheme ColorScheme {
  789. get {
  790. if (colorScheme == null)
  791. return SuperView?.ColorScheme;
  792. return colorScheme;
  793. }
  794. set {
  795. colorScheme = value;
  796. }
  797. }
  798. ColorScheme colorScheme;
  799. /// <summary>
  800. /// Displays the specified character in the specified column and row.
  801. /// </summary>
  802. /// <param name="col">Col.</param>
  803. /// <param name="row">Row.</param>
  804. /// <param name="ch">Ch.</param>
  805. public void AddRune (int col, int row, Rune ch)
  806. {
  807. if (row < 0 || col < 0)
  808. return;
  809. if (row > frame.Height - 1 || col > frame.Width - 1)
  810. return;
  811. Move (col, row);
  812. Driver.AddRune (ch);
  813. }
  814. /// <summary>
  815. /// Removes the SetNeedsDisplay and the ChildNeedsDisplay setting on this view.
  816. /// </summary>
  817. protected void ClearNeedsDisplay ()
  818. {
  819. NeedDisplay = Rect.Empty;
  820. childNeedsDisplay = false;
  821. }
  822. /// <summary>
  823. /// Performs a redraw of this view and its subviews, only redraws the views that have been flagged for a re-display.
  824. /// </summary>
  825. /// <param name="region">The region to redraw, this is relative to the view itself.</param>
  826. /// <remarks>
  827. /// <para>
  828. /// Views should set the color that they want to use on entry, as otherwise this will inherit
  829. /// the last color that was set globaly on the driver.
  830. /// </para>
  831. /// </remarks>
  832. public virtual void Redraw (Rect region)
  833. {
  834. var clipRect = new Rect (Point.Empty, frame.Size);
  835. if (subviews != null) {
  836. foreach (var view in subviews) {
  837. if (!view.NeedDisplay.IsEmpty || view.childNeedsDisplay) {
  838. if (view.Frame.IntersectsWith (clipRect) && view.Frame.IntersectsWith (region)) {
  839. // TODO: optimize this by computing the intersection of region and view.Bounds
  840. view.Redraw (view.Bounds);
  841. }
  842. view.NeedDisplay = Rect.Empty;
  843. view.childNeedsDisplay = false;
  844. }
  845. }
  846. }
  847. ClearNeedsDisplay ();
  848. }
  849. /// <summary>
  850. /// Focuses the specified sub-view.
  851. /// </summary>
  852. /// <param name="view">View.</param>
  853. public void SetFocus (View view)
  854. {
  855. if (view == null)
  856. return;
  857. //Console.WriteLine ($"Request to focus {view}");
  858. if (!view.CanFocus)
  859. return;
  860. if (focused == view)
  861. return;
  862. // Make sure that this view is a subview
  863. View c;
  864. for (c = view.container; c != null; c = c.container)
  865. if (c == this)
  866. break;
  867. if (c == null)
  868. throw new ArgumentException ("the specified view is not part of the hierarchy of this view");
  869. if (focused != null)
  870. focused.HasFocus = false;
  871. focused = view;
  872. focused.HasFocus = true;
  873. focused.EnsureFocus ();
  874. // Send focus upwards
  875. SuperView?.SetFocus(this);
  876. }
  877. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  878. public override bool ProcessKey (KeyEvent keyEvent)
  879. {
  880. if (Focused?.ProcessKey (keyEvent) == true)
  881. return true;
  882. return false;
  883. }
  884. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  885. public override bool ProcessHotKey (KeyEvent keyEvent)
  886. {
  887. if (subviews == null || subviews.Count == 0)
  888. return false;
  889. foreach (var view in subviews)
  890. if (view.ProcessHotKey (keyEvent))
  891. return true;
  892. return false;
  893. }
  894. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  895. public override bool ProcessColdKey (KeyEvent keyEvent)
  896. {
  897. if (subviews == null || subviews.Count == 0)
  898. return false;
  899. foreach (var view in subviews)
  900. if (view.ProcessColdKey (keyEvent))
  901. return true;
  902. return false;
  903. }
  904. /// <summary>
  905. /// Finds the first view in the hierarchy that wants to get the focus if nothing is currently focused, otherwise, it does nothing.
  906. /// </summary>
  907. public void EnsureFocus ()
  908. {
  909. if (focused == null)
  910. if (FocusDirection == Direction.Forward)
  911. FocusFirst ();
  912. else
  913. FocusLast ();
  914. }
  915. /// <summary>
  916. /// Focuses the first focusable subview if one exists.
  917. /// </summary>
  918. public void FocusFirst ()
  919. {
  920. if (subviews == null) {
  921. SuperView?.SetFocus (this);
  922. return;
  923. }
  924. foreach (var view in subviews) {
  925. if (view.CanFocus) {
  926. SetFocus (view);
  927. return;
  928. }
  929. }
  930. }
  931. /// <summary>
  932. /// Focuses the last focusable subview if one exists.
  933. /// </summary>
  934. public void FocusLast ()
  935. {
  936. if (subviews == null) {
  937. SuperView?.SetFocus(this);
  938. return;
  939. }
  940. for (int i = subviews.Count; i > 0;) {
  941. i--;
  942. View v = subviews [i];
  943. if (v.CanFocus) {
  944. SetFocus (v);
  945. return;
  946. }
  947. }
  948. }
  949. /// <summary>
  950. /// Focuses the previous view.
  951. /// </summary>
  952. /// <returns><c>true</c>, if previous was focused, <c>false</c> otherwise.</returns>
  953. public bool FocusPrev ()
  954. {
  955. FocusDirection = Direction.Backward;
  956. if (subviews == null || subviews.Count == 0)
  957. return false;
  958. if (focused == null) {
  959. FocusLast ();
  960. return focused != null;
  961. }
  962. int focused_idx = -1;
  963. for (int i = subviews.Count; i > 0;) {
  964. i--;
  965. View w = subviews [i];
  966. if (w.HasFocus) {
  967. if (w.FocusPrev ())
  968. return true;
  969. focused_idx = i;
  970. continue;
  971. }
  972. if (w.CanFocus && focused_idx != -1) {
  973. focused.HasFocus = false;
  974. if (w != null && w.CanFocus)
  975. w.FocusLast ();
  976. SetFocus (w);
  977. return true;
  978. }
  979. }
  980. if (focused != null) {
  981. focused.HasFocus = false;
  982. focused = null;
  983. }
  984. return false;
  985. }
  986. /// <summary>
  987. /// Focuses the next view.
  988. /// </summary>
  989. /// <returns><c>true</c>, if next was focused, <c>false</c> otherwise.</returns>
  990. public bool FocusNext ()
  991. {
  992. FocusDirection = Direction.Forward;
  993. if (subviews == null || subviews.Count == 0)
  994. return false;
  995. if (focused == null) {
  996. FocusFirst ();
  997. return focused != null;
  998. }
  999. int n = subviews.Count;
  1000. int focused_idx = -1;
  1001. for (int i = 0; i < n; i++) {
  1002. View w = subviews [i];
  1003. if (w.HasFocus) {
  1004. if (w.FocusNext ())
  1005. return true;
  1006. focused_idx = i;
  1007. continue;
  1008. }
  1009. if (w.CanFocus && focused_idx != -1) {
  1010. focused.HasFocus = false;
  1011. if (w != null && w.CanFocus)
  1012. w.FocusFirst ();
  1013. SetFocus (w);
  1014. return true;
  1015. }
  1016. }
  1017. if (focused != null) {
  1018. focused.HasFocus = false;
  1019. focused = null;
  1020. }
  1021. return false;
  1022. }
  1023. /// <summary>
  1024. /// Computes the RelativeLayout for the view, given the frame for its container.
  1025. /// </summary>
  1026. /// <param name="hostFrame">The Frame for the host.</param>
  1027. internal void RelativeLayout (Rect hostFrame)
  1028. {
  1029. int w, h, _x, _y;
  1030. if (x is Pos.PosCenter) {
  1031. if (width == null)
  1032. w = hostFrame.Width;
  1033. else
  1034. w = width.Anchor (hostFrame.Width);
  1035. _x = x.Anchor (hostFrame.Width - w);
  1036. } else {
  1037. if (x == null)
  1038. _x = 0;
  1039. else
  1040. _x = x.Anchor (hostFrame.Width);
  1041. if (width == null)
  1042. w = hostFrame.Width;
  1043. else
  1044. w = width.Anchor (hostFrame.Width - _x);
  1045. }
  1046. if (y is Pos.PosCenter) {
  1047. if (height == null)
  1048. h = hostFrame.Height;
  1049. else
  1050. h = height.Anchor (hostFrame.Height);
  1051. _y = y.Anchor (hostFrame.Height - h);
  1052. } else {
  1053. if (y == null)
  1054. _y = 0;
  1055. else
  1056. _y = y.Anchor (hostFrame.Height);
  1057. if (height == null)
  1058. h = hostFrame.Height;
  1059. else
  1060. h = height.Anchor (hostFrame.Height - _y);
  1061. }
  1062. Frame = new Rect (_x, _y, w, h);
  1063. }
  1064. // https://en.wikipedia.org/wiki/Topological_sorting
  1065. static List<View> TopologicalSort (HashSet<View> nodes, HashSet<(View, View)> edges)
  1066. {
  1067. var result = new List<View> ();
  1068. // Set of all nodes with no incoming edges
  1069. var S = new HashSet<View> (nodes.Where (n => edges.All (e => e.Item2.Equals (n) == false)));
  1070. while (S.Any ()) {
  1071. // remove a node n from S
  1072. var n = S.First ();
  1073. S.Remove (n);
  1074. // add n to tail of L
  1075. result.Add (n);
  1076. // for each node m with an edge e from n to m do
  1077. foreach (var e in edges.Where (e => e.Item1.Equals (n)).ToList ()) {
  1078. var m = e.Item2;
  1079. // remove edge e from the graph
  1080. edges.Remove (e);
  1081. // if m has no other incoming edges then
  1082. if (edges.All (me => me.Item2.Equals (m) == false)) {
  1083. // insert m into S
  1084. S.Add (m);
  1085. }
  1086. }
  1087. }
  1088. // if graph has edges then
  1089. if (edges.Any ()) {
  1090. // return error (graph has at least one cycle)
  1091. return null;
  1092. } else {
  1093. // return L (a topologically sorted order)
  1094. return result;
  1095. }
  1096. }
  1097. /// <summary>
  1098. /// This virtual method is invoked when a view starts executing or
  1099. /// when the dimensions of the view have changed, for example in
  1100. /// response to the container view or terminal resizing.
  1101. /// </summary>
  1102. public virtual void LayoutSubviews ()
  1103. {
  1104. if (!layoutNeeded)
  1105. return;
  1106. // Sort out the dependencies of the X, Y, Width, Height properties
  1107. var nodes = new HashSet<View> ();
  1108. var edges = new HashSet<(View, View)> ();
  1109. foreach (var v in InternalSubviews) {
  1110. nodes.Add (v);
  1111. if (v.LayoutStyle == LayoutStyle.Computed) {
  1112. if (v.X is Pos.PosView)
  1113. edges.Add ((v, (v.X as Pos.PosView).Target));
  1114. if (v.Y is Pos.PosView)
  1115. edges.Add ((v, (v.Y as Pos.PosView).Target));
  1116. if (v.Width is Dim.DimView)
  1117. edges.Add ((v, (v.Width as Dim.DimView).Target));
  1118. if (v.Height is Dim.DimView)
  1119. edges.Add ((v, (v.Height as Dim.DimView).Target));
  1120. }
  1121. }
  1122. var ordered = TopologicalSort (nodes, edges);
  1123. ordered.Reverse ();
  1124. if (ordered == null)
  1125. throw new Exception ("There is a recursive cycle in the relative Pos/Dim in the views of " + this);
  1126. foreach (var v in ordered) {
  1127. if (v.LayoutStyle == LayoutStyle.Computed)
  1128. v.RelativeLayout (Frame);
  1129. v.LayoutSubviews ();
  1130. v.layoutNeeded = false;
  1131. }
  1132. layoutNeeded = false;
  1133. }
  1134. /// <summary>
  1135. /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:Terminal.Gui.View"/>.
  1136. /// </summary>
  1137. /// <returns>A <see cref="T:System.String"/> that represents the current <see cref="T:Terminal.Gui.View"/>.</returns>
  1138. public override string ToString ()
  1139. {
  1140. return $"{GetType ().Name}({Id})({Frame})";
  1141. }
  1142. }
  1143. /// <summary>
  1144. /// Toplevel views can be modally executed.
  1145. /// </summary>
  1146. /// <remarks>
  1147. /// <para>
  1148. /// Toplevels can be modally executing views, and they return control
  1149. /// to the caller when the "Running" property is set to false, or
  1150. /// by calling <see cref="M:Terminal.Gui.Application.RequestStop()"/>
  1151. /// </para>
  1152. /// <para>
  1153. /// There will be a toplevel created for you on the first time use
  1154. /// and can be accessed from the property <see cref="P:Terminal.Gui.Application.Top"/>,
  1155. /// but new toplevels can be created and ran on top of it. To run, create the
  1156. /// toplevel and then invoke <see cref="M:Terminal.Gui.Application.Run"/> with the
  1157. /// new toplevel.
  1158. /// </para>
  1159. /// </remarks>
  1160. public class Toplevel : View {
  1161. /// <summary>
  1162. /// This flag is checked on each iteration of the mainloop and it continues
  1163. /// running until this flag is set to false.
  1164. /// </summary>
  1165. public bool Running;
  1166. /// <summary>
  1167. /// Initializes a new instance of the <see cref="T:Terminal.Gui.Toplevel"/> class with the specified absolute layout.
  1168. /// </summary>
  1169. /// <param name="frame">Frame.</param>
  1170. public Toplevel (Rect frame) : base (frame)
  1171. {
  1172. ColorScheme = Colors.Base;
  1173. }
  1174. /// <summary>
  1175. /// Initializes a new instance of the <see cref="T:Terminal.Gui.Toplevel"/> class with Computed layout, defaulting to <see langword="async"/> full screen.
  1176. /// </summary>
  1177. public Toplevel () : base ()
  1178. {
  1179. ColorScheme = Colors.Base;
  1180. Width = Dim.Fill ();
  1181. Height = Dim.Fill ();
  1182. }
  1183. /// <summary>
  1184. /// Convenience factory method that creates a new toplevel with the current terminal dimensions.
  1185. /// </summary>
  1186. /// <returns>The create.</returns>
  1187. public static Toplevel Create ()
  1188. {
  1189. return new Toplevel (new Rect (0, 0, Driver.Cols, Driver.Rows));
  1190. }
  1191. public override bool CanFocus {
  1192. get => true;
  1193. }
  1194. public override bool ProcessKey (KeyEvent keyEvent)
  1195. {
  1196. if (base.ProcessKey (keyEvent))
  1197. return true;
  1198. switch (keyEvent.Key) {
  1199. case Key.ControlC:
  1200. // TODO: stop current execution of this container
  1201. break;
  1202. case Key.ControlZ:
  1203. Driver.Suspend ();
  1204. return true;
  1205. #if false
  1206. case Key.F5:
  1207. Application.DebugDrawBounds = !Application.DebugDrawBounds;
  1208. SetNeedsDisplay ();
  1209. return true;
  1210. #endif
  1211. case Key.Tab:
  1212. case Key.CursorRight:
  1213. case Key.CursorDown:
  1214. var old = Focused;
  1215. if (!FocusNext ())
  1216. FocusNext ();
  1217. if (old != Focused) {
  1218. old?.SetNeedsDisplay ();
  1219. Focused?.SetNeedsDisplay ();
  1220. }
  1221. return true;
  1222. case Key.CursorLeft:
  1223. case Key.CursorUp:
  1224. case Key.BackTab:
  1225. old = Focused;
  1226. if (!FocusPrev ())
  1227. FocusPrev ();
  1228. if (old != Focused) {
  1229. old?.SetNeedsDisplay ();
  1230. Focused?.SetNeedsDisplay ();
  1231. }
  1232. return true;
  1233. case Key.ControlL:
  1234. Application.Refresh ();
  1235. return true;
  1236. }
  1237. return false;
  1238. }
  1239. /// <summary>
  1240. /// This method is invoked by Application.Begin as part of the Application.Run after
  1241. /// the views have been laid out, and before the views are drawn for the first time.
  1242. /// </summary>
  1243. public virtual void WillPresent ()
  1244. {
  1245. FocusFirst ();
  1246. }
  1247. }
  1248. /// <summary>
  1249. /// A toplevel view that draws a frame around its region and has a "ContentView" subview where the contents are added.
  1250. /// </summary>
  1251. public class Window : Toplevel, IEnumerable {
  1252. View contentView;
  1253. ustring title;
  1254. /// <summary>
  1255. /// The title to be displayed for this window.
  1256. /// </summary>
  1257. /// <value>The title.</value>
  1258. public ustring Title {
  1259. get => title;
  1260. set {
  1261. title = value;
  1262. SetNeedsDisplay ();
  1263. }
  1264. }
  1265. class ContentView : View {
  1266. public ContentView (Rect frame) : base (frame) { }
  1267. public ContentView () : base () { }
  1268. #if false
  1269. public override void Redraw (Rect region)
  1270. {
  1271. Driver.SetAttribute (ColorScheme.Focus);
  1272. for (int y = 0; y < Frame.Height; y++) {
  1273. Move (0, y);
  1274. for (int x = 0; x < Frame.Width; x++) {
  1275. Driver.AddRune ('x');
  1276. }
  1277. }
  1278. }
  1279. #endif
  1280. }
  1281. /// <summary>
  1282. /// Initializes a new instance of the <see cref="T:Terminal.Gui.Gui.Window"/> class with an optional title and a set frame.
  1283. /// </summary>
  1284. /// <param name="frame">Frame.</param>
  1285. /// <param name="title">Title.</param>
  1286. public Window (Rect frame, ustring title = null) : this (frame, title, padding: 0)
  1287. {
  1288. }
  1289. /// <summary>
  1290. /// Initializes a new instance of the <see cref="T:Terminal.Gui.Window"/> class with an optional title.
  1291. /// </summary>
  1292. /// <param name="title">Title.</param>
  1293. public Window (ustring title = null) : this (title, padding: 0)
  1294. {
  1295. }
  1296. int padding;
  1297. /// <summary>
  1298. /// Initializes a new instance of the <see cref="T:Terminal.Gui.Window"/> with
  1299. /// the specified frame for its location, with the specified border
  1300. /// an optional title.
  1301. /// </summary>
  1302. /// <param name="frame">Frame.</param>
  1303. /// <param name="padding">Number of characters to use for padding of the drawn frame.</param>
  1304. /// <param name="title">Title.</param>
  1305. public Window (Rect frame, ustring title = null, int padding = 0) : base (frame)
  1306. {
  1307. this.Title = title;
  1308. int wb = 2 * (1 + padding);
  1309. this.padding = padding;
  1310. var cFrame = new Rect (1 + padding, 1 + padding, frame.Width - wb, frame.Height - wb);
  1311. contentView = new ContentView (cFrame);
  1312. base.Add (contentView);
  1313. }
  1314. /// <summary>
  1315. /// Initializes a new instance of the <see cref="T:Terminal.Gui.Window"/> with
  1316. /// the specified frame for its location, with the specified border
  1317. /// an optional title.
  1318. /// </summary>
  1319. /// <param name="padding">Number of characters to use for padding of the drawn frame.</param>
  1320. /// <param name="title">Title.</param>
  1321. public Window (ustring title = null, int padding = 0) : base ()
  1322. {
  1323. this.Title = title;
  1324. int wb = 1 + padding;
  1325. this.padding = padding;
  1326. contentView = new ContentView () {
  1327. X = wb,
  1328. Y = wb,
  1329. Width = Dim.Fill (wb),
  1330. Height = Dim.Fill (wb)
  1331. };
  1332. base.Add (contentView);
  1333. }
  1334. /// <summary>
  1335. /// Enumerates the various views in the ContentView.
  1336. /// </summary>
  1337. /// <returns>The enumerator.</returns>
  1338. public new IEnumerator GetEnumerator ()
  1339. {
  1340. return contentView.GetEnumerator ();
  1341. }
  1342. void DrawFrame ()
  1343. {
  1344. DrawFrame (new Rect (0, 0, Frame.Width, Frame.Height), padding, fill: true);
  1345. }
  1346. /// <summary>
  1347. /// Add the specified view to the ContentView.
  1348. /// </summary>
  1349. /// <param name="view">View to add to the window.</param>
  1350. public override void Add (View view)
  1351. {
  1352. contentView.Add (view);
  1353. if (view.CanFocus)
  1354. CanFocus = true;
  1355. }
  1356. /// <summary>
  1357. /// Removes a widget from this container.
  1358. /// </summary>
  1359. /// <remarks>
  1360. /// </remarks>
  1361. public override void Remove (View view)
  1362. {
  1363. if (view == null)
  1364. return;
  1365. SetNeedsDisplay ();
  1366. var touched = view.Frame;
  1367. contentView.Remove (view);
  1368. if (contentView.InternalSubviews.Count < 1)
  1369. this.CanFocus = false;
  1370. }
  1371. /// <summary>
  1372. /// Removes all widgets from this container.
  1373. /// </summary>
  1374. /// <remarks>
  1375. /// </remarks>
  1376. public override void RemoveAll ()
  1377. {
  1378. contentView.RemoveAll ();
  1379. }
  1380. public override void Redraw (Rect bounds)
  1381. {
  1382. if (!NeedDisplay.IsEmpty) {
  1383. Driver.SetAttribute (ColorScheme.Normal);
  1384. DrawFrame ();
  1385. if (HasFocus)
  1386. Driver.SetAttribute (ColorScheme.Normal);
  1387. var width = Frame.Width;
  1388. if (Title != null && width > 4) {
  1389. Move (1+padding, padding);
  1390. Driver.AddRune (' ');
  1391. var str = Title.Length > width ? Title [0, width-4] : Title;
  1392. Driver.AddStr (str);
  1393. Driver.AddRune (' ');
  1394. }
  1395. Driver.SetAttribute (ColorScheme.Normal);
  1396. }
  1397. contentView.Redraw (contentView.Bounds);
  1398. ClearNeedsDisplay ();
  1399. }
  1400. #if true
  1401. //
  1402. // It does not look like the event is raised on clicked-drag
  1403. // need to figure that out.
  1404. //
  1405. Point? dragPosition;
  1406. public override bool MouseEvent(MouseEvent mouseEvent)
  1407. {
  1408. // The code is currently disabled, because the
  1409. // Driver.UncookMouse does not seem to have an effect if there is
  1410. // a pending mouse event activated.
  1411. if (true)
  1412. return false;
  1413. if ((mouseEvent.Flags == MouseFlags.Button1Pressed|| mouseEvent.Flags == MouseFlags.Button4Pressed)){
  1414. if (dragPosition.HasValue) {
  1415. var dx = mouseEvent.X - dragPosition.Value.X;
  1416. var dy = mouseEvent.Y - dragPosition.Value.Y;
  1417. var nx = Frame.X + dx;
  1418. var ny = Frame.Y + dy;
  1419. if (nx < 0)
  1420. nx = 0;
  1421. if (ny < 0)
  1422. ny = 0;
  1423. //Demo.ml2.Text = $"{dx},{dy}";
  1424. dragPosition = new Point (mouseEvent.X, mouseEvent.Y);
  1425. // TODO: optimize, only SetNeedsDisplay on the before/after regions.
  1426. if (SuperView == null)
  1427. Application.Refresh ();
  1428. else
  1429. SuperView.SetNeedsDisplay ();
  1430. Frame = new Rect (nx, ny, Frame.Width, Frame.Height);
  1431. SetNeedsDisplay ();
  1432. return true;
  1433. } else {
  1434. // Only start grabbing if the user clicks on the title bar.
  1435. if (mouseEvent.Y == 0) {
  1436. dragPosition = new Point (mouseEvent.X, mouseEvent.Y);
  1437. Application.GrabMouse (this);
  1438. }
  1439. //Demo.ml2.Text = $"Starting at {dragPosition}";
  1440. return true;
  1441. }
  1442. }
  1443. if (mouseEvent.Flags == MouseFlags.Button1Released) {
  1444. Application.UngrabMouse ();
  1445. Driver.UncookMouse ();
  1446. dragPosition = null;
  1447. //Driver.StopReportingMouseMoves ();
  1448. }
  1449. //Demo.ml.Text = me.ToString ();
  1450. return false;
  1451. }
  1452. #endif
  1453. }
  1454. /// <summary>
  1455. /// The application driver for gui.cs
  1456. /// </summary>
  1457. /// <remarks>
  1458. /// <para>
  1459. /// You can hook up to the Iteration event to have your method
  1460. /// invoked on each iteration of the mainloop.
  1461. /// </para>
  1462. /// <para>
  1463. /// Creates a mainloop to process input events, handle timers and
  1464. /// other sources of data. It is accessible via the MainLoop property.
  1465. /// </para>
  1466. /// <para>
  1467. /// When invoked sets the SynchronizationContext to one that is tied
  1468. /// to the mainloop, allowing user code to use async/await.
  1469. /// </para>
  1470. /// </remarks>
  1471. public static class Application {
  1472. /// <summary>
  1473. /// The current Console Driver in use.
  1474. /// </summary>
  1475. public static ConsoleDriver Driver;
  1476. /// <summary>
  1477. /// The Toplevel object used for the application on startup.
  1478. /// </summary>
  1479. /// <value>The top.</value>
  1480. public static Toplevel Top { get; private set; }
  1481. /// <summary>
  1482. /// The current toplevel object. This is updated when Application.Run enters and leaves and points to the current toplevel.
  1483. /// </summary>
  1484. /// <value>The current.</value>
  1485. public static Toplevel Current { get; private set; }
  1486. /// <summary>
  1487. /// The mainloop driver for the applicaiton
  1488. /// </summary>
  1489. /// <value>The main loop.</value>
  1490. public static Mono.Terminal.MainLoop MainLoop { get; private set; }
  1491. static Stack<Toplevel> toplevels = new Stack<Toplevel> ();
  1492. /// <summary>
  1493. /// This event is raised on each iteration of the
  1494. /// main loop.
  1495. /// </summary>
  1496. /// <remarks>
  1497. /// See also <see cref="Timeout"/>
  1498. /// </remarks>
  1499. static public event EventHandler Iteration;
  1500. /// <summary>
  1501. /// Returns a rectangle that is centered in the screen for the provided size.
  1502. /// </summary>
  1503. /// <returns>The centered rect.</returns>
  1504. /// <param name="size">Size for the rectangle.</param>
  1505. public static Rect MakeCenteredRect (Size size)
  1506. {
  1507. return new Rect (new Point ((Driver.Cols - size.Width) / 2, (Driver.Rows - size.Height) / 2), size);
  1508. }
  1509. //
  1510. // provides the sync context set while executing code in gui.cs, to let
  1511. // users use async/await on their code
  1512. //
  1513. class MainLoopSyncContext : SynchronizationContext {
  1514. Mono.Terminal.MainLoop mainLoop;
  1515. public MainLoopSyncContext (Mono.Terminal.MainLoop mainLoop)
  1516. {
  1517. this.mainLoop = mainLoop;
  1518. }
  1519. public override SynchronizationContext CreateCopy ()
  1520. {
  1521. return new MainLoopSyncContext (MainLoop);
  1522. }
  1523. public override void Post (SendOrPostCallback d, object state)
  1524. {
  1525. mainLoop.AddIdle (() => {
  1526. d (state);
  1527. return false;
  1528. });
  1529. }
  1530. public override void Send (SendOrPostCallback d, object state)
  1531. {
  1532. mainLoop.Invoke (() => {
  1533. d (state);
  1534. });
  1535. }
  1536. }
  1537. /// <summary>
  1538. /// If set, it forces the use of the System.Console-based driver.
  1539. /// </summary>
  1540. public static bool UseSystemConsole;
  1541. /// <summary>
  1542. /// Initializes the Application
  1543. /// </summary>
  1544. public static void Init () => Init (() => Toplevel.Create ());
  1545. /// <summary>
  1546. /// Initializes the Application
  1547. /// </summary>
  1548. static void Init (Func<Toplevel> topLevelFactory)
  1549. {
  1550. if (Top != null)
  1551. return;
  1552. var p = Environment.OSVersion.Platform;
  1553. Mono.Terminal.IMainLoopDriver mainLoopDriver;
  1554. if (UseSystemConsole) {
  1555. mainLoopDriver = new Mono.Terminal.NetMainLoop ();
  1556. Driver = new NetDriver ();
  1557. } else if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows){
  1558. var windowsDriver = new WindowsDriver ();
  1559. mainLoopDriver = windowsDriver;
  1560. Driver = windowsDriver;
  1561. } else {
  1562. mainLoopDriver = new Mono.Terminal.UnixMainLoop ();
  1563. Driver = new CursesDriver ();
  1564. }
  1565. Driver.Init (TerminalResized);
  1566. MainLoop = new Mono.Terminal.MainLoop (mainLoopDriver);
  1567. SynchronizationContext.SetSynchronizationContext (new MainLoopSyncContext (MainLoop));
  1568. Top = topLevelFactory ();
  1569. Current = Top;
  1570. }
  1571. /// <summary>
  1572. /// Captures the execution state for the provided TopLevel view.
  1573. /// </summary>
  1574. public class RunState : IDisposable {
  1575. internal RunState (Toplevel view)
  1576. {
  1577. Toplevel = view;
  1578. }
  1579. internal Toplevel Toplevel;
  1580. /// <summary>
  1581. /// Releases alTop = l resource used by the <see cref="T:Terminal.Gui.Application.RunState"/> object.
  1582. /// </summary>
  1583. /// <remarks>Call <see cref="Dispose()"/> when you are finished using the <see cref="T:Terminal.Gui.Application.RunState"/>. The
  1584. /// <see cref="Dispose()"/> method leaves the <see cref="T:Terminal.Gui.Application.RunState"/> in an unusable state. After
  1585. /// calling <see cref="Dispose()"/>, you must release all references to the
  1586. /// <see cref="T:Terminal.Gui.Application.RunState"/> so the garbage collector can reclaim the memory that the
  1587. /// <see cref="T:Terminal.Gui.Application.RunState"/> was occupying.</remarks>
  1588. public void Dispose ()
  1589. {
  1590. Dispose (true);
  1591. GC.SuppressFinalize (this);
  1592. }
  1593. /// <summary>
  1594. /// Dispose the specified disposing.
  1595. /// </summary>
  1596. /// <returns>The dispose.</returns>
  1597. /// <param name="disposing">If set to <c>true</c> disposing.</param>
  1598. protected virtual void Dispose (bool disposing)
  1599. {
  1600. if (Toplevel != null) {
  1601. End (Toplevel);
  1602. Toplevel = null;
  1603. }
  1604. }
  1605. }
  1606. static void ProcessKeyEvent (KeyEvent ke)
  1607. {
  1608. if (Current.ProcessHotKey (ke))
  1609. return;
  1610. if (Current.ProcessKey (ke))
  1611. return;
  1612. // Process the key normally
  1613. if (Current.ProcessColdKey (ke))
  1614. return;
  1615. }
  1616. static View FindDeepestView (View start, int x, int y, out int resx, out int resy)
  1617. {
  1618. var startFrame = start.Frame;
  1619. if (!startFrame.Contains (x, y)) {
  1620. resx = 0;
  1621. resy = 0;
  1622. return null;
  1623. }
  1624. if (start.InternalSubviews != null){
  1625. int count = start.InternalSubviews.Count;
  1626. if (count > 0) {
  1627. var rx = x - startFrame.X;
  1628. var ry = y - startFrame.Y;
  1629. for (int i = count - 1; i >= 0; i--) {
  1630. View v = start.InternalSubviews [i];
  1631. if (v.Frame.Contains (rx, ry)) {
  1632. var deep = FindDeepestView (v, rx, ry, out resx, out resy);
  1633. if (deep == null)
  1634. return v;
  1635. return deep;
  1636. }
  1637. }
  1638. }
  1639. }
  1640. resx = x-startFrame.X;
  1641. resy = y-startFrame.Y;
  1642. return start;
  1643. }
  1644. static View mouseGrabView;
  1645. /// <summary>
  1646. /// Grabs the mouse, forcing all mouse events to be routed to the specified view until UngrabMouse is called.
  1647. /// </summary>
  1648. /// <returns>The grab.</returns>
  1649. /// <param name="view">View that will receive all mouse events until UngrabMouse is invoked.</param>
  1650. public static void GrabMouse (View view)
  1651. {
  1652. if (view == null)
  1653. return;
  1654. mouseGrabView = view;
  1655. Driver.UncookMouse ();
  1656. }
  1657. /// <summary>
  1658. /// Releases the mouse grab, so mouse events will be routed to the view on which the mouse is.
  1659. /// </summary>
  1660. public static void UngrabMouse ()
  1661. {
  1662. mouseGrabView = null;
  1663. Driver.CookMouse ();
  1664. }
  1665. /// <summary>
  1666. /// Merely a debugging aid to see the raw mouse events
  1667. /// </summary>
  1668. static public Action<MouseEvent> RootMouseEvent;
  1669. static void ProcessMouseEvent (MouseEvent me)
  1670. {
  1671. RootMouseEvent?.Invoke (me);
  1672. if (mouseGrabView != null) {
  1673. var newxy = mouseGrabView.ScreenToView (me.X, me.Y);
  1674. var nme = new MouseEvent () {
  1675. X = newxy.X,
  1676. Y = newxy.Y,
  1677. Flags = me.Flags
  1678. };
  1679. mouseGrabView.MouseEvent (me);
  1680. return;
  1681. }
  1682. int rx, ry;
  1683. var view = FindDeepestView (Current, me.X, me.Y, out rx, out ry);
  1684. if (view != null) {
  1685. if (!view.WantMousePositionReports && me.Flags == MouseFlags.ReportMousePosition)
  1686. return;
  1687. var nme = new MouseEvent () {
  1688. X = rx,
  1689. Y = ry,
  1690. Flags = me.Flags
  1691. };
  1692. // Should we bubbled up the event, if it is not handled?
  1693. view.MouseEvent (nme);
  1694. }
  1695. }
  1696. /// <summary>
  1697. /// Building block API: Prepares the provided toplevel for execution.
  1698. /// </summary>
  1699. /// <returns>The runstate handle that needs to be passed to the End() method upon completion.</returns>
  1700. /// <param name="toplevel">Toplevel to prepare execution for.</param>
  1701. /// <remarks>
  1702. /// This method prepares the provided toplevel for running with the focus,
  1703. /// it adds this to the list of toplevels, sets up the mainloop to process the
  1704. /// event, lays out the subviews, focuses the first element, and draws the
  1705. /// toplevel in the screen. This is usually followed by executing
  1706. /// the <see cref="RunLoop"/> method, and then the <see cref="End(RunState)"/> method upon termination which will
  1707. /// undo these changes.
  1708. /// </remarks>
  1709. static public RunState Begin (Toplevel toplevel)
  1710. {
  1711. if (toplevel == null)
  1712. throw new ArgumentNullException (nameof (toplevel));
  1713. var rs = new RunState (toplevel);
  1714. Init ();
  1715. toplevels.Push (toplevel);
  1716. Current = toplevel;
  1717. Driver.PrepareToRun (MainLoop, ProcessKeyEvent, ProcessMouseEvent);
  1718. if (toplevel.LayoutStyle == LayoutStyle.Computed)
  1719. toplevel.RelativeLayout (new Rect (0, 0, Driver.Cols, Driver.Rows));
  1720. toplevel.LayoutSubviews ();
  1721. toplevel.WillPresent ();
  1722. Redraw (toplevel);
  1723. toplevel.PositionCursor ();
  1724. Driver.Refresh ();
  1725. return rs;
  1726. }
  1727. /// <summary>
  1728. /// Building block API: completes the exection of a Toplevel that was started with Begin.
  1729. /// </summary>
  1730. /// <param name="runState">The runstate returned by the <see cref="Begin(Toplevel)"/> method.</param>
  1731. static public void End (RunState runState)
  1732. {
  1733. if (runState == null)
  1734. throw new ArgumentNullException (nameof (runState));
  1735. runState.Dispose ();
  1736. }
  1737. static void Shutdown ()
  1738. {
  1739. Driver.End ();
  1740. }
  1741. static void Redraw (View view)
  1742. {
  1743. view.Redraw (view.Bounds);
  1744. Driver.Refresh ();
  1745. }
  1746. static void Refresh (View view)
  1747. {
  1748. view.Redraw (view.Bounds);
  1749. Driver.Refresh ();
  1750. }
  1751. /// <summary>
  1752. /// Triggers a refresh of the entire display.
  1753. /// </summary>
  1754. public static void Refresh ()
  1755. {
  1756. Driver.UpdateScreen ();
  1757. View last = null;
  1758. foreach (var v in toplevels.Reverse ()) {
  1759. v.SetNeedsDisplay ();
  1760. v.Redraw (v.Bounds);
  1761. last = v;
  1762. }
  1763. last?.PositionCursor ();
  1764. Driver.Refresh ();
  1765. }
  1766. internal static void End (View view)
  1767. {
  1768. if (toplevels.Peek () != view)
  1769. throw new ArgumentException ("The view that you end with must be balanced");
  1770. toplevels.Pop ();
  1771. if (toplevels.Count == 0)
  1772. Shutdown ();
  1773. else
  1774. {
  1775. Current = toplevels.Peek();
  1776. Refresh ();
  1777. }
  1778. }
  1779. /// <summary>
  1780. /// Building block API: Runs the main loop for the created dialog
  1781. /// </summary>
  1782. /// <remarks>
  1783. /// Use the wait parameter to control whether this is a
  1784. /// blocking or non-blocking call.
  1785. /// </remarks>
  1786. /// <param name="state">The state returned by the Begin method.</param>
  1787. /// <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>
  1788. public static void RunLoop (RunState state, bool wait = true)
  1789. {
  1790. if (state == null)
  1791. throw new ArgumentNullException (nameof (state));
  1792. if (state.Toplevel == null)
  1793. throw new ObjectDisposedException ("state");
  1794. for (state.Toplevel.Running = true; state.Toplevel.Running;) {
  1795. if (MainLoop.EventsPending (wait)) {
  1796. MainLoop.MainIteration ();
  1797. if (Iteration != null)
  1798. Iteration (null, EventArgs.Empty);
  1799. } else if (wait == false)
  1800. return;
  1801. if (!state.Toplevel.NeedDisplay.IsEmpty || state.Toplevel.childNeedsDisplay) {
  1802. state.Toplevel.Redraw (state.Toplevel.Bounds);
  1803. if (DebugDrawBounds)
  1804. DrawBounds (state.Toplevel);
  1805. state.Toplevel.PositionCursor ();
  1806. Driver.Refresh ();
  1807. } else
  1808. Driver.UpdateCursor ();
  1809. }
  1810. }
  1811. internal static bool DebugDrawBounds;
  1812. // Need to look into why this does not work properly.
  1813. static void DrawBounds (View v)
  1814. {
  1815. v.DrawFrame (v.Frame, padding: 0, fill: false);
  1816. if (v.InternalSubviews != null && v.InternalSubviews.Count > 0)
  1817. foreach (var sub in v.InternalSubviews)
  1818. DrawBounds (sub);
  1819. }
  1820. /// <summary>
  1821. /// Runs the application with the built-in toplevel view
  1822. /// </summary>
  1823. public static void Run ()
  1824. {
  1825. Run (Top);
  1826. }
  1827. /// <summary>
  1828. /// Runs the application with a new instance of the specified toplevel view
  1829. /// </summary>
  1830. public static void Run<T> () where T : Toplevel, new()
  1831. {
  1832. Init (() => new T());
  1833. Run (Top);
  1834. }
  1835. /// <summary>
  1836. /// Runs the main loop on the given container.
  1837. /// </summary>
  1838. /// <remarks>
  1839. /// <para>
  1840. /// This method is used to start processing events
  1841. /// for the main application, but it is also used to
  1842. /// run modal dialog boxes.
  1843. /// </para>
  1844. /// <para>
  1845. /// To make a toplevel stop execution, set the "Running"
  1846. /// property to false.
  1847. /// </para>
  1848. /// <para>
  1849. /// This is equivalent to calling Begin on the toplevel view, followed by RunLoop with the
  1850. /// returned value, and then calling end on the return value.
  1851. /// </para>
  1852. /// <para>
  1853. /// Alternatively, if your program needs to control the main loop and needs to
  1854. /// process events manually, you can invoke Begin to set things up manually and then
  1855. /// repeatedly call RunLoop with the wait parameter set to false. By doing this
  1856. /// the RunLoop method will only process any pending events, timers, idle handlers and
  1857. /// then return control immediately.
  1858. /// </para>
  1859. /// </remarks>
  1860. public static void Run (Toplevel view)
  1861. {
  1862. var runToken = Begin (view);
  1863. RunLoop (runToken);
  1864. End (runToken);
  1865. }
  1866. /// <summary>
  1867. /// Stops running the most recent toplevel
  1868. /// </summary>
  1869. public static void RequestStop ()
  1870. {
  1871. Current.Running = false;
  1872. }
  1873. static void TerminalResized ()
  1874. {
  1875. var full = new Rect (0, 0, Driver.Cols, Driver.Rows);
  1876. Driver.Clip = full;
  1877. foreach (var t in toplevels) {
  1878. t.RelativeLayout (full);
  1879. t.LayoutSubviews ();
  1880. }
  1881. Refresh ();
  1882. }
  1883. }
  1884. }