Core.cs 65 KB

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