CursesDriver.cs 25 KB

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