CursesDriver.cs 16 KB

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