CursesDriver.cs 38 KB

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