Core.cs 73 KB

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