2
0

Core.cs 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946
  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. var p = Environment.OSVersion.Platform;
  1431. if (UseSystemConsole)
  1432. Driver = new NetDriver ();
  1433. else if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows)
  1434. Driver = new WindowsDriver();
  1435. else
  1436. Driver = new CursesDriver ();
  1437. Driver.Init (TerminalResized);
  1438. MainLoop = new Mono.Terminal.MainLoop (Driver is CursesDriver, UseSystemConsole);
  1439. SynchronizationContext.SetSynchronizationContext (new MainLoopSyncContext (MainLoop));
  1440. Top = Toplevel.Create ();
  1441. Current = Top;
  1442. }
  1443. /// <summary>
  1444. /// Captures the execution state for the provided TopLevel view.
  1445. /// </summary>
  1446. public class RunState : IDisposable {
  1447. internal RunState (Toplevel view)
  1448. {
  1449. Toplevel = view;
  1450. }
  1451. internal Toplevel Toplevel;
  1452. /// <summary>
  1453. /// Releases alTop = l resource used by the <see cref="T:Terminal.Gui.Application.RunState"/> object.
  1454. /// </summary>
  1455. /// <remarks>Call <see cref="Dispose()"/> when you are finished using the <see cref="T:Terminal.Gui.Application.RunState"/>. The
  1456. /// <see cref="Dispose()"/> method leaves the <see cref="T:Terminal.Gui.Application.RunState"/> in an unusable state. After
  1457. /// calling <see cref="Dispose()"/>, you must release all references to the
  1458. /// <see cref="T:Terminal.Gui.Application.RunState"/> so the garbage collector can reclaim the memory that the
  1459. /// <see cref="T:Terminal.Gui.Application.RunState"/> was occupying.</remarks>
  1460. public void Dispose ()
  1461. {
  1462. Dispose (true);
  1463. GC.SuppressFinalize (this);
  1464. }
  1465. /// <summary>
  1466. /// Dispose the specified disposing.
  1467. /// </summary>
  1468. /// <returns>The dispose.</returns>
  1469. /// <param name="disposing">If set to <c>true</c> disposing.</param>
  1470. protected virtual void Dispose (bool disposing)
  1471. {
  1472. if (Toplevel != null) {
  1473. End (Toplevel);
  1474. Toplevel = null;
  1475. }
  1476. }
  1477. }
  1478. static void ProcessKeyEvent (KeyEvent ke)
  1479. {
  1480. if (Current.ProcessHotKey (ke))
  1481. return;
  1482. if (Current.ProcessKey (ke))
  1483. return;
  1484. // Process the key normally
  1485. if (Current.ProcessColdKey (ke))
  1486. return;
  1487. }
  1488. static View FindDeepestView (View start, int x, int y, out int resx, out int resy)
  1489. {
  1490. var startFrame = start.Frame;
  1491. if (!startFrame.Contains (x, y)) {
  1492. resx = 0;
  1493. resy = 0;
  1494. return null;
  1495. }
  1496. if (start.Subviews != null){
  1497. int count = start.Subviews.Count;
  1498. if (count > 0) {
  1499. var rx = x - startFrame.X;
  1500. var ry = y - startFrame.Y;
  1501. for (int i = count - 1; i >= 0; i--) {
  1502. View v = start.Subviews [i];
  1503. if (v.Frame.Contains (rx, ry)) {
  1504. var deep = FindDeepestView (v, rx, ry, out resx, out resy);
  1505. if (deep == null)
  1506. return v;
  1507. return deep;
  1508. }
  1509. }
  1510. }
  1511. }
  1512. resx = x-startFrame.X;
  1513. resy = y-startFrame.Y;
  1514. return start;
  1515. }
  1516. static View mouseGrabView;
  1517. /// <summary>
  1518. /// Grabs the mouse, forcing all mouse events to be routed to the specified view until UngrabMouse is called.
  1519. /// </summary>
  1520. /// <returns>The grab.</returns>
  1521. /// <param name="view">View that will receive all mouse events until UngrabMouse is invoked.</param>
  1522. public static void GrabMouse (View view)
  1523. {
  1524. if (view == null)
  1525. return;
  1526. mouseGrabView = view;
  1527. Driver.UncookMouse ();
  1528. }
  1529. /// <summary>
  1530. /// Releases the mouse grab, so mouse events will be routed to the view on which the mouse is.
  1531. /// </summary>
  1532. public static void UngrabMouse ()
  1533. {
  1534. mouseGrabView = null;
  1535. Driver.CookMouse ();
  1536. }
  1537. /// <summary>
  1538. /// Merely a debugging aid to see the raw mouse events
  1539. /// </summary>
  1540. static public Action<MouseEvent> RootMouseEvent;
  1541. static void ProcessMouseEvent (MouseEvent me)
  1542. {
  1543. RootMouseEvent?.Invoke (me);
  1544. if (mouseGrabView != null) {
  1545. var newxy = mouseGrabView.ScreenToView (me.X, me.Y);
  1546. var nme = new MouseEvent () {
  1547. X = newxy.X,
  1548. Y = newxy.Y,
  1549. Flags = me.Flags
  1550. };
  1551. mouseGrabView.MouseEvent (me);
  1552. return;
  1553. }
  1554. int rx, ry;
  1555. var view = FindDeepestView (Current, me.X, me.Y, out rx, out ry);
  1556. if (view != null) {
  1557. if (!view.WantMousePositionReports && me.Flags == MouseFlags.ReportMousePosition)
  1558. return;
  1559. var nme = new MouseEvent () {
  1560. X = rx,
  1561. Y = ry,
  1562. Flags = me.Flags
  1563. };
  1564. // Should we bubbled up the event, if it is not handled?
  1565. view.MouseEvent (nme);
  1566. }
  1567. }
  1568. /// <summary>
  1569. /// Building block API: Prepares the provided toplevel for execution.
  1570. /// </summary>
  1571. /// <returns>The runstate handle that needs to be passed to the End() method upon completion.</returns>
  1572. /// <param name="toplevel">Toplevel to prepare execution for.</param>
  1573. /// <remarks>
  1574. /// This method prepares the provided toplevel for running with the focus,
  1575. /// it adds this to the list of toplevels, sets up the mainloop to process the
  1576. /// event, lays out the subviews, focuses the first element, and draws the
  1577. /// toplevel in the screen. This is usually followed by executing
  1578. /// the <see cref="RunLoop"/> method, and then the <see cref="End(RunState)"/> method upon termination which will
  1579. /// undo these changes.
  1580. /// </remarks>
  1581. static public RunState Begin (Toplevel toplevel)
  1582. {
  1583. if (toplevel == null)
  1584. throw new ArgumentNullException (nameof (toplevel));
  1585. var rs = new RunState (toplevel);
  1586. Init ();
  1587. toplevels.Push (toplevel);
  1588. Current = toplevel;
  1589. Driver.PrepareToRun (MainLoop, ProcessKeyEvent, ProcessMouseEvent);
  1590. if (toplevel.LayoutStyle == LayoutStyle.Computed)
  1591. toplevel.RelativeLayout (new Rect (0, 0, Driver.Cols, Driver.Rows));
  1592. toplevel.LayoutSubviews ();
  1593. toplevel.WillPresent ();
  1594. Redraw (toplevel);
  1595. toplevel.PositionCursor ();
  1596. Driver.Refresh ();
  1597. return rs;
  1598. }
  1599. /// <summary>
  1600. /// Building block API: completes the exection of a Toplevel that was started with Begin.
  1601. /// </summary>
  1602. /// <param name="runState">The runstate returned by the <see cref="Begin(Toplevel)"/> method.</param>
  1603. static public void End (RunState runState)
  1604. {
  1605. if (runState == null)
  1606. throw new ArgumentNullException (nameof (runState));
  1607. runState.Dispose ();
  1608. }
  1609. static void Shutdown ()
  1610. {
  1611. Driver.End ();
  1612. }
  1613. static void Redraw (View view)
  1614. {
  1615. view.Redraw (view.Bounds);
  1616. Driver.Refresh ();
  1617. }
  1618. static void Refresh (View view)
  1619. {
  1620. view.Redraw (view.Bounds);
  1621. Driver.Refresh ();
  1622. }
  1623. /// <summary>
  1624. /// Triggers a refresh of the entire display.
  1625. /// </summary>
  1626. public static void Refresh ()
  1627. {
  1628. Driver.UpdateScreen ();
  1629. View last = null;
  1630. foreach (var v in toplevels.Reverse ()) {
  1631. v.SetNeedsDisplay ();
  1632. v.Redraw (v.Bounds);
  1633. last = v;
  1634. }
  1635. last?.PositionCursor ();
  1636. Driver.Refresh ();
  1637. }
  1638. internal static void End (View view)
  1639. {
  1640. if (toplevels.Peek () != view)
  1641. throw new ArgumentException ("The view that you end with must be balanced");
  1642. toplevels.Pop ();
  1643. if (toplevels.Count == 0)
  1644. Shutdown ();
  1645. else
  1646. {
  1647. Current = toplevels.Peek();
  1648. Refresh ();
  1649. }
  1650. }
  1651. /// <summary>
  1652. /// Building block API: Runs the main loop for the created dialog
  1653. /// </summary>
  1654. /// <remarks>
  1655. /// Use the wait parameter to control whether this is a
  1656. /// blocking or non-blocking call.
  1657. /// </remarks>
  1658. /// <param name="state">The state returned by the Begin method.</param>
  1659. /// <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>
  1660. public static void RunLoop (RunState state, bool wait = true)
  1661. {
  1662. if (state == null)
  1663. throw new ArgumentNullException (nameof (state));
  1664. if (state.Toplevel == null)
  1665. throw new ObjectDisposedException ("state");
  1666. for (state.Toplevel.Running = true; state.Toplevel.Running;) {
  1667. if (MainLoop.EventsPending (wait)) {
  1668. MainLoop.MainIteration ();
  1669. if (Iteration != null)
  1670. Iteration (null, EventArgs.Empty);
  1671. } else if (wait == false)
  1672. return;
  1673. if (!state.Toplevel.NeedDisplay.IsEmpty || state.Toplevel.childNeedsDisplay) {
  1674. state.Toplevel.Redraw (state.Toplevel.Bounds);
  1675. if (DebugDrawBounds)
  1676. DrawBounds (state.Toplevel);
  1677. state.Toplevel.PositionCursor ();
  1678. Driver.Refresh ();
  1679. } else
  1680. Driver.UpdateCursor ();
  1681. }
  1682. }
  1683. internal static bool DebugDrawBounds;
  1684. // Need to look into why this does not work properly.
  1685. static void DrawBounds (View v)
  1686. {
  1687. v.DrawFrame (v.Frame, padding: 0, fill: false);
  1688. if (v.Subviews != null && v.Subviews.Count > 0)
  1689. foreach (var sub in v.Subviews)
  1690. DrawBounds (sub);
  1691. }
  1692. /// <summary>
  1693. /// Runs the application with the built-in toplevel view
  1694. /// </summary>
  1695. public static void Run ()
  1696. {
  1697. Run (Top);
  1698. }
  1699. /// <summary>
  1700. /// Runs the main loop on the given container.
  1701. /// </summary>
  1702. /// <remarks>
  1703. /// <para>
  1704. /// This method is used to start processing events
  1705. /// for the main application, but it is also used to
  1706. /// run modal dialog boxes.
  1707. /// </para>
  1708. /// <para>
  1709. /// To make a toplevel stop execution, set the "Running"
  1710. /// property to false.
  1711. /// </para>
  1712. /// <para>
  1713. /// This is equivalent to calling Begin on the toplevel view, followed by RunLoop with the
  1714. /// returned value, and then calling end on the return value.
  1715. /// </para>
  1716. /// <para>
  1717. /// Alternatively, if your program needs to control the main loop and needs to
  1718. /// process events manually, you can invoke Begin to set things up manually and then
  1719. /// repeatedly call RunLoop with the wait parameter set to false. By doing this
  1720. /// the RunLoop method will only process any pending events, timers, idle handlers and
  1721. /// then return control immediately.
  1722. /// </para>
  1723. /// </remarks>
  1724. public static void Run (Toplevel view)
  1725. {
  1726. var runToken = Begin (view);
  1727. RunLoop (runToken);
  1728. End (runToken);
  1729. }
  1730. /// <summary>
  1731. /// Stops running the most recent toplevel
  1732. /// </summary>
  1733. public static void RequestStop ()
  1734. {
  1735. Current.Running = false;
  1736. }
  1737. static void TerminalResized ()
  1738. {
  1739. var full = new Rect (0, 0, Driver.Cols, Driver.Rows);
  1740. Driver.Clip = full;
  1741. foreach (var t in toplevels) {
  1742. t.RelativeLayout (full);
  1743. t.LayoutSubviews ();
  1744. }
  1745. Refresh ();
  1746. }
  1747. }
  1748. }