CursesDriver.cs 16 KB

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