CursesDriver.cs 38 KB

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