CursesDriver.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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. public override int Cols => Curses.Cols;
  19. public override int Rows => Curses.Lines;
  20. // Current row, and current col, tracked by Move/AddRune only
  21. int ccol, crow;
  22. bool needMove;
  23. public override void Move (int col, int row)
  24. {
  25. ccol = col;
  26. crow = row;
  27. if (Clip.Contains (col, row)) {
  28. Curses.move (row, col);
  29. needMove = false;
  30. } else {
  31. Curses.move (Clip.Y, Clip.X);
  32. needMove = true;
  33. }
  34. }
  35. static bool sync;
  36. public override void AddRune (Rune rune)
  37. {
  38. if (Clip.Contains (ccol, crow)) {
  39. if (needMove) {
  40. Curses.move (crow, ccol);
  41. needMove = false;
  42. }
  43. Curses.addch ((int)(uint)rune);
  44. } else
  45. needMove = true;
  46. if (sync)
  47. Application.Driver.Refresh ();
  48. ccol++;
  49. }
  50. public override void AddStr (ustring str)
  51. {
  52. // TODO; optimize this to determine if the str fits in the clip region, and if so, use Curses.addstr directly
  53. foreach (var rune in str)
  54. AddRune (rune);
  55. }
  56. public override void Refresh () => Curses.refresh ();
  57. public override void UpdateCursor () => Curses.refresh ();
  58. public override void End () => Curses.endwin ();
  59. public override void UpdateScreen () => window.redrawwin ();
  60. public override void SetAttribute (Attribute c) => Curses.attrset (c.value);
  61. public Curses.Window window;
  62. static short last_color_pair = 16;
  63. /// <summary>
  64. /// Creates a curses color from the provided foreground and background colors
  65. /// </summary>
  66. /// <param name="foreground">Contains the curses attributes for the foreground (color, plus any attributes)</param>
  67. /// <param name="background">Contains the curses attributes for the background (color, plus any attributes)</param>
  68. /// <returns></returns>
  69. public static Attribute MakeColor (short foreground, short background)
  70. {
  71. Curses.InitColorPair (++last_color_pair, foreground, background);
  72. return new Attribute () { value = Curses.ColorPair (last_color_pair) };
  73. }
  74. int [,] colorPairs = new int [16, 16];
  75. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  76. {
  77. int f = (short)foreground;
  78. int b = (short)background;
  79. var v = colorPairs [f, b];
  80. if ((v & 0x10000) == 0) {
  81. b = b & 0x7;
  82. bool bold = (f & 0x8) != 0;
  83. f = f & 0x7;
  84. v = MakeColor ((short)f, (short)b) | (bold ? Curses.A_BOLD : 0);
  85. colorPairs [(int)foreground, (int)background] = v | 0x1000;
  86. }
  87. SetAttribute (v & 0xffff);
  88. }
  89. Dictionary<int, int> rawPairs = new Dictionary<int, int> ();
  90. public override void SetColors (short foreColorId, short backgroundColorId)
  91. {
  92. int key = (((ushort)foreColorId << 16)) | (ushort)backgroundColorId;
  93. if (!rawPairs.TryGetValue (key, out var v)) {
  94. v = MakeColor (foreColorId, backgroundColorId);
  95. rawPairs [key] = v;
  96. }
  97. SetAttribute (v);
  98. }
  99. static Key MapCursesKey (int cursesKey)
  100. {
  101. switch (cursesKey) {
  102. case Curses.KeyF1: return Key.F1;
  103. case Curses.KeyF2: return Key.F2;
  104. case Curses.KeyF3: return Key.F3;
  105. case Curses.KeyF4: return Key.F4;
  106. case Curses.KeyF5: return Key.F5;
  107. case Curses.KeyF6: return Key.F6;
  108. case Curses.KeyF7: return Key.F7;
  109. case Curses.KeyF8: return Key.F8;
  110. case Curses.KeyF9: return Key.F9;
  111. case Curses.KeyF10: return Key.F10;
  112. case Curses.KeyUp: return Key.CursorUp;
  113. case Curses.KeyDown: return Key.CursorDown;
  114. case Curses.KeyLeft: return Key.CursorLeft;
  115. case Curses.KeyRight: return Key.CursorRight;
  116. case Curses.KeyHome: return Key.Home;
  117. case Curses.KeyEnd: return Key.End;
  118. case Curses.KeyNPage: return Key.PageDown;
  119. case Curses.KeyPPage: return Key.PageUp;
  120. case Curses.KeyDeleteChar: return Key.DeleteChar;
  121. case Curses.KeyInsertChar: return Key.InsertChar;
  122. case Curses.KeyBackTab: return Key.BackTab;
  123. case Curses.KeyBackspace: return Key.Backspace;
  124. default: return Key.Unknown;
  125. }
  126. }
  127. static MouseEvent ToDriverMouse (Curses.MouseEvent cev)
  128. {
  129. return new MouseEvent () {
  130. X = cev.X,
  131. Y = cev.Y,
  132. Flags = (MouseFlags)cev.ButtonState
  133. };
  134. }
  135. void ProcessInput (Action<KeyEvent> keyHandler, Action<MouseEvent> mouseHandler)
  136. {
  137. int wch;
  138. var code = Curses.get_wch (out wch);
  139. if (code == Curses.ERR)
  140. return;
  141. if (code == Curses.KEY_CODE_YES) {
  142. if (wch == Curses.KeyResize) {
  143. if (Curses.CheckWinChange ()) {
  144. TerminalResized?.Invoke ();
  145. return;
  146. }
  147. }
  148. if (wch == Curses.KeyMouse) {
  149. Curses.MouseEvent ev;
  150. Curses.getmouse (out ev);
  151. mouseHandler (ToDriverMouse (ev));
  152. return;
  153. }
  154. keyHandler (new KeyEvent (MapCursesKey (wch)));
  155. return;
  156. }
  157. // Special handling for ESC, we want to try to catch ESC+letter to simulate alt-letter as well as Alt-Fkey
  158. if (wch == 27) {
  159. Curses.timeout (200);
  160. code = Curses.get_wch (out wch);
  161. if (code == Curses.KEY_CODE_YES)
  162. keyHandler (new KeyEvent (Key.AltMask | MapCursesKey (wch)));
  163. if (code == 0) {
  164. KeyEvent key;
  165. // The ESC-number handling, debatable.
  166. if (wch >= '1' && wch <= '9')
  167. key = new KeyEvent ((Key)((int)Key.F1 + (wch - '0' - 1)));
  168. else if (wch == '0')
  169. key = new KeyEvent (Key.F10);
  170. else if (wch == 27)
  171. key = new KeyEvent ((Key)wch);
  172. else
  173. key = new KeyEvent (Key.AltMask | (Key)wch);
  174. keyHandler (key);
  175. } else
  176. keyHandler (new KeyEvent (Key.Esc));
  177. } else
  178. keyHandler (new KeyEvent ((Key)wch));
  179. }
  180. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<MouseEvent> mouseHandler)
  181. {
  182. Curses.timeout (-1);
  183. (mainLoop.Driver as Mono.Terminal.UnixMainLoop).AddWatch (0, Mono.Terminal.UnixMainLoop.Condition.PollIn, x => {
  184. ProcessInput (keyHandler, mouseHandler);
  185. return true;
  186. });
  187. }
  188. Curses.Event oldMouseEvents, reportableMouseEvents;
  189. public override void Init (Action terminalResized)
  190. {
  191. if (window != null)
  192. return;
  193. try {
  194. window = Curses.initscr ();
  195. } catch (Exception e) {
  196. Console.WriteLine ("Curses failed to initialize, the exception is: " + e);
  197. }
  198. Curses.raw ();
  199. Curses.noecho ();
  200. Curses.Window.Standard.keypad (true);
  201. reportableMouseEvents = Curses.mousemask (Curses.Event.AllEvents | Curses.Event.ReportMousePosition, out oldMouseEvents);
  202. TerminalResized = terminalResized;
  203. if (reportableMouseEvents.HasFlag (Curses.Event.ReportMousePosition))
  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. if (reportableMouseEvents.HasFlag (Curses.Event.ReportMousePosition))
  311. StopReportingMouseMoves ();
  312. Platform.Suspend ();
  313. Curses.Window.Standard.redrawwin ();
  314. Curses.refresh ();
  315. if (reportableMouseEvents.HasFlag (Curses.Event.ReportMousePosition))
  316. StartReportingMouseMoves ();
  317. }
  318. public override void StartReportingMouseMoves ()
  319. {
  320. Console.Out.Write ("\x1b[?1003h");
  321. Console.Out.Flush ();
  322. }
  323. public override void StopReportingMouseMoves ()
  324. {
  325. Console.Out.Write ("\x1b[?1003l");
  326. Console.Out.Flush ();
  327. }
  328. int lastMouseInterval;
  329. bool mouseGrabbed;
  330. public override void UncookMouse ()
  331. {
  332. if (mouseGrabbed)
  333. return;
  334. lastMouseInterval = Curses.mouseinterval (0);
  335. mouseGrabbed = true;
  336. }
  337. public override void CookMouse ()
  338. {
  339. mouseGrabbed = false;
  340. Curses.mouseinterval (lastMouseInterval);
  341. }
  342. }
  343. internal static class Platform {
  344. [DllImport ("libc")]
  345. static extern int uname (IntPtr buf);
  346. [DllImport ("libc")]
  347. static extern int killpg (int pgrp, int pid);
  348. static int suspendSignal;
  349. static int GetSuspendSignal ()
  350. {
  351. if (suspendSignal != 0)
  352. return suspendSignal;
  353. IntPtr buf = Marshal.AllocHGlobal (8192);
  354. if (uname (buf) != 0) {
  355. Marshal.FreeHGlobal (buf);
  356. suspendSignal = -1;
  357. return suspendSignal;
  358. }
  359. try {
  360. switch (Marshal.PtrToStringAnsi (buf)) {
  361. case "Darwin":
  362. case "DragonFly":
  363. case "FreeBSD":
  364. case "NetBSD":
  365. case "OpenBSD":
  366. suspendSignal = 18;
  367. break;
  368. case "Linux":
  369. // TODO: should fetch the machine name and
  370. // if it is MIPS return 24
  371. suspendSignal = 20;
  372. break;
  373. case "Solaris":
  374. suspendSignal = 24;
  375. break;
  376. default:
  377. suspendSignal = -1;
  378. break;
  379. }
  380. return suspendSignal;
  381. } finally {
  382. Marshal.FreeHGlobal (buf);
  383. }
  384. }
  385. /// <summary>
  386. /// Suspends the process by sending SIGTSTP to itself
  387. /// </summary>
  388. /// <returns>The suspend.</returns>
  389. static public bool Suspend ()
  390. {
  391. int signal = GetSuspendSignal ();
  392. if (signal == -1)
  393. return false;
  394. killpg (0, signal);
  395. return true;
  396. }
  397. }
  398. }