CursesDriver.cs 36 KB

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