CursesDriver.cs 24 KB

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