CursesDriver.cs 26 KB

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