Core.cs 67 KB

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