CursesDriver.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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. case Curses.ShiftKeyUp: return Key.CursorUp | Key.ShiftMask;
  131. case Curses.ShiftKeyDown: return Key.CursorDown | Key.ShiftMask;
  132. case Curses.ShiftKeyLeft: return Key.CursorLeft | Key.ShiftMask;
  133. case Curses.ShiftKeyRight: return Key.CursorRight | Key.ShiftMask;
  134. case Curses.ShiftKeyHome: return Key.Home | Key.ShiftMask;
  135. case Curses.ShiftKeyEnd: return Key.End | Key.ShiftMask;
  136. case Curses.ShiftKeyNPage: return Key.PageDown | Key.ShiftMask;
  137. case Curses.ShiftKeyPPage: return Key.PageUp | Key.ShiftMask;
  138. case Curses.AltKeyUp: return Key.CursorUp | Key.AltMask;
  139. case Curses.AltKeyDown: return Key.CursorDown | Key.AltMask;
  140. case Curses.AltKeyLeft: return Key.CursorLeft | Key.AltMask;
  141. case Curses.AltKeyRight: return Key.CursorRight | Key.AltMask;
  142. case Curses.AltKeyHome: return Key.Home | Key.AltMask;
  143. case Curses.AltKeyEnd: return Key.End | Key.AltMask;
  144. case Curses.AltKeyNPage: return Key.PageDown | Key.AltMask;
  145. case Curses.AltKeyPPage: return Key.PageUp | Key.AltMask;
  146. case Curses.CtrlKeyUp: return Key.CursorUp | Key.CtrlMask;
  147. case Curses.CtrlKeyDown: return Key.CursorDown | Key.CtrlMask;
  148. case Curses.CtrlKeyLeft: return Key.CursorLeft | Key.CtrlMask;
  149. case Curses.CtrlKeyRight: return Key.CursorRight | Key.CtrlMask;
  150. case Curses.CtrlKeyHome: return Key.Home | Key.CtrlMask;
  151. case Curses.CtrlKeyEnd: return Key.End | Key.CtrlMask;
  152. case Curses.CtrlKeyNPage: return Key.PageDown | Key.CtrlMask;
  153. case Curses.CtrlKeyPPage: return Key.PageUp | Key.CtrlMask;
  154. case Curses.ShiftCtrlKeyUp: return Key.CursorUp | Key.ShiftMask | Key.CtrlMask;
  155. case Curses.ShiftCtrlKeyDown: return Key.CursorDown | Key.ShiftMask | Key.CtrlMask;
  156. case Curses.ShiftCtrlKeyLeft: return Key.CursorLeft | Key.ShiftMask | Key.CtrlMask;
  157. case Curses.ShiftCtrlKeyRight: return Key.CursorRight | Key.ShiftMask | Key.CtrlMask;
  158. case Curses.ShiftCtrlKeyHome: return Key.Home | Key.ShiftMask | Key.CtrlMask;
  159. case Curses.ShiftCtrlKeyEnd: return Key.End | Key.ShiftMask | Key.CtrlMask;
  160. case Curses.ShiftCtrlKeyNPage: return Key.PageDown | Key.ShiftMask | Key.CtrlMask;
  161. case Curses.ShiftCtrlKeyPPage: return Key.PageUp | Key.ShiftMask | Key.CtrlMask;
  162. default: return Key.Unknown;
  163. }
  164. }
  165. static MouseEvent ToDriverMouse (Curses.MouseEvent cev)
  166. {
  167. return new MouseEvent () {
  168. X = cev.X,
  169. Y = cev.Y,
  170. Flags = (MouseFlags)cev.ButtonState
  171. };
  172. }
  173. void ProcessInput (Action<KeyEvent> keyHandler, Action<MouseEvent> mouseHandler)
  174. {
  175. int wch;
  176. var code = Curses.get_wch (out wch);
  177. if (code == Curses.ERR)
  178. return;
  179. if (code == Curses.KEY_CODE_YES) {
  180. if (wch == Curses.KeyResize) {
  181. if (Curses.CheckWinChange ()) {
  182. TerminalResized?.Invoke ();
  183. return;
  184. }
  185. }
  186. if (wch == Curses.KeyMouse) {
  187. Curses.MouseEvent ev;
  188. Curses.getmouse (out ev);
  189. mouseHandler (ToDriverMouse (ev));
  190. return;
  191. }
  192. keyHandler (new KeyEvent (MapCursesKey (wch)));
  193. return;
  194. }
  195. // Special handling for ESC, we want to try to catch ESC+letter to simulate alt-letter as well as Alt-Fkey
  196. if (wch == 27) {
  197. Curses.timeout (200);
  198. code = Curses.get_wch (out wch);
  199. if (code == Curses.KEY_CODE_YES)
  200. keyHandler (new KeyEvent (Key.AltMask | MapCursesKey (wch)));
  201. if (code == 0) {
  202. KeyEvent key;
  203. // The ESC-number handling, debatable.
  204. // Simulates the AltMask itself by pressing Alt + Space.
  205. if (wch == (int)Key.Space)
  206. key = new KeyEvent (Key.AltMask);
  207. else if (wch - (int)Key.Space >= 'A' && wch - (int)Key.Space <= 'Z')
  208. key = new KeyEvent ((Key)((uint)Key.AltMask + (wch - (int)Key.Space)));
  209. else if (wch >= '1' && wch <= '9')
  210. key = new KeyEvent ((Key)((int)Key.F1 + (wch - '0' - 1)));
  211. else if (wch == '0')
  212. key = new KeyEvent (Key.F10);
  213. else if (wch == 27)
  214. key = new KeyEvent ((Key)wch);
  215. else
  216. key = new KeyEvent (Key.AltMask | (Key)wch);
  217. keyHandler (key);
  218. } else
  219. keyHandler (new KeyEvent (Key.Esc));
  220. } else
  221. keyHandler (new KeyEvent ((Key)wch));
  222. }
  223. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
  224. {
  225. // Note: Curses doesn't support keydown/up events and thus any passed keyDown/UpHandlers will never be called
  226. Curses.timeout (-1);
  227. (mainLoop.Driver as Mono.Terminal.UnixMainLoop).AddWatch (0, Mono.Terminal.UnixMainLoop.Condition.PollIn |
  228. Mono.Terminal.UnixMainLoop.Condition.PollOut, x => {
  229. ProcessInput (keyHandler, mouseHandler);
  230. return true;
  231. });
  232. }
  233. Curses.Event oldMouseEvents, reportableMouseEvents;
  234. public override void Init (Action terminalResized)
  235. {
  236. if (window != null)
  237. return;
  238. try {
  239. window = Curses.initscr ();
  240. } catch (Exception e) {
  241. Console.WriteLine ("Curses failed to initialize, the exception is: " + e);
  242. }
  243. Curses.raw ();
  244. Curses.noecho ();
  245. Curses.Window.Standard.keypad (true);
  246. reportableMouseEvents = Curses.mousemask (Curses.Event.AllEvents | Curses.Event.ReportMousePosition, out oldMouseEvents);
  247. TerminalResized = terminalResized;
  248. if (reportableMouseEvents.HasFlag (Curses.Event.ReportMousePosition))
  249. StartReportingMouseMoves ();
  250. HLine = Curses.ACS_HLINE;
  251. VLine = Curses.ACS_VLINE;
  252. Stipple = Curses.ACS_CKBOARD;
  253. Diamond = Curses.ACS_DIAMOND;
  254. ULCorner = Curses.ACS_ULCORNER;
  255. LLCorner = Curses.ACS_LLCORNER;
  256. URCorner = Curses.ACS_URCORNER;
  257. LRCorner = Curses.ACS_LRCORNER;
  258. LeftTee = Curses.ACS_LTEE;
  259. RightTee = Curses.ACS_RTEE;
  260. TopTee = Curses.ACS_TTEE;
  261. BottomTee = Curses.ACS_BTEE;
  262. Colors.Base = new ColorScheme ();
  263. Colors.Dialog = new ColorScheme ();
  264. Colors.Menu = new ColorScheme ();
  265. Colors.Error = new ColorScheme ();
  266. Clip = new Rect (0, 0, Cols, Rows);
  267. if (Curses.HasColors) {
  268. Curses.StartColor ();
  269. Curses.UseDefaultColors ();
  270. Colors.Base.Normal = MakeColor (Curses.COLOR_WHITE, Curses.COLOR_BLUE);
  271. Colors.Base.Focus = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_CYAN);
  272. Colors.Base.HotNormal = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_BLUE);
  273. Colors.Base.HotFocus = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_CYAN);
  274. // Focused,
  275. // Selected, Hot: Yellow on Black
  276. // Selected, text: white on black
  277. // Unselected, hot: yellow on cyan
  278. // unselected, text: same as unfocused
  279. Colors.Menu.HotFocus = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_BLACK);
  280. Colors.Menu.Focus = Curses.A_BOLD | MakeColor (Curses.COLOR_WHITE, Curses.COLOR_BLACK);
  281. Colors.Menu.HotNormal = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_CYAN);
  282. Colors.Menu.Normal = Curses.A_BOLD | MakeColor (Curses.COLOR_WHITE, Curses.COLOR_CYAN);
  283. Colors.Menu.Disabled = MakeColor(Curses.COLOR_WHITE, Curses.COLOR_CYAN);
  284. Colors.Dialog.Normal = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_WHITE);
  285. Colors.Dialog.Focus = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_CYAN);
  286. Colors.Dialog.HotNormal = MakeColor (Curses.COLOR_BLUE, Curses.COLOR_WHITE);
  287. Colors.Dialog.HotFocus = MakeColor (Curses.COLOR_BLUE, Curses.COLOR_CYAN);
  288. Colors.Error.Normal = Curses.A_BOLD | MakeColor (Curses.COLOR_WHITE, Curses.COLOR_RED);
  289. Colors.Error.Focus = MakeColor (Curses.COLOR_BLACK, Curses.COLOR_WHITE);
  290. Colors.Error.HotNormal = Curses.A_BOLD | MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_RED);
  291. Colors.Error.HotFocus = Colors.Error.HotNormal;
  292. } else {
  293. Colors.Base.Normal = Curses.A_NORMAL;
  294. Colors.Base.Focus = Curses.A_REVERSE;
  295. Colors.Base.HotNormal = Curses.A_BOLD;
  296. Colors.Base.HotFocus = Curses.A_BOLD | Curses.A_REVERSE;
  297. Colors.Menu.Normal = Curses.A_REVERSE;
  298. Colors.Menu.Focus = Curses.A_NORMAL;
  299. Colors.Menu.HotNormal = Curses.A_BOLD;
  300. Colors.Menu.HotFocus = Curses.A_NORMAL;
  301. Colors.Dialog.Normal = Curses.A_REVERSE;
  302. Colors.Dialog.Focus = Curses.A_NORMAL;
  303. Colors.Dialog.HotNormal = Curses.A_BOLD;
  304. Colors.Dialog.HotFocus = Curses.A_NORMAL;
  305. Colors.Error.Normal = Curses.A_BOLD;
  306. Colors.Error.Focus = Curses.A_BOLD | Curses.A_REVERSE;
  307. Colors.Error.HotNormal = Curses.A_BOLD | Curses.A_REVERSE;
  308. Colors.Error.HotFocus = Curses.A_REVERSE;
  309. }
  310. Colors.TopLevel = new ColorScheme ();
  311. Colors.TopLevel.Normal = MakeColor (Curses.COLOR_GREEN, Curses.COLOR_BLACK);
  312. Colors.TopLevel.Focus = MakeColor (Curses.COLOR_WHITE, Curses.COLOR_CYAN);
  313. Colors.TopLevel.HotNormal = MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_BLACK);
  314. Colors.TopLevel.HotFocus = MakeColor (Curses.COLOR_YELLOW, Curses.COLOR_CYAN);
  315. }
  316. static int MapColor (Color color)
  317. {
  318. switch (color) {
  319. case Color.Black:
  320. return Curses.COLOR_BLACK;
  321. case Color.Blue:
  322. return Curses.COLOR_BLUE;
  323. case Color.Green:
  324. return Curses.COLOR_GREEN;
  325. case Color.Cyan:
  326. return Curses.COLOR_CYAN;
  327. case Color.Red:
  328. return Curses.COLOR_RED;
  329. case Color.Magenta:
  330. return Curses.COLOR_MAGENTA;
  331. case Color.Brown:
  332. return Curses.COLOR_YELLOW;
  333. case Color.Gray:
  334. return Curses.COLOR_WHITE;
  335. case Color.DarkGray:
  336. return Curses.COLOR_BLACK | Curses.A_BOLD;
  337. case Color.BrightBlue:
  338. return Curses.COLOR_BLUE | Curses.A_BOLD;
  339. case Color.BrightGreen:
  340. return Curses.COLOR_GREEN | Curses.A_BOLD;
  341. case Color.BrighCyan:
  342. return Curses.COLOR_CYAN | Curses.A_BOLD;
  343. case Color.BrightRed:
  344. return Curses.COLOR_RED | Curses.A_BOLD;
  345. case Color.BrightMagenta:
  346. return Curses.COLOR_MAGENTA | Curses.A_BOLD;
  347. case Color.BrightYellow:
  348. return Curses.COLOR_YELLOW | Curses.A_BOLD;
  349. case Color.White:
  350. return Curses.COLOR_WHITE | Curses.A_BOLD;
  351. }
  352. throw new ArgumentException ("Invalid color code");
  353. }
  354. public override Attribute MakeAttribute (Color fore, Color back)
  355. {
  356. var f = MapColor (fore);
  357. return MakeColor ((short)(f & 0xffff), (short)MapColor (back)) | ((f & Curses.A_BOLD) != 0 ? Curses.A_BOLD : 0);
  358. }
  359. public override void Suspend ()
  360. {
  361. if (reportableMouseEvents.HasFlag (Curses.Event.ReportMousePosition))
  362. StopReportingMouseMoves ();
  363. Platform.Suspend ();
  364. Curses.Window.Standard.redrawwin ();
  365. Curses.refresh ();
  366. if (reportableMouseEvents.HasFlag (Curses.Event.ReportMousePosition))
  367. StartReportingMouseMoves ();
  368. }
  369. public override void StartReportingMouseMoves ()
  370. {
  371. Console.Out.Write ("\x1b[?1003h");
  372. Console.Out.Flush ();
  373. }
  374. public override void StopReportingMouseMoves ()
  375. {
  376. Console.Out.Write ("\x1b[?1003l");
  377. Console.Out.Flush ();
  378. }
  379. int lastMouseInterval;
  380. bool mouseGrabbed;
  381. public override void UncookMouse ()
  382. {
  383. if (mouseGrabbed)
  384. return;
  385. lastMouseInterval = Curses.mouseinterval (0);
  386. mouseGrabbed = true;
  387. }
  388. public override void CookMouse ()
  389. {
  390. mouseGrabbed = false;
  391. Curses.mouseinterval (lastMouseInterval);
  392. }
  393. }
  394. internal static class Platform {
  395. [DllImport ("libc")]
  396. static extern int uname (IntPtr buf);
  397. [DllImport ("libc")]
  398. static extern int killpg (int pgrp, int pid);
  399. static int suspendSignal;
  400. static int GetSuspendSignal ()
  401. {
  402. if (suspendSignal != 0)
  403. return suspendSignal;
  404. IntPtr buf = Marshal.AllocHGlobal (8192);
  405. if (uname (buf) != 0) {
  406. Marshal.FreeHGlobal (buf);
  407. suspendSignal = -1;
  408. return suspendSignal;
  409. }
  410. try {
  411. switch (Marshal.PtrToStringAnsi (buf)) {
  412. case "Darwin":
  413. case "DragonFly":
  414. case "FreeBSD":
  415. case "NetBSD":
  416. case "OpenBSD":
  417. suspendSignal = 18;
  418. break;
  419. case "Linux":
  420. // TODO: should fetch the machine name and
  421. // if it is MIPS return 24
  422. suspendSignal = 20;
  423. break;
  424. case "Solaris":
  425. suspendSignal = 24;
  426. break;
  427. default:
  428. suspendSignal = -1;
  429. break;
  430. }
  431. return suspendSignal;
  432. } finally {
  433. Marshal.FreeHGlobal (buf);
  434. }
  435. }
  436. /// <summary>
  437. /// Suspends the process by sending SIGTSTP to itself
  438. /// </summary>
  439. /// <returns>The suspend.</returns>
  440. static public bool Suspend ()
  441. {
  442. int signal = GetSuspendSignal ();
  443. if (signal == -1)
  444. return false;
  445. killpg (0, signal);
  446. return true;
  447. }
  448. }
  449. }