Core.cs 56 KB

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