Core.cs 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580
  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 bool HasMenuBar { get; set; }
  1392. /// <summary>
  1393. /// Check id current toplevel has status bar
  1394. /// </summary>
  1395. public bool HasStatusBar { 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. HasMenuBar = true;
  1450. if (view is StatusBar)
  1451. HasStatusBar = true;
  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. HasMenuBar = true;
  1461. if (view is StatusBar)
  1462. HasStatusBar = true;
  1463. }
  1464. base.Remove (view);
  1465. }
  1466. ///<inheritdoc cref="RemoveAll"/>
  1467. public override void RemoveAll ()
  1468. {
  1469. if (this == Application.Top) {
  1470. HasMenuBar = false;
  1471. HasStatusBar = false;
  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 || SuperView.GetType() != typeof(Toplevel))
  1481. m = Application.Top.HasMenuBar;
  1482. else
  1483. m = ((Toplevel)SuperView).HasMenuBar;
  1484. int l = m ? 1 : 0;
  1485. ny = Math.Max (y, l);
  1486. if (SuperView == null)
  1487. s = Application.Top.HasStatusBar;
  1488. else
  1489. s = ((Toplevel)SuperView).HasStatusBar;
  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 (HasStatusBar && ny + top.Frame.Height > Driver.Rows - 1) {
  1511. if (top.Height is Dim.DimFill)
  1512. top.Height = Dim.Fill () - 1;
  1513. }
  1514. }
  1515. }
  1516. }
  1517. }
  1518. ///<inheritdoc cref="Redraw"/>
  1519. public override void Redraw (Rect region)
  1520. {
  1521. Application.CurrentView = this;
  1522. if (this == Application.Top) {
  1523. if (!NeedDisplay.IsEmpty) {
  1524. Driver.SetAttribute (Colors.TopLevel.Normal);
  1525. Clear (region);
  1526. Driver.SetAttribute (Colors.Base.Normal);
  1527. }
  1528. foreach (var view in Subviews) {
  1529. if (view.Frame.IntersectsWith (region)) {
  1530. view.SetNeedsLayout ();
  1531. view.SetNeedsDisplay (view.Bounds);
  1532. }
  1533. }
  1534. ClearNeedsDisplay ();
  1535. }
  1536. base.Redraw (base.Bounds);
  1537. }
  1538. /// <summary>
  1539. /// This method is invoked by Application.Begin as part of the Application.Run after
  1540. /// the views have been laid out, and before the views are drawn for the first time.
  1541. /// </summary>
  1542. public virtual void WillPresent ()
  1543. {
  1544. FocusFirst ();
  1545. }
  1546. }
  1547. /// <summary>
  1548. /// A toplevel view that draws a frame around its region and has a "ContentView" subview where the contents are added.
  1549. /// </summary>
  1550. public class Window : Toplevel, IEnumerable {
  1551. View contentView;
  1552. ustring title;
  1553. /// <summary>
  1554. /// The title to be displayed for this window.
  1555. /// </summary>
  1556. /// <value>The title.</value>
  1557. public ustring Title {
  1558. get => title;
  1559. set {
  1560. title = value;
  1561. SetNeedsDisplay ();
  1562. }
  1563. }
  1564. class ContentView : View {
  1565. public ContentView (Rect frame) : base (frame) { }
  1566. public ContentView () : base () { }
  1567. #if false
  1568. public override void Redraw (Rect region)
  1569. {
  1570. Driver.SetAttribute (ColorScheme.Focus);
  1571. for (int y = 0; y < Frame.Height; y++) {
  1572. Move (0, y);
  1573. for (int x = 0; x < Frame.Width; x++) {
  1574. Driver.AddRune ('x');
  1575. }
  1576. }
  1577. }
  1578. #endif
  1579. }
  1580. /// <summary>
  1581. /// Initializes a new instance of the <see cref="T:Terminal.Gui.Gui.Window"/> class with an optional title and a set frame.
  1582. /// </summary>
  1583. /// <param name="frame">Frame.</param>
  1584. /// <param name="title">Title.</param>
  1585. public Window (Rect frame, ustring title = null) : this (frame, title, padding: 0)
  1586. {
  1587. }
  1588. /// <summary>
  1589. /// Initializes a new instance of the <see cref="T:Terminal.Gui.Window"/> class with an optional title.
  1590. /// </summary>
  1591. /// <param name="title">Title.</param>
  1592. public Window (ustring title = null) : this (title, padding: 0)
  1593. {
  1594. }
  1595. int padding;
  1596. /// <summary>
  1597. /// Initializes a new instance of the <see cref="T:Terminal.Gui.Window"/> with
  1598. /// the specified frame for its location, with the specified border
  1599. /// an optional title.
  1600. /// </summary>
  1601. /// <param name="frame">Frame.</param>
  1602. /// <param name="padding">Number of characters to use for padding of the drawn frame.</param>
  1603. /// <param name="title">Title.</param>
  1604. public Window (Rect frame, ustring title = null, int padding = 0) : base (frame)
  1605. {
  1606. this.Title = title;
  1607. int wb = 2 * (1 + padding);
  1608. this.padding = padding;
  1609. var cFrame = new Rect (1 + padding, 1 + padding, frame.Width - wb, frame.Height - wb);
  1610. contentView = new ContentView (cFrame);
  1611. base.Add (contentView);
  1612. }
  1613. /// <summary>
  1614. /// Initializes a new instance of the <see cref="T:Terminal.Gui.Window"/> with
  1615. /// the specified frame for its location, with the specified border
  1616. /// an optional title.
  1617. /// </summary>
  1618. /// <param name="padding">Number of characters to use for padding of the drawn frame.</param>
  1619. /// <param name="title">Title.</param>
  1620. public Window (ustring title = null, int padding = 0) : base ()
  1621. {
  1622. this.Title = title;
  1623. int wb = 1 + padding;
  1624. this.padding = padding;
  1625. contentView = new ContentView () {
  1626. X = wb,
  1627. Y = wb,
  1628. Width = Dim.Fill (wb),
  1629. Height = Dim.Fill (wb)
  1630. };
  1631. base.Add (contentView);
  1632. }
  1633. /// <summary>
  1634. /// Enumerates the various views in the ContentView.
  1635. /// </summary>
  1636. /// <returns>The enumerator.</returns>
  1637. public new IEnumerator GetEnumerator ()
  1638. {
  1639. return contentView.GetEnumerator ();
  1640. }
  1641. void DrawFrame (bool fill = true)
  1642. {
  1643. DrawFrame (new Rect (0, 0, Frame.Width, Frame.Height), padding, fill: fill);
  1644. }
  1645. /// <summary>
  1646. /// Add the specified view to the ContentView.
  1647. /// </summary>
  1648. /// <param name="view">View to add to the window.</param>
  1649. public override void Add (View view)
  1650. {
  1651. contentView.Add (view);
  1652. if (view.CanFocus)
  1653. CanFocus = true;
  1654. }
  1655. /// <summary>
  1656. /// Removes a widget from this container.
  1657. /// </summary>
  1658. /// <remarks>
  1659. /// </remarks>
  1660. public override void Remove (View view)
  1661. {
  1662. if (view == null)
  1663. return;
  1664. SetNeedsDisplay ();
  1665. var touched = view.Frame;
  1666. contentView.Remove (view);
  1667. if (contentView.InternalSubviews.Count < 1)
  1668. this.CanFocus = false;
  1669. }
  1670. /// <summary>
  1671. /// Removes all widgets from this container.
  1672. /// </summary>
  1673. /// <remarks>
  1674. /// </remarks>
  1675. public override void RemoveAll ()
  1676. {
  1677. contentView.RemoveAll ();
  1678. }
  1679. ///<inheritdoc cref="Redraw"/>
  1680. public override void Redraw (Rect bounds)
  1681. {
  1682. Application.CurrentView = this;
  1683. if (!NeedDisplay.IsEmpty) {
  1684. DrawFrameWindow ();
  1685. }
  1686. contentView.Redraw (contentView.Bounds);
  1687. ClearNeedsDisplay ();
  1688. DrawFrameWindow (false);
  1689. void DrawFrameWindow (bool fill = true)
  1690. {
  1691. Driver.SetAttribute (ColorScheme.Normal);
  1692. DrawFrame (fill);
  1693. if (HasFocus)
  1694. Driver.SetAttribute (ColorScheme.HotNormal);
  1695. var width = Frame.Width - (padding + 2) * 2;
  1696. if (Title != null && width > 4) {
  1697. Move (1 + padding, padding);
  1698. Driver.AddRune (' ');
  1699. var str = Title.Length >= width ? Title [0, width - 2] : Title;
  1700. Driver.AddStr (str);
  1701. Driver.AddRune (' ');
  1702. }
  1703. Driver.SetAttribute (ColorScheme.Normal);
  1704. }
  1705. }
  1706. //
  1707. // FIXED:It does not look like the event is raised on clicked-drag
  1708. // need to figure that out.
  1709. //
  1710. internal static Point? dragPosition;
  1711. Point start;
  1712. ///<inheritdoc cref="MouseEvent(Gui.MouseEvent)"/>
  1713. public override bool MouseEvent (MouseEvent mouseEvent)
  1714. {
  1715. // FIXED:The code is currently disabled, because the
  1716. // Driver.UncookMouse does not seem to have an effect if there is
  1717. // a pending mouse event activated.
  1718. int nx, ny;
  1719. if ((mouseEvent.Flags == (MouseFlags.Button1Pressed | MouseFlags.ReportMousePosition) ||
  1720. mouseEvent.Flags == MouseFlags.Button3Pressed)) {
  1721. if (dragPosition.HasValue) {
  1722. if (SuperView == null) {
  1723. Application.Top.SetNeedsDisplay (Frame);
  1724. Application.Top.Redraw (Frame);
  1725. } else {
  1726. SuperView.SetNeedsDisplay (Frame);
  1727. }
  1728. EnsureVisibleBounds (this, mouseEvent.X + mouseEvent.OfX - start.X,
  1729. mouseEvent.Y + mouseEvent.OfY, out nx, out ny);
  1730. dragPosition = new Point (nx, ny);
  1731. Frame = new Rect (nx, ny, Frame.Width, Frame.Height);
  1732. X = nx;
  1733. Y = ny;
  1734. //Demo.ml2.Text = $"{dx},{dy}";
  1735. // FIXED: optimize, only SetNeedsDisplay on the before/after regions.
  1736. SetNeedsDisplay ();
  1737. return true;
  1738. } else {
  1739. // Only start grabbing if the user clicks on the title bar.
  1740. if (mouseEvent.Y == 0) {
  1741. start = new Point (mouseEvent.X, mouseEvent.Y);
  1742. dragPosition = new Point ();
  1743. nx = mouseEvent.X - mouseEvent.OfX;
  1744. ny = mouseEvent.Y - mouseEvent.OfY;
  1745. dragPosition = new Point (nx, ny);
  1746. Application.GrabMouse (this);
  1747. }
  1748. //Demo.ml2.Text = $"Starting at {dragPosition}";
  1749. return true;
  1750. }
  1751. }
  1752. if (mouseEvent.Flags == MouseFlags.Button1Released && dragPosition.HasValue) {
  1753. Application.UngrabMouse ();
  1754. Driver.UncookMouse ();
  1755. dragPosition = null;
  1756. }
  1757. //Demo.ml.Text = me.ToString ();
  1758. return false;
  1759. }
  1760. }
  1761. /// <summary>
  1762. /// The application driver for gui.cs
  1763. /// </summary>
  1764. /// <remarks>
  1765. /// <para>
  1766. /// You can hook up to the Iteration event to have your method
  1767. /// invoked on each iteration of the mainloop.
  1768. /// </para>
  1769. /// <para>
  1770. /// Creates a mainloop to process input events, handle timers and
  1771. /// other sources of data. It is accessible via the MainLoop property.
  1772. /// </para>
  1773. /// <para>
  1774. /// When invoked sets the SynchronizationContext to one that is tied
  1775. /// to the mainloop, allowing user code to use async/await.
  1776. /// </para>
  1777. /// </remarks>
  1778. public static class Application {
  1779. /// <summary>
  1780. /// The current Console Driver in use.
  1781. /// </summary>
  1782. public static ConsoleDriver Driver;
  1783. /// <summary>
  1784. /// The Toplevel object used for the application on startup.
  1785. /// </summary>
  1786. /// <value>The top.</value>
  1787. public static Toplevel Top { get; private set; }
  1788. /// <summary>
  1789. /// The current toplevel object. This is updated when Application.Run enters and leaves and points to the current toplevel.
  1790. /// </summary>
  1791. /// <value>The current.</value>
  1792. public static Toplevel Current { get; private set; }
  1793. /// <summary>
  1794. /// TThe current view object being redrawn.
  1795. /// </summary>
  1796. /// /// <value>The current.</value>
  1797. public static View CurrentView { get; set; }
  1798. /// <summary>
  1799. /// The mainloop driver for the applicaiton
  1800. /// </summary>
  1801. /// <value>The main loop.</value>
  1802. public static Mono.Terminal.MainLoop MainLoop { get; private set; }
  1803. static Stack<Toplevel> toplevels = new Stack<Toplevel> ();
  1804. /// <summary>
  1805. /// This event is raised on each iteration of the
  1806. /// main loop.
  1807. /// </summary>
  1808. /// <remarks>
  1809. /// See also <see cref="Timeout"/>
  1810. /// </remarks>
  1811. public static event EventHandler Iteration;
  1812. /// <summary>
  1813. /// Returns a rectangle that is centered in the screen for the provided size.
  1814. /// </summary>
  1815. /// <returns>The centered rect.</returns>
  1816. /// <param name="size">Size for the rectangle.</param>
  1817. public static Rect MakeCenteredRect (Size size)
  1818. {
  1819. return new Rect (new Point ((Driver.Cols - size.Width) / 2, (Driver.Rows - size.Height) / 2), size);
  1820. }
  1821. //
  1822. // provides the sync context set while executing code in gui.cs, to let
  1823. // users use async/await on their code
  1824. //
  1825. class MainLoopSyncContext : SynchronizationContext {
  1826. Mono.Terminal.MainLoop mainLoop;
  1827. public MainLoopSyncContext (Mono.Terminal.MainLoop mainLoop)
  1828. {
  1829. this.mainLoop = mainLoop;
  1830. }
  1831. public override SynchronizationContext CreateCopy ()
  1832. {
  1833. return new MainLoopSyncContext (MainLoop);
  1834. }
  1835. public override void Post (SendOrPostCallback d, object state)
  1836. {
  1837. mainLoop.AddIdle (() => {
  1838. d (state);
  1839. return false;
  1840. });
  1841. mainLoop.Driver.Wakeup ();
  1842. }
  1843. public override void Send (SendOrPostCallback d, object state)
  1844. {
  1845. mainLoop.Invoke (() => {
  1846. d (state);
  1847. });
  1848. }
  1849. }
  1850. /// <summary>
  1851. /// If set, it forces the use of the System.Console-based driver.
  1852. /// </summary>
  1853. public static bool UseSystemConsole;
  1854. /// <summary>
  1855. /// Initializes the Application
  1856. /// </summary>
  1857. public static void Init () => Init (() => Toplevel.Create ());
  1858. internal static bool _initialized = false;
  1859. /// <summary>
  1860. /// Initializes the Application
  1861. /// </summary>
  1862. static void Init (Func<Toplevel> topLevelFactory)
  1863. {
  1864. if (_initialized) return;
  1865. var p = Environment.OSVersion.Platform;
  1866. Mono.Terminal.IMainLoopDriver mainLoopDriver;
  1867. if (UseSystemConsole) {
  1868. mainLoopDriver = new Mono.Terminal.NetMainLoop ();
  1869. Driver = new NetDriver ();
  1870. } else if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows) {
  1871. var windowsDriver = new WindowsDriver ();
  1872. mainLoopDriver = windowsDriver;
  1873. Driver = windowsDriver;
  1874. } else {
  1875. mainLoopDriver = new Mono.Terminal.UnixMainLoop ();
  1876. Driver = new CursesDriver ();
  1877. }
  1878. Driver.Init (TerminalResized);
  1879. MainLoop = new Mono.Terminal.MainLoop (mainLoopDriver);
  1880. SynchronizationContext.SetSynchronizationContext (new MainLoopSyncContext (MainLoop));
  1881. Top = topLevelFactory ();
  1882. Current = Top;
  1883. CurrentView = Top;
  1884. _initialized = true;
  1885. }
  1886. /// <summary>
  1887. /// Captures the execution state for the provided TopLevel view.
  1888. /// </summary>
  1889. public class RunState : IDisposable {
  1890. internal RunState (Toplevel view)
  1891. {
  1892. Toplevel = view;
  1893. }
  1894. internal Toplevel Toplevel;
  1895. /// <summary>
  1896. /// Releases alTop = l resource used by the <see cref="T:Terminal.Gui.Application.RunState"/> object.
  1897. /// </summary>
  1898. /// <remarks>Call <see cref="Dispose()"/> when you are finished using the <see cref="T:Terminal.Gui.Application.RunState"/>. The
  1899. /// <see cref="Dispose()"/> method leaves the <see cref="T:Terminal.Gui.Application.RunState"/> in an unusable state. After
  1900. /// calling <see cref="Dispose()"/>, you must release all references to the
  1901. /// <see cref="T:Terminal.Gui.Application.RunState"/> so the garbage collector can reclaim the memory that the
  1902. /// <see cref="T:Terminal.Gui.Application.RunState"/> was occupying.</remarks>
  1903. public void Dispose ()
  1904. {
  1905. Dispose (true);
  1906. GC.SuppressFinalize (this);
  1907. }
  1908. /// <summary>
  1909. /// Dispose the specified disposing.
  1910. /// </summary>
  1911. /// <returns>The dispose.</returns>
  1912. /// <param name="disposing">If set to <c>true</c> disposing.</param>
  1913. protected virtual void Dispose (bool disposing)
  1914. {
  1915. if (Toplevel != null) {
  1916. End (Toplevel);
  1917. Toplevel = null;
  1918. }
  1919. }
  1920. }
  1921. static void ProcessKeyEvent (KeyEvent ke)
  1922. {
  1923. var chain = toplevels.ToList ();
  1924. foreach (var topLevel in chain) {
  1925. if (topLevel.ProcessHotKey (ke))
  1926. return;
  1927. if (topLevel.Modal)
  1928. break;
  1929. }
  1930. foreach (var topLevel in chain) {
  1931. if (topLevel.ProcessKey (ke))
  1932. return;
  1933. if (topLevel.Modal)
  1934. break;
  1935. }
  1936. foreach (var topLevel in chain) {
  1937. // Process the key normally
  1938. if (topLevel.ProcessColdKey (ke))
  1939. return;
  1940. if (topLevel.Modal)
  1941. break;
  1942. }
  1943. }
  1944. static void ProcessKeyDownEvent (KeyEvent ke)
  1945. {
  1946. var chain = toplevels.ToList ();
  1947. foreach (var topLevel in chain) {
  1948. if (topLevel.OnKeyDown (ke))
  1949. return;
  1950. if (topLevel.Modal)
  1951. break;
  1952. }
  1953. }
  1954. static void ProcessKeyUpEvent (KeyEvent ke)
  1955. {
  1956. var chain = toplevels.ToList ();
  1957. foreach (var topLevel in chain) {
  1958. if (topLevel.OnKeyUp (ke))
  1959. return;
  1960. if (topLevel.Modal)
  1961. break;
  1962. }
  1963. }
  1964. static View FindDeepestView (View start, int x, int y, out int resx, out int resy)
  1965. {
  1966. var startFrame = start.Frame;
  1967. if (!startFrame.Contains (x, y)) {
  1968. resx = 0;
  1969. resy = 0;
  1970. return null;
  1971. }
  1972. if (start.InternalSubviews != null) {
  1973. int count = start.InternalSubviews.Count;
  1974. if (count > 0) {
  1975. var rx = x - startFrame.X;
  1976. var ry = y - startFrame.Y;
  1977. for (int i = count - 1; i >= 0; i--) {
  1978. View v = start.InternalSubviews [i];
  1979. if (v.Frame.Contains (rx, ry)) {
  1980. var deep = FindDeepestView (v, rx, ry, out resx, out resy);
  1981. if (deep == null)
  1982. return v;
  1983. return deep;
  1984. }
  1985. }
  1986. }
  1987. }
  1988. resx = x - startFrame.X;
  1989. resy = y - startFrame.Y;
  1990. return start;
  1991. }
  1992. internal static View mouseGrabView;
  1993. /// <summary>
  1994. /// Grabs the mouse, forcing all mouse events to be routed to the specified view until UngrabMouse is called.
  1995. /// </summary>
  1996. /// <returns>The grab.</returns>
  1997. /// <param name="view">View that will receive all mouse events until UngrabMouse is invoked.</param>
  1998. public static void GrabMouse (View view)
  1999. {
  2000. if (view == null)
  2001. return;
  2002. mouseGrabView = view;
  2003. Driver.UncookMouse ();
  2004. }
  2005. /// <summary>
  2006. /// Releases the mouse grab, so mouse events will be routed to the view on which the mouse is.
  2007. /// </summary>
  2008. public static void UngrabMouse ()
  2009. {
  2010. mouseGrabView = null;
  2011. Driver.CookMouse ();
  2012. }
  2013. /// <summary>
  2014. /// Merely a debugging aid to see the raw mouse events
  2015. /// </summary>
  2016. public static Action<MouseEvent> RootMouseEvent;
  2017. internal static View wantContinuousButtonPressedView;
  2018. static View lastMouseOwnerView;
  2019. static void ProcessMouseEvent (MouseEvent me)
  2020. {
  2021. var view = FindDeepestView (Current, me.X, me.Y, out int rx, out int ry);
  2022. if (view != null && view.WantContinuousButtonPressed)
  2023. wantContinuousButtonPressedView = view;
  2024. else
  2025. wantContinuousButtonPressedView = null;
  2026. RootMouseEvent?.Invoke (me);
  2027. if (mouseGrabView != null) {
  2028. var newxy = mouseGrabView.ScreenToView (me.X, me.Y);
  2029. var nme = new MouseEvent () {
  2030. X = newxy.X,
  2031. Y = newxy.Y,
  2032. Flags = me.Flags,
  2033. OfX = me.X - newxy.X,
  2034. OfY = me.Y - newxy.Y,
  2035. View = view
  2036. };
  2037. if (OutsideFrame (new Point (nme.X, nme.Y), mouseGrabView.Frame))
  2038. lastMouseOwnerView.OnMouseLeave (me);
  2039. if (mouseGrabView != null) {
  2040. mouseGrabView.MouseEvent (nme);
  2041. return;
  2042. }
  2043. }
  2044. if (view != null) {
  2045. var nme = new MouseEvent () {
  2046. X = rx,
  2047. Y = ry,
  2048. Flags = me.Flags,
  2049. OfX = rx,
  2050. OfY = ry,
  2051. View = view
  2052. };
  2053. if (lastMouseOwnerView == null) {
  2054. lastMouseOwnerView = view;
  2055. view.OnMouseEnter (nme);
  2056. } else if (lastMouseOwnerView != view) {
  2057. lastMouseOwnerView.OnMouseLeave (nme);
  2058. view.OnMouseEnter (nme);
  2059. lastMouseOwnerView = view;
  2060. }
  2061. if (!view.WantMousePositionReports && me.Flags == MouseFlags.ReportMousePosition)
  2062. return;
  2063. if (view.WantContinuousButtonPressed)
  2064. wantContinuousButtonPressedView = view;
  2065. else
  2066. wantContinuousButtonPressedView = null;
  2067. // Should we bubbled up the event, if it is not handled?
  2068. view.MouseEvent (nme);
  2069. }
  2070. }
  2071. static bool OutsideFrame (Point p, Rect r)
  2072. {
  2073. return p.X < 0 || p.X > r.Width - 1 || p.Y < 0 || p.Y > r.Height - 1;
  2074. }
  2075. /// <summary>
  2076. /// This event is fired once when the application is first loaded. The dimensions of the
  2077. /// terminal are provided.
  2078. /// </summary>
  2079. public static event EventHandler<ResizedEventArgs> Loaded;
  2080. /// <summary>
  2081. /// Building block API: Prepares the provided toplevel for execution.
  2082. /// </summary>
  2083. /// <returns>The runstate handle that needs to be passed to the End() method upon completion.</returns>
  2084. /// <param name="toplevel">Toplevel to prepare execution for.</param>
  2085. /// <remarks>
  2086. /// This method prepares the provided toplevel for running with the focus,
  2087. /// it adds this to the list of toplevels, sets up the mainloop to process the
  2088. /// event, lays out the subviews, focuses the first element, and draws the
  2089. /// toplevel in the screen. This is usually followed by executing
  2090. /// the <see cref="RunLoop"/> method, and then the <see cref="End(RunState)"/> method upon termination which will
  2091. /// undo these changes.
  2092. /// </remarks>
  2093. public static RunState Begin (Toplevel toplevel)
  2094. {
  2095. if (toplevel == null)
  2096. throw new ArgumentNullException (nameof (toplevel));
  2097. var rs = new RunState (toplevel);
  2098. Init ();
  2099. if (toplevel is ISupportInitializeNotification initializableNotification &&
  2100. !initializableNotification.IsInitialized) {
  2101. initializableNotification.BeginInit ();
  2102. initializableNotification.EndInit ();
  2103. } else if (toplevel is ISupportInitialize initializable) {
  2104. initializable.BeginInit ();
  2105. initializable.EndInit ();
  2106. }
  2107. toplevels.Push (toplevel);
  2108. Current = toplevel;
  2109. Driver.PrepareToRun (MainLoop, ProcessKeyEvent, ProcessKeyDownEvent, ProcessKeyUpEvent, ProcessMouseEvent);
  2110. if (toplevel.LayoutStyle == LayoutStyle.Computed)
  2111. toplevel.RelativeLayout (new Rect (0, 0, Driver.Cols, Driver.Rows));
  2112. toplevel.LayoutSubviews ();
  2113. Loaded?.Invoke (null, new ResizedEventArgs () { Rows = Driver.Rows, Cols = Driver.Cols } );
  2114. toplevel.WillPresent ();
  2115. Redraw (toplevel);
  2116. toplevel.PositionCursor ();
  2117. Driver.Refresh ();
  2118. return rs;
  2119. }
  2120. /// <summary>
  2121. /// Building block API: completes the execution of a Toplevel that was started with Begin.
  2122. /// </summary>
  2123. /// <param name="runState">The runstate returned by the <see cref="Begin(Toplevel)"/> method.</param>
  2124. public static void End (RunState runState)
  2125. {
  2126. if (runState == null)
  2127. throw new ArgumentNullException (nameof (runState));
  2128. runState.Dispose ();
  2129. }
  2130. /// <summary>
  2131. /// Finalize the driver.
  2132. /// </summary>
  2133. public static void Shutdown ()
  2134. {
  2135. Driver.End ();
  2136. _initialized = false;
  2137. }
  2138. static void Redraw (View view)
  2139. {
  2140. Application.CurrentView = view;
  2141. view.Redraw (view.Bounds);
  2142. Driver.Refresh ();
  2143. }
  2144. static void Refresh (View view)
  2145. {
  2146. view.Redraw (view.Bounds);
  2147. Driver.Refresh ();
  2148. }
  2149. /// <summary>
  2150. /// Triggers a refresh of the entire display.
  2151. /// </summary>
  2152. public static void Refresh ()
  2153. {
  2154. Driver.UpdateScreen ();
  2155. View last = null;
  2156. foreach (var v in toplevels.Reverse ()) {
  2157. v.SetNeedsDisplay ();
  2158. v.Redraw (v.Bounds);
  2159. last = v;
  2160. }
  2161. last?.PositionCursor ();
  2162. Driver.Refresh ();
  2163. }
  2164. internal static void End (View view)
  2165. {
  2166. if (toplevels.Peek () != view)
  2167. throw new ArgumentException ("The view that you end with must be balanced");
  2168. toplevels.Pop ();
  2169. if (toplevels.Count == 0)
  2170. Shutdown ();
  2171. else {
  2172. Current = toplevels.Peek ();
  2173. Refresh ();
  2174. }
  2175. }
  2176. /// <summary>
  2177. /// Building block API: Runs the main loop for the created dialog
  2178. /// </summary>
  2179. /// <remarks>
  2180. /// Use the wait parameter to control whether this is a
  2181. /// blocking or non-blocking call.
  2182. /// </remarks>
  2183. /// <param name="state">The state returned by the Begin method.</param>
  2184. /// <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>
  2185. public static void RunLoop (RunState state, bool wait = true)
  2186. {
  2187. if (state == null)
  2188. throw new ArgumentNullException (nameof (state));
  2189. if (state.Toplevel == null)
  2190. throw new ObjectDisposedException ("state");
  2191. bool firstIteration = true;
  2192. for (state.Toplevel.Running = true; state.Toplevel.Running;) {
  2193. if (MainLoop.EventsPending (wait)) {
  2194. // Notify Toplevel it's ready
  2195. if (firstIteration) {
  2196. state.Toplevel.OnReady ();
  2197. }
  2198. firstIteration = false;
  2199. MainLoop.MainIteration ();
  2200. Iteration?.Invoke (null, EventArgs.Empty);
  2201. } else if (wait == false)
  2202. return;
  2203. if (!state.Toplevel.NeedDisplay.IsEmpty || state.Toplevel.childNeedsDisplay) {
  2204. state.Toplevel.Redraw (state.Toplevel.Bounds);
  2205. if (DebugDrawBounds)
  2206. DrawBounds (state.Toplevel);
  2207. state.Toplevel.PositionCursor ();
  2208. Driver.Refresh ();
  2209. } else
  2210. Driver.UpdateCursor ();
  2211. }
  2212. }
  2213. internal static bool DebugDrawBounds = false;
  2214. // Need to look into why this does not work properly.
  2215. static void DrawBounds (View v)
  2216. {
  2217. v.DrawFrame (v.Frame, padding: 0, fill: false);
  2218. if (v.InternalSubviews != null && v.InternalSubviews.Count > 0)
  2219. foreach (var sub in v.InternalSubviews)
  2220. DrawBounds (sub);
  2221. }
  2222. /// <summary>
  2223. /// Runs the application with the built-in toplevel view
  2224. /// </summary>
  2225. public static void Run ()
  2226. {
  2227. Run (Top);
  2228. }
  2229. /// <summary>
  2230. /// Runs the application with a new instance of the specified toplevel view
  2231. /// </summary>
  2232. public static void Run<T> () where T : Toplevel, new()
  2233. {
  2234. Init (() => new T ());
  2235. Run (Top);
  2236. }
  2237. /// <summary>
  2238. /// Runs the main loop on the given container.
  2239. /// </summary>
  2240. /// <remarks>
  2241. /// <para>
  2242. /// This method is used to start processing events
  2243. /// for the main application, but it is also used to
  2244. /// run modal dialog boxes.
  2245. /// </para>
  2246. /// <para>
  2247. /// To make a toplevel stop execution, set the "Running"
  2248. /// property to false.
  2249. /// </para>
  2250. /// <para>
  2251. /// This is equivalent to calling Begin on the toplevel view, followed by RunLoop with the
  2252. /// returned value, and then calling end on the return value.
  2253. /// </para>
  2254. /// <para>
  2255. /// Alternatively, if your program needs to control the main loop and needs to
  2256. /// process events manually, you can invoke Begin to set things up manually and then
  2257. /// repeatedly call RunLoop with the wait parameter set to false. By doing this
  2258. /// the RunLoop method will only process any pending events, timers, idle handlers and
  2259. /// then return control immediately.
  2260. /// </para>
  2261. /// </remarks>
  2262. public static void Run (Toplevel view)
  2263. {
  2264. var runToken = Begin (view);
  2265. RunLoop (runToken);
  2266. End (runToken);
  2267. }
  2268. /// <summary>
  2269. /// Stops running the most recent toplevel
  2270. /// </summary>
  2271. public static void RequestStop ()
  2272. {
  2273. Current.Running = false;
  2274. }
  2275. /// <summary>
  2276. /// Event arguments for the <see cref="T:Terminal.Gui.Application.Resized"/> event.
  2277. /// </summary>
  2278. public class ResizedEventArgs : EventArgs {
  2279. /// <summary>
  2280. /// The number of rows in the resized terminal.
  2281. /// </summary>
  2282. public int Rows { get; set; }
  2283. /// <summary>
  2284. /// The number of columns in the resized terminal.
  2285. /// </summary>
  2286. public int Cols { get; set; }
  2287. }
  2288. /// <summary>
  2289. /// Invoked when the terminal was resized. The new size of the terminal is provided.
  2290. /// </summary>
  2291. public static event EventHandler<ResizedEventArgs> Resized;
  2292. static void TerminalResized ()
  2293. {
  2294. var full = new Rect (0, 0, Driver.Cols, Driver.Rows);
  2295. Resized?.Invoke (null, new ResizedEventArgs () { Cols = full.Width, Rows = full.Height });
  2296. Driver.Clip = full;
  2297. foreach (var t in toplevels) {
  2298. t.PositionToplevels ();
  2299. t.RelativeLayout (full);
  2300. t.LayoutSubviews ();
  2301. }
  2302. Refresh ();
  2303. }
  2304. }
  2305. }