CursesDriver.cs 26 KB

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