CursesDriver.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  1. // TODO: #nullable enable
  2. //
  3. // Driver.cs: Curses-based Driver
  4. //
  5. using System.Diagnostics;
  6. using System.Runtime.InteropServices;
  7. using Terminal.Gui.ConsoleDrivers;
  8. using Unix.Terminal;
  9. namespace Terminal.Gui;
  10. /// <summary>A Linux/Mac driver based on the Curses libary.</summary>
  11. internal class CursesDriver : ConsoleDriver
  12. {
  13. public override string GetVersionInfo () { return $"{Curses.curses_version ()}"; }
  14. public override void Refresh ()
  15. {
  16. UpdateScreen ();
  17. UpdateCursor ();
  18. }
  19. public override void Suspend ()
  20. {
  21. StopReportingMouseMoves ();
  22. if (!RunningUnitTests)
  23. {
  24. Platform.Suspend ();
  25. if (Force16Colors)
  26. {
  27. Curses.Window.Standard.redrawwin ();
  28. Curses.refresh ();
  29. }
  30. }
  31. StartReportingMouseMoves ();
  32. }
  33. #region Screen and Contents
  34. public override int Cols
  35. {
  36. get => Curses.Cols;
  37. internal set
  38. {
  39. Curses.Cols = value;
  40. ClearContents ();
  41. }
  42. }
  43. public override int Rows
  44. {
  45. get => Curses.Lines;
  46. internal set
  47. {
  48. Curses.Lines = value;
  49. ClearContents ();
  50. }
  51. }
  52. public override bool IsRuneSupported (Rune rune)
  53. {
  54. // See Issue #2615 - CursesDriver is broken with non-BMP characters
  55. return base.IsRuneSupported (rune) && rune.IsBmp;
  56. }
  57. public override void Move (int col, int row)
  58. {
  59. base.Move (col, row);
  60. if (RunningUnitTests)
  61. {
  62. return;
  63. }
  64. if (IsValidLocation (col, row))
  65. {
  66. Curses.move (row, col);
  67. }
  68. else
  69. {
  70. // Not a valid location (outside screen or clip region)
  71. // Move within the clip region, then AddRune will actually move to Col, Row
  72. Curses.move (Clip.Y, Clip.X);
  73. }
  74. }
  75. public override void UpdateScreen ()
  76. {
  77. if (Force16Colors)
  78. {
  79. for (var row = 0; row < Rows; row++)
  80. {
  81. if (!_dirtyLines [row])
  82. {
  83. continue;
  84. }
  85. _dirtyLines [row] = false;
  86. for (var col = 0; col < Cols; col++)
  87. {
  88. if (Contents [row, col].IsDirty == false)
  89. {
  90. continue;
  91. }
  92. if (RunningUnitTests)
  93. {
  94. // In unit tests, we don't want to actually write to the screen.
  95. continue;
  96. }
  97. Curses.attrset (Contents [row, col].Attribute.GetValueOrDefault ().PlatformColor);
  98. Rune rune = Contents [row, col].Rune;
  99. if (rune.IsBmp)
  100. {
  101. // 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.
  102. if (rune.GetColumns () < 2)
  103. {
  104. Curses.mvaddch (row, col, rune.Value);
  105. }
  106. else /*if (col + 1 < Cols)*/
  107. {
  108. Curses.mvaddwstr (row, col, rune.ToString ());
  109. }
  110. }
  111. else
  112. {
  113. Curses.mvaddwstr (row, col, rune.ToString ());
  114. if (rune.GetColumns () > 1 && col + 1 < Cols)
  115. {
  116. // TODO: This is a hack to deal with non-BMP and wide characters.
  117. //col++;
  118. Curses.mvaddch (row, ++col, '*');
  119. }
  120. }
  121. }
  122. }
  123. if (!RunningUnitTests)
  124. {
  125. Curses.move (Row, Col);
  126. _window.wrefresh ();
  127. }
  128. }
  129. else
  130. {
  131. if (RunningUnitTests
  132. || Console.WindowHeight < 1
  133. || Contents.Length != Rows * Cols
  134. || Rows != Console.WindowHeight)
  135. {
  136. return;
  137. }
  138. var top = 0;
  139. var left = 0;
  140. int rows = Rows;
  141. int cols = Cols;
  142. var output = new StringBuilder ();
  143. Attribute? redrawAttr = null;
  144. int lastCol = -1;
  145. CursorVisibility? savedVisibility = _currentCursorVisibility;
  146. SetCursorVisibility (CursorVisibility.Invisible);
  147. for (int row = top; row < rows; row++)
  148. {
  149. if (Console.WindowHeight < 1)
  150. {
  151. return;
  152. }
  153. if (!_dirtyLines [row])
  154. {
  155. continue;
  156. }
  157. if (!SetCursorPosition (0, row))
  158. {
  159. return;
  160. }
  161. _dirtyLines [row] = false;
  162. output.Clear ();
  163. for (int col = left; col < cols; col++)
  164. {
  165. lastCol = -1;
  166. var outputWidth = 0;
  167. for (; col < cols; col++)
  168. {
  169. if (!Contents [row, col].IsDirty)
  170. {
  171. if (output.Length > 0)
  172. {
  173. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  174. }
  175. else if (lastCol == -1)
  176. {
  177. lastCol = col;
  178. }
  179. if (lastCol + 1 < cols)
  180. {
  181. lastCol++;
  182. }
  183. continue;
  184. }
  185. if (lastCol == -1)
  186. {
  187. lastCol = col;
  188. }
  189. Attribute attr = Contents [row, col].Attribute.Value;
  190. // Performance: Only send the escape sequence if the attribute has changed.
  191. if (attr != redrawAttr)
  192. {
  193. redrawAttr = attr;
  194. output.Append (
  195. AnsiEscapeSequenceRequestUtils.CSI_SetForegroundColorRGB (
  196. attr.Foreground.R,
  197. attr.Foreground.G,
  198. attr.Foreground.B
  199. )
  200. );
  201. output.Append (
  202. AnsiEscapeSequenceRequestUtils.CSI_SetBackgroundColorRGB (
  203. attr.Background.R,
  204. attr.Background.G,
  205. attr.Background.B
  206. )
  207. );
  208. }
  209. outputWidth++;
  210. Rune rune = Contents [row, col].Rune;
  211. output.Append (rune);
  212. if (Contents [row, col].CombiningMarks.Count > 0)
  213. {
  214. // AtlasEngine does not support NON-NORMALIZED combining marks in a way
  215. // compatible with the driver architecture. Any CMs (except in the first col)
  216. // are correctly combined with the base char, but are ALSO treated as 1 column
  217. // width codepoints E.g. `echo "[e`u{0301}`u{0301}]"` will output `[é ]`.
  218. //
  219. // For now, we just ignore the list of CMs.
  220. //foreach (var combMark in Contents [row, col].CombiningMarks) {
  221. // output.Append (combMark);
  222. //}
  223. // WriteToConsole (output, ref lastCol, row, ref outputWidth);
  224. }
  225. else if (rune.IsSurrogatePair () && rune.GetColumns () < 2)
  226. {
  227. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  228. SetCursorPosition (col - 1, row);
  229. }
  230. Contents [row, col].IsDirty = false;
  231. }
  232. }
  233. if (output.Length > 0)
  234. {
  235. SetCursorPosition (lastCol, row);
  236. Console.Write (output);
  237. }
  238. }
  239. // SIXELS
  240. foreach (SixelToRender s in Application.Sixel)
  241. {
  242. SetCursorPosition (s.ScreenPosition.X, s.ScreenPosition.Y);
  243. Console.Write (s.SixelData);
  244. }
  245. SetCursorPosition (0, 0);
  246. _currentCursorVisibility = savedVisibility;
  247. void WriteToConsole (StringBuilder output, ref int lastCol, int row, ref int outputWidth)
  248. {
  249. SetCursorPosition (lastCol, row);
  250. Console.Write (output);
  251. output.Clear ();
  252. lastCol += outputWidth;
  253. outputWidth = 0;
  254. }
  255. }
  256. }
  257. #endregion Screen and Contents
  258. #region Color Handling
  259. public override bool SupportsTrueColor => true;
  260. /// <summary>Creates an Attribute from the provided curses-based foreground and background color numbers</summary>
  261. /// <param name="foreground">Contains the curses color number for the foreground (color, plus any attributes)</param>
  262. /// <param name="background">Contains the curses color number for the background (color, plus any attributes)</param>
  263. /// <returns></returns>
  264. private static Attribute MakeColor (short foreground, short background)
  265. {
  266. //var v = (short)((ushort)foreground | (background << 4));
  267. var v = (short)(((ushort)(foreground & 0xffff) << 16) | (background & 0xffff));
  268. // TODO: for TrueColor - Use InitExtendedPair
  269. Curses.InitColorPair (v, foreground, background);
  270. return new (
  271. Curses.ColorPair (v),
  272. CursesColorNumberToColorName16 (foreground),
  273. CursesColorNumberToColorName16 (background)
  274. );
  275. }
  276. /// <inheritdoc/>
  277. /// <remarks>
  278. /// In the CursesDriver, colors are encoded as an int. The foreground color is stored in the most significant 4
  279. /// bits, and the background color is stored in the least significant 4 bits. The Terminal.GUi Color values are
  280. /// converted to curses color encoding before being encoded.
  281. /// </remarks>
  282. public override Attribute MakeColor (in Color foreground, in Color background)
  283. {
  284. if (!RunningUnitTests && Force16Colors)
  285. {
  286. return MakeColor (
  287. ColorNameToCursesColorNumber (foreground.GetClosestNamedColor16 ()),
  288. ColorNameToCursesColorNumber (background.GetClosestNamedColor16 ())
  289. );
  290. }
  291. return new (
  292. 0,
  293. foreground,
  294. background
  295. );
  296. }
  297. private static short ColorNameToCursesColorNumber (ColorName16 color)
  298. {
  299. switch (color)
  300. {
  301. case ColorName16.Black:
  302. return Curses.COLOR_BLACK;
  303. case ColorName16.Blue:
  304. return Curses.COLOR_BLUE;
  305. case ColorName16.Green:
  306. return Curses.COLOR_GREEN;
  307. case ColorName16.Cyan:
  308. return Curses.COLOR_CYAN;
  309. case ColorName16.Red:
  310. return Curses.COLOR_RED;
  311. case ColorName16.Magenta:
  312. return Curses.COLOR_MAGENTA;
  313. case ColorName16.Yellow:
  314. return Curses.COLOR_YELLOW;
  315. case ColorName16.Gray:
  316. return Curses.COLOR_WHITE;
  317. case ColorName16.DarkGray:
  318. return Curses.COLOR_GRAY;
  319. case ColorName16.BrightBlue:
  320. return Curses.COLOR_BLUE | Curses.COLOR_GRAY;
  321. case ColorName16.BrightGreen:
  322. return Curses.COLOR_GREEN | Curses.COLOR_GRAY;
  323. case ColorName16.BrightCyan:
  324. return Curses.COLOR_CYAN | Curses.COLOR_GRAY;
  325. case ColorName16.BrightRed:
  326. return Curses.COLOR_RED | Curses.COLOR_GRAY;
  327. case ColorName16.BrightMagenta:
  328. return Curses.COLOR_MAGENTA | Curses.COLOR_GRAY;
  329. case ColorName16.BrightYellow:
  330. return Curses.COLOR_YELLOW | Curses.COLOR_GRAY;
  331. case ColorName16.White:
  332. return Curses.COLOR_WHITE | Curses.COLOR_GRAY;
  333. }
  334. throw new ArgumentException ("Invalid color code");
  335. }
  336. private static ColorName16 CursesColorNumberToColorName16 (short color)
  337. {
  338. switch (color)
  339. {
  340. case Curses.COLOR_BLACK:
  341. return ColorName16.Black;
  342. case Curses.COLOR_BLUE:
  343. return ColorName16.Blue;
  344. case Curses.COLOR_GREEN:
  345. return ColorName16.Green;
  346. case Curses.COLOR_CYAN:
  347. return ColorName16.Cyan;
  348. case Curses.COLOR_RED:
  349. return ColorName16.Red;
  350. case Curses.COLOR_MAGENTA:
  351. return ColorName16.Magenta;
  352. case Curses.COLOR_YELLOW:
  353. return ColorName16.Yellow;
  354. case Curses.COLOR_WHITE:
  355. return ColorName16.Gray;
  356. case Curses.COLOR_GRAY:
  357. return ColorName16.DarkGray;
  358. case Curses.COLOR_BLUE | Curses.COLOR_GRAY:
  359. return ColorName16.BrightBlue;
  360. case Curses.COLOR_GREEN | Curses.COLOR_GRAY:
  361. return ColorName16.BrightGreen;
  362. case Curses.COLOR_CYAN | Curses.COLOR_GRAY:
  363. return ColorName16.BrightCyan;
  364. case Curses.COLOR_RED | Curses.COLOR_GRAY:
  365. return ColorName16.BrightRed;
  366. case Curses.COLOR_MAGENTA | Curses.COLOR_GRAY:
  367. return ColorName16.BrightMagenta;
  368. case Curses.COLOR_YELLOW | Curses.COLOR_GRAY:
  369. return ColorName16.BrightYellow;
  370. case Curses.COLOR_WHITE | Curses.COLOR_GRAY:
  371. return ColorName16.White;
  372. }
  373. throw new ArgumentException ("Invalid curses color code");
  374. }
  375. #endregion
  376. #region Cursor Support
  377. private CursorVisibility? _currentCursorVisibility;
  378. private CursorVisibility? _initialCursorVisibility;
  379. /// <inheritdoc/>
  380. public override bool EnsureCursorVisibility ()
  381. {
  382. if (!(Col >= 0 && Row >= 0 && Col < Cols && Row < Rows))
  383. {
  384. GetCursorVisibility (out CursorVisibility cursorVisibility);
  385. _currentCursorVisibility = cursorVisibility;
  386. SetCursorVisibility (CursorVisibility.Invisible);
  387. return false;
  388. }
  389. SetCursorVisibility (_currentCursorVisibility ?? CursorVisibility.Default);
  390. return _currentCursorVisibility == CursorVisibility.Default;
  391. }
  392. /// <inheritdoc/>
  393. public override bool GetCursorVisibility (out CursorVisibility visibility)
  394. {
  395. visibility = CursorVisibility.Invisible;
  396. if (!_currentCursorVisibility.HasValue)
  397. {
  398. return false;
  399. }
  400. visibility = _currentCursorVisibility.Value;
  401. return true;
  402. }
  403. /// <inheritdoc/>
  404. public override bool SetCursorVisibility (CursorVisibility visibility)
  405. {
  406. if (_initialCursorVisibility.HasValue == false)
  407. {
  408. return false;
  409. }
  410. if (!RunningUnitTests)
  411. {
  412. Curses.curs_set (((int)visibility >> 16) & 0x000000FF);
  413. }
  414. if (visibility != CursorVisibility.Invisible)
  415. {
  416. Console.Out.Write (
  417. AnsiEscapeSequenceRequestUtils.CSI_SetCursorStyle (
  418. (AnsiEscapeSequenceRequestUtils.DECSCUSR_Style)(((int)visibility >> 24)
  419. & 0xFF)
  420. )
  421. );
  422. }
  423. _currentCursorVisibility = visibility;
  424. return true;
  425. }
  426. public override void UpdateCursor ()
  427. {
  428. EnsureCursorVisibility ();
  429. if (!RunningUnitTests && Col >= 0 && Col < Cols && Row >= 0 && Row < Rows)
  430. {
  431. if (Force16Colors)
  432. {
  433. Curses.move (Row, Col);
  434. Curses.raw ();
  435. Curses.noecho ();
  436. Curses.refresh ();
  437. }
  438. else
  439. {
  440. _mainLoopDriver.WriteRaw (AnsiEscapeSequenceRequestUtils.CSI_SetCursorPosition (Row + 1, Col + 1));
  441. }
  442. }
  443. }
  444. #endregion Cursor Support
  445. #region Keyboard Support
  446. public override void SendKeys (char keyChar, ConsoleKey consoleKey, bool shift, bool alt, bool control)
  447. {
  448. KeyCode key;
  449. if (consoleKey == ConsoleKey.Packet)
  450. {
  451. var mod = new ConsoleModifiers ();
  452. if (shift)
  453. {
  454. mod |= ConsoleModifiers.Shift;
  455. }
  456. if (alt)
  457. {
  458. mod |= ConsoleModifiers.Alt;
  459. }
  460. if (control)
  461. {
  462. mod |= ConsoleModifiers.Control;
  463. }
  464. var cKeyInfo = new ConsoleKeyInfo (keyChar, consoleKey, shift, alt, control);
  465. cKeyInfo = ConsoleKeyMapping.DecodeVKPacketToKConsoleKeyInfo (cKeyInfo);
  466. key = ConsoleKeyMapping.MapConsoleKeyInfoToKeyCode (cKeyInfo);
  467. }
  468. else
  469. {
  470. key = (KeyCode)keyChar;
  471. }
  472. OnKeyDown (new (key));
  473. OnKeyUp (new (key));
  474. //OnKeyPressed (new KeyEventArgsEventArgs (key));
  475. }
  476. // TODO: Unused- Remove
  477. private static KeyCode MapCursesKey (int cursesKey)
  478. {
  479. switch (cursesKey)
  480. {
  481. case Curses.KeyF1: return KeyCode.F1;
  482. case Curses.KeyF2: return KeyCode.F2;
  483. case Curses.KeyF3: return KeyCode.F3;
  484. case Curses.KeyF4: return KeyCode.F4;
  485. case Curses.KeyF5: return KeyCode.F5;
  486. case Curses.KeyF6: return KeyCode.F6;
  487. case Curses.KeyF7: return KeyCode.F7;
  488. case Curses.KeyF8: return KeyCode.F8;
  489. case Curses.KeyF9: return KeyCode.F9;
  490. case Curses.KeyF10: return KeyCode.F10;
  491. case Curses.KeyF11: return KeyCode.F11;
  492. case Curses.KeyF12: return KeyCode.F12;
  493. case Curses.KeyUp: return KeyCode.CursorUp;
  494. case Curses.KeyDown: return KeyCode.CursorDown;
  495. case Curses.KeyLeft: return KeyCode.CursorLeft;
  496. case Curses.KeyRight: return KeyCode.CursorRight;
  497. case Curses.KeyHome: return KeyCode.Home;
  498. case Curses.KeyEnd: return KeyCode.End;
  499. case Curses.KeyNPage: return KeyCode.PageDown;
  500. case Curses.KeyPPage: return KeyCode.PageUp;
  501. case Curses.KeyDeleteChar: return KeyCode.Delete;
  502. case Curses.KeyInsertChar: return KeyCode.Insert;
  503. case Curses.KeyTab: return KeyCode.Tab;
  504. case Curses.KeyBackTab: return KeyCode.Tab | KeyCode.ShiftMask;
  505. case Curses.KeyBackspace: return KeyCode.Backspace;
  506. case Curses.ShiftKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask;
  507. case Curses.ShiftKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask;
  508. case Curses.ShiftKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask;
  509. case Curses.ShiftKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask;
  510. case Curses.ShiftKeyHome: return KeyCode.Home | KeyCode.ShiftMask;
  511. case Curses.ShiftKeyEnd: return KeyCode.End | KeyCode.ShiftMask;
  512. case Curses.ShiftKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask;
  513. case Curses.ShiftKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask;
  514. case Curses.AltKeyUp: return KeyCode.CursorUp | KeyCode.AltMask;
  515. case Curses.AltKeyDown: return KeyCode.CursorDown | KeyCode.AltMask;
  516. case Curses.AltKeyLeft: return KeyCode.CursorLeft | KeyCode.AltMask;
  517. case Curses.AltKeyRight: return KeyCode.CursorRight | KeyCode.AltMask;
  518. case Curses.AltKeyHome: return KeyCode.Home | KeyCode.AltMask;
  519. case Curses.AltKeyEnd: return KeyCode.End | KeyCode.AltMask;
  520. case Curses.AltKeyNPage: return KeyCode.PageDown | KeyCode.AltMask;
  521. case Curses.AltKeyPPage: return KeyCode.PageUp | KeyCode.AltMask;
  522. case Curses.CtrlKeyUp: return KeyCode.CursorUp | KeyCode.CtrlMask;
  523. case Curses.CtrlKeyDown: return KeyCode.CursorDown | KeyCode.CtrlMask;
  524. case Curses.CtrlKeyLeft: return KeyCode.CursorLeft | KeyCode.CtrlMask;
  525. case Curses.CtrlKeyRight: return KeyCode.CursorRight | KeyCode.CtrlMask;
  526. case Curses.CtrlKeyHome: return KeyCode.Home | KeyCode.CtrlMask;
  527. case Curses.CtrlKeyEnd: return KeyCode.End | KeyCode.CtrlMask;
  528. case Curses.CtrlKeyNPage: return KeyCode.PageDown | KeyCode.CtrlMask;
  529. case Curses.CtrlKeyPPage: return KeyCode.PageUp | KeyCode.CtrlMask;
  530. case Curses.ShiftCtrlKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask | KeyCode.CtrlMask;
  531. case Curses.ShiftCtrlKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask | KeyCode.CtrlMask;
  532. case Curses.ShiftCtrlKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask | KeyCode.CtrlMask;
  533. case Curses.ShiftCtrlKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask | KeyCode.CtrlMask;
  534. case Curses.ShiftCtrlKeyHome: return KeyCode.Home | KeyCode.ShiftMask | KeyCode.CtrlMask;
  535. case Curses.ShiftCtrlKeyEnd: return KeyCode.End | KeyCode.ShiftMask | KeyCode.CtrlMask;
  536. case Curses.ShiftCtrlKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask | KeyCode.CtrlMask;
  537. case Curses.ShiftCtrlKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask | KeyCode.CtrlMask;
  538. case Curses.ShiftAltKeyUp: return KeyCode.CursorUp | KeyCode.ShiftMask | KeyCode.AltMask;
  539. case Curses.ShiftAltKeyDown: return KeyCode.CursorDown | KeyCode.ShiftMask | KeyCode.AltMask;
  540. case Curses.ShiftAltKeyLeft: return KeyCode.CursorLeft | KeyCode.ShiftMask | KeyCode.AltMask;
  541. case Curses.ShiftAltKeyRight: return KeyCode.CursorRight | KeyCode.ShiftMask | KeyCode.AltMask;
  542. case Curses.ShiftAltKeyNPage: return KeyCode.PageDown | KeyCode.ShiftMask | KeyCode.AltMask;
  543. case Curses.ShiftAltKeyPPage: return KeyCode.PageUp | KeyCode.ShiftMask | KeyCode.AltMask;
  544. case Curses.ShiftAltKeyHome: return KeyCode.Home | KeyCode.ShiftMask | KeyCode.AltMask;
  545. case Curses.ShiftAltKeyEnd: return KeyCode.End | KeyCode.ShiftMask | KeyCode.AltMask;
  546. case Curses.AltCtrlKeyNPage: return KeyCode.PageDown | KeyCode.AltMask | KeyCode.CtrlMask;
  547. case Curses.AltCtrlKeyPPage: return KeyCode.PageUp | KeyCode.AltMask | KeyCode.CtrlMask;
  548. case Curses.AltCtrlKeyHome: return KeyCode.Home | KeyCode.AltMask | KeyCode.CtrlMask;
  549. case Curses.AltCtrlKeyEnd: return KeyCode.End | KeyCode.AltMask | KeyCode.CtrlMask;
  550. default: return KeyCode.Null;
  551. }
  552. }
  553. #endregion Keyboard Support
  554. #region Mouse Support
  555. public void StartReportingMouseMoves ()
  556. {
  557. if (!RunningUnitTests)
  558. {
  559. Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_EnableMouseEvents);
  560. }
  561. }
  562. public void StopReportingMouseMoves ()
  563. {
  564. if (!RunningUnitTests)
  565. {
  566. Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_DisableMouseEvents);
  567. }
  568. }
  569. #endregion Mouse Support
  570. private bool SetCursorPosition (int col, int row)
  571. {
  572. // + 1 is needed because non-Windows is based on 1 instead of 0 and
  573. // Console.CursorTop/CursorLeft isn't reliable.
  574. Console.Out.Write (AnsiEscapeSequenceRequestUtils.CSI_SetCursorPosition (row + 1, col + 1));
  575. return true;
  576. }
  577. #region Init/End/MainLoop
  578. public Curses.Window _window;
  579. private UnixMainLoop _mainLoopDriver;
  580. internal override MainLoop Init ()
  581. {
  582. _mainLoopDriver = new (this);
  583. if (!RunningUnitTests)
  584. {
  585. _window = Curses.initscr ();
  586. Curses.set_escdelay (10);
  587. // Ensures that all procedures are performed at some previous closing.
  588. Curses.doupdate ();
  589. //
  590. // We are setting Invisible as default, so we could ignore XTerm DECSUSR setting
  591. //
  592. switch (Curses.curs_set (0))
  593. {
  594. case 0:
  595. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Invisible;
  596. break;
  597. case 1:
  598. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Underline;
  599. Curses.curs_set (1);
  600. break;
  601. case 2:
  602. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Box;
  603. Curses.curs_set (2);
  604. break;
  605. default:
  606. _currentCursorVisibility = _initialCursorVisibility = null;
  607. break;
  608. }
  609. if (!Curses.HasColors)
  610. {
  611. throw new InvalidOperationException ("V2 - This should never happen. File an Issue if it does.");
  612. }
  613. Curses.raw ();
  614. Curses.noecho ();
  615. Curses.Window.Standard.keypad (true);
  616. Curses.StartColor ();
  617. Curses.UseDefaultColors ();
  618. if (!RunningUnitTests)
  619. {
  620. Curses.timeout (0);
  621. }
  622. }
  623. CurrentAttribute = new (ColorName16.White, ColorName16.Black);
  624. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  625. {
  626. Clipboard = new FakeDriver.FakeClipboard ();
  627. }
  628. else
  629. {
  630. if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX))
  631. {
  632. Clipboard = new MacOSXClipboard ();
  633. }
  634. else
  635. {
  636. if (Is_WSL_Platform ())
  637. {
  638. Clipboard = new WSLClipboard ();
  639. }
  640. else
  641. {
  642. Clipboard = new CursesClipboard ();
  643. }
  644. }
  645. }
  646. ClearContents ();
  647. StartReportingMouseMoves ();
  648. if (!RunningUnitTests)
  649. {
  650. Curses.CheckWinChange ();
  651. ClearContents ();
  652. if (Force16Colors)
  653. {
  654. Curses.refresh ();
  655. }
  656. }
  657. return new (_mainLoopDriver);
  658. }
  659. internal void ProcessInput (UnixMainLoop.PollData inputEvent)
  660. {
  661. switch (inputEvent.EventType)
  662. {
  663. case UnixMainLoop.EventType.Key:
  664. ConsoleKeyInfo consoleKeyInfo = inputEvent.KeyEvent;
  665. KeyCode map = AnsiEscapeSequenceRequestUtils.MapKey (consoleKeyInfo);
  666. if (map == KeyCode.Null)
  667. {
  668. break;
  669. }
  670. OnKeyDown (new (map));
  671. OnKeyUp (new (map));
  672. break;
  673. case UnixMainLoop.EventType.Mouse:
  674. var me = new MouseEventArgs { Position = inputEvent.MouseEvent.Position, Flags = inputEvent.MouseEvent.MouseFlags };
  675. OnMouseEvent (me);
  676. break;
  677. case UnixMainLoop.EventType.WindowSize:
  678. Size size = new (inputEvent.WindowSizeEvent.Size.Width, inputEvent.WindowSizeEvent.Size.Height);
  679. ProcessWinChange (inputEvent.WindowSizeEvent.Size);
  680. break;
  681. default:
  682. throw new ArgumentOutOfRangeException ();
  683. }
  684. }
  685. private void ProcessWinChange (Size size)
  686. {
  687. if (!RunningUnitTests && Curses.ChangeWindowSize (size.Height, size.Width))
  688. {
  689. ClearContents ();
  690. OnSizeChanged (new (new (Cols, Rows)));
  691. }
  692. }
  693. internal override void End ()
  694. {
  695. _ansiResponseTokenSource?.Cancel ();
  696. _ansiResponseTokenSource?.Dispose ();
  697. _waitAnsiResponse?.Dispose ();
  698. StopReportingMouseMoves ();
  699. SetCursorVisibility (CursorVisibility.Default);
  700. if (RunningUnitTests)
  701. {
  702. return;
  703. }
  704. // throws away any typeahead that has been typed by
  705. // the user and has not yet been read by the program.
  706. Curses.flushinp ();
  707. Curses.endwin ();
  708. }
  709. #endregion Init/End/MainLoop
  710. public static bool Is_WSL_Platform ()
  711. {
  712. // xclip does not work on WSL, so we need to use the Windows clipboard vis Powershell
  713. //if (new CursesClipboard ().IsSupported) {
  714. // // If xclip is installed on Linux under WSL, this will return true.
  715. // return false;
  716. //}
  717. (int exitCode, string result) = ClipboardProcessRunner.Bash ("uname -a", waitForOutput: true);
  718. if (exitCode == 0 && result.Contains ("microsoft") && result.Contains ("WSL"))
  719. {
  720. return true;
  721. }
  722. return false;
  723. }
  724. #region Low-Level Unix Stuff
  725. private readonly ManualResetEventSlim _waitAnsiResponse = new (false);
  726. private readonly CancellationTokenSource _ansiResponseTokenSource = new ();
  727. /// <inheritdoc/>
  728. public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest)
  729. {
  730. if (_mainLoopDriver is null)
  731. {
  732. return string.Empty;
  733. }
  734. try
  735. {
  736. lock (ansiRequest._responseLock)
  737. {
  738. ansiRequest.ResponseFromInput += (s, e) =>
  739. {
  740. Debug.Assert (s == ansiRequest);
  741. Debug.Assert (e == ansiRequest.Response);
  742. _waitAnsiResponse.Set ();
  743. };
  744. _mainLoopDriver.EscSeqRequests.Add (ansiRequest, this);
  745. _mainLoopDriver._forceRead = true;
  746. }
  747. if (!_ansiResponseTokenSource.IsCancellationRequested)
  748. {
  749. _mainLoopDriver._waitForInput.Set ();
  750. _waitAnsiResponse.Wait (_ansiResponseTokenSource.Token);
  751. }
  752. }
  753. catch (OperationCanceledException)
  754. {
  755. return string.Empty;
  756. }
  757. lock (ansiRequest._responseLock)
  758. {
  759. _mainLoopDriver._forceRead = false;
  760. if (_mainLoopDriver.EscSeqRequests.Statuses.TryPeek (out AnsiEscapeSequenceRequestStatus request))
  761. {
  762. if (_mainLoopDriver.EscSeqRequests.Statuses.Count > 0
  763. && string.IsNullOrEmpty (request.AnsiRequest.Response))
  764. {
  765. lock (request!.AnsiRequest._responseLock)
  766. {
  767. // Bad request or no response at all
  768. _mainLoopDriver.EscSeqRequests.Statuses.TryDequeue (out _);
  769. }
  770. }
  771. }
  772. _waitAnsiResponse.Reset ();
  773. return ansiRequest.Response;
  774. }
  775. }
  776. /// <inheritdoc/>
  777. public override void WriteRaw (string ansi) { _mainLoopDriver.WriteRaw (ansi); }
  778. }
  779. // TODO: One type per file - move to another file
  780. internal static class Platform
  781. {
  782. private static int _suspendSignal;
  783. /// <summary>Suspends the process by sending SIGTSTP to itself</summary>
  784. /// <returns>True if the suspension was successful.</returns>
  785. public static bool Suspend ()
  786. {
  787. int signal = GetSuspendSignal ();
  788. if (signal == -1)
  789. {
  790. return false;
  791. }
  792. killpg (0, signal);
  793. return true;
  794. }
  795. private static int GetSuspendSignal ()
  796. {
  797. if (_suspendSignal != 0)
  798. {
  799. return _suspendSignal;
  800. }
  801. nint buf = Marshal.AllocHGlobal (8192);
  802. if (uname (buf) != 0)
  803. {
  804. Marshal.FreeHGlobal (buf);
  805. _suspendSignal = -1;
  806. return _suspendSignal;
  807. }
  808. try
  809. {
  810. switch (Marshal.PtrToStringAnsi (buf))
  811. {
  812. case "Darwin":
  813. case "DragonFly":
  814. case "FreeBSD":
  815. case "NetBSD":
  816. case "OpenBSD":
  817. _suspendSignal = 18;
  818. break;
  819. case "Linux":
  820. // TODO: should fetch the machine name and
  821. // if it is MIPS return 24
  822. _suspendSignal = 20;
  823. break;
  824. case "Solaris":
  825. _suspendSignal = 24;
  826. break;
  827. default:
  828. _suspendSignal = -1;
  829. break;
  830. }
  831. return _suspendSignal;
  832. }
  833. finally
  834. {
  835. Marshal.FreeHGlobal (buf);
  836. }
  837. }
  838. [DllImport ("libc")]
  839. private static extern int killpg (int pgrp, int pid);
  840. [DllImport ("libc")]
  841. private static extern int uname (nint buf);
  842. }
  843. #endregion Low-Level Unix Stuff