Core.cs 61 KB

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