Core.cs 72 KB

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