CursesDriver.cs 24 KB

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