CursesDriver.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  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 {
  16. get => Curses.Cols;
  17. internal set => Curses.Cols = value;
  18. }
  19. public override int Rows {
  20. get => Curses.Lines;
  21. internal set => Curses.Lines = value;
  22. }
  23. CursorVisibility? _initialCursorVisibility = null;
  24. CursorVisibility? _currentCursorVisibility = null;
  25. public override string GetVersionInfo () => $"{Curses.curses_version ()}";
  26. UnixMainLoop _mainLoopDriver = null;
  27. public override bool SupportsTrueColor => false;
  28. object _processInputToken;
  29. internal override MainLoop Init ()
  30. {
  31. _mainLoopDriver = new UnixMainLoop (this);
  32. if (!RunningUnitTests) {
  33. _window = Curses.initscr ();
  34. Curses.set_escdelay (10);
  35. // Ensures that all procedures are performed at some previous closing.
  36. Curses.doupdate ();
  37. //
  38. // We are setting Invisible as default so we could ignore XTerm DECSUSR setting
  39. //
  40. switch (Curses.curs_set (0)) {
  41. case 0:
  42. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Invisible;
  43. break;
  44. case 1:
  45. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Underline;
  46. Curses.curs_set (1);
  47. break;
  48. case 2:
  49. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Box;
  50. Curses.curs_set (2);
  51. break;
  52. default:
  53. _currentCursorVisibility = _initialCursorVisibility = null;
  54. break;
  55. }
  56. if (!Curses.HasColors) {
  57. throw new InvalidOperationException ("V2 - This should never happen. File an Issue if it does.");
  58. }
  59. Curses.raw ();
  60. Curses.noecho ();
  61. Curses.Window.Standard.keypad (true);
  62. Curses.StartColor ();
  63. Curses.UseDefaultColors ();
  64. if (!RunningUnitTests) {
  65. Curses.timeout (0);
  66. }
  67. _processInputToken = _mainLoopDriver?.AddWatch (0, UnixMainLoop.Condition.PollIn, x => {
  68. ProcessInput ();
  69. return true;
  70. });
  71. }
  72. CurrentAttribute = new Attribute (ColorName.White, ColorName.Black);
  73. if (Environment.OSVersion.Platform == PlatformID.Win32NT) {
  74. Clipboard = new FakeDriver.FakeClipboard ();
  75. } else {
  76. if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX)) {
  77. Clipboard = new MacOSXClipboard ();
  78. } else {
  79. if (Is_WSL_Platform ()) {
  80. Clipboard = new WSLClipboard ();
  81. } else {
  82. Clipboard = new CursesClipboard ();
  83. }
  84. }
  85. }
  86. ClearContents ();
  87. StartReportingMouseMoves ();
  88. if (!RunningUnitTests) {
  89. Curses.CheckWinChange ();
  90. Curses.refresh ();
  91. }
  92. return new MainLoop (_mainLoopDriver);
  93. }
  94. public override void Move (int col, int row)
  95. {
  96. base.Move (col, row);
  97. if (RunningUnitTests) {
  98. return;
  99. }
  100. if (IsValidLocation (col, row)) {
  101. Curses.move (row, col);
  102. } else {
  103. // Not a valid location (outside screen or clip region)
  104. // Move within the clip region, then AddRune will actually move to Col, Row
  105. Curses.move (Clip.Y, Clip.X);
  106. }
  107. }
  108. public override bool IsRuneSupported (Rune rune)
  109. {
  110. // See Issue #2615 - CursesDriver is broken with non-BMP characters
  111. return base.IsRuneSupported (rune) && rune.IsBmp;
  112. }
  113. public override void Refresh ()
  114. {
  115. UpdateScreen ();
  116. UpdateCursor ();
  117. }
  118. internal void ProcessWinChange ()
  119. {
  120. if (!RunningUnitTests && Curses.CheckWinChange ()) {
  121. ClearContents ();
  122. OnSizeChanged (new SizeChangedEventArgs (new Size (Cols, Rows)));
  123. }
  124. }
  125. #region Color Handling
  126. /// <summary>
  127. /// Creates an Attribute from the provided curses-based foreground and background color numbers
  128. /// </summary>
  129. /// <param name="foreground">Contains the curses color number for the foreground (color, plus any attributes)</param>
  130. /// <param name="background">Contains the curses color number for the background (color, plus any attributes)</param>
  131. /// <returns></returns>
  132. static Attribute MakeColor (short foreground, short background)
  133. {
  134. var v = (short)((int)foreground | background << 4);
  135. // TODO: for TrueColor - Use InitExtendedPair
  136. Curses.InitColorPair (v, foreground, background);
  137. return new Attribute (
  138. platformColor: Curses.ColorPair (v),
  139. foreground: CursesColorNumberToColorName (foreground),
  140. background: CursesColorNumberToColorName (background));
  141. }
  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. platformColor: 0,
  155. foreground: foreground,
  156. background: 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 Key MapCursesKey (int cursesKey)
  299. {
  300. switch (cursesKey) {
  301. case Curses.KeyF1: return Key.F1;
  302. case Curses.KeyF2: return Key.F2;
  303. case Curses.KeyF3: return Key.F3;
  304. case Curses.KeyF4: return Key.F4;
  305. case Curses.KeyF5: return Key.F5;
  306. case Curses.KeyF6: return Key.F6;
  307. case Curses.KeyF7: return Key.F7;
  308. case Curses.KeyF8: return Key.F8;
  309. case Curses.KeyF9: return Key.F9;
  310. case Curses.KeyF10: return Key.F10;
  311. case Curses.KeyF11: return Key.F11;
  312. case Curses.KeyF12: return Key.F12;
  313. case Curses.KeyUp: return Key.CursorUp;
  314. case Curses.KeyDown: return Key.CursorDown;
  315. case Curses.KeyLeft: return Key.CursorLeft;
  316. case Curses.KeyRight: return Key.CursorRight;
  317. case Curses.KeyHome: return Key.Home;
  318. case Curses.KeyEnd: return Key.End;
  319. case Curses.KeyNPage: return Key.PageDown;
  320. case Curses.KeyPPage: return Key.PageUp;
  321. case Curses.KeyDeleteChar: return Key.DeleteChar;
  322. case Curses.KeyInsertChar: return Key.InsertChar;
  323. case Curses.KeyTab: return Key.Tab;
  324. case Curses.KeyBackTab: return Key.BackTab;
  325. case Curses.KeyBackspace: return Key.Backspace;
  326. case Curses.ShiftKeyUp: return Key.CursorUp | Key.ShiftMask;
  327. case Curses.ShiftKeyDown: return Key.CursorDown | Key.ShiftMask;
  328. case Curses.ShiftKeyLeft: return Key.CursorLeft | Key.ShiftMask;
  329. case Curses.ShiftKeyRight: return Key.CursorRight | Key.ShiftMask;
  330. case Curses.ShiftKeyHome: return Key.Home | Key.ShiftMask;
  331. case Curses.ShiftKeyEnd: return Key.End | Key.ShiftMask;
  332. case Curses.ShiftKeyNPage: return Key.PageDown | Key.ShiftMask;
  333. case Curses.ShiftKeyPPage: return Key.PageUp | Key.ShiftMask;
  334. case Curses.AltKeyUp: return Key.CursorUp | Key.AltMask;
  335. case Curses.AltKeyDown: return Key.CursorDown | Key.AltMask;
  336. case Curses.AltKeyLeft: return Key.CursorLeft | Key.AltMask;
  337. case Curses.AltKeyRight: return Key.CursorRight | Key.AltMask;
  338. case Curses.AltKeyHome: return Key.Home | Key.AltMask;
  339. case Curses.AltKeyEnd: return Key.End | Key.AltMask;
  340. case Curses.AltKeyNPage: return Key.PageDown | Key.AltMask;
  341. case Curses.AltKeyPPage: return Key.PageUp | Key.AltMask;
  342. case Curses.CtrlKeyUp: return Key.CursorUp | Key.CtrlMask;
  343. case Curses.CtrlKeyDown: return Key.CursorDown | Key.CtrlMask;
  344. case Curses.CtrlKeyLeft: return Key.CursorLeft | Key.CtrlMask;
  345. case Curses.CtrlKeyRight: return Key.CursorRight | Key.CtrlMask;
  346. case Curses.CtrlKeyHome: return Key.Home | Key.CtrlMask;
  347. case Curses.CtrlKeyEnd: return Key.End | Key.CtrlMask;
  348. case Curses.CtrlKeyNPage: return Key.PageDown | Key.CtrlMask;
  349. case Curses.CtrlKeyPPage: return Key.PageUp | Key.CtrlMask;
  350. case Curses.ShiftCtrlKeyUp: return Key.CursorUp | Key.ShiftMask | Key.CtrlMask;
  351. case Curses.ShiftCtrlKeyDown: return Key.CursorDown | Key.ShiftMask | Key.CtrlMask;
  352. case Curses.ShiftCtrlKeyLeft: return Key.CursorLeft | Key.ShiftMask | Key.CtrlMask;
  353. case Curses.ShiftCtrlKeyRight: return Key.CursorRight | Key.ShiftMask | Key.CtrlMask;
  354. case Curses.ShiftCtrlKeyHome: return Key.Home | Key.ShiftMask | Key.CtrlMask;
  355. case Curses.ShiftCtrlKeyEnd: return Key.End | Key.ShiftMask | Key.CtrlMask;
  356. case Curses.ShiftCtrlKeyNPage: return Key.PageDown | Key.ShiftMask | Key.CtrlMask;
  357. case Curses.ShiftCtrlKeyPPage: return Key.PageUp | Key.ShiftMask | Key.CtrlMask;
  358. case Curses.ShiftAltKeyUp: return Key.CursorUp | Key.ShiftMask | Key.AltMask;
  359. case Curses.ShiftAltKeyDown: return Key.CursorDown | Key.ShiftMask | Key.AltMask;
  360. case Curses.ShiftAltKeyLeft: return Key.CursorLeft | Key.ShiftMask | Key.AltMask;
  361. case Curses.ShiftAltKeyRight: return Key.CursorRight | Key.ShiftMask | Key.AltMask;
  362. case Curses.ShiftAltKeyNPage: return Key.PageDown | Key.ShiftMask | Key.AltMask;
  363. case Curses.ShiftAltKeyPPage: return Key.PageUp | Key.ShiftMask | Key.AltMask;
  364. case Curses.ShiftAltKeyHome: return Key.Home | Key.ShiftMask | Key.AltMask;
  365. case Curses.ShiftAltKeyEnd: return Key.End | Key.ShiftMask | Key.AltMask;
  366. case Curses.AltCtrlKeyNPage: return Key.PageDown | Key.AltMask | Key.CtrlMask;
  367. case Curses.AltCtrlKeyPPage: return Key.PageUp | Key.AltMask | Key.CtrlMask;
  368. case Curses.AltCtrlKeyHome: return Key.Home | Key.AltMask | Key.CtrlMask;
  369. case Curses.AltCtrlKeyEnd: return Key.End | Key.AltMask | Key.CtrlMask;
  370. default: return Key.Unknown;
  371. }
  372. }
  373. KeyModifiers _keyModifiers;
  374. KeyModifiers MapKeyModifiers (Key key)
  375. {
  376. if (_keyModifiers == null) {
  377. _keyModifiers = new KeyModifiers ();
  378. }
  379. if (!_keyModifiers.Shift && (key & Key.ShiftMask) != 0) {
  380. _keyModifiers.Shift = true;
  381. }
  382. if (!_keyModifiers.Alt && (key & Key.AltMask) != 0) {
  383. _keyModifiers.Alt = true;
  384. }
  385. if (!_keyModifiers.Ctrl && (key & Key.CtrlMask) != 0) {
  386. _keyModifiers.Ctrl = true;
  387. }
  388. return _keyModifiers;
  389. }
  390. internal void ProcessInput ()
  391. {
  392. int wch;
  393. var code = Curses.get_wch (out wch);
  394. //System.Diagnostics.Debug.WriteLine ($"code: {code}; wch: {wch}");
  395. if (code == Curses.ERR) {
  396. return;
  397. }
  398. _keyModifiers = new KeyModifiers ();
  399. Key k = Key.Null;
  400. if (code == Curses.KEY_CODE_YES) {
  401. while (code == Curses.KEY_CODE_YES && wch == Curses.KeyResize) {
  402. ProcessWinChange ();
  403. code = Curses.get_wch (out wch);
  404. }
  405. if (wch == 0) {
  406. return;
  407. }
  408. if (wch == Curses.KeyMouse) {
  409. int wch2 = wch;
  410. while (wch2 == Curses.KeyMouse) {
  411. KeyEvent key = null;
  412. ConsoleKeyInfo [] cki = new ConsoleKeyInfo [] {
  413. new ConsoleKeyInfo ((char)Key.Esc, 0, false, false, false),
  414. new ConsoleKeyInfo ('[', 0, false, false, false),
  415. new ConsoleKeyInfo ('<', 0, false, false, false)
  416. };
  417. code = 0;
  418. HandleEscSeqResponse (ref code, ref k, ref wch2, ref key, ref cki);
  419. }
  420. return;
  421. }
  422. k = MapCursesKey (wch);
  423. if (wch >= 277 && wch <= 288) {
  424. // Shift+(F1 - F12)
  425. wch -= 12;
  426. k = Key.ShiftMask | MapCursesKey (wch);
  427. } else if (wch >= 289 && wch <= 300) {
  428. // Ctrl+(F1 - F12)
  429. wch -= 24;
  430. k = Key.CtrlMask | MapCursesKey (wch);
  431. } else if (wch >= 301 && wch <= 312) {
  432. // Ctrl+Shift+(F1 - F12)
  433. wch -= 36;
  434. k = Key.CtrlMask | Key.ShiftMask | MapCursesKey (wch);
  435. } else if (wch >= 313 && wch <= 324) {
  436. // Alt+(F1 - F12)
  437. wch -= 48;
  438. k = Key.AltMask | MapCursesKey (wch);
  439. } else if (wch >= 325 && wch <= 327) {
  440. // Shift+Alt+(F1 - F3)
  441. wch -= 60;
  442. k = Key.ShiftMask | Key.AltMask | MapCursesKey (wch);
  443. }
  444. OnKeyDown (new KeyEventEventArgs (new KeyEvent (k, MapKeyModifiers (k))));
  445. OnKeyUp (new KeyEventEventArgs (new KeyEvent (k, MapKeyModifiers (k))));
  446. OnKeyPressed (new KeyEventEventArgs (new KeyEvent (k, MapKeyModifiers (k))));
  447. return;
  448. }
  449. // Special handling for ESC, we want to try to catch ESC+letter to simulate alt-letter as well as Alt-Fkey
  450. if (wch == 27) {
  451. Curses.timeout (10);
  452. code = Curses.get_wch (out int wch2);
  453. if (code == Curses.KEY_CODE_YES) {
  454. k = Key.AltMask | MapCursesKey (wch);
  455. }
  456. if (code == 0) {
  457. KeyEvent key = null;
  458. // The ESC-number handling, debatable.
  459. // Simulates the AltMask itself by pressing Alt + Space.
  460. if (wch2 == (int)Key.Space) {
  461. k = Key.AltMask;
  462. } else if (wch2 - (int)Key.Space >= (uint)Key.A && wch2 - (int)Key.Space <= (uint)Key.Z) {
  463. k = (Key)((uint)Key.AltMask + (wch2 - (int)Key.Space));
  464. } else if (wch2 >= (uint)Key.A - 64 && wch2 <= (uint)Key.Z - 64) {
  465. k = (Key)((uint)(Key.AltMask | Key.CtrlMask) + (wch2 + 64));
  466. } else if (wch2 >= (uint)Key.D0 && wch2 <= (uint)Key.D9) {
  467. k = (Key)((uint)Key.AltMask + (uint)Key.D0 + (wch2 - (uint)Key.D0));
  468. } else if (wch2 == Curses.KeyCSI) {
  469. ConsoleKeyInfo [] cki = new ConsoleKeyInfo [] {
  470. new ConsoleKeyInfo ((char)Key.Esc, 0, false, false, false),
  471. new ConsoleKeyInfo ('[', 0, false, false, false)
  472. };
  473. HandleEscSeqResponse (ref code, ref k, ref wch2, ref key, ref cki);
  474. return;
  475. } else {
  476. // Unfortunately there are no way to differentiate Ctrl+Alt+alfa and Ctrl+Shift+Alt+alfa.
  477. if (((Key)wch2 & Key.CtrlMask) != 0) {
  478. _keyModifiers.Ctrl = true;
  479. }
  480. if (wch2 == 0) {
  481. k = Key.CtrlMask | Key.AltMask | Key.Space;
  482. } else if (wch >= (uint)Key.A && wch <= (uint)Key.Z) {
  483. _keyModifiers.Shift = true;
  484. _keyModifiers.Alt = true;
  485. } else if (wch2 < 256) {
  486. k = (Key)wch2;
  487. _keyModifiers.Alt = true;
  488. } else {
  489. k = (Key)((uint)(Key.AltMask | Key.CtrlMask) + wch2);
  490. }
  491. }
  492. key = new KeyEvent (k, MapKeyModifiers (k));
  493. OnKeyDown (new KeyEventEventArgs (key));
  494. OnKeyUp (new KeyEventEventArgs (key));
  495. OnKeyPressed (new KeyEventEventArgs (key));
  496. } else {
  497. k = Key.Esc;
  498. OnKeyPressed (new KeyEventEventArgs (new KeyEvent (k, MapKeyModifiers (k))));
  499. }
  500. } else if (wch == Curses.KeyTab) {
  501. k = MapCursesKey (wch);
  502. OnKeyDown (new KeyEventEventArgs (new KeyEvent (k, MapKeyModifiers (k))));
  503. OnKeyUp (new KeyEventEventArgs (new KeyEvent (k, MapKeyModifiers (k))));
  504. OnKeyPressed (new KeyEventEventArgs (new KeyEvent (k, MapKeyModifiers (k))));
  505. } else {
  506. // Unfortunately there are no way to differentiate Ctrl+alfa and Ctrl+Shift+alfa.
  507. k = (Key)wch;
  508. if (wch == 0) {
  509. k = Key.CtrlMask | Key.Space;
  510. } else if (wch >= (uint)Key.A - 64 && wch <= (uint)Key.Z - 64) {
  511. if ((Key)(wch + 64) != Key.J) {
  512. k = Key.CtrlMask | (Key)(wch + 64);
  513. }
  514. } else if (wch >= (uint)Key.A && wch <= (uint)Key.Z) {
  515. _keyModifiers.Shift = true;
  516. }
  517. OnKeyDown (new KeyEventEventArgs (new KeyEvent (k, MapKeyModifiers (k))));
  518. OnKeyUp (new KeyEventEventArgs (new KeyEvent (k, MapKeyModifiers (k))));
  519. OnKeyPressed (new KeyEventEventArgs (new KeyEvent (k, MapKeyModifiers (k))));
  520. }
  521. // Cause OnKeyUp and OnKeyPressed. Note that the special handling for ESC above
  522. // will not impact KeyUp.
  523. // This is causing ESC firing even if another keystroke was handled.
  524. //if (wch == Curses.KeyTab) {
  525. // keyUpHandler (new KeyEvent (MapCursesKey (wch), keyModifiers));
  526. //} else {
  527. // keyUpHandler (new KeyEvent ((Key)wch, keyModifiers));
  528. //}
  529. }
  530. void HandleEscSeqResponse (ref int code, ref Key k, ref int wch2, ref KeyEvent key, ref ConsoleKeyInfo [] cki)
  531. {
  532. ConsoleKey ck = 0;
  533. ConsoleModifiers mod = 0;
  534. while (code == 0) {
  535. code = Curses.get_wch (out wch2);
  536. var consoleKeyInfo = new ConsoleKeyInfo ((char)wch2, 0, false, false, false);
  537. if (wch2 == 0 || wch2 == 27 || wch2 == Curses.KeyMouse) {
  538. 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 _, ProcessMouseEvent);
  539. if (isKeyMouse) {
  540. foreach (var mf in mouseFlags) {
  541. ProcessMouseEvent (mf, pos);
  542. }
  543. cki = null;
  544. if (wch2 == 27) {
  545. cki = EscSeqUtils.ResizeArray (new ConsoleKeyInfo ((char)Key.Esc, 0,
  546. false, false, false), cki);
  547. }
  548. } else {
  549. k = ConsoleKeyMapping.MapConsoleKeyToKey (consoleKeyInfo.Key, out _);
  550. k = ConsoleKeyMapping.MapKeyModifiers (consoleKeyInfo, k);
  551. key = new KeyEvent (k, MapKeyModifiers (k));
  552. OnKeyDown (new KeyEventEventArgs (key));
  553. OnKeyPressed (new KeyEventEventArgs (key));
  554. }
  555. } else {
  556. cki = EscSeqUtils.ResizeArray (consoleKeyInfo, cki);
  557. }
  558. }
  559. }
  560. MouseFlags _lastMouseFlags;
  561. void ProcessMouseEvent (MouseFlags mouseFlag, Point pos)
  562. {
  563. bool WasButtonReleased (MouseFlags flag)
  564. {
  565. return flag.HasFlag (MouseFlags.Button1Released) ||
  566. flag.HasFlag (MouseFlags.Button2Released) ||
  567. flag.HasFlag (MouseFlags.Button3Released) ||
  568. flag.HasFlag (MouseFlags.Button4Released);
  569. }
  570. bool IsButtonNotPressed (MouseFlags flag)
  571. {
  572. return !flag.HasFlag (MouseFlags.Button1Pressed) &&
  573. !flag.HasFlag (MouseFlags.Button2Pressed) &&
  574. !flag.HasFlag (MouseFlags.Button3Pressed) &&
  575. !flag.HasFlag (MouseFlags.Button4Pressed);
  576. }
  577. bool IsButtonClickedOrDoubleClicked (MouseFlags flag)
  578. {
  579. return flag.HasFlag (MouseFlags.Button1Clicked) ||
  580. flag.HasFlag (MouseFlags.Button2Clicked) ||
  581. flag.HasFlag (MouseFlags.Button3Clicked) ||
  582. flag.HasFlag (MouseFlags.Button4Clicked) ||
  583. flag.HasFlag (MouseFlags.Button1DoubleClicked) ||
  584. flag.HasFlag (MouseFlags.Button2DoubleClicked) ||
  585. flag.HasFlag (MouseFlags.Button3DoubleClicked) ||
  586. flag.HasFlag (MouseFlags.Button4DoubleClicked);
  587. }
  588. if ((WasButtonReleased (mouseFlag) && IsButtonNotPressed (_lastMouseFlags)) ||
  589. (IsButtonClickedOrDoubleClicked (mouseFlag) && _lastMouseFlags == 0)) {
  590. return;
  591. }
  592. _lastMouseFlags = mouseFlag;
  593. var me = new MouseEvent () {
  594. Flags = mouseFlag,
  595. X = pos.X,
  596. Y = pos.Y
  597. };
  598. OnMouseEvent (new MouseEventEventArgs (me));
  599. }
  600. public static bool Is_WSL_Platform ()
  601. {
  602. // xclip does not work on WSL, so we need to use the Windows clipboard vis Powershell
  603. //if (new CursesClipboard ().IsSupported) {
  604. // // If xclip is installed on Linux under WSL, this will return true.
  605. // return false;
  606. //}
  607. var (exitCode, result) = ClipboardProcessRunner.Bash ("uname -a", waitForOutput: true);
  608. if (exitCode == 0 && result.Contains ("microsoft") && result.Contains ("WSL")) {
  609. return true;
  610. }
  611. return false;
  612. }
  613. public override void Suspend ()
  614. {
  615. StopReportingMouseMoves ();
  616. if (!RunningUnitTests) {
  617. Platform.Suspend ();
  618. Curses.Window.Standard.redrawwin ();
  619. Curses.refresh ();
  620. }
  621. StartReportingMouseMoves ();
  622. }
  623. public void StartReportingMouseMoves ()
  624. {
  625. if (!RunningUnitTests) {
  626. Console.Out.Write (EscSeqUtils.CSI_EnableMouseEvents);
  627. }
  628. }
  629. public void StopReportingMouseMoves ()
  630. {
  631. if (!RunningUnitTests) {
  632. Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents);
  633. }
  634. }
  635. /// <inheritdoc/>
  636. public override bool GetCursorVisibility (out CursorVisibility visibility)
  637. {
  638. visibility = CursorVisibility.Invisible;
  639. if (!_currentCursorVisibility.HasValue)
  640. return false;
  641. visibility = _currentCursorVisibility.Value;
  642. return true;
  643. }
  644. /// <inheritdoc/>
  645. public override bool SetCursorVisibility (CursorVisibility visibility)
  646. {
  647. if (_initialCursorVisibility.HasValue == false) {
  648. return false;
  649. }
  650. if (!RunningUnitTests) {
  651. Curses.curs_set (((int)visibility >> 16) & 0x000000FF);
  652. }
  653. if (visibility != CursorVisibility.Invisible) {
  654. Console.Out.Write (EscSeqUtils.CSI_SetCursorStyle ((EscSeqUtils.DECSCUSR_Style)(((int)visibility >> 24) & 0xFF)));
  655. }
  656. _currentCursorVisibility = visibility;
  657. return true;
  658. }
  659. /// <inheritdoc/>
  660. public override bool EnsureCursorVisibility ()
  661. {
  662. return false;
  663. }
  664. public override void SendKeys (char keyChar, ConsoleKey consoleKey, bool shift, bool alt, bool control)
  665. {
  666. Key key;
  667. if (consoleKey == ConsoleKey.Packet) {
  668. ConsoleModifiers mod = new ConsoleModifiers ();
  669. if (shift) {
  670. mod |= ConsoleModifiers.Shift;
  671. }
  672. if (alt) {
  673. mod |= ConsoleModifiers.Alt;
  674. }
  675. if (control) {
  676. mod |= ConsoleModifiers.Control;
  677. }
  678. var kchar = ConsoleKeyMapping.GetKeyCharFromConsoleKey (keyChar, mod, out uint ckey, out _);
  679. key = ConsoleKeyMapping.MapConsoleKeyToKey ((ConsoleKey)ckey, out bool mappable);
  680. if (mappable) {
  681. key = (Key)kchar;
  682. }
  683. } else {
  684. key = (Key)keyChar;
  685. }
  686. KeyModifiers km = new KeyModifiers ();
  687. if (shift) {
  688. if (keyChar == 0) {
  689. key |= Key.ShiftMask;
  690. }
  691. km.Shift = shift;
  692. }
  693. if (alt) {
  694. key |= Key.AltMask;
  695. km.Alt = alt;
  696. }
  697. if (control) {
  698. key |= Key.CtrlMask;
  699. km.Ctrl = control;
  700. }
  701. OnKeyDown (new KeyEventEventArgs (new KeyEvent (key, km)));
  702. OnKeyPressed (new KeyEventEventArgs (new KeyEvent (key, km)));
  703. OnKeyUp (new KeyEventEventArgs (new KeyEvent (key, km)));
  704. }
  705. }
  706. internal static class Platform {
  707. [DllImport ("libc")]
  708. static extern int uname (IntPtr buf);
  709. [DllImport ("libc")]
  710. static extern int killpg (int pgrp, int pid);
  711. static int _suspendSignal;
  712. static int GetSuspendSignal ()
  713. {
  714. if (_suspendSignal != 0) {
  715. return _suspendSignal;
  716. }
  717. IntPtr buf = Marshal.AllocHGlobal (8192);
  718. if (uname (buf) != 0) {
  719. Marshal.FreeHGlobal (buf);
  720. _suspendSignal = -1;
  721. return _suspendSignal;
  722. }
  723. try {
  724. switch (Marshal.PtrToStringAnsi (buf)) {
  725. case "Darwin":
  726. case "DragonFly":
  727. case "FreeBSD":
  728. case "NetBSD":
  729. case "OpenBSD":
  730. _suspendSignal = 18;
  731. break;
  732. case "Linux":
  733. // TODO: should fetch the machine name and
  734. // if it is MIPS return 24
  735. _suspendSignal = 20;
  736. break;
  737. case "Solaris":
  738. _suspendSignal = 24;
  739. break;
  740. default:
  741. _suspendSignal = -1;
  742. break;
  743. }
  744. return _suspendSignal;
  745. } finally {
  746. Marshal.FreeHGlobal (buf);
  747. }
  748. }
  749. /// <summary>
  750. /// Suspends the process by sending SIGTSTP to itself
  751. /// </summary>
  752. /// <returns>The suspend.</returns>
  753. static public bool Suspend ()
  754. {
  755. int signal = GetSuspendSignal ();
  756. if (signal == -1) {
  757. return false;
  758. }
  759. killpg (0, signal);
  760. return true;
  761. }
  762. }