Core.cs 71 KB

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