CursesDriver.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  1. //
  2. // Driver.cs: Curses-based Driver
  3. //
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.Runtime.InteropServices;
  8. using System.Text;
  9. using Unix.Terminal;
  10. namespace Terminal.Gui;
  11. /// <summary>
  12. /// This is the Curses driver for the gui.cs/Terminal framework.
  13. /// </summary>
  14. internal class CursesDriver : ConsoleDriver {
  15. public override int Cols => Curses.Cols;
  16. public override int Rows => Curses.Lines;
  17. CursorVisibility? _initialCursorVisibility = null;
  18. CursorVisibility? _currentCursorVisibility = null;
  19. public override string GetVersionInfo () => $"{Curses.curses_version ()}";
  20. public override bool SupportsTrueColor => false;
  21. public override void Move (int col, int row)
  22. {
  23. base.Move (col, row);
  24. if (RunningUnitTests) {
  25. return;
  26. }
  27. if (IsValidLocation (col, row)) {
  28. Curses.move (row, col);
  29. } else {
  30. // Not a valid location (outside screen or clip region)
  31. // Move within the clip region, then AddRune will actually move to Col, Row
  32. Curses.move (Clip.Y, Clip.X);
  33. }
  34. }
  35. public override bool IsRuneSupported (Rune rune)
  36. {
  37. // See Issue #2615 - CursesDriver is broken with non-BMP characters
  38. return base.IsRuneSupported (rune) && rune.IsBmp;
  39. }
  40. public override void Refresh ()
  41. {
  42. UpdateScreen ();
  43. UpdateCursor ();
  44. }
  45. private void ProcessWinChange ()
  46. {
  47. if (!RunningUnitTests && Curses.CheckWinChange ()) {
  48. ClearContents ();
  49. TerminalResized?.Invoke ();
  50. }
  51. }
  52. #region Color Handling
  53. /// <summary>
  54. /// Creates an Attribute from the provided curses-based foreground and background color numbers
  55. /// </summary>
  56. /// <param name="foreground">Contains the curses color number for the foreground (color, plus any attributes)</param>
  57. /// <param name="background">Contains the curses color number for the background (color, plus any attributes)</param>
  58. /// <returns></returns>
  59. static Attribute MakeColor (short foreground, short background)
  60. {
  61. var v = (short)((int)foreground | background << 4);
  62. // TODO: for TrueColor - Use InitExtendedPair
  63. Curses.InitColorPair (v, foreground, background);
  64. return new Attribute (
  65. platformColor: Curses.ColorPair (v),
  66. foreground: CursesColorNumberToColor (foreground),
  67. background: CursesColorNumberToColor (background));
  68. }
  69. /// <remarks>
  70. /// In the CursesDriver, colors are encoded as an int.
  71. /// The foreground color is stored in the most significant 4 bits,
  72. /// and the background color is stored in the least significant 4 bits.
  73. /// The Terminal.GUi Color values are converted to curses color encoding before being encoded.
  74. /// </remarks>
  75. public override Attribute MakeColor (ColorNames fore, ColorNames back)
  76. {
  77. if (!RunningUnitTests) {
  78. return MakeColor (ColorNameToCursesColorNumber (fore), ColorNameToCursesColorNumber (back));
  79. } else {
  80. return new Attribute (
  81. platformColor: 0,
  82. foreground: ColorNameToCursesColorNumber (fore),
  83. background: ColorNameToCursesColorNumber (back));
  84. }
  85. }
  86. public override Attribute MakeColor (Color foreground, Color background)
  87. {
  88. if (!RunningUnitTests) {
  89. return MakeColor (foreground.ColorName, background.ColorName);
  90. } else {
  91. return new Attribute (
  92. platformColor: 0,
  93. foreground: foreground,
  94. background: background);
  95. }
  96. }
  97. static short ColorNameToCursesColorNumber (ColorNames color)
  98. {
  99. switch (color) {
  100. case ColorNames.Black:
  101. return Curses.COLOR_BLACK;
  102. case ColorNames.Blue:
  103. return Curses.COLOR_BLUE;
  104. case ColorNames.Green:
  105. return Curses.COLOR_GREEN;
  106. case ColorNames.Cyan:
  107. return Curses.COLOR_CYAN;
  108. case ColorNames.Red:
  109. return Curses.COLOR_RED;
  110. case ColorNames.Magenta:
  111. return Curses.COLOR_MAGENTA;
  112. case ColorNames.Brown:
  113. return Curses.COLOR_YELLOW;
  114. case ColorNames.Gray:
  115. return Curses.COLOR_WHITE;
  116. case ColorNames.DarkGray:
  117. return Curses.COLOR_GRAY;
  118. case ColorNames.BrightBlue:
  119. return Curses.COLOR_BLUE | Curses.COLOR_GRAY;
  120. case ColorNames.BrightGreen:
  121. return Curses.COLOR_GREEN | Curses.COLOR_GRAY;
  122. case ColorNames.BrightCyan:
  123. return Curses.COLOR_CYAN | Curses.COLOR_GRAY;
  124. case ColorNames.BrightRed:
  125. return Curses.COLOR_RED | Curses.COLOR_GRAY;
  126. case ColorNames.BrightMagenta:
  127. return Curses.COLOR_MAGENTA | Curses.COLOR_GRAY;
  128. case ColorNames.BrightYellow:
  129. return Curses.COLOR_YELLOW | Curses.COLOR_GRAY;
  130. case ColorNames.White:
  131. return Curses.COLOR_WHITE | Curses.COLOR_GRAY;
  132. }
  133. throw new ArgumentException ("Invalid color code");
  134. }
  135. static ColorNames CursesColorNumberToColor (short color)
  136. {
  137. switch (color) {
  138. case Curses.COLOR_BLACK:
  139. return Color.Black;
  140. case Curses.COLOR_BLUE:
  141. return Color.Blue;
  142. case Curses.COLOR_GREEN:
  143. return Color.Green;
  144. case Curses.COLOR_CYAN:
  145. return Color.Cyan;
  146. case Curses.COLOR_RED:
  147. return Color.Red;
  148. case Curses.COLOR_MAGENTA:
  149. return Color.Magenta;
  150. case Curses.COLOR_YELLOW:
  151. return Color.Brown;
  152. case Curses.COLOR_WHITE:
  153. return Color.Gray;
  154. case Curses.COLOR_GRAY:
  155. return Color.DarkGray;
  156. case Curses.COLOR_BLUE | Curses.COLOR_GRAY:
  157. return Color.BrightBlue;
  158. case Curses.COLOR_GREEN | Curses.COLOR_GRAY:
  159. return Color.BrightGreen;
  160. case Curses.COLOR_CYAN | Curses.COLOR_GRAY:
  161. return Color.BrightCyan;
  162. case Curses.COLOR_RED | Curses.COLOR_GRAY:
  163. return Color.BrightRed;
  164. case Curses.COLOR_MAGENTA | Curses.COLOR_GRAY:
  165. return Color.BrightMagenta;
  166. case Curses.COLOR_YELLOW | Curses.COLOR_GRAY:
  167. return Color.BrightYellow;
  168. case Curses.COLOR_WHITE | Curses.COLOR_GRAY:
  169. return Color.White;
  170. }
  171. throw new ArgumentException ("Invalid curses color code");
  172. }
  173. /// <remarks>
  174. /// In the CursesDriver, colors are encoded as an int.
  175. /// The foreground color is stored in the most significant 4 bits,
  176. /// and the background color is stored in the least significant 4 bits.
  177. /// The Terminal.GUI Color values are converted to curses color encoding before being encoded.
  178. /// </remarks>
  179. internal override void GetColors (int value, out ColorNames foreground, out ColorNames background)
  180. {
  181. // Assume a 4-bit encoded value for both foreground and background colors.
  182. foreground = CursesColorNumberToColor ((short)((value >> 4) & 0xF));
  183. background = CursesColorNumberToColor ((short)(value & 0xF));
  184. }
  185. #endregion
  186. public override void UpdateCursor ()
  187. {
  188. EnsureCursorVisibility ();
  189. if (!RunningUnitTests && Col >= 0 && Col < Cols && Row >= 0 && Row < Rows) {
  190. Curses.move (Row, Col);
  191. }
  192. }
  193. public override void End ()
  194. {
  195. StopReportingMouseMoves ();
  196. SetCursorVisibility (CursorVisibility.Default);
  197. if (_mainLoop != null) {
  198. _mainLoop.RemoveWatch (_processInputToken);
  199. _mainLoop.WinChanged -= ProcessInput;
  200. }
  201. if (RunningUnitTests) {
  202. return;
  203. }
  204. // throws away any typeahead that has been typed by
  205. // the user and has not yet been read by the program.
  206. Curses.flushinp ();
  207. Curses.endwin ();
  208. }
  209. public override void UpdateScreen ()
  210. {
  211. for (int row = 0; row < Rows; row++) {
  212. if (!_dirtyLines [row]) {
  213. continue;
  214. }
  215. _dirtyLines [row] = false;
  216. for (int col = 0; col < Cols; col++) {
  217. if (Contents [row, col].IsDirty == false) {
  218. continue;
  219. }
  220. if (RunningUnitTests) {
  221. // In unit tests, we don't want to actually write to the screen.
  222. continue;
  223. }
  224. Curses.attrset (Contents [row, col].Attribute.GetValueOrDefault ().Value);
  225. var rune = Contents [row, col].Runes [0];
  226. if (rune.IsBmp) {
  227. // BUGBUG: CursesDriver doesn't render CharMap correctly for wide chars (and other Unicode) - Curses is doing something funky with glyphs that report GetColums() of 1 yet are rendered wide. E.g. 0x2064 (invisible times) is reported as 1 column but is rendered as 2. WindowsDriver & NetDriver correctly render this as 1 column, overlapping the next cell.
  228. if (rune.GetColumns () < 2) {
  229. Curses.mvaddch (row, col, rune.Value);
  230. } else /*if (col + 1 < Cols)*/ {
  231. Curses.mvaddwstr (row, col, rune.ToString ());
  232. }
  233. } else {
  234. Curses.mvaddwstr (row, col, rune.ToString ());
  235. if (rune.GetColumns () > 1 && col + 1 < Cols) {
  236. // TODO: This is a hack to deal with non-BMP and wide characters.
  237. //col++;
  238. Curses.mvaddch (row, ++col, '*');
  239. }
  240. }
  241. }
  242. }
  243. if (!RunningUnitTests) {
  244. Curses.move (Row, Col);
  245. _window.wrefresh ();
  246. }
  247. }
  248. public Curses.Window _window;
  249. static Key MapCursesKey (int cursesKey)
  250. {
  251. switch (cursesKey) {
  252. case Curses.KeyF1: return Key.F1;
  253. case Curses.KeyF2: return Key.F2;
  254. case Curses.KeyF3: return Key.F3;
  255. case Curses.KeyF4: return Key.F4;
  256. case Curses.KeyF5: return Key.F5;
  257. case Curses.KeyF6: return Key.F6;
  258. case Curses.KeyF7: return Key.F7;
  259. case Curses.KeyF8: return Key.F8;
  260. case Curses.KeyF9: return Key.F9;
  261. case Curses.KeyF10: return Key.F10;
  262. case Curses.KeyF11: return Key.F11;
  263. case Curses.KeyF12: return Key.F12;
  264. case Curses.KeyUp: return Key.CursorUp;
  265. case Curses.KeyDown: return Key.CursorDown;
  266. case Curses.KeyLeft: return Key.CursorLeft;
  267. case Curses.KeyRight: return Key.CursorRight;
  268. case Curses.KeyHome: return Key.Home;
  269. case Curses.KeyEnd: return Key.End;
  270. case Curses.KeyNPage: return Key.PageDown;
  271. case Curses.KeyPPage: return Key.PageUp;
  272. case Curses.KeyDeleteChar: return Key.DeleteChar;
  273. case Curses.KeyInsertChar: return Key.InsertChar;
  274. case Curses.KeyTab: return Key.Tab;
  275. case Curses.KeyBackTab: return Key.BackTab;
  276. case Curses.KeyBackspace: return Key.Backspace;
  277. case Curses.ShiftKeyUp: return Key.CursorUp | Key.ShiftMask;
  278. case Curses.ShiftKeyDown: return Key.CursorDown | Key.ShiftMask;
  279. case Curses.ShiftKeyLeft: return Key.CursorLeft | Key.ShiftMask;
  280. case Curses.ShiftKeyRight: return Key.CursorRight | Key.ShiftMask;
  281. case Curses.ShiftKeyHome: return Key.Home | Key.ShiftMask;
  282. case Curses.ShiftKeyEnd: return Key.End | Key.ShiftMask;
  283. case Curses.ShiftKeyNPage: return Key.PageDown | Key.ShiftMask;
  284. case Curses.ShiftKeyPPage: return Key.PageUp | Key.ShiftMask;
  285. case Curses.AltKeyUp: return Key.CursorUp | Key.AltMask;
  286. case Curses.AltKeyDown: return Key.CursorDown | Key.AltMask;
  287. case Curses.AltKeyLeft: return Key.CursorLeft | Key.AltMask;
  288. case Curses.AltKeyRight: return Key.CursorRight | Key.AltMask;
  289. case Curses.AltKeyHome: return Key.Home | Key.AltMask;
  290. case Curses.AltKeyEnd: return Key.End | Key.AltMask;
  291. case Curses.AltKeyNPage: return Key.PageDown | Key.AltMask;
  292. case Curses.AltKeyPPage: return Key.PageUp | Key.AltMask;
  293. case Curses.CtrlKeyUp: return Key.CursorUp | Key.CtrlMask;
  294. case Curses.CtrlKeyDown: return Key.CursorDown | Key.CtrlMask;
  295. case Curses.CtrlKeyLeft: return Key.CursorLeft | Key.CtrlMask;
  296. case Curses.CtrlKeyRight: return Key.CursorRight | Key.CtrlMask;
  297. case Curses.CtrlKeyHome: return Key.Home | Key.CtrlMask;
  298. case Curses.CtrlKeyEnd: return Key.End | Key.CtrlMask;
  299. case Curses.CtrlKeyNPage: return Key.PageDown | Key.CtrlMask;
  300. case Curses.CtrlKeyPPage: return Key.PageUp | Key.CtrlMask;
  301. case Curses.ShiftCtrlKeyUp: return Key.CursorUp | Key.ShiftMask | Key.CtrlMask;
  302. case Curses.ShiftCtrlKeyDown: return Key.CursorDown | Key.ShiftMask | Key.CtrlMask;
  303. case Curses.ShiftCtrlKeyLeft: return Key.CursorLeft | Key.ShiftMask | Key.CtrlMask;
  304. case Curses.ShiftCtrlKeyRight: return Key.CursorRight | Key.ShiftMask | Key.CtrlMask;
  305. case Curses.ShiftCtrlKeyHome: return Key.Home | Key.ShiftMask | Key.CtrlMask;
  306. case Curses.ShiftCtrlKeyEnd: return Key.End | Key.ShiftMask | Key.CtrlMask;
  307. case Curses.ShiftCtrlKeyNPage: return Key.PageDown | Key.ShiftMask | Key.CtrlMask;
  308. case Curses.ShiftCtrlKeyPPage: return Key.PageUp | Key.ShiftMask | Key.CtrlMask;
  309. case Curses.ShiftAltKeyUp: return Key.CursorUp | Key.ShiftMask | Key.AltMask;
  310. case Curses.ShiftAltKeyDown: return Key.CursorDown | Key.ShiftMask | Key.AltMask;
  311. case Curses.ShiftAltKeyLeft: return Key.CursorLeft | Key.ShiftMask | Key.AltMask;
  312. case Curses.ShiftAltKeyRight: return Key.CursorRight | Key.ShiftMask | Key.AltMask;
  313. case Curses.ShiftAltKeyNPage: return Key.PageDown | Key.ShiftMask | Key.AltMask;
  314. case Curses.ShiftAltKeyPPage: return Key.PageUp | Key.ShiftMask | Key.AltMask;
  315. case Curses.ShiftAltKeyHome: return Key.Home | Key.ShiftMask | Key.AltMask;
  316. case Curses.ShiftAltKeyEnd: return Key.End | Key.ShiftMask | Key.AltMask;
  317. case Curses.AltCtrlKeyNPage: return Key.PageDown | Key.AltMask | Key.CtrlMask;
  318. case Curses.AltCtrlKeyPPage: return Key.PageUp | Key.AltMask | Key.CtrlMask;
  319. case Curses.AltCtrlKeyHome: return Key.Home | Key.AltMask | Key.CtrlMask;
  320. case Curses.AltCtrlKeyEnd: return Key.End | Key.AltMask | Key.CtrlMask;
  321. default: return Key.Unknown;
  322. }
  323. }
  324. KeyModifiers _keyModifiers;
  325. KeyModifiers MapKeyModifiers (Key key)
  326. {
  327. if (_keyModifiers == null) {
  328. _keyModifiers = new KeyModifiers ();
  329. }
  330. if (!_keyModifiers.Shift && (key & Key.ShiftMask) != 0) {
  331. _keyModifiers.Shift = true;
  332. }
  333. if (!_keyModifiers.Alt && (key & Key.AltMask) != 0) {
  334. _keyModifiers.Alt = true;
  335. }
  336. if (!_keyModifiers.Ctrl && (key & Key.CtrlMask) != 0) {
  337. _keyModifiers.Ctrl = true;
  338. }
  339. return _keyModifiers;
  340. }
  341. void ProcessInput ()
  342. {
  343. int wch;
  344. var code = Curses.get_wch (out wch);
  345. //System.Diagnostics.Debug.WriteLine ($"code: {code}; wch: {wch}");
  346. if (code == Curses.ERR) {
  347. return;
  348. }
  349. _keyModifiers = new KeyModifiers ();
  350. Key k = Key.Null;
  351. if (code == Curses.KEY_CODE_YES) {
  352. while (code == Curses.KEY_CODE_YES && wch == Curses.KeyResize) {
  353. ProcessWinChange ();
  354. code = Curses.get_wch (out wch);
  355. }
  356. if (wch == 0) {
  357. return;
  358. }
  359. if (wch == Curses.KeyMouse) {
  360. int wch2 = wch;
  361. while (wch2 == Curses.KeyMouse) {
  362. KeyEvent key = null;
  363. ConsoleKeyInfo [] cki = new ConsoleKeyInfo [] {
  364. new ConsoleKeyInfo ((char)Key.Esc, 0, false, false, false),
  365. new ConsoleKeyInfo ('[', 0, false, false, false),
  366. new ConsoleKeyInfo ('<', 0, false, false, false)
  367. };
  368. code = 0;
  369. HandleEscSeqResponse (ref code, ref k, ref wch2, ref key, ref cki);
  370. }
  371. return;
  372. }
  373. k = MapCursesKey (wch);
  374. if (wch >= 277 && wch <= 288) {
  375. // Shift+(F1 - F12)
  376. wch -= 12;
  377. k = Key.ShiftMask | MapCursesKey (wch);
  378. } else if (wch >= 289 && wch <= 300) {
  379. // Ctrl+(F1 - F12)
  380. wch -= 24;
  381. k = Key.CtrlMask | MapCursesKey (wch);
  382. } else if (wch >= 301 && wch <= 312) {
  383. // Ctrl+Shift+(F1 - F12)
  384. wch -= 36;
  385. k = Key.CtrlMask | Key.ShiftMask | MapCursesKey (wch);
  386. } else if (wch >= 313 && wch <= 324) {
  387. // Alt+(F1 - F12)
  388. wch -= 48;
  389. k = Key.AltMask | MapCursesKey (wch);
  390. } else if (wch >= 325 && wch <= 327) {
  391. // Shift+Alt+(F1 - F3)
  392. wch -= 60;
  393. k = Key.ShiftMask | Key.AltMask | MapCursesKey (wch);
  394. }
  395. _keyDownHandler (new KeyEvent (k, MapKeyModifiers (k)));
  396. _keyHandler (new KeyEvent (k, MapKeyModifiers (k)));
  397. _keyUpHandler (new KeyEvent (k, MapKeyModifiers (k)));
  398. return;
  399. }
  400. // Special handling for ESC, we want to try to catch ESC+letter to simulate alt-letter as well as Alt-Fkey
  401. if (wch == 27) {
  402. Curses.timeout (10);
  403. code = Curses.get_wch (out int wch2);
  404. if (code == Curses.KEY_CODE_YES) {
  405. k = Key.AltMask | MapCursesKey (wch);
  406. }
  407. if (code == 0) {
  408. KeyEvent key = null;
  409. // The ESC-number handling, debatable.
  410. // Simulates the AltMask itself by pressing Alt + Space.
  411. if (wch2 == (int)Key.Space) {
  412. k = Key.AltMask;
  413. } else if (wch2 - (int)Key.Space >= (uint)Key.A && wch2 - (int)Key.Space <= (uint)Key.Z) {
  414. k = (Key)((uint)Key.AltMask + (wch2 - (int)Key.Space));
  415. } else if (wch2 >= (uint)Key.A - 64 && wch2 <= (uint)Key.Z - 64) {
  416. k = (Key)((uint)(Key.AltMask | Key.CtrlMask) + (wch2 + 64));
  417. } else if (wch2 >= (uint)Key.D0 && wch2 <= (uint)Key.D9) {
  418. k = (Key)((uint)Key.AltMask + (uint)Key.D0 + (wch2 - (uint)Key.D0));
  419. } else if (wch2 == Curses.KeyCSI) {
  420. ConsoleKeyInfo [] cki = new ConsoleKeyInfo [] {
  421. new ConsoleKeyInfo ((char)Key.Esc, 0, false, false, false),
  422. new ConsoleKeyInfo ('[', 0, false, false, false)
  423. };
  424. HandleEscSeqResponse (ref code, ref k, ref wch2, ref key, ref cki);
  425. return;
  426. } else {
  427. // Unfortunately there are no way to differentiate Ctrl+Alt+alfa and Ctrl+Shift+Alt+alfa.
  428. if (((Key)wch2 & Key.CtrlMask) != 0) {
  429. _keyModifiers.Ctrl = true;
  430. }
  431. if (wch2 == 0) {
  432. k = Key.CtrlMask | Key.AltMask | Key.Space;
  433. } else if (wch >= (uint)Key.A && wch <= (uint)Key.Z) {
  434. _keyModifiers.Shift = true;
  435. _keyModifiers.Alt = true;
  436. } else if (wch2 < 256) {
  437. k = (Key)wch2;
  438. _keyModifiers.Alt = true;
  439. } else {
  440. k = (Key)((uint)(Key.AltMask | Key.CtrlMask) + wch2);
  441. }
  442. }
  443. key = new KeyEvent (k, MapKeyModifiers (k));
  444. _keyDownHandler (key);
  445. _keyHandler (key);
  446. } else {
  447. k = Key.Esc;
  448. _keyHandler (new KeyEvent (k, MapKeyModifiers (k)));
  449. }
  450. } else if (wch == Curses.KeyTab) {
  451. k = MapCursesKey (wch);
  452. _keyDownHandler (new KeyEvent (k, MapKeyModifiers (k)));
  453. _keyHandler (new KeyEvent (k, MapKeyModifiers (k)));
  454. } else {
  455. // Unfortunately there are no way to differentiate Ctrl+alfa and Ctrl+Shift+alfa.
  456. k = (Key)wch;
  457. if (wch == 0) {
  458. k = Key.CtrlMask | Key.Space;
  459. } else if (wch >= (uint)Key.A - 64 && wch <= (uint)Key.Z - 64) {
  460. if ((Key)(wch + 64) != Key.J) {
  461. k = Key.CtrlMask | (Key)(wch + 64);
  462. }
  463. } else if (wch >= (uint)Key.A && wch <= (uint)Key.Z) {
  464. _keyModifiers.Shift = true;
  465. }
  466. _keyDownHandler (new KeyEvent (k, MapKeyModifiers (k)));
  467. _keyHandler (new KeyEvent (k, MapKeyModifiers (k)));
  468. _keyUpHandler (new KeyEvent (k, MapKeyModifiers (k)));
  469. }
  470. // Cause OnKeyUp and OnKeyPressed. Note that the special handling for ESC above
  471. // will not impact KeyUp.
  472. // This is causing ESC firing even if another keystroke was handled.
  473. //if (wch == Curses.KeyTab) {
  474. // keyUpHandler (new KeyEvent (MapCursesKey (wch), keyModifiers));
  475. //} else {
  476. // keyUpHandler (new KeyEvent ((Key)wch, keyModifiers));
  477. //}
  478. }
  479. void HandleEscSeqResponse (ref int code, ref Key k, ref int wch2, ref KeyEvent key, ref ConsoleKeyInfo [] cki)
  480. {
  481. ConsoleKey ck = 0;
  482. ConsoleModifiers mod = 0;
  483. while (code == 0) {
  484. code = Curses.get_wch (out wch2);
  485. var consoleKeyInfo = new ConsoleKeyInfo ((char)wch2, 0, false, false, false);
  486. if (wch2 == 0 || wch2 == 27 || wch2 == Curses.KeyMouse) {
  487. EscSeqUtils.DecodeEscSeq (null, ref consoleKeyInfo, ref ck, cki, ref mod, out _, out _, out _, out _, out bool isKeyMouse, out List<MouseFlags> mouseFlags, out Point pos, out _, ProcessContinuousButtonPressed);
  488. if (isKeyMouse) {
  489. foreach (var mf in mouseFlags) {
  490. ProcessMouseEvent (mf, pos);
  491. }
  492. cki = null;
  493. if (wch2 == 27) {
  494. cki = EscSeqUtils.ResizeArray (new ConsoleKeyInfo ((char)Key.Esc, 0,
  495. false, false, false), cki);
  496. }
  497. } else {
  498. k = ConsoleKeyMapping.MapConsoleKeyToKey (consoleKeyInfo.Key, out _);
  499. k = ConsoleKeyMapping.MapKeyModifiers (consoleKeyInfo, k);
  500. key = new KeyEvent (k, MapKeyModifiers (k));
  501. _keyDownHandler (key);
  502. _keyHandler (key);
  503. }
  504. } else {
  505. cki = EscSeqUtils.ResizeArray (consoleKeyInfo, cki);
  506. }
  507. }
  508. }
  509. MouseFlags _lastMouseFlags;
  510. void ProcessMouseEvent (MouseFlags mouseFlag, Point pos)
  511. {
  512. bool WasButtonReleased (MouseFlags flag)
  513. {
  514. return flag.HasFlag (MouseFlags.Button1Released) ||
  515. flag.HasFlag (MouseFlags.Button2Released) ||
  516. flag.HasFlag (MouseFlags.Button3Released) ||
  517. flag.HasFlag (MouseFlags.Button4Released);
  518. }
  519. bool IsButtonNotPressed (MouseFlags flag)
  520. {
  521. return !flag.HasFlag (MouseFlags.Button1Pressed) &&
  522. !flag.HasFlag (MouseFlags.Button2Pressed) &&
  523. !flag.HasFlag (MouseFlags.Button3Pressed) &&
  524. !flag.HasFlag (MouseFlags.Button4Pressed);
  525. }
  526. bool IsButtonClickedOrDoubleClicked (MouseFlags flag)
  527. {
  528. return flag.HasFlag (MouseFlags.Button1Clicked) ||
  529. flag.HasFlag (MouseFlags.Button2Clicked) ||
  530. flag.HasFlag (MouseFlags.Button3Clicked) ||
  531. flag.HasFlag (MouseFlags.Button4Clicked) ||
  532. flag.HasFlag (MouseFlags.Button1DoubleClicked) ||
  533. flag.HasFlag (MouseFlags.Button2DoubleClicked) ||
  534. flag.HasFlag (MouseFlags.Button3DoubleClicked) ||
  535. flag.HasFlag (MouseFlags.Button4DoubleClicked);
  536. }
  537. if ((WasButtonReleased (mouseFlag) && IsButtonNotPressed (_lastMouseFlags)) ||
  538. (IsButtonClickedOrDoubleClicked (mouseFlag) && _lastMouseFlags == 0)) {
  539. return;
  540. }
  541. _lastMouseFlags = mouseFlag;
  542. var me = new MouseEvent () {
  543. Flags = mouseFlag,
  544. X = pos.X,
  545. Y = pos.Y
  546. };
  547. _mouseHandler (me);
  548. }
  549. void ProcessContinuousButtonPressed (MouseFlags mouseFlag, Point pos)
  550. {
  551. ProcessMouseEvent (mouseFlag, pos);
  552. }
  553. Action<KeyEvent> _keyHandler;
  554. Action<KeyEvent> _keyDownHandler;
  555. Action<KeyEvent> _keyUpHandler;
  556. Action<MouseEvent> _mouseHandler;
  557. UnixMainLoop _mainLoop;
  558. object _processInputToken;
  559. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
  560. {
  561. if (!RunningUnitTests) {
  562. // Note: Curses doesn't support keydown/up events and thus any passed keyDown/UpHandlers will never be called
  563. Curses.timeout (0);
  564. }
  565. this._keyHandler = keyHandler;
  566. this._keyDownHandler = keyDownHandler;
  567. this._keyUpHandler = keyUpHandler;
  568. this._mouseHandler = mouseHandler;
  569. _mainLoop = mainLoop.MainLoopDriver as UnixMainLoop;
  570. _processInputToken = _mainLoop?.AddWatch (0, UnixMainLoop.Condition.PollIn, x => {
  571. ProcessInput ();
  572. return true;
  573. });
  574. _mainLoop.WinChanged += ProcessInput;
  575. }
  576. public override void Init (Action terminalResized)
  577. {
  578. if (!RunningUnitTests) {
  579. _window = Curses.initscr ();
  580. Curses.set_escdelay (10);
  581. // Ensures that all procedures are performed at some previous closing.
  582. Curses.doupdate ();
  583. //
  584. // We are setting Invisible as default so we could ignore XTerm DECSUSR setting
  585. //
  586. switch (Curses.curs_set (0)) {
  587. case 0:
  588. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Invisible;
  589. break;
  590. case 1:
  591. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Underline;
  592. Curses.curs_set (1);
  593. break;
  594. case 2:
  595. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Box;
  596. Curses.curs_set (2);
  597. break;
  598. default:
  599. _currentCursorVisibility = _initialCursorVisibility = null;
  600. break;
  601. }
  602. if (!Curses.HasColors) {
  603. throw new InvalidOperationException ("V2 - This should never happen. File an Issue if it does.");
  604. }
  605. Curses.raw ();
  606. Curses.noecho ();
  607. Curses.Window.Standard.keypad (true);
  608. Curses.StartColor ();
  609. Curses.UseDefaultColors ();
  610. }
  611. CurrentAttribute = MakeColor (Color.White, Color.Black);
  612. InitializeColorSchemes ();
  613. TerminalResized = terminalResized;
  614. if (Environment.OSVersion.Platform == PlatformID.Win32NT) {
  615. Clipboard = new FakeDriver.FakeClipboard ();
  616. } else {
  617. if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX)) {
  618. Clipboard = new MacOSXClipboard ();
  619. } else {
  620. if (Is_WSL_Platform ()) {
  621. Clipboard = new WSLClipboard ();
  622. } else {
  623. Clipboard = new CursesClipboard ();
  624. }
  625. }
  626. }
  627. ClearContents ();
  628. StartReportingMouseMoves ();
  629. if (!RunningUnitTests) {
  630. Curses.CheckWinChange ();
  631. Curses.refresh ();
  632. }
  633. }
  634. public static bool Is_WSL_Platform ()
  635. {
  636. // xclip does not work on WSL, so we need to use the Windows clipboard vis Powershell
  637. //if (new CursesClipboard ().IsSupported) {
  638. // // If xclip is installed on Linux under WSL, this will return true.
  639. // return false;
  640. //}
  641. var (exitCode, result) = ClipboardProcessRunner.Bash ("uname -a", waitForOutput: true);
  642. if (exitCode == 0 && result.Contains ("microsoft") && result.Contains ("WSL")) {
  643. return true;
  644. }
  645. return false;
  646. }
  647. public override void Suspend ()
  648. {
  649. StopReportingMouseMoves ();
  650. if (!RunningUnitTests) {
  651. Platform.Suspend ();
  652. Curses.Window.Standard.redrawwin ();
  653. Curses.refresh ();
  654. }
  655. StartReportingMouseMoves ();
  656. }
  657. public void StartReportingMouseMoves ()
  658. {
  659. if (!RunningUnitTests) {
  660. Console.Out.Write (EscSeqUtils.CSI_EnableMouseEvents);
  661. }
  662. }
  663. public void StopReportingMouseMoves ()
  664. {
  665. if (!RunningUnitTests) {
  666. Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents);
  667. }
  668. }
  669. /// <inheritdoc/>
  670. public override bool GetCursorVisibility (out CursorVisibility visibility)
  671. {
  672. visibility = CursorVisibility.Invisible;
  673. if (!_currentCursorVisibility.HasValue)
  674. return false;
  675. visibility = _currentCursorVisibility.Value;
  676. return true;
  677. }
  678. /// <inheritdoc/>
  679. public override bool SetCursorVisibility (CursorVisibility visibility)
  680. {
  681. if (_initialCursorVisibility.HasValue == false) {
  682. return false;
  683. }
  684. if (!RunningUnitTests) {
  685. Curses.curs_set (((int)visibility >> 16) & 0x000000FF);
  686. }
  687. if (visibility != CursorVisibility.Invisible) {
  688. Console.Out.Write (EscSeqUtils.CSI_SetCursorStyle ((EscSeqUtils.DECSCUSR_Style)(((int)visibility >> 24) & 0xFF)));
  689. }
  690. _currentCursorVisibility = visibility;
  691. return true;
  692. }
  693. /// <inheritdoc/>
  694. public override bool EnsureCursorVisibility ()
  695. {
  696. return false;
  697. }
  698. public override void SendKeys (char keyChar, ConsoleKey consoleKey, bool shift, bool alt, bool control)
  699. {
  700. Key key;
  701. if (consoleKey == ConsoleKey.Packet) {
  702. ConsoleModifiers mod = new ConsoleModifiers ();
  703. if (shift) {
  704. mod |= ConsoleModifiers.Shift;
  705. }
  706. if (alt) {
  707. mod |= ConsoleModifiers.Alt;
  708. }
  709. if (control) {
  710. mod |= ConsoleModifiers.Control;
  711. }
  712. var kchar = ConsoleKeyMapping.GetKeyCharFromConsoleKey (keyChar, mod, out uint ckey, out _);
  713. key = ConsoleKeyMapping.MapConsoleKeyToKey ((ConsoleKey)ckey, out bool mappable);
  714. if (mappable) {
  715. key = (Key)kchar;
  716. }
  717. } else {
  718. key = (Key)keyChar;
  719. }
  720. KeyModifiers km = new KeyModifiers ();
  721. if (shift) {
  722. if (keyChar == 0) {
  723. key |= Key.ShiftMask;
  724. }
  725. km.Shift = shift;
  726. }
  727. if (alt) {
  728. key |= Key.AltMask;
  729. km.Alt = alt;
  730. }
  731. if (control) {
  732. key |= Key.CtrlMask;
  733. km.Ctrl = control;
  734. }
  735. _keyDownHandler (new KeyEvent (key, km));
  736. _keyHandler (new KeyEvent (key, km));
  737. _keyUpHandler (new KeyEvent (key, km));
  738. }
  739. }
  740. internal static class Platform {
  741. [DllImport ("libc")]
  742. static extern int uname (IntPtr buf);
  743. [DllImport ("libc")]
  744. static extern int killpg (int pgrp, int pid);
  745. static int _suspendSignal;
  746. static int GetSuspendSignal ()
  747. {
  748. if (_suspendSignal != 0) {
  749. return _suspendSignal;
  750. }
  751. IntPtr buf = Marshal.AllocHGlobal (8192);
  752. if (uname (buf) != 0) {
  753. Marshal.FreeHGlobal (buf);
  754. _suspendSignal = -1;
  755. return _suspendSignal;
  756. }
  757. try {
  758. switch (Marshal.PtrToStringAnsi (buf)) {
  759. case "Darwin":
  760. case "DragonFly":
  761. case "FreeBSD":
  762. case "NetBSD":
  763. case "OpenBSD":
  764. _suspendSignal = 18;
  765. break;
  766. case "Linux":
  767. // TODO: should fetch the machine name and
  768. // if it is MIPS return 24
  769. _suspendSignal = 20;
  770. break;
  771. case "Solaris":
  772. _suspendSignal = 24;
  773. break;
  774. default:
  775. _suspendSignal = -1;
  776. break;
  777. }
  778. return _suspendSignal;
  779. } finally {
  780. Marshal.FreeHGlobal (buf);
  781. }
  782. }
  783. /// <summary>
  784. /// Suspends the process by sending SIGTSTP to itself
  785. /// </summary>
  786. /// <returns>The suspend.</returns>
  787. static public bool Suspend ()
  788. {
  789. int signal = GetSuspendSignal ();
  790. if (signal == -1) {
  791. return false;
  792. }
  793. killpg (0, signal);
  794. return true;
  795. }
  796. }