Core.cs 67 KB

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