Core.cs 56 KB

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