CursesDriver.cs 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285
  1. //
  2. // Driver.cs: Curses-based Driver
  3. //
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.Linq;
  8. using System.Runtime.InteropServices;
  9. using System.Threading.Tasks;
  10. using NStack;
  11. using Unix.Terminal;
  12. namespace Terminal.Gui {
  13. /// <summary>
  14. /// This is the Curses driver for the gui.cs/Terminal framework.
  15. /// </summary>
  16. internal class CursesDriver : ConsoleDriver {
  17. public override int Cols => Curses.Cols;
  18. public override int Rows => Curses.Lines;
  19. public override int Left => 0;
  20. public override int Top => 0;
  21. [Obsolete ("This API is deprecated", false)]
  22. public override bool EnableConsoleScrolling { get; set; }
  23. [Obsolete ("This API is deprecated", false)]
  24. public override bool HeightAsBuffer { get; set; }
  25. public override IClipboard Clipboard { get => clipboard; }
  26. CursorVisibility? initialCursorVisibility = null;
  27. CursorVisibility? currentCursorVisibility = null;
  28. IClipboard clipboard;
  29. int [,,] contents;
  30. public override int [,,] Contents => contents;
  31. // Current row, and current col, tracked by Move/AddRune only
  32. int ccol, crow;
  33. bool needMove;
  34. public override void Move (int col, int row)
  35. {
  36. ccol = col;
  37. crow = row;
  38. if (Clip.Contains (col, row)) {
  39. Curses.move (row, col);
  40. needMove = false;
  41. } else {
  42. Curses.move (Clip.Y, Clip.X);
  43. needMove = true;
  44. }
  45. }
  46. static bool sync = false;
  47. public override void AddRune (Rune rune)
  48. {
  49. rune = MakePrintable (rune);
  50. var runeWidth = Rune.ColumnWidth (rune);
  51. var validClip = IsValidContent (ccol, crow, Clip);
  52. if (validClip) {
  53. if (needMove) {
  54. Curses.move (crow, ccol);
  55. needMove = false;
  56. }
  57. if (runeWidth == 0 && ccol > 0) {
  58. var r = contents [crow, ccol - 1, 0];
  59. var s = new string (new char [] { (char)r, (char)rune });
  60. string sn;
  61. if (!s.IsNormalized ()) {
  62. sn = s.Normalize ();
  63. } else {
  64. sn = s;
  65. }
  66. var c = sn [0];
  67. Curses.mvaddch (crow, ccol - 1, (int)(uint)c);
  68. contents [crow, ccol - 1, 0] = c;
  69. contents [crow, ccol - 1, 1] = CurrentAttribute;
  70. contents [crow, ccol - 1, 2] = 1;
  71. } else {
  72. if (runeWidth < 2 && ccol > 0
  73. && Rune.ColumnWidth ((char)contents [crow, ccol - 1, 0]) > 1) {
  74. var curAtttib = CurrentAttribute;
  75. Curses.attrset (contents [crow, ccol - 1, 1]);
  76. Curses.mvaddch (crow, ccol - 1, (int)(uint)' ');
  77. contents [crow, ccol - 1, 0] = (int)(uint)' ';
  78. Curses.move (crow, ccol);
  79. Curses.attrset (curAtttib);
  80. } else if (runeWidth < 2 && ccol <= Clip.Right - 1
  81. && Rune.ColumnWidth ((char)contents [crow, ccol, 0]) > 1) {
  82. var curAtttib = CurrentAttribute;
  83. Curses.attrset (contents [crow, ccol + 1, 1]);
  84. Curses.mvaddch (crow, ccol + 1, (int)(uint)' ');
  85. contents [crow, ccol + 1, 0] = (int)(uint)' ';
  86. Curses.move (crow, ccol);
  87. Curses.attrset (curAtttib);
  88. }
  89. if (runeWidth > 1 && ccol == Clip.Right - 1) {
  90. Curses.addch ((int)(uint)' ');
  91. contents [crow, ccol, 0] = (int)(uint)' ';
  92. } else {
  93. Curses.addch ((int)(uint)rune);
  94. contents [crow, ccol, 0] = (int)(uint)rune;
  95. }
  96. contents [crow, ccol, 1] = CurrentAttribute;
  97. contents [crow, ccol, 2] = 1;
  98. }
  99. } else {
  100. needMove = true;
  101. }
  102. if (runeWidth < 0 || runeWidth > 0) {
  103. ccol++;
  104. }
  105. if (runeWidth > 1) {
  106. if (validClip && ccol < Clip.Right) {
  107. contents [crow, ccol, 1] = CurrentAttribute;
  108. contents [crow, ccol, 2] = 0;
  109. }
  110. ccol++;
  111. }
  112. if (sync) {
  113. UpdateScreen ();
  114. }
  115. }
  116. public override void AddStr (ustring str)
  117. {
  118. // TODO; optimize this to determine if the str fits in the clip region, and if so, use Curses.addstr directly
  119. foreach (var rune in str)
  120. AddRune (rune);
  121. }
  122. public override void Refresh ()
  123. {
  124. Curses.raw ();
  125. Curses.noecho ();
  126. Curses.refresh ();
  127. ProcessWinChange ();
  128. }
  129. private void ProcessWinChange ()
  130. {
  131. if (Curses.CheckWinChange ()) {
  132. ResizeScreen ();
  133. UpdateOffScreen ();
  134. TerminalResized?.Invoke ();
  135. }
  136. }
  137. public override void UpdateCursor () => Refresh ();
  138. public override void End ()
  139. {
  140. StopReportingMouseMoves ();
  141. SetCursorVisibility (CursorVisibility.Default);
  142. // throws away any typeahead that has been typed by
  143. // the user and has not yet been read by the program.
  144. Curses.flushinp ();
  145. Curses.endwin ();
  146. }
  147. public override void UpdateScreen () => window.redrawwin ();
  148. public override void SetAttribute (Attribute c)
  149. {
  150. base.SetAttribute (c);
  151. Curses.attrset (CurrentAttribute);
  152. }
  153. public Curses.Window window;
  154. //static short last_color_pair = 16;
  155. /// <summary>
  156. /// Creates a curses color from the provided foreground and background colors
  157. /// </summary>
  158. /// <param name="foreground">Contains the curses attributes for the foreground (color, plus any attributes)</param>
  159. /// <param name="background">Contains the curses attributes for the background (color, plus any attributes)</param>
  160. /// <returns></returns>
  161. public static Attribute MakeColor (short foreground, short background)
  162. {
  163. var v = (short)((int)foreground | background << 4);
  164. //Curses.InitColorPair (++last_color_pair, foreground, background);
  165. Curses.InitColorPair (v, foreground, background);
  166. return new Attribute (
  167. //value: Curses.ColorPair (last_color_pair),
  168. value: Curses.ColorPair (v),
  169. //foreground: (Color)foreground,
  170. foreground: MapCursesColor (foreground),
  171. //background: (Color)background);
  172. background: MapCursesColor (background));
  173. }
  174. public override Attribute MakeColor (Color fore, Color back)
  175. {
  176. return MakeColor ((short)MapColor (fore), (short)MapColor (back));
  177. }
  178. int [,] colorPairs = new int [16, 16];
  179. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  180. {
  181. // BUGBUG: This code is never called ?? See Issue #2300
  182. int f = (short)foreground;
  183. int b = (short)background;
  184. var v = colorPairs [f, b];
  185. if ((v & 0x10000) == 0) {
  186. b &= 0x7;
  187. bool bold = (f & 0x8) != 0;
  188. f &= 0x7;
  189. v = MakeColor ((short)f, (short)b) | (bold ? Curses.A_BOLD : 0);
  190. colorPairs [(int)foreground, (int)background] = v | 0x1000;
  191. }
  192. SetAttribute (v & 0xffff);
  193. }
  194. Dictionary<int, int> rawPairs = new Dictionary<int, int> ();
  195. public override void SetColors (short foreColorId, short backgroundColorId)
  196. {
  197. // BUGBUG: This code is never called ?? See Issue #2300
  198. int key = ((ushort)foreColorId << 16) | (ushort)backgroundColorId;
  199. if (!rawPairs.TryGetValue (key, out var v)) {
  200. v = MakeColor (foreColorId, backgroundColorId);
  201. rawPairs [key] = v;
  202. }
  203. SetAttribute (v);
  204. }
  205. static Key MapCursesKey (int cursesKey)
  206. {
  207. switch (cursesKey) {
  208. case Curses.KeyF1: return Key.F1;
  209. case Curses.KeyF2: return Key.F2;
  210. case Curses.KeyF3: return Key.F3;
  211. case Curses.KeyF4: return Key.F4;
  212. case Curses.KeyF5: return Key.F5;
  213. case Curses.KeyF6: return Key.F6;
  214. case Curses.KeyF7: return Key.F7;
  215. case Curses.KeyF8: return Key.F8;
  216. case Curses.KeyF9: return Key.F9;
  217. case Curses.KeyF10: return Key.F10;
  218. case Curses.KeyF11: return Key.F11;
  219. case Curses.KeyF12: return Key.F12;
  220. case Curses.KeyUp: return Key.CursorUp;
  221. case Curses.KeyDown: return Key.CursorDown;
  222. case Curses.KeyLeft: return Key.CursorLeft;
  223. case Curses.KeyRight: return Key.CursorRight;
  224. case Curses.KeyHome: return Key.Home;
  225. case Curses.KeyEnd: return Key.End;
  226. case Curses.KeyNPage: return Key.PageDown;
  227. case Curses.KeyPPage: return Key.PageUp;
  228. case Curses.KeyDeleteChar: return Key.DeleteChar;
  229. case Curses.KeyInsertChar: return Key.InsertChar;
  230. case Curses.KeyTab: return Key.Tab;
  231. case Curses.KeyBackTab: return Key.BackTab;
  232. case Curses.KeyBackspace: return Key.Backspace;
  233. case Curses.ShiftKeyUp: return Key.CursorUp | Key.ShiftMask;
  234. case Curses.ShiftKeyDown: return Key.CursorDown | Key.ShiftMask;
  235. case Curses.ShiftKeyLeft: return Key.CursorLeft | Key.ShiftMask;
  236. case Curses.ShiftKeyRight: return Key.CursorRight | Key.ShiftMask;
  237. case Curses.ShiftKeyHome: return Key.Home | Key.ShiftMask;
  238. case Curses.ShiftKeyEnd: return Key.End | Key.ShiftMask;
  239. case Curses.ShiftKeyNPage: return Key.PageDown | Key.ShiftMask;
  240. case Curses.ShiftKeyPPage: return Key.PageUp | Key.ShiftMask;
  241. case Curses.AltKeyUp: return Key.CursorUp | Key.AltMask;
  242. case Curses.AltKeyDown: return Key.CursorDown | Key.AltMask;
  243. case Curses.AltKeyLeft: return Key.CursorLeft | Key.AltMask;
  244. case Curses.AltKeyRight: return Key.CursorRight | Key.AltMask;
  245. case Curses.AltKeyHome: return Key.Home | Key.AltMask;
  246. case Curses.AltKeyEnd: return Key.End | Key.AltMask;
  247. case Curses.AltKeyNPage: return Key.PageDown | Key.AltMask;
  248. case Curses.AltKeyPPage: return Key.PageUp | Key.AltMask;
  249. case Curses.CtrlKeyUp: return Key.CursorUp | Key.CtrlMask;
  250. case Curses.CtrlKeyDown: return Key.CursorDown | Key.CtrlMask;
  251. case Curses.CtrlKeyLeft: return Key.CursorLeft | Key.CtrlMask;
  252. case Curses.CtrlKeyRight: return Key.CursorRight | Key.CtrlMask;
  253. case Curses.CtrlKeyHome: return Key.Home | Key.CtrlMask;
  254. case Curses.CtrlKeyEnd: return Key.End | Key.CtrlMask;
  255. case Curses.CtrlKeyNPage: return Key.PageDown | Key.CtrlMask;
  256. case Curses.CtrlKeyPPage: return Key.PageUp | Key.CtrlMask;
  257. case Curses.ShiftCtrlKeyUp: return Key.CursorUp | Key.ShiftMask | Key.CtrlMask;
  258. case Curses.ShiftCtrlKeyDown: return Key.CursorDown | Key.ShiftMask | Key.CtrlMask;
  259. case Curses.ShiftCtrlKeyLeft: return Key.CursorLeft | Key.ShiftMask | Key.CtrlMask;
  260. case Curses.ShiftCtrlKeyRight: return Key.CursorRight | Key.ShiftMask | Key.CtrlMask;
  261. case Curses.ShiftCtrlKeyHome: return Key.Home | Key.ShiftMask | Key.CtrlMask;
  262. case Curses.ShiftCtrlKeyEnd: return Key.End | Key.ShiftMask | Key.CtrlMask;
  263. case Curses.ShiftCtrlKeyNPage: return Key.PageDown | Key.ShiftMask | Key.CtrlMask;
  264. case Curses.ShiftCtrlKeyPPage: return Key.PageUp | Key.ShiftMask | Key.CtrlMask;
  265. case Curses.ShiftAltKeyUp: return Key.CursorUp | Key.ShiftMask | Key.AltMask;
  266. case Curses.ShiftAltKeyDown: return Key.CursorDown | Key.ShiftMask | Key.AltMask;
  267. case Curses.ShiftAltKeyLeft: return Key.CursorLeft | Key.ShiftMask | Key.AltMask;
  268. case Curses.ShiftAltKeyRight: return Key.CursorRight | Key.ShiftMask | Key.AltMask;
  269. case Curses.ShiftAltKeyNPage: return Key.PageDown | Key.ShiftMask | Key.AltMask;
  270. case Curses.ShiftAltKeyPPage: return Key.PageUp | Key.ShiftMask | Key.AltMask;
  271. case Curses.ShiftAltKeyHome: return Key.Home | Key.ShiftMask | Key.AltMask;
  272. case Curses.ShiftAltKeyEnd: return Key.End | Key.ShiftMask | Key.AltMask;
  273. case Curses.AltCtrlKeyNPage: return Key.PageDown | Key.AltMask | Key.CtrlMask;
  274. case Curses.AltCtrlKeyPPage: return Key.PageUp | Key.AltMask | Key.CtrlMask;
  275. case Curses.AltCtrlKeyHome: return Key.Home | Key.AltMask | Key.CtrlMask;
  276. case Curses.AltCtrlKeyEnd: return Key.End | Key.AltMask | Key.CtrlMask;
  277. default: return Key.Unknown;
  278. }
  279. }
  280. KeyModifiers keyModifiers;
  281. KeyModifiers MapKeyModifiers (Key key)
  282. {
  283. if (keyModifiers == null)
  284. keyModifiers = new KeyModifiers ();
  285. if (!keyModifiers.Shift && (key & Key.ShiftMask) != 0)
  286. keyModifiers.Shift = true;
  287. if (!keyModifiers.Alt && (key & Key.AltMask) != 0)
  288. keyModifiers.Alt = true;
  289. if (!keyModifiers.Ctrl && (key & Key.CtrlMask) != 0)
  290. keyModifiers.Ctrl = true;
  291. return keyModifiers;
  292. }
  293. void ProcessInput ()
  294. {
  295. int wch;
  296. var code = Curses.get_wch (out wch);
  297. //System.Diagnostics.Debug.WriteLine ($"code: {code}; wch: {wch}");
  298. if (code == Curses.ERR)
  299. return;
  300. keyModifiers = new KeyModifiers ();
  301. Key k = Key.Null;
  302. if (code == Curses.KEY_CODE_YES) {
  303. var lastWch = wch;
  304. while (code == Curses.KEY_CODE_YES && wch == Curses.KeyResize) {
  305. ProcessWinChange ();
  306. code = Curses.get_wch (out wch);
  307. }
  308. if (wch == 0) {
  309. return;
  310. }
  311. if (wch == Curses.KeyMouse) {
  312. int wch2 = wch;
  313. while (wch2 == Curses.KeyMouse) {
  314. KeyEvent key = null;
  315. ConsoleKeyInfo [] cki = new ConsoleKeyInfo [] {
  316. new ConsoleKeyInfo ((char)Key.Esc, 0, false, false, false),
  317. new ConsoleKeyInfo ('[', 0, false, false, false),
  318. new ConsoleKeyInfo ('<', 0, false, false, false)
  319. };
  320. code = 0;
  321. GetEscSeq (ref code, ref k, ref wch2, ref key, ref cki);
  322. }
  323. return;
  324. }
  325. k = MapCursesKey (wch);
  326. if (wch >= 277 && wch <= 288) { // Shift+(F1 - F12)
  327. wch -= 12;
  328. k = Key.ShiftMask | MapCursesKey (wch);
  329. } else if (wch >= 289 && wch <= 300) { // Ctrl+(F1 - F12)
  330. wch -= 24;
  331. k = Key.CtrlMask | MapCursesKey (wch);
  332. } else if (wch >= 301 && wch <= 312) { // Ctrl+Shift+(F1 - F12)
  333. wch -= 36;
  334. k = Key.CtrlMask | Key.ShiftMask | MapCursesKey (wch);
  335. } else if (wch >= 313 && wch <= 324) { // Alt+(F1 - F12)
  336. wch -= 48;
  337. k = Key.AltMask | MapCursesKey (wch);
  338. } else if (wch >= 325 && wch <= 327) { // Shift+Alt+(F1 - F3)
  339. wch -= 60;
  340. k = Key.ShiftMask | Key.AltMask | MapCursesKey (wch);
  341. } else {
  342. code = Curses.get_wch (out wch);
  343. if (code == 0) {
  344. switch (wch) {
  345. // Shift code.
  346. case 16:
  347. keyModifiers.Shift = true;
  348. break;
  349. default:
  350. if (lastWch == Curses.KeyResize && wch == 91) {
  351. // Returns this keys to the std input which is a CSI (\x1b[).
  352. Curses.ungetch (91); // [
  353. Curses.ungetch (27); // Esc
  354. return;
  355. } else {
  356. throw new Exception ();
  357. }
  358. }
  359. }
  360. }
  361. keyDownHandler (new KeyEvent (k, MapKeyModifiers (k)));
  362. keyHandler (new KeyEvent (k, MapKeyModifiers (k)));
  363. keyUpHandler (new KeyEvent (k, MapKeyModifiers (k)));
  364. return;
  365. }
  366. // Special handling for ESC, we want to try to catch ESC+letter to simulate alt-letter as well as Alt-Fkey
  367. if (wch == 27) {
  368. code = Curses.get_wch (out int wch2);
  369. if (code == Curses.KEY_CODE_YES) {
  370. k = Key.AltMask | MapCursesKey (wch);
  371. }
  372. if (code == 0) {
  373. KeyEvent key = null;
  374. // The ESC-number handling, debatable.
  375. // Simulates the AltMask itself by pressing Alt + Space.
  376. if (wch2 == (int)Key.Space) {
  377. k = Key.AltMask;
  378. } else if (wch2 - (int)Key.Space >= (uint)Key.A && wch2 - (int)Key.Space <= (uint)Key.Z) {
  379. k = (Key)((uint)Key.AltMask + (wch2 - (int)Key.Space));
  380. } else if (wch2 >= (uint)Key.A - 64 && wch2 <= (uint)Key.Z - 64) {
  381. k = (Key)((uint)(Key.AltMask | Key.CtrlMask) + (wch2 + 64));
  382. } else if (wch2 >= (uint)Key.D0 && wch2 <= (uint)Key.D9) {
  383. k = (Key)((uint)Key.AltMask + (uint)Key.D0 + (wch2 - (uint)Key.D0));
  384. } else if (wch2 == Curses.KeyCSI) {
  385. ConsoleKeyInfo [] cki = new ConsoleKeyInfo [] {
  386. new ConsoleKeyInfo ((char)Key.Esc, 0, false, false, false),
  387. new ConsoleKeyInfo ('[', 0, false, false, false)
  388. };
  389. GetEscSeq (ref code, ref k, ref wch2, ref key, ref cki);
  390. return;
  391. } else {
  392. // Unfortunately there are no way to differentiate Ctrl+Alt+alfa and Ctrl+Shift+Alt+alfa.
  393. if (((Key)wch2 & Key.CtrlMask) != 0) {
  394. keyModifiers.Ctrl = true;
  395. }
  396. if (wch2 == 0) {
  397. k = Key.CtrlMask | Key.AltMask | Key.Space;
  398. } else if (wch >= (uint)Key.A && wch <= (uint)Key.Z) {
  399. keyModifiers.Shift = true;
  400. keyModifiers.Alt = true;
  401. } else if (wch2 == Curses.KeySS3) {
  402. while (code > -1) {
  403. code = Curses.get_wch (out wch2);
  404. if (code == 0) {
  405. switch (wch2) {
  406. case 16:
  407. keyModifiers.Shift = true;
  408. break;
  409. case 108:
  410. k = (Key)'+';
  411. break;
  412. case 109:
  413. k = (Key)'-';
  414. break;
  415. case 112:
  416. k = Key.InsertChar;
  417. break;
  418. case 113:
  419. k = Key.End;
  420. break;
  421. case 114:
  422. k = Key.CursorDown;
  423. break;
  424. case 115:
  425. k = Key.PageDown;
  426. break;
  427. case 116:
  428. k = Key.CursorLeft;
  429. break;
  430. case 117:
  431. k = Key.Clear;
  432. break;
  433. case 118:
  434. k = Key.CursorRight;
  435. break;
  436. case 119:
  437. k = Key.Home;
  438. break;
  439. case 120:
  440. k = Key.CursorUp;
  441. break;
  442. case 121:
  443. k = Key.PageUp;
  444. break;
  445. default:
  446. k = (Key)wch2;
  447. break;
  448. }
  449. }
  450. }
  451. } else if (wch2 < 256) {
  452. k = (Key)wch2;
  453. keyModifiers.Alt = true;
  454. } else {
  455. k = (Key)((uint)(Key.AltMask | Key.CtrlMask) + wch2);
  456. }
  457. }
  458. key = new KeyEvent (k, MapKeyModifiers (k));
  459. keyDownHandler (key);
  460. keyHandler (key);
  461. } else {
  462. k = Key.Esc;
  463. keyHandler (new KeyEvent (k, MapKeyModifiers (k)));
  464. }
  465. } else if (wch == Curses.KeyTab) {
  466. k = MapCursesKey (wch);
  467. keyDownHandler (new KeyEvent (k, MapKeyModifiers (k)));
  468. keyHandler (new KeyEvent (k, MapKeyModifiers (k)));
  469. } else {
  470. // Unfortunately there are no way to differentiate Ctrl+alfa and Ctrl+Shift+alfa.
  471. k = (Key)wch;
  472. if (wch == 0) {
  473. k = Key.CtrlMask | Key.Space;
  474. } else if (wch >= (uint)Key.A - 64 && wch <= (uint)Key.Z - 64) {
  475. if ((Key)(wch + 64) != Key.J) {
  476. k = Key.CtrlMask | (Key)(wch + 64);
  477. }
  478. } else if (wch >= (uint)Key.A && wch <= (uint)Key.Z) {
  479. keyModifiers.Shift = true;
  480. }
  481. keyDownHandler (new KeyEvent (k, MapKeyModifiers (k)));
  482. keyHandler (new KeyEvent (k, MapKeyModifiers (k)));
  483. keyUpHandler (new KeyEvent (k, MapKeyModifiers (k)));
  484. }
  485. // Cause OnKeyUp and OnKeyPressed. Note that the special handling for ESC above
  486. // will not impact KeyUp.
  487. // This is causing ESC firing even if another keystroke was handled.
  488. //if (wch == Curses.KeyTab) {
  489. // keyUpHandler (new KeyEvent (MapCursesKey (wch), keyModifiers));
  490. //} else {
  491. // keyUpHandler (new KeyEvent ((Key)wch, keyModifiers));
  492. //}
  493. }
  494. void GetEscSeq (ref int code, ref Key k, ref int wch2, ref KeyEvent key, ref ConsoleKeyInfo [] cki)
  495. {
  496. ConsoleKey ck = 0;
  497. ConsoleModifiers mod = 0;
  498. while (code == 0) {
  499. code = Curses.get_wch (out wch2);
  500. var consoleKeyInfo = new ConsoleKeyInfo ((char)wch2, 0, false, false, false);
  501. if (wch2 == 0 || wch2 == 27 || wch2 == Curses.KeyMouse) {
  502. 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);
  503. if (isKeyMouse) {
  504. foreach (var mf in mouseFlags) {
  505. ProcessMouseEvent (mf, pos);
  506. }
  507. cki = null;
  508. if (wch2 == 27) {
  509. cki = EscSeqUtils.ResizeArray (new ConsoleKeyInfo ((char)Key.Esc, 0,
  510. false, false, false), cki);
  511. }
  512. } else {
  513. k = ConsoleKeyMapping.MapConsoleKeyToKey (consoleKeyInfo.Key, out _);
  514. k = ConsoleKeyMapping.MapKeyModifiers (consoleKeyInfo, k);
  515. key = new KeyEvent (k, MapKeyModifiers (k));
  516. keyDownHandler (key);
  517. keyHandler (key);
  518. }
  519. } else {
  520. cki = EscSeqUtils.ResizeArray (consoleKeyInfo, cki);
  521. }
  522. }
  523. }
  524. MouseFlags lastMouseFlags;
  525. void ProcessMouseEvent (MouseFlags mouseFlag, Point pos)
  526. {
  527. bool WasButtonReleased (MouseFlags flag)
  528. {
  529. return flag.HasFlag (MouseFlags.Button1Released) ||
  530. flag.HasFlag (MouseFlags.Button2Released) ||
  531. flag.HasFlag (MouseFlags.Button3Released) ||
  532. flag.HasFlag (MouseFlags.Button4Released);
  533. }
  534. bool IsButtonNotPressed (MouseFlags flag)
  535. {
  536. return !flag.HasFlag (MouseFlags.Button1Pressed) &&
  537. !flag.HasFlag (MouseFlags.Button2Pressed) &&
  538. !flag.HasFlag (MouseFlags.Button3Pressed) &&
  539. !flag.HasFlag (MouseFlags.Button4Pressed);
  540. }
  541. bool IsButtonClickedOrDoubleClicked (MouseFlags flag)
  542. {
  543. return flag.HasFlag (MouseFlags.Button1Clicked) ||
  544. flag.HasFlag (MouseFlags.Button2Clicked) ||
  545. flag.HasFlag (MouseFlags.Button3Clicked) ||
  546. flag.HasFlag (MouseFlags.Button4Clicked) ||
  547. flag.HasFlag (MouseFlags.Button1DoubleClicked) ||
  548. flag.HasFlag (MouseFlags.Button2DoubleClicked) ||
  549. flag.HasFlag (MouseFlags.Button3DoubleClicked) ||
  550. flag.HasFlag (MouseFlags.Button4DoubleClicked);
  551. }
  552. if ((WasButtonReleased (mouseFlag) && IsButtonNotPressed (lastMouseFlags)) ||
  553. (IsButtonClickedOrDoubleClicked (mouseFlag) && lastMouseFlags == 0)) {
  554. return;
  555. }
  556. lastMouseFlags = mouseFlag;
  557. var me = new MouseEvent () {
  558. Flags = mouseFlag,
  559. X = pos.X,
  560. Y = pos.Y
  561. };
  562. mouseHandler (me);
  563. }
  564. void ProcessContinuousButtonPressed (MouseFlags mouseFlag, Point pos)
  565. {
  566. ProcessMouseEvent (mouseFlag, pos);
  567. }
  568. Action<KeyEvent> keyHandler;
  569. Action<KeyEvent> keyDownHandler;
  570. Action<KeyEvent> keyUpHandler;
  571. Action<MouseEvent> mouseHandler;
  572. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
  573. {
  574. // Note: Curses doesn't support keydown/up events and thus any passed keyDown/UpHandlers will never be called
  575. this.keyHandler = keyHandler;
  576. this.keyDownHandler = keyDownHandler;
  577. this.keyUpHandler = keyUpHandler;
  578. this.mouseHandler = mouseHandler;
  579. var mLoop = mainLoop.Driver as UnixMainLoop;
  580. mLoop.AddWatch (0, UnixMainLoop.Condition.PollIn, x => {
  581. ProcessInput ();
  582. return true;
  583. });
  584. mLoop.WinChanged += () => ProcessWinChange ();
  585. }
  586. public override void Init (Action terminalResized)
  587. {
  588. if (window != null)
  589. return;
  590. try {
  591. window = Curses.initscr ();
  592. Curses.set_escdelay (10);
  593. Curses.nodelay (window.Handle, true);
  594. } catch (Exception e) {
  595. throw new Exception ($"Curses failed to initialize, the exception is: {e.Message}");
  596. }
  597. // Ensures that all procedures are performed at some previous closing.
  598. Curses.doupdate ();
  599. //
  600. // We are setting Invisible as default so we could ignore XTerm DECSUSR setting
  601. //
  602. switch (Curses.curs_set (0)) {
  603. case 0:
  604. currentCursorVisibility = initialCursorVisibility = CursorVisibility.Invisible;
  605. break;
  606. case 1:
  607. currentCursorVisibility = initialCursorVisibility = CursorVisibility.Underline;
  608. Curses.curs_set (1);
  609. break;
  610. case 2:
  611. currentCursorVisibility = initialCursorVisibility = CursorVisibility.Box;
  612. Curses.curs_set (2);
  613. break;
  614. default:
  615. currentCursorVisibility = initialCursorVisibility = null;
  616. break;
  617. }
  618. if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX)) {
  619. clipboard = new MacOSXClipboard ();
  620. } else {
  621. if (Is_WSL_Platform ()) {
  622. clipboard = new WSLClipboard ();
  623. } else {
  624. clipboard = new CursesClipboard ();
  625. }
  626. }
  627. Curses.raw ();
  628. Curses.noecho ();
  629. Curses.Window.Standard.keypad (true);
  630. TerminalResized = terminalResized;
  631. StartReportingMouseMoves ();
  632. CurrentAttribute = MakeColor (Color.White, Color.Black);
  633. if (Curses.HasColors) {
  634. Curses.StartColor ();
  635. Curses.UseDefaultColors ();
  636. InitalizeColorSchemes ();
  637. } else {
  638. InitalizeColorSchemes (false);
  639. // BUGBUG: This is a hack to make the colors work on the Mac?
  640. // The new Theme support overwrites these colors, so this is not needed?
  641. Colors.TopLevel.Normal = Curses.COLOR_GREEN;
  642. Colors.TopLevel.Focus = Curses.COLOR_WHITE;
  643. Colors.TopLevel.HotNormal = Curses.COLOR_YELLOW;
  644. Colors.TopLevel.HotFocus = Curses.COLOR_YELLOW;
  645. Colors.TopLevel.Disabled = Curses.A_BOLD | Curses.COLOR_GRAY;
  646. Colors.Base.Normal = Curses.A_NORMAL;
  647. Colors.Base.Focus = Curses.A_REVERSE;
  648. Colors.Base.HotNormal = Curses.A_BOLD;
  649. Colors.Base.HotFocus = Curses.A_BOLD | Curses.A_REVERSE;
  650. Colors.Base.Disabled = Curses.A_BOLD | Curses.COLOR_GRAY;
  651. Colors.Menu.Normal = Curses.A_REVERSE;
  652. Colors.Menu.Focus = Curses.A_NORMAL;
  653. Colors.Menu.HotNormal = Curses.A_BOLD;
  654. Colors.Menu.HotFocus = Curses.A_NORMAL;
  655. Colors.Menu.Disabled = Curses.A_BOLD | Curses.COLOR_GRAY;
  656. Colors.Dialog.Normal = Curses.A_REVERSE;
  657. Colors.Dialog.Focus = Curses.A_NORMAL;
  658. Colors.Dialog.HotNormal = Curses.A_BOLD;
  659. Colors.Dialog.HotFocus = Curses.A_NORMAL;
  660. Colors.Dialog.Disabled = Curses.A_BOLD | Curses.COLOR_GRAY;
  661. Colors.Error.Normal = Curses.A_BOLD;
  662. Colors.Error.Focus = Curses.A_BOLD | Curses.A_REVERSE;
  663. Colors.Error.HotNormal = Curses.A_BOLD | Curses.A_REVERSE;
  664. Colors.Error.HotFocus = Curses.A_REVERSE;
  665. Colors.Error.Disabled = Curses.A_BOLD | Curses.COLOR_GRAY;
  666. }
  667. ResizeScreen ();
  668. UpdateOffScreen ();
  669. }
  670. public override void ResizeScreen ()
  671. {
  672. Clip = new Rect (0, 0, Cols, Rows);
  673. }
  674. public override void UpdateOffScreen ()
  675. {
  676. contents = new int [Rows, Cols, 3];
  677. for (int row = 0; row < Rows; row++) {
  678. for (int col = 0; col < Cols; col++) {
  679. //Curses.move (row, col);
  680. //Curses.attrset (Colors.TopLevel.Normal);
  681. //Curses.addch ((int)(uint)' ');
  682. contents [row, col, 0] = ' ';
  683. contents [row, col, 1] = Colors.TopLevel.Normal;
  684. contents [row, col, 2] = 0;
  685. }
  686. }
  687. }
  688. public static bool Is_WSL_Platform ()
  689. {
  690. // xclip does not work on WSL, so we need to use the Windows clipboard vis Powershell
  691. //if (new CursesClipboard ().IsSupported) {
  692. // // If xclip is installed on Linux under WSL, this will return true.
  693. // return false;
  694. //}
  695. var (exitCode, result) = ClipboardProcessRunner.Bash ("uname -a", waitForOutput: true);
  696. if (exitCode == 0 && result.Contains ("microsoft") && result.Contains ("WSL")) {
  697. return true;
  698. }
  699. return false;
  700. }
  701. static int MapColor (Color color)
  702. {
  703. switch (color) {
  704. case Color.Black:
  705. return Curses.COLOR_BLACK;
  706. case Color.Blue:
  707. return Curses.COLOR_BLUE;
  708. case Color.Green:
  709. return Curses.COLOR_GREEN;
  710. case Color.Cyan:
  711. return Curses.COLOR_CYAN;
  712. case Color.Red:
  713. return Curses.COLOR_RED;
  714. case Color.Magenta:
  715. return Curses.COLOR_MAGENTA;
  716. case Color.Brown:
  717. return Curses.COLOR_YELLOW;
  718. case Color.Gray:
  719. return Curses.COLOR_WHITE;
  720. case Color.DarkGray:
  721. //return Curses.COLOR_BLACK | Curses.A_BOLD;
  722. return Curses.COLOR_GRAY;
  723. case Color.BrightBlue:
  724. return Curses.COLOR_BLUE | Curses.A_BOLD | Curses.COLOR_GRAY;
  725. case Color.BrightGreen:
  726. return Curses.COLOR_GREEN | Curses.A_BOLD | Curses.COLOR_GRAY;
  727. case Color.BrightCyan:
  728. return Curses.COLOR_CYAN | Curses.A_BOLD | Curses.COLOR_GRAY;
  729. case Color.BrightRed:
  730. return Curses.COLOR_RED | Curses.A_BOLD | Curses.COLOR_GRAY;
  731. case Color.BrightMagenta:
  732. return Curses.COLOR_MAGENTA | Curses.A_BOLD | Curses.COLOR_GRAY;
  733. case Color.BrightYellow:
  734. return Curses.COLOR_YELLOW | Curses.A_BOLD | Curses.COLOR_GRAY;
  735. case Color.White:
  736. return Curses.COLOR_WHITE | Curses.A_BOLD | Curses.COLOR_GRAY;
  737. }
  738. throw new ArgumentException ("Invalid color code");
  739. }
  740. static Color MapCursesColor (int color)
  741. {
  742. switch (color) {
  743. case Curses.COLOR_BLACK:
  744. return Color.Black;
  745. case Curses.COLOR_BLUE:
  746. return Color.Blue;
  747. case Curses.COLOR_GREEN:
  748. return Color.Green;
  749. case Curses.COLOR_CYAN:
  750. return Color.Cyan;
  751. case Curses.COLOR_RED:
  752. return Color.Red;
  753. case Curses.COLOR_MAGENTA:
  754. return Color.Magenta;
  755. case Curses.COLOR_YELLOW:
  756. return Color.Brown;
  757. case Curses.COLOR_WHITE:
  758. return Color.Gray;
  759. case Curses.COLOR_GRAY:
  760. return Color.DarkGray;
  761. case Curses.COLOR_BLUE | Curses.COLOR_GRAY:
  762. return Color.BrightBlue;
  763. case Curses.COLOR_GREEN | Curses.COLOR_GRAY:
  764. return Color.BrightGreen;
  765. case Curses.COLOR_CYAN | Curses.COLOR_GRAY:
  766. return Color.BrightCyan;
  767. case Curses.COLOR_RED | Curses.COLOR_GRAY:
  768. return Color.BrightRed;
  769. case Curses.COLOR_MAGENTA | Curses.COLOR_GRAY:
  770. return Color.BrightMagenta;
  771. case Curses.COLOR_YELLOW | Curses.COLOR_GRAY:
  772. return Color.BrightYellow;
  773. case Curses.COLOR_WHITE | Curses.COLOR_GRAY:
  774. return Color.White;
  775. }
  776. throw new ArgumentException ("Invalid curses color code");
  777. }
  778. public override Attribute MakeAttribute (Color fore, Color back)
  779. {
  780. var f = MapColor (fore);
  781. //return MakeColor ((short)(f & 0xffff), (short)MapColor (back)) | ((f & Curses.A_BOLD) != 0 ? Curses.A_BOLD : 0);
  782. return MakeColor ((short)(f & 0xffff), (short)MapColor (back));
  783. }
  784. public override void Suspend ()
  785. {
  786. StopReportingMouseMoves ();
  787. Platform.Suspend ();
  788. Curses.Window.Standard.redrawwin ();
  789. Curses.refresh ();
  790. StartReportingMouseMoves ();
  791. }
  792. public override void StartReportingMouseMoves ()
  793. {
  794. Console.Out.Write (EscSeqUtils.EnableMouseEvents);
  795. }
  796. public override void StopReportingMouseMoves ()
  797. {
  798. Console.Out.Write (EscSeqUtils.DisableMouseEvents);
  799. }
  800. //int lastMouseInterval;
  801. //bool mouseGrabbed;
  802. public override void UncookMouse ()
  803. {
  804. //if (mouseGrabbed)
  805. // return;
  806. //lastMouseInterval = Curses.mouseinterval (0);
  807. //mouseGrabbed = true;
  808. }
  809. public override void CookMouse ()
  810. {
  811. //mouseGrabbed = false;
  812. //Curses.mouseinterval (lastMouseInterval);
  813. }
  814. /// <inheritdoc/>
  815. public override bool GetCursorVisibility (out CursorVisibility visibility)
  816. {
  817. visibility = CursorVisibility.Invisible;
  818. if (!currentCursorVisibility.HasValue)
  819. return false;
  820. visibility = currentCursorVisibility.Value;
  821. return true;
  822. }
  823. /// <inheritdoc/>
  824. public override bool SetCursorVisibility (CursorVisibility visibility)
  825. {
  826. if (initialCursorVisibility.HasValue == false)
  827. return false;
  828. Curses.curs_set (((int)visibility >> 16) & 0x000000FF);
  829. if (visibility != CursorVisibility.Invisible) {
  830. Console.Out.Write ("\x1b[{0} q", ((int)visibility >> 24) & 0xFF);
  831. }
  832. currentCursorVisibility = visibility;
  833. return true;
  834. }
  835. /// <inheritdoc/>
  836. public override bool EnsureCursorVisibility ()
  837. {
  838. return false;
  839. }
  840. public override void SendKeys (char keyChar, ConsoleKey consoleKey, bool shift, bool alt, bool control)
  841. {
  842. Key key;
  843. if (consoleKey == ConsoleKey.Packet) {
  844. ConsoleModifiers mod = new ConsoleModifiers ();
  845. if (shift) {
  846. mod |= ConsoleModifiers.Shift;
  847. }
  848. if (alt) {
  849. mod |= ConsoleModifiers.Alt;
  850. }
  851. if (control) {
  852. mod |= ConsoleModifiers.Control;
  853. }
  854. var kchar = ConsoleKeyMapping.GetKeyCharFromConsoleKey (keyChar, mod, out uint ckey, out _);
  855. key = ConsoleKeyMapping.MapConsoleKeyToKey ((ConsoleKey)ckey, out bool mappable);
  856. if (mappable) {
  857. key = (Key)kchar;
  858. }
  859. } else {
  860. key = (Key)keyChar;
  861. }
  862. KeyModifiers km = new KeyModifiers ();
  863. if (shift) {
  864. if (keyChar == 0) {
  865. key |= Key.ShiftMask;
  866. }
  867. km.Shift = shift;
  868. }
  869. if (alt) {
  870. key |= Key.AltMask;
  871. km.Alt = alt;
  872. }
  873. if (control) {
  874. key |= Key.CtrlMask;
  875. km.Ctrl = control;
  876. }
  877. keyDownHandler (new KeyEvent (key, km));
  878. keyHandler (new KeyEvent (key, km));
  879. keyUpHandler (new KeyEvent (key, km));
  880. }
  881. public override bool GetColors (int value, out Color foreground, out Color background)
  882. {
  883. bool hasColor = false;
  884. foreground = default;
  885. background = default;
  886. int back = -1;
  887. IEnumerable<int> values = Enum.GetValues (typeof (ConsoleColor))
  888. .OfType<ConsoleColor> ()
  889. .Select (s => (int)s);
  890. if (values.Contains ((value >> 12) & 0xffff)) {
  891. hasColor = true;
  892. back = (value >> 12) & 0xffff;
  893. background = MapCursesColor (back);
  894. }
  895. if (values.Contains ((value - (back << 12)) >> 8)) {
  896. hasColor = true;
  897. foreground = MapCursesColor ((value - (back << 12)) >> 8);
  898. }
  899. return hasColor;
  900. }
  901. }
  902. internal static class Platform {
  903. [DllImport ("libc")]
  904. static extern int uname (IntPtr buf);
  905. [DllImport ("libc")]
  906. static extern int killpg (int pgrp, int pid);
  907. static int suspendSignal;
  908. static int GetSuspendSignal ()
  909. {
  910. if (suspendSignal != 0)
  911. return suspendSignal;
  912. IntPtr buf = Marshal.AllocHGlobal (8192);
  913. if (uname (buf) != 0) {
  914. Marshal.FreeHGlobal (buf);
  915. suspendSignal = -1;
  916. return suspendSignal;
  917. }
  918. try {
  919. switch (Marshal.PtrToStringAnsi (buf)) {
  920. case "Darwin":
  921. case "DragonFly":
  922. case "FreeBSD":
  923. case "NetBSD":
  924. case "OpenBSD":
  925. suspendSignal = 18;
  926. break;
  927. case "Linux":
  928. // TODO: should fetch the machine name and
  929. // if it is MIPS return 24
  930. suspendSignal = 20;
  931. break;
  932. case "Solaris":
  933. suspendSignal = 24;
  934. break;
  935. default:
  936. suspendSignal = -1;
  937. break;
  938. }
  939. return suspendSignal;
  940. } finally {
  941. Marshal.FreeHGlobal (buf);
  942. }
  943. }
  944. /// <summary>
  945. /// Suspends the process by sending SIGTSTP to itself
  946. /// </summary>
  947. /// <returns>The suspend.</returns>
  948. static public bool Suspend ()
  949. {
  950. int signal = GetSuspendSignal ();
  951. if (signal == -1)
  952. return false;
  953. killpg (0, signal);
  954. return true;
  955. }
  956. }
  957. /// <summary>
  958. /// A clipboard implementation for Linux.
  959. /// This implementation uses the xclip command to access the clipboard.
  960. /// </summary>
  961. /// <remarks>
  962. /// If xclip is not installed, this implementation will not work.
  963. /// </remarks>
  964. class CursesClipboard : ClipboardBase {
  965. public CursesClipboard ()
  966. {
  967. IsSupported = CheckSupport ();
  968. }
  969. string xclipPath = string.Empty;
  970. public override bool IsSupported { get; }
  971. bool CheckSupport ()
  972. {
  973. #pragma warning disable RCS1075 // Avoid empty catch clause that catches System.Exception.
  974. try {
  975. var (exitCode, result) = ClipboardProcessRunner.Bash ("which xclip", waitForOutput: true);
  976. if (exitCode == 0 && result.FileExists ()) {
  977. xclipPath = result;
  978. return true;
  979. }
  980. } catch (Exception) {
  981. // Permissions issue.
  982. }
  983. #pragma warning restore RCS1075 // Avoid empty catch clause that catches System.Exception.
  984. return false;
  985. }
  986. protected override string GetClipboardDataImpl ()
  987. {
  988. var tempFileName = System.IO.Path.GetTempFileName ();
  989. var xclipargs = "-selection clipboard -o";
  990. try {
  991. var (exitCode, result) = ClipboardProcessRunner.Bash ($"{xclipPath} {xclipargs} > {tempFileName}", waitForOutput: false);
  992. if (exitCode == 0) {
  993. if (Application.Driver is CursesDriver) {
  994. Curses.raw ();
  995. Curses.noecho ();
  996. }
  997. return System.IO.File.ReadAllText (tempFileName);
  998. }
  999. } catch (Exception e) {
  1000. throw new NotSupportedException ($"\"{xclipPath} {xclipargs}\" failed.", e);
  1001. } finally {
  1002. System.IO.File.Delete (tempFileName);
  1003. }
  1004. return string.Empty;
  1005. }
  1006. protected override void SetClipboardDataImpl (string text)
  1007. {
  1008. var xclipargs = "-selection clipboard -i";
  1009. try {
  1010. var (exitCode, _) = ClipboardProcessRunner.Bash ($"{xclipPath} {xclipargs}", text, waitForOutput: false);
  1011. if (exitCode == 0 && Application.Driver is CursesDriver) {
  1012. Curses.raw ();
  1013. Curses.noecho ();
  1014. }
  1015. } catch (Exception e) {
  1016. throw new NotSupportedException ($"\"{xclipPath} {xclipargs} < {text}\" failed", e);
  1017. }
  1018. }
  1019. }
  1020. /// <summary>
  1021. /// A clipboard implementation for MacOSX.
  1022. /// This implementation uses the Mac clipboard API (via P/Invoke) to copy/paste.
  1023. /// The existance of the Mac pbcopy and pbpaste commands
  1024. /// is used to determine if copy/paste is supported.
  1025. /// </summary>
  1026. class MacOSXClipboard : ClipboardBase {
  1027. IntPtr nsString = objc_getClass ("NSString");
  1028. IntPtr nsPasteboard = objc_getClass ("NSPasteboard");
  1029. IntPtr utfTextType;
  1030. IntPtr generalPasteboard;
  1031. IntPtr initWithUtf8Register = sel_registerName ("initWithUTF8String:");
  1032. IntPtr allocRegister = sel_registerName ("alloc");
  1033. IntPtr setStringRegister = sel_registerName ("setString:forType:");
  1034. IntPtr stringForTypeRegister = sel_registerName ("stringForType:");
  1035. IntPtr utf8Register = sel_registerName ("UTF8String");
  1036. IntPtr nsStringPboardType;
  1037. IntPtr generalPasteboardRegister = sel_registerName ("generalPasteboard");
  1038. IntPtr clearContentsRegister = sel_registerName ("clearContents");
  1039. public MacOSXClipboard ()
  1040. {
  1041. utfTextType = objc_msgSend (objc_msgSend (nsString, allocRegister), initWithUtf8Register, "public.utf8-plain-text");
  1042. nsStringPboardType = objc_msgSend (objc_msgSend (nsString, allocRegister), initWithUtf8Register, "NSStringPboardType");
  1043. generalPasteboard = objc_msgSend (nsPasteboard, generalPasteboardRegister);
  1044. IsSupported = CheckSupport ();
  1045. }
  1046. public override bool IsSupported { get; }
  1047. bool CheckSupport ()
  1048. {
  1049. var (exitCode, result) = ClipboardProcessRunner.Bash ("which pbcopy", waitForOutput: true);
  1050. if (exitCode != 0 || !result.FileExists ()) {
  1051. return false;
  1052. }
  1053. (exitCode, result) = ClipboardProcessRunner.Bash ("which pbpaste", waitForOutput: true);
  1054. return exitCode == 0 && result.FileExists ();
  1055. }
  1056. protected override string GetClipboardDataImpl ()
  1057. {
  1058. var ptr = objc_msgSend (generalPasteboard, stringForTypeRegister, nsStringPboardType);
  1059. var charArray = objc_msgSend (ptr, utf8Register);
  1060. return Marshal.PtrToStringAnsi (charArray);
  1061. }
  1062. protected override void SetClipboardDataImpl (string text)
  1063. {
  1064. IntPtr str = default;
  1065. try {
  1066. str = objc_msgSend (objc_msgSend (nsString, allocRegister), initWithUtf8Register, text);
  1067. objc_msgSend (generalPasteboard, clearContentsRegister);
  1068. objc_msgSend (generalPasteboard, setStringRegister, str, utfTextType);
  1069. } finally {
  1070. if (str != default) {
  1071. objc_msgSend (str, sel_registerName ("release"));
  1072. }
  1073. }
  1074. }
  1075. [DllImport ("/System/Library/Frameworks/AppKit.framework/AppKit")]
  1076. static extern IntPtr objc_getClass (string className);
  1077. [DllImport ("/System/Library/Frameworks/AppKit.framework/AppKit")]
  1078. static extern IntPtr objc_msgSend (IntPtr receiver, IntPtr selector);
  1079. [DllImport ("/System/Library/Frameworks/AppKit.framework/AppKit")]
  1080. static extern IntPtr objc_msgSend (IntPtr receiver, IntPtr selector, string arg1);
  1081. [DllImport ("/System/Library/Frameworks/AppKit.framework/AppKit")]
  1082. static extern IntPtr objc_msgSend (IntPtr receiver, IntPtr selector, IntPtr arg1);
  1083. [DllImport ("/System/Library/Frameworks/AppKit.framework/AppKit")]
  1084. static extern IntPtr objc_msgSend (IntPtr receiver, IntPtr selector, IntPtr arg1, IntPtr arg2);
  1085. [DllImport ("/System/Library/Frameworks/AppKit.framework/AppKit")]
  1086. static extern IntPtr sel_registerName (string selectorName);
  1087. }
  1088. /// <summary>
  1089. /// A clipboard implementation for Linux, when running under WSL.
  1090. /// This implementation uses the Windows clipboard to store the data, and uses Windows'
  1091. /// powershell.exe (launched via WSL interop services) to set/get the Windows
  1092. /// clipboard.
  1093. /// </summary>
  1094. class WSLClipboard : ClipboardBase {
  1095. bool isSupported = false;
  1096. public WSLClipboard ()
  1097. {
  1098. isSupported = CheckSupport ();
  1099. }
  1100. public override bool IsSupported {
  1101. get {
  1102. return isSupported = CheckSupport ();
  1103. }
  1104. }
  1105. private static string powershellPath = string.Empty;
  1106. bool CheckSupport ()
  1107. {
  1108. if (string.IsNullOrEmpty (powershellPath)) {
  1109. // Specify pwsh.exe (not pwsh) to ensure we get the Windows version (invoked via WSL)
  1110. var (exitCode, result) = ClipboardProcessRunner.Bash ("which pwsh.exe", waitForOutput: true);
  1111. if (exitCode > 0) {
  1112. (exitCode, result) = ClipboardProcessRunner.Bash ("which powershell.exe", waitForOutput: true);
  1113. }
  1114. if (exitCode == 0) {
  1115. powershellPath = result;
  1116. }
  1117. }
  1118. return !string.IsNullOrEmpty (powershellPath);
  1119. }
  1120. protected override string GetClipboardDataImpl ()
  1121. {
  1122. if (!IsSupported) {
  1123. return string.Empty;
  1124. }
  1125. var (exitCode, output) = ClipboardProcessRunner.Process (powershellPath, "-noprofile -command \"Get-Clipboard\"");
  1126. if (exitCode == 0) {
  1127. if (Application.Driver is CursesDriver) {
  1128. Curses.raw ();
  1129. Curses.noecho ();
  1130. }
  1131. if (output.EndsWith ("\r\n")) {
  1132. output = output.Substring (0, output.Length - 2);
  1133. }
  1134. return output;
  1135. }
  1136. return string.Empty;
  1137. }
  1138. protected override void SetClipboardDataImpl (string text)
  1139. {
  1140. if (!IsSupported) {
  1141. return;
  1142. }
  1143. var (exitCode, output) = ClipboardProcessRunner.Process (powershellPath, $"-noprofile -command \"Set-Clipboard -Value \\\"{text}\\\"\"");
  1144. if (exitCode == 0) {
  1145. if (Application.Driver is CursesDriver) {
  1146. Curses.raw ();
  1147. Curses.noecho ();
  1148. }
  1149. }
  1150. }
  1151. }
  1152. }