CursesDriver.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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. internal 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. static Attribute MakeColor (short f, short b)
  65. {
  66. Curses.InitColorPair (++last_color_pair, f, b);
  67. return new Attribute () { value = Curses.ColorPair (last_color_pair) };
  68. }
  69. int [,] colorPairs = new int [16, 16];
  70. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  71. {
  72. int f = (short)foreground;
  73. int b = (short)background;
  74. var v = colorPairs [f, b];
  75. if ((v & 0x10000) == 0) {
  76. b = b & 0x7;
  77. bool bold = (f & 0x8) != 0;
  78. f = f & 0x7;
  79. v = MakeColor ((short)f, (short)b) | (bold ? Curses.A_BOLD : 0);
  80. colorPairs [(int)foreground, (int)background] = v | 0x1000;
  81. }
  82. SetAttribute (v & 0xffff);
  83. }
  84. Dictionary<int, int> rawPairs = new Dictionary<int, int> ();
  85. public override void SetColors (short foreColorId, short backgroundColorId)
  86. {
  87. int key = (((ushort)foreColorId << 16)) | (ushort)backgroundColorId;
  88. if (!rawPairs.TryGetValue (key, out var v)) {
  89. v = MakeColor (foreColorId, backgroundColorId);
  90. rawPairs [key] = v;
  91. }
  92. SetAttribute (v);
  93. }
  94. static Key MapCursesKey (int cursesKey)
  95. {
  96. switch (cursesKey) {
  97. case Curses.KeyF1: return Key.F1;
  98. case Curses.KeyF2: return Key.F2;
  99. case Curses.KeyF3: return Key.F3;
  100. case Curses.KeyF4: return Key.F4;
  101. case Curses.KeyF5: return Key.F5;
  102. case Curses.KeyF6: return Key.F6;
  103. case Curses.KeyF7: return Key.F7;
  104. case Curses.KeyF8: return Key.F8;
  105. case Curses.KeyF9: return Key.F9;
  106. case Curses.KeyF10: return Key.F10;
  107. case Curses.KeyUp: return Key.CursorUp;
  108. case Curses.KeyDown: return Key.CursorDown;
  109. case Curses.KeyLeft: return Key.CursorLeft;
  110. case Curses.KeyRight: return Key.CursorRight;
  111. case Curses.KeyHome: return Key.Home;
  112. case Curses.KeyEnd: return Key.End;
  113. case Curses.KeyNPage: return Key.PageDown;
  114. case Curses.KeyPPage: return Key.PageUp;
  115. case Curses.KeyDeleteChar: return Key.DeleteChar;
  116. case Curses.KeyInsertChar: return Key.InsertChar;
  117. case Curses.KeyBackTab: return Key.BackTab;
  118. case Curses.KeyBackspace: return Key.Backspace;
  119. default: return Key.Unknown;
  120. }
  121. }
  122. static MouseEvent ToDriverMouse (Curses.MouseEvent cev)
  123. {
  124. return new MouseEvent () {
  125. X = cev.X,
  126. Y = cev.Y,
  127. Flags = (MouseFlags)cev.ButtonState
  128. };
  129. }
  130. void ProcessInput (Action<KeyEvent> keyHandler, Action<MouseEvent> mouseHandler)
  131. {
  132. int wch;
  133. var code = Curses.get_wch (out wch);
  134. if (code == Curses.ERR)
  135. return;
  136. if (code == Curses.KEY_CODE_YES) {
  137. if (wch == Curses.KeyResize) {
  138. if (Curses.CheckWinChange ()) {
  139. terminalResized ();
  140. return;
  141. }
  142. }
  143. if (wch == Curses.KeyMouse) {
  144. Curses.MouseEvent ev;
  145. Curses.getmouse (out ev);
  146. mouseHandler (ToDriverMouse (ev));
  147. return;
  148. }
  149. keyHandler (new KeyEvent (MapCursesKey (wch)));
  150. return;
  151. }
  152. // Special handling for ESC, we want to try to catch ESC+letter to simulate alt-letter as well as Alt-Fkey
  153. if (wch == 27) {
  154. Curses.timeout (200);
  155. code = Curses.get_wch (out wch);
  156. if (code == Curses.KEY_CODE_YES)
  157. keyHandler (new KeyEvent (Key.AltMask | MapCursesKey (wch)));
  158. if (code == 0) {
  159. KeyEvent key;
  160. // The ESC-number handling, debatable.
  161. if (wch >= '1' && wch <= '9')
  162. key = new KeyEvent ((Key)((int)Key.F1 + (wch - '0' - 1)));
  163. else if (wch == '0')
  164. key = new KeyEvent (Key.F10);
  165. else if (wch == 27)
  166. key = new KeyEvent ((Key)wch);
  167. else
  168. key = new KeyEvent (Key.AltMask | (Key)wch);
  169. keyHandler (key);
  170. } else
  171. keyHandler (new KeyEvent (Key.Esc));
  172. } else
  173. keyHandler (new KeyEvent ((Key)wch));
  174. }
  175. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<MouseEvent> mouseHandler)
  176. {
  177. Curses.timeout (-1);
  178. (mainLoop.Driver as Mono.Terminal.UnixMainLoop).AddWatch (0, Mono.Terminal.UnixMainLoop.Condition.PollIn, x => {
  179. ProcessInput (keyHandler, mouseHandler);
  180. return true;
  181. });
  182. }
  183. Curses.Event oldMouseEvents, reportableMouseEvents;
  184. public override void Init (Action terminalResized)
  185. {
  186. if (window != null)
  187. return;
  188. try {
  189. window = Curses.initscr ();
  190. } catch (Exception e) {
  191. Console.WriteLine ("Curses failed to initialize, the exception is: " + e);
  192. }
  193. Curses.raw ();
  194. Curses.noecho ();
  195. Curses.Window.Standard.keypad (true);
  196. reportableMouseEvents = Curses.mousemask (Curses.Event.AllEvents | Curses.Event.ReportMousePosition, out oldMouseEvents);
  197. this.terminalResized = terminalResized;
  198. StartReportingMouseMoves ();
  199. HLine = Curses.ACS_HLINE;
  200. VLine = Curses.ACS_VLINE;
  201. Stipple = Curses.ACS_CKBOARD;
  202. Diamond = Curses.ACS_DIAMOND;
  203. ULCorner = Curses.ACS_ULCORNER;
  204. LLCorner = Curses.ACS_LLCORNER;
  205. URCorner = Curses.ACS_URCORNER;
  206. LRCorner = Curses.ACS_LRCORNER;
  207. LeftTee = Curses.ACS_LTEE;
  208. RightTee = Curses.ACS_RTEE;
  209. TopTee = Curses.ACS_TTEE;
  210. BottomTee = Curses.ACS_BTEE;
  211. Colors.Base = new ColorScheme ();
  212. Colors.Dialog = new ColorScheme ();
  213. Colors.Menu = new ColorScheme ();
  214. Colors.Error = new ColorScheme ();
  215. Clip = new Rect (0, 0, Cols, Rows);
  216. if (Curses.HasColors) {
  217. Curses.StartColor ();
  218. Curses.UseDefaultColors ();
  219. Colors.Base.Normal = MakeColor (Curses.COLOR_WHITE, Curses.COLOR_BLUE);
  220. Colors.Base.Focus = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_CYAN);
  221. Colors.Base.HotNormal = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_BLUE);
  222. Colors.Base.HotFocus = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_CYAN);
  223. // Focused,
  224. // Selected, Hot: Yellow on Black
  225. // Selected, text: white on black
  226. // Unselected, hot: yellow on cyan
  227. // unselected, text: same as unfocused
  228. Colors.Menu.HotFocus = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_BLACK);
  229. Colors.Menu.Focus = Curses.A_BOLD | MakeColor (Curses.COLOR_WHITE, Curses.COLOR_BLACK);
  230. Colors.Menu.HotNormal = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_CYAN);
  231. Colors.Menu.Normal = Curses.A_BOLD | MakeColor (Curses.COLOR_WHITE, Curses.COLOR_CYAN);
  232. Colors.Dialog.Normal = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_WHITE);
  233. Colors.Dialog.Focus = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_CYAN);
  234. Colors.Dialog.HotNormal = MakeColor (Curses.COLOR_BLUE, Curses.COLOR_WHITE);
  235. Colors.Dialog.HotFocus = MakeColor (Curses.COLOR_BLUE, Curses.COLOR_CYAN);
  236. Colors.Error.Normal = Curses.A_BOLD | MakeColor (Curses.COLOR_WHITE, Curses.COLOR_RED);
  237. Colors.Error.Focus = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_WHITE);
  238. Colors.Error.HotNormal = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_RED);
  239. Colors.Error.HotFocus = Colors.Error.HotNormal;
  240. } else {
  241. Colors.Base.Normal = Curses.A_NORMAL;
  242. Colors.Base.Focus = Curses.A_REVERSE;
  243. Colors.Base.HotNormal = Curses.A_BOLD;
  244. Colors.Base.HotFocus = Curses.A_BOLD | Curses.A_REVERSE;
  245. Colors.Menu.Normal = Curses.A_REVERSE;
  246. Colors.Menu.Focus = Curses.A_NORMAL;
  247. Colors.Menu.HotNormal = Curses.A_BOLD;
  248. Colors.Menu.HotFocus = Curses.A_NORMAL;
  249. Colors.Dialog.Normal = Curses.A_REVERSE;
  250. Colors.Dialog.Focus = Curses.A_NORMAL;
  251. Colors.Dialog.HotNormal = Curses.A_BOLD;
  252. Colors.Dialog.HotFocus = Curses.A_NORMAL;
  253. Colors.Error.Normal = Curses.A_BOLD;
  254. Colors.Error.Focus = Curses.A_BOLD | Curses.A_REVERSE;
  255. Colors.Error.HotNormal = Curses.A_BOLD | Curses.A_REVERSE;
  256. Colors.Error.HotFocus = Curses.A_REVERSE;
  257. }
  258. }
  259. public override void Suspend ()
  260. {
  261. StopReportingMouseMoves ();
  262. Platform.Suspend ();
  263. Curses.Window.Standard.redrawwin ();
  264. Curses.refresh ();
  265. StartReportingMouseMoves ();
  266. }
  267. public override void StartReportingMouseMoves ()
  268. {
  269. Console.Out.Write ("\x1b[?1003h");
  270. Console.Out.Flush ();
  271. }
  272. public override void StopReportingMouseMoves ()
  273. {
  274. Console.Out.Write ("\x1b[?1003l");
  275. Console.Out.Flush ();
  276. }
  277. int lastMouseInterval;
  278. bool mouseGrabbed;
  279. public override void UncookMouse ()
  280. {
  281. if (mouseGrabbed)
  282. return;
  283. lastMouseInterval = Curses.mouseinterval (0);
  284. mouseGrabbed = true;
  285. }
  286. public override void CookMouse ()
  287. {
  288. mouseGrabbed = false;
  289. Curses.mouseinterval (lastMouseInterval);
  290. }
  291. }
  292. internal static class Platform {
  293. [DllImport ("libc")]
  294. static extern int uname (IntPtr buf);
  295. [DllImport ("libc")]
  296. static extern int killpg (int pgrp, int pid);
  297. static int suspendSignal;
  298. static int GetSuspendSignal ()
  299. {
  300. if (suspendSignal != 0)
  301. return suspendSignal;
  302. IntPtr buf = Marshal.AllocHGlobal (8192);
  303. if (uname (buf) != 0) {
  304. Marshal.FreeHGlobal (buf);
  305. suspendSignal = -1;
  306. return suspendSignal;
  307. }
  308. try {
  309. switch (Marshal.PtrToStringAnsi (buf)) {
  310. case "Darwin":
  311. case "DragonFly":
  312. case "FreeBSD":
  313. case "NetBSD":
  314. case "OpenBSD":
  315. suspendSignal = 18;
  316. break;
  317. case "Linux":
  318. // TODO: should fetch the machine name and
  319. // if it is MIPS return 24
  320. suspendSignal = 20;
  321. break;
  322. case "Solaris":
  323. suspendSignal = 24;
  324. break;
  325. default:
  326. suspendSignal = -1;
  327. break;
  328. }
  329. return suspendSignal;
  330. } finally {
  331. Marshal.FreeHGlobal (buf);
  332. }
  333. }
  334. /// <summary>
  335. /// Suspends the process by sending SIGTSTP to itself
  336. /// </summary>
  337. /// <returns>The suspend.</returns>
  338. static public bool Suspend ()
  339. {
  340. int signal = GetSuspendSignal ();
  341. if (signal == -1)
  342. return false;
  343. killpg (0, signal);
  344. return true;
  345. }
  346. }
  347. }