Core.cs 74 KB

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