CursesDriver.cs 36 KB

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