Core.cs 55 KB

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