Driver.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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 Mono.Terminal;
  10. using Unix.Terminal;
  11. namespace Terminal {
  12. /// <summary>
  13. /// Basic colors that can be used to set the foreground and background colors in console applications. These can only be
  14. /// </summary>
  15. public enum Color {
  16. Black,
  17. Blue,
  18. Green,
  19. Cyan,
  20. Red,
  21. Magenta,
  22. Brown,
  23. Gray,
  24. DarkGray,
  25. BrightBlue,
  26. BrightGreen,
  27. BrighCyan,
  28. BrightRed,
  29. BrightMagenta,
  30. BrightYellow,
  31. White
  32. }
  33. /// <summary>
  34. /// Attributes are used as elements that contain both a foreground and a background or platform specific features
  35. /// </summary>
  36. /// <remarks>
  37. /// Attributes are needed to map colors to terminal capabilities that might lack colors, on color
  38. /// scenarios, they encode both the foreground and the background color and are used in the ColorScheme
  39. /// class to define color schemes that can be used in your application.
  40. /// </remarks>
  41. public struct Attribute {
  42. internal int value;
  43. public Attribute (int v)
  44. {
  45. value = v;
  46. }
  47. public static implicit operator int (Attribute c) => c.value;
  48. public static implicit operator Attribute (int v) => new Attribute (v);
  49. }
  50. /// <summary>
  51. /// Color scheme definitions
  52. /// </summary>
  53. public class ColorScheme {
  54. public Attribute Normal;
  55. public Attribute Focus;
  56. public Attribute HotNormal;
  57. public Attribute HotFocus;
  58. }
  59. public static class Colors {
  60. public static ColorScheme Base, Dialog, Menu, Error;
  61. }
  62. public enum SpecialChar {
  63. HLine,
  64. }
  65. public abstract class ConsoleDriver {
  66. public abstract int Cols { get; }
  67. public abstract int Rows { get; }
  68. public abstract void Init (Action terminalResized);
  69. public abstract void Move (int col, int row);
  70. public abstract void AddCh (int ch);
  71. public abstract void AddStr (string str);
  72. public abstract void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> target);
  73. public abstract void Refresh ();
  74. public abstract void End ();
  75. public abstract void RedrawTop ();
  76. public abstract void SetAttribute (Attribute c);
  77. // Set Colors from limit sets of colors
  78. public abstract void SetColors (ConsoleColor foreground, ConsoleColor background);
  79. // Advanced uses - set colors to any pre-set pairs, you would need to init_color
  80. // that independently with the R, G, B values.
  81. public abstract void SetColors (short foreColorId, short backgroundColorId);
  82. public abstract void DrawFrame (Rect region, bool fill);
  83. public abstract void AddSpecial (SpecialChar ch);
  84. Rect clip;
  85. public Rect Clip {
  86. get => clip;
  87. set => this.clip = value;
  88. }
  89. }
  90. public class CursesDriver : ConsoleDriver {
  91. Action terminalResized;
  92. public override int Cols => Curses.Cols;
  93. public override int Rows => Curses.Lines;
  94. // Current row, and current col, tracked by Move/AddCh only
  95. int ccol, crow;
  96. bool needMove;
  97. public override void Move (int col, int row)
  98. {
  99. ccol = col;
  100. crow = row;
  101. if (Clip.Contains (col, row)) {
  102. Curses.move (row, col);
  103. needMove = false;
  104. } else {
  105. Curses.move (Clip.Y, Clip.X);
  106. needMove = true;
  107. }
  108. }
  109. static bool sync;
  110. public override void AddCh (int ch)
  111. {
  112. if (Clip.Contains (ccol, crow)) {
  113. if (needMove) {
  114. Curses.move (crow, ccol);
  115. needMove = false;
  116. }
  117. Curses.addch (ch);
  118. } else
  119. needMove = true;
  120. if (sync)
  121. Application.Driver.Refresh ();
  122. ccol++;
  123. }
  124. public override void AddSpecial (SpecialChar ch)
  125. {
  126. switch (ch) {
  127. case SpecialChar.HLine:
  128. AddCh (Curses.ACS_HLINE);
  129. break;
  130. }
  131. }
  132. public override void AddStr (string str)
  133. {
  134. // TODO; optimize this to determine if the str fits in the clip region, and if so, use Curses.addstr directly
  135. foreach (var c in str)
  136. AddCh ((int)c);
  137. }
  138. public override void Refresh () => Curses.refresh ();
  139. public override void End () => Curses.endwin ();
  140. public override void RedrawTop () => window.redrawwin ();
  141. public override void SetAttribute (Attribute c) => Curses.attrset (c.value);
  142. public Curses.Window window;
  143. static short last_color_pair = 16;
  144. static Attribute MakeColor (short f, short b)
  145. {
  146. Curses.InitColorPair (++last_color_pair, f, b);
  147. return new Attribute () { value = Curses.ColorPair (last_color_pair) };
  148. }
  149. int [,] colorPairs = new int [16, 16];
  150. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  151. {
  152. int f = (short)foreground;
  153. int b = (short)background;
  154. var v = colorPairs [f, b];
  155. if ((v & 0x10000) == 0) {
  156. b = b & 0x7;
  157. bool bold = (f & 0x8) != 0;
  158. f = f & 0x7;
  159. v = MakeColor ((short)f, (short)b) | (bold ? Curses.A_BOLD : 0);
  160. colorPairs [(int)foreground, (int)background] = v | 0x1000;
  161. }
  162. SetAttribute (v & 0xffff);
  163. }
  164. Dictionary<int, int> rawPairs = new Dictionary<int, int> ();
  165. public override void SetColors (short foreColorId, short backgroundColorId)
  166. {
  167. int key = (((ushort)foreColorId << 16)) | (ushort)backgroundColorId;
  168. if (!rawPairs.TryGetValue (key, out var v)) {
  169. v = MakeColor (foreColorId, backgroundColorId);
  170. rawPairs [key] = v;
  171. }
  172. SetAttribute (v);
  173. }
  174. static Key MapCursesKey (int cursesKey)
  175. {
  176. switch (cursesKey) {
  177. case Curses.KeyF1: return Key.F1;
  178. case Curses.KeyF2: return Key.F2;
  179. case Curses.KeyF3: return Key.F3;
  180. case Curses.KeyF4: return Key.F4;
  181. case Curses.KeyF5: return Key.F5;
  182. case Curses.KeyF6: return Key.F6;
  183. case Curses.KeyF7: return Key.F7;
  184. case Curses.KeyF8: return Key.F8;
  185. case Curses.KeyF9: return Key.F9;
  186. case Curses.KeyF10: return Key.F10;
  187. case Curses.KeyUp: return Key.CursorUp;
  188. case Curses.KeyDown: return Key.CursorDown;
  189. case Curses.KeyLeft: return Key.CursorLeft;
  190. case Curses.KeyRight: return Key.CursorRight;
  191. case Curses.KeyHome: return Key.Home;
  192. case Curses.KeyEnd: return Key.End;
  193. case Curses.KeyNPage: return Key.PageDown;
  194. case Curses.KeyPPage: return Key.PageUp;
  195. case Curses.KeyDeleteChar: return Key.DeleteChar;
  196. case Curses.KeyInsertChar: return Key.InsertChar;
  197. case Curses.KeyBackTab: return Key.BackTab;
  198. default: return Key.Unknown;
  199. }
  200. }
  201. void ProcessInput (Action<KeyEvent> keyHandler)
  202. {
  203. int wch;
  204. var code = Curses.get_wch (out wch);
  205. if (code == Curses.KEY_CODE_YES) {
  206. if (wch == Curses.KeyResize) {
  207. if (Curses.CheckWinChange ()) {
  208. terminalResized ();
  209. return;
  210. }
  211. }
  212. if (code == Curses.KeyMouse) {
  213. // TODO
  214. // Curses.MouseEvent ev;
  215. // Curses.getmouse (out ev);
  216. // handler.HandleMouse ();
  217. return;
  218. }
  219. keyHandler (new KeyEvent (MapCursesKey (wch)));
  220. return;
  221. }
  222. // Special handling for ESC, we want to try to catch ESC+letter to simulate alt-letter as well as Alt-Fkey
  223. if (wch == 27) {
  224. Curses.timeout (100);
  225. code = Curses.get_wch (out wch);
  226. if (code == Curses.KEY_CODE_YES)
  227. keyHandler (new KeyEvent (Key.AltMask | MapCursesKey (wch)));
  228. if (code == 0) {
  229. KeyEvent key;
  230. // The ESC-number handling, debatable.
  231. if (wch >= '1' && wch <= '9')
  232. key = new KeyEvent ((Key)((int)Key.F1 + (wch - '0' - 1)));
  233. else if (wch == '0')
  234. key = new KeyEvent (Key.F10);
  235. else if (wch == 27)
  236. key = new KeyEvent ((Key)wch);
  237. else
  238. key = new KeyEvent (Key.AltMask | (Key)wch);
  239. keyHandler (key);
  240. } else
  241. keyHandler (new KeyEvent (Key.Esc));
  242. } else
  243. keyHandler (new KeyEvent ((Key)wch));
  244. }
  245. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler)
  246. {
  247. Curses.timeout (-1);
  248. mainLoop.AddWatch (0, Mono.Terminal.MainLoop.Condition.PollIn, x => {
  249. ProcessInput (keyHandler);
  250. return true;
  251. });
  252. }
  253. public override void DrawFrame (Rect region, bool fill)
  254. {
  255. int width = region.Width;
  256. int height = region.Height;
  257. int b;
  258. Move (region.X, region.Y);
  259. AddCh (Curses.ACS_ULCORNER);
  260. for (b = 0; b < width - 2; b++)
  261. AddCh (Curses.ACS_HLINE);
  262. AddCh (Curses.ACS_URCORNER);
  263. for (b = 1; b < height - 1; b++) {
  264. Move (region.X, region.Y + b);
  265. AddCh (Curses.ACS_VLINE);
  266. if (fill) {
  267. for (int x = 1; x < width - 1; x++)
  268. AddCh (' ');
  269. } else
  270. Move (region.X + width - 1, region.Y + b);
  271. AddCh (Curses.ACS_VLINE);
  272. }
  273. Move (region.X, region.Y + height - 1);
  274. AddCh (Curses.ACS_LLCORNER);
  275. for (b = 0; b < width - 2; b++)
  276. AddCh (Curses.ACS_HLINE);
  277. AddCh (Curses.ACS_LRCORNER);
  278. }
  279. public override void Init (Action terminalResized)
  280. {
  281. if (window != null)
  282. return;
  283. try {
  284. window = Curses.initscr ();
  285. } catch (Exception e) {
  286. Console.WriteLine ("Curses failed to initialize, the exception is: " + e);
  287. }
  288. Curses.raw ();
  289. Curses.noecho ();
  290. Curses.Window.Standard.keypad (true);
  291. this.terminalResized = terminalResized;
  292. Colors.Base = new ColorScheme ();
  293. Colors.Dialog = new ColorScheme ();
  294. Colors.Menu = new ColorScheme ();
  295. Colors.Error = new ColorScheme ();
  296. Clip = new Rect (0, 0, Cols, Rows);
  297. if (Curses.HasColors) {
  298. Curses.StartColor ();
  299. Curses.UseDefaultColors ();
  300. Colors.Base.Normal = MakeColor (Curses.COLOR_WHITE, Curses.COLOR_BLUE);
  301. Colors.Base.Focus = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_CYAN);
  302. Colors.Base.HotNormal = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_BLUE);
  303. Colors.Base.HotFocus = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_CYAN);
  304. // Focused,
  305. // Selected, Hot: Yellow on Black
  306. // Selected, text: white on black
  307. // Unselected, hot: yellow on cyan
  308. // unselected, text: same as unfocused
  309. Colors.Menu.HotFocus = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_BLACK);
  310. Colors.Menu.Focus = Curses.A_BOLD | MakeColor (Curses.COLOR_WHITE, Curses.COLOR_BLACK);
  311. Colors.Menu.HotNormal = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_CYAN);
  312. Colors.Menu.Normal = Curses.A_BOLD | MakeColor (Curses.COLOR_WHITE, Curses.COLOR_CYAN);
  313. Colors.Dialog.Normal = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_WHITE);
  314. Colors.Dialog.Focus = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_CYAN);
  315. Colors.Dialog.HotNormal = MakeColor (Curses.COLOR_BLUE, Curses.COLOR_WHITE);
  316. Colors.Dialog.HotFocus = MakeColor (Curses.COLOR_BLUE, Curses.COLOR_CYAN);
  317. Colors.Error.Normal = Curses.A_BOLD | MakeColor (Curses.COLOR_WHITE, Curses.COLOR_RED);
  318. Colors.Error.Focus = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_WHITE);
  319. Colors.Error.HotNormal = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_RED);
  320. Colors.Error.HotFocus = Colors.Error.HotNormal;
  321. } else {
  322. Colors.Base.Normal = Curses.A_NORMAL;
  323. Colors.Base.Focus = Curses.A_REVERSE;
  324. Colors.Base.HotNormal = Curses.A_BOLD;
  325. Colors.Base.HotFocus = Curses.A_BOLD | Curses.A_REVERSE;
  326. Colors.Menu.Normal = Curses.A_REVERSE;
  327. Colors.Menu.Focus = Curses.A_NORMAL;
  328. Colors.Menu.HotNormal = Curses.A_BOLD;
  329. Colors.Menu.HotFocus = Curses.A_NORMAL;
  330. Colors.Dialog.Normal = Curses.A_REVERSE;
  331. Colors.Dialog.Focus = Curses.A_NORMAL;
  332. Colors.Dialog.HotNormal = Curses.A_BOLD;
  333. Colors.Dialog.HotFocus = Curses.A_NORMAL;
  334. Colors.Error.Normal = Curses.A_BOLD;
  335. Colors.Error.Focus = Curses.A_BOLD | Curses.A_REVERSE;
  336. Colors.Error.HotNormal = Curses.A_BOLD | Curses.A_REVERSE;
  337. Colors.Error.HotFocus = Curses.A_REVERSE;
  338. }
  339. }
  340. }
  341. }