CursesDriver.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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<MouseEvent> mouseHandler)
  187. {
  188. Curses.timeout (-1);
  189. (mainLoop.Driver as Mono.Terminal.UnixMainLoop).AddWatch (0, Mono.Terminal.UnixMainLoop.Condition.PollIn, x => {
  190. ProcessInput (keyHandler, mouseHandler);
  191. return true;
  192. });
  193. }
  194. Curses.Event oldMouseEvents, reportableMouseEvents;
  195. public override void Init (Action terminalResized)
  196. {
  197. if (window != null)
  198. return;
  199. try {
  200. window = Curses.initscr ();
  201. } catch (Exception e) {
  202. Console.WriteLine ("Curses failed to initialize, the exception is: " + e);
  203. }
  204. Curses.raw ();
  205. Curses.noecho ();
  206. Curses.Window.Standard.keypad (true);
  207. reportableMouseEvents = Curses.mousemask (Curses.Event.AllEvents | Curses.Event.ReportMousePosition, out oldMouseEvents);
  208. TerminalResized = terminalResized;
  209. if (reportableMouseEvents.HasFlag (Curses.Event.ReportMousePosition))
  210. StartReportingMouseMoves ();
  211. HLine = Curses.ACS_HLINE;
  212. VLine = Curses.ACS_VLINE;
  213. Stipple = Curses.ACS_CKBOARD;
  214. Diamond = Curses.ACS_DIAMOND;
  215. ULCorner = Curses.ACS_ULCORNER;
  216. LLCorner = Curses.ACS_LLCORNER;
  217. URCorner = Curses.ACS_URCORNER;
  218. LRCorner = Curses.ACS_LRCORNER;
  219. LeftTee = Curses.ACS_LTEE;
  220. RightTee = Curses.ACS_RTEE;
  221. TopTee = Curses.ACS_TTEE;
  222. BottomTee = Curses.ACS_BTEE;
  223. Colors.Base = new ColorScheme ();
  224. Colors.Dialog = new ColorScheme ();
  225. Colors.Menu = new ColorScheme ();
  226. Colors.Error = new ColorScheme ();
  227. Clip = new Rect (0, 0, Cols, Rows);
  228. if (Curses.HasColors) {
  229. Curses.StartColor ();
  230. Curses.UseDefaultColors ();
  231. Colors.Base.Normal = MakeColor (Curses.COLOR_WHITE, Curses.COLOR_BLUE);
  232. Colors.Base.Focus = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_CYAN);
  233. Colors.Base.HotNormal = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_BLUE);
  234. Colors.Base.HotFocus = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_CYAN);
  235. // Focused,
  236. // Selected, Hot: Yellow on Black
  237. // Selected, text: white on black
  238. // Unselected, hot: yellow on cyan
  239. // unselected, text: same as unfocused
  240. Colors.Menu.HotFocus = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_BLACK);
  241. Colors.Menu.Focus = Curses.A_BOLD | MakeColor (Curses.COLOR_WHITE, Curses.COLOR_BLACK);
  242. Colors.Menu.HotNormal = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_CYAN);
  243. Colors.Menu.Normal = Curses.A_BOLD | MakeColor (Curses.COLOR_WHITE, Curses.COLOR_CYAN);
  244. Colors.Menu.Disabled = MakeColor(Curses.COLOR_WHITE, Curses.COLOR_CYAN);
  245. Colors.Dialog.Normal = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_WHITE);
  246. Colors.Dialog.Focus = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_CYAN);
  247. Colors.Dialog.HotNormal = MakeColor (Curses.COLOR_BLUE, Curses.COLOR_WHITE);
  248. Colors.Dialog.HotFocus = MakeColor (Curses.COLOR_BLUE, Curses.COLOR_CYAN);
  249. Colors.Error.Normal = Curses.A_BOLD | MakeColor (Curses.COLOR_WHITE, Curses.COLOR_RED);
  250. Colors.Error.Focus = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_WHITE);
  251. Colors.Error.HotNormal = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_RED);
  252. Colors.Error.HotFocus = Colors.Error.HotNormal;
  253. } else {
  254. Colors.Base.Normal = Curses.A_NORMAL;
  255. Colors.Base.Focus = Curses.A_REVERSE;
  256. Colors.Base.HotNormal = Curses.A_BOLD;
  257. Colors.Base.HotFocus = Curses.A_BOLD | Curses.A_REVERSE;
  258. Colors.Menu.Normal = Curses.A_REVERSE;
  259. Colors.Menu.Focus = Curses.A_NORMAL;
  260. Colors.Menu.HotNormal = Curses.A_BOLD;
  261. Colors.Menu.HotFocus = Curses.A_NORMAL;
  262. Colors.Dialog.Normal = Curses.A_REVERSE;
  263. Colors.Dialog.Focus = Curses.A_NORMAL;
  264. Colors.Dialog.HotNormal = Curses.A_BOLD;
  265. Colors.Dialog.HotFocus = Curses.A_NORMAL;
  266. Colors.Error.Normal = Curses.A_BOLD;
  267. Colors.Error.Focus = Curses.A_BOLD | Curses.A_REVERSE;
  268. Colors.Error.HotNormal = Curses.A_BOLD | Curses.A_REVERSE;
  269. Colors.Error.HotFocus = Curses.A_REVERSE;
  270. }
  271. Colors.TopLevel = new ColorScheme ();
  272. Colors.TopLevel.Normal = MakeColor (Curses.COLOR_GREEN, Curses.COLOR_BLACK);
  273. Colors.TopLevel.Focus = MakeColor (Curses.COLOR_WHITE, Curses.COLOR_CYAN);
  274. Colors.TopLevel.HotNormal = MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_BLACK);
  275. Colors.TopLevel.HotFocus = MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_CYAN);
  276. }
  277. static int MapColor (Color color)
  278. {
  279. switch (color) {
  280. case Color.Black:
  281. return Curses.COLOR_BLACK;
  282. case Color.Blue:
  283. return Curses.COLOR_BLUE;
  284. case Color.Green:
  285. return Curses.COLOR_GREEN;
  286. case Color.Cyan:
  287. return Curses.COLOR_CYAN;
  288. case Color.Red:
  289. return Curses.COLOR_RED;
  290. case Color.Magenta:
  291. return Curses.COLOR_MAGENTA;
  292. case Color.Brown:
  293. return Curses.COLOR_YELLOW;
  294. case Color.Gray:
  295. return Curses.COLOR_WHITE;
  296. case Color.DarkGray:
  297. return Curses.COLOR_BLACK | Curses.A_BOLD;
  298. case Color.BrightBlue:
  299. return Curses.COLOR_BLUE | Curses.A_BOLD;
  300. case Color.BrightGreen:
  301. return Curses.COLOR_GREEN | Curses.A_BOLD;
  302. case Color.BrighCyan:
  303. return Curses.COLOR_CYAN | Curses.A_BOLD;
  304. case Color.BrightRed:
  305. return Curses.COLOR_RED | Curses.A_BOLD;
  306. case Color.BrightMagenta:
  307. return Curses.COLOR_MAGENTA | Curses.A_BOLD;
  308. case Color.BrightYellow:
  309. return Curses.COLOR_YELLOW | Curses.A_BOLD;
  310. case Color.White:
  311. return Curses.COLOR_WHITE | Curses.A_BOLD;
  312. }
  313. throw new ArgumentException ("Invalid color code");
  314. }
  315. public override Attribute MakeAttribute (Color fore, Color back)
  316. {
  317. var f = MapColor (fore);
  318. return MakeColor ((short)(f & 0xffff), (short)MapColor (back)) | ((f & Curses.A_BOLD) != 0 ? Curses.A_BOLD : 0);
  319. }
  320. public override void Suspend ()
  321. {
  322. if (reportableMouseEvents.HasFlag (Curses.Event.ReportMousePosition))
  323. StopReportingMouseMoves ();
  324. Platform.Suspend ();
  325. Curses.Window.Standard.redrawwin ();
  326. Curses.refresh ();
  327. if (reportableMouseEvents.HasFlag (Curses.Event.ReportMousePosition))
  328. StartReportingMouseMoves ();
  329. }
  330. public override void StartReportingMouseMoves ()
  331. {
  332. Console.Out.Write ("\x1b[?1003h");
  333. Console.Out.Flush ();
  334. }
  335. public override void StopReportingMouseMoves ()
  336. {
  337. Console.Out.Write ("\x1b[?1003l");
  338. Console.Out.Flush ();
  339. }
  340. int lastMouseInterval;
  341. bool mouseGrabbed;
  342. public override void UncookMouse ()
  343. {
  344. if (mouseGrabbed)
  345. return;
  346. lastMouseInterval = Curses.mouseinterval (0);
  347. mouseGrabbed = true;
  348. }
  349. public override void CookMouse ()
  350. {
  351. mouseGrabbed = false;
  352. Curses.mouseinterval (lastMouseInterval);
  353. }
  354. }
  355. internal static class Platform {
  356. [DllImport ("libc")]
  357. static extern int uname (IntPtr buf);
  358. [DllImport ("libc")]
  359. static extern int killpg (int pgrp, int pid);
  360. static int suspendSignal;
  361. static int GetSuspendSignal ()
  362. {
  363. if (suspendSignal != 0)
  364. return suspendSignal;
  365. IntPtr buf = Marshal.AllocHGlobal (8192);
  366. if (uname (buf) != 0) {
  367. Marshal.FreeHGlobal (buf);
  368. suspendSignal = -1;
  369. return suspendSignal;
  370. }
  371. try {
  372. switch (Marshal.PtrToStringAnsi (buf)) {
  373. case "Darwin":
  374. case "DragonFly":
  375. case "FreeBSD":
  376. case "NetBSD":
  377. case "OpenBSD":
  378. suspendSignal = 18;
  379. break;
  380. case "Linux":
  381. // TODO: should fetch the machine name and
  382. // if it is MIPS return 24
  383. suspendSignal = 20;
  384. break;
  385. case "Solaris":
  386. suspendSignal = 24;
  387. break;
  388. default:
  389. suspendSignal = -1;
  390. break;
  391. }
  392. return suspendSignal;
  393. } finally {
  394. Marshal.FreeHGlobal (buf);
  395. }
  396. }
  397. /// <summary>
  398. /// Suspends the process by sending SIGTSTP to itself
  399. /// </summary>
  400. /// <returns>The suspend.</returns>
  401. static public bool Suspend ()
  402. {
  403. int signal = GetSuspendSignal ();
  404. if (signal == -1)
  405. return false;
  406. killpg (0, signal);
  407. return true;
  408. }
  409. }
  410. }