Core.cs 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963
  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. }
  671. }
  672. /// <summary>
  673. /// Returns the currently focused view inside this view, or null if nothing is focused.
  674. /// </summary>
  675. /// <value>The focused.</value>
  676. public View Focused => focused;
  677. /// <summary>
  678. /// Returns the most focused view in the chain of subviews (the leaf view that has the focus).
  679. /// </summary>
  680. /// <value>The most focused.</value>
  681. public View MostFocused {
  682. get {
  683. if (Focused == null)
  684. return null;
  685. var most = Focused.MostFocused;
  686. if (most != null)
  687. return most;
  688. return Focused;
  689. }
  690. }
  691. /// <summary>
  692. /// The color scheme for this view, if it is not defined, it returns the parent's
  693. /// color scheme.
  694. /// </summary>
  695. public ColorScheme ColorScheme {
  696. get {
  697. if (colorScheme == null)
  698. return SuperView?.ColorScheme;
  699. return colorScheme;
  700. }
  701. set {
  702. colorScheme = value;
  703. }
  704. }
  705. ColorScheme colorScheme;
  706. /// <summary>
  707. /// Displays the specified character in the specified column and row.
  708. /// </summary>
  709. /// <param name="col">Col.</param>
  710. /// <param name="row">Row.</param>
  711. /// <param name="ch">Ch.</param>
  712. public void AddRune (int col, int row, Rune ch)
  713. {
  714. if (row < 0 || col < 0)
  715. return;
  716. if (row > frame.Height - 1 || col > frame.Width - 1)
  717. return;
  718. Move (col, row);
  719. Driver.AddRune (ch);
  720. }
  721. /// <summary>
  722. /// Removes the SetNeedsDisplay and the ChildNeedsDisplay setting on this view.
  723. /// </summary>
  724. protected void ClearNeedsDisplay ()
  725. {
  726. NeedDisplay = Rect.Empty;
  727. childNeedsDisplay = false;
  728. }
  729. /// <summary>
  730. /// Performs a redraw of this view and its subviews, only redraws the views that have been flagged for a re-display.
  731. /// </summary>
  732. /// <param name="region">The region to redraw, this is relative to the view itself.</param>
  733. /// <remarks>
  734. /// <para>
  735. /// Views should set the color that they want to use on entry, as otherwise this will inherit
  736. /// the last color that was set globaly on the driver.
  737. /// </para>
  738. /// </remarks>
  739. public virtual void Redraw (Rect region)
  740. {
  741. var clipRect = new Rect (Point.Empty, frame.Size);
  742. if (subviews != null) {
  743. foreach (var view in subviews) {
  744. if (!view.NeedDisplay.IsEmpty || view.childNeedsDisplay) {
  745. if (view.Frame.IntersectsWith (clipRect) && view.Frame.IntersectsWith (region)) {
  746. // TODO: optimize this by computing the intersection of region and view.Bounds
  747. view.Redraw (view.Bounds);
  748. }
  749. view.NeedDisplay = Rect.Empty;
  750. view.childNeedsDisplay = false;
  751. }
  752. }
  753. }
  754. ClearNeedsDisplay ();
  755. }
  756. /// <summary>
  757. /// Focuses the specified sub-view.
  758. /// </summary>
  759. /// <param name="view">View.</param>
  760. public void SetFocus (View view)
  761. {
  762. if (view == null)
  763. return;
  764. //Console.WriteLine ($"Request to focus {view}");
  765. if (!view.CanFocus)
  766. return;
  767. if (focused == view)
  768. return;
  769. // Make sure that this view is a subview
  770. View c;
  771. for (c = view.container; c != null; c = c.container)
  772. if (c == this)
  773. break;
  774. if (c == null)
  775. throw new ArgumentException ("the specified view is not part of the hierarchy of this view");
  776. if (focused != null)
  777. focused.HasFocus = false;
  778. focused = view;
  779. focused.HasFocus = true;
  780. focused.EnsureFocus ();
  781. }
  782. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  783. public override bool ProcessKey (KeyEvent keyEvent)
  784. {
  785. if (Focused?.ProcessKey (keyEvent) == true)
  786. return true;
  787. return false;
  788. }
  789. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  790. public override bool ProcessHotKey (KeyEvent keyEvent)
  791. {
  792. if (subviews == null || subviews.Count == 0)
  793. return false;
  794. foreach (var view in subviews)
  795. if (view.ProcessHotKey (keyEvent))
  796. return true;
  797. return false;
  798. }
  799. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  800. public override bool ProcessColdKey (KeyEvent keyEvent)
  801. {
  802. if (subviews == null || subviews.Count == 0)
  803. return false;
  804. foreach (var view in subviews)
  805. if (view.ProcessColdKey (keyEvent))
  806. return true;
  807. return false;
  808. }
  809. /// <summary>
  810. /// Finds the first view in the hierarchy that wants to get the focus if nothing is currently focused, otherwise, it does nothing.
  811. /// </summary>
  812. public void EnsureFocus ()
  813. {
  814. if (focused == null)
  815. FocusFirst ();
  816. }
  817. /// <summary>
  818. /// Focuses the first focusable subview if one exists.
  819. /// </summary>
  820. public void FocusFirst ()
  821. {
  822. if (subviews == null) {
  823. SuperView.SetFocus (this);
  824. return;
  825. }
  826. foreach (var view in subviews) {
  827. if (view.CanFocus) {
  828. SetFocus (view);
  829. return;
  830. }
  831. }
  832. }
  833. /// <summary>
  834. /// Focuses the last focusable subview if one exists.
  835. /// </summary>
  836. public void FocusLast ()
  837. {
  838. if (subviews == null)
  839. return;
  840. for (int i = subviews.Count; i > 0;) {
  841. i--;
  842. View v = subviews [i];
  843. if (v.CanFocus) {
  844. SetFocus (v);
  845. return;
  846. }
  847. }
  848. }
  849. /// <summary>
  850. /// Focuses the previous view.
  851. /// </summary>
  852. /// <returns><c>true</c>, if previous was focused, <c>false</c> otherwise.</returns>
  853. public bool FocusPrev ()
  854. {
  855. if (subviews == null || subviews.Count == 0)
  856. return false;
  857. if (focused == null) {
  858. FocusLast ();
  859. return true;
  860. }
  861. int focused_idx = -1;
  862. for (int i = subviews.Count; i > 0;) {
  863. i--;
  864. View w = subviews [i];
  865. if (w.HasFocus) {
  866. if (w.FocusPrev ())
  867. return true;
  868. focused_idx = i;
  869. continue;
  870. }
  871. if (w.CanFocus && focused_idx != -1) {
  872. focused.HasFocus = false;
  873. if (w.CanFocus)
  874. w.FocusLast ();
  875. SetFocus (w);
  876. return true;
  877. }
  878. }
  879. if (focused_idx != -1) {
  880. FocusLast ();
  881. return true;
  882. }
  883. if (focused != null) {
  884. focused.HasFocus = false;
  885. focused = null;
  886. }
  887. return false;
  888. }
  889. /// <summary>
  890. /// Focuses the next view.
  891. /// </summary>
  892. /// <returns><c>true</c>, if next was focused, <c>false</c> otherwise.</returns>
  893. public bool FocusNext ()
  894. {
  895. if (subviews == null || subviews.Count == 0)
  896. return false;
  897. if (focused == null) {
  898. FocusFirst ();
  899. return focused != null;
  900. }
  901. int n = subviews.Count;
  902. int focused_idx = -1;
  903. for (int i = 0; i < n; i++) {
  904. View w = subviews [i];
  905. if (w.HasFocus) {
  906. if (w.FocusNext ())
  907. return true;
  908. focused_idx = i;
  909. continue;
  910. }
  911. if (w.CanFocus && focused_idx != -1) {
  912. focused.HasFocus = false;
  913. if (w != null && w.CanFocus)
  914. w.FocusFirst ();
  915. SetFocus (w);
  916. return true;
  917. }
  918. }
  919. if (focused != null) {
  920. focused.HasFocus = false;
  921. focused = null;
  922. }
  923. return false;
  924. }
  925. /// <summary>
  926. /// Computes the RelativeLayout for the view, given the frame for its container.
  927. /// </summary>
  928. /// <param name="hostFrame">The Frame for the host.</param>
  929. internal void RelativeLayout (Rect hostFrame)
  930. {
  931. int w, h, _x, _y;
  932. if (x is Pos.PosCenter) {
  933. if (width == null)
  934. w = hostFrame.Width;
  935. else
  936. w = width.Anchor (hostFrame.Width);
  937. _x = x.Anchor (hostFrame.Width - w);
  938. } else {
  939. if (x == null)
  940. _x = 0;
  941. else
  942. _x = x.Anchor (hostFrame.Width);
  943. if (width == null)
  944. w = hostFrame.Width;
  945. else
  946. w = width.Anchor (hostFrame.Width - _x);
  947. }
  948. if (y is Pos.PosCenter) {
  949. if (height == null)
  950. h = hostFrame.Height;
  951. else
  952. h = height.Anchor (hostFrame.Height);
  953. _y = y.Anchor (hostFrame.Height - h);
  954. } else {
  955. if (y == null)
  956. _y = 0;
  957. else
  958. _y = y.Anchor (hostFrame.Height);
  959. if (height == null)
  960. h = hostFrame.Height;
  961. else
  962. h = height.Anchor (hostFrame.Height - _y);
  963. }
  964. Frame = new Rect (_x, _y, w, h);
  965. }
  966. // https://en.wikipedia.org/wiki/Topological_sorting
  967. static List<View> TopologicalSort (HashSet<View> nodes, HashSet<(View, View)> edges)
  968. {
  969. var result = new List<View> ();
  970. // Set of all nodes with no incoming edges
  971. var S = new HashSet<View> (nodes.Where (n => edges.All (e => e.Item2.Equals (n) == false)));
  972. while (S.Any ()) {
  973. // remove a node n from S
  974. var n = S.First ();
  975. S.Remove (n);
  976. // add n to tail of L
  977. result.Add (n);
  978. // for each node m with an edge e from n to m do
  979. foreach (var e in edges.Where (e => e.Item1.Equals (n)).ToList ()) {
  980. var m = e.Item2;
  981. // remove edge e from the graph
  982. edges.Remove (e);
  983. // if m has no other incoming edges then
  984. if (edges.All (me => me.Item2.Equals (m) == false)) {
  985. // insert m into S
  986. S.Add (m);
  987. }
  988. }
  989. }
  990. // if graph has edges then
  991. if (edges.Any ()) {
  992. // return error (graph has at least one cycle)
  993. return null;
  994. } else {
  995. // return L (a topologically sorted order)
  996. return result;
  997. }
  998. }
  999. /// <summary>
  1000. /// This virtual method is invoked when a view starts executing or
  1001. /// when the dimensions of the view have changed, for example in
  1002. /// response to the container view or terminal resizing.
  1003. /// </summary>
  1004. public virtual void LayoutSubviews ()
  1005. {
  1006. if (!layoutNeeded)
  1007. return;
  1008. // Sort out the dependencies of the X, Y, Width, Height properties
  1009. var nodes = new HashSet<View> ();
  1010. var edges = new HashSet<(View, View)> ();
  1011. foreach (var v in Subviews) {
  1012. nodes.Add (v);
  1013. if (v.LayoutStyle == LayoutStyle.Computed) {
  1014. if (v.X is Pos.PosView)
  1015. edges.Add ((v, (v.X as Pos.PosView).Target));
  1016. if (v.Y is Pos.PosView)
  1017. edges.Add ((v, (v.Y as Pos.PosView).Target));
  1018. if (v.Width is Dim.DimView)
  1019. edges.Add ((v, (v.Width as Dim.DimView).Target));
  1020. if (v.Height is Dim.DimView)
  1021. edges.Add ((v, (v.Height as Dim.DimView).Target));
  1022. }
  1023. }
  1024. var ordered = TopologicalSort (nodes, edges);
  1025. ordered.Reverse ();
  1026. if (ordered == null)
  1027. throw new Exception ("There is a recursive cycle in the relative Pos/Dim in the views of " + this);
  1028. foreach (var v in ordered) {
  1029. if (v.LayoutStyle == LayoutStyle.Computed)
  1030. v.RelativeLayout (Frame);
  1031. v.LayoutSubviews ();
  1032. v.layoutNeeded = false;
  1033. }
  1034. layoutNeeded = false;
  1035. }
  1036. /// <summary>
  1037. /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:Terminal.Gui.View"/>.
  1038. /// </summary>
  1039. /// <returns>A <see cref="T:System.String"/> that represents the current <see cref="T:Terminal.Gui.View"/>.</returns>
  1040. public override string ToString ()
  1041. {
  1042. return $"{GetType ().Name}({Id})({Frame})";
  1043. }
  1044. }
  1045. /// <summary>
  1046. /// Toplevel views can be modally executed.
  1047. /// </summary>
  1048. /// <remarks>
  1049. /// <para>
  1050. /// Toplevels can be modally executing views, and they return control
  1051. /// to the caller when the "Running" property is set to false, or
  1052. /// by calling <see cref="M:Terminal.Gui.Application.RequestStop()"/>
  1053. /// </para>
  1054. /// <para>
  1055. /// There will be a toplevel created for you on the first time use
  1056. /// and can be accessed from the property <see cref="P:Terminal.Gui.Application.Top"/>,
  1057. /// but new toplevels can be created and ran on top of it. To run, create the
  1058. /// toplevel and then invoke <see cref="M:Terminal.Gui.Application.Run"/> with the
  1059. /// new toplevel.
  1060. /// </para>
  1061. /// </remarks>
  1062. public class Toplevel : View {
  1063. /// <summary>
  1064. /// This flag is checked on each iteration of the mainloop and it continues
  1065. /// running until this flag is set to false.
  1066. /// </summary>
  1067. public bool Running;
  1068. /// <summary>
  1069. /// Initializes a new instance of the <see cref="T:Terminal.Gui.Toplevel"/> class with the specified absolute layout.
  1070. /// </summary>
  1071. /// <param name="frame">Frame.</param>
  1072. public Toplevel (Rect frame) : base (frame)
  1073. {
  1074. ColorScheme = Colors.Base;
  1075. }
  1076. /// <summary>
  1077. /// Initializes a new instance of the <see cref="T:Terminal.Gui.Toplevel"/> class with Computed layout, defaulting to <see langword="async"/> full screen.
  1078. /// </summary>
  1079. public Toplevel () : base ()
  1080. {
  1081. ColorScheme = Colors.Base;
  1082. Width = Dim.Fill ();
  1083. Height = Dim.Fill ();
  1084. }
  1085. /// <summary>
  1086. /// Convenience factory method that creates a new toplevel with the current terminal dimensions.
  1087. /// </summary>
  1088. /// <returns>The create.</returns>
  1089. public static Toplevel Create ()
  1090. {
  1091. return new Toplevel (new Rect (0, 0, Driver.Cols, Driver.Rows));
  1092. }
  1093. public override bool CanFocus {
  1094. get => true;
  1095. }
  1096. public override bool ProcessKey (KeyEvent keyEvent)
  1097. {
  1098. if (base.ProcessKey (keyEvent))
  1099. return true;
  1100. switch (keyEvent.Key) {
  1101. case Key.ControlC:
  1102. // TODO: stop current execution of this container
  1103. break;
  1104. case Key.ControlZ:
  1105. Driver.Suspend ();
  1106. return true;
  1107. #if false
  1108. case Key.F5:
  1109. Application.DebugDrawBounds = !Application.DebugDrawBounds;
  1110. SetNeedsDisplay ();
  1111. return true;
  1112. #endif
  1113. case Key.Tab:
  1114. case Key.CursorRight:
  1115. case Key.CursorDown:
  1116. var old = Focused;
  1117. if (!FocusNext ())
  1118. FocusNext ();
  1119. if (old != Focused) {
  1120. old?.SetNeedsDisplay ();
  1121. Focused?.SetNeedsDisplay ();
  1122. }
  1123. return true;
  1124. case Key.CursorLeft:
  1125. case Key.CursorUp:
  1126. case Key.BackTab:
  1127. old = Focused;
  1128. if (!FocusPrev ())
  1129. FocusPrev ();
  1130. if (old != Focused) {
  1131. old?.SetNeedsDisplay ();
  1132. Focused?.SetNeedsDisplay ();
  1133. }
  1134. return true;
  1135. case Key.ControlL:
  1136. Application.Refresh ();
  1137. return true;
  1138. }
  1139. return false;
  1140. }
  1141. /// <summary>
  1142. /// This method is invoked by Application.Begin as part of the Application.Run after
  1143. /// the views have been laid out, and before the views are drawn for the first time.
  1144. /// </summary>
  1145. public virtual void WillPresent ()
  1146. {
  1147. FocusFirst ();
  1148. }
  1149. }
  1150. /// <summary>
  1151. /// A toplevel view that draws a frame around its region and has a "ContentView" subview where the contents are added.
  1152. /// </summary>
  1153. public class Window : Toplevel, IEnumerable {
  1154. View contentView;
  1155. ustring title;
  1156. /// <summary>
  1157. /// The title to be displayed for this window.
  1158. /// </summary>
  1159. /// <value>The title.</value>
  1160. public ustring Title {
  1161. get => title;
  1162. set {
  1163. title = value;
  1164. SetNeedsDisplay ();
  1165. }
  1166. }
  1167. class ContentView : View {
  1168. public ContentView (Rect frame) : base (frame) { }
  1169. public ContentView () : base () { }
  1170. #if false
  1171. public override void Redraw (Rect region)
  1172. {
  1173. Driver.SetAttribute (ColorScheme.Focus);
  1174. for (int y = 0; y < Frame.Height; y++) {
  1175. Move (0, y);
  1176. for (int x = 0; x < Frame.Width; x++) {
  1177. Driver.AddRune ('x');
  1178. }
  1179. }
  1180. }
  1181. #endif
  1182. }
  1183. /// <summary>
  1184. /// Initializes a new instance of the <see cref="T:Terminal.Gui.Gui.Window"/> class with an optional title and a set frame.
  1185. /// </summary>
  1186. /// <param name="frame">Frame.</param>
  1187. /// <param name="title">Title.</param>
  1188. public Window (Rect frame, ustring title = null) : this (frame, title, padding: 0)
  1189. {
  1190. }
  1191. /// <summary>
  1192. /// Initializes a new instance of the <see cref="T:Terminal.Gui.Window"/> class with an optional title.
  1193. /// </summary>
  1194. /// <param name="title">Title.</param>
  1195. public Window (ustring title = null) : this (title, padding: 0)
  1196. {
  1197. }
  1198. int padding;
  1199. /// <summary>
  1200. /// Initializes a new instance of the <see cref="T:Terminal.Gui.Window"/> with
  1201. /// the specified frame for its location, with the specified border
  1202. /// an optional title.
  1203. /// </summary>
  1204. /// <param name="frame">Frame.</param>
  1205. /// <param name="padding">Number of characters to use for padding of the drawn frame.</param>
  1206. /// <param name="title">Title.</param>
  1207. public Window (Rect frame, ustring title = null, int padding = 0) : base (frame)
  1208. {
  1209. this.Title = title;
  1210. int wb = 2 * (1 + padding);
  1211. this.padding = padding;
  1212. var cFrame = new Rect (1 + padding, 1 + padding, frame.Width - wb, frame.Height - wb);
  1213. contentView = new ContentView (cFrame);
  1214. base.Add (contentView);
  1215. }
  1216. /// <summary>
  1217. /// Initializes a new instance of the <see cref="T:Terminal.Gui.Window"/> with
  1218. /// the specified frame for its location, with the specified border
  1219. /// an optional title.
  1220. /// </summary>
  1221. /// <param name="padding">Number of characters to use for padding of the drawn frame.</param>
  1222. /// <param name="title">Title.</param>
  1223. public Window (ustring title = null, int padding = 0) : base ()
  1224. {
  1225. this.Title = title;
  1226. int wb = 1 + padding;
  1227. this.padding = padding;
  1228. contentView = new ContentView () {
  1229. X = wb,
  1230. Y = wb,
  1231. Width = Dim.Fill (wb),
  1232. Height = Dim.Fill (wb)
  1233. };
  1234. base.Add (contentView);
  1235. }
  1236. /// <summary>
  1237. /// Enumerates the various views in the ContentView.
  1238. /// </summary>
  1239. /// <returns>The enumerator.</returns>
  1240. public new IEnumerator GetEnumerator ()
  1241. {
  1242. return contentView.GetEnumerator ();
  1243. }
  1244. void DrawFrame ()
  1245. {
  1246. DrawFrame (new Rect (0, 0, Frame.Width, Frame.Height), padding, fill: true);
  1247. }
  1248. /// <summary>
  1249. /// Add the specified view to the ContentView.
  1250. /// </summary>
  1251. /// <param name="view">View to add to the window.</param>
  1252. public override void Add (View view)
  1253. {
  1254. contentView.Add (view);
  1255. if (view.CanFocus)
  1256. CanFocus = true;
  1257. }
  1258. /// <summary>
  1259. /// Removes a widget from this container.
  1260. /// </summary>
  1261. /// <remarks>
  1262. /// </remarks>
  1263. public override void Remove (View view)
  1264. {
  1265. if (view == null)
  1266. return;
  1267. SetNeedsDisplay ();
  1268. var touched = view.Frame;
  1269. contentView.Remove (view);
  1270. if (contentView.Subviews.Count < 1)
  1271. this.CanFocus = false;
  1272. }
  1273. public override void Redraw (Rect bounds)
  1274. {
  1275. if (!NeedDisplay.IsEmpty) {
  1276. Driver.SetAttribute (ColorScheme.Normal);
  1277. DrawFrame ();
  1278. if (HasFocus)
  1279. Driver.SetAttribute (ColorScheme.Normal);
  1280. var width = Frame.Width;
  1281. if (Title != null && width > 4) {
  1282. Move (1+padding, padding);
  1283. Driver.AddRune (' ');
  1284. var str = Title.Length > width ? Title [0, width-4] : Title;
  1285. Driver.AddStr (str);
  1286. Driver.AddRune (' ');
  1287. }
  1288. Driver.SetAttribute (ColorScheme.Normal);
  1289. }
  1290. contentView.Redraw (contentView.Bounds);
  1291. ClearNeedsDisplay ();
  1292. }
  1293. #if true
  1294. //
  1295. // It does not look like the event is raised on clicked-drag
  1296. // need to figure that out.
  1297. //
  1298. Point? dragPosition;
  1299. public override bool MouseEvent(MouseEvent mouseEvent)
  1300. {
  1301. // The code is currently disabled, because the
  1302. // Driver.UncookMouse does not seem to have an effect if there is
  1303. // a pending mouse event activated.
  1304. if (true)
  1305. return false;
  1306. if ((mouseEvent.Flags == MouseFlags.Button1Pressed|| mouseEvent.Flags == MouseFlags.Button4Pressed)){
  1307. if (dragPosition.HasValue) {
  1308. var dx = mouseEvent.X - dragPosition.Value.X;
  1309. var dy = mouseEvent.Y - dragPosition.Value.Y;
  1310. var nx = Frame.X + dx;
  1311. var ny = Frame.Y + dy;
  1312. if (nx < 0)
  1313. nx = 0;
  1314. if (ny < 0)
  1315. ny = 0;
  1316. //Demo.ml2.Text = $"{dx},{dy}";
  1317. dragPosition = new Point (mouseEvent.X, mouseEvent.Y);
  1318. // TODO: optimize, only SetNeedsDisplay on the before/after regions.
  1319. if (SuperView == null)
  1320. Application.Refresh ();
  1321. else
  1322. SuperView.SetNeedsDisplay ();
  1323. Frame = new Rect (nx, ny, Frame.Width, Frame.Height);
  1324. SetNeedsDisplay ();
  1325. return true;
  1326. } else {
  1327. // Only start grabbing if the user clicks on the title bar.
  1328. if (mouseEvent.Y == 0) {
  1329. dragPosition = new Point (mouseEvent.X, mouseEvent.Y);
  1330. Application.GrabMouse (this);
  1331. }
  1332. //Demo.ml2.Text = $"Starting at {dragPosition}";
  1333. return true;
  1334. }
  1335. }
  1336. if (mouseEvent.Flags == MouseFlags.Button1Released) {
  1337. Application.UngrabMouse ();
  1338. Driver.UncookMouse ();
  1339. dragPosition = null;
  1340. //Driver.StopReportingMouseMoves ();
  1341. }
  1342. //Demo.ml.Text = me.ToString ();
  1343. return false;
  1344. }
  1345. #endif
  1346. }
  1347. /// <summary>
  1348. /// The application driver for gui.cs
  1349. /// </summary>
  1350. /// <remarks>
  1351. /// <para>
  1352. /// You can hook up to the Iteration event to have your method
  1353. /// invoked on each iteration of the mainloop.
  1354. /// </para>
  1355. /// <para>
  1356. /// Creates a mainloop to process input events, handle timers and
  1357. /// other sources of data. It is accessible via the MainLoop property.
  1358. /// </para>
  1359. /// <para>
  1360. /// When invoked sets the SynchronizationContext to one that is tied
  1361. /// to the mainloop, allowing user code to use async/await.
  1362. /// </para>
  1363. /// </remarks>
  1364. public static class Application {
  1365. /// <summary>
  1366. /// The current Console Driver in use.
  1367. /// </summary>
  1368. public static ConsoleDriver Driver;
  1369. /// <summary>
  1370. /// The Toplevel object used for the application on startup.
  1371. /// </summary>
  1372. /// <value>The top.</value>
  1373. public static Toplevel Top { get; private set; }
  1374. /// <summary>
  1375. /// The current toplevel object. This is updated when Application.Run enters and leaves and points to the current toplevel.
  1376. /// </summary>
  1377. /// <value>The current.</value>
  1378. public static Toplevel Current { get; private set; }
  1379. /// <summary>
  1380. /// The mainloop driver for the applicaiton
  1381. /// </summary>
  1382. /// <value>The main loop.</value>
  1383. public static Mono.Terminal.MainLoop MainLoop { get; private set; }
  1384. static Stack<Toplevel> toplevels = new Stack<Toplevel> ();
  1385. /// <summary>
  1386. /// This event is raised on each iteration of the
  1387. /// main loop.
  1388. /// </summary>
  1389. /// <remarks>
  1390. /// See also <see cref="Timeout"/>
  1391. /// </remarks>
  1392. static public event EventHandler Iteration;
  1393. /// <summary>
  1394. /// Returns a rectangle that is centered in the screen for the provided size.
  1395. /// </summary>
  1396. /// <returns>The centered rect.</returns>
  1397. /// <param name="size">Size for the rectangle.</param>
  1398. public static Rect MakeCenteredRect (Size size)
  1399. {
  1400. return new Rect (new Point ((Driver.Cols - size.Width) / 2, (Driver.Rows - size.Height) / 2), size);
  1401. }
  1402. //
  1403. // provides the sync context set while executing code in gui.cs, to let
  1404. // users use async/await on their code
  1405. //
  1406. class MainLoopSyncContext : SynchronizationContext {
  1407. Mono.Terminal.MainLoop mainLoop;
  1408. public MainLoopSyncContext (Mono.Terminal.MainLoop mainLoop)
  1409. {
  1410. this.mainLoop = mainLoop;
  1411. }
  1412. public override SynchronizationContext CreateCopy ()
  1413. {
  1414. return new MainLoopSyncContext (MainLoop);
  1415. }
  1416. public override void Post (SendOrPostCallback d, object state)
  1417. {
  1418. mainLoop.AddIdle (() => {
  1419. d (state);
  1420. return false;
  1421. });
  1422. }
  1423. public override void Send (SendOrPostCallback d, object state)
  1424. {
  1425. mainLoop.Invoke (() => {
  1426. d (state);
  1427. });
  1428. }
  1429. }
  1430. /// <summary>
  1431. /// If set, it forces the use of the System.Console-based driver.
  1432. /// </summary>
  1433. public static bool UseSystemConsole;
  1434. /// <summary>
  1435. /// Initializes the Application
  1436. /// </summary>
  1437. public static void Init ()
  1438. {
  1439. if (Top != null)
  1440. return;
  1441. var p = Environment.OSVersion.Platform;
  1442. Mono.Terminal.IMainLoopDriver mainLoopDriver;
  1443. if (UseSystemConsole) {
  1444. mainLoopDriver = new Mono.Terminal.NetMainLoop ();
  1445. Driver = new NetDriver ();
  1446. } else if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows){
  1447. var windowsDriver = new WindowsDriver ();
  1448. mainLoopDriver = windowsDriver;
  1449. Driver = windowsDriver;
  1450. } else {
  1451. mainLoopDriver = new Mono.Terminal.UnixMainLoop ();
  1452. Driver = new CursesDriver ();
  1453. }
  1454. Driver.Init (TerminalResized);
  1455. MainLoop = new Mono.Terminal.MainLoop (mainLoopDriver);
  1456. SynchronizationContext.SetSynchronizationContext (new MainLoopSyncContext (MainLoop));
  1457. Top = Toplevel.Create ();
  1458. Current = Top;
  1459. }
  1460. /// <summary>
  1461. /// Captures the execution state for the provided TopLevel view.
  1462. /// </summary>
  1463. public class RunState : IDisposable {
  1464. internal RunState (Toplevel view)
  1465. {
  1466. Toplevel = view;
  1467. }
  1468. internal Toplevel Toplevel;
  1469. /// <summary>
  1470. /// Releases alTop = l resource used by the <see cref="T:Terminal.Gui.Application.RunState"/> object.
  1471. /// </summary>
  1472. /// <remarks>Call <see cref="Dispose()"/> when you are finished using the <see cref="T:Terminal.Gui.Application.RunState"/>. The
  1473. /// <see cref="Dispose()"/> method leaves the <see cref="T:Terminal.Gui.Application.RunState"/> in an unusable state. After
  1474. /// calling <see cref="Dispose()"/>, you must release all references to the
  1475. /// <see cref="T:Terminal.Gui.Application.RunState"/> so the garbage collector can reclaim the memory that the
  1476. /// <see cref="T:Terminal.Gui.Application.RunState"/> was occupying.</remarks>
  1477. public void Dispose ()
  1478. {
  1479. Dispose (true);
  1480. GC.SuppressFinalize (this);
  1481. }
  1482. /// <summary>
  1483. /// Dispose the specified disposing.
  1484. /// </summary>
  1485. /// <returns>The dispose.</returns>
  1486. /// <param name="disposing">If set to <c>true</c> disposing.</param>
  1487. protected virtual void Dispose (bool disposing)
  1488. {
  1489. if (Toplevel != null) {
  1490. End (Toplevel);
  1491. Toplevel = null;
  1492. }
  1493. }
  1494. }
  1495. static void ProcessKeyEvent (KeyEvent ke)
  1496. {
  1497. if (Current.ProcessHotKey (ke))
  1498. return;
  1499. if (Current.ProcessKey (ke))
  1500. return;
  1501. // Process the key normally
  1502. if (Current.ProcessColdKey (ke))
  1503. return;
  1504. }
  1505. static View FindDeepestView (View start, int x, int y, out int resx, out int resy)
  1506. {
  1507. var startFrame = start.Frame;
  1508. if (!startFrame.Contains (x, y)) {
  1509. resx = 0;
  1510. resy = 0;
  1511. return null;
  1512. }
  1513. if (start.Subviews != null){
  1514. int count = start.Subviews.Count;
  1515. if (count > 0) {
  1516. var rx = x - startFrame.X;
  1517. var ry = y - startFrame.Y;
  1518. for (int i = count - 1; i >= 0; i--) {
  1519. View v = start.Subviews [i];
  1520. if (v.Frame.Contains (rx, ry)) {
  1521. var deep = FindDeepestView (v, rx, ry, out resx, out resy);
  1522. if (deep == null)
  1523. return v;
  1524. return deep;
  1525. }
  1526. }
  1527. }
  1528. }
  1529. resx = x-startFrame.X;
  1530. resy = y-startFrame.Y;
  1531. return start;
  1532. }
  1533. static View mouseGrabView;
  1534. /// <summary>
  1535. /// Grabs the mouse, forcing all mouse events to be routed to the specified view until UngrabMouse is called.
  1536. /// </summary>
  1537. /// <returns>The grab.</returns>
  1538. /// <param name="view">View that will receive all mouse events until UngrabMouse is invoked.</param>
  1539. public static void GrabMouse (View view)
  1540. {
  1541. if (view == null)
  1542. return;
  1543. mouseGrabView = view;
  1544. Driver.UncookMouse ();
  1545. }
  1546. /// <summary>
  1547. /// Releases the mouse grab, so mouse events will be routed to the view on which the mouse is.
  1548. /// </summary>
  1549. public static void UngrabMouse ()
  1550. {
  1551. mouseGrabView = null;
  1552. Driver.CookMouse ();
  1553. }
  1554. /// <summary>
  1555. /// Merely a debugging aid to see the raw mouse events
  1556. /// </summary>
  1557. static public Action<MouseEvent> RootMouseEvent;
  1558. static void ProcessMouseEvent (MouseEvent me)
  1559. {
  1560. RootMouseEvent?.Invoke (me);
  1561. if (mouseGrabView != null) {
  1562. var newxy = mouseGrabView.ScreenToView (me.X, me.Y);
  1563. var nme = new MouseEvent () {
  1564. X = newxy.X,
  1565. Y = newxy.Y,
  1566. Flags = me.Flags
  1567. };
  1568. mouseGrabView.MouseEvent (me);
  1569. return;
  1570. }
  1571. int rx, ry;
  1572. var view = FindDeepestView (Current, me.X, me.Y, out rx, out ry);
  1573. if (view != null) {
  1574. if (!view.WantMousePositionReports && me.Flags == MouseFlags.ReportMousePosition)
  1575. return;
  1576. var nme = new MouseEvent () {
  1577. X = rx,
  1578. Y = ry,
  1579. Flags = me.Flags
  1580. };
  1581. // Should we bubbled up the event, if it is not handled?
  1582. view.MouseEvent (nme);
  1583. }
  1584. }
  1585. /// <summary>
  1586. /// Building block API: Prepares the provided toplevel for execution.
  1587. /// </summary>
  1588. /// <returns>The runstate handle that needs to be passed to the End() method upon completion.</returns>
  1589. /// <param name="toplevel">Toplevel to prepare execution for.</param>
  1590. /// <remarks>
  1591. /// This method prepares the provided toplevel for running with the focus,
  1592. /// it adds this to the list of toplevels, sets up the mainloop to process the
  1593. /// event, lays out the subviews, focuses the first element, and draws the
  1594. /// toplevel in the screen. This is usually followed by executing
  1595. /// the <see cref="RunLoop"/> method, and then the <see cref="End(RunState)"/> method upon termination which will
  1596. /// undo these changes.
  1597. /// </remarks>
  1598. static public RunState Begin (Toplevel toplevel)
  1599. {
  1600. if (toplevel == null)
  1601. throw new ArgumentNullException (nameof (toplevel));
  1602. var rs = new RunState (toplevel);
  1603. Init ();
  1604. toplevels.Push (toplevel);
  1605. Current = toplevel;
  1606. Driver.PrepareToRun (MainLoop, ProcessKeyEvent, ProcessMouseEvent);
  1607. if (toplevel.LayoutStyle == LayoutStyle.Computed)
  1608. toplevel.RelativeLayout (new Rect (0, 0, Driver.Cols, Driver.Rows));
  1609. toplevel.LayoutSubviews ();
  1610. toplevel.WillPresent ();
  1611. Redraw (toplevel);
  1612. toplevel.PositionCursor ();
  1613. Driver.Refresh ();
  1614. return rs;
  1615. }
  1616. /// <summary>
  1617. /// Building block API: completes the exection of a Toplevel that was started with Begin.
  1618. /// </summary>
  1619. /// <param name="runState">The runstate returned by the <see cref="Begin(Toplevel)"/> method.</param>
  1620. static public void End (RunState runState)
  1621. {
  1622. if (runState == null)
  1623. throw new ArgumentNullException (nameof (runState));
  1624. runState.Dispose ();
  1625. }
  1626. static void Shutdown ()
  1627. {
  1628. Driver.End ();
  1629. }
  1630. static void Redraw (View view)
  1631. {
  1632. view.Redraw (view.Bounds);
  1633. Driver.Refresh ();
  1634. }
  1635. static void Refresh (View view)
  1636. {
  1637. view.Redraw (view.Bounds);
  1638. Driver.Refresh ();
  1639. }
  1640. /// <summary>
  1641. /// Triggers a refresh of the entire display.
  1642. /// </summary>
  1643. public static void Refresh ()
  1644. {
  1645. Driver.UpdateScreen ();
  1646. View last = null;
  1647. foreach (var v in toplevels.Reverse ()) {
  1648. v.SetNeedsDisplay ();
  1649. v.Redraw (v.Bounds);
  1650. last = v;
  1651. }
  1652. last?.PositionCursor ();
  1653. Driver.Refresh ();
  1654. }
  1655. internal static void End (View view)
  1656. {
  1657. if (toplevels.Peek () != view)
  1658. throw new ArgumentException ("The view that you end with must be balanced");
  1659. toplevels.Pop ();
  1660. if (toplevels.Count == 0)
  1661. Shutdown ();
  1662. else
  1663. {
  1664. Current = toplevels.Peek();
  1665. Refresh ();
  1666. }
  1667. }
  1668. /// <summary>
  1669. /// Building block API: Runs the main loop for the created dialog
  1670. /// </summary>
  1671. /// <remarks>
  1672. /// Use the wait parameter to control whether this is a
  1673. /// blocking or non-blocking call.
  1674. /// </remarks>
  1675. /// <param name="state">The state returned by the Begin method.</param>
  1676. /// <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>
  1677. public static void RunLoop (RunState state, bool wait = true)
  1678. {
  1679. if (state == null)
  1680. throw new ArgumentNullException (nameof (state));
  1681. if (state.Toplevel == null)
  1682. throw new ObjectDisposedException ("state");
  1683. for (state.Toplevel.Running = true; state.Toplevel.Running;) {
  1684. if (MainLoop.EventsPending (wait)) {
  1685. MainLoop.MainIteration ();
  1686. if (Iteration != null)
  1687. Iteration (null, EventArgs.Empty);
  1688. } else if (wait == false)
  1689. return;
  1690. if (!state.Toplevel.NeedDisplay.IsEmpty || state.Toplevel.childNeedsDisplay) {
  1691. state.Toplevel.Redraw (state.Toplevel.Bounds);
  1692. if (DebugDrawBounds)
  1693. DrawBounds (state.Toplevel);
  1694. state.Toplevel.PositionCursor ();
  1695. Driver.Refresh ();
  1696. } else
  1697. Driver.UpdateCursor ();
  1698. }
  1699. }
  1700. internal static bool DebugDrawBounds;
  1701. // Need to look into why this does not work properly.
  1702. static void DrawBounds (View v)
  1703. {
  1704. v.DrawFrame (v.Frame, padding: 0, fill: false);
  1705. if (v.Subviews != null && v.Subviews.Count > 0)
  1706. foreach (var sub in v.Subviews)
  1707. DrawBounds (sub);
  1708. }
  1709. /// <summary>
  1710. /// Runs the application with the built-in toplevel view
  1711. /// </summary>
  1712. public static void Run ()
  1713. {
  1714. Run (Top);
  1715. }
  1716. /// <summary>
  1717. /// Runs the main loop on the given container.
  1718. /// </summary>
  1719. /// <remarks>
  1720. /// <para>
  1721. /// This method is used to start processing events
  1722. /// for the main application, but it is also used to
  1723. /// run modal dialog boxes.
  1724. /// </para>
  1725. /// <para>
  1726. /// To make a toplevel stop execution, set the "Running"
  1727. /// property to false.
  1728. /// </para>
  1729. /// <para>
  1730. /// This is equivalent to calling Begin on the toplevel view, followed by RunLoop with the
  1731. /// returned value, and then calling end on the return value.
  1732. /// </para>
  1733. /// <para>
  1734. /// Alternatively, if your program needs to control the main loop and needs to
  1735. /// process events manually, you can invoke Begin to set things up manually and then
  1736. /// repeatedly call RunLoop with the wait parameter set to false. By doing this
  1737. /// the RunLoop method will only process any pending events, timers, idle handlers and
  1738. /// then return control immediately.
  1739. /// </para>
  1740. /// </remarks>
  1741. public static void Run (Toplevel view)
  1742. {
  1743. var runToken = Begin (view);
  1744. RunLoop (runToken);
  1745. End (runToken);
  1746. }
  1747. /// <summary>
  1748. /// Stops running the most recent toplevel
  1749. /// </summary>
  1750. public static void RequestStop ()
  1751. {
  1752. Current.Running = false;
  1753. }
  1754. static void TerminalResized ()
  1755. {
  1756. var full = new Rect (0, 0, Driver.Cols, Driver.Rows);
  1757. Driver.Clip = full;
  1758. foreach (var t in toplevels) {
  1759. t.RelativeLayout (full);
  1760. t.LayoutSubviews ();
  1761. }
  1762. Refresh ();
  1763. }
  1764. }
  1765. }