Core.cs 76 KB

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