Core.cs 24 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  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. namespace Terminal {
  20. public class Responder {
  21. public virtual bool CanFocus { get; set; }
  22. public virtual bool HasFocus { get; internal set; }
  23. // Key handling
  24. /// <summary>
  25. /// This method can be overwritten by view that
  26. /// want to provide accelerator functionality
  27. /// (Alt-key for example).
  28. /// </summary>
  29. /// <remarks>
  30. /// <para>
  31. /// Before keys are sent to the subview on the
  32. /// current view, all the views are
  33. /// processed and the key is passed to the widgets
  34. /// to allow some of them to process the keystroke
  35. /// as a hot-key. </para>
  36. /// <para>
  37. /// For example, if you implement a button that
  38. /// has a hotkey ok "o", you would catch the
  39. /// combination Alt-o here. If the event is
  40. /// caught, you must return true to stop the
  41. /// keystroke from being dispatched to other
  42. /// views.
  43. /// </para>
  44. /// </remarks>
  45. public virtual bool ProcessHotKey (KeyEvent kb)
  46. {
  47. return false;
  48. }
  49. /// <summary>
  50. /// If the view is focused, gives the view a
  51. /// chance to process the keystroke.
  52. /// </summary>
  53. /// <remarks>
  54. /// <para>
  55. /// Views can override this method if they are
  56. /// interested in processing the given keystroke.
  57. /// If they consume the keystroke, they must
  58. /// return true to stop the keystroke from being
  59. /// processed by other widgets or consumed by the
  60. /// widget engine. If they return false, the
  61. /// keystroke will be passed using the ProcessColdKey
  62. /// method to other views to process.
  63. /// </para>
  64. /// </remarks>
  65. public virtual bool ProcessKey (KeyEvent kb)
  66. {
  67. return false;
  68. }
  69. /// <summary>
  70. /// This method can be overwritten by views that
  71. /// want to provide accelerator functionality
  72. /// (Alt-key for example), but without
  73. /// interefering with normal ProcessKey behavior.
  74. /// </summary>
  75. /// <remarks>
  76. /// <para>
  77. /// After keys are sent to the subviews on the
  78. /// current view, all the view are
  79. /// processed and the key is passed to the views
  80. /// to allow some of them to process the keystroke
  81. /// as a cold-key. </para>
  82. /// <para>
  83. /// This functionality is used, for example, by
  84. /// default buttons to act on the enter key.
  85. /// Processing this as a hot-key would prevent
  86. /// non-default buttons from consuming the enter
  87. /// keypress when they have the focus.
  88. /// </para>
  89. /// </remarks>
  90. public virtual bool ProcessColdKey (KeyEvent kb)
  91. {
  92. return false;
  93. }
  94. // Mouse events
  95. public virtual void MouseEvent (Event.Mouse me) { }
  96. }
  97. public class View : Responder, IEnumerable {
  98. string id = "";
  99. View container = null;
  100. View focused = null;
  101. public static ConsoleDriver Driver = Application.Driver;
  102. public static IList<View> empty = new List<View> (0).AsReadOnly ();
  103. List<View> subviews;
  104. public IList<View> Subviews => subviews == null ? empty : subviews.AsReadOnly ();
  105. internal Rect NeedDisplay { get; private set; } = Rect.Empty;
  106. // The frame for the object
  107. Rect frame;
  108. public string Id {
  109. get => id;
  110. set {
  111. id = value;
  112. }
  113. }
  114. // The frame for this view
  115. public Rect Frame {
  116. get => frame;
  117. set {
  118. if (SuperView != null) {
  119. SuperView.SetNeedsDisplay (frame);
  120. SuperView.SetNeedsDisplay (value);
  121. }
  122. frame = value;
  123. SetNeedsDisplay (frame);
  124. }
  125. }
  126. public IEnumerator GetEnumerator ()
  127. {
  128. foreach (var v in subviews)
  129. yield return v;
  130. }
  131. public Rect Bounds {
  132. get => new Rect (Point.Empty, Frame.Size);
  133. set {
  134. Frame = new Rect (frame.Location, value.Size);
  135. }
  136. }
  137. public View SuperView => container;
  138. public View (Rect frame)
  139. {
  140. this.Frame = frame;
  141. CanFocus = false;
  142. }
  143. /// <summary>
  144. /// Invoke to flag that this view needs to be redisplayed, by any code
  145. /// that alters the state of the view.
  146. /// </summary>
  147. public void SetNeedsDisplay ()
  148. {
  149. SetNeedsDisplay (Frame);
  150. }
  151. public void SetNeedsDisplay (Rect region)
  152. {
  153. if (NeedDisplay.IsEmpty)
  154. NeedDisplay = region;
  155. else {
  156. var x = Math.Min (NeedDisplay.X, region.X);
  157. var y = Math.Min (NeedDisplay.Y, region.Y);
  158. var w = Math.Max (NeedDisplay.Width, region.Width);
  159. var h = Math.Max (NeedDisplay.Height, region.Height);
  160. NeedDisplay = new Rect (x, y, w, h);
  161. }
  162. if (container != null)
  163. container.ChildNeedsDisplay ();
  164. if (subviews == null)
  165. return;
  166. foreach (var view in subviews)
  167. if (view.Frame.IntersectsWith (region)) {
  168. view.SetNeedsDisplay (Rect.Intersect (view.Frame, region));
  169. }
  170. }
  171. internal bool childNeedsDisplay;
  172. public void ChildNeedsDisplay ()
  173. {
  174. childNeedsDisplay = true;
  175. if (container != null)
  176. container.ChildNeedsDisplay ();
  177. }
  178. /// <summary>
  179. /// Adds a subview to this view.
  180. /// </summary>
  181. /// <remarks>
  182. /// </remarks>
  183. public virtual void Add (View view)
  184. {
  185. if (view == null)
  186. return;
  187. if (subviews == null)
  188. subviews = new List<View> ();
  189. subviews.Add (view);
  190. view.container = this;
  191. if (view.CanFocus)
  192. CanFocus = true;
  193. SetNeedsDisplay ();
  194. }
  195. public void Add (params View [] views)
  196. {
  197. if (views == null)
  198. return;
  199. foreach (var view in views)
  200. Add (view);
  201. }
  202. /// <summary>
  203. /// Removes all the widgets from this container.
  204. /// </summary>
  205. /// <remarks>
  206. /// </remarks>
  207. public virtual void RemoveAll ()
  208. {
  209. if (subviews == null)
  210. return;
  211. while (subviews.Count > 0) {
  212. var view = subviews [0];
  213. Remove (view);
  214. subviews.RemoveAt (0);
  215. }
  216. }
  217. /// <summary>
  218. /// Removes a widget from this container.
  219. /// </summary>
  220. /// <remarks>
  221. /// </remarks>
  222. public virtual void Remove (View view)
  223. {
  224. if (view == null)
  225. return;
  226. SetNeedsDisplay ();
  227. var touched = view.Frame;
  228. subviews.Remove (view);
  229. view.container = null;
  230. if (subviews.Count < 1)
  231. this.CanFocus = false;
  232. foreach (var v in subviews) {
  233. if (v.Frame.IntersectsWith (touched))
  234. view.SetNeedsDisplay ();
  235. }
  236. }
  237. /// <summary>
  238. /// Clears the view region with the current color.
  239. /// </summary>
  240. /// <remarks>
  241. /// <para>
  242. /// This clears the entire region used by this view.
  243. /// </para>
  244. /// </remarks>
  245. public void Clear ()
  246. {
  247. var h = Frame.Height;
  248. var w = Frame.Width;
  249. for (int line = 0; line < h; line++) {
  250. Move (0, line);
  251. for (int col = 0; col < w; col++)
  252. Driver.AddCh (' ');
  253. }
  254. }
  255. /// <summary>
  256. /// Converts the (col,row) position from the view into a screen (col,row). The values are clamped to (0..ScreenDim-1)
  257. /// </summary>
  258. /// <param name="col">View-based column.</param>
  259. /// <param name="row">View-based row.</param>
  260. /// <param name="rcol">Absolute column, display relative.</param>
  261. /// <param name="rrow">Absolute row, display relative.</param>
  262. internal void ViewToScreen (int col, int row, out int rcol, out int rrow, bool clipped = true)
  263. {
  264. // Computes the real row, col relative to the screen.
  265. rrow = row + frame.Y;
  266. rcol = col + frame.X;
  267. var ccontainer = container;
  268. while (ccontainer != null) {
  269. rrow += ccontainer.frame.Y;
  270. rcol += ccontainer.frame.X;
  271. ccontainer = ccontainer.container;
  272. }
  273. // The following ensures that the cursor is always in the screen boundaries.
  274. if (clipped) {
  275. rrow = Math.Max (0, Math.Min (rrow, Driver.Rows - 1));
  276. rcol = Math.Max (0, Math.Min (rcol, Driver.Cols - 1));
  277. }
  278. }
  279. // Converts a rectangle in view coordinates to screen coordinates.
  280. Rect RectToScreen (Rect rect)
  281. {
  282. ViewToScreen (rect.X, rect.Y, out var x, out var y, clipped: false);
  283. return new Rect (x, y, rect.Width, rect.Height);
  284. }
  285. // Clips a rectangle in screen coordinates to the dimensions currently available on the screen
  286. Rect ScreenClip (Rect rect)
  287. {
  288. var x = rect.X < 0 ? 0 : rect.X;
  289. var y = rect.Y < 0 ? 0 : rect.Y;
  290. var w = rect.X + rect.Width >= Driver.Cols ? Driver.Cols - rect.X : rect.Width;
  291. var h = rect.Y + rect.Height >= Driver.Rows ? Driver.Rows - rect.Y : rect.Height;
  292. return new Rect (x, y, w, h);
  293. }
  294. /// <summary>
  295. /// Draws a frame in the current view, clipped by the boundary of this view
  296. /// </summary>
  297. /// <param name="rect">Rectangular region for the frame to be drawn.</param>
  298. /// <param name="fill">If set to <c>true</c> it fill will the contents.</param>
  299. public void DrawFrame (Rect rect, bool fill = false)
  300. {
  301. var scrRect = RectToScreen (rect);
  302. var savedClip = Driver.Clip;
  303. Driver.Clip = ScreenClip (RectToScreen (Bounds));
  304. Driver.DrawFrame (scrRect, fill);
  305. Driver.Clip = savedClip;
  306. }
  307. /// <summary>
  308. /// Utility function to draw strings that contain a hotkey
  309. /// </summary>
  310. /// <param name="s">String to display, the underscoore before a letter flags the next letter as the hotkey.</param>
  311. /// <param name="hotColor">Hot color.</param>
  312. /// <param name="normalColor">Normal color.</param>
  313. public void DrawHotString (string text, Attribute hotColor, Attribute normalColor)
  314. {
  315. Driver.SetAttribute (normalColor);
  316. foreach (var c in text) {
  317. if (c == '_') {
  318. Driver.SetAttribute (hotColor);
  319. continue;
  320. }
  321. Driver.AddCh (c);
  322. Driver.SetAttribute (normalColor);
  323. }
  324. }
  325. /// <summary>
  326. /// This moves the cursor to the specified column and row in the view.
  327. /// </summary>
  328. /// <returns>The move.</returns>
  329. /// <param name="col">Col.</param>
  330. /// <param name="row">Row.</param>
  331. public void Move (int col, int row)
  332. {
  333. ViewToScreen (col, row, out var rcol, out var rrow);
  334. Driver.Move (rcol, rrow);
  335. }
  336. /// <summary>
  337. /// Positions the cursor in the right position based on the currently focused view in the chain.
  338. /// </summary>
  339. public virtual void PositionCursor ()
  340. {
  341. if (focused != null)
  342. focused.PositionCursor ();
  343. else
  344. Move (frame.X, frame.Y);
  345. }
  346. public override bool HasFocus {
  347. get {
  348. return base.HasFocus;
  349. }
  350. internal set {
  351. if (base.HasFocus != value)
  352. SetNeedsDisplay ();
  353. base.HasFocus = value;
  354. }
  355. }
  356. /// <summary>
  357. /// Returns the currently focused view inside this view, or null if nothing is focused.
  358. /// </summary>
  359. /// <value>The focused.</value>
  360. public View Focused => focused;
  361. public View MostFocused {
  362. get {
  363. if (Focused == null)
  364. return null;
  365. var most = Focused.MostFocused;
  366. if (most != null)
  367. return most;
  368. return Focused;
  369. }
  370. }
  371. /// <summary>
  372. /// Displays the specified character in the specified column and row.
  373. /// </summary>
  374. /// <param name="col">Col.</param>
  375. /// <param name="row">Row.</param>
  376. /// <param name="ch">Ch.</param>
  377. public void AddCh (int col, int row, int ch)
  378. {
  379. if (row < 0 || col < 0)
  380. return;
  381. if (row > frame.Height - 1 || col > frame.Width - 1)
  382. return;
  383. Move (col, row);
  384. Driver.AddCh (ch);
  385. }
  386. /// <summary>
  387. /// Performs a redraw of this view and its subviews, only redraws the views that have been flagged for a re-display.
  388. /// </summary>
  389. /// <remarks>
  390. /// The region argument is relative to the view itself.
  391. /// </remarks>
  392. public virtual void Redraw (Rect region)
  393. {
  394. var clipRect = new Rect (Point.Empty, frame.Size);
  395. if (subviews != null) {
  396. foreach (var view in subviews) {
  397. if (!view.NeedDisplay.IsEmpty || view.childNeedsDisplay) {
  398. if (view.Frame.IntersectsWith (clipRect) && view.Frame.IntersectsWith (region)) {
  399. // TODO: optimize this by computing the intersection of region and view.Bounds
  400. view.Redraw (view.Bounds);
  401. }
  402. view.NeedDisplay = Rect.Empty;
  403. view.childNeedsDisplay = false;
  404. }
  405. }
  406. }
  407. NeedDisplay = Rect.Empty;
  408. childNeedsDisplay = false;
  409. }
  410. /// <summary>
  411. /// Focuses the specified sub-view.
  412. /// </summary>
  413. /// <param name="view">View.</param>
  414. public void SetFocus (View view)
  415. {
  416. if (view == null)
  417. return;
  418. //Console.WriteLine ($"Request to focus {view}");
  419. if (!view.CanFocus)
  420. return;
  421. if (focused == view)
  422. return;
  423. // Make sure that this view is a subview
  424. View c;
  425. for (c = view.container; c != null; c = c.container)
  426. if (c == this)
  427. break;
  428. if (c == null)
  429. throw new ArgumentException ("the specified view is not part of the hierarchy of this view");
  430. if (focused != null)
  431. focused.HasFocus = false;
  432. focused = view;
  433. focused.HasFocus = true;
  434. focused.EnsureFocus ();
  435. }
  436. public override bool ProcessKey (KeyEvent kb)
  437. {
  438. if (Focused?.ProcessKey (kb) == true)
  439. return true;
  440. return false;
  441. }
  442. public override bool ProcessHotKey (KeyEvent kb)
  443. {
  444. if (subviews == null || subviews.Count == 0)
  445. return false;
  446. foreach (var view in subviews)
  447. if (view.ProcessHotKey (kb))
  448. return true;
  449. return false;
  450. }
  451. public override bool ProcessColdKey (KeyEvent kb)
  452. {
  453. if (subviews == null || subviews.Count == 0)
  454. return false;
  455. foreach (var view in subviews)
  456. if (view.ProcessHotKey (kb))
  457. return true;
  458. return false;
  459. }
  460. /// <summary>
  461. /// Finds the first view in the hierarchy that wants to get the focus if nothing is currently focused, otherwise, it does nothing.
  462. /// </summary>
  463. public void EnsureFocus ()
  464. {
  465. if (focused == null)
  466. FocusFirst ();
  467. }
  468. /// <summary>
  469. /// Focuses the first focusable subview if one exists.
  470. /// </summary>
  471. public void FocusFirst ()
  472. {
  473. if (subviews == null) {
  474. SuperView.SetFocus (this);
  475. return;
  476. }
  477. foreach (var view in subviews) {
  478. if (view.CanFocus) {
  479. SetFocus (view);
  480. return;
  481. }
  482. }
  483. }
  484. /// <summary>
  485. /// Focuses the last focusable subview if one exists.
  486. /// </summary>
  487. public void FocusLast ()
  488. {
  489. if (subviews == null)
  490. return;
  491. for (int i = subviews.Count; i > 0;) {
  492. i--;
  493. View v = subviews [i];
  494. if (v.CanFocus) {
  495. SetFocus (v);
  496. return;
  497. }
  498. }
  499. }
  500. /// <summary>
  501. /// Focuses the previous view.
  502. /// </summary>
  503. /// <returns><c>true</c>, if previous was focused, <c>false</c> otherwise.</returns>
  504. public bool FocusPrev ()
  505. {
  506. if (subviews == null || subviews.Count == 0)
  507. return false;
  508. if (focused == null) {
  509. FocusLast ();
  510. return true;
  511. }
  512. int focused_idx = -1;
  513. for (int i = subviews.Count; i > 0;) {
  514. i--;
  515. View w = subviews [i];
  516. if (w.HasFocus) {
  517. if (w.FocusPrev ())
  518. return true;
  519. focused_idx = i;
  520. continue;
  521. }
  522. if (w.CanFocus && focused_idx != -1) {
  523. focused.HasFocus = false;
  524. if (w.CanFocus)
  525. w.FocusLast ();
  526. SetFocus (w);
  527. return true;
  528. }
  529. }
  530. if (focused_idx != -1) {
  531. FocusLast ();
  532. return true;
  533. }
  534. if (focused != null) {
  535. focused.HasFocus = false;
  536. focused = null;
  537. }
  538. return false;
  539. }
  540. /// <summary>
  541. /// Focuses the next view.
  542. /// </summary>
  543. /// <returns><c>true</c>, if next was focused, <c>false</c> otherwise.</returns>
  544. public bool FocusNext ()
  545. {
  546. if (subviews == null || subviews.Count == 0)
  547. return false;
  548. if (focused == null) {
  549. FocusFirst ();
  550. return focused != null;
  551. }
  552. int n = subviews.Count;
  553. int focused_idx = -1;
  554. for (int i = 0; i < n; i++) {
  555. View w = subviews [i];
  556. if (w.HasFocus) {
  557. if (w.FocusNext ())
  558. return true;
  559. focused_idx = i;
  560. continue;
  561. }
  562. if (w.CanFocus && focused_idx != -1) {
  563. focused.HasFocus = false;
  564. if (w != null && w.CanFocus)
  565. w.FocusFirst ();
  566. SetFocus (w);
  567. return true;
  568. }
  569. }
  570. if (focused != null) {
  571. focused.HasFocus = false;
  572. focused = null;
  573. }
  574. return false;
  575. }
  576. public virtual void LayoutSubviews ()
  577. {
  578. }
  579. public override string ToString ()
  580. {
  581. return $"{GetType ().Name}({id})({Frame})";
  582. }
  583. }
  584. /// <summary>
  585. /// Toplevel views can be modally executed.
  586. /// </summary>
  587. public class Toplevel : View {
  588. public bool Running;
  589. public Toplevel (Rect frame) : base (frame)
  590. {
  591. }
  592. public static Toplevel Create ()
  593. {
  594. return new Toplevel (new Rect (0, 0, Driver.Cols, Driver.Rows));
  595. }
  596. public override bool CanFocus {
  597. get => true;
  598. }
  599. public override bool ProcessKey (KeyEvent kb)
  600. {
  601. if (base.ProcessKey (kb))
  602. return true;
  603. switch (kb.Key) {
  604. case Key.ControlC:
  605. // TODO: stop current execution of this container
  606. break;
  607. case Key.ControlZ:
  608. // TODO: should suspend
  609. // console_csharp_send_sigtstp ();
  610. break;
  611. case Key.Tab:
  612. var old = Focused;
  613. if (!FocusNext ())
  614. FocusNext ();
  615. if (old != Focused) {
  616. old?.SetNeedsDisplay ();
  617. Focused?.SetNeedsDisplay ();
  618. }
  619. return true;
  620. case Key.BackTab:
  621. old = Focused;
  622. if (!FocusPrev ())
  623. FocusPrev ();
  624. if (old != Focused) {
  625. old?.SetNeedsDisplay ();
  626. Focused?.SetNeedsDisplay ();
  627. }
  628. return true;
  629. case Key.ControlL:
  630. SetNeedsDisplay();
  631. return true;
  632. }
  633. return false;
  634. }
  635. #if false
  636. public override void Redraw ()
  637. {
  638. base.Redraw ();
  639. for (int i = 0; i < Driver.Cols; i++) {
  640. Driver.Move (0, i);
  641. Driver.AddStr ("Line: " + i);
  642. }
  643. }
  644. #endif
  645. }
  646. /// <summary>
  647. /// A toplevel view that draws a frame around its region
  648. /// </summary>
  649. public class Window : Toplevel, IEnumerable {
  650. View contentView;
  651. string title;
  652. public string Title {
  653. get => title;
  654. set {
  655. title = value;
  656. SetNeedsDisplay ();
  657. }
  658. }
  659. class ContentView : View {
  660. public ContentView (Rect frame) : base (frame) { }
  661. }
  662. public Window (Rect frame, string title = null) : base (frame)
  663. {
  664. this.Title = title;
  665. frame.Inflate (-1, -1);
  666. contentView = new ContentView (frame);
  667. base.Add (contentView);
  668. }
  669. public new IEnumerator GetEnumerator ()
  670. {
  671. return contentView.GetEnumerator ();
  672. }
  673. void DrawFrame ()
  674. {
  675. DrawFrame (new Rect (0, 0, Frame.Width, Frame.Height), true);
  676. }
  677. public override void Add (View view)
  678. {
  679. contentView.Add (view);
  680. }
  681. public override void Redraw (Rect bounds)
  682. {
  683. if (!NeedDisplay.IsEmpty) {
  684. Driver.SetAttribute (Colors.Base.Normal);
  685. DrawFrame ();
  686. if (HasFocus)
  687. Driver.SetAttribute (Colors.Dialog.Normal);
  688. var width = Frame.Width;
  689. if (Title != null && width > 4) {
  690. Move (1, 0);
  691. Driver.AddCh (' ');
  692. var str = Title.Length > width ? Title.Substring (0, width - 4) : Title;
  693. Driver.AddStr (str);
  694. Driver.AddCh (' ');
  695. }
  696. Driver.SetAttribute (Colors.Dialog.Normal);
  697. }
  698. contentView.Redraw (contentView.Bounds);
  699. }
  700. }
  701. public class Application {
  702. public static ConsoleDriver Driver = new CursesDriver ();
  703. public static Toplevel Top { get; private set; }
  704. public static Mono.Terminal.MainLoop MainLoop { get; private set; }
  705. static Stack<View> toplevels = new Stack<View> ();
  706. static Responder focus;
  707. /// <summary>
  708. /// This event is raised on each iteration of the
  709. /// main loop.
  710. /// </summary>
  711. /// <remarks>
  712. /// See also <see cref="Timeout"/>
  713. /// </remarks>
  714. static public event EventHandler Iteration;
  715. /// <summary>
  716. /// Returns a rectangle that is centered in the screen for the provided size.
  717. /// </summary>
  718. /// <returns>The centered rect.</returns>
  719. /// <param name="size">Size for the rectangle.</param>
  720. public static Rect MakeCenteredRect (Size size)
  721. {
  722. return new Rect (new Point ((Driver.Cols - size.Width) / 2, (Driver.Rows - size.Height) / 2), size);
  723. }
  724. class MainLoopSyncContext : SynchronizationContext {
  725. Mono.Terminal.MainLoop mainLoop;
  726. public MainLoopSyncContext (Mono.Terminal.MainLoop mainLoop)
  727. {
  728. this.mainLoop = mainLoop;
  729. }
  730. public override SynchronizationContext CreateCopy ()
  731. {
  732. return new MainLoopSyncContext (MainLoop);
  733. }
  734. public override void Post (SendOrPostCallback d, object state)
  735. {
  736. mainLoop.AddIdle (() => {
  737. d (state);
  738. return false;
  739. });
  740. }
  741. public override void Send (SendOrPostCallback d, object state)
  742. {
  743. mainLoop.Invoke (() => {
  744. d (state);
  745. });
  746. }
  747. }
  748. /// <summary>
  749. /// Initializes the Application
  750. /// </summary>
  751. public static void Init ()
  752. {
  753. if (Top != null)
  754. return;
  755. Driver.Init (TerminalResized);
  756. MainLoop = new Mono.Terminal.MainLoop ();
  757. SynchronizationContext.SetSynchronizationContext (new MainLoopSyncContext (MainLoop));
  758. Top = Toplevel.Create ();
  759. focus = Top;
  760. }
  761. public class RunState : IDisposable {
  762. internal RunState (Toplevel view)
  763. {
  764. Toplevel = view;
  765. }
  766. internal Toplevel Toplevel;
  767. public void Dispose ()
  768. {
  769. Dispose (true);
  770. GC.SuppressFinalize (this);
  771. }
  772. public virtual void Dispose (bool disposing)
  773. {
  774. if (Toplevel != null) {
  775. Application.End (Toplevel);
  776. Toplevel = null;
  777. }
  778. }
  779. }
  780. static void ProcessKeyEvent (KeyEvent ke)
  781. {
  782. if (Top.ProcessHotKey (ke))
  783. return;
  784. if (Top.ProcessKey (ke))
  785. return;
  786. // Process the key normally
  787. if (Top.ProcessColdKey (ke))
  788. return;
  789. }
  790. static public RunState Begin (Toplevel toplevel)
  791. {
  792. if (toplevel == null)
  793. throw new ArgumentNullException (nameof (toplevel));
  794. var rs = new RunState (toplevel);
  795. Init ();
  796. toplevels.Push (toplevel);
  797. Driver.PrepareToRun (MainLoop, ProcessKeyEvent);
  798. toplevel.LayoutSubviews ();
  799. toplevel.FocusFirst ();
  800. Redraw (toplevel);
  801. toplevel.PositionCursor ();
  802. Driver.Refresh ();
  803. return rs;
  804. }
  805. static public void End (RunState rs)
  806. {
  807. if (rs == null)
  808. throw new ArgumentNullException (nameof (rs));
  809. rs.Dispose ();
  810. }
  811. static void Shutdown ()
  812. {
  813. Driver.End ();
  814. }
  815. static void Redraw (View view)
  816. {
  817. view.Redraw (view.Bounds);
  818. Driver.Refresh ();
  819. }
  820. static void Refresh (View view)
  821. {
  822. view.Redraw (view.Bounds);
  823. Driver.Refresh ();
  824. }
  825. public static void Refresh ()
  826. {
  827. Driver.RedrawTop ();
  828. View last = null;
  829. foreach (var v in toplevels) {
  830. v.Redraw (v.Bounds);
  831. last = v;
  832. }
  833. if (last != null)
  834. last.PositionCursor ();
  835. Driver.Refresh ();
  836. }
  837. internal static void End (View view)
  838. {
  839. if (toplevels.Peek () != view)
  840. throw new ArgumentException ("The view that you end with must be balanced");
  841. toplevels.Pop ();
  842. if (toplevels.Count == 0)
  843. Shutdown ();
  844. else
  845. Refresh ();
  846. }
  847. /// <summary>
  848. /// Runs the main loop for the created dialog
  849. /// </summary>
  850. /// <remarks>
  851. /// Use the wait parameter to control whether this is a
  852. /// blocking or non-blocking call.
  853. /// </remarks>
  854. public static void RunLoop (RunState state, bool wait = true)
  855. {
  856. if (state == null)
  857. throw new ArgumentNullException (nameof (state));
  858. if (state.Toplevel == null)
  859. throw new ObjectDisposedException ("state");
  860. for (state.Toplevel.Running = true; state.Toplevel.Running;) {
  861. if (MainLoop.EventsPending (wait)) {
  862. MainLoop.MainIteration ();
  863. if (Iteration != null)
  864. Iteration (null, EventArgs.Empty);
  865. } else if (wait == false)
  866. return;
  867. if (!state.Toplevel.NeedDisplay.IsEmpty || state.Toplevel.childNeedsDisplay) {
  868. state.Toplevel.Redraw (state.Toplevel.Bounds);
  869. state.Toplevel.PositionCursor ();
  870. Driver.Refresh ();
  871. }
  872. }
  873. }
  874. public static void Run ()
  875. {
  876. Run (Top);
  877. }
  878. /// <summary>
  879. /// Runs the main loop on the given container.
  880. /// </summary>
  881. /// <remarks>
  882. /// This method is used to start processing events
  883. /// for the main application, but it is also used to
  884. /// run modal dialog boxes.
  885. /// </remarks>
  886. public static void Run (Toplevel view)
  887. {
  888. var runToken = Begin (view);
  889. RunLoop (runToken);
  890. End (runToken);
  891. }
  892. static void TerminalResized ()
  893. {
  894. foreach (var t in toplevels) {
  895. t.Frame = new Rect (0, 0, Driver.Cols, Driver.Rows);
  896. }
  897. }
  898. }
  899. }