Core.cs 61 KB

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