Application.cs 19 KB

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