Core.cs 59 KB

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