CursesDriver.cs 14 KB

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