CursesDriver.cs 26 KB

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