CursesDriver.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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. #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
  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 = false;
  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. var runeWidth = Rune.ColumnWidth(rune);
  51. if (runeWidth > 1) {
  52. for (int i = 1; i < runeWidth; i++) {
  53. ccol++;
  54. }
  55. }
  56. }
  57. public override void AddStr (ustring str)
  58. {
  59. // TODO; optimize this to determine if the str fits in the clip region, and if so, use Curses.addstr directly
  60. foreach (var rune in str)
  61. AddRune (rune);
  62. }
  63. public override void Refresh () => Curses.refresh ();
  64. public override void UpdateCursor () => Curses.refresh ();
  65. public override void End () => Curses.endwin ();
  66. public override void UpdateScreen () => window.redrawwin ();
  67. public override void SetAttribute (Attribute c) => Curses.attrset (c.value);
  68. public Curses.Window window;
  69. static short last_color_pair = 16;
  70. /// <summary>
  71. /// Creates a curses color from the provided foreground and background colors
  72. /// </summary>
  73. /// <param name="foreground">Contains the curses attributes for the foreground (color, plus any attributes)</param>
  74. /// <param name="background">Contains the curses attributes for the background (color, plus any attributes)</param>
  75. /// <returns></returns>
  76. public static Attribute MakeColor (short foreground, short background)
  77. {
  78. Curses.InitColorPair (++last_color_pair, foreground, background);
  79. return new Attribute () { value = Curses.ColorPair (last_color_pair) };
  80. }
  81. int [,] colorPairs = new int [16, 16];
  82. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  83. {
  84. int f = (short)foreground;
  85. int b = (short)background;
  86. var v = colorPairs [f, b];
  87. if ((v & 0x10000) == 0) {
  88. b = b & 0x7;
  89. bool bold = (f & 0x8) != 0;
  90. f = f & 0x7;
  91. v = MakeColor ((short)f, (short)b) | (bold ? Curses.A_BOLD : 0);
  92. colorPairs [(int)foreground, (int)background] = v | 0x1000;
  93. }
  94. SetAttribute (v & 0xffff);
  95. }
  96. Dictionary<int, int> rawPairs = new Dictionary<int, int> ();
  97. public override void SetColors (short foreColorId, short backgroundColorId)
  98. {
  99. int key = (((ushort)foreColorId << 16)) | (ushort)backgroundColorId;
  100. if (!rawPairs.TryGetValue (key, out var v)) {
  101. v = MakeColor (foreColorId, backgroundColorId);
  102. rawPairs [key] = v;
  103. }
  104. SetAttribute (v);
  105. }
  106. static Key MapCursesKey (int cursesKey)
  107. {
  108. switch (cursesKey) {
  109. case Curses.KeyF1: return Key.F1;
  110. case Curses.KeyF2: return Key.F2;
  111. case Curses.KeyF3: return Key.F3;
  112. case Curses.KeyF4: return Key.F4;
  113. case Curses.KeyF5: return Key.F5;
  114. case Curses.KeyF6: return Key.F6;
  115. case Curses.KeyF7: return Key.F7;
  116. case Curses.KeyF8: return Key.F8;
  117. case Curses.KeyF9: return Key.F9;
  118. case Curses.KeyF10: return Key.F10;
  119. case Curses.KeyUp: return Key.CursorUp;
  120. case Curses.KeyDown: return Key.CursorDown;
  121. case Curses.KeyLeft: return Key.CursorLeft;
  122. case Curses.KeyRight: return Key.CursorRight;
  123. case Curses.KeyHome: return Key.Home;
  124. case Curses.KeyEnd: return Key.End;
  125. case Curses.KeyNPage: return Key.PageDown;
  126. case Curses.KeyPPage: return Key.PageUp;
  127. case Curses.KeyDeleteChar: return Key.DeleteChar;
  128. case Curses.KeyInsertChar: return Key.InsertChar;
  129. case Curses.KeyBackTab: return Key.BackTab;
  130. case Curses.KeyBackspace: return Key.Backspace;
  131. case Curses.ShiftKeyUp: return Key.CursorUp | Key.ShiftMask;
  132. case Curses.ShiftKeyDown: return Key.CursorDown | Key.ShiftMask;
  133. case Curses.ShiftKeyLeft: return Key.CursorLeft | Key.ShiftMask;
  134. case Curses.ShiftKeyRight: return Key.CursorRight | Key.ShiftMask;
  135. case Curses.ShiftKeyHome: return Key.Home | Key.ShiftMask;
  136. case Curses.ShiftKeyEnd: return Key.End | Key.ShiftMask;
  137. case Curses.ShiftKeyNPage: return Key.PageDown | Key.ShiftMask;
  138. case Curses.ShiftKeyPPage: return Key.PageUp | Key.ShiftMask;
  139. case Curses.AltKeyUp: return Key.CursorUp | Key.AltMask;
  140. case Curses.AltKeyDown: return Key.CursorDown | Key.AltMask;
  141. case Curses.AltKeyLeft: return Key.CursorLeft | Key.AltMask;
  142. case Curses.AltKeyRight: return Key.CursorRight | Key.AltMask;
  143. case Curses.AltKeyHome: return Key.Home | Key.AltMask;
  144. case Curses.AltKeyEnd: return Key.End | Key.AltMask;
  145. case Curses.AltKeyNPage: return Key.PageDown | Key.AltMask;
  146. case Curses.AltKeyPPage: return Key.PageUp | Key.AltMask;
  147. case Curses.CtrlKeyUp: return Key.CursorUp | Key.CtrlMask;
  148. case Curses.CtrlKeyDown: return Key.CursorDown | Key.CtrlMask;
  149. case Curses.CtrlKeyLeft: return Key.CursorLeft | Key.CtrlMask;
  150. case Curses.CtrlKeyRight: return Key.CursorRight | Key.CtrlMask;
  151. case Curses.CtrlKeyHome: return Key.Home | Key.CtrlMask;
  152. case Curses.CtrlKeyEnd: return Key.End | Key.CtrlMask;
  153. case Curses.CtrlKeyNPage: return Key.PageDown | Key.CtrlMask;
  154. case Curses.CtrlKeyPPage: return Key.PageUp | Key.CtrlMask;
  155. case Curses.ShiftCtrlKeyUp: return Key.CursorUp | Key.ShiftMask | Key.CtrlMask;
  156. case Curses.ShiftCtrlKeyDown: return Key.CursorDown | Key.ShiftMask | Key.CtrlMask;
  157. case Curses.ShiftCtrlKeyLeft: return Key.CursorLeft | Key.ShiftMask | Key.CtrlMask;
  158. case Curses.ShiftCtrlKeyRight: return Key.CursorRight | Key.ShiftMask | Key.CtrlMask;
  159. case Curses.ShiftCtrlKeyHome: return Key.Home | Key.ShiftMask | Key.CtrlMask;
  160. case Curses.ShiftCtrlKeyEnd: return Key.End | Key.ShiftMask | Key.CtrlMask;
  161. case Curses.ShiftCtrlKeyNPage: return Key.PageDown | Key.ShiftMask | Key.CtrlMask;
  162. case Curses.ShiftCtrlKeyPPage: return Key.PageUp | Key.ShiftMask | Key.CtrlMask;
  163. default: return Key.Unknown;
  164. }
  165. }
  166. static MouseEvent ToDriverMouse (Curses.MouseEvent cev)
  167. {
  168. return new MouseEvent () {
  169. X = cev.X,
  170. Y = cev.Y,
  171. Flags = (MouseFlags)cev.ButtonState
  172. };
  173. }
  174. void ProcessInput (Action<KeyEvent> keyHandler, Action<MouseEvent> mouseHandler)
  175. {
  176. int wch;
  177. var code = Curses.get_wch (out wch);
  178. if (code == Curses.ERR)
  179. return;
  180. if (code == Curses.KEY_CODE_YES) {
  181. if (wch == Curses.KeyResize) {
  182. if (Curses.CheckWinChange ()) {
  183. TerminalResized?.Invoke ();
  184. return;
  185. }
  186. }
  187. if (wch == Curses.KeyMouse) {
  188. Curses.MouseEvent ev;
  189. Curses.getmouse (out ev);
  190. mouseHandler (ToDriverMouse (ev));
  191. return;
  192. }
  193. keyHandler (new KeyEvent (MapCursesKey (wch)));
  194. return;
  195. }
  196. // Special handling for ESC, we want to try to catch ESC+letter to simulate alt-letter as well as Alt-Fkey
  197. if (wch == 27) {
  198. Curses.timeout (200);
  199. code = Curses.get_wch (out wch);
  200. if (code == Curses.KEY_CODE_YES)
  201. keyHandler (new KeyEvent (Key.AltMask | MapCursesKey (wch)));
  202. if (code == 0) {
  203. KeyEvent key;
  204. // The ESC-number handling, debatable.
  205. // Simulates the AltMask itself by pressing Alt + Space.
  206. if (wch == (int)Key.Space)
  207. key = new KeyEvent (Key.AltMask);
  208. else if (wch - (int)Key.Space >= 'A' && wch - (int)Key.Space <= 'Z')
  209. key = new KeyEvent ((Key)((uint)Key.AltMask + (wch - (int)Key.Space)));
  210. else if (wch >= '1' && wch <= '9')
  211. key = new KeyEvent ((Key)((int)Key.F1 + (wch - '0' - 1)));
  212. else if (wch == '0')
  213. key = new KeyEvent (Key.F10);
  214. else if (wch == 27)
  215. key = new KeyEvent ((Key)wch);
  216. else
  217. key = new KeyEvent (Key.AltMask | (Key)wch);
  218. keyHandler (key);
  219. } else
  220. keyHandler (new KeyEvent (Key.Esc));
  221. } else
  222. keyHandler (new KeyEvent ((Key)wch));
  223. }
  224. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
  225. {
  226. // Note: Curses doesn't support keydown/up events and thus any passed keyDown/UpHandlers will never be called
  227. Curses.timeout (-1);
  228. (mainLoop.Driver as Mono.Terminal.UnixMainLoop).AddWatch (0, Mono.Terminal.UnixMainLoop.Condition.PollIn, 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. #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
  449. }
  450. }