Core.cs 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520
  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. /// <summary>
  820. /// Gets or sets a value indicating whether this <see cref="T:Terminal.Gui.View"/> has focus.
  821. /// </summary>
  822. /// <value><c>true</c> if has focus; otherwise, <c>false</c>.</value>
  823. public override bool HasFocus {
  824. get {
  825. return base.HasFocus;
  826. }
  827. internal set {
  828. if (base.HasFocus != value)
  829. if (value)
  830. OnEnter ();
  831. else
  832. OnLeave ();
  833. SetNeedsDisplay ();
  834. base.HasFocus = value;
  835. // Remove focus down the chain of subviews if focus is removed
  836. if (!value && focused != null) {
  837. focused.OnLeave ();
  838. focused.HasFocus = false;
  839. focused = null;
  840. }
  841. }
  842. }
  843. public override bool OnEnter ()
  844. {
  845. Enter?.Invoke (this, new EventArgs ());
  846. return base.OnEnter ();
  847. }
  848. public override bool OnLeave ()
  849. {
  850. Leave?.Invoke (this, new EventArgs ());
  851. return base.OnLeave ();
  852. }
  853. /// <summary>
  854. /// Returns the currently focused view inside this view, or null if nothing is focused.
  855. /// </summary>
  856. /// <value>The focused.</value>
  857. public View Focused => focused;
  858. /// <summary>
  859. /// Returns the most focused view in the chain of subviews (the leaf view that has the focus).
  860. /// </summary>
  861. /// <value>The most focused.</value>
  862. public View MostFocused {
  863. get {
  864. if (Focused == null)
  865. return null;
  866. var most = Focused.MostFocused;
  867. if (most != null)
  868. return most;
  869. return Focused;
  870. }
  871. }
  872. /// <summary>
  873. /// The color scheme for this view, if it is not defined, it returns the parent's
  874. /// color scheme.
  875. /// </summary>
  876. public ColorScheme ColorScheme {
  877. get {
  878. if (colorScheme == null)
  879. return SuperView?.ColorScheme;
  880. return colorScheme;
  881. }
  882. set {
  883. colorScheme = value;
  884. }
  885. }
  886. ColorScheme colorScheme;
  887. /// <summary>
  888. /// Displays the specified character in the specified column and row.
  889. /// </summary>
  890. /// <param name="col">Col.</param>
  891. /// <param name="row">Row.</param>
  892. /// <param name="ch">Ch.</param>
  893. public void AddRune (int col, int row, Rune ch)
  894. {
  895. if (row < 0 || col < 0)
  896. return;
  897. if (row > frame.Height - 1 || col > frame.Width - 1)
  898. return;
  899. Move (col, row);
  900. Driver.AddRune (ch);
  901. }
  902. /// <summary>
  903. /// Removes the SetNeedsDisplay and the ChildNeedsDisplay setting on this view.
  904. /// </summary>
  905. protected void ClearNeedsDisplay ()
  906. {
  907. NeedDisplay = Rect.Empty;
  908. childNeedsDisplay = false;
  909. }
  910. /// <summary>
  911. /// Performs a redraw of this view and its subviews, only redraws the views that have been flagged for a re-display.
  912. /// </summary>
  913. /// <param name="region">The region to redraw, this is relative to the view itself.</param>
  914. /// <remarks>
  915. /// <para>
  916. /// Views should set the color that they want to use on entry, as otherwise this will inherit
  917. /// the last color that was set globaly on the driver.
  918. /// </para>
  919. /// </remarks>
  920. public virtual void Redraw (Rect region)
  921. {
  922. var clipRect = new Rect (Point.Empty, frame.Size);
  923. if (subviews != null) {
  924. foreach (var view in subviews) {
  925. if (!view.NeedDisplay.IsEmpty || view.childNeedsDisplay) {
  926. if (view.Frame.IntersectsWith (clipRect) && view.Frame.IntersectsWith (region)) {
  927. // FIXED: optimize this by computing the intersection of region and view.Bounds
  928. if (view.layoutNeeded)
  929. view.LayoutSubviews ();
  930. Application.CurrentView = view;
  931. view.Redraw (view.Bounds);
  932. }
  933. view.NeedDisplay = Rect.Empty;
  934. view.childNeedsDisplay = false;
  935. }
  936. }
  937. }
  938. ClearNeedsDisplay ();
  939. }
  940. /// <summary>
  941. /// Focuses the specified sub-view.
  942. /// </summary>
  943. /// <param name="view">View.</param>
  944. public void SetFocus (View view)
  945. {
  946. if (view == null)
  947. return;
  948. //Console.WriteLine ($"Request to focus {view}");
  949. if (!view.CanFocus)
  950. return;
  951. if (focused == view)
  952. return;
  953. // Make sure that this view is a subview
  954. View c;
  955. for (c = view.container; c != null; c = c.container)
  956. if (c == this)
  957. break;
  958. if (c == null)
  959. throw new ArgumentException ("the specified view is not part of the hierarchy of this view");
  960. if (focused != null)
  961. focused.HasFocus = false;
  962. focused = view;
  963. focused.HasFocus = true;
  964. focused.EnsureFocus ();
  965. // Send focus upwards
  966. SuperView?.SetFocus(this);
  967. }
  968. public class KeyEventEventArgs : EventArgs {
  969. public KeyEventEventArgs(KeyEvent ke) => KeyEvent = ke;
  970. public KeyEvent KeyEvent { get; set; }
  971. }
  972. /// <summary>
  973. /// Invoked when a character key is pressed and occurs after the key down event.
  974. /// </summary>
  975. public event EventHandler<KeyEventEventArgs> KeyPress;
  976. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  977. public override bool ProcessKey (KeyEvent keyEvent)
  978. {
  979. KeyPress?.Invoke (this, new KeyEventEventArgs(keyEvent));
  980. if (Focused?.ProcessKey (keyEvent) == true)
  981. return true;
  982. return false;
  983. }
  984. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  985. public override bool ProcessHotKey (KeyEvent keyEvent)
  986. {
  987. KeyPress?.Invoke (this, new KeyEventEventArgs (keyEvent));
  988. if (subviews == null || subviews.Count == 0)
  989. return false;
  990. foreach (var view in subviews)
  991. if (view.ProcessHotKey (keyEvent))
  992. return true;
  993. return false;
  994. }
  995. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  996. public override bool ProcessColdKey (KeyEvent keyEvent)
  997. {
  998. KeyPress?.Invoke (this, new KeyEventEventArgs(keyEvent));
  999. if (subviews == null || subviews.Count == 0)
  1000. return false;
  1001. foreach (var view in subviews)
  1002. if (view.ProcessColdKey (keyEvent))
  1003. return true;
  1004. return false;
  1005. }
  1006. /// <summary>
  1007. /// Invoked when a key is pressed
  1008. /// </summary>
  1009. public event EventHandler<KeyEventEventArgs> KeyDown;
  1010. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  1011. public override bool OnKeyDown (KeyEvent keyEvent)
  1012. {
  1013. KeyDown?.Invoke (this, new KeyEventEventArgs (keyEvent));
  1014. if (subviews == null || subviews.Count == 0)
  1015. return false;
  1016. foreach (var view in subviews)
  1017. if (view.OnKeyDown (keyEvent))
  1018. return true;
  1019. return false;
  1020. }
  1021. /// <summary>
  1022. /// Invoked when a key is released
  1023. /// </summary>
  1024. public event EventHandler<KeyEventEventArgs> KeyUp;
  1025. /// <param name="keyEvent">Contains the details about the key that produced the event.</param>
  1026. public override bool OnKeyUp (KeyEvent keyEvent)
  1027. {
  1028. KeyUp?.Invoke (this, new KeyEventEventArgs (keyEvent));
  1029. if (subviews == null || subviews.Count == 0)
  1030. return false;
  1031. foreach (var view in subviews)
  1032. if (view.OnKeyUp (keyEvent))
  1033. return true;
  1034. return false;
  1035. }
  1036. /// <summary>
  1037. /// Finds the first view in the hierarchy that wants to get the focus if nothing is currently focused, otherwise, it does nothing.
  1038. /// </summary>
  1039. public void EnsureFocus ()
  1040. {
  1041. if (focused == null)
  1042. if (FocusDirection == Direction.Forward)
  1043. FocusFirst ();
  1044. else
  1045. FocusLast ();
  1046. }
  1047. /// <summary>
  1048. /// Focuses the first focusable subview if one exists.
  1049. /// </summary>
  1050. public void FocusFirst ()
  1051. {
  1052. if (subviews == null) {
  1053. SuperView?.SetFocus (this);
  1054. return;
  1055. }
  1056. foreach (var view in subviews) {
  1057. if (view.CanFocus) {
  1058. SetFocus (view);
  1059. return;
  1060. }
  1061. }
  1062. }
  1063. /// <summary>
  1064. /// Focuses the last focusable subview if one exists.
  1065. /// </summary>
  1066. public void FocusLast ()
  1067. {
  1068. if (subviews == null) {
  1069. SuperView?.SetFocus(this);
  1070. return;
  1071. }
  1072. for (int i = subviews.Count; i > 0;) {
  1073. i--;
  1074. View v = subviews [i];
  1075. if (v.CanFocus) {
  1076. SetFocus (v);
  1077. return;
  1078. }
  1079. }
  1080. }
  1081. /// <summary>
  1082. /// Focuses the previous view.
  1083. /// </summary>
  1084. /// <returns><c>true</c>, if previous was focused, <c>false</c> otherwise.</returns>
  1085. public bool FocusPrev ()
  1086. {
  1087. FocusDirection = Direction.Backward;
  1088. if (subviews == null || subviews.Count == 0)
  1089. return false;
  1090. if (focused == null) {
  1091. FocusLast ();
  1092. return focused != null;
  1093. }
  1094. int focused_idx = -1;
  1095. for (int i = subviews.Count; i > 0;) {
  1096. i--;
  1097. View w = subviews [i];
  1098. if (w.HasFocus) {
  1099. if (w.FocusPrev ())
  1100. return true;
  1101. focused_idx = i;
  1102. continue;
  1103. }
  1104. if (w.CanFocus && focused_idx != -1) {
  1105. focused.HasFocus = false;
  1106. if (w != null && w.CanFocus)
  1107. w.FocusLast ();
  1108. SetFocus (w);
  1109. return true;
  1110. }
  1111. }
  1112. if (focused != null) {
  1113. focused.HasFocus = false;
  1114. focused = null;
  1115. }
  1116. return false;
  1117. }
  1118. /// <summary>
  1119. /// Focuses the next view.
  1120. /// </summary>
  1121. /// <returns><c>true</c>, if next was focused, <c>false</c> otherwise.</returns>
  1122. public bool FocusNext ()
  1123. {
  1124. FocusDirection = Direction.Forward;
  1125. if (subviews == null || subviews.Count == 0)
  1126. return false;
  1127. if (focused == null) {
  1128. FocusFirst ();
  1129. return focused != null;
  1130. }
  1131. int n = subviews.Count;
  1132. int focused_idx = -1;
  1133. for (int i = 0; i < n; i++) {
  1134. View w = subviews [i];
  1135. if (w.HasFocus) {
  1136. if (w.FocusNext ())
  1137. return true;
  1138. focused_idx = i;
  1139. continue;
  1140. }
  1141. if (w.CanFocus && focused_idx != -1) {
  1142. focused.HasFocus = false;
  1143. if (w != null && w.CanFocus)
  1144. w.FocusFirst ();
  1145. SetFocus (w);
  1146. return true;
  1147. }
  1148. }
  1149. if (focused != null) {
  1150. focused.HasFocus = false;
  1151. focused = null;
  1152. }
  1153. return false;
  1154. }
  1155. /// <summary>
  1156. /// Computes the RelativeLayout for the view, given the frame for its container.
  1157. /// </summary>
  1158. /// <param name="hostFrame">The Frame for the host.</param>
  1159. internal void RelativeLayout (Rect hostFrame)
  1160. {
  1161. int w, h, _x, _y;
  1162. if (x is Pos.PosCenter) {
  1163. if (width == null)
  1164. w = hostFrame.Width;
  1165. else
  1166. w = width.Anchor (hostFrame.Width);
  1167. _x = x.Anchor (hostFrame.Width - w);
  1168. } else {
  1169. if (x == null)
  1170. _x = 0;
  1171. else
  1172. _x = x.Anchor (hostFrame.Width);
  1173. if (width == null)
  1174. w = hostFrame.Width;
  1175. else
  1176. w = width.Anchor (hostFrame.Width - _x);
  1177. }
  1178. if (y is Pos.PosCenter) {
  1179. if (height == null)
  1180. h = hostFrame.Height;
  1181. else
  1182. h = height.Anchor (hostFrame.Height);
  1183. _y = y.Anchor (hostFrame.Height - h);
  1184. } else {
  1185. if (y == null)
  1186. _y = 0;
  1187. else
  1188. _y = y.Anchor (hostFrame.Height);
  1189. if (height == null)
  1190. h = hostFrame.Height;
  1191. else
  1192. h = height.Anchor (hostFrame.Height - _y);
  1193. }
  1194. Frame = new Rect (_x, _y, w, h);
  1195. // layoutNeeded = false;
  1196. }
  1197. // https://en.wikipedia.org/wiki/Topological_sorting
  1198. List<View> TopologicalSort (HashSet<View> nodes, HashSet<(View From, View To)> edges)
  1199. {
  1200. var result = new List<View> ();
  1201. // Set of all nodes with no incoming edges
  1202. var S = new HashSet<View> (nodes.Where (n => edges.All (e => e.To.Equals (n) == false)));
  1203. while (S.Any ()) {
  1204. // remove a node n from S
  1205. var n = S.First ();
  1206. S.Remove (n);
  1207. // add n to tail of L
  1208. if (n != this?.SuperView)
  1209. result.Add (n);
  1210. // for each node m with an edge e from n to m do
  1211. foreach (var e in edges.Where (e => e.From.Equals (n)).ToArray ()) {
  1212. var m = e.To;
  1213. // remove edge e from the graph
  1214. edges.Remove (e);
  1215. // if m has no other incoming edges then
  1216. if (edges.All (me => me.To.Equals (m) == false) && m != this?.SuperView) {
  1217. // insert m into S
  1218. S.Add (m);
  1219. }
  1220. }
  1221. }
  1222. // if graph has edges then
  1223. if (edges.Any ()) {
  1224. // return error (graph has at least one cycle)
  1225. return null;
  1226. } else {
  1227. // return L (a topologically sorted order)
  1228. return result;
  1229. }
  1230. }
  1231. /// <summary>
  1232. /// This virtual method is invoked when a view starts executing or
  1233. /// when the dimensions of the view have changed, for example in
  1234. /// response to the container view or terminal resizing.
  1235. /// </summary>
  1236. public virtual void LayoutSubviews ()
  1237. {
  1238. if (!layoutNeeded)
  1239. return;
  1240. // Sort out the dependencies of the X, Y, Width, Height properties
  1241. var nodes = new HashSet<View> ();
  1242. var edges = new HashSet<(View, View)> ();
  1243. foreach (var v in InternalSubviews) {
  1244. nodes.Add (v);
  1245. if (v.LayoutStyle == LayoutStyle.Computed) {
  1246. if (v.X is Pos.PosView vX)
  1247. edges.Add ((vX.Target, v));
  1248. if (v.Y is Pos.PosView vY)
  1249. edges.Add ((vY.Target, v));
  1250. if (v.Width is Dim.DimView vWidth)
  1251. edges.Add ((vWidth.Target, v));
  1252. if (v.Height is Dim.DimView vHeight)
  1253. edges.Add ((vHeight.Target, v));
  1254. }
  1255. }
  1256. var ordered = TopologicalSort (nodes, edges);
  1257. if (ordered == null)
  1258. throw new Exception ("There is a recursive cycle in the relative Pos/Dim in the views of " + this);
  1259. foreach (var v in ordered) {
  1260. if (v.LayoutStyle == LayoutStyle.Computed)
  1261. v.RelativeLayout (Frame);
  1262. v.LayoutSubviews ();
  1263. v.layoutNeeded = false;
  1264. }
  1265. if (SuperView == Application.Top && layoutNeeded && ordered.Count == 0 && LayoutStyle == LayoutStyle.Computed) {
  1266. RelativeLayout (Frame);
  1267. }
  1268. layoutNeeded = false;
  1269. }
  1270. /// <summary>
  1271. /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:Terminal.Gui.View"/>.
  1272. /// </summary>
  1273. /// <returns>A <see cref="T:System.String"/> that represents the current <see cref="T:Terminal.Gui.View"/>.</returns>
  1274. public override string ToString ()
  1275. {
  1276. return $"{GetType ().Name}({Id})({Frame})";
  1277. }
  1278. public override bool OnMouseEnter (MouseEvent mouseEvent)
  1279. {
  1280. if (!base.OnMouseEnter (mouseEvent)) {
  1281. MouseEnter?.Invoke (this, mouseEvent);
  1282. return false;
  1283. }
  1284. return true;
  1285. }
  1286. public override bool OnMouseLeave (MouseEvent mouseEvent)
  1287. {
  1288. if (!base.OnMouseLeave (mouseEvent)) {
  1289. MouseLeave?.Invoke (this, mouseEvent);
  1290. return false;
  1291. }
  1292. return true;
  1293. }
  1294. }
  1295. /// <summary>
  1296. /// Toplevel views can be modally executed.
  1297. /// </summary>
  1298. /// <remarks>
  1299. /// <para>
  1300. /// Toplevels can be modally executing views, and they return control
  1301. /// to the caller when the "Running" property is set to false, or
  1302. /// by calling <see cref="M:Terminal.Gui.Application.RequestStop()"/>
  1303. /// </para>
  1304. /// <para>
  1305. /// There will be a toplevel created for you on the first time use
  1306. /// and can be accessed from the property <see cref="P:Terminal.Gui.Application.Top"/>,
  1307. /// but new toplevels can be created and ran on top of it. To run, create the
  1308. /// toplevel and then invoke <see cref="M:Terminal.Gui.Application.Run"/> with the
  1309. /// new toplevel.
  1310. /// </para>
  1311. /// <para>
  1312. /// TopLevels can also opt-in to more sophisticated initialization
  1313. /// by implementing <see cref="ISupportInitialize"/>. When they do
  1314. /// so, the <see cref="ISupportInitialize.BeginInit"/> and
  1315. /// <see cref="ISupportInitialize.EndInit"/> methods will be called
  1316. /// before running the view.
  1317. /// If first-run-only initialization is preferred, the <see cref="ISupportInitializeNotification"/>
  1318. /// can be implemented too, in which case the <see cref="ISupportInitialize"/>
  1319. /// methods will only be called if <see cref="ISupportInitializeNotification.IsInitialized"/>
  1320. /// is <see langword="false"/>. This allows proper View inheritance hierarchies
  1321. /// to override base class layout code optimally by doing so only on first run,
  1322. /// instead of on every run.
  1323. /// </para>
  1324. /// </remarks>
  1325. public class Toplevel : View {
  1326. /// <summary>
  1327. /// This flag is checked on each iteration of the mainloop and it continues
  1328. /// running until this flag is set to false.
  1329. /// </summary>
  1330. public bool Running;
  1331. /// <summary>
  1332. /// Initializes a new instance of the <see cref="T:Terminal.Gui.Toplevel"/> class with the specified absolute layout.
  1333. /// </summary>
  1334. /// <param name="frame">Frame.</param>
  1335. public Toplevel (Rect frame) : base (frame)
  1336. {
  1337. Initialize ();
  1338. }
  1339. /// <summary>
  1340. /// Initializes a new instance of the <see cref="T:Terminal.Gui.Toplevel"/> class with Computed layout, defaulting to <see langword="async"/> full screen.
  1341. /// </summary>
  1342. public Toplevel () : base ()
  1343. {
  1344. Initialize ();
  1345. Width = Dim.Fill ();
  1346. Height = Dim.Fill ();
  1347. }
  1348. void Initialize ()
  1349. {
  1350. ColorScheme = Colors.Base;
  1351. }
  1352. /// <summary>
  1353. /// Convenience factory method that creates a new toplevel with the current terminal dimensions.
  1354. /// </summary>
  1355. /// <returns>The create.</returns>
  1356. public static Toplevel Create ()
  1357. {
  1358. return new Toplevel (new Rect (0, 0, Driver.Cols, Driver.Rows));
  1359. }
  1360. public override bool CanFocus {
  1361. get => true;
  1362. }
  1363. /// <summary>
  1364. /// Determines whether the <see cref="Toplevel"/> is modal or not.
  1365. /// Causes <see cref="ProcessKey(KeyEvent)"/> to propagate keys upwards
  1366. /// by default unless set to <see langword="true"/>.
  1367. /// </summary>
  1368. public bool Modal { get; set; }
  1369. /// <summary>
  1370. /// Check id current toplevel has menu bar
  1371. /// </summary>
  1372. public bool HasMenuBar { get; set; }
  1373. /// <summary>
  1374. /// Check id current toplevel has status bar
  1375. /// </summary>
  1376. public bool HasStatusBar { get; set; }
  1377. public override bool ProcessKey (KeyEvent keyEvent)
  1378. {
  1379. if (base.ProcessKey (keyEvent))
  1380. return true;
  1381. switch (keyEvent.Key) {
  1382. case Key.ControlQ:
  1383. // FIXED: stop current execution of this container
  1384. Application.RequestStop ();
  1385. break;
  1386. case Key.ControlZ:
  1387. Driver.Suspend ();
  1388. return true;
  1389. #if false
  1390. case Key.F5:
  1391. Application.DebugDrawBounds = !Application.DebugDrawBounds;
  1392. SetNeedsDisplay ();
  1393. return true;
  1394. #endif
  1395. case Key.Tab:
  1396. case Key.CursorRight:
  1397. case Key.CursorDown:
  1398. case Key.ControlI: // Unix
  1399. var old = Focused;
  1400. if (!FocusNext ())
  1401. FocusNext ();
  1402. if (old != Focused) {
  1403. old?.SetNeedsDisplay ();
  1404. Focused?.SetNeedsDisplay ();
  1405. }
  1406. return true;
  1407. case Key.CursorLeft:
  1408. case Key.CursorUp:
  1409. case Key.BackTab:
  1410. old = Focused;
  1411. if (!FocusPrev ())
  1412. FocusPrev ();
  1413. if (old != Focused) {
  1414. old?.SetNeedsDisplay ();
  1415. Focused?.SetNeedsDisplay ();
  1416. }
  1417. return true;
  1418. case Key.ControlL:
  1419. Application.Refresh ();
  1420. return true;
  1421. }
  1422. return false;
  1423. }
  1424. public override void Add (View view)
  1425. {
  1426. if (this == Application.Top) {
  1427. if (view is MenuBar)
  1428. HasMenuBar = true;
  1429. if (view is StatusBar)
  1430. HasStatusBar = true;
  1431. }
  1432. base.Add (view);
  1433. }
  1434. public override void Remove (View view)
  1435. {
  1436. if (this == Application.Top) {
  1437. if (view is MenuBar)
  1438. HasMenuBar = true;
  1439. if (view is StatusBar)
  1440. HasStatusBar = true;
  1441. }
  1442. base.Remove (view);
  1443. }
  1444. public override void RemoveAll ()
  1445. {
  1446. if (this == Application.Top) {
  1447. HasMenuBar = false;
  1448. HasStatusBar = false;
  1449. }
  1450. base.RemoveAll ();
  1451. }
  1452. internal void EnsureVisibleBounds (Toplevel top, int x, int y, out int nx, out int ny)
  1453. {
  1454. nx = Math.Max (x, 0);
  1455. nx = nx + top.Frame.Width > Driver.Cols ? Math.Max(Driver.Cols - top.Frame.Width, 0) : nx;
  1456. bool m, s;
  1457. if (SuperView == null)
  1458. m = Application.Top.HasMenuBar;
  1459. else
  1460. m = ((Toplevel)SuperView).HasMenuBar;
  1461. int l = m ? 1 : 0;
  1462. ny = Math.Max (y, l);
  1463. if (SuperView == null)
  1464. s = Application.Top.HasStatusBar;
  1465. else
  1466. s = ((Toplevel)SuperView).HasStatusBar;
  1467. l = s ? Driver.Rows - 1 : Driver.Rows;
  1468. ny = Math.Min (ny, l);
  1469. ny = ny + top.Frame.Height > l ? Math.Max(l - top.Frame.Height, m ? 1 : 0) : ny;
  1470. }
  1471. internal void PositionToplevels ()
  1472. {
  1473. if (this != Application.Top) {
  1474. EnsureVisibleBounds (this, Frame.X, Frame.Y, out int nx, out int ny);
  1475. if ((nx != Frame.X || ny != Frame.Y) && LayoutStyle != LayoutStyle.Computed) {
  1476. X = nx;
  1477. Y = ny;
  1478. }
  1479. } else {
  1480. foreach (var top in Subviews) {
  1481. if (top is Toplevel) {
  1482. EnsureVisibleBounds ((Toplevel)top, top.Frame.X, top.Frame.Y, out int nx, out int ny);
  1483. if ((nx != top.Frame.X || ny != top.Frame.Y) && top.LayoutStyle != LayoutStyle.Computed) {
  1484. top.X = nx;
  1485. top.Y = ny;
  1486. }
  1487. if (HasStatusBar && ny + top.Frame.Height > Driver.Rows - 1) {
  1488. if (top.Height is Dim.DimFill)
  1489. top.Height = Dim.Fill () - 1;
  1490. }
  1491. }
  1492. }
  1493. }
  1494. }
  1495. public override void Redraw (Rect region)
  1496. {
  1497. Application.CurrentView = this;
  1498. if (this == Application.Top) {
  1499. if (!NeedDisplay.IsEmpty) {
  1500. Driver.SetAttribute (Colors.TopLevel.Normal);
  1501. Clear (region);
  1502. Driver.SetAttribute (Colors.Base.Normal);
  1503. }
  1504. foreach (var view in Subviews) {
  1505. if (view.Frame.IntersectsWith (region)) {
  1506. view.SetNeedsLayout ();
  1507. view.SetNeedsDisplay (view.Bounds);
  1508. }
  1509. }
  1510. ClearNeedsDisplay ();
  1511. }
  1512. base.Redraw (base.Bounds);
  1513. }
  1514. /// <summary>
  1515. /// This method is invoked by Application.Begin as part of the Application.Run after
  1516. /// the views have been laid out, and before the views are drawn for the first time.
  1517. /// </summary>
  1518. public virtual void WillPresent ()
  1519. {
  1520. FocusFirst ();
  1521. }
  1522. }
  1523. /// <summary>
  1524. /// A toplevel view that draws a frame around its region and has a "ContentView" subview where the contents are added.
  1525. /// </summary>
  1526. public class Window : Toplevel, IEnumerable {
  1527. View contentView;
  1528. ustring title;
  1529. /// <summary>
  1530. /// The title to be displayed for this window.
  1531. /// </summary>
  1532. /// <value>The title.</value>
  1533. public ustring Title {
  1534. get => title;
  1535. set {
  1536. title = value;
  1537. SetNeedsDisplay ();
  1538. }
  1539. }
  1540. class ContentView : View {
  1541. public ContentView (Rect frame) : base (frame) { }
  1542. public ContentView () : base () { }
  1543. #if false
  1544. public override void Redraw (Rect region)
  1545. {
  1546. Driver.SetAttribute (ColorScheme.Focus);
  1547. for (int y = 0; y < Frame.Height; y++) {
  1548. Move (0, y);
  1549. for (int x = 0; x < Frame.Width; x++) {
  1550. Driver.AddRune ('x');
  1551. }
  1552. }
  1553. }
  1554. #endif
  1555. }
  1556. /// <summary>
  1557. /// Initializes a new instance of the <see cref="T:Terminal.Gui.Gui.Window"/> class with an optional title and a set frame.
  1558. /// </summary>
  1559. /// <param name="frame">Frame.</param>
  1560. /// <param name="title">Title.</param>
  1561. public Window (Rect frame, ustring title = null) : this (frame, title, padding: 0)
  1562. {
  1563. }
  1564. /// <summary>
  1565. /// Initializes a new instance of the <see cref="T:Terminal.Gui.Window"/> class with an optional title.
  1566. /// </summary>
  1567. /// <param name="title">Title.</param>
  1568. public Window (ustring title = null) : this (title, padding: 0)
  1569. {
  1570. }
  1571. int padding;
  1572. /// <summary>
  1573. /// Initializes a new instance of the <see cref="T:Terminal.Gui.Window"/> with
  1574. /// the specified frame for its location, with the specified border
  1575. /// an optional title.
  1576. /// </summary>
  1577. /// <param name="frame">Frame.</param>
  1578. /// <param name="padding">Number of characters to use for padding of the drawn frame.</param>
  1579. /// <param name="title">Title.</param>
  1580. public Window (Rect frame, ustring title = null, int padding = 0) : base (frame)
  1581. {
  1582. this.Title = title;
  1583. int wb = 2 * (1 + padding);
  1584. this.padding = padding;
  1585. var cFrame = new Rect (1 + padding, 1 + padding, frame.Width - wb, frame.Height - wb);
  1586. contentView = new ContentView (cFrame);
  1587. base.Add (contentView);
  1588. }
  1589. /// <summary>
  1590. /// Initializes a new instance of the <see cref="T:Terminal.Gui.Window"/> with
  1591. /// the specified frame for its location, with the specified border
  1592. /// an optional title.
  1593. /// </summary>
  1594. /// <param name="padding">Number of characters to use for padding of the drawn frame.</param>
  1595. /// <param name="title">Title.</param>
  1596. public Window (ustring title = null, int padding = 0) : base ()
  1597. {
  1598. this.Title = title;
  1599. int wb = 1 + padding;
  1600. this.padding = padding;
  1601. contentView = new ContentView () {
  1602. X = wb,
  1603. Y = wb,
  1604. Width = Dim.Fill (wb),
  1605. Height = Dim.Fill (wb)
  1606. };
  1607. base.Add (contentView);
  1608. }
  1609. /// <summary>
  1610. /// Enumerates the various views in the ContentView.
  1611. /// </summary>
  1612. /// <returns>The enumerator.</returns>
  1613. public new IEnumerator GetEnumerator ()
  1614. {
  1615. return contentView.GetEnumerator ();
  1616. }
  1617. void DrawFrame (bool fill = true)
  1618. {
  1619. DrawFrame (new Rect (0, 0, Frame.Width, Frame.Height), padding, fill: fill);
  1620. }
  1621. /// <summary>
  1622. /// Add the specified view to the ContentView.
  1623. /// </summary>
  1624. /// <param name="view">View to add to the window.</param>
  1625. public override void Add (View view)
  1626. {
  1627. contentView.Add (view);
  1628. if (view.CanFocus)
  1629. CanFocus = true;
  1630. }
  1631. /// <summary>
  1632. /// Removes a widget from this container.
  1633. /// </summary>
  1634. /// <remarks>
  1635. /// </remarks>
  1636. public override void Remove (View view)
  1637. {
  1638. if (view == null)
  1639. return;
  1640. SetNeedsDisplay ();
  1641. var touched = view.Frame;
  1642. contentView.Remove (view);
  1643. if (contentView.InternalSubviews.Count < 1)
  1644. this.CanFocus = false;
  1645. }
  1646. /// <summary>
  1647. /// Removes all widgets from this container.
  1648. /// </summary>
  1649. /// <remarks>
  1650. /// </remarks>
  1651. public override void RemoveAll ()
  1652. {
  1653. contentView.RemoveAll ();
  1654. }
  1655. public override void Redraw (Rect bounds)
  1656. {
  1657. Application.CurrentView = this;
  1658. if (!NeedDisplay.IsEmpty) {
  1659. DrawFrameWindow ();
  1660. }
  1661. contentView.Redraw (contentView.Bounds);
  1662. ClearNeedsDisplay ();
  1663. DrawFrameWindow (false);
  1664. void DrawFrameWindow (bool fill = true)
  1665. {
  1666. Driver.SetAttribute (ColorScheme.Normal);
  1667. DrawFrame (fill);
  1668. if (HasFocus)
  1669. Driver.SetAttribute (ColorScheme.HotNormal);
  1670. var width = Frame.Width - (padding + 2) * 2;
  1671. if (Title != null && width > 4) {
  1672. Move (1 + padding, padding);
  1673. Driver.AddRune (' ');
  1674. var str = Title.Length >= width ? Title [0, width - 2] : Title;
  1675. Driver.AddStr (str);
  1676. Driver.AddRune (' ');
  1677. }
  1678. Driver.SetAttribute (ColorScheme.Normal);
  1679. }
  1680. }
  1681. //
  1682. // FIXED:It does not look like the event is raised on clicked-drag
  1683. // need to figure that out.
  1684. //
  1685. internal static Point? dragPosition;
  1686. Point start;
  1687. public override bool MouseEvent (MouseEvent mouseEvent)
  1688. {
  1689. // FIXED:The code is currently disabled, because the
  1690. // Driver.UncookMouse does not seem to have an effect if there is
  1691. // a pending mouse event activated.
  1692. int nx, ny;
  1693. if ((mouseEvent.Flags == (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) ||
  1694. mouseEvent.Flags == MouseFlags.Button3Pressed)) {
  1695. if (dragPosition.HasValue) {
  1696. if (SuperView == null) {
  1697. Application.Top.SetNeedsDisplay (Frame);
  1698. Application.Top.Redraw (Frame);
  1699. } else {
  1700. SuperView.SetNeedsDisplay (Frame);
  1701. }
  1702. EnsureVisibleBounds (this, mouseEvent.X + mouseEvent.OfX - start.X,
  1703. mouseEvent.Y + mouseEvent.OfY, out nx, out ny);
  1704. dragPosition = new Point (nx, ny);
  1705. Frame = new Rect (nx, ny, Frame.Width, Frame.Height);
  1706. X = nx;
  1707. Y = ny;
  1708. //Demo.ml2.Text = $"{dx},{dy}";
  1709. // FIXED: optimize, only SetNeedsDisplay on the before/after regions.
  1710. SetNeedsDisplay ();
  1711. return true;
  1712. } else {
  1713. // Only start grabbing if the user clicks on the title bar.
  1714. if (mouseEvent.Y == 0) {
  1715. start = new Point (mouseEvent.X, mouseEvent.Y);
  1716. dragPosition = new Point ();
  1717. nx = mouseEvent.X - mouseEvent.OfX;
  1718. ny = mouseEvent.Y - mouseEvent.OfY;
  1719. dragPosition = new Point (nx, ny);
  1720. Application.GrabMouse (this);
  1721. }
  1722. //Demo.ml2.Text = $"Starting at {dragPosition}";
  1723. return true;
  1724. }
  1725. }
  1726. if (mouseEvent.Flags == MouseFlags.Button1Released && dragPosition.HasValue) {
  1727. Application.UngrabMouse ();
  1728. Driver.UncookMouse ();
  1729. dragPosition = null;
  1730. }
  1731. //Demo.ml.Text = me.ToString ();
  1732. return false;
  1733. }
  1734. }
  1735. /// <summary>
  1736. /// The application driver for gui.cs
  1737. /// </summary>
  1738. /// <remarks>
  1739. /// <para>
  1740. /// You can hook up to the Iteration event to have your method
  1741. /// invoked on each iteration of the mainloop.
  1742. /// </para>
  1743. /// <para>
  1744. /// Creates a mainloop to process input events, handle timers and
  1745. /// other sources of data. It is accessible via the MainLoop property.
  1746. /// </para>
  1747. /// <para>
  1748. /// When invoked sets the SynchronizationContext to one that is tied
  1749. /// to the mainloop, allowing user code to use async/await.
  1750. /// </para>
  1751. /// </remarks>
  1752. public static class Application {
  1753. /// <summary>
  1754. /// The current Console Driver in use.
  1755. /// </summary>
  1756. public static ConsoleDriver Driver;
  1757. /// <summary>
  1758. /// The Toplevel object used for the application on startup.
  1759. /// </summary>
  1760. /// <value>The top.</value>
  1761. public static Toplevel Top { get; private set; }
  1762. /// <summary>
  1763. /// The current toplevel object. This is updated when Application.Run enters and leaves and points to the current toplevel.
  1764. /// </summary>
  1765. /// <value>The current.</value>
  1766. public static Toplevel Current { get; private set; }
  1767. /// <summary>
  1768. /// TThe current view object being redrawn.
  1769. /// </summary>
  1770. /// /// <value>The current.</value>
  1771. public static View CurrentView { get; set; }
  1772. /// <summary>
  1773. /// The mainloop driver for the applicaiton
  1774. /// </summary>
  1775. /// <value>The main loop.</value>
  1776. public static Mono.Terminal.MainLoop MainLoop { get; private set; }
  1777. static Stack<Toplevel> toplevels = new Stack<Toplevel> ();
  1778. /// <summary>
  1779. /// This event is raised on each iteration of the
  1780. /// main loop.
  1781. /// </summary>
  1782. /// <remarks>
  1783. /// See also <see cref="Timeout"/>
  1784. /// </remarks>
  1785. static public event EventHandler Iteration;
  1786. /// <summary>
  1787. /// Returns a rectangle that is centered in the screen for the provided size.
  1788. /// </summary>
  1789. /// <returns>The centered rect.</returns>
  1790. /// <param name="size">Size for the rectangle.</param>
  1791. public static Rect MakeCenteredRect (Size size)
  1792. {
  1793. return new Rect (new Point ((Driver.Cols - size.Width) / 2, (Driver.Rows - size.Height) / 2), size);
  1794. }
  1795. //
  1796. // provides the sync context set while executing code in gui.cs, to let
  1797. // users use async/await on their code
  1798. //
  1799. class MainLoopSyncContext : SynchronizationContext {
  1800. Mono.Terminal.MainLoop mainLoop;
  1801. public MainLoopSyncContext (Mono.Terminal.MainLoop mainLoop)
  1802. {
  1803. this.mainLoop = mainLoop;
  1804. }
  1805. public override SynchronizationContext CreateCopy ()
  1806. {
  1807. return new MainLoopSyncContext (MainLoop);
  1808. }
  1809. public override void Post (SendOrPostCallback d, object state)
  1810. {
  1811. mainLoop.AddIdle (() => {
  1812. d (state);
  1813. return false;
  1814. });
  1815. mainLoop.Driver.Wakeup ();
  1816. }
  1817. public override void Send (SendOrPostCallback d, object state)
  1818. {
  1819. mainLoop.Invoke (() => {
  1820. d (state);
  1821. });
  1822. }
  1823. }
  1824. /// <summary>
  1825. /// If set, it forces the use of the System.Console-based driver.
  1826. /// </summary>
  1827. public static bool UseSystemConsole;
  1828. /// <summary>
  1829. /// Initializes the Application
  1830. /// </summary>
  1831. public static void Init () => Init (() => Toplevel.Create ());
  1832. internal static bool _initialized = false;
  1833. /// <summary>
  1834. /// Initializes the Application
  1835. /// </summary>
  1836. static void Init (Func<Toplevel> topLevelFactory)
  1837. {
  1838. if (_initialized) return;
  1839. var p = Environment.OSVersion.Platform;
  1840. Mono.Terminal.IMainLoopDriver mainLoopDriver;
  1841. if (UseSystemConsole) {
  1842. mainLoopDriver = new Mono.Terminal.NetMainLoop ();
  1843. Driver = new NetDriver ();
  1844. } else if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows){
  1845. var windowsDriver = new WindowsDriver ();
  1846. mainLoopDriver = windowsDriver;
  1847. Driver = windowsDriver;
  1848. } else {
  1849. mainLoopDriver = new Mono.Terminal.UnixMainLoop ();
  1850. Driver = new CursesDriver ();
  1851. }
  1852. Driver.Init (TerminalResized);
  1853. MainLoop = new Mono.Terminal.MainLoop (mainLoopDriver);
  1854. SynchronizationContext.SetSynchronizationContext (new MainLoopSyncContext (MainLoop));
  1855. Top = topLevelFactory ();
  1856. Current = Top;
  1857. CurrentView = Top;
  1858. _initialized = true;
  1859. }
  1860. /// <summary>
  1861. /// Captures the execution state for the provided TopLevel view.
  1862. /// </summary>
  1863. public class RunState : IDisposable {
  1864. internal RunState (Toplevel view)
  1865. {
  1866. Toplevel = view;
  1867. }
  1868. internal Toplevel Toplevel;
  1869. /// <summary>
  1870. /// Releases alTop = l resource used by the <see cref="T:Terminal.Gui.Application.RunState"/> object.
  1871. /// </summary>
  1872. /// <remarks>Call <see cref="Dispose()"/> when you are finished using the <see cref="T:Terminal.Gui.Application.RunState"/>. The
  1873. /// <see cref="Dispose()"/> method leaves the <see cref="T:Terminal.Gui.Application.RunState"/> in an unusable state. After
  1874. /// calling <see cref="Dispose()"/>, you must release all references to the
  1875. /// <see cref="T:Terminal.Gui.Application.RunState"/> so the garbage collector can reclaim the memory that the
  1876. /// <see cref="T:Terminal.Gui.Application.RunState"/> was occupying.</remarks>
  1877. public void Dispose ()
  1878. {
  1879. Dispose (true);
  1880. GC.SuppressFinalize (this);
  1881. }
  1882. /// <summary>
  1883. /// Dispose the specified disposing.
  1884. /// </summary>
  1885. /// <returns>The dispose.</returns>
  1886. /// <param name="disposing">If set to <c>true</c> disposing.</param>
  1887. protected virtual void Dispose (bool disposing)
  1888. {
  1889. if (Toplevel != null) {
  1890. End (Toplevel);
  1891. Toplevel = null;
  1892. }
  1893. }
  1894. }
  1895. static void ProcessKeyEvent (KeyEvent ke)
  1896. {
  1897. var chain = toplevels.ToList();
  1898. foreach (var topLevel in chain) {
  1899. if (topLevel.ProcessHotKey (ke))
  1900. return;
  1901. if (topLevel.Modal)
  1902. break;
  1903. }
  1904. foreach (var topLevel in chain) {
  1905. if (topLevel.ProcessKey (ke))
  1906. return;
  1907. if (topLevel.Modal)
  1908. break;
  1909. }
  1910. foreach (var topLevel in chain) {
  1911. // Process the key normally
  1912. if (topLevel.ProcessColdKey (ke))
  1913. return;
  1914. if (topLevel.Modal)
  1915. break;
  1916. }
  1917. }
  1918. static void ProcessKeyDownEvent (KeyEvent ke)
  1919. {
  1920. var chain = toplevels.ToList ();
  1921. foreach (var topLevel in chain) {
  1922. if (topLevel.OnKeyDown (ke))
  1923. return;
  1924. if (topLevel.Modal)
  1925. break;
  1926. }
  1927. }
  1928. static void ProcessKeyUpEvent (KeyEvent ke)
  1929. {
  1930. var chain = toplevels.ToList ();
  1931. foreach (var topLevel in chain) {
  1932. if (topLevel.OnKeyUp (ke))
  1933. return;
  1934. if (topLevel.Modal)
  1935. break;
  1936. }
  1937. }
  1938. static View FindDeepestView (View start, int x, int y, out int resx, out int resy)
  1939. {
  1940. var startFrame = start.Frame;
  1941. if (!startFrame.Contains (x, y)) {
  1942. resx = 0;
  1943. resy = 0;
  1944. return null;
  1945. }
  1946. if (start.InternalSubviews != null){
  1947. int count = start.InternalSubviews.Count;
  1948. if (count > 0) {
  1949. var rx = x - startFrame.X;
  1950. var ry = y - startFrame.Y;
  1951. for (int i = count - 1; i >= 0; i--) {
  1952. View v = start.InternalSubviews [i];
  1953. if (v.Frame.Contains (rx, ry)) {
  1954. var deep = FindDeepestView (v, rx, ry, out resx, out resy);
  1955. if (deep == null)
  1956. return v;
  1957. return deep;
  1958. }
  1959. }
  1960. }
  1961. }
  1962. resx = x-startFrame.X;
  1963. resy = y-startFrame.Y;
  1964. return start;
  1965. }
  1966. internal static View mouseGrabView;
  1967. /// <summary>
  1968. /// Grabs the mouse, forcing all mouse events to be routed to the specified view until UngrabMouse is called.
  1969. /// </summary>
  1970. /// <returns>The grab.</returns>
  1971. /// <param name="view">View that will receive all mouse events until UngrabMouse is invoked.</param>
  1972. public static void GrabMouse (View view)
  1973. {
  1974. if (view == null)
  1975. return;
  1976. mouseGrabView = view;
  1977. Driver.UncookMouse ();
  1978. }
  1979. /// <summary>
  1980. /// Releases the mouse grab, so mouse events will be routed to the view on which the mouse is.
  1981. /// </summary>
  1982. public static void UngrabMouse ()
  1983. {
  1984. mouseGrabView = null;
  1985. Driver.CookMouse ();
  1986. }
  1987. /// <summary>
  1988. /// Merely a debugging aid to see the raw mouse events
  1989. /// </summary>
  1990. static public Action<MouseEvent> RootMouseEvent;
  1991. internal static View wantContinuousButtonPressedView;
  1992. static View lastMouseOwnerView;
  1993. static void ProcessMouseEvent (MouseEvent me)
  1994. {
  1995. var view = FindDeepestView (Current, me.X, me.Y, out int rx, out int ry);
  1996. if (view != null && view.WantContinuousButtonPressed)
  1997. wantContinuousButtonPressedView = view;
  1998. else
  1999. wantContinuousButtonPressedView = null;
  2000. RootMouseEvent?.Invoke (me);
  2001. if (mouseGrabView != null) {
  2002. var newxy = mouseGrabView.ScreenToView (me.X, me.Y);
  2003. var nme = new MouseEvent () {
  2004. X = newxy.X,
  2005. Y = newxy.Y,
  2006. Flags = me.Flags,
  2007. OfX = me.X - newxy.X,
  2008. OfY = me.Y - newxy.Y,
  2009. View = view
  2010. };
  2011. mouseGrabView.MouseEvent (nme);
  2012. return;
  2013. }
  2014. if (view != null) {
  2015. var nme = new MouseEvent () {
  2016. X = rx,
  2017. Y = ry,
  2018. Flags = me.Flags,
  2019. OfX = rx,
  2020. OfY = ry,
  2021. View = view
  2022. };
  2023. if (lastMouseOwnerView == null) {
  2024. lastMouseOwnerView = view;
  2025. view.OnMouseEnter (nme);
  2026. } else if (lastMouseOwnerView != view) {
  2027. lastMouseOwnerView.OnMouseLeave (nme);
  2028. view.OnMouseEnter (nme);
  2029. lastMouseOwnerView = view;
  2030. }
  2031. if (!view.WantMousePositionReports && me.Flags == MouseFlags.ReportMousePosition)
  2032. return;
  2033. if (view.WantContinuousButtonPressed)
  2034. wantContinuousButtonPressedView = view;
  2035. else
  2036. wantContinuousButtonPressedView = null;
  2037. // Should we bubbled up the event, if it is not handled?
  2038. view.MouseEvent (nme);
  2039. }
  2040. }
  2041. /// <summary>
  2042. /// Action that is invoked once at beginning.
  2043. /// </summary>
  2044. static public Action OnLoad;
  2045. /// <summary>
  2046. /// Building block API: Prepares the provided toplevel for execution.
  2047. /// </summary>
  2048. /// <returns>The runstate handle that needs to be passed to the End() method upon completion.</returns>
  2049. /// <param name="toplevel">Toplevel to prepare execution for.</param>
  2050. /// <remarks>
  2051. /// This method prepares the provided toplevel for running with the focus,
  2052. /// it adds this to the list of toplevels, sets up the mainloop to process the
  2053. /// event, lays out the subviews, focuses the first element, and draws the
  2054. /// toplevel in the screen. This is usually followed by executing
  2055. /// the <see cref="RunLoop"/> method, and then the <see cref="End(RunState)"/> method upon termination which will
  2056. /// undo these changes.
  2057. /// </remarks>
  2058. static public RunState Begin (Toplevel toplevel)
  2059. {
  2060. if (toplevel == null)
  2061. throw new ArgumentNullException (nameof (toplevel));
  2062. var rs = new RunState (toplevel);
  2063. Init ();
  2064. if (toplevel is ISupportInitializeNotification initializableNotification &&
  2065. !initializableNotification.IsInitialized) {
  2066. initializableNotification.BeginInit();
  2067. initializableNotification.EndInit();
  2068. } else if (toplevel is ISupportInitialize initializable) {
  2069. initializable.BeginInit();
  2070. initializable.EndInit();
  2071. }
  2072. toplevels.Push (toplevel);
  2073. Current = toplevel;
  2074. Driver.PrepareToRun (MainLoop, ProcessKeyEvent, ProcessKeyDownEvent, ProcessKeyUpEvent, ProcessMouseEvent);
  2075. if (toplevel.LayoutStyle == LayoutStyle.Computed)
  2076. toplevel.RelativeLayout (new Rect (0, 0, Driver.Cols, Driver.Rows));
  2077. toplevel.LayoutSubviews ();
  2078. OnLoad?.Invoke ();
  2079. toplevel.WillPresent ();
  2080. Redraw (toplevel);
  2081. toplevel.PositionCursor ();
  2082. Driver.Refresh ();
  2083. return rs;
  2084. }
  2085. /// <summary>
  2086. /// Building block API: completes the execution of a Toplevel that was started with Begin.
  2087. /// </summary>
  2088. /// <param name="runState">The runstate returned by the <see cref="Begin(Toplevel)"/> method.</param>
  2089. static public void End (RunState runState)
  2090. {
  2091. if (runState == null)
  2092. throw new ArgumentNullException (nameof (runState));
  2093. runState.Dispose ();
  2094. }
  2095. /// <summary>
  2096. /// Finalize the driver.
  2097. /// </summary>
  2098. public static void Shutdown ()
  2099. {
  2100. Driver.End ();
  2101. _initialized = false;
  2102. }
  2103. static void Redraw (View view)
  2104. {
  2105. Application.CurrentView = view;
  2106. view.Redraw (view.Bounds);
  2107. Driver.Refresh ();
  2108. }
  2109. static void Refresh (View view)
  2110. {
  2111. view.Redraw (view.Bounds);
  2112. Driver.Refresh ();
  2113. }
  2114. /// <summary>
  2115. /// Triggers a refresh of the entire display.
  2116. /// </summary>
  2117. public static void Refresh ()
  2118. {
  2119. Driver.UpdateScreen ();
  2120. View last = null;
  2121. foreach (var v in toplevels.Reverse ()) {
  2122. v.SetNeedsDisplay ();
  2123. v.Redraw (v.Bounds);
  2124. last = v;
  2125. }
  2126. last?.PositionCursor ();
  2127. Driver.Refresh ();
  2128. }
  2129. internal static void End (View view)
  2130. {
  2131. if (toplevels.Peek () != view)
  2132. throw new ArgumentException ("The view that you end with must be balanced");
  2133. toplevels.Pop ();
  2134. if (toplevels.Count == 0)
  2135. Shutdown ();
  2136. else
  2137. {
  2138. Current = toplevels.Peek();
  2139. Refresh ();
  2140. }
  2141. }
  2142. /// <summary>
  2143. /// Building block API: Runs the main loop for the created dialog
  2144. /// </summary>
  2145. /// <remarks>
  2146. /// Use the wait parameter to control whether this is a
  2147. /// blocking or non-blocking call.
  2148. /// </remarks>
  2149. /// <param name="state">The state returned by the Begin method.</param>
  2150. /// <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>
  2151. public static void RunLoop (RunState state, bool wait = true)
  2152. {
  2153. if (state == null)
  2154. throw new ArgumentNullException (nameof (state));
  2155. if (state.Toplevel == null)
  2156. throw new ObjectDisposedException ("state");
  2157. for (state.Toplevel.Running = true; state.Toplevel.Running;) {
  2158. if (MainLoop.EventsPending (wait)) {
  2159. MainLoop.MainIteration ();
  2160. Iteration?.Invoke (null, EventArgs.Empty);
  2161. } else if (wait == false)
  2162. return;
  2163. if (!state.Toplevel.NeedDisplay.IsEmpty || state.Toplevel.childNeedsDisplay) {
  2164. state.Toplevel.Redraw (state.Toplevel.Bounds);
  2165. if (DebugDrawBounds)
  2166. DrawBounds (state.Toplevel);
  2167. state.Toplevel.PositionCursor ();
  2168. Driver.Refresh ();
  2169. } else
  2170. Driver.UpdateCursor ();
  2171. }
  2172. }
  2173. internal static bool DebugDrawBounds;
  2174. // Need to look into why this does not work properly.
  2175. static void DrawBounds (View v)
  2176. {
  2177. v.DrawFrame (v.Frame, padding: 0, fill: false);
  2178. if (v.InternalSubviews != null && v.InternalSubviews.Count > 0)
  2179. foreach (var sub in v.InternalSubviews)
  2180. DrawBounds (sub);
  2181. }
  2182. /// <summary>
  2183. /// Runs the application with the built-in toplevel view
  2184. /// </summary>
  2185. public static void Run ()
  2186. {
  2187. Run (Top);
  2188. }
  2189. /// <summary>
  2190. /// Runs the application with a new instance of the specified toplevel view
  2191. /// </summary>
  2192. public static void Run<T> () where T : Toplevel, new()
  2193. {
  2194. Init (() => new T());
  2195. Run (Top);
  2196. }
  2197. /// <summary>
  2198. /// Runs the main loop on the given container.
  2199. /// </summary>
  2200. /// <remarks>
  2201. /// <para>
  2202. /// This method is used to start processing events
  2203. /// for the main application, but it is also used to
  2204. /// run modal dialog boxes.
  2205. /// </para>
  2206. /// <para>
  2207. /// To make a toplevel stop execution, set the "Running"
  2208. /// property to false.
  2209. /// </para>
  2210. /// <para>
  2211. /// This is equivalent to calling Begin on the toplevel view, followed by RunLoop with the
  2212. /// returned value, and then calling end on the return value.
  2213. /// </para>
  2214. /// <para>
  2215. /// Alternatively, if your program needs to control the main loop and needs to
  2216. /// process events manually, you can invoke Begin to set things up manually and then
  2217. /// repeatedly call RunLoop with the wait parameter set to false. By doing this
  2218. /// the RunLoop method will only process any pending events, timers, idle handlers and
  2219. /// then return control immediately.
  2220. /// </para>
  2221. /// </remarks>
  2222. public static void Run (Toplevel view)
  2223. {
  2224. var runToken = Begin (view);
  2225. RunLoop (runToken);
  2226. End (runToken);
  2227. }
  2228. /// <summary>
  2229. /// Stops running the most recent toplevel
  2230. /// </summary>
  2231. public static void RequestStop ()
  2232. {
  2233. Current.Running = false;
  2234. }
  2235. /// <summary>
  2236. /// Invoked when the terminal was resized.
  2237. /// </summary>
  2238. static public Action OnResized;
  2239. static void TerminalResized ()
  2240. {
  2241. OnResized?.Invoke ();
  2242. var full = new Rect (0, 0, Driver.Cols, Driver.Rows);
  2243. Driver.Clip = full;
  2244. foreach (var t in toplevels) {
  2245. t.PositionToplevels ();
  2246. t.RelativeLayout (full);
  2247. t.LayoutSubviews ();
  2248. }
  2249. Refresh ();
  2250. }
  2251. }
  2252. }