Driver.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. //
  2. // Driver.cs: Abstract and concrete interfaces to the console (curses or console)
  3. //
  4. // Authors:
  5. // Miguel de Icaza ([email protected])
  6. //
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Runtime.InteropServices;
  10. using Mono.Terminal;
  11. using Unix.Terminal;
  12. namespace Terminal {
  13. /// <summary>
  14. /// Basic colors that can be used to set the foreground and background colors in console applications. These can only be
  15. /// </summary>
  16. public enum Color {
  17. /// <summary>
  18. /// The black color.
  19. /// </summary>
  20. Black,
  21. /// <summary>
  22. /// The blue color.
  23. /// </summary>
  24. Blue,
  25. /// <summary>
  26. /// The green color.
  27. /// </summary>
  28. Green,
  29. /// <summary>
  30. /// The cyan color.
  31. /// </summary>
  32. Cyan,
  33. /// <summary>
  34. /// The red color.
  35. /// </summary>
  36. Red,
  37. /// <summary>
  38. /// The magenta color.
  39. /// </summary>
  40. Magenta,
  41. /// <summary>
  42. /// The brown color.
  43. /// </summary>
  44. Brown,
  45. /// <summary>
  46. /// The gray color.
  47. /// </summary>
  48. Gray,
  49. /// <summary>
  50. /// The dark gray color.
  51. /// </summary>
  52. DarkGray,
  53. /// <summary>
  54. /// The bright bBlue color.
  55. /// </summary>
  56. BrightBlue,
  57. /// <summary>
  58. /// The bright green color.
  59. /// </summary>
  60. BrightGreen,
  61. /// <summary>
  62. /// The brigh cyan color.
  63. /// </summary>
  64. BrighCyan,
  65. /// <summary>
  66. /// The bright red color.
  67. /// </summary>
  68. BrightRed,
  69. /// <summary>
  70. /// The bright magenta color.
  71. /// </summary>
  72. BrightMagenta,
  73. /// <summary>
  74. /// The bright yellow color.
  75. /// </summary>
  76. BrightYellow,
  77. /// <summary>
  78. /// The White color.
  79. /// </summary>
  80. White
  81. }
  82. /// <summary>
  83. /// Attributes are used as elements that contain both a foreground and a background or platform specific features
  84. /// </summary>
  85. /// <remarks>
  86. /// Attributes are needed to map colors to terminal capabilities that might lack colors, on color
  87. /// scenarios, they encode both the foreground and the background color and are used in the ColorScheme
  88. /// class to define color schemes that can be used in your application.
  89. /// </remarks>
  90. public struct Attribute {
  91. internal int value;
  92. public Attribute (int v)
  93. {
  94. value = v;
  95. }
  96. public static implicit operator int (Attribute c) => c.value;
  97. public static implicit operator Attribute (int v) => new Attribute (v);
  98. }
  99. /// <summary>
  100. /// Color scheme definitions, they cover some common scenarios and are used
  101. /// typically in toplevel containers to set the scheme that is used by all the
  102. /// views contained inside.
  103. /// </summary>
  104. public class ColorScheme {
  105. /// <summary>
  106. /// The default color for text, when the view is not focused.
  107. /// </summary>
  108. public Attribute Normal;
  109. /// <summary>
  110. /// The color for text when the view has the focus.
  111. /// </summary>
  112. public Attribute Focus;
  113. /// <summary>
  114. /// The color for the hotkey when a view is not focused
  115. /// </summary>
  116. public Attribute HotNormal;
  117. /// <summary>
  118. /// The color for the hotkey when the view is focused.
  119. /// </summary>
  120. public Attribute HotFocus;
  121. }
  122. /// <summary>
  123. /// The default ColorSchemes for the application.
  124. /// </summary>
  125. public static class Colors {
  126. /// <summary>
  127. /// The base color scheme, for the default toplevel views.
  128. /// </summary>
  129. public static ColorScheme Base;
  130. /// <summary>
  131. /// The dialog color scheme, for standard popup dialog boxes
  132. /// </summary>
  133. public static ColorScheme Dialog;
  134. /// <summary>
  135. /// The menu bar color
  136. /// </summary>
  137. public static ColorScheme Menu;
  138. /// <summary>
  139. /// The color scheme for showing errors.
  140. /// </summary>
  141. public static ColorScheme Error;
  142. }
  143. /// <summary>
  144. /// Special characters that can be drawn with Driver.AddSpecial.
  145. /// </summary>
  146. public enum SpecialChar {
  147. /// <summary>
  148. /// Horizontal line character.
  149. /// </summary>
  150. HLine,
  151. }
  152. /// <summary>
  153. /// ConsoleDriver is an abstract class that defines the requirements for a console driver. One implementation if the CursesDriver, and another one uses the .NET Console one.
  154. /// </summary>
  155. public abstract class ConsoleDriver {
  156. /// <summary>
  157. /// The current number of columns in the terminal.
  158. /// </summary>
  159. public abstract int Cols { get; }
  160. /// <summary>
  161. /// The current number of rows in the terminal.
  162. /// </summary>
  163. public abstract int Rows { get; }
  164. /// <summary>
  165. /// Initializes the driver
  166. /// </summary>
  167. /// <param name="terminalResized">Method to invoke when the terminal is resized.</param>
  168. public abstract void Init (Action terminalResized);
  169. /// <summary>
  170. /// Moves the cursor to the specified column and row.
  171. /// </summary>
  172. /// <param name="col">Column to move the cursor to.</param>
  173. /// <param name="row">Row to move the cursor to.</param>
  174. public abstract void Move (int col, int row);
  175. /// <summary>
  176. /// Adds the specified rune to the display at the current cursor position
  177. /// </summary>
  178. /// <param name="rune">Rune to add.</param>
  179. public abstract void AddCh (int rune);
  180. /// <summary>
  181. /// Adds the specified
  182. /// </summary>
  183. /// <param name="str">String.</param>
  184. public abstract void AddStr (string str);
  185. public abstract void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> target, Action<MouseEvent> mouse);
  186. /// <summary>
  187. /// Updates the screen to reflect all the changes that have been done to the display buffer
  188. /// </summary>
  189. public abstract void Refresh ();
  190. /// <summary>
  191. /// Ends the execution of the console driver.
  192. /// </summary>
  193. public abstract void End ();
  194. public abstract void RedrawTop ();
  195. public abstract void SetAttribute (Attribute c);
  196. // Set Colors from limit sets of colors
  197. public abstract void SetColors (ConsoleColor foreground, ConsoleColor background);
  198. // Advanced uses - set colors to any pre-set pairs, you would need to init_color
  199. // that independently with the R, G, B values.
  200. /// <summary>
  201. /// Advanced uses - set colors to any pre-set pairs, you would need to init_color
  202. /// that independently with the R, G, B values.
  203. /// </summary>
  204. /// <param name="foregroundColorId">Foreground color identifier.</param>
  205. /// <param name="backgroundColorId">Background color identifier.</param>
  206. public abstract void SetColors (short foregroundColorId, short backgroundColorId);
  207. public abstract void DrawFrame (Rect region, bool fill);
  208. /// <summary>
  209. /// Draws a special characters in the screen
  210. /// </summary>
  211. /// <param name="ch">Ch.</param>
  212. public abstract void AddSpecial (SpecialChar ch);
  213. /// <summary>
  214. /// Suspend the application, typically needs to save the state, suspend the app and upon return, reset the console driver.
  215. /// </summary>
  216. public abstract void Suspend ();
  217. Rect clip;
  218. /// <summary>
  219. /// Controls the current clipping region that AddCh/AddStr is subject to.
  220. /// </summary>
  221. /// <value>The clip.</value>
  222. public Rect Clip {
  223. get => clip;
  224. set => this.clip = value;
  225. }
  226. public abstract void StartReportingMouseMoves ();
  227. public abstract void StopReportingMouseMoves ();
  228. }
  229. /// <summary>
  230. /// This is the Curses driver for the gui.cs/Terminal framework.
  231. /// </summary>
  232. internal class CursesDriver : ConsoleDriver {
  233. Action terminalResized;
  234. public override int Cols => Curses.Cols;
  235. public override int Rows => Curses.Lines;
  236. // Current row, and current col, tracked by Move/AddCh only
  237. int ccol, crow;
  238. bool needMove;
  239. public override void Move (int col, int row)
  240. {
  241. ccol = col;
  242. crow = row;
  243. if (Clip.Contains (col, row)) {
  244. Curses.move (row, col);
  245. needMove = false;
  246. } else {
  247. Curses.move (Clip.Y, Clip.X);
  248. needMove = true;
  249. }
  250. }
  251. static bool sync;
  252. public override void AddCh (int rune)
  253. {
  254. if (Clip.Contains (ccol, crow)) {
  255. if (needMove) {
  256. Curses.move (crow, ccol);
  257. needMove = false;
  258. }
  259. Curses.addch (rune);
  260. } else
  261. needMove = true;
  262. if (sync)
  263. Application.Driver.Refresh ();
  264. ccol++;
  265. }
  266. public override void AddSpecial (SpecialChar ch)
  267. {
  268. switch (ch) {
  269. case SpecialChar.HLine:
  270. AddCh (Curses.ACS_HLINE);
  271. break;
  272. }
  273. }
  274. public override void AddStr (string str)
  275. {
  276. // TODO; optimize this to determine if the str fits in the clip region, and if so, use Curses.addstr directly
  277. foreach (var rune in str)
  278. AddCh ((int)rune);
  279. }
  280. public override void Refresh () => Curses.refresh ();
  281. public override void End () => Curses.endwin ();
  282. public override void RedrawTop () => window.redrawwin ();
  283. public override void SetAttribute (Attribute c) => Curses.attrset (c.value);
  284. public Curses.Window window;
  285. static short last_color_pair = 16;
  286. static Attribute MakeColor (short f, short b)
  287. {
  288. Curses.InitColorPair (++last_color_pair, f, b);
  289. return new Attribute () { value = Curses.ColorPair (last_color_pair) };
  290. }
  291. int [,] colorPairs = new int [16, 16];
  292. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  293. {
  294. int f = (short)foreground;
  295. int b = (short)background;
  296. var v = colorPairs [f, b];
  297. if ((v & 0x10000) == 0) {
  298. b = b & 0x7;
  299. bool bold = (f & 0x8) != 0;
  300. f = f & 0x7;
  301. v = MakeColor ((short)f, (short)b) | (bold ? Curses.A_BOLD : 0);
  302. colorPairs [(int)foreground, (int)background] = v | 0x1000;
  303. }
  304. SetAttribute (v & 0xffff);
  305. }
  306. Dictionary<int, int> rawPairs = new Dictionary<int, int> ();
  307. public override void SetColors (short foreColorId, short backgroundColorId)
  308. {
  309. int key = (((ushort)foreColorId << 16)) | (ushort)backgroundColorId;
  310. if (!rawPairs.TryGetValue (key, out var v)) {
  311. v = MakeColor (foreColorId, backgroundColorId);
  312. rawPairs [key] = v;
  313. }
  314. SetAttribute (v);
  315. }
  316. static Key MapCursesKey (int cursesKey)
  317. {
  318. switch (cursesKey) {
  319. case Curses.KeyF1: return Key.F1;
  320. case Curses.KeyF2: return Key.F2;
  321. case Curses.KeyF3: return Key.F3;
  322. case Curses.KeyF4: return Key.F4;
  323. case Curses.KeyF5: return Key.F5;
  324. case Curses.KeyF6: return Key.F6;
  325. case Curses.KeyF7: return Key.F7;
  326. case Curses.KeyF8: return Key.F8;
  327. case Curses.KeyF9: return Key.F9;
  328. case Curses.KeyF10: return Key.F10;
  329. case Curses.KeyUp: return Key.CursorUp;
  330. case Curses.KeyDown: return Key.CursorDown;
  331. case Curses.KeyLeft: return Key.CursorLeft;
  332. case Curses.KeyRight: return Key.CursorRight;
  333. case Curses.KeyHome: return Key.Home;
  334. case Curses.KeyEnd: return Key.End;
  335. case Curses.KeyNPage: return Key.PageDown;
  336. case Curses.KeyPPage: return Key.PageUp;
  337. case Curses.KeyDeleteChar: return Key.DeleteChar;
  338. case Curses.KeyInsertChar: return Key.InsertChar;
  339. case Curses.KeyBackTab: return Key.BackTab;
  340. default: return Key.Unknown;
  341. }
  342. }
  343. static MouseEvent ToDriverMouse (Curses.MouseEvent cev)
  344. {
  345. return new MouseEvent () {
  346. X = cev.X,
  347. Y = cev.Y,
  348. Flags = (MouseFlags)cev.ButtonState
  349. };
  350. }
  351. void ProcessInput (Action<KeyEvent> keyHandler, Action<MouseEvent> mouseHandler)
  352. {
  353. int wch;
  354. var code = Curses.get_wch (out wch);
  355. if (code == Curses.KEY_CODE_YES) {
  356. if (wch == Curses.KeyResize) {
  357. if (Curses.CheckWinChange ()) {
  358. terminalResized ();
  359. return;
  360. }
  361. }
  362. if (wch == Curses.KeyMouse) {
  363. Curses.MouseEvent ev;
  364. Curses.getmouse (out ev);
  365. mouseHandler (ToDriverMouse (ev));
  366. return;
  367. }
  368. keyHandler (new KeyEvent (MapCursesKey (wch)));
  369. return;
  370. }
  371. // Special handling for ESC, we want to try to catch ESC+letter to simulate alt-letter as well as Alt-Fkey
  372. if (wch == 27) {
  373. Curses.timeout (100);
  374. code = Curses.get_wch (out wch);
  375. if (code == Curses.KEY_CODE_YES)
  376. keyHandler (new KeyEvent (Key.AltMask | MapCursesKey (wch)));
  377. if (code == 0) {
  378. KeyEvent key;
  379. // The ESC-number handling, debatable.
  380. if (wch >= '1' && wch <= '9')
  381. key = new KeyEvent ((Key)((int)Key.F1 + (wch - '0' - 1)));
  382. else if (wch == '0')
  383. key = new KeyEvent (Key.F10);
  384. else if (wch == 27)
  385. key = new KeyEvent ((Key)wch);
  386. else
  387. key = new KeyEvent (Key.AltMask | (Key)wch);
  388. keyHandler (key);
  389. } else
  390. keyHandler (new KeyEvent (Key.Esc));
  391. } else
  392. keyHandler (new KeyEvent ((Key)wch));
  393. }
  394. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<MouseEvent> mouseHandler)
  395. {
  396. Curses.timeout (-1);
  397. mainLoop.AddWatch (0, Mono.Terminal.MainLoop.Condition.PollIn, x => {
  398. ProcessInput (keyHandler, mouseHandler);
  399. return true;
  400. });
  401. }
  402. public override void DrawFrame (Rect region, bool fill)
  403. {
  404. int width = region.Width;
  405. int height = region.Height;
  406. int b;
  407. Move (region.X, region.Y);
  408. AddCh (Curses.ACS_ULCORNER);
  409. for (b = 0; b < width - 2; b++)
  410. AddCh (Curses.ACS_HLINE);
  411. AddCh (Curses.ACS_URCORNER);
  412. for (b = 1; b < height - 1; b++) {
  413. Move (region.X, region.Y + b);
  414. AddCh (Curses.ACS_VLINE);
  415. if (fill) {
  416. for (int x = 1; x < width - 1; x++)
  417. AddCh (' ');
  418. } else
  419. Move (region.X + width - 1, region.Y + b);
  420. AddCh (Curses.ACS_VLINE);
  421. }
  422. Move (region.X, region.Y + height - 1);
  423. AddCh (Curses.ACS_LLCORNER);
  424. for (b = 0; b < width - 2; b++)
  425. AddCh (Curses.ACS_HLINE);
  426. AddCh (Curses.ACS_LRCORNER);
  427. }
  428. Curses.Event oldMouseEvents, reportableMouseEvents;
  429. public override void Init (Action terminalResized)
  430. {
  431. if (window != null)
  432. return;
  433. try {
  434. window = Curses.initscr ();
  435. } catch (Exception e) {
  436. Console.WriteLine ("Curses failed to initialize, the exception is: " + e);
  437. }
  438. Curses.raw ();
  439. Curses.noecho ();
  440. Curses.Window.Standard.keypad (true);
  441. reportableMouseEvents = Curses.mousemask (Curses.Event.AllEvents | Curses.Event.ReportMousePosition, out oldMouseEvents);
  442. this.terminalResized = terminalResized;
  443. StartReportingMouseMoves ();
  444. Colors.Base = new ColorScheme ();
  445. Colors.Dialog = new ColorScheme ();
  446. Colors.Menu = new ColorScheme ();
  447. Colors.Error = new ColorScheme ();
  448. Clip = new Rect (0, 0, Cols, Rows);
  449. if (Curses.HasColors) {
  450. Curses.StartColor ();
  451. Curses.UseDefaultColors ();
  452. Colors.Base.Normal = MakeColor (Curses.COLOR_WHITE, Curses.COLOR_BLUE);
  453. Colors.Base.Focus = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_CYAN);
  454. Colors.Base.HotNormal = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_BLUE);
  455. Colors.Base.HotFocus = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_CYAN);
  456. // Focused,
  457. // Selected, Hot: Yellow on Black
  458. // Selected, text: white on black
  459. // Unselected, hot: yellow on cyan
  460. // unselected, text: same as unfocused
  461. Colors.Menu.HotFocus = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_BLACK);
  462. Colors.Menu.Focus = Curses.A_BOLD | MakeColor (Curses.COLOR_WHITE, Curses.COLOR_BLACK);
  463. Colors.Menu.HotNormal = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_CYAN);
  464. Colors.Menu.Normal = Curses.A_BOLD | MakeColor (Curses.COLOR_WHITE, Curses.COLOR_CYAN);
  465. Colors.Dialog.Normal = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_WHITE);
  466. Colors.Dialog.Focus = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_CYAN);
  467. Colors.Dialog.HotNormal = MakeColor (Curses.COLOR_BLUE, Curses.COLOR_WHITE);
  468. Colors.Dialog.HotFocus = MakeColor (Curses.COLOR_BLUE, Curses.COLOR_CYAN);
  469. Colors.Error.Normal = Curses.A_BOLD | MakeColor (Curses.COLOR_WHITE, Curses.COLOR_RED);
  470. Colors.Error.Focus = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_WHITE);
  471. Colors.Error.HotNormal = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_RED);
  472. Colors.Error.HotFocus = Colors.Error.HotNormal;
  473. } else {
  474. Colors.Base.Normal = Curses.A_NORMAL;
  475. Colors.Base.Focus = Curses.A_REVERSE;
  476. Colors.Base.HotNormal = Curses.A_BOLD;
  477. Colors.Base.HotFocus = Curses.A_BOLD | Curses.A_REVERSE;
  478. Colors.Menu.Normal = Curses.A_REVERSE;
  479. Colors.Menu.Focus = Curses.A_NORMAL;
  480. Colors.Menu.HotNormal = Curses.A_BOLD;
  481. Colors.Menu.HotFocus = Curses.A_NORMAL;
  482. Colors.Dialog.Normal = Curses.A_REVERSE;
  483. Colors.Dialog.Focus = Curses.A_NORMAL;
  484. Colors.Dialog.HotNormal = Curses.A_BOLD;
  485. Colors.Dialog.HotFocus = Curses.A_NORMAL;
  486. Colors.Error.Normal = Curses.A_BOLD;
  487. Colors.Error.Focus = Curses.A_BOLD | Curses.A_REVERSE;
  488. Colors.Error.HotNormal = Curses.A_BOLD | Curses.A_REVERSE;
  489. Colors.Error.HotFocus = Curses.A_REVERSE;
  490. }
  491. }
  492. public override void Suspend ()
  493. {
  494. StopReportingMouseMoves ();
  495. Platform.Suspend ();
  496. Curses.Window.Standard.redrawwin ();
  497. Curses.refresh ();
  498. StartReportingMouseMoves ();
  499. }
  500. public override void StartReportingMouseMoves()
  501. {
  502. Console.Out.Write ("\x1b[?1003h");
  503. Console.Out.Flush ();
  504. }
  505. public override void StopReportingMouseMoves()
  506. {
  507. Console.Out.Write ("\x1b[?1003l");
  508. Console.Out.Flush ();
  509. }
  510. }
  511. internal static class Platform {
  512. [DllImport ("libc")]
  513. static extern int uname (IntPtr buf);
  514. [DllImport ("libc")]
  515. static extern int killpg (int pgrp, int pid);
  516. static int suspendSignal;
  517. static int GetSuspendSignal ()
  518. {
  519. if (suspendSignal != 0)
  520. return suspendSignal;
  521. IntPtr buf = Marshal.AllocHGlobal (8192);
  522. if (uname (buf) != 0) {
  523. Marshal.FreeHGlobal (buf);
  524. suspendSignal = -1;
  525. return suspendSignal;
  526. }
  527. try {
  528. switch (Marshal.PtrToStringAnsi (buf)) {
  529. case "Darwin":
  530. case "DragonFly":
  531. case "FreeBSD":
  532. case "NetBSD":
  533. case "OpenBSD":
  534. suspendSignal = 18;
  535. break;
  536. case "Linux":
  537. // TODO: should fetch the machine name and
  538. // if it is MIPS return 24
  539. suspendSignal = 20;
  540. break;
  541. case "Solaris":
  542. suspendSignal = 24;
  543. break;
  544. default:
  545. suspendSignal = -1;
  546. break;
  547. }
  548. return suspendSignal;
  549. } finally {
  550. Marshal.FreeHGlobal (buf);
  551. }
  552. }
  553. /// <summary>
  554. /// Suspends the process by sending SIGTSTP to itself
  555. /// </summary>
  556. /// <returns>The suspend.</returns>
  557. static public bool Suspend ()
  558. {
  559. int signal = GetSuspendSignal ();
  560. if (signal == -1)
  561. return false;
  562. killpg (0, signal);
  563. return true;
  564. }
  565. }
  566. }