Core.cs 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108
  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. /// </remarks>
  1161. public class Toplevel : View {
  1162. /// <summary>
  1163. /// This flag is checked on each iteration of the mainloop and it continues
  1164. /// running until this flag is set to false.
  1165. /// </summary>
  1166. public bool Running;
  1167. /// <summary>
  1168. /// Initializes a new instance of the <see cref="T:Terminal.Gui.Toplevel"/> class with the specified absolute layout.
  1169. /// </summary>
  1170. /// <param name="frame">Frame.</param>
  1171. public Toplevel (Rect frame) : base (frame)
  1172. {
  1173. ColorScheme = Colors.Base;
  1174. }
  1175. /// <summary>
  1176. /// Initializes a new instance of the <see cref="T:Terminal.Gui.Toplevel"/> class with Computed layout, defaulting to <see langword="async"/> full screen.
  1177. /// </summary>
  1178. public Toplevel () : base ()
  1179. {
  1180. ColorScheme = Colors.Base;
  1181. Width = Dim.Fill ();
  1182. Height = Dim.Fill ();
  1183. }
  1184. /// <summary>
  1185. /// Convenience factory method that creates a new toplevel with the current terminal dimensions.
  1186. /// </summary>
  1187. /// <returns>The create.</returns>
  1188. public static Toplevel Create ()
  1189. {
  1190. return new Toplevel (new Rect (0, 0, Driver.Cols, Driver.Rows));
  1191. }
  1192. public override bool CanFocus {
  1193. get => true;
  1194. }
  1195. public override bool ProcessKey (KeyEvent keyEvent)
  1196. {
  1197. if (base.ProcessKey (keyEvent))
  1198. return true;
  1199. switch (keyEvent.Key) {
  1200. case Key.ControlC:
  1201. // TODO: stop current execution of this container
  1202. break;
  1203. case Key.ControlZ:
  1204. Driver.Suspend ();
  1205. return true;
  1206. #if false
  1207. case Key.F5:
  1208. Application.DebugDrawBounds = !Application.DebugDrawBounds;
  1209. SetNeedsDisplay ();
  1210. return true;
  1211. #endif
  1212. case Key.Tab:
  1213. case Key.CursorRight:
  1214. case Key.CursorDown:
  1215. var old = Focused;
  1216. if (!FocusNext ())
  1217. FocusNext ();
  1218. if (old != Focused) {
  1219. old?.SetNeedsDisplay ();
  1220. Focused?.SetNeedsDisplay ();
  1221. }
  1222. return true;
  1223. case Key.CursorLeft:
  1224. case Key.CursorUp:
  1225. case Key.BackTab:
  1226. old = Focused;
  1227. if (!FocusPrev ())
  1228. FocusPrev ();
  1229. if (old != Focused) {
  1230. old?.SetNeedsDisplay ();
  1231. Focused?.SetNeedsDisplay ();
  1232. }
  1233. return true;
  1234. case Key.ControlL:
  1235. Application.Refresh ();
  1236. return true;
  1237. }
  1238. return false;
  1239. }
  1240. /// <summary>
  1241. /// This method is invoked by Application.Begin as part of the Application.Run after
  1242. /// the views have been laid out, and before the views are drawn for the first time.
  1243. /// </summary>
  1244. public virtual void WillPresent ()
  1245. {
  1246. FocusFirst ();
  1247. }
  1248. }
  1249. /// <summary>
  1250. /// A toplevel view that draws a frame around its region and has a "ContentView" subview where the contents are added.
  1251. /// </summary>
  1252. public class Window : Toplevel, IEnumerable {
  1253. View contentView;
  1254. ustring title;
  1255. /// <summary>
  1256. /// The title to be displayed for this window.
  1257. /// </summary>
  1258. /// <value>The title.</value>
  1259. public ustring Title {
  1260. get => title;
  1261. set {
  1262. title = value;
  1263. SetNeedsDisplay ();
  1264. }
  1265. }
  1266. class ContentView : View {
  1267. public ContentView (Rect frame) : base (frame) { }
  1268. public ContentView () : base () { }
  1269. #if false
  1270. public override void Redraw (Rect region)
  1271. {
  1272. Driver.SetAttribute (ColorScheme.Focus);
  1273. for (int y = 0; y < Frame.Height; y++) {
  1274. Move (0, y);
  1275. for (int x = 0; x < Frame.Width; x++) {
  1276. Driver.AddRune ('x');
  1277. }
  1278. }
  1279. }
  1280. #endif
  1281. }
  1282. /// <summary>
  1283. /// Initializes a new instance of the <see cref="T:Terminal.Gui.Gui.Window"/> class with an optional title and a set frame.
  1284. /// </summary>
  1285. /// <param name="frame">Frame.</param>
  1286. /// <param name="title">Title.</param>
  1287. public Window (Rect frame, ustring title = null) : this (frame, title, padding: 0)
  1288. {
  1289. }
  1290. /// <summary>
  1291. /// Initializes a new instance of the <see cref="T:Terminal.Gui.Window"/> class with an optional title.
  1292. /// </summary>
  1293. /// <param name="title">Title.</param>
  1294. public Window (ustring title = null) : this (title, padding: 0)
  1295. {
  1296. }
  1297. int padding;
  1298. /// <summary>
  1299. /// Initializes a new instance of the <see cref="T:Terminal.Gui.Window"/> with
  1300. /// the specified frame for its location, with the specified border
  1301. /// an optional title.
  1302. /// </summary>
  1303. /// <param name="frame">Frame.</param>
  1304. /// <param name="padding">Number of characters to use for padding of the drawn frame.</param>
  1305. /// <param name="title">Title.</param>
  1306. public Window (Rect frame, ustring title = null, int padding = 0) : base (frame)
  1307. {
  1308. this.Title = title;
  1309. int wb = 2 * (1 + padding);
  1310. this.padding = padding;
  1311. var cFrame = new Rect (1 + padding, 1 + padding, frame.Width - wb, frame.Height - wb);
  1312. contentView = new ContentView (cFrame);
  1313. base.Add (contentView);
  1314. }
  1315. /// <summary>
  1316. /// Initializes a new instance of the <see cref="T:Terminal.Gui.Window"/> with
  1317. /// the specified frame for its location, with the specified border
  1318. /// an optional title.
  1319. /// </summary>
  1320. /// <param name="padding">Number of characters to use for padding of the drawn frame.</param>
  1321. /// <param name="title">Title.</param>
  1322. public Window (ustring title = null, int padding = 0) : base ()
  1323. {
  1324. this.Title = title;
  1325. int wb = 1 + padding;
  1326. this.padding = padding;
  1327. contentView = new ContentView () {
  1328. X = wb,
  1329. Y = wb,
  1330. Width = Dim.Fill (wb),
  1331. Height = Dim.Fill (wb)
  1332. };
  1333. base.Add (contentView);
  1334. }
  1335. /// <summary>
  1336. /// Enumerates the various views in the ContentView.
  1337. /// </summary>
  1338. /// <returns>The enumerator.</returns>
  1339. public new IEnumerator GetEnumerator ()
  1340. {
  1341. return contentView.GetEnumerator ();
  1342. }
  1343. void DrawFrame ()
  1344. {
  1345. DrawFrame (new Rect (0, 0, Frame.Width, Frame.Height), padding, fill: true);
  1346. }
  1347. /// <summary>
  1348. /// Add the specified view to the ContentView.
  1349. /// </summary>
  1350. /// <param name="view">View to add to the window.</param>
  1351. public override void Add (View view)
  1352. {
  1353. contentView.Add (view);
  1354. if (view.CanFocus)
  1355. CanFocus = true;
  1356. }
  1357. /// <summary>
  1358. /// Removes a widget from this container.
  1359. /// </summary>
  1360. /// <remarks>
  1361. /// </remarks>
  1362. public override void Remove (View view)
  1363. {
  1364. if (view == null)
  1365. return;
  1366. SetNeedsDisplay ();
  1367. var touched = view.Frame;
  1368. contentView.Remove (view);
  1369. if (contentView.InternalSubviews.Count < 1)
  1370. this.CanFocus = false;
  1371. }
  1372. /// <summary>
  1373. /// Removes all widgets from this container.
  1374. /// </summary>
  1375. /// <remarks>
  1376. /// </remarks>
  1377. public override void RemoveAll ()
  1378. {
  1379. contentView.RemoveAll ();
  1380. }
  1381. public override void Redraw (Rect bounds)
  1382. {
  1383. if (!NeedDisplay.IsEmpty) {
  1384. Driver.SetAttribute (ColorScheme.Normal);
  1385. DrawFrame ();
  1386. if (HasFocus)
  1387. Driver.SetAttribute (ColorScheme.Normal);
  1388. var width = Frame.Width;
  1389. if (Title != null && width > 4) {
  1390. Move (1+padding, padding);
  1391. Driver.AddRune (' ');
  1392. var str = Title.Length > width ? Title [0, width-4] : Title;
  1393. Driver.AddStr (str);
  1394. Driver.AddRune (' ');
  1395. }
  1396. Driver.SetAttribute (ColorScheme.Normal);
  1397. }
  1398. contentView.Redraw (contentView.Bounds);
  1399. ClearNeedsDisplay ();
  1400. }
  1401. #if true
  1402. //
  1403. // It does not look like the event is raised on clicked-drag
  1404. // need to figure that out.
  1405. //
  1406. Point? dragPosition;
  1407. public override bool MouseEvent(MouseEvent mouseEvent)
  1408. {
  1409. // The code is currently disabled, because the
  1410. // Driver.UncookMouse does not seem to have an effect if there is
  1411. // a pending mouse event activated.
  1412. if (true)
  1413. return false;
  1414. if ((mouseEvent.Flags == MouseFlags.Button1Pressed|| mouseEvent.Flags == MouseFlags.Button4Pressed)){
  1415. if (dragPosition.HasValue) {
  1416. var dx = mouseEvent.X - dragPosition.Value.X;
  1417. var dy = mouseEvent.Y - dragPosition.Value.Y;
  1418. var nx = Frame.X + dx;
  1419. var ny = Frame.Y + dy;
  1420. if (nx < 0)
  1421. nx = 0;
  1422. if (ny < 0)
  1423. ny = 0;
  1424. //Demo.ml2.Text = $"{dx},{dy}";
  1425. dragPosition = new Point (mouseEvent.X, mouseEvent.Y);
  1426. // TODO: optimize, only SetNeedsDisplay on the before/after regions.
  1427. if (SuperView == null)
  1428. Application.Refresh ();
  1429. else
  1430. SuperView.SetNeedsDisplay ();
  1431. Frame = new Rect (nx, ny, Frame.Width, Frame.Height);
  1432. SetNeedsDisplay ();
  1433. return true;
  1434. } else {
  1435. // Only start grabbing if the user clicks on the title bar.
  1436. if (mouseEvent.Y == 0) {
  1437. dragPosition = new Point (mouseEvent.X, mouseEvent.Y);
  1438. Application.GrabMouse (this);
  1439. }
  1440. //Demo.ml2.Text = $"Starting at {dragPosition}";
  1441. return true;
  1442. }
  1443. }
  1444. if (mouseEvent.Flags == MouseFlags.Button1Released) {
  1445. Application.UngrabMouse ();
  1446. Driver.UncookMouse ();
  1447. dragPosition = null;
  1448. //Driver.StopReportingMouseMoves ();
  1449. }
  1450. //Demo.ml.Text = me.ToString ();
  1451. return false;
  1452. }
  1453. #endif
  1454. }
  1455. /// <summary>
  1456. /// The application driver for gui.cs
  1457. /// </summary>
  1458. /// <remarks>
  1459. /// <para>
  1460. /// You can hook up to the Iteration event to have your method
  1461. /// invoked on each iteration of the mainloop.
  1462. /// </para>
  1463. /// <para>
  1464. /// Creates a mainloop to process input events, handle timers and
  1465. /// other sources of data. It is accessible via the MainLoop property.
  1466. /// </para>
  1467. /// <para>
  1468. /// When invoked sets the SynchronizationContext to one that is tied
  1469. /// to the mainloop, allowing user code to use async/await.
  1470. /// </para>
  1471. /// </remarks>
  1472. public static class Application {
  1473. /// <summary>
  1474. /// The current Console Driver in use.
  1475. /// </summary>
  1476. public static ConsoleDriver Driver;
  1477. /// <summary>
  1478. /// The Toplevel object used for the application on startup.
  1479. /// </summary>
  1480. /// <value>The top.</value>
  1481. public static Toplevel Top { get; private set; }
  1482. /// <summary>
  1483. /// The current toplevel object. This is updated when Application.Run enters and leaves and points to the current toplevel.
  1484. /// </summary>
  1485. /// <value>The current.</value>
  1486. public static Toplevel Current { get; private set; }
  1487. /// <summary>
  1488. /// The mainloop driver for the applicaiton
  1489. /// </summary>
  1490. /// <value>The main loop.</value>
  1491. public static Mono.Terminal.MainLoop MainLoop { get; private set; }
  1492. static Stack<Toplevel> toplevels = new Stack<Toplevel> ();
  1493. /// <summary>
  1494. /// This event is raised on each iteration of the
  1495. /// main loop.
  1496. /// </summary>
  1497. /// <remarks>
  1498. /// See also <see cref="Timeout"/>
  1499. /// </remarks>
  1500. static public event EventHandler Iteration;
  1501. /// <summary>
  1502. /// Returns a rectangle that is centered in the screen for the provided size.
  1503. /// </summary>
  1504. /// <returns>The centered rect.</returns>
  1505. /// <param name="size">Size for the rectangle.</param>
  1506. public static Rect MakeCenteredRect (Size size)
  1507. {
  1508. return new Rect (new Point ((Driver.Cols - size.Width) / 2, (Driver.Rows - size.Height) / 2), size);
  1509. }
  1510. //
  1511. // provides the sync context set while executing code in gui.cs, to let
  1512. // users use async/await on their code
  1513. //
  1514. class MainLoopSyncContext : SynchronizationContext {
  1515. Mono.Terminal.MainLoop mainLoop;
  1516. public MainLoopSyncContext (Mono.Terminal.MainLoop mainLoop)
  1517. {
  1518. this.mainLoop = mainLoop;
  1519. }
  1520. public override SynchronizationContext CreateCopy ()
  1521. {
  1522. return new MainLoopSyncContext (MainLoop);
  1523. }
  1524. public override void Post (SendOrPostCallback d, object state)
  1525. {
  1526. mainLoop.AddIdle (() => {
  1527. d (state);
  1528. return false;
  1529. });
  1530. }
  1531. public override void Send (SendOrPostCallback d, object state)
  1532. {
  1533. mainLoop.Invoke (() => {
  1534. d (state);
  1535. });
  1536. }
  1537. }
  1538. /// <summary>
  1539. /// If set, it forces the use of the System.Console-based driver.
  1540. /// </summary>
  1541. public static bool UseSystemConsole;
  1542. /// <summary>
  1543. /// Initializes the Application
  1544. /// </summary>
  1545. public static void Init () => Init (() => Toplevel.Create ());
  1546. /// <summary>
  1547. /// Initializes the Application
  1548. /// </summary>
  1549. static void Init (Func<Toplevel> topLevelFactory)
  1550. {
  1551. if (Top != null)
  1552. return;
  1553. var p = Environment.OSVersion.Platform;
  1554. Mono.Terminal.IMainLoopDriver mainLoopDriver;
  1555. if (UseSystemConsole) {
  1556. mainLoopDriver = new Mono.Terminal.NetMainLoop ();
  1557. Driver = new NetDriver ();
  1558. } else if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows){
  1559. var windowsDriver = new WindowsDriver ();
  1560. mainLoopDriver = windowsDriver;
  1561. Driver = windowsDriver;
  1562. } else {
  1563. mainLoopDriver = new Mono.Terminal.UnixMainLoop ();
  1564. Driver = new CursesDriver ();
  1565. }
  1566. Driver.Init (TerminalResized);
  1567. MainLoop = new Mono.Terminal.MainLoop (mainLoopDriver);
  1568. SynchronizationContext.SetSynchronizationContext (new MainLoopSyncContext (MainLoop));
  1569. Top = topLevelFactory ();
  1570. Current = Top;
  1571. }
  1572. /// <summary>
  1573. /// Captures the execution state for the provided TopLevel view.
  1574. /// </summary>
  1575. public class RunState : IDisposable {
  1576. internal RunState (Toplevel view)
  1577. {
  1578. Toplevel = view;
  1579. }
  1580. internal Toplevel Toplevel;
  1581. /// <summary>
  1582. /// Releases alTop = l resource used by the <see cref="T:Terminal.Gui.Application.RunState"/> object.
  1583. /// </summary>
  1584. /// <remarks>Call <see cref="Dispose()"/> when you are finished using the <see cref="T:Terminal.Gui.Application.RunState"/>. The
  1585. /// <see cref="Dispose()"/> method leaves the <see cref="T:Terminal.Gui.Application.RunState"/> in an unusable state. After
  1586. /// calling <see cref="Dispose()"/>, you must release all references to the
  1587. /// <see cref="T:Terminal.Gui.Application.RunState"/> so the garbage collector can reclaim the memory that the
  1588. /// <see cref="T:Terminal.Gui.Application.RunState"/> was occupying.</remarks>
  1589. public void Dispose ()
  1590. {
  1591. Dispose (true);
  1592. GC.SuppressFinalize (this);
  1593. }
  1594. /// <summary>
  1595. /// Dispose the specified disposing.
  1596. /// </summary>
  1597. /// <returns>The dispose.</returns>
  1598. /// <param name="disposing">If set to <c>true</c> disposing.</param>
  1599. protected virtual void Dispose (bool disposing)
  1600. {
  1601. if (Toplevel != null) {
  1602. End (Toplevel);
  1603. Toplevel = null;
  1604. }
  1605. }
  1606. }
  1607. static void ProcessKeyEvent (KeyEvent ke)
  1608. {
  1609. if (Current.ProcessHotKey (ke))
  1610. return;
  1611. if (Current.ProcessKey (ke))
  1612. return;
  1613. // Process the key normally
  1614. if (Current.ProcessColdKey (ke))
  1615. return;
  1616. }
  1617. static View FindDeepestView (View start, int x, int y, out int resx, out int resy)
  1618. {
  1619. var startFrame = start.Frame;
  1620. if (!startFrame.Contains (x, y)) {
  1621. resx = 0;
  1622. resy = 0;
  1623. return null;
  1624. }
  1625. if (start.InternalSubviews != null){
  1626. int count = start.InternalSubviews.Count;
  1627. if (count > 0) {
  1628. var rx = x - startFrame.X;
  1629. var ry = y - startFrame.Y;
  1630. for (int i = count - 1; i >= 0; i--) {
  1631. View v = start.InternalSubviews [i];
  1632. if (v.Frame.Contains (rx, ry)) {
  1633. var deep = FindDeepestView (v, rx, ry, out resx, out resy);
  1634. if (deep == null)
  1635. return v;
  1636. return deep;
  1637. }
  1638. }
  1639. }
  1640. }
  1641. resx = x-startFrame.X;
  1642. resy = y-startFrame.Y;
  1643. return start;
  1644. }
  1645. static View mouseGrabView;
  1646. /// <summary>
  1647. /// Grabs the mouse, forcing all mouse events to be routed to the specified view until UngrabMouse is called.
  1648. /// </summary>
  1649. /// <returns>The grab.</returns>
  1650. /// <param name="view">View that will receive all mouse events until UngrabMouse is invoked.</param>
  1651. public static void GrabMouse (View view)
  1652. {
  1653. if (view == null)
  1654. return;
  1655. mouseGrabView = view;
  1656. Driver.UncookMouse ();
  1657. }
  1658. /// <summary>
  1659. /// Releases the mouse grab, so mouse events will be routed to the view on which the mouse is.
  1660. /// </summary>
  1661. public static void UngrabMouse ()
  1662. {
  1663. mouseGrabView = null;
  1664. Driver.CookMouse ();
  1665. }
  1666. /// <summary>
  1667. /// Merely a debugging aid to see the raw mouse events
  1668. /// </summary>
  1669. static public Action<MouseEvent> RootMouseEvent;
  1670. static void ProcessMouseEvent (MouseEvent me)
  1671. {
  1672. RootMouseEvent?.Invoke (me);
  1673. if (mouseGrabView != null) {
  1674. var newxy = mouseGrabView.ScreenToView (me.X, me.Y);
  1675. var nme = new MouseEvent () {
  1676. X = newxy.X,
  1677. Y = newxy.Y,
  1678. Flags = me.Flags
  1679. };
  1680. mouseGrabView.MouseEvent (me);
  1681. return;
  1682. }
  1683. int rx, ry;
  1684. var view = FindDeepestView (Current, me.X, me.Y, out rx, out ry);
  1685. if (view != null) {
  1686. if (!view.WantMousePositionReports && me.Flags == MouseFlags.ReportMousePosition)
  1687. return;
  1688. var nme = new MouseEvent () {
  1689. X = rx,
  1690. Y = ry,
  1691. Flags = me.Flags
  1692. };
  1693. // Should we bubbled up the event, if it is not handled?
  1694. view.MouseEvent (nme);
  1695. }
  1696. }
  1697. /// <summary>
  1698. /// Building block API: Prepares the provided toplevel for execution.
  1699. /// </summary>
  1700. /// <returns>The runstate handle that needs to be passed to the End() method upon completion.</returns>
  1701. /// <param name="toplevel">Toplevel to prepare execution for.</param>
  1702. /// <remarks>
  1703. /// This method prepares the provided toplevel for running with the focus,
  1704. /// it adds this to the list of toplevels, sets up the mainloop to process the
  1705. /// event, lays out the subviews, focuses the first element, and draws the
  1706. /// toplevel in the screen. This is usually followed by executing
  1707. /// the <see cref="RunLoop"/> method, and then the <see cref="End(RunState)"/> method upon termination which will
  1708. /// undo these changes.
  1709. /// </remarks>
  1710. static public RunState Begin (Toplevel toplevel)
  1711. {
  1712. if (toplevel == null)
  1713. throw new ArgumentNullException (nameof (toplevel));
  1714. var rs = new RunState (toplevel);
  1715. Init ();
  1716. if (toplevel is ISupportInitializeNotification initializableNotification &&
  1717. !initializableNotification.IsInitialized) {
  1718. initializableNotification.BeginInit();
  1719. initializableNotification.EndInit();
  1720. } else if (toplevel is ISupportInitialize initializable) {
  1721. initializable.BeginInit();
  1722. initializable.EndInit();
  1723. }
  1724. toplevels.Push (toplevel);
  1725. Current = toplevel;
  1726. Driver.PrepareToRun (MainLoop, ProcessKeyEvent, ProcessMouseEvent);
  1727. if (toplevel.LayoutStyle == LayoutStyle.Computed)
  1728. toplevel.RelativeLayout (new Rect (0, 0, Driver.Cols, Driver.Rows));
  1729. toplevel.LayoutSubviews ();
  1730. toplevel.WillPresent ();
  1731. Redraw (toplevel);
  1732. toplevel.PositionCursor ();
  1733. Driver.Refresh ();
  1734. return rs;
  1735. }
  1736. /// <summary>
  1737. /// Building block API: completes the exection of a Toplevel that was started with Begin.
  1738. /// </summary>
  1739. /// <param name="runState">The runstate returned by the <see cref="Begin(Toplevel)"/> method.</param>
  1740. static public void End (RunState runState)
  1741. {
  1742. if (runState == null)
  1743. throw new ArgumentNullException (nameof (runState));
  1744. runState.Dispose ();
  1745. }
  1746. static void Shutdown ()
  1747. {
  1748. Driver.End ();
  1749. }
  1750. static void Redraw (View view)
  1751. {
  1752. view.Redraw (view.Bounds);
  1753. Driver.Refresh ();
  1754. }
  1755. static void Refresh (View view)
  1756. {
  1757. view.Redraw (view.Bounds);
  1758. Driver.Refresh ();
  1759. }
  1760. /// <summary>
  1761. /// Triggers a refresh of the entire display.
  1762. /// </summary>
  1763. public static void Refresh ()
  1764. {
  1765. Driver.UpdateScreen ();
  1766. View last = null;
  1767. foreach (var v in toplevels.Reverse ()) {
  1768. v.SetNeedsDisplay ();
  1769. v.Redraw (v.Bounds);
  1770. last = v;
  1771. }
  1772. last?.PositionCursor ();
  1773. Driver.Refresh ();
  1774. }
  1775. internal static void End (View view)
  1776. {
  1777. if (toplevels.Peek () != view)
  1778. throw new ArgumentException ("The view that you end with must be balanced");
  1779. toplevels.Pop ();
  1780. if (toplevels.Count == 0)
  1781. Shutdown ();
  1782. else
  1783. {
  1784. Current = toplevels.Peek();
  1785. Refresh ();
  1786. }
  1787. }
  1788. /// <summary>
  1789. /// Building block API: Runs the main loop for the created dialog
  1790. /// </summary>
  1791. /// <remarks>
  1792. /// Use the wait parameter to control whether this is a
  1793. /// blocking or non-blocking call.
  1794. /// </remarks>
  1795. /// <param name="state">The state returned by the Begin method.</param>
  1796. /// <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>
  1797. public static void RunLoop (RunState state, bool wait = true)
  1798. {
  1799. if (state == null)
  1800. throw new ArgumentNullException (nameof (state));
  1801. if (state.Toplevel == null)
  1802. throw new ObjectDisposedException ("state");
  1803. for (state.Toplevel.Running = true; state.Toplevel.Running;) {
  1804. if (MainLoop.EventsPending (wait)) {
  1805. MainLoop.MainIteration ();
  1806. if (Iteration != null)
  1807. Iteration (null, EventArgs.Empty);
  1808. } else if (wait == false)
  1809. return;
  1810. if (!state.Toplevel.NeedDisplay.IsEmpty || state.Toplevel.childNeedsDisplay) {
  1811. state.Toplevel.Redraw (state.Toplevel.Bounds);
  1812. if (DebugDrawBounds)
  1813. DrawBounds (state.Toplevel);
  1814. state.Toplevel.PositionCursor ();
  1815. Driver.Refresh ();
  1816. } else
  1817. Driver.UpdateCursor ();
  1818. }
  1819. }
  1820. internal static bool DebugDrawBounds;
  1821. // Need to look into why this does not work properly.
  1822. static void DrawBounds (View v)
  1823. {
  1824. v.DrawFrame (v.Frame, padding: 0, fill: false);
  1825. if (v.InternalSubviews != null && v.InternalSubviews.Count > 0)
  1826. foreach (var sub in v.InternalSubviews)
  1827. DrawBounds (sub);
  1828. }
  1829. /// <summary>
  1830. /// Runs the application with the built-in toplevel view
  1831. /// </summary>
  1832. public static void Run ()
  1833. {
  1834. Run (Top);
  1835. }
  1836. /// <summary>
  1837. /// Runs the application with a new instance of the specified toplevel view
  1838. /// </summary>
  1839. public static void Run<T> () where T : Toplevel, new()
  1840. {
  1841. Init (() => new T());
  1842. Run (Top);
  1843. }
  1844. /// <summary>
  1845. /// Runs the main loop on the given container.
  1846. /// </summary>
  1847. /// <remarks>
  1848. /// <para>
  1849. /// This method is used to start processing events
  1850. /// for the main application, but it is also used to
  1851. /// run modal dialog boxes.
  1852. /// </para>
  1853. /// <para>
  1854. /// To make a toplevel stop execution, set the "Running"
  1855. /// property to false.
  1856. /// </para>
  1857. /// <para>
  1858. /// This is equivalent to calling Begin on the toplevel view, followed by RunLoop with the
  1859. /// returned value, and then calling end on the return value.
  1860. /// </para>
  1861. /// <para>
  1862. /// Alternatively, if your program needs to control the main loop and needs to
  1863. /// process events manually, you can invoke Begin to set things up manually and then
  1864. /// repeatedly call RunLoop with the wait parameter set to false. By doing this
  1865. /// the RunLoop method will only process any pending events, timers, idle handlers and
  1866. /// then return control immediately.
  1867. /// </para>
  1868. /// </remarks>
  1869. public static void Run (Toplevel view)
  1870. {
  1871. var runToken = Begin (view);
  1872. RunLoop (runToken);
  1873. End (runToken);
  1874. }
  1875. /// <summary>
  1876. /// Stops running the most recent toplevel
  1877. /// </summary>
  1878. public static void RequestStop ()
  1879. {
  1880. Current.Running = false;
  1881. }
  1882. static void TerminalResized ()
  1883. {
  1884. var full = new Rect (0, 0, Driver.Cols, Driver.Rows);
  1885. Driver.Clip = full;
  1886. foreach (var t in toplevels) {
  1887. t.RelativeLayout (full);
  1888. t.LayoutSubviews ();
  1889. }
  1890. Refresh ();
  1891. }
  1892. }
  1893. }