Core.cs 59 KB

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