CursesDriver.cs 36 KB

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