CursesDriver.cs 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198
  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. }
  128. private void ProcessWinChange ()
  129. {
  130. if (Curses.CheckWinChange ()) {
  131. ResizeScreen ();
  132. UpdateOffScreen ();
  133. TerminalResized?.Invoke ();
  134. }
  135. }
  136. public override void UpdateCursor () => Refresh ();
  137. public override void End ()
  138. {
  139. StopReportingMouseMoves ();
  140. SetCursorVisibility (CursorVisibility.Default);
  141. var code = Curses.get_wch (out _);
  142. while (code != -1) {
  143. code = Curses.get_wch (out _);
  144. }
  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. if (wch == Curses.KeyResize) {
  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. }
  312. if (wch == Curses.KeyMouse) {
  313. int wch2 = wch;
  314. while (wch2 == Curses.KeyMouse) {
  315. KeyEvent key = null;
  316. ConsoleKeyInfo [] cki = new ConsoleKeyInfo [] {
  317. new ConsoleKeyInfo ((char)Key.Esc, 0, false, false, false),
  318. new ConsoleKeyInfo ('[', 0, false, false, false),
  319. new ConsoleKeyInfo ('<', 0, false, false, false)
  320. };
  321. code = 0;
  322. GetEscSeq (ref code, ref k, ref wch2, ref key, ref cki);
  323. }
  324. return;
  325. }
  326. k = MapCursesKey (wch);
  327. if (wch >= 277 && wch <= 288) { // Shift+(F1 - F12)
  328. wch -= 12;
  329. k = Key.ShiftMask | MapCursesKey (wch);
  330. } else if (wch >= 289 && wch <= 300) { // Ctrl+(F1 - F12)
  331. wch -= 24;
  332. k = Key.CtrlMask | MapCursesKey (wch);
  333. } else if (wch >= 301 && wch <= 312) { // Ctrl+Shift+(F1 - F12)
  334. wch -= 36;
  335. k = Key.CtrlMask | Key.ShiftMask | MapCursesKey (wch);
  336. } else if (wch >= 313 && wch <= 324) { // Alt+(F1 - F12)
  337. wch -= 48;
  338. k = Key.AltMask | MapCursesKey (wch);
  339. } else if (wch >= 325 && wch <= 327) { // Shift+Alt+(F1 - F3)
  340. wch -= 60;
  341. k = Key.ShiftMask | Key.AltMask | MapCursesKey (wch);
  342. }
  343. keyDownHandler (new KeyEvent (k, MapKeyModifiers (k)));
  344. keyHandler (new KeyEvent (k, MapKeyModifiers (k)));
  345. keyUpHandler (new KeyEvent (k, MapKeyModifiers (k)));
  346. return;
  347. }
  348. // Special handling for ESC, we want to try to catch ESC+letter to simulate alt-letter as well as Alt-Fkey
  349. if (wch == 27) {
  350. Curses.timeout (10);
  351. code = Curses.get_wch (out int wch2);
  352. if (code == Curses.KEY_CODE_YES) {
  353. k = Key.AltMask | MapCursesKey (wch);
  354. }
  355. if (code == 0) {
  356. KeyEvent key = null;
  357. // The ESC-number handling, debatable.
  358. // Simulates the AltMask itself by pressing Alt + Space.
  359. if (wch2 == (int)Key.Space) {
  360. k = Key.AltMask;
  361. } else if (wch2 - (int)Key.Space >= (uint)Key.A && wch2 - (int)Key.Space <= (uint)Key.Z) {
  362. k = (Key)((uint)Key.AltMask + (wch2 - (int)Key.Space));
  363. } else if (wch2 >= (uint)Key.A - 64 && wch2 <= (uint)Key.Z - 64) {
  364. k = (Key)((uint)(Key.AltMask | Key.CtrlMask) + (wch2 + 64));
  365. } else if (wch2 >= (uint)Key.D0 && wch2 <= (uint)Key.D9) {
  366. k = (Key)((uint)Key.AltMask + (uint)Key.D0 + (wch2 - (uint)Key.D0));
  367. } else if (wch2 == Curses.KeyCSI) {
  368. ConsoleKeyInfo [] cki = new ConsoleKeyInfo [] {
  369. new ConsoleKeyInfo ((char)Key.Esc, 0, false, false, false),
  370. new ConsoleKeyInfo ('[', 0, false, false, false)
  371. };
  372. GetEscSeq (ref code, ref k, ref wch2, ref key, ref cki);
  373. return;
  374. } else {
  375. // Unfortunately there are no way to differentiate Ctrl+Alt+alfa and Ctrl+Shift+Alt+alfa.
  376. if (((Key)wch2 & Key.CtrlMask) != 0) {
  377. keyModifiers.Ctrl = true;
  378. }
  379. if (wch2 == 0) {
  380. k = Key.CtrlMask | Key.AltMask | Key.Space;
  381. } else if (wch >= (uint)Key.A && wch <= (uint)Key.Z) {
  382. keyModifiers.Shift = true;
  383. keyModifiers.Alt = true;
  384. } else if (wch2 < 256) {
  385. k = (Key)wch2;
  386. keyModifiers.Alt = true;
  387. } else {
  388. k = (Key)((uint)(Key.AltMask | Key.CtrlMask) + wch2);
  389. }
  390. }
  391. key = new KeyEvent (k, MapKeyModifiers (k));
  392. keyDownHandler (key);
  393. keyHandler (key);
  394. } else {
  395. k = Key.Esc;
  396. keyHandler (new KeyEvent (k, MapKeyModifiers (k)));
  397. }
  398. } else if (wch == Curses.KeyTab) {
  399. k = MapCursesKey (wch);
  400. keyDownHandler (new KeyEvent (k, MapKeyModifiers (k)));
  401. keyHandler (new KeyEvent (k, MapKeyModifiers (k)));
  402. } else {
  403. // Unfortunately there are no way to differentiate Ctrl+alfa and Ctrl+Shift+alfa.
  404. k = (Key)wch;
  405. if (wch == 0) {
  406. k = Key.CtrlMask | Key.Space;
  407. } else if (wch >= (uint)Key.A - 64 && wch <= (uint)Key.Z - 64) {
  408. if ((Key)(wch + 64) != Key.J) {
  409. k = Key.CtrlMask | (Key)(wch + 64);
  410. }
  411. } else if (wch >= (uint)Key.A && wch <= (uint)Key.Z) {
  412. keyModifiers.Shift = true;
  413. }
  414. keyDownHandler (new KeyEvent (k, MapKeyModifiers (k)));
  415. keyHandler (new KeyEvent (k, MapKeyModifiers (k)));
  416. keyUpHandler (new KeyEvent (k, MapKeyModifiers (k)));
  417. }
  418. // Cause OnKeyUp and OnKeyPressed. Note that the special handling for ESC above
  419. // will not impact KeyUp.
  420. // This is causing ESC firing even if another keystroke was handled.
  421. //if (wch == Curses.KeyTab) {
  422. // keyUpHandler (new KeyEvent (MapCursesKey (wch), keyModifiers));
  423. //} else {
  424. // keyUpHandler (new KeyEvent ((Key)wch, keyModifiers));
  425. //}
  426. }
  427. void GetEscSeq (ref int code, ref Key k, ref int wch2, ref KeyEvent key, ref ConsoleKeyInfo [] cki)
  428. {
  429. ConsoleKey ck = 0;
  430. ConsoleModifiers mod = 0;
  431. while (code == 0) {
  432. code = Curses.get_wch (out wch2);
  433. var consoleKeyInfo = new ConsoleKeyInfo ((char)wch2, 0, false, false, false);
  434. if (wch2 == 0 || wch2 == 27 || wch2 == Curses.KeyMouse) {
  435. 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);
  436. if (isKeyMouse) {
  437. foreach (var mf in mouseFlags) {
  438. ProcessMouseEvent (mf, pos);
  439. }
  440. cki = null;
  441. if (wch2 == 27) {
  442. cki = EscSeqUtils.ResizeArray (new ConsoleKeyInfo ((char)Key.Esc, 0,
  443. false, false, false), cki);
  444. }
  445. } else {
  446. k = ConsoleKeyMapping.MapConsoleKeyToKey (consoleKeyInfo.Key, out _);
  447. k = ConsoleKeyMapping.MapKeyModifiers (consoleKeyInfo, k);
  448. key = new KeyEvent (k, MapKeyModifiers (k));
  449. keyDownHandler (key);
  450. keyHandler (key);
  451. }
  452. } else {
  453. cki = EscSeqUtils.ResizeArray (consoleKeyInfo, cki);
  454. }
  455. }
  456. }
  457. MouseFlags lastMouseFlags;
  458. void ProcessMouseEvent (MouseFlags mouseFlag, Point pos)
  459. {
  460. if (((mouseFlag.HasFlag (MouseFlags.Button1Released) || mouseFlag.HasFlag (MouseFlags.Button2Released) || mouseFlag.HasFlag (MouseFlags.Button3Released) || mouseFlag.HasFlag (MouseFlags.Button4Released))
  461. && (!lastMouseFlags.HasFlag (MouseFlags.Button1Pressed) || !lastMouseFlags.HasFlag (MouseFlags.Button2Pressed) || !lastMouseFlags.HasFlag (MouseFlags.Button3Pressed) || !lastMouseFlags.HasFlag (MouseFlags.Button4Pressed)))
  462. || ((mouseFlag.HasFlag (MouseFlags.Button1Clicked) || mouseFlag.HasFlag (MouseFlags.Button2Clicked) || mouseFlag.HasFlag (MouseFlags.Button3Clicked) || mouseFlag.HasFlag (MouseFlags.Button4Clicked)
  463. || mouseFlag.HasFlag (MouseFlags.Button1DoubleClicked) || mouseFlag.HasFlag (MouseFlags.Button2DoubleClicked) || mouseFlag.HasFlag (MouseFlags.Button3DoubleClicked) || mouseFlag.HasFlag (MouseFlags.Button4DoubleClicked))
  464. && lastMouseFlags == 0)) {
  465. return;
  466. }
  467. lastMouseFlags = mouseFlag;
  468. var me = new MouseEvent () {
  469. Flags = mouseFlag,
  470. X = pos.X,
  471. Y = pos.Y
  472. };
  473. mouseHandler (me);
  474. }
  475. void ProcessContinuousButtonPressed (MouseFlags mouseFlag, Point pos)
  476. {
  477. ProcessMouseEvent (mouseFlag, pos);
  478. }
  479. Action<KeyEvent> keyHandler;
  480. Action<KeyEvent> keyDownHandler;
  481. Action<KeyEvent> keyUpHandler;
  482. Action<MouseEvent> mouseHandler;
  483. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
  484. {
  485. // Note: Curses doesn't support keydown/up events and thus any passed keyDown/UpHandlers will never be called
  486. Curses.timeout (0);
  487. this.keyHandler = keyHandler;
  488. this.keyDownHandler = keyDownHandler;
  489. this.keyUpHandler = keyUpHandler;
  490. this.mouseHandler = mouseHandler;
  491. var mLoop = mainLoop.Driver as UnixMainLoop;
  492. mLoop.AddWatch (0, UnixMainLoop.Condition.PollIn, x => {
  493. ProcessInput ();
  494. return true;
  495. });
  496. mLoop.WinChanged += () => {
  497. ProcessInput ();
  498. };
  499. }
  500. public override void Init (Action terminalResized)
  501. {
  502. if (window != null)
  503. return;
  504. try {
  505. window = Curses.initscr ();
  506. Curses.set_escdelay (10);
  507. } catch (Exception e) {
  508. throw new Exception ($"Curses failed to initialize, the exception is: {e.Message}");
  509. }
  510. // Ensures that all procedures are performed at some previous closing.
  511. Curses.doupdate ();
  512. //
  513. // We are setting Invisible as default so we could ignore XTerm DECSUSR setting
  514. //
  515. switch (Curses.curs_set (0)) {
  516. case 0:
  517. currentCursorVisibility = initialCursorVisibility = CursorVisibility.Invisible;
  518. break;
  519. case 1:
  520. currentCursorVisibility = initialCursorVisibility = CursorVisibility.Underline;
  521. Curses.curs_set (1);
  522. break;
  523. case 2:
  524. currentCursorVisibility = initialCursorVisibility = CursorVisibility.Box;
  525. Curses.curs_set (2);
  526. break;
  527. default:
  528. currentCursorVisibility = initialCursorVisibility = null;
  529. break;
  530. }
  531. if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX)) {
  532. clipboard = new MacOSXClipboard ();
  533. } else {
  534. if (Is_WSL_Platform ()) {
  535. clipboard = new WSLClipboard ();
  536. } else {
  537. clipboard = new CursesClipboard ();
  538. }
  539. }
  540. Curses.raw ();
  541. Curses.noecho ();
  542. Curses.Window.Standard.keypad (true);
  543. TerminalResized = terminalResized;
  544. StartReportingMouseMoves ();
  545. CurrentAttribute = MakeColor (Color.White, Color.Black);
  546. if (Curses.HasColors) {
  547. Curses.StartColor ();
  548. Curses.UseDefaultColors ();
  549. InitalizeColorSchemes ();
  550. } else {
  551. InitalizeColorSchemes (false);
  552. // BUGBUG: This is a hack to make the colors work on the Mac?
  553. // The new Theme support overwrites these colors, so this is not needed?
  554. Colors.TopLevel.Normal = Curses.COLOR_GREEN;
  555. Colors.TopLevel.Focus = Curses.COLOR_WHITE;
  556. Colors.TopLevel.HotNormal = Curses.COLOR_YELLOW;
  557. Colors.TopLevel.HotFocus = Curses.COLOR_YELLOW;
  558. Colors.TopLevel.Disabled = Curses.A_BOLD | Curses.COLOR_GRAY;
  559. Colors.Base.Normal = Curses.A_NORMAL;
  560. Colors.Base.Focus = Curses.A_REVERSE;
  561. Colors.Base.HotNormal = Curses.A_BOLD;
  562. Colors.Base.HotFocus = Curses.A_BOLD | Curses.A_REVERSE;
  563. Colors.Base.Disabled = Curses.A_BOLD | Curses.COLOR_GRAY;
  564. Colors.Menu.Normal = Curses.A_REVERSE;
  565. Colors.Menu.Focus = Curses.A_NORMAL;
  566. Colors.Menu.HotNormal = Curses.A_BOLD;
  567. Colors.Menu.HotFocus = Curses.A_NORMAL;
  568. Colors.Menu.Disabled = Curses.A_BOLD | Curses.COLOR_GRAY;
  569. Colors.Dialog.Normal = Curses.A_REVERSE;
  570. Colors.Dialog.Focus = Curses.A_NORMAL;
  571. Colors.Dialog.HotNormal = Curses.A_BOLD;
  572. Colors.Dialog.HotFocus = Curses.A_NORMAL;
  573. Colors.Dialog.Disabled = Curses.A_BOLD | Curses.COLOR_GRAY;
  574. Colors.Error.Normal = Curses.A_BOLD;
  575. Colors.Error.Focus = Curses.A_BOLD | Curses.A_REVERSE;
  576. Colors.Error.HotNormal = Curses.A_BOLD | Curses.A_REVERSE;
  577. Colors.Error.HotFocus = Curses.A_REVERSE;
  578. Colors.Error.Disabled = Curses.A_BOLD | Curses.COLOR_GRAY;
  579. }
  580. ResizeScreen ();
  581. UpdateOffScreen ();
  582. }
  583. public override void ResizeScreen ()
  584. {
  585. Clip = new Rect (0, 0, Cols, Rows);
  586. Curses.refresh ();
  587. }
  588. public override void UpdateOffScreen ()
  589. {
  590. contents = new int [Rows, Cols, 3];
  591. for (int row = 0; row < Rows; row++) {
  592. for (int col = 0; col < Cols; col++) {
  593. //Curses.move (row, col);
  594. //Curses.attrset (Colors.TopLevel.Normal);
  595. //Curses.addch ((int)(uint)' ');
  596. contents [row, col, 0] = ' ';
  597. contents [row, col, 1] = Colors.TopLevel.Normal;
  598. contents [row, col, 2] = 0;
  599. }
  600. }
  601. }
  602. public static bool Is_WSL_Platform ()
  603. {
  604. // xclip does not work on WSL, so we need to use the Windows clipboard vis Powershell
  605. //if (new CursesClipboard ().IsSupported) {
  606. // // If xclip is installed on Linux under WSL, this will return true.
  607. // return false;
  608. //}
  609. var (exitCode, result) = ClipboardProcessRunner.Bash ("uname -a", waitForOutput: true);
  610. if (exitCode == 0 && result.Contains ("microsoft") && result.Contains ("WSL")) {
  611. return true;
  612. }
  613. return false;
  614. }
  615. static int MapColor (Color color)
  616. {
  617. switch (color) {
  618. case Color.Black:
  619. return Curses.COLOR_BLACK;
  620. case Color.Blue:
  621. return Curses.COLOR_BLUE;
  622. case Color.Green:
  623. return Curses.COLOR_GREEN;
  624. case Color.Cyan:
  625. return Curses.COLOR_CYAN;
  626. case Color.Red:
  627. return Curses.COLOR_RED;
  628. case Color.Magenta:
  629. return Curses.COLOR_MAGENTA;
  630. case Color.Brown:
  631. return Curses.COLOR_YELLOW;
  632. case Color.Gray:
  633. return Curses.COLOR_WHITE;
  634. case Color.DarkGray:
  635. //return Curses.COLOR_BLACK | Curses.A_BOLD;
  636. return Curses.COLOR_GRAY;
  637. case Color.BrightBlue:
  638. return Curses.COLOR_BLUE | Curses.A_BOLD | Curses.COLOR_GRAY;
  639. case Color.BrightGreen:
  640. return Curses.COLOR_GREEN | Curses.A_BOLD | Curses.COLOR_GRAY;
  641. case Color.BrightCyan:
  642. return Curses.COLOR_CYAN | Curses.A_BOLD | Curses.COLOR_GRAY;
  643. case Color.BrightRed:
  644. return Curses.COLOR_RED | Curses.A_BOLD | Curses.COLOR_GRAY;
  645. case Color.BrightMagenta:
  646. return Curses.COLOR_MAGENTA | Curses.A_BOLD | Curses.COLOR_GRAY;
  647. case Color.BrightYellow:
  648. return Curses.COLOR_YELLOW | Curses.A_BOLD | Curses.COLOR_GRAY;
  649. case Color.White:
  650. return Curses.COLOR_WHITE | Curses.A_BOLD | Curses.COLOR_GRAY;
  651. }
  652. throw new ArgumentException ("Invalid color code");
  653. }
  654. static Color MapCursesColor (int color)
  655. {
  656. switch (color) {
  657. case Curses.COLOR_BLACK:
  658. return Color.Black;
  659. case Curses.COLOR_BLUE:
  660. return Color.Blue;
  661. case Curses.COLOR_GREEN:
  662. return Color.Green;
  663. case Curses.COLOR_CYAN:
  664. return Color.Cyan;
  665. case Curses.COLOR_RED:
  666. return Color.Red;
  667. case Curses.COLOR_MAGENTA:
  668. return Color.Magenta;
  669. case Curses.COLOR_YELLOW:
  670. return Color.Brown;
  671. case Curses.COLOR_WHITE:
  672. return Color.Gray;
  673. case Curses.COLOR_GRAY:
  674. return Color.DarkGray;
  675. case Curses.COLOR_BLUE | Curses.COLOR_GRAY:
  676. return Color.BrightBlue;
  677. case Curses.COLOR_GREEN | Curses.COLOR_GRAY:
  678. return Color.BrightGreen;
  679. case Curses.COLOR_CYAN | Curses.COLOR_GRAY:
  680. return Color.BrightCyan;
  681. case Curses.COLOR_RED | Curses.COLOR_GRAY:
  682. return Color.BrightRed;
  683. case Curses.COLOR_MAGENTA | Curses.COLOR_GRAY:
  684. return Color.BrightMagenta;
  685. case Curses.COLOR_YELLOW | Curses.COLOR_GRAY:
  686. return Color.BrightYellow;
  687. case Curses.COLOR_WHITE | Curses.COLOR_GRAY:
  688. return Color.White;
  689. }
  690. throw new ArgumentException ("Invalid curses color code");
  691. }
  692. public override Attribute MakeAttribute (Color fore, Color back)
  693. {
  694. var f = MapColor (fore);
  695. //return MakeColor ((short)(f & 0xffff), (short)MapColor (back)) | ((f & Curses.A_BOLD) != 0 ? Curses.A_BOLD : 0);
  696. return MakeColor ((short)(f & 0xffff), (short)MapColor (back));
  697. }
  698. public override void Suspend ()
  699. {
  700. StopReportingMouseMoves ();
  701. Platform.Suspend ();
  702. Curses.Window.Standard.redrawwin ();
  703. Curses.refresh ();
  704. StartReportingMouseMoves ();
  705. }
  706. public override void StartReportingMouseMoves ()
  707. {
  708. Console.Out.Write (EscSeqUtils.EnableMouseEvents);
  709. }
  710. public override void StopReportingMouseMoves ()
  711. {
  712. Console.Out.Write (EscSeqUtils.DisableMouseEvents);
  713. }
  714. //int lastMouseInterval;
  715. //bool mouseGrabbed;
  716. public override void UncookMouse ()
  717. {
  718. //if (mouseGrabbed)
  719. // return;
  720. //lastMouseInterval = Curses.mouseinterval (0);
  721. //mouseGrabbed = true;
  722. }
  723. public override void CookMouse ()
  724. {
  725. //mouseGrabbed = false;
  726. //Curses.mouseinterval (lastMouseInterval);
  727. }
  728. /// <inheritdoc/>
  729. public override bool GetCursorVisibility (out CursorVisibility visibility)
  730. {
  731. visibility = CursorVisibility.Invisible;
  732. if (!currentCursorVisibility.HasValue)
  733. return false;
  734. visibility = currentCursorVisibility.Value;
  735. return true;
  736. }
  737. /// <inheritdoc/>
  738. public override bool SetCursorVisibility (CursorVisibility visibility)
  739. {
  740. if (initialCursorVisibility.HasValue == false)
  741. return false;
  742. Curses.curs_set (((int)visibility >> 16) & 0x000000FF);
  743. if (visibility != CursorVisibility.Invisible) {
  744. Console.Out.Write ("\x1b[{0} q", ((int)visibility >> 24) & 0xFF);
  745. }
  746. currentCursorVisibility = visibility;
  747. return true;
  748. }
  749. /// <inheritdoc/>
  750. public override bool EnsureCursorVisibility ()
  751. {
  752. return false;
  753. }
  754. public override void SendKeys (char keyChar, ConsoleKey consoleKey, bool shift, bool alt, bool control)
  755. {
  756. Key key;
  757. if (consoleKey == ConsoleKey.Packet) {
  758. ConsoleModifiers mod = new ConsoleModifiers ();
  759. if (shift) {
  760. mod |= ConsoleModifiers.Shift;
  761. }
  762. if (alt) {
  763. mod |= ConsoleModifiers.Alt;
  764. }
  765. if (control) {
  766. mod |= ConsoleModifiers.Control;
  767. }
  768. var kchar = ConsoleKeyMapping.GetKeyCharFromConsoleKey (keyChar, mod, out uint ckey, out _);
  769. key = ConsoleKeyMapping.MapConsoleKeyToKey ((ConsoleKey)ckey, out bool mappable);
  770. if (mappable) {
  771. key = (Key)kchar;
  772. }
  773. } else {
  774. key = (Key)keyChar;
  775. }
  776. KeyModifiers km = new KeyModifiers ();
  777. if (shift) {
  778. if (keyChar == 0) {
  779. key |= Key.ShiftMask;
  780. }
  781. km.Shift = shift;
  782. }
  783. if (alt) {
  784. key |= Key.AltMask;
  785. km.Alt = alt;
  786. }
  787. if (control) {
  788. key |= Key.CtrlMask;
  789. km.Ctrl = control;
  790. }
  791. keyDownHandler (new KeyEvent (key, km));
  792. keyHandler (new KeyEvent (key, km));
  793. keyUpHandler (new KeyEvent (key, km));
  794. }
  795. public override bool GetColors (int value, out Color foreground, out Color background)
  796. {
  797. bool hasColor = false;
  798. foreground = default;
  799. background = default;
  800. int back = -1;
  801. IEnumerable<int> values = Enum.GetValues (typeof (ConsoleColor))
  802. .OfType<ConsoleColor> ()
  803. .Select (s => (int)s);
  804. if (values.Contains ((value >> 12) & 0xffff)) {
  805. hasColor = true;
  806. back = (value >> 12) & 0xffff;
  807. background = MapCursesColor (back);
  808. }
  809. if (values.Contains ((value - (back << 12)) >> 8)) {
  810. hasColor = true;
  811. foreground = MapCursesColor ((value - (back << 12)) >> 8);
  812. }
  813. return hasColor;
  814. }
  815. }
  816. internal static class Platform {
  817. [DllImport ("libc")]
  818. static extern int uname (IntPtr buf);
  819. [DllImport ("libc")]
  820. static extern int killpg (int pgrp, int pid);
  821. static int suspendSignal;
  822. static int GetSuspendSignal ()
  823. {
  824. if (suspendSignal != 0)
  825. return suspendSignal;
  826. IntPtr buf = Marshal.AllocHGlobal (8192);
  827. if (uname (buf) != 0) {
  828. Marshal.FreeHGlobal (buf);
  829. suspendSignal = -1;
  830. return suspendSignal;
  831. }
  832. try {
  833. switch (Marshal.PtrToStringAnsi (buf)) {
  834. case "Darwin":
  835. case "DragonFly":
  836. case "FreeBSD":
  837. case "NetBSD":
  838. case "OpenBSD":
  839. suspendSignal = 18;
  840. break;
  841. case "Linux":
  842. // TODO: should fetch the machine name and
  843. // if it is MIPS return 24
  844. suspendSignal = 20;
  845. break;
  846. case "Solaris":
  847. suspendSignal = 24;
  848. break;
  849. default:
  850. suspendSignal = -1;
  851. break;
  852. }
  853. return suspendSignal;
  854. } finally {
  855. Marshal.FreeHGlobal (buf);
  856. }
  857. }
  858. /// <summary>
  859. /// Suspends the process by sending SIGTSTP to itself
  860. /// </summary>
  861. /// <returns>The suspend.</returns>
  862. static public bool Suspend ()
  863. {
  864. int signal = GetSuspendSignal ();
  865. if (signal == -1)
  866. return false;
  867. killpg (0, signal);
  868. return true;
  869. }
  870. }
  871. /// <summary>
  872. /// A clipboard implementation for Linux.
  873. /// This implementation uses the xclip command to access the clipboard.
  874. /// </summary>
  875. /// <remarks>
  876. /// If xclip is not installed, this implementation will not work.
  877. /// </remarks>
  878. class CursesClipboard : ClipboardBase {
  879. public CursesClipboard ()
  880. {
  881. IsSupported = CheckSupport ();
  882. }
  883. string xclipPath = string.Empty;
  884. public override bool IsSupported { get; }
  885. bool CheckSupport ()
  886. {
  887. #pragma warning disable RCS1075 // Avoid empty catch clause that catches System.Exception.
  888. try {
  889. var (exitCode, result) = ClipboardProcessRunner.Bash ("which xclip", waitForOutput: true);
  890. if (exitCode == 0 && result.FileExists ()) {
  891. xclipPath = result;
  892. return true;
  893. }
  894. } catch (Exception) {
  895. // Permissions issue.
  896. }
  897. #pragma warning restore RCS1075 // Avoid empty catch clause that catches System.Exception.
  898. return false;
  899. }
  900. protected override string GetClipboardDataImpl ()
  901. {
  902. var tempFileName = System.IO.Path.GetTempFileName ();
  903. var xclipargs = "-selection clipboard -o";
  904. try {
  905. var (exitCode, result) = ClipboardProcessRunner.Bash ($"{xclipPath} {xclipargs} > {tempFileName}", waitForOutput: false);
  906. if (exitCode == 0) {
  907. if (Application.Driver is CursesDriver) {
  908. Curses.raw ();
  909. Curses.noecho ();
  910. }
  911. return System.IO.File.ReadAllText (tempFileName);
  912. }
  913. } catch (Exception e) {
  914. throw new NotSupportedException ($"\"{xclipPath} {xclipargs}\" failed.", e);
  915. } finally {
  916. System.IO.File.Delete (tempFileName);
  917. }
  918. return string.Empty;
  919. }
  920. protected override void SetClipboardDataImpl (string text)
  921. {
  922. var xclipargs = "-selection clipboard -i";
  923. try {
  924. var (exitCode, _) = ClipboardProcessRunner.Bash ($"{xclipPath} {xclipargs}", text, waitForOutput: false);
  925. if (exitCode == 0 && Application.Driver is CursesDriver) {
  926. Curses.raw ();
  927. Curses.noecho ();
  928. }
  929. } catch (Exception e) {
  930. throw new NotSupportedException ($"\"{xclipPath} {xclipargs} < {text}\" failed", e);
  931. }
  932. }
  933. }
  934. /// <summary>
  935. /// A clipboard implementation for MacOSX.
  936. /// This implementation uses the Mac clipboard API (via P/Invoke) to copy/paste.
  937. /// The existance of the Mac pbcopy and pbpaste commands
  938. /// is used to determine if copy/paste is supported.
  939. /// </summary>
  940. class MacOSXClipboard : ClipboardBase {
  941. IntPtr nsString = objc_getClass ("NSString");
  942. IntPtr nsPasteboard = objc_getClass ("NSPasteboard");
  943. IntPtr utfTextType;
  944. IntPtr generalPasteboard;
  945. IntPtr initWithUtf8Register = sel_registerName ("initWithUTF8String:");
  946. IntPtr allocRegister = sel_registerName ("alloc");
  947. IntPtr setStringRegister = sel_registerName ("setString:forType:");
  948. IntPtr stringForTypeRegister = sel_registerName ("stringForType:");
  949. IntPtr utf8Register = sel_registerName ("UTF8String");
  950. IntPtr nsStringPboardType;
  951. IntPtr generalPasteboardRegister = sel_registerName ("generalPasteboard");
  952. IntPtr clearContentsRegister = sel_registerName ("clearContents");
  953. public MacOSXClipboard ()
  954. {
  955. utfTextType = objc_msgSend (objc_msgSend (nsString, allocRegister), initWithUtf8Register, "public.utf8-plain-text");
  956. nsStringPboardType = objc_msgSend (objc_msgSend (nsString, allocRegister), initWithUtf8Register, "NSStringPboardType");
  957. generalPasteboard = objc_msgSend (nsPasteboard, generalPasteboardRegister);
  958. IsSupported = CheckSupport ();
  959. }
  960. public override bool IsSupported { get; }
  961. bool CheckSupport ()
  962. {
  963. var (exitCode, result) = ClipboardProcessRunner.Bash ("which pbcopy", waitForOutput: true);
  964. if (exitCode != 0 || !result.FileExists ()) {
  965. return false;
  966. }
  967. (exitCode, result) = ClipboardProcessRunner.Bash ("which pbpaste", waitForOutput: true);
  968. return exitCode == 0 && result.FileExists ();
  969. }
  970. protected override string GetClipboardDataImpl ()
  971. {
  972. var ptr = objc_msgSend (generalPasteboard, stringForTypeRegister, nsStringPboardType);
  973. var charArray = objc_msgSend (ptr, utf8Register);
  974. return Marshal.PtrToStringAnsi (charArray);
  975. }
  976. protected override void SetClipboardDataImpl (string text)
  977. {
  978. IntPtr str = default;
  979. try {
  980. str = objc_msgSend (objc_msgSend (nsString, allocRegister), initWithUtf8Register, text);
  981. objc_msgSend (generalPasteboard, clearContentsRegister);
  982. objc_msgSend (generalPasteboard, setStringRegister, str, utfTextType);
  983. } finally {
  984. if (str != default) {
  985. objc_msgSend (str, sel_registerName ("release"));
  986. }
  987. }
  988. }
  989. [DllImport ("/System/Library/Frameworks/AppKit.framework/AppKit")]
  990. static extern IntPtr objc_getClass (string className);
  991. [DllImport ("/System/Library/Frameworks/AppKit.framework/AppKit")]
  992. static extern IntPtr objc_msgSend (IntPtr receiver, IntPtr selector);
  993. [DllImport ("/System/Library/Frameworks/AppKit.framework/AppKit")]
  994. static extern IntPtr objc_msgSend (IntPtr receiver, IntPtr selector, string arg1);
  995. [DllImport ("/System/Library/Frameworks/AppKit.framework/AppKit")]
  996. static extern IntPtr objc_msgSend (IntPtr receiver, IntPtr selector, IntPtr arg1);
  997. [DllImport ("/System/Library/Frameworks/AppKit.framework/AppKit")]
  998. static extern IntPtr objc_msgSend (IntPtr receiver, IntPtr selector, IntPtr arg1, IntPtr arg2);
  999. [DllImport ("/System/Library/Frameworks/AppKit.framework/AppKit")]
  1000. static extern IntPtr sel_registerName (string selectorName);
  1001. }
  1002. /// <summary>
  1003. /// A clipboard implementation for Linux, when running under WSL.
  1004. /// This implementation uses the Windows clipboard to store the data, and uses Windows'
  1005. /// powershell.exe (launched via WSL interop services) to set/get the Windows
  1006. /// clipboard.
  1007. /// </summary>
  1008. class WSLClipboard : ClipboardBase {
  1009. bool isSupported = false;
  1010. public WSLClipboard ()
  1011. {
  1012. isSupported = CheckSupport ();
  1013. }
  1014. public override bool IsSupported {
  1015. get {
  1016. return isSupported = CheckSupport ();
  1017. }
  1018. }
  1019. private static string powershellPath = string.Empty;
  1020. bool CheckSupport ()
  1021. {
  1022. if (string.IsNullOrEmpty (powershellPath)) {
  1023. // Specify pwsh.exe (not pwsh) to ensure we get the Windows version (invoked via WSL)
  1024. var (exitCode, result) = ClipboardProcessRunner.Bash ("which pwsh.exe", waitForOutput: true);
  1025. if (exitCode > 0) {
  1026. (exitCode, result) = ClipboardProcessRunner.Bash ("which powershell.exe", waitForOutput: true);
  1027. }
  1028. if (exitCode == 0) {
  1029. powershellPath = result;
  1030. }
  1031. }
  1032. return !string.IsNullOrEmpty (powershellPath);
  1033. }
  1034. protected override string GetClipboardDataImpl ()
  1035. {
  1036. if (!IsSupported) {
  1037. return string.Empty;
  1038. }
  1039. var (exitCode, output) = ClipboardProcessRunner.Process (powershellPath, "-noprofile -command \"Get-Clipboard\"");
  1040. if (exitCode == 0) {
  1041. if (Application.Driver is CursesDriver) {
  1042. Curses.raw ();
  1043. Curses.noecho ();
  1044. }
  1045. if (output.EndsWith ("\r\n")) {
  1046. output = output.Substring (0, output.Length - 2);
  1047. }
  1048. return output;
  1049. }
  1050. return string.Empty;
  1051. }
  1052. protected override void SetClipboardDataImpl (string text)
  1053. {
  1054. if (!IsSupported) {
  1055. return;
  1056. }
  1057. var (exitCode, output) = ClipboardProcessRunner.Process (powershellPath, $"-noprofile -command \"Set-Clipboard -Value \\\"{text}\\\"\"");
  1058. if (exitCode == 0) {
  1059. if (Application.Driver is CursesDriver) {
  1060. Curses.raw ();
  1061. Curses.noecho ();
  1062. }
  1063. }
  1064. }
  1065. }
  1066. }