Core.cs 67 KB

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