Driver.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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. Black,
  18. Blue,
  19. Green,
  20. Cyan,
  21. Red,
  22. Magenta,
  23. Brown,
  24. Gray,
  25. DarkGray,
  26. BrightBlue,
  27. BrightGreen,
  28. BrighCyan,
  29. BrightRed,
  30. BrightMagenta,
  31. BrightYellow,
  32. White
  33. }
  34. /// <summary>
  35. /// Attributes are used as elements that contain both a foreground and a background or platform specific features
  36. /// </summary>
  37. /// <remarks>
  38. /// Attributes are needed to map colors to terminal capabilities that might lack colors, on color
  39. /// scenarios, they encode both the foreground and the background color and are used in the ColorScheme
  40. /// class to define color schemes that can be used in your application.
  41. /// </remarks>
  42. public struct Attribute {
  43. internal int value;
  44. public Attribute (int v)
  45. {
  46. value = v;
  47. }
  48. public static implicit operator int (Attribute c) => c.value;
  49. public static implicit operator Attribute (int v) => new Attribute (v);
  50. }
  51. /// <summary>
  52. /// Color scheme definitions
  53. /// </summary>
  54. public class ColorScheme {
  55. public Attribute Normal;
  56. public Attribute Focus;
  57. public Attribute HotNormal;
  58. public Attribute HotFocus;
  59. }
  60. public static class Colors {
  61. public static ColorScheme Base, Dialog, Menu, Error;
  62. }
  63. public enum SpecialChar {
  64. HLine,
  65. }
  66. /// <summary>
  67. /// 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.
  68. /// </summary>
  69. public abstract class ConsoleDriver {
  70. public abstract int Cols { get; }
  71. public abstract int Rows { get; }
  72. public abstract void Init (Action terminalResized);
  73. public abstract void Move (int col, int row);
  74. public abstract void AddCh (int ch);
  75. public abstract void AddStr (string str);
  76. public abstract void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> target, Action<MouseEvent> mouse);
  77. public abstract void Refresh ();
  78. public abstract void End ();
  79. public abstract void RedrawTop ();
  80. public abstract void SetAttribute (Attribute c);
  81. // Set Colors from limit sets of colors
  82. public abstract void SetColors (ConsoleColor foreground, ConsoleColor background);
  83. // Advanced uses - set colors to any pre-set pairs, you would need to init_color
  84. // that independently with the R, G, B values.
  85. public abstract void SetColors (short foreColorId, short backgroundColorId);
  86. public abstract void DrawFrame (Rect region, bool fill);
  87. public abstract void AddSpecial (SpecialChar ch);
  88. public abstract void Suspend ();
  89. Rect clip;
  90. public Rect Clip {
  91. get => clip;
  92. set => this.clip = value;
  93. }
  94. public abstract void StartReportingMouseMoves ();
  95. public abstract void StopReportingMouseMoves ();
  96. }
  97. /// <summary>
  98. /// This is the Curses driver for the gui.cs/Terminal framework.
  99. /// </summary>
  100. public class CursesDriver : ConsoleDriver {
  101. Action terminalResized;
  102. public override int Cols => Curses.Cols;
  103. public override int Rows => Curses.Lines;
  104. // Current row, and current col, tracked by Move/AddCh only
  105. int ccol, crow;
  106. bool needMove;
  107. public override void Move (int col, int row)
  108. {
  109. ccol = col;
  110. crow = row;
  111. if (Clip.Contains (col, row)) {
  112. Curses.move (row, col);
  113. needMove = false;
  114. } else {
  115. Curses.move (Clip.Y, Clip.X);
  116. needMove = true;
  117. }
  118. }
  119. static bool sync;
  120. public override void AddCh (int ch)
  121. {
  122. if (Clip.Contains (ccol, crow)) {
  123. if (needMove) {
  124. Curses.move (crow, ccol);
  125. needMove = false;
  126. }
  127. Curses.addch (ch);
  128. } else
  129. needMove = true;
  130. if (sync)
  131. Application.Driver.Refresh ();
  132. ccol++;
  133. }
  134. public override void AddSpecial (SpecialChar ch)
  135. {
  136. switch (ch) {
  137. case SpecialChar.HLine:
  138. AddCh (Curses.ACS_HLINE);
  139. break;
  140. }
  141. }
  142. public override void AddStr (string str)
  143. {
  144. // TODO; optimize this to determine if the str fits in the clip region, and if so, use Curses.addstr directly
  145. foreach (var c in str)
  146. AddCh ((int)c);
  147. }
  148. public override void Refresh () => Curses.refresh ();
  149. public override void End () => Curses.endwin ();
  150. public override void RedrawTop () => window.redrawwin ();
  151. public override void SetAttribute (Attribute c) => Curses.attrset (c.value);
  152. public Curses.Window window;
  153. static short last_color_pair = 16;
  154. static Attribute MakeColor (short f, short b)
  155. {
  156. Curses.InitColorPair (++last_color_pair, f, b);
  157. return new Attribute () { value = Curses.ColorPair (last_color_pair) };
  158. }
  159. int [,] colorPairs = new int [16, 16];
  160. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  161. {
  162. int f = (short)foreground;
  163. int b = (short)background;
  164. var v = colorPairs [f, b];
  165. if ((v & 0x10000) == 0) {
  166. b = b & 0x7;
  167. bool bold = (f & 0x8) != 0;
  168. f = f & 0x7;
  169. v = MakeColor ((short)f, (short)b) | (bold ? Curses.A_BOLD : 0);
  170. colorPairs [(int)foreground, (int)background] = v | 0x1000;
  171. }
  172. SetAttribute (v & 0xffff);
  173. }
  174. Dictionary<int, int> rawPairs = new Dictionary<int, int> ();
  175. public override void SetColors (short foreColorId, short backgroundColorId)
  176. {
  177. int key = (((ushort)foreColorId << 16)) | (ushort)backgroundColorId;
  178. if (!rawPairs.TryGetValue (key, out var v)) {
  179. v = MakeColor (foreColorId, backgroundColorId);
  180. rawPairs [key] = v;
  181. }
  182. SetAttribute (v);
  183. }
  184. static Key MapCursesKey (int cursesKey)
  185. {
  186. switch (cursesKey) {
  187. case Curses.KeyF1: return Key.F1;
  188. case Curses.KeyF2: return Key.F2;
  189. case Curses.KeyF3: return Key.F3;
  190. case Curses.KeyF4: return Key.F4;
  191. case Curses.KeyF5: return Key.F5;
  192. case Curses.KeyF6: return Key.F6;
  193. case Curses.KeyF7: return Key.F7;
  194. case Curses.KeyF8: return Key.F8;
  195. case Curses.KeyF9: return Key.F9;
  196. case Curses.KeyF10: return Key.F10;
  197. case Curses.KeyUp: return Key.CursorUp;
  198. case Curses.KeyDown: return Key.CursorDown;
  199. case Curses.KeyLeft: return Key.CursorLeft;
  200. case Curses.KeyRight: return Key.CursorRight;
  201. case Curses.KeyHome: return Key.Home;
  202. case Curses.KeyEnd: return Key.End;
  203. case Curses.KeyNPage: return Key.PageDown;
  204. case Curses.KeyPPage: return Key.PageUp;
  205. case Curses.KeyDeleteChar: return Key.DeleteChar;
  206. case Curses.KeyInsertChar: return Key.InsertChar;
  207. case Curses.KeyBackTab: return Key.BackTab;
  208. default: return Key.Unknown;
  209. }
  210. }
  211. static MouseEvent ToDriverMouse (Curses.MouseEvent cev)
  212. {
  213. return new MouseEvent () {
  214. X = cev.X,
  215. Y = cev.Y,
  216. Flags = (MouseFlags)cev.ButtonState
  217. };
  218. }
  219. void ProcessInput (Action<KeyEvent> keyHandler, Action<MouseEvent> mouseHandler)
  220. {
  221. int wch;
  222. var code = Curses.get_wch (out wch);
  223. if (code == Curses.KEY_CODE_YES) {
  224. if (wch == Curses.KeyResize) {
  225. if (Curses.CheckWinChange ()) {
  226. terminalResized ();
  227. return;
  228. }
  229. }
  230. if (wch == Curses.KeyMouse) {
  231. Curses.MouseEvent ev;
  232. Curses.getmouse (out ev);
  233. mouseHandler (ToDriverMouse (ev));
  234. return;
  235. }
  236. keyHandler (new KeyEvent (MapCursesKey (wch)));
  237. return;
  238. }
  239. // Special handling for ESC, we want to try to catch ESC+letter to simulate alt-letter as well as Alt-Fkey
  240. if (wch == 27) {
  241. Curses.timeout (100);
  242. code = Curses.get_wch (out wch);
  243. if (code == Curses.KEY_CODE_YES)
  244. keyHandler (new KeyEvent (Key.AltMask | MapCursesKey (wch)));
  245. if (code == 0) {
  246. KeyEvent key;
  247. // The ESC-number handling, debatable.
  248. if (wch >= '1' && wch <= '9')
  249. key = new KeyEvent ((Key)((int)Key.F1 + (wch - '0' - 1)));
  250. else if (wch == '0')
  251. key = new KeyEvent (Key.F10);
  252. else if (wch == 27)
  253. key = new KeyEvent ((Key)wch);
  254. else
  255. key = new KeyEvent (Key.AltMask | (Key)wch);
  256. keyHandler (key);
  257. } else
  258. keyHandler (new KeyEvent (Key.Esc));
  259. } else
  260. keyHandler (new KeyEvent ((Key)wch));
  261. }
  262. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<MouseEvent> mouseHandler)
  263. {
  264. Curses.timeout (-1);
  265. mainLoop.AddWatch (0, Mono.Terminal.MainLoop.Condition.PollIn, x => {
  266. ProcessInput (keyHandler, mouseHandler);
  267. return true;
  268. });
  269. }
  270. public override void DrawFrame (Rect region, bool fill)
  271. {
  272. int width = region.Width;
  273. int height = region.Height;
  274. int b;
  275. Move (region.X, region.Y);
  276. AddCh (Curses.ACS_ULCORNER);
  277. for (b = 0; b < width - 2; b++)
  278. AddCh (Curses.ACS_HLINE);
  279. AddCh (Curses.ACS_URCORNER);
  280. for (b = 1; b < height - 1; b++) {
  281. Move (region.X, region.Y + b);
  282. AddCh (Curses.ACS_VLINE);
  283. if (fill) {
  284. for (int x = 1; x < width - 1; x++)
  285. AddCh (' ');
  286. } else
  287. Move (region.X + width - 1, region.Y + b);
  288. AddCh (Curses.ACS_VLINE);
  289. }
  290. Move (region.X, region.Y + height - 1);
  291. AddCh (Curses.ACS_LLCORNER);
  292. for (b = 0; b < width - 2; b++)
  293. AddCh (Curses.ACS_HLINE);
  294. AddCh (Curses.ACS_LRCORNER);
  295. }
  296. Curses.Event oldMouseEvents, reportableMouseEvents;
  297. public override void Init (Action terminalResized)
  298. {
  299. if (window != null)
  300. return;
  301. try {
  302. window = Curses.initscr ();
  303. } catch (Exception e) {
  304. Console.WriteLine ("Curses failed to initialize, the exception is: " + e);
  305. }
  306. Curses.raw ();
  307. Curses.noecho ();
  308. Curses.Window.Standard.keypad (true);
  309. reportableMouseEvents = Curses.mousemask (Curses.Event.AllEvents | Curses.Event.ReportMousePosition, out oldMouseEvents);
  310. this.terminalResized = terminalResized;
  311. StartReportingMouseMoves ();
  312. Colors.Base = new ColorScheme ();
  313. Colors.Dialog = new ColorScheme ();
  314. Colors.Menu = new ColorScheme ();
  315. Colors.Error = new ColorScheme ();
  316. Clip = new Rect (0, 0, Cols, Rows);
  317. if (Curses.HasColors) {
  318. Curses.StartColor ();
  319. Curses.UseDefaultColors ();
  320. Colors.Base.Normal = MakeColor (Curses.COLOR_WHITE, Curses.COLOR_BLUE);
  321. Colors.Base.Focus = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_CYAN);
  322. Colors.Base.HotNormal = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_BLUE);
  323. Colors.Base.HotFocus = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_CYAN);
  324. // Focused,
  325. // Selected, Hot: Yellow on Black
  326. // Selected, text: white on black
  327. // Unselected, hot: yellow on cyan
  328. // unselected, text: same as unfocused
  329. Colors.Menu.HotFocus = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_BLACK);
  330. Colors.Menu.Focus = Curses.A_BOLD | MakeColor (Curses.COLOR_WHITE, Curses.COLOR_BLACK);
  331. Colors.Menu.HotNormal = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_CYAN);
  332. Colors.Menu.Normal = Curses.A_BOLD | MakeColor (Curses.COLOR_WHITE, Curses.COLOR_CYAN);
  333. Colors.Dialog.Normal = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_WHITE);
  334. Colors.Dialog.Focus = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_CYAN);
  335. Colors.Dialog.HotNormal = MakeColor (Curses.COLOR_BLUE, Curses.COLOR_WHITE);
  336. Colors.Dialog.HotFocus = MakeColor (Curses.COLOR_BLUE, Curses.COLOR_CYAN);
  337. Colors.Error.Normal = Curses.A_BOLD | MakeColor (Curses.COLOR_WHITE, Curses.COLOR_RED);
  338. Colors.Error.Focus = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_WHITE);
  339. Colors.Error.HotNormal = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_RED);
  340. Colors.Error.HotFocus = Colors.Error.HotNormal;
  341. } else {
  342. Colors.Base.Normal = Curses.A_NORMAL;
  343. Colors.Base.Focus = Curses.A_REVERSE;
  344. Colors.Base.HotNormal = Curses.A_BOLD;
  345. Colors.Base.HotFocus = Curses.A_BOLD | Curses.A_REVERSE;
  346. Colors.Menu.Normal = Curses.A_REVERSE;
  347. Colors.Menu.Focus = Curses.A_NORMAL;
  348. Colors.Menu.HotNormal = Curses.A_BOLD;
  349. Colors.Menu.HotFocus = Curses.A_NORMAL;
  350. Colors.Dialog.Normal = Curses.A_REVERSE;
  351. Colors.Dialog.Focus = Curses.A_NORMAL;
  352. Colors.Dialog.HotNormal = Curses.A_BOLD;
  353. Colors.Dialog.HotFocus = Curses.A_NORMAL;
  354. Colors.Error.Normal = Curses.A_BOLD;
  355. Colors.Error.Focus = Curses.A_BOLD | Curses.A_REVERSE;
  356. Colors.Error.HotNormal = Curses.A_BOLD | Curses.A_REVERSE;
  357. Colors.Error.HotFocus = Curses.A_REVERSE;
  358. }
  359. }
  360. public override void Suspend ()
  361. {
  362. StopReportingMouseMoves ();
  363. Platform.Suspend ();
  364. Curses.Window.Standard.redrawwin ();
  365. Curses.refresh ();
  366. StartReportingMouseMoves ();
  367. }
  368. public override void StartReportingMouseMoves()
  369. {
  370. Console.Out.Write ("\x1b[?1003h");
  371. Console.Out.Flush ();
  372. }
  373. public override void StopReportingMouseMoves()
  374. {
  375. Console.Out.Write ("\x1b[?1003l");
  376. Console.Out.Flush ();
  377. }
  378. }
  379. internal static class Platform {
  380. [DllImport ("libc")]
  381. static extern int uname (IntPtr buf);
  382. [DllImport ("libc")]
  383. static extern int killpg (int pgrp, int pid);
  384. static int suspendSignal;
  385. static int GetSuspendSignal ()
  386. {
  387. if (suspendSignal != 0)
  388. return suspendSignal;
  389. IntPtr buf = Marshal.AllocHGlobal (8192);
  390. if (uname (buf) != 0) {
  391. Marshal.FreeHGlobal (buf);
  392. suspendSignal = -1;
  393. return suspendSignal;
  394. }
  395. try {
  396. switch (Marshal.PtrToStringAnsi (buf)) {
  397. case "Darwin":
  398. case "DragonFly":
  399. case "FreeBSD":
  400. case "NetBSD":
  401. case "OpenBSD":
  402. suspendSignal = 18;
  403. break;
  404. case "Linux":
  405. // TODO: should fetch the machine name and
  406. // if it is MIPS return 24
  407. suspendSignal = 20;
  408. break;
  409. case "Solaris":
  410. suspendSignal = 24;
  411. break;
  412. default:
  413. suspendSignal = -1;
  414. break;
  415. }
  416. return suspendSignal;
  417. } finally {
  418. Marshal.FreeHGlobal (buf);
  419. }
  420. }
  421. /// <summary>
  422. /// Suspends the process by sending SIGTSTP to itself
  423. /// </summary>
  424. /// <returns>The suspend.</returns>
  425. static public bool Suspend ()
  426. {
  427. int signal = GetSuspendSignal ();
  428. if (signal == -1)
  429. return false;
  430. killpg (0, signal);
  431. return true;
  432. }
  433. }
  434. }