Core.cs 23 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  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 (focused == null) {
  507. FocusLast ();
  508. return true;
  509. }
  510. int focused_idx = -1;
  511. for (int i = subviews.Count; i > 0;) {
  512. i--;
  513. View w = subviews [i];
  514. if (w.HasFocus) {
  515. if (w.FocusPrev ())
  516. return true;
  517. focused_idx = i;
  518. continue;
  519. }
  520. if (w.CanFocus && focused_idx != -1) {
  521. focused.HasFocus = false;
  522. if (w.CanFocus)
  523. w.FocusLast ();
  524. SetFocus (w);
  525. return true;
  526. }
  527. }
  528. if (focused != null) {
  529. focused.HasFocus = false;
  530. focused = null;
  531. }
  532. return false;
  533. }
  534. /// <summary>
  535. /// Focuses the next view.
  536. /// </summary>
  537. /// <returns><c>true</c>, if next was focused, <c>false</c> otherwise.</returns>
  538. public bool FocusNext ()
  539. {
  540. if (subviews == null || subviews.Count == 0)
  541. return false;
  542. if (focused == null) {
  543. FocusFirst ();
  544. return focused != null;
  545. }
  546. int n = subviews.Count;
  547. int focused_idx = -1;
  548. for (int i = 0; i < n; i++) {
  549. View w = subviews [i];
  550. if (w.HasFocus) {
  551. if (w.FocusNext ())
  552. return true;
  553. focused_idx = i;
  554. continue;
  555. }
  556. if (w.CanFocus && focused_idx != -1) {
  557. focused.HasFocus = false;
  558. if (w != null && w.CanFocus)
  559. w.FocusFirst ();
  560. SetFocus (w);
  561. return true;
  562. }
  563. }
  564. if (focused != null) {
  565. focused.HasFocus = false;
  566. focused = null;
  567. }
  568. return false;
  569. }
  570. public virtual void LayoutSubviews ()
  571. {
  572. }
  573. public override string ToString ()
  574. {
  575. return $"{GetType ().Name}({id})({Frame})";
  576. }
  577. }
  578. /// <summary>
  579. /// Toplevel views can be modally executed.
  580. /// </summary>
  581. public class Toplevel : View {
  582. public bool Running;
  583. public Toplevel (Rect frame) : base (frame)
  584. {
  585. }
  586. public static Toplevel Create ()
  587. {
  588. return new Toplevel (new Rect (0, 0, Driver.Cols, Driver.Rows));
  589. }
  590. public override bool CanFocus {
  591. get => true;
  592. }
  593. public override bool ProcessKey (KeyEvent kb)
  594. {
  595. if (ProcessHotKey (kb))
  596. return true;
  597. if (base.ProcessKey (kb))
  598. return true;
  599. // Process the key normally
  600. if (ProcessColdKey (kb))
  601. return true;
  602. switch (kb.Key) {
  603. case Key.ControlC:
  604. // TODO: stop current execution of this container
  605. break;
  606. case Key.ControlZ:
  607. // TODO: should suspend
  608. // console_csharp_send_sigtstp ();
  609. break;
  610. case Key.Tab:
  611. var old = Focused;
  612. if (!FocusNext ())
  613. FocusNext ();
  614. if (old != Focused) {
  615. old?.SetNeedsDisplay ();
  616. Focused?.SetNeedsDisplay ();
  617. }
  618. return true;
  619. case Key.BackTab:
  620. old = Focused;
  621. if (!FocusPrev ())
  622. FocusPrev ();
  623. if (old != Focused) {
  624. old?.SetNeedsDisplay ();
  625. Focused?.SetNeedsDisplay ();
  626. }
  627. return true;
  628. case Key.ControlL:
  629. SetNeedsDisplay();
  630. return true;
  631. }
  632. return false;
  633. }
  634. #if false
  635. public override void Redraw ()
  636. {
  637. base.Redraw ();
  638. for (int i = 0; i < Driver.Cols; i++) {
  639. Driver.Move (0, i);
  640. Driver.AddStr ("Line: " + i);
  641. }
  642. }
  643. #endif
  644. }
  645. /// <summary>
  646. /// A toplevel view that draws a frame around its region
  647. /// </summary>
  648. public class Window : Toplevel, IEnumerable {
  649. View contentView;
  650. string title;
  651. public string Title {
  652. get => title;
  653. set {
  654. title = value;
  655. SetNeedsDisplay ();
  656. }
  657. }
  658. class ContentView : View {
  659. public ContentView (Rect frame) : base (frame) { }
  660. }
  661. public Window (Rect frame, string title = null) : base (frame)
  662. {
  663. this.Title = title;
  664. frame.Inflate (-1, -1);
  665. contentView = new ContentView (frame);
  666. base.Add (contentView);
  667. }
  668. public new IEnumerator GetEnumerator ()
  669. {
  670. return contentView.GetEnumerator ();
  671. }
  672. void DrawFrame ()
  673. {
  674. DrawFrame (new Rect (0, 0, Frame.Width, Frame.Height), true);
  675. }
  676. public override void Add (View view)
  677. {
  678. contentView.Add (view);
  679. }
  680. public override void Redraw (Rect bounds)
  681. {
  682. if (!NeedDisplay.IsEmpty) {
  683. Driver.SetAttribute (Colors.Base.Normal);
  684. DrawFrame ();
  685. if (HasFocus)
  686. Driver.SetAttribute (Colors.Dialog.Normal);
  687. var width = Frame.Width;
  688. if (Title != null && width > 4) {
  689. Move (1, 0);
  690. Driver.AddCh (' ');
  691. var str = Title.Length > width ? Title.Substring (0, width - 4) : Title;
  692. Driver.AddStr (str);
  693. Driver.AddCh (' ');
  694. }
  695. Driver.SetAttribute (Colors.Dialog.Normal);
  696. }
  697. contentView.Redraw (contentView.Bounds);
  698. }
  699. }
  700. public class Application {
  701. public static ConsoleDriver Driver = new CursesDriver ();
  702. public static Toplevel Top { get; private set; }
  703. public static Mono.Terminal.MainLoop MainLoop { get; private set; }
  704. static Stack<View> toplevels = new Stack<View> ();
  705. static Responder focus;
  706. /// <summary>
  707. /// This event is raised on each iteration of the
  708. /// main loop.
  709. /// </summary>
  710. /// <remarks>
  711. /// See also <see cref="Timeout"/>
  712. /// </remarks>
  713. static public event EventHandler Iteration;
  714. public static void MakeFirstResponder (Responder newResponder)
  715. {
  716. if (newResponder == null)
  717. throw new ArgumentNullException ();
  718. throw new NotImplementedException ();
  719. }
  720. class MainLoopSyncContext : SynchronizationContext {
  721. Mono.Terminal.MainLoop mainLoop;
  722. public MainLoopSyncContext (Mono.Terminal.MainLoop mainLoop)
  723. {
  724. this.mainLoop = mainLoop;
  725. }
  726. public override SynchronizationContext CreateCopy ()
  727. {
  728. return new MainLoopSyncContext (MainLoop);
  729. }
  730. public override void Post (SendOrPostCallback d, object state)
  731. {
  732. mainLoop.AddIdle (() => {
  733. d (state);
  734. return false;
  735. });
  736. }
  737. public override void Send (SendOrPostCallback d, object state)
  738. {
  739. mainLoop.Invoke (() => {
  740. d (state);
  741. });
  742. }
  743. }
  744. /// <summary>
  745. /// Initializes the Application
  746. /// </summary>
  747. public static void Init ()
  748. {
  749. if (Top != null)
  750. return;
  751. Driver.Init (TerminalResized);
  752. MainLoop = new Mono.Terminal.MainLoop ();
  753. SynchronizationContext.SetSynchronizationContext (new MainLoopSyncContext (MainLoop));
  754. Top = Toplevel.Create ();
  755. focus = Top;
  756. }
  757. public class RunState : IDisposable {
  758. internal RunState (Toplevel view)
  759. {
  760. Toplevel = view;
  761. }
  762. internal Toplevel Toplevel;
  763. public void Dispose ()
  764. {
  765. Dispose (true);
  766. GC.SuppressFinalize (this);
  767. }
  768. public virtual void Dispose (bool disposing)
  769. {
  770. if (Toplevel != null) {
  771. Application.End (Toplevel);
  772. Toplevel = null;
  773. }
  774. }
  775. }
  776. static void KeyEvent (Key key)
  777. {
  778. }
  779. static public RunState Begin (Toplevel toplevel)
  780. {
  781. if (toplevel == null)
  782. throw new ArgumentNullException (nameof (toplevel));
  783. var rs = new RunState (toplevel);
  784. Init ();
  785. toplevels.Push (toplevel);
  786. Driver.PrepareToRun (MainLoop, toplevel);
  787. toplevel.LayoutSubviews ();
  788. toplevel.FocusFirst ();
  789. Redraw (toplevel);
  790. toplevel.PositionCursor ();
  791. Driver.Refresh ();
  792. return rs;
  793. }
  794. static public void End (RunState rs)
  795. {
  796. if (rs == null)
  797. throw new ArgumentNullException (nameof (rs));
  798. rs.Dispose ();
  799. }
  800. static void Shutdown ()
  801. {
  802. Driver.End ();
  803. }
  804. static void Redraw (View view)
  805. {
  806. view.Redraw (view.Bounds);
  807. Driver.Refresh ();
  808. }
  809. static void Refresh (View view)
  810. {
  811. view.Redraw (view.Bounds);
  812. Driver.Refresh ();
  813. }
  814. public static void Refresh ()
  815. {
  816. Driver.RedrawTop ();
  817. View last = null;
  818. foreach (var v in toplevels) {
  819. v.Redraw (v.Bounds);
  820. last = v;
  821. }
  822. if (last != null)
  823. last.PositionCursor ();
  824. Driver.Refresh ();
  825. }
  826. internal static void End (View view)
  827. {
  828. if (toplevels.Peek () != view)
  829. throw new ArgumentException ("The view that you end with must be balanced");
  830. toplevels.Pop ();
  831. if (toplevels.Count == 0)
  832. Shutdown ();
  833. else
  834. Refresh ();
  835. }
  836. /// <summary>
  837. /// Runs the main loop for the created dialog
  838. /// </summary>
  839. /// <remarks>
  840. /// Use the wait parameter to control whether this is a
  841. /// blocking or non-blocking call.
  842. /// </remarks>
  843. public static void RunLoop (RunState state, bool wait = true)
  844. {
  845. if (state == null)
  846. throw new ArgumentNullException (nameof (state));
  847. if (state.Toplevel == null)
  848. throw new ObjectDisposedException ("state");
  849. for (state.Toplevel.Running = true; state.Toplevel.Running;) {
  850. if (MainLoop.EventsPending (wait)) {
  851. MainLoop.MainIteration ();
  852. if (Iteration != null)
  853. Iteration (null, EventArgs.Empty);
  854. } else if (wait == false)
  855. return;
  856. if (!state.Toplevel.NeedDisplay.IsEmpty || state.Toplevel.childNeedsDisplay) {
  857. state.Toplevel.Redraw (state.Toplevel.Bounds);
  858. state.Toplevel.PositionCursor ();
  859. Driver.Refresh ();
  860. }
  861. }
  862. }
  863. public static void Run ()
  864. {
  865. Run (Top);
  866. }
  867. /// <summary>
  868. /// Runs the main loop on the given container.
  869. /// </summary>
  870. /// <remarks>
  871. /// This method is used to start processing events
  872. /// for the main application, but it is also used to
  873. /// run modal dialog boxes.
  874. /// </remarks>
  875. public static void Run (Toplevel view)
  876. {
  877. var runToken = Begin (view);
  878. RunLoop (runToken);
  879. End (runToken);
  880. }
  881. static void TerminalResized ()
  882. {
  883. foreach (var t in toplevels) {
  884. t.Frame = new Rect (0, 0, Driver.Cols, Driver.Rows);
  885. }
  886. }
  887. }
  888. }