CursesDriver.cs 13 KB

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