CursesDriver.cs 27 KB

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