Application.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. //
  2. //
  3. // Pending:
  4. // - Check for NeedDisplay on the hierarchy and repaint
  5. // - Layout support
  6. //
  7. // Optimziations
  8. // - Add rendering limitation to the exposed area
  9. using System;
  10. using System.Collections.Generic;
  11. namespace Terminal {
  12. public class Responder {
  13. public virtual bool CanFocus { get; set; }
  14. public bool HasFocus { get; internal set; }
  15. // Key handling
  16. public virtual void KeyDown (Event.Key kb) {}
  17. // Mouse events
  18. public virtual void MouseEvent (Event.Mouse me) {}
  19. }
  20. public class View : Responder {
  21. View container = null;
  22. View focused = null;
  23. public static ConsoleDriver Driver = Application.Driver;
  24. public static IList<View> empty = new List<View>(0).AsReadOnly ();
  25. List<View> subviews;
  26. public IList<View> Subviews => subviews == null ? empty : subviews.AsReadOnly ();
  27. internal bool NeedDisplay { get; private set; } = true;
  28. // The frame for the object
  29. Rect frame;
  30. // The offset of the first child view inside the view
  31. Point offset;
  32. // The frame for this view
  33. public Rect Frame {
  34. get => frame;
  35. set {
  36. frame = value;
  37. SetNeedsDisplay ();
  38. }
  39. }
  40. public View (Rect frame)
  41. {
  42. this.Frame = frame;
  43. CanFocus = false;
  44. }
  45. /// <summary>
  46. /// Invoke to flag that this view needs to be redisplayed, by any code
  47. /// that alters the state of the view.
  48. /// </summary>
  49. public void SetNeedsDisplay ()
  50. {
  51. NeedDisplay = true;
  52. }
  53. /// <summary>
  54. /// Adds a subview to this view.
  55. /// </summary>
  56. /// <remarks>
  57. /// </remarks>
  58. public void Add (View view)
  59. {
  60. if (view == null)
  61. return;
  62. if (subviews == null)
  63. subviews = new List<View> ();
  64. subviews.Add (view);
  65. view.container = this;
  66. if (view.CanFocus)
  67. CanFocus = true;
  68. }
  69. /// <summary>
  70. /// Removes all the widgets from this container.
  71. /// </summary>
  72. /// <remarks>
  73. /// </remarks>
  74. public virtual void RemoveAll ()
  75. {
  76. if (subviews == null)
  77. return;
  78. while (subviews.Count > 0) {
  79. var view = subviews [0];
  80. Remove (view);
  81. subviews.RemoveAt (0);
  82. }
  83. }
  84. /// <summary>
  85. /// Removes a widget from this container.
  86. /// </summary>
  87. /// <remarks>
  88. /// </remarks>
  89. public virtual void Remove (View view)
  90. {
  91. if (view == null)
  92. return;
  93. subviews.Remove (view);
  94. view.container = null;
  95. if (subviews.Count < 1)
  96. this.CanFocus = false;
  97. }
  98. /// <summary>
  99. /// Clears the view region with the current color.
  100. /// </summary>
  101. /// <remarks>
  102. /// <para>
  103. /// This clears the entire region used by this view.
  104. /// </para>
  105. /// </remarks>
  106. public void Clear ()
  107. {
  108. var h = Frame.Height;
  109. var w = Frame.Width;
  110. for (int line = 0; line < h; line++) {
  111. Move (0, line);
  112. for (int col = 0; col < w; col++)
  113. Driver.AddCh (' ');
  114. }
  115. }
  116. /// <summary>
  117. /// Converts the (col,row) position from the view into a screen (col,row). The values are clamped to (0..ScreenDim-1)
  118. /// </summary>
  119. /// <param name="col">View-based column.</param>
  120. /// <param name="row">View-based row.</param>
  121. /// <param name="rcol">Absolute column, display relative.</param>
  122. /// <param name="rrow">Absolute row, display relative.</param>
  123. internal void ViewToScreen (int col, int row, out int rcol, out int rrow, bool clipped = true)
  124. {
  125. // Computes the real row, col relative to the screen.
  126. rrow = row + frame.X;
  127. rcol = col + frame.Y;
  128. var ccontainer = container;
  129. while (ccontainer != null){
  130. rrow += ccontainer.frame.Y;
  131. rcol += ccontainer.frame.X;
  132. ccontainer = ccontainer.container;
  133. }
  134. // The following ensures that the cursor is always in the screen boundaries.
  135. if (clipped) {
  136. rrow = Math.Max (0, Math.Min (rrow, Driver.Rows - 1));
  137. rcol = Math.Max (0, Math.Min (rcol, Driver.Cols - 1));
  138. }
  139. }
  140. /// <summary>
  141. /// Draws a frame in the current view, clipped by the boundary of this view
  142. /// </summary>
  143. /// <param name="rect">Rectangular region for the frame to be drawn.</param>
  144. /// <param name="fill">If set to <c>true</c> it fill will the contents.</param>
  145. public void DrawFrame (Rect rect, bool fill = false)
  146. {
  147. ViewToScreen (rect.X, rect.Y, out var x, out var y, clipped: false);
  148. Driver.DrawFrame (new Rect (x, y, rect.Width, rect.Height), fill);
  149. }
  150. /// <summary>
  151. /// This moves the cursor to the specified column and row in the view.
  152. /// </summary>
  153. /// <returns>The move.</returns>
  154. /// <param name="col">Col.</param>
  155. /// <param name="row">Row.</param>
  156. public void Move (int col, int row)
  157. {
  158. ViewToScreen (col, row, out var rcol, out var rrow);
  159. Driver.Move (rcol, rrow);
  160. }
  161. /// <summary>
  162. /// Positions the cursor in the right position based on the currently focused view in the chain.
  163. /// </summary>
  164. public virtual void PositionCursor ()
  165. {
  166. if (focused != null)
  167. focused.PositionCursor ();
  168. else
  169. Move (frame.X, frame.Y);
  170. }
  171. /// <summary>
  172. /// Displays the specified character in the specified column and row.
  173. /// </summary>
  174. /// <param name="col">Col.</param>
  175. /// <param name="row">Row.</param>
  176. /// <param name="ch">Ch.</param>
  177. public void AddCh (int col, int row, int ch)
  178. {
  179. if (row < 0 || col < 0)
  180. return;
  181. if (row > frame.Height-1 || col > frame.Width-1)
  182. return;
  183. Move (col, row);
  184. Driver.AddCh (ch);
  185. }
  186. /// <summary>
  187. /// Performs a redraw of this view and its subviews, only redraws the views that have been flagged for a re-display.
  188. /// </summary>
  189. public virtual void Redraw ()
  190. {
  191. var clipRect = new Rect (offset, frame.Size);
  192. if (subviews != null) {
  193. foreach (var view in subviews) {
  194. if (view.NeedDisplay) {
  195. if (view.Frame.IntersectsWith (clipRect)) {
  196. view.Redraw ();
  197. }
  198. view.NeedDisplay = false;
  199. }
  200. }
  201. }
  202. NeedDisplay = false;
  203. }
  204. /// <summary>
  205. /// Focuses the specified sub-view.
  206. /// </summary>
  207. /// <param name="view">View.</param>
  208. public void SetFocus (View view)
  209. {
  210. if (view == null)
  211. return;
  212. if (!view.CanFocus)
  213. return;
  214. if (focused == view)
  215. return;
  216. // Make sure that this view is a subview
  217. View c;
  218. for (c = view.container; c != null; c = c.container)
  219. if (c == this)
  220. break;
  221. if (c == null)
  222. throw new ArgumentException ("the specified view is not part of the hierarchy of this view");
  223. if (focused != null)
  224. focused.HasFocus = false;
  225. focused = view;
  226. view.HasFocus = true;
  227. if (view != null)
  228. view.EnsureFocus ();
  229. focused.PositionCursor ();
  230. }
  231. /// <summary>
  232. /// Finds the first view in the hierarchy that wants to get the focus if nothing is currently focused, otherwise, it does nothing.
  233. /// </summary>
  234. public void EnsureFocus ()
  235. {
  236. if (focused == null)
  237. FocusFirst ();
  238. }
  239. /// <summary>
  240. /// Focuses the first focusable subview if one exists.
  241. /// </summary>
  242. public void FocusFirst ()
  243. {
  244. foreach (var view in subviews){
  245. if (view.CanFocus){
  246. SetFocus (view);
  247. return;
  248. }
  249. }
  250. }
  251. /// <summary>
  252. /// Focuses the last focusable subview if one exists.
  253. /// </summary>
  254. public void FocusLast ()
  255. {
  256. for (int i = subviews.Count; i > 0; ){
  257. i--;
  258. View v = subviews [i];
  259. if (v.CanFocus){
  260. SetFocus (v);
  261. return;
  262. }
  263. }
  264. }
  265. /// <summary>
  266. /// Focuses the previous view.
  267. /// </summary>
  268. /// <returns><c>true</c>, if previous was focused, <c>false</c> otherwise.</returns>
  269. public bool FocusPrev ()
  270. {
  271. if (focused == null){
  272. FocusLast ();
  273. return true;
  274. }
  275. int focused_idx = -1;
  276. for (int i = subviews.Count; i > 0; ){
  277. i--;
  278. View w = subviews [i];
  279. if (w.HasFocus){
  280. if (w.FocusPrev ())
  281. return true;
  282. focused_idx = i;
  283. continue;
  284. }
  285. if (w.CanFocus && focused_idx != -1){
  286. focused.HasFocus = false;
  287. if (w.CanFocus)
  288. w.FocusLast ();
  289. SetFocus (w);
  290. return true;
  291. }
  292. }
  293. if (focused != null){
  294. focused.HasFocus = false;
  295. focused = null;
  296. }
  297. return false;
  298. }
  299. /// <summary>
  300. /// Focuses the next view.
  301. /// </summary>
  302. /// <returns><c>true</c>, if next was focused, <c>false</c> otherwise.</returns>
  303. public bool FocusNext ()
  304. {
  305. if (focused == null){
  306. FocusFirst ();
  307. return focused != null;
  308. }
  309. int n = subviews.Count;
  310. int focused_idx = -1;
  311. for (int i = 0; i < n; i++){
  312. View w = subviews [i];
  313. if (w.HasFocus){
  314. if (w.FocusNext ())
  315. return true;
  316. focused_idx = i;
  317. continue;
  318. }
  319. if (w.CanFocus && focused_idx != -1){
  320. focused.HasFocus = false;
  321. if (w != null && w.CanFocus)
  322. w.FocusFirst ();
  323. SetFocus (w);
  324. return true;
  325. }
  326. }
  327. if (focused != null){
  328. focused.HasFocus = false;
  329. focused = null;
  330. }
  331. return false;
  332. }
  333. public virtual void LayoutSubviews ()
  334. {
  335. }
  336. }
  337. /// <summary>
  338. /// Toplevel views can be modally executed.
  339. /// </summary>
  340. public class Toplevel : View {
  341. public bool Running;
  342. public Toplevel (Rect frame) : base (frame)
  343. {
  344. }
  345. public static Toplevel Create ()
  346. {
  347. return new Toplevel (new Rect (0, 0, Driver.Cols, Driver.Rows));
  348. }
  349. }
  350. /// <summary>
  351. /// A toplevel view that draws a frame around its region
  352. /// </summary>
  353. public class Window : Toplevel {
  354. View contentView;
  355. string title;
  356. public string Title {
  357. get => title;
  358. set {
  359. title = value;
  360. SetNeedsDisplay ();
  361. }
  362. }
  363. public Window (Rect frame, string title = null) : base (frame)
  364. {
  365. this.Title = title;
  366. frame.Inflate (-1, -1);
  367. contentView = new View (frame);
  368. Add(contentView);
  369. }
  370. void DrawFrame ()
  371. {
  372. DrawFrame (new Rect (Point.Empty, Frame.Size), true);
  373. }
  374. public override void Redraw ()
  375. {
  376. Driver.SetColor (Colors.Base.Normal);
  377. Clear ();
  378. DrawFrame ();
  379. if (HasFocus)
  380. Driver.SetColor (Colors.Dialog.Normal);
  381. var width = Frame.Width;
  382. if (Title != null && width > 4) {
  383. Move (1, 0);
  384. Driver.AddCh (' ');
  385. var str = Title.Length > width ? Title.Substring (0, width - 4) : Title;
  386. Driver.AddStr (str);
  387. Driver.AddCh (' ');
  388. }
  389. Driver.SetColor (Colors.Dialog.Normal);
  390. contentView.Redraw ();
  391. }
  392. }
  393. public class Application {
  394. public static ConsoleDriver Driver = new CursesDriver ();
  395. public static Toplevel Top { get; private set; }
  396. public static Mono.Terminal.MainLoop MainLoop { get; private set; }
  397. static Stack<View> toplevels = new Stack<View> ();
  398. static Responder focus;
  399. /// <summary>
  400. /// This event is raised on each iteration of the
  401. /// main loop.
  402. /// </summary>
  403. /// <remarks>
  404. /// See also <see cref="Timeout"/>
  405. /// </remarks>
  406. static public event EventHandler Iteration;
  407. public static void MakeFirstResponder (Responder newResponder)
  408. {
  409. if (newResponder == null)
  410. throw new ArgumentNullException ();
  411. throw new NotImplementedException ();
  412. }
  413. /// <summary>
  414. /// Initializes the Application
  415. /// </summary>
  416. public static void Init ()
  417. {
  418. if (Top != null)
  419. return;
  420. Driver.Init ();
  421. MainLoop = new Mono.Terminal.MainLoop ();
  422. Top = Toplevel.Create ();
  423. focus = Top;
  424. MainLoop.AddWatch (0, Mono.Terminal.MainLoop.Condition.PollIn, x => {
  425. //ProcessChar ();
  426. return true;
  427. });
  428. }
  429. public class RunState : IDisposable {
  430. internal RunState (Toplevel view)
  431. {
  432. Toplevel = view;
  433. }
  434. internal Toplevel Toplevel;
  435. public void Dispose ()
  436. {
  437. Dispose (true);
  438. GC.SuppressFinalize(this);
  439. }
  440. public virtual void Dispose (bool disposing)
  441. {
  442. if (Toplevel != null){
  443. Application.End (Toplevel);
  444. Toplevel = null;
  445. }
  446. }
  447. }
  448. static public RunState Begin (Toplevel toplevel)
  449. {
  450. if (toplevel == null)
  451. throw new ArgumentNullException (nameof(toplevel));
  452. var rs = new RunState (toplevel);
  453. Init ();
  454. Driver.PrepareToRun ();
  455. toplevels.Push (toplevel);
  456. toplevel.LayoutSubviews ();
  457. toplevel.FocusFirst ();
  458. Redraw (toplevel);
  459. toplevel.PositionCursor ();
  460. Driver.Refresh ();
  461. return rs;
  462. }
  463. static public void End (RunState rs)
  464. {
  465. if (rs == null)
  466. throw new ArgumentNullException (nameof (rs));
  467. rs.Dispose ();
  468. }
  469. static void Shutdown ()
  470. {
  471. Driver.End ();
  472. }
  473. static void Redraw (View view)
  474. {
  475. view.Redraw ();
  476. Driver.Refresh ();
  477. }
  478. static void Refresh (View view)
  479. {
  480. view.Redraw ();
  481. Driver.Refresh ();
  482. }
  483. public static void Refresh ()
  484. {
  485. Driver.RedrawTop ();
  486. View last = null;
  487. foreach (var v in toplevels){
  488. v.Redraw ();
  489. last = v;
  490. }
  491. if (last != null)
  492. last.PositionCursor ();
  493. Driver.Refresh ();
  494. }
  495. internal static void End (View view)
  496. {
  497. if (toplevels.Peek () != view)
  498. throw new ArgumentException ("The view that you end with must be balanced");
  499. toplevels.Pop ();
  500. if (toplevels.Count == 0)
  501. Shutdown ();
  502. else
  503. Refresh ();
  504. }
  505. /// <summary>
  506. /// Runs the main loop for the created dialog
  507. /// </summary>
  508. /// <remarks>
  509. /// Use the wait parameter to control whether this is a
  510. /// blocking or non-blocking call.
  511. /// </remarks>
  512. public static void RunLoop(RunState state, bool wait = true)
  513. {
  514. if (state == null)
  515. throw new ArgumentNullException(nameof(state));
  516. if (state.Toplevel == null)
  517. throw new ObjectDisposedException("state");
  518. for (state.Toplevel.Running = true; state.Toplevel.Running;) {
  519. if (MainLoop.EventsPending(wait)){
  520. MainLoop.MainIteration();
  521. if (Iteration != null)
  522. Iteration(null, EventArgs.Empty);
  523. }
  524. else if (wait == false)
  525. return;
  526. }
  527. }
  528. public static void Run ()
  529. {
  530. Run (Top);
  531. }
  532. /// <summary>
  533. /// Runs the main loop on the given container.
  534. /// </summary>
  535. /// <remarks>
  536. /// This method is used to start processing events
  537. /// for the main application, but it is also used to
  538. /// run modal dialog boxes.
  539. /// </remarks>
  540. public static void Run (Toplevel view)
  541. {
  542. var runToken = Begin (view);
  543. RunLoop (runToken);
  544. End (runToken);
  545. }
  546. }
  547. }