Core.cs 75 KB

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