CursesDriver.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  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. if (_window != null) {
  222. Curses.move (Row, Col);
  223. _window.wrefresh ();
  224. }
  225. }
  226. public Curses.Window _window;
  227. static Key MapCursesKey (int cursesKey)
  228. {
  229. switch (cursesKey) {
  230. case Curses.KeyF1: return Key.F1;
  231. case Curses.KeyF2: return Key.F2;
  232. case Curses.KeyF3: return Key.F3;
  233. case Curses.KeyF4: return Key.F4;
  234. case Curses.KeyF5: return Key.F5;
  235. case Curses.KeyF6: return Key.F6;
  236. case Curses.KeyF7: return Key.F7;
  237. case Curses.KeyF8: return Key.F8;
  238. case Curses.KeyF9: return Key.F9;
  239. case Curses.KeyF10: return Key.F10;
  240. case Curses.KeyF11: return Key.F11;
  241. case Curses.KeyF12: return Key.F12;
  242. case Curses.KeyUp: return Key.CursorUp;
  243. case Curses.KeyDown: return Key.CursorDown;
  244. case Curses.KeyLeft: return Key.CursorLeft;
  245. case Curses.KeyRight: return Key.CursorRight;
  246. case Curses.KeyHome: return Key.Home;
  247. case Curses.KeyEnd: return Key.End;
  248. case Curses.KeyNPage: return Key.PageDown;
  249. case Curses.KeyPPage: return Key.PageUp;
  250. case Curses.KeyDeleteChar: return Key.DeleteChar;
  251. case Curses.KeyInsertChar: return Key.InsertChar;
  252. case Curses.KeyTab: return Key.Tab;
  253. case Curses.KeyBackTab: return Key.BackTab;
  254. case Curses.KeyBackspace: return Key.Backspace;
  255. case Curses.ShiftKeyUp: return Key.CursorUp | Key.ShiftMask;
  256. case Curses.ShiftKeyDown: return Key.CursorDown | Key.ShiftMask;
  257. case Curses.ShiftKeyLeft: return Key.CursorLeft | Key.ShiftMask;
  258. case Curses.ShiftKeyRight: return Key.CursorRight | Key.ShiftMask;
  259. case Curses.ShiftKeyHome: return Key.Home | Key.ShiftMask;
  260. case Curses.ShiftKeyEnd: return Key.End | Key.ShiftMask;
  261. case Curses.ShiftKeyNPage: return Key.PageDown | Key.ShiftMask;
  262. case Curses.ShiftKeyPPage: return Key.PageUp | Key.ShiftMask;
  263. case Curses.AltKeyUp: return Key.CursorUp | Key.AltMask;
  264. case Curses.AltKeyDown: return Key.CursorDown | Key.AltMask;
  265. case Curses.AltKeyLeft: return Key.CursorLeft | Key.AltMask;
  266. case Curses.AltKeyRight: return Key.CursorRight | Key.AltMask;
  267. case Curses.AltKeyHome: return Key.Home | Key.AltMask;
  268. case Curses.AltKeyEnd: return Key.End | Key.AltMask;
  269. case Curses.AltKeyNPage: return Key.PageDown | Key.AltMask;
  270. case Curses.AltKeyPPage: return Key.PageUp | Key.AltMask;
  271. case Curses.CtrlKeyUp: return Key.CursorUp | Key.CtrlMask;
  272. case Curses.CtrlKeyDown: return Key.CursorDown | Key.CtrlMask;
  273. case Curses.CtrlKeyLeft: return Key.CursorLeft | Key.CtrlMask;
  274. case Curses.CtrlKeyRight: return Key.CursorRight | Key.CtrlMask;
  275. case Curses.CtrlKeyHome: return Key.Home | Key.CtrlMask;
  276. case Curses.CtrlKeyEnd: return Key.End | Key.CtrlMask;
  277. case Curses.CtrlKeyNPage: return Key.PageDown | Key.CtrlMask;
  278. case Curses.CtrlKeyPPage: return Key.PageUp | Key.CtrlMask;
  279. case Curses.ShiftCtrlKeyUp: return Key.CursorUp | Key.ShiftMask | Key.CtrlMask;
  280. case Curses.ShiftCtrlKeyDown: return Key.CursorDown | Key.ShiftMask | Key.CtrlMask;
  281. case Curses.ShiftCtrlKeyLeft: return Key.CursorLeft | Key.ShiftMask | Key.CtrlMask;
  282. case Curses.ShiftCtrlKeyRight: return Key.CursorRight | Key.ShiftMask | Key.CtrlMask;
  283. case Curses.ShiftCtrlKeyHome: return Key.Home | Key.ShiftMask | Key.CtrlMask;
  284. case Curses.ShiftCtrlKeyEnd: return Key.End | Key.ShiftMask | Key.CtrlMask;
  285. case Curses.ShiftCtrlKeyNPage: return Key.PageDown | Key.ShiftMask | Key.CtrlMask;
  286. case Curses.ShiftCtrlKeyPPage: return Key.PageUp | Key.ShiftMask | Key.CtrlMask;
  287. case Curses.ShiftAltKeyUp: return Key.CursorUp | Key.ShiftMask | Key.AltMask;
  288. case Curses.ShiftAltKeyDown: return Key.CursorDown | Key.ShiftMask | Key.AltMask;
  289. case Curses.ShiftAltKeyLeft: return Key.CursorLeft | Key.ShiftMask | Key.AltMask;
  290. case Curses.ShiftAltKeyRight: return Key.CursorRight | Key.ShiftMask | Key.AltMask;
  291. case Curses.ShiftAltKeyNPage: return Key.PageDown | Key.ShiftMask | Key.AltMask;
  292. case Curses.ShiftAltKeyPPage: return Key.PageUp | Key.ShiftMask | Key.AltMask;
  293. case Curses.ShiftAltKeyHome: return Key.Home | Key.ShiftMask | Key.AltMask;
  294. case Curses.ShiftAltKeyEnd: return Key.End | Key.ShiftMask | Key.AltMask;
  295. case Curses.AltCtrlKeyNPage: return Key.PageDown | Key.AltMask | Key.CtrlMask;
  296. case Curses.AltCtrlKeyPPage: return Key.PageUp | Key.AltMask | Key.CtrlMask;
  297. case Curses.AltCtrlKeyHome: return Key.Home | Key.AltMask | Key.CtrlMask;
  298. case Curses.AltCtrlKeyEnd: return Key.End | Key.AltMask | Key.CtrlMask;
  299. default: return Key.Unknown;
  300. }
  301. }
  302. KeyModifiers _keyModifiers;
  303. KeyModifiers MapKeyModifiers (Key key)
  304. {
  305. if (_keyModifiers == null) {
  306. _keyModifiers = new KeyModifiers ();
  307. }
  308. if (!_keyModifiers.Shift && (key & Key.ShiftMask) != 0) {
  309. _keyModifiers.Shift = true;
  310. }
  311. if (!_keyModifiers.Alt && (key & Key.AltMask) != 0) {
  312. _keyModifiers.Alt = true;
  313. }
  314. if (!_keyModifiers.Ctrl && (key & Key.CtrlMask) != 0) {
  315. _keyModifiers.Ctrl = true;
  316. }
  317. return _keyModifiers;
  318. }
  319. void ProcessInput ()
  320. {
  321. int wch;
  322. var code = Curses.get_wch (out wch);
  323. //System.Diagnostics.Debug.WriteLine ($"code: {code}; wch: {wch}");
  324. if (code == Curses.ERR) {
  325. return;
  326. }
  327. _keyModifiers = new KeyModifiers ();
  328. Key k = Key.Null;
  329. if (code == Curses.KEY_CODE_YES) {
  330. while (code == Curses.KEY_CODE_YES && wch == Curses.KeyResize) {
  331. ProcessWinChange ();
  332. code = Curses.get_wch (out wch);
  333. }
  334. if (wch == 0) {
  335. return;
  336. }
  337. if (wch == Curses.KeyMouse) {
  338. int wch2 = wch;
  339. while (wch2 == Curses.KeyMouse) {
  340. KeyEvent key = null;
  341. ConsoleKeyInfo [] cki = new ConsoleKeyInfo [] {
  342. new ConsoleKeyInfo ((char)Key.Esc, 0, false, false, false),
  343. new ConsoleKeyInfo ('[', 0, false, false, false),
  344. new ConsoleKeyInfo ('<', 0, false, false, false)
  345. };
  346. code = 0;
  347. HandleEscSeqResponse (ref code, ref k, ref wch2, ref key, ref cki);
  348. }
  349. return;
  350. }
  351. k = MapCursesKey (wch);
  352. if (wch >= 277 && wch <= 288) {
  353. // Shift+(F1 - F12)
  354. wch -= 12;
  355. k = Key.ShiftMask | MapCursesKey (wch);
  356. } else if (wch >= 289 && wch <= 300) {
  357. // Ctrl+(F1 - F12)
  358. wch -= 24;
  359. k = Key.CtrlMask | MapCursesKey (wch);
  360. } else if (wch >= 301 && wch <= 312) {
  361. // Ctrl+Shift+(F1 - F12)
  362. wch -= 36;
  363. k = Key.CtrlMask | Key.ShiftMask | MapCursesKey (wch);
  364. } else if (wch >= 313 && wch <= 324) {
  365. // Alt+(F1 - F12)
  366. wch -= 48;
  367. k = Key.AltMask | MapCursesKey (wch);
  368. } else if (wch >= 325 && wch <= 327) {
  369. // Shift+Alt+(F1 - F3)
  370. wch -= 60;
  371. k = Key.ShiftMask | Key.AltMask | MapCursesKey (wch);
  372. }
  373. _keyDownHandler (new KeyEvent (k, MapKeyModifiers (k)));
  374. _keyHandler (new KeyEvent (k, MapKeyModifiers (k)));
  375. _keyUpHandler (new KeyEvent (k, MapKeyModifiers (k)));
  376. return;
  377. }
  378. // Special handling for ESC, we want to try to catch ESC+letter to simulate alt-letter as well as Alt-Fkey
  379. if (wch == 27) {
  380. Curses.timeout (10);
  381. code = Curses.get_wch (out int wch2);
  382. if (code == Curses.KEY_CODE_YES) {
  383. k = Key.AltMask | MapCursesKey (wch);
  384. }
  385. if (code == 0) {
  386. KeyEvent key = null;
  387. // The ESC-number handling, debatable.
  388. // Simulates the AltMask itself by pressing Alt + Space.
  389. if (wch2 == (int)Key.Space) {
  390. k = Key.AltMask;
  391. } else if (wch2 - (int)Key.Space >= (uint)Key.A && wch2 - (int)Key.Space <= (uint)Key.Z) {
  392. k = (Key)((uint)Key.AltMask + (wch2 - (int)Key.Space));
  393. } else if (wch2 >= (uint)Key.A - 64 && wch2 <= (uint)Key.Z - 64) {
  394. k = (Key)((uint)(Key.AltMask | Key.CtrlMask) + (wch2 + 64));
  395. } else if (wch2 >= (uint)Key.D0 && wch2 <= (uint)Key.D9) {
  396. k = (Key)((uint)Key.AltMask + (uint)Key.D0 + (wch2 - (uint)Key.D0));
  397. } else if (wch2 == Curses.KeyCSI) {
  398. ConsoleKeyInfo [] cki = new ConsoleKeyInfo [] {
  399. new ConsoleKeyInfo ((char)Key.Esc, 0, false, false, false),
  400. new ConsoleKeyInfo ('[', 0, false, false, false)
  401. };
  402. HandleEscSeqResponse (ref code, ref k, ref wch2, ref key, ref cki);
  403. return;
  404. } else {
  405. // Unfortunately there are no way to differentiate Ctrl+Alt+alfa and Ctrl+Shift+Alt+alfa.
  406. if (((Key)wch2 & Key.CtrlMask) != 0) {
  407. _keyModifiers.Ctrl = true;
  408. }
  409. if (wch2 == 0) {
  410. k = Key.CtrlMask | Key.AltMask | Key.Space;
  411. } else if (wch >= (uint)Key.A && wch <= (uint)Key.Z) {
  412. _keyModifiers.Shift = true;
  413. _keyModifiers.Alt = true;
  414. } else if (wch2 < 256) {
  415. k = (Key)wch2;
  416. _keyModifiers.Alt = true;
  417. } else {
  418. k = (Key)((uint)(Key.AltMask | Key.CtrlMask) + wch2);
  419. }
  420. }
  421. key = new KeyEvent (k, MapKeyModifiers (k));
  422. _keyDownHandler (key);
  423. _keyHandler (key);
  424. } else {
  425. k = Key.Esc;
  426. _keyHandler (new KeyEvent (k, MapKeyModifiers (k)));
  427. }
  428. } else if (wch == Curses.KeyTab) {
  429. k = MapCursesKey (wch);
  430. _keyDownHandler (new KeyEvent (k, MapKeyModifiers (k)));
  431. _keyHandler (new KeyEvent (k, MapKeyModifiers (k)));
  432. } else {
  433. // Unfortunately there are no way to differentiate Ctrl+alfa and Ctrl+Shift+alfa.
  434. k = (Key)wch;
  435. if (wch == 0) {
  436. k = Key.CtrlMask | Key.Space;
  437. } else if (wch >= (uint)Key.A - 64 && wch <= (uint)Key.Z - 64) {
  438. if ((Key)(wch + 64) != Key.J) {
  439. k = Key.CtrlMask | (Key)(wch + 64);
  440. }
  441. } else if (wch >= (uint)Key.A && wch <= (uint)Key.Z) {
  442. _keyModifiers.Shift = true;
  443. }
  444. _keyDownHandler (new KeyEvent (k, MapKeyModifiers (k)));
  445. _keyHandler (new KeyEvent (k, MapKeyModifiers (k)));
  446. _keyUpHandler (new KeyEvent (k, MapKeyModifiers (k)));
  447. }
  448. // Cause OnKeyUp and OnKeyPressed. Note that the special handling for ESC above
  449. // will not impact KeyUp.
  450. // This is causing ESC firing even if another keystroke was handled.
  451. //if (wch == Curses.KeyTab) {
  452. // keyUpHandler (new KeyEvent (MapCursesKey (wch), keyModifiers));
  453. //} else {
  454. // keyUpHandler (new KeyEvent ((Key)wch, keyModifiers));
  455. //}
  456. }
  457. void HandleEscSeqResponse (ref int code, ref Key k, ref int wch2, ref KeyEvent key, ref ConsoleKeyInfo [] cki)
  458. {
  459. ConsoleKey ck = 0;
  460. ConsoleModifiers mod = 0;
  461. while (code == 0) {
  462. code = Curses.get_wch (out wch2);
  463. var consoleKeyInfo = new ConsoleKeyInfo ((char)wch2, 0, false, false, false);
  464. if (wch2 == 0 || wch2 == 27 || wch2 == Curses.KeyMouse) {
  465. 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);
  466. if (isKeyMouse) {
  467. foreach (var mf in mouseFlags) {
  468. ProcessMouseEvent (mf, pos);
  469. }
  470. cki = null;
  471. if (wch2 == 27) {
  472. cki = EscSeqUtils.ResizeArray (new ConsoleKeyInfo ((char)Key.Esc, 0,
  473. false, false, false), cki);
  474. }
  475. } else {
  476. k = ConsoleKeyMapping.MapConsoleKeyToKey (consoleKeyInfo.Key, out _);
  477. k = ConsoleKeyMapping.MapKeyModifiers (consoleKeyInfo, k);
  478. key = new KeyEvent (k, MapKeyModifiers (k));
  479. _keyDownHandler (key);
  480. _keyHandler (key);
  481. }
  482. } else {
  483. cki = EscSeqUtils.ResizeArray (consoleKeyInfo, cki);
  484. }
  485. }
  486. }
  487. MouseFlags _lastMouseFlags;
  488. void ProcessMouseEvent (MouseFlags mouseFlag, Point pos)
  489. {
  490. bool WasButtonReleased (MouseFlags flag)
  491. {
  492. return flag.HasFlag (MouseFlags.Button1Released) ||
  493. flag.HasFlag (MouseFlags.Button2Released) ||
  494. flag.HasFlag (MouseFlags.Button3Released) ||
  495. flag.HasFlag (MouseFlags.Button4Released);
  496. }
  497. bool IsButtonNotPressed (MouseFlags flag)
  498. {
  499. return !flag.HasFlag (MouseFlags.Button1Pressed) &&
  500. !flag.HasFlag (MouseFlags.Button2Pressed) &&
  501. !flag.HasFlag (MouseFlags.Button3Pressed) &&
  502. !flag.HasFlag (MouseFlags.Button4Pressed);
  503. }
  504. bool IsButtonClickedOrDoubleClicked (MouseFlags flag)
  505. {
  506. return flag.HasFlag (MouseFlags.Button1Clicked) ||
  507. flag.HasFlag (MouseFlags.Button2Clicked) ||
  508. flag.HasFlag (MouseFlags.Button3Clicked) ||
  509. flag.HasFlag (MouseFlags.Button4Clicked) ||
  510. flag.HasFlag (MouseFlags.Button1DoubleClicked) ||
  511. flag.HasFlag (MouseFlags.Button2DoubleClicked) ||
  512. flag.HasFlag (MouseFlags.Button3DoubleClicked) ||
  513. flag.HasFlag (MouseFlags.Button4DoubleClicked);
  514. }
  515. if ((WasButtonReleased (mouseFlag) && IsButtonNotPressed (_lastMouseFlags)) ||
  516. (IsButtonClickedOrDoubleClicked (mouseFlag) && _lastMouseFlags == 0)) {
  517. return;
  518. }
  519. _lastMouseFlags = mouseFlag;
  520. var me = new MouseEvent () {
  521. Flags = mouseFlag,
  522. X = pos.X,
  523. Y = pos.Y
  524. };
  525. _mouseHandler (me);
  526. }
  527. void ProcessContinuousButtonPressed (MouseFlags mouseFlag, Point pos)
  528. {
  529. ProcessMouseEvent (mouseFlag, pos);
  530. }
  531. Action<KeyEvent> _keyHandler;
  532. Action<KeyEvent> _keyDownHandler;
  533. Action<KeyEvent> _keyUpHandler;
  534. Action<MouseEvent> _mouseHandler;
  535. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
  536. {
  537. // Note: Curses doesn't support keydown/up events and thus any passed keyDown/UpHandlers will never be called
  538. Curses.timeout (0);
  539. this._keyHandler = keyHandler;
  540. this._keyDownHandler = keyDownHandler;
  541. this._keyUpHandler = keyUpHandler;
  542. this._mouseHandler = mouseHandler;
  543. var mLoop = mainLoop.MainLoopDriver as UnixMainLoop;
  544. mLoop.AddWatch (0, UnixMainLoop.Condition.PollIn, x => {
  545. ProcessInput ();
  546. return true;
  547. });
  548. mLoop.WinChanged += ProcessInput;
  549. }
  550. public override void Init (Action terminalResized)
  551. {
  552. if (_window != null) {
  553. return;
  554. }
  555. try {
  556. _window = Curses.initscr ();
  557. Curses.set_escdelay (10);
  558. } catch (Exception e) {
  559. _window = null;
  560. Debug.WriteLine ($"Curses failed to initialize. Assuming Unit Tests. The exception is: {e.Message}");
  561. }
  562. if (_window != null) {
  563. // Ensures that all procedures are performed at some previous closing.
  564. Curses.doupdate ();
  565. //
  566. // We are setting Invisible as default so we could ignore XTerm DECSUSR setting
  567. //
  568. switch (Curses.curs_set (0)) {
  569. case 0:
  570. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Invisible;
  571. break;
  572. case 1:
  573. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Underline;
  574. Curses.curs_set (1);
  575. break;
  576. case 2:
  577. _currentCursorVisibility = _initialCursorVisibility = CursorVisibility.Box;
  578. Curses.curs_set (2);
  579. break;
  580. default:
  581. _currentCursorVisibility = _initialCursorVisibility = null;
  582. break;
  583. }
  584. if (!Curses.HasColors) {
  585. throw new InvalidOperationException ("V2 - This should never happen. File an Issue if it does.");
  586. }
  587. Curses.raw ();
  588. Curses.noecho ();
  589. Curses.Window.Standard.keypad (true);
  590. Curses.StartColor ();
  591. Curses.UseDefaultColors ();
  592. }
  593. CurrentAttribute = MakeColor (Color.White, Color.Black);
  594. InitializeColorSchemes ();
  595. TerminalResized = terminalResized;
  596. if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX)) {
  597. Clipboard = new MacOSXClipboard ();
  598. } else {
  599. if (Is_WSL_Platform ()) {
  600. Clipboard = new WSLClipboard ();
  601. } else {
  602. Clipboard = new CursesClipboard ();
  603. }
  604. }
  605. if (_window != null) {
  606. Curses.CheckWinChange ();
  607. ClearContents ();
  608. Curses.refresh ();
  609. StartReportingMouseMoves ();
  610. }
  611. }
  612. public static bool Is_WSL_Platform ()
  613. {
  614. // xclip does not work on WSL, so we need to use the Windows clipboard vis Powershell
  615. //if (new CursesClipboard ().IsSupported) {
  616. // // If xclip is installed on Linux under WSL, this will return true.
  617. // return false;
  618. //}
  619. var (exitCode, result) = ClipboardProcessRunner.Bash ("uname -a", waitForOutput: true);
  620. if (exitCode == 0 && result.Contains ("microsoft") && result.Contains ("WSL")) {
  621. return true;
  622. }
  623. return false;
  624. }
  625. public override void Suspend ()
  626. {
  627. StopReportingMouseMoves ();
  628. Platform.Suspend ();
  629. Curses.Window.Standard.redrawwin ();
  630. Curses.refresh ();
  631. StartReportingMouseMoves ();
  632. }
  633. public void StartReportingMouseMoves ()
  634. {
  635. Console.Out.Write (EscSeqUtils.CSI_EnableMouseEvents);
  636. }
  637. public void StopReportingMouseMoves ()
  638. {
  639. Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents);
  640. }
  641. /// <inheritdoc/>
  642. public override bool GetCursorVisibility (out CursorVisibility visibility)
  643. {
  644. visibility = CursorVisibility.Invisible;
  645. if (!_currentCursorVisibility.HasValue)
  646. return false;
  647. visibility = _currentCursorVisibility.Value;
  648. return true;
  649. }
  650. /// <inheritdoc/>
  651. public override bool SetCursorVisibility (CursorVisibility visibility)
  652. {
  653. if (_initialCursorVisibility.HasValue == false) {
  654. return false;
  655. }
  656. Curses.curs_set (((int)visibility >> 16) & 0x000000FF);
  657. if (visibility != CursorVisibility.Invisible) {
  658. Console.Out.Write (EscSeqUtils.CSI_SetCursorStyle ((EscSeqUtils.DECSCUSR_Style)(((int)visibility >> 24) & 0xFF)));
  659. }
  660. _currentCursorVisibility = visibility;
  661. return true;
  662. }
  663. /// <inheritdoc/>
  664. public override bool EnsureCursorVisibility ()
  665. {
  666. return false;
  667. }
  668. public override void SendKeys (char keyChar, ConsoleKey consoleKey, bool shift, bool alt, bool control)
  669. {
  670. Key key;
  671. if (consoleKey == ConsoleKey.Packet) {
  672. ConsoleModifiers mod = new ConsoleModifiers ();
  673. if (shift) {
  674. mod |= ConsoleModifiers.Shift;
  675. }
  676. if (alt) {
  677. mod |= ConsoleModifiers.Alt;
  678. }
  679. if (control) {
  680. mod |= ConsoleModifiers.Control;
  681. }
  682. var kchar = ConsoleKeyMapping.GetKeyCharFromConsoleKey (keyChar, mod, out uint ckey, out _);
  683. key = ConsoleKeyMapping.MapConsoleKeyToKey ((ConsoleKey)ckey, out bool mappable);
  684. if (mappable) {
  685. key = (Key)kchar;
  686. }
  687. } else {
  688. key = (Key)keyChar;
  689. }
  690. KeyModifiers km = new KeyModifiers ();
  691. if (shift) {
  692. if (keyChar == 0) {
  693. key |= Key.ShiftMask;
  694. }
  695. km.Shift = shift;
  696. }
  697. if (alt) {
  698. key |= Key.AltMask;
  699. km.Alt = alt;
  700. }
  701. if (control) {
  702. key |= Key.CtrlMask;
  703. km.Ctrl = control;
  704. }
  705. _keyDownHandler (new KeyEvent (key, km));
  706. _keyHandler (new KeyEvent (key, km));
  707. _keyUpHandler (new KeyEvent (key, km));
  708. }
  709. }
  710. internal static class Platform {
  711. [DllImport ("libc")]
  712. static extern int uname (IntPtr buf);
  713. [DllImport ("libc")]
  714. static extern int killpg (int pgrp, int pid);
  715. static int _suspendSignal;
  716. static int GetSuspendSignal ()
  717. {
  718. if (_suspendSignal != 0) {
  719. return _suspendSignal;
  720. }
  721. IntPtr buf = Marshal.AllocHGlobal (8192);
  722. if (uname (buf) != 0) {
  723. Marshal.FreeHGlobal (buf);
  724. _suspendSignal = -1;
  725. return _suspendSignal;
  726. }
  727. try {
  728. switch (Marshal.PtrToStringAnsi (buf)) {
  729. case "Darwin":
  730. case "DragonFly":
  731. case "FreeBSD":
  732. case "NetBSD":
  733. case "OpenBSD":
  734. _suspendSignal = 18;
  735. break;
  736. case "Linux":
  737. // TODO: should fetch the machine name and
  738. // if it is MIPS return 24
  739. _suspendSignal = 20;
  740. break;
  741. case "Solaris":
  742. _suspendSignal = 24;
  743. break;
  744. default:
  745. _suspendSignal = -1;
  746. break;
  747. }
  748. return _suspendSignal;
  749. } finally {
  750. Marshal.FreeHGlobal (buf);
  751. }
  752. }
  753. /// <summary>
  754. /// Suspends the process by sending SIGTSTP to itself
  755. /// </summary>
  756. /// <returns>The suspend.</returns>
  757. static public bool Suspend ()
  758. {
  759. int signal = GetSuspendSignal ();
  760. if (signal == -1) {
  761. return false;
  762. }
  763. killpg (0, signal);
  764. return true;
  765. }
  766. }