CursesDriver.cs 26 KB

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