CursesDriver.cs 39 KB

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