CursesDriver.cs 26 KB

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