CursesDriver.cs 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544
  1. //
  2. // Driver.cs: Curses-based Driver
  3. //
  4. // Authors:
  5. // Miguel de Icaza ([email protected])
  6. //
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Diagnostics;
  10. using System.Linq;
  11. using System.Runtime.InteropServices;
  12. using System.Threading.Tasks;
  13. using NStack;
  14. using Unix.Terminal;
  15. namespace Terminal.Gui {
  16. /// <summary>
  17. /// This is the Curses driver for the gui.cs/Terminal framework.
  18. /// </summary>
  19. internal class CursesDriver : ConsoleDriver {
  20. public override int Cols => Curses.Cols;
  21. public override int Rows => Curses.Lines;
  22. public override int Left => 0;
  23. public override int Top => 0;
  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 < 2 && ccol > 0
  58. && Rune.ColumnWidth ((char)contents [crow, ccol - 1, 0]) > 1) {
  59. var curAtttib = currentAttribute;
  60. Curses.attrset (contents [crow, ccol - 1, 1]);
  61. Curses.mvaddch (crow, ccol - 1, (int)(uint)' ');
  62. contents [crow, ccol - 1, 0] = (int)(uint)' ';
  63. Curses.move (crow, ccol);
  64. Curses.attrset (curAtttib);
  65. } else if (runeWidth < 2 && ccol <= Clip.Right - 1
  66. && Rune.ColumnWidth ((char)contents [crow, ccol, 0]) > 1) {
  67. var curAtttib = currentAttribute;
  68. Curses.attrset (contents [crow, ccol + 1, 1]);
  69. Curses.mvaddch (crow, ccol + 1, (int)(uint)' ');
  70. contents [crow, ccol + 1, 0] = (int)(uint)' ';
  71. Curses.move (crow, ccol);
  72. Curses.attrset (curAtttib);
  73. }
  74. if (runeWidth > 1 && ccol == Clip.Right - 1) {
  75. Curses.addch ((int)(uint)' ');
  76. contents [crow, ccol, 0] = (int)(uint)' ';
  77. } else {
  78. Curses.addch ((int)(uint)rune);
  79. contents [crow, ccol, 0] = (int)(uint)rune;
  80. }
  81. contents [crow, ccol, 1] = currentAttribute;
  82. contents [crow, ccol, 2] = 1;
  83. } else
  84. needMove = true;
  85. ccol++;
  86. if (runeWidth > 1) {
  87. if (validClip && ccol < Clip.Right) {
  88. contents [crow, ccol, 1] = currentAttribute;
  89. contents [crow, ccol, 2] = 0;
  90. }
  91. ccol++;
  92. }
  93. if (sync)
  94. UpdateScreen ();
  95. }
  96. public override void AddStr (ustring str)
  97. {
  98. // TODO; optimize this to determine if the str fits in the clip region, and if so, use Curses.addstr directly
  99. foreach (var rune in str)
  100. AddRune (rune);
  101. }
  102. public override void Refresh ()
  103. {
  104. Curses.raw ();
  105. Curses.noecho ();
  106. Curses.refresh ();
  107. ProcessWinChange ();
  108. }
  109. private void ProcessWinChange ()
  110. {
  111. if (Curses.CheckWinChange ()) {
  112. ResizeScreen ();
  113. UpdateOffScreen ();
  114. TerminalResized?.Invoke ();
  115. }
  116. }
  117. public override void UpdateCursor () => Refresh ();
  118. public override void End ()
  119. {
  120. if (reportableMouseEvents.HasFlag (Curses.Event.ReportMousePosition)) {
  121. StopReportingMouseMoves ();
  122. }
  123. SetCursorVisibility (CursorVisibility.Default);
  124. Curses.endwin ();
  125. // I'm commenting this because was used in a trying to fix the Linux hanging and forgot to exclude it.
  126. // Clear and reset entire screen.
  127. //Console.Out.Write ("\x1b[2J");
  128. //Console.Out.Flush ();
  129. // Set top and bottom lines of a window.
  130. //Console.Out.Write ("\x1b[1;25r");
  131. //Console.Out.Flush ();
  132. //Set cursor key to cursor.
  133. //Console.Out.Write ("\x1b[?1l");
  134. //Console.Out.Flush ();
  135. }
  136. public override void UpdateScreen () => window.redrawwin ();
  137. Attribute currentAttribute;
  138. public override void SetAttribute (Attribute c)
  139. {
  140. currentAttribute = c;
  141. Curses.attrset (currentAttribute);
  142. }
  143. public Curses.Window window;
  144. //static short last_color_pair = 16;
  145. /// <summary>
  146. /// Creates a curses color from the provided foreground and background colors
  147. /// </summary>
  148. /// <param name="foreground">Contains the curses attributes for the foreground (color, plus any attributes)</param>
  149. /// <param name="background">Contains the curses attributes for the background (color, plus any attributes)</param>
  150. /// <returns></returns>
  151. public static Attribute MakeColor (short foreground, short background)
  152. {
  153. var v = (short)((int)foreground | background << 4);
  154. //Curses.InitColorPair (++last_color_pair, foreground, background);
  155. Curses.InitColorPair (v, foreground, background);
  156. return new Attribute (
  157. //value: Curses.ColorPair (last_color_pair),
  158. value: Curses.ColorPair (v),
  159. //foreground: (Color)foreground,
  160. foreground: MapCursesColor (foreground),
  161. //background: (Color)background);
  162. background: MapCursesColor (background));
  163. }
  164. public override Attribute MakeColor (Color fore, Color back)
  165. {
  166. return MakeColor ((short)MapColor (fore), (short)MapColor (back));
  167. }
  168. int [,] colorPairs = new int [16, 16];
  169. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  170. {
  171. int f = (short)foreground;
  172. int b = (short)background;
  173. var v = colorPairs [f, b];
  174. if ((v & 0x10000) == 0) {
  175. b &= 0x7;
  176. bool bold = (f & 0x8) != 0;
  177. f &= 0x7;
  178. v = MakeColor ((short)f, (short)b) | (bold ? Curses.A_BOLD : 0);
  179. colorPairs [(int)foreground, (int)background] = v | 0x1000;
  180. }
  181. SetAttribute (v & 0xffff);
  182. }
  183. Dictionary<int, int> rawPairs = new Dictionary<int, int> ();
  184. public override void SetColors (short foreColorId, short backgroundColorId)
  185. {
  186. int key = ((ushort)foreColorId << 16) | (ushort)backgroundColorId;
  187. if (!rawPairs.TryGetValue (key, out var v)) {
  188. v = MakeColor (foreColorId, backgroundColorId);
  189. rawPairs [key] = v;
  190. }
  191. SetAttribute (v);
  192. }
  193. static Key MapCursesKey (int cursesKey)
  194. {
  195. switch (cursesKey) {
  196. case Curses.KeyF1: return Key.F1;
  197. case Curses.KeyF2: return Key.F2;
  198. case Curses.KeyF3: return Key.F3;
  199. case Curses.KeyF4: return Key.F4;
  200. case Curses.KeyF5: return Key.F5;
  201. case Curses.KeyF6: return Key.F6;
  202. case Curses.KeyF7: return Key.F7;
  203. case Curses.KeyF8: return Key.F8;
  204. case Curses.KeyF9: return Key.F9;
  205. case Curses.KeyF10: return Key.F10;
  206. case Curses.KeyF11: return Key.F11;
  207. case Curses.KeyF12: return Key.F12;
  208. case Curses.KeyUp: return Key.CursorUp;
  209. case Curses.KeyDown: return Key.CursorDown;
  210. case Curses.KeyLeft: return Key.CursorLeft;
  211. case Curses.KeyRight: return Key.CursorRight;
  212. case Curses.KeyHome: return Key.Home;
  213. case Curses.KeyEnd: return Key.End;
  214. case Curses.KeyNPage: return Key.PageDown;
  215. case Curses.KeyPPage: return Key.PageUp;
  216. case Curses.KeyDeleteChar: return Key.DeleteChar;
  217. case Curses.KeyInsertChar: return Key.InsertChar;
  218. case Curses.KeyTab: return Key.Tab;
  219. case Curses.KeyBackTab: return Key.BackTab;
  220. case Curses.KeyBackspace: return Key.Backspace;
  221. case Curses.ShiftKeyUp: return Key.CursorUp | Key.ShiftMask;
  222. case Curses.ShiftKeyDown: return Key.CursorDown | Key.ShiftMask;
  223. case Curses.ShiftKeyLeft: return Key.CursorLeft | Key.ShiftMask;
  224. case Curses.ShiftKeyRight: return Key.CursorRight | Key.ShiftMask;
  225. case Curses.ShiftKeyHome: return Key.Home | Key.ShiftMask;
  226. case Curses.ShiftKeyEnd: return Key.End | Key.ShiftMask;
  227. case Curses.ShiftKeyNPage: return Key.PageDown | Key.ShiftMask;
  228. case Curses.ShiftKeyPPage: return Key.PageUp | Key.ShiftMask;
  229. case Curses.AltKeyUp: return Key.CursorUp | Key.AltMask;
  230. case Curses.AltKeyDown: return Key.CursorDown | Key.AltMask;
  231. case Curses.AltKeyLeft: return Key.CursorLeft | Key.AltMask;
  232. case Curses.AltKeyRight: return Key.CursorRight | Key.AltMask;
  233. case Curses.AltKeyHome: return Key.Home | Key.AltMask;
  234. case Curses.AltKeyEnd: return Key.End | Key.AltMask;
  235. case Curses.AltKeyNPage: return Key.PageDown | Key.AltMask;
  236. case Curses.AltKeyPPage: return Key.PageUp | Key.AltMask;
  237. case Curses.CtrlKeyUp: return Key.CursorUp | Key.CtrlMask;
  238. case Curses.CtrlKeyDown: return Key.CursorDown | Key.CtrlMask;
  239. case Curses.CtrlKeyLeft: return Key.CursorLeft | Key.CtrlMask;
  240. case Curses.CtrlKeyRight: return Key.CursorRight | Key.CtrlMask;
  241. case Curses.CtrlKeyHome: return Key.Home | Key.CtrlMask;
  242. case Curses.CtrlKeyEnd: return Key.End | Key.CtrlMask;
  243. case Curses.CtrlKeyNPage: return Key.PageDown | Key.CtrlMask;
  244. case Curses.CtrlKeyPPage: return Key.PageUp | Key.CtrlMask;
  245. case Curses.ShiftCtrlKeyUp: return Key.CursorUp | Key.ShiftMask | Key.CtrlMask;
  246. case Curses.ShiftCtrlKeyDown: return Key.CursorDown | Key.ShiftMask | Key.CtrlMask;
  247. case Curses.ShiftCtrlKeyLeft: return Key.CursorLeft | Key.ShiftMask | Key.CtrlMask;
  248. case Curses.ShiftCtrlKeyRight: return Key.CursorRight | Key.ShiftMask | Key.CtrlMask;
  249. case Curses.ShiftCtrlKeyHome: return Key.Home | Key.ShiftMask | Key.CtrlMask;
  250. case Curses.ShiftCtrlKeyEnd: return Key.End | Key.ShiftMask | Key.CtrlMask;
  251. case Curses.ShiftCtrlKeyNPage: return Key.PageDown | Key.ShiftMask | Key.CtrlMask;
  252. case Curses.ShiftCtrlKeyPPage: return Key.PageUp | Key.ShiftMask | Key.CtrlMask;
  253. case Curses.ShiftAltKeyUp: return Key.CursorUp | Key.ShiftMask | Key.AltMask;
  254. case Curses.ShiftAltKeyDown: return Key.CursorDown | Key.ShiftMask | Key.AltMask;
  255. case Curses.ShiftAltKeyLeft: return Key.CursorLeft | Key.ShiftMask | Key.AltMask;
  256. case Curses.ShiftAltKeyRight: return Key.CursorRight | Key.ShiftMask | Key.AltMask;
  257. case Curses.ShiftAltKeyNPage: return Key.PageDown | Key.ShiftMask | Key.AltMask;
  258. case Curses.ShiftAltKeyPPage: return Key.PageUp | Key.ShiftMask | Key.AltMask;
  259. case Curses.ShiftAltKeyHome: return Key.Home | Key.ShiftMask | Key.AltMask;
  260. case Curses.ShiftAltKeyEnd: return Key.End | Key.ShiftMask | Key.AltMask;
  261. case Curses.AltCtrlKeyNPage: return Key.PageDown | Key.AltMask | Key.CtrlMask;
  262. case Curses.AltCtrlKeyPPage: return Key.PageUp | Key.AltMask | Key.CtrlMask;
  263. case Curses.AltCtrlKeyHome: return Key.Home | Key.AltMask | Key.CtrlMask;
  264. case Curses.AltCtrlKeyEnd: return Key.End | Key.AltMask | Key.CtrlMask;
  265. default: return Key.Unknown;
  266. }
  267. }
  268. Curses.Event? lastMouseButtonPressed;
  269. bool isButtonPressed;
  270. bool cancelButtonClicked;
  271. bool isReportMousePosition;
  272. Point point;
  273. int buttonPressedCount;
  274. MouseEvent ToDriverMouse (Curses.MouseEvent cev)
  275. {
  276. MouseFlags mouseFlag = MouseFlags.AllEvents;
  277. if (lastMouseButtonPressed != null && cev.ButtonState != Curses.Event.ReportMousePosition) {
  278. lastMouseButtonPressed = null;
  279. isButtonPressed = false;
  280. }
  281. if (cev.ButtonState == Curses.Event.Button1Pressed
  282. || cev.ButtonState == Curses.Event.Button2Pressed
  283. || cev.ButtonState == Curses.Event.Button3Pressed) {
  284. isButtonPressed = true;
  285. buttonPressedCount++;
  286. } else {
  287. buttonPressedCount = 0;
  288. }
  289. //System.Diagnostics.Debug.WriteLine ($"buttonPressedCount: {buttonPressedCount}");
  290. if (buttonPressedCount == 2
  291. && (cev.ButtonState == Curses.Event.Button1Pressed
  292. || cev.ButtonState == Curses.Event.Button2Pressed
  293. || cev.ButtonState == Curses.Event.Button3Pressed)) {
  294. switch (cev.ButtonState) {
  295. case Curses.Event.Button1Pressed:
  296. mouseFlag = MouseFlags.Button1DoubleClicked;
  297. break;
  298. case Curses.Event.Button2Pressed:
  299. mouseFlag = MouseFlags.Button2DoubleClicked;
  300. break;
  301. case Curses.Event.Button3Pressed:
  302. mouseFlag = MouseFlags.Button3DoubleClicked;
  303. break;
  304. }
  305. cancelButtonClicked = true;
  306. } else if (buttonPressedCount == 3
  307. && (cev.ButtonState == Curses.Event.Button1Pressed
  308. || cev.ButtonState == Curses.Event.Button2Pressed
  309. || cev.ButtonState == Curses.Event.Button3Pressed)) {
  310. switch (cev.ButtonState) {
  311. case Curses.Event.Button1Pressed:
  312. mouseFlag = MouseFlags.Button1TripleClicked;
  313. break;
  314. case Curses.Event.Button2Pressed:
  315. mouseFlag = MouseFlags.Button2TripleClicked;
  316. break;
  317. case Curses.Event.Button3Pressed:
  318. mouseFlag = MouseFlags.Button3TripleClicked;
  319. break;
  320. }
  321. buttonPressedCount = 0;
  322. } else if ((cev.ButtonState == Curses.Event.Button1Clicked || cev.ButtonState == Curses.Event.Button2Clicked ||
  323. cev.ButtonState == Curses.Event.Button3Clicked) &&
  324. lastMouseButtonPressed == null) {
  325. isButtonPressed = false;
  326. mouseFlag = ProcessButtonClickedEvent (cev);
  327. } else if (((cev.ButtonState == Curses.Event.Button1Pressed || cev.ButtonState == Curses.Event.Button2Pressed ||
  328. cev.ButtonState == Curses.Event.Button3Pressed) && lastMouseButtonPressed == null) ||
  329. isButtonPressed && lastMouseButtonPressed != null && cev.ButtonState == Curses.Event.ReportMousePosition) {
  330. mouseFlag = MapCursesButton (cev.ButtonState);
  331. if (cev.ButtonState != Curses.Event.ReportMousePosition)
  332. lastMouseButtonPressed = cev.ButtonState;
  333. isButtonPressed = true;
  334. isReportMousePosition = false;
  335. if (cev.ButtonState == Curses.Event.ReportMousePosition) {
  336. mouseFlag = MapCursesButton ((Curses.Event)lastMouseButtonPressed) | MouseFlags.ReportMousePosition;
  337. cancelButtonClicked = true;
  338. }
  339. point = new Point () {
  340. X = cev.X,
  341. Y = cev.Y
  342. };
  343. if ((mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  344. Application.MainLoop.AddIdle (() => {
  345. Task.Run (async () => await ProcessContinuousButtonPressedAsync (mouseFlag));
  346. return false;
  347. });
  348. }
  349. } else if ((cev.ButtonState == Curses.Event.Button1Released || cev.ButtonState == Curses.Event.Button2Released ||
  350. cev.ButtonState == Curses.Event.Button3Released)) {
  351. mouseFlag = ProcessButtonReleasedEvent (cev);
  352. isButtonPressed = false;
  353. } else if (cev.ButtonState == Curses.Event.ButtonWheeledUp) {
  354. mouseFlag = MouseFlags.WheeledUp;
  355. } else if (cev.ButtonState == Curses.Event.ButtonWheeledDown) {
  356. mouseFlag = MouseFlags.WheeledDown;
  357. } else if ((cev.ButtonState & (Curses.Event.ButtonWheeledUp & Curses.Event.ButtonShift)) != 0) {
  358. mouseFlag = MouseFlags.WheeledLeft;
  359. } else if ((cev.ButtonState & (Curses.Event.ButtonWheeledDown & Curses.Event.ButtonShift)) != 0) {
  360. mouseFlag = MouseFlags.WheeledRight;
  361. } else if (cev.ButtonState == Curses.Event.ReportMousePosition) {
  362. if (cev.X != point.X || cev.Y != point.Y) {
  363. mouseFlag = MouseFlags.ReportMousePosition;
  364. isReportMousePosition = true;
  365. point = new Point ();
  366. } else {
  367. mouseFlag = 0;
  368. }
  369. } else {
  370. mouseFlag = 0;
  371. var eFlags = cev.ButtonState;
  372. foreach (Enum value in Enum.GetValues (eFlags.GetType ())) {
  373. if (eFlags.HasFlag (value)) {
  374. mouseFlag |= MapCursesButton ((Curses.Event)value);
  375. }
  376. }
  377. }
  378. mouseFlag = SetControlKeyStates (cev, mouseFlag);
  379. return new MouseEvent () {
  380. X = cev.X,
  381. Y = cev.Y,
  382. //Flags = MapCursesButton (cev.ButtonState)
  383. Flags = mouseFlag
  384. };
  385. }
  386. MouseFlags ProcessButtonClickedEvent (Curses.MouseEvent cev)
  387. {
  388. lastMouseButtonPressed = cev.ButtonState;
  389. var mf = GetButtonState (cev, true);
  390. mouseHandler (ProcessButtonState (cev, mf));
  391. if (lastMouseButtonPressed != null && lastMouseButtonPressed == cev.ButtonState) {
  392. mf = GetButtonState (cev, false);
  393. mouseHandler (ProcessButtonState (cev, mf));
  394. if (lastMouseButtonPressed != null && lastMouseButtonPressed == cev.ButtonState) {
  395. mf = MapCursesButton (cev.ButtonState);
  396. }
  397. }
  398. lastMouseButtonPressed = null;
  399. isButtonPressed = false;
  400. return mf;
  401. }
  402. MouseFlags ProcessButtonReleasedEvent (Curses.MouseEvent cev)
  403. {
  404. var mf = MapCursesButton (cev.ButtonState);
  405. if (!cancelButtonClicked && lastMouseButtonPressed == null && !isReportMousePosition) {
  406. mouseHandler (ProcessButtonState (cev, mf));
  407. mf = GetButtonState (cev);
  408. } else if (isReportMousePosition) {
  409. mf = MouseFlags.ReportMousePosition;
  410. }
  411. cancelButtonClicked = false;
  412. return mf;
  413. }
  414. async Task ProcessContinuousButtonPressedAsync (MouseFlags mouseFlag)
  415. {
  416. while (isButtonPressed) {
  417. await Task.Delay (100);
  418. var me = new MouseEvent () {
  419. X = point.X,
  420. Y = point.Y,
  421. Flags = mouseFlag
  422. };
  423. var view = Application.WantContinuousButtonPressedView;
  424. if (view == null)
  425. break;
  426. if (isButtonPressed && lastMouseButtonPressed != null && (mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  427. Application.MainLoop.Invoke (() => mouseHandler (me));
  428. }
  429. }
  430. }
  431. MouseFlags GetButtonState (Curses.MouseEvent cev, bool pressed = false)
  432. {
  433. MouseFlags mf = default;
  434. switch (cev.ButtonState) {
  435. case Curses.Event.Button1Clicked:
  436. if (pressed)
  437. mf = MouseFlags.Button1Pressed;
  438. else
  439. mf = MouseFlags.Button1Released;
  440. break;
  441. case Curses.Event.Button2Clicked:
  442. if (pressed)
  443. mf = MouseFlags.Button2Pressed;
  444. else
  445. mf = MouseFlags.Button2Released;
  446. break;
  447. case Curses.Event.Button3Clicked:
  448. if (pressed)
  449. mf = MouseFlags.Button3Pressed;
  450. else
  451. mf = MouseFlags.Button3Released;
  452. break;
  453. case Curses.Event.Button1Released:
  454. mf = MouseFlags.Button1Clicked;
  455. break;
  456. case Curses.Event.Button2Released:
  457. mf = MouseFlags.Button2Clicked;
  458. break;
  459. case Curses.Event.Button3Released:
  460. mf = MouseFlags.Button3Clicked;
  461. break;
  462. }
  463. return mf;
  464. }
  465. MouseEvent ProcessButtonState (Curses.MouseEvent cev, MouseFlags mf)
  466. {
  467. return new MouseEvent () {
  468. X = cev.X,
  469. Y = cev.Y,
  470. Flags = mf
  471. };
  472. }
  473. MouseFlags MapCursesButton (Curses.Event cursesButton)
  474. {
  475. switch (cursesButton) {
  476. case Curses.Event.Button1Pressed: return MouseFlags.Button1Pressed;
  477. case Curses.Event.Button1Released: return MouseFlags.Button1Released;
  478. case Curses.Event.Button1Clicked: return MouseFlags.Button1Clicked;
  479. case Curses.Event.Button1DoubleClicked: return MouseFlags.Button1DoubleClicked;
  480. case Curses.Event.Button1TripleClicked: return MouseFlags.Button1TripleClicked;
  481. case Curses.Event.Button2Pressed: return MouseFlags.Button2Pressed;
  482. case Curses.Event.Button2Released: return MouseFlags.Button2Released;
  483. case Curses.Event.Button2Clicked: return MouseFlags.Button2Clicked;
  484. case Curses.Event.Button2DoubleClicked: return MouseFlags.Button2DoubleClicked;
  485. case Curses.Event.Button2TrippleClicked: return MouseFlags.Button2TripleClicked;
  486. case Curses.Event.Button3Pressed: return MouseFlags.Button3Pressed;
  487. case Curses.Event.Button3Released: return MouseFlags.Button3Released;
  488. case Curses.Event.Button3Clicked: return MouseFlags.Button3Clicked;
  489. case Curses.Event.Button3DoubleClicked: return MouseFlags.Button3DoubleClicked;
  490. case Curses.Event.Button3TripleClicked: return MouseFlags.Button3TripleClicked;
  491. case Curses.Event.ButtonWheeledUp: return MouseFlags.WheeledUp;
  492. case Curses.Event.ButtonWheeledDown: return MouseFlags.WheeledDown;
  493. case Curses.Event.Button4Pressed: return MouseFlags.Button4Pressed;
  494. case Curses.Event.Button4Released: return MouseFlags.Button4Released;
  495. case Curses.Event.Button4Clicked: return MouseFlags.Button4Clicked;
  496. case Curses.Event.Button4DoubleClicked: return MouseFlags.Button4DoubleClicked;
  497. case Curses.Event.Button4TripleClicked: return MouseFlags.Button4TripleClicked;
  498. case Curses.Event.ButtonShift: return MouseFlags.ButtonShift;
  499. case Curses.Event.ButtonCtrl: return MouseFlags.ButtonCtrl;
  500. case Curses.Event.ButtonAlt: return MouseFlags.ButtonAlt;
  501. case Curses.Event.ReportMousePosition: return MouseFlags.ReportMousePosition;
  502. case Curses.Event.AllEvents: return MouseFlags.AllEvents;
  503. default: return 0;
  504. }
  505. }
  506. static MouseFlags SetControlKeyStates (Curses.MouseEvent cev, MouseFlags mouseFlag)
  507. {
  508. if ((cev.ButtonState & Curses.Event.ButtonCtrl) != 0 && (mouseFlag & MouseFlags.ButtonCtrl) == 0)
  509. mouseFlag |= MouseFlags.ButtonCtrl;
  510. if ((cev.ButtonState & Curses.Event.ButtonShift) != 0 && (mouseFlag & MouseFlags.ButtonShift) == 0)
  511. mouseFlag |= MouseFlags.ButtonShift;
  512. if ((cev.ButtonState & Curses.Event.ButtonAlt) != 0 && (mouseFlag & MouseFlags.ButtonAlt) == 0)
  513. mouseFlag |= MouseFlags.ButtonAlt;
  514. return mouseFlag;
  515. }
  516. KeyModifiers keyModifiers;
  517. KeyModifiers MapKeyModifiers (Key key)
  518. {
  519. if (keyModifiers == null)
  520. keyModifiers = new KeyModifiers ();
  521. if (!keyModifiers.Shift && (key & Key.ShiftMask) != 0)
  522. keyModifiers.Shift = true;
  523. if (!keyModifiers.Alt && (key & Key.AltMask) != 0)
  524. keyModifiers.Alt = true;
  525. if (!keyModifiers.Ctrl && (key & Key.CtrlMask) != 0)
  526. keyModifiers.Ctrl = true;
  527. return keyModifiers;
  528. }
  529. void ProcessInput ()
  530. {
  531. int wch;
  532. var code = Curses.get_wch (out wch);
  533. //System.Diagnostics.Debug.WriteLine ($"code: {code}; wch: {wch}");
  534. if (code == Curses.ERR)
  535. return;
  536. keyModifiers = new KeyModifiers ();
  537. Key k = Key.Null;
  538. if (code == Curses.KEY_CODE_YES) {
  539. if (wch == Curses.KeyResize) {
  540. ProcessWinChange ();
  541. }
  542. if (wch == Curses.KeyMouse) {
  543. Curses.getmouse (out Curses.MouseEvent ev);
  544. //System.Diagnostics.Debug.WriteLine ($"ButtonState: {ev.ButtonState}; ID: {ev.ID}; X: {ev.X}; Y: {ev.Y}; Z: {ev.Z}");
  545. mouseHandler (ToDriverMouse (ev));
  546. return;
  547. }
  548. k = MapCursesKey (wch);
  549. if (wch >= 277 && wch <= 288) { // Shift+(F1 - F12)
  550. wch -= 12;
  551. k = Key.ShiftMask | MapCursesKey (wch);
  552. } else if (wch >= 289 && wch <= 300) { // Ctrl+(F1 - F12)
  553. wch -= 24;
  554. k = Key.CtrlMask | MapCursesKey (wch);
  555. } else if (wch >= 301 && wch <= 312) { // Ctrl+Shift+(F1 - F12)
  556. wch -= 36;
  557. k = Key.CtrlMask | Key.ShiftMask | MapCursesKey (wch);
  558. } else if (wch >= 313 && wch <= 324) { // Alt+(F1 - F12)
  559. wch -= 48;
  560. k = Key.AltMask | MapCursesKey (wch);
  561. } else if (wch >= 325 && wch <= 327) { // Shift+Alt+(F1 - F3)
  562. wch -= 60;
  563. k = Key.ShiftMask | Key.AltMask | MapCursesKey (wch);
  564. }
  565. keyDownHandler (new KeyEvent (k, MapKeyModifiers (k)));
  566. keyHandler (new KeyEvent (k, MapKeyModifiers (k)));
  567. keyUpHandler (new KeyEvent (k, MapKeyModifiers (k)));
  568. return;
  569. }
  570. // Special handling for ESC, we want to try to catch ESC+letter to simulate alt-letter as well as Alt-Fkey
  571. if (wch == 27) {
  572. Curses.timeout (10);
  573. code = Curses.get_wch (out int wch2);
  574. if (code == Curses.KEY_CODE_YES) {
  575. k = Key.AltMask | MapCursesKey (wch);
  576. }
  577. if (code == 0) {
  578. KeyEvent key;
  579. // The ESC-number handling, debatable.
  580. // Simulates the AltMask itself by pressing Alt + Space.
  581. if (wch2 == (int)Key.Space) {
  582. k = Key.AltMask;
  583. } else if (wch2 - (int)Key.Space >= (uint)Key.A && wch2 - (int)Key.Space <= (uint)Key.Z) {
  584. k = (Key)((uint)Key.AltMask + (wch2 - (int)Key.Space));
  585. } else if (wch2 >= (uint)Key.A - 64 && wch2 <= (uint)Key.Z - 64) {
  586. k = (Key)((uint)(Key.AltMask | Key.CtrlMask) + (wch2 + 64));
  587. } else if (wch2 >= (uint)Key.D0 && wch2 <= (uint)Key.D9) {
  588. k = (Key)((uint)Key.AltMask + (uint)Key.D0 + (wch2 - (uint)Key.D0));
  589. } else if (wch2 == 27) {
  590. k = (Key)wch2;
  591. } else if (wch2 == Curses.KEY_CODE_SEQ) {
  592. int [] c = null;
  593. while (code == 0) {
  594. code = Curses.get_wch (out wch2);
  595. if (wch2 > 0) {
  596. Array.Resize (ref c, c == null ? 1 : c.Length + 1);
  597. c [c.Length - 1] = wch2;
  598. }
  599. }
  600. if (c [0] == 49 && c [1] == 59 && c [2] == 55 && c [3] >= 80 && c [3] <= 83) { // Ctrl+Alt+(F1 - F4)
  601. wch2 = c [3] + 185;
  602. k = Key.CtrlMask | Key.AltMask | MapCursesKey (wch2);
  603. } else if (c [0] == 49 && c [2] == 59 && c [3] == 55 && c [4] == 126 && c [1] >= 53 && c [1] <= 57) { // Ctrl+Alt+(F5 - F8)
  604. wch2 = c [1] == 53 ? c [1] + 216 : c [1] + 215;
  605. k = Key.CtrlMask | Key.AltMask | MapCursesKey (wch2);
  606. } else if (c [0] == 50 && c [2] == 59 && c [3] == 55 && c [4] == 126 && c [1] >= 48 && c [1] <= 52) { // Ctrl+Alt+(F9 - F12)
  607. wch2 = c [1] < 51 ? c [1] + 225 : c [1] + 224;
  608. k = Key.CtrlMask | Key.AltMask | MapCursesKey (wch2);
  609. } else if (c [0] == 49 && c [1] == 59 && c [2] == 56 && c [3] >= 80 && c [3] <= 83) { // Ctrl+Shift+Alt+(F1 - F4)
  610. wch2 = c [3] + 185;
  611. k = Key.CtrlMask | Key.ShiftMask | Key.AltMask | MapCursesKey (wch2);
  612. } else if (c [0] == 49 && c [2] == 59 && c [3] == 56 && c [4] == 126 && c [1] >= 53 && c [1] <= 57) { // Ctrl+Shift+Alt+(F5 - F8)
  613. wch2 = c [1] == 53 ? c [1] + 216 : c [1] + 215;
  614. k = Key.CtrlMask | Key.ShiftMask | Key.AltMask | MapCursesKey (wch2);
  615. } else if (c [0] == 50 && c [2] == 59 && c [3] == 56 && c [4] == 126 && c [1] >= 48 && c [1] <= 52) { // Ctrl+Shift+Alt+(F9 - F12)
  616. wch2 = c [1] < 51 ? c [1] + 225 : c [1] + 224;
  617. k = Key.CtrlMask | Key.ShiftMask | Key.AltMask | MapCursesKey (wch2);
  618. } else if (c [0] == 49 && c [1] == 59 && c [2] == 52 && c [3] == 83) { // Shift+Alt+(F4)
  619. wch2 = 268;
  620. k = Key.ShiftMask | Key.AltMask | MapCursesKey (wch2);
  621. } else if (c [0] == 49 && c [2] == 59 && c [3] == 52 && c [4] == 126 && c [1] >= 53 && c [1] <= 57) { // Shift+Alt+(F5 - F8)
  622. wch2 = c [1] < 55 ? c [1] + 216 : c [1] + 215;
  623. k = Key.ShiftMask | Key.AltMask | MapCursesKey (wch2);
  624. } else if (c [0] == 50 && c [2] == 59 && c [3] == 52 && c [4] == 126 && c [1] >= 48 && c [1] <= 52) { // Shift+Alt+(F9 - F12)
  625. wch2 = c [1] < 51 ? c [1] + 225 : c [1] + 224;
  626. k = Key.ShiftMask | Key.AltMask | MapCursesKey (wch2);
  627. } else if (c [0] == 54 && c [1] == 59 && c [2] == 56 && c [3] == 126) { // Shift+Ctrl+Alt+KeyNPage
  628. k = Key.ShiftMask | Key.CtrlMask | Key.AltMask | Key.PageDown;
  629. } else if (c [0] == 53 && c [1] == 59 && c [2] == 56 && c [3] == 126) { // Shift+Ctrl+Alt+KeyPPage
  630. k = Key.ShiftMask | Key.CtrlMask | Key.AltMask | Key.PageUp;
  631. } else if (c [0] == 49 && c [1] == 59 && c [2] == 56 && c [3] == 72) { // Shift+Ctrl+Alt+KeyHome
  632. k = Key.ShiftMask | Key.CtrlMask | Key.AltMask | Key.Home;
  633. } else if (c [0] == 49 && c [1] == 59 && c [2] == 56 && c [3] == 70) { // Shift+Ctrl+Alt+KeyEnd
  634. k = Key.ShiftMask | Key.CtrlMask | Key.AltMask | Key.End;
  635. } else {
  636. k = MapCursesKey (wch2);
  637. }
  638. } else {
  639. // Unfortunately there are no way to differentiate Ctrl+Alt+alfa and Ctrl+Shift+Alt+alfa.
  640. if (((Key)wch2 & Key.CtrlMask) != 0) {
  641. keyModifiers.Ctrl = true;
  642. }
  643. if (wch2 == 0) {
  644. k = Key.CtrlMask | Key.AltMask | Key.Space;
  645. } else if (wch >= (uint)Key.A && wch <= (uint)Key.Z) {
  646. keyModifiers.Shift = true;
  647. keyModifiers.Alt = true;
  648. } else if (wch2 < 256) {
  649. k = (Key)wch2;
  650. keyModifiers.Alt = true;
  651. } else {
  652. k = (Key)((uint)(Key.AltMask | Key.CtrlMask) + wch2);
  653. }
  654. }
  655. key = new KeyEvent (k, MapKeyModifiers (k));
  656. keyDownHandler (key);
  657. keyHandler (key);
  658. } else {
  659. k = Key.Esc;
  660. keyHandler (new KeyEvent (k, MapKeyModifiers (k)));
  661. }
  662. } else if (wch == Curses.KeyTab) {
  663. k = MapCursesKey (wch);
  664. keyDownHandler (new KeyEvent (k, MapKeyModifiers (k)));
  665. keyHandler (new KeyEvent (k, MapKeyModifiers (k)));
  666. } else {
  667. // Unfortunately there are no way to differentiate Ctrl+alfa and Ctrl+Shift+alfa.
  668. k = (Key)wch;
  669. if (wch == 0) {
  670. k = Key.CtrlMask | Key.Space;
  671. } else if (wch >= (uint)Key.A - 64 && wch <= (uint)Key.Z - 64) {
  672. if ((Key)(wch + 64) != Key.J) {
  673. k = Key.CtrlMask | (Key)(wch + 64);
  674. }
  675. } else if (wch >= (uint)Key.A && wch <= (uint)Key.Z) {
  676. keyModifiers.Shift = true;
  677. }
  678. keyDownHandler (new KeyEvent (k, MapKeyModifiers (k)));
  679. keyHandler (new KeyEvent (k, MapKeyModifiers (k)));
  680. keyUpHandler (new KeyEvent (k, MapKeyModifiers (k)));
  681. }
  682. // Cause OnKeyUp and OnKeyPressed. Note that the special handling for ESC above
  683. // will not impact KeyUp.
  684. // This is causing ESC firing even if another keystroke was handled.
  685. //if (wch == Curses.KeyTab) {
  686. // keyUpHandler (new KeyEvent (MapCursesKey (wch), keyModifiers));
  687. //} else {
  688. // keyUpHandler (new KeyEvent ((Key)wch, keyModifiers));
  689. //}
  690. }
  691. Action<KeyEvent> keyHandler;
  692. Action<KeyEvent> keyDownHandler;
  693. Action<KeyEvent> keyUpHandler;
  694. Action<MouseEvent> mouseHandler;
  695. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
  696. {
  697. // Note: Curses doesn't support keydown/up events and thus any passed keyDown/UpHandlers will never be called
  698. Curses.timeout (0);
  699. this.keyHandler = keyHandler;
  700. this.keyDownHandler = keyDownHandler;
  701. this.keyUpHandler = keyUpHandler;
  702. this.mouseHandler = mouseHandler;
  703. var mLoop = mainLoop.Driver as UnixMainLoop;
  704. mLoop.AddWatch (0, UnixMainLoop.Condition.PollIn, x => {
  705. ProcessInput ();
  706. return true;
  707. });
  708. mLoop.WinChanged += () => {
  709. ProcessWinChange ();
  710. };
  711. }
  712. Curses.Event oldMouseEvents, reportableMouseEvents;
  713. public override void Init (Action terminalResized)
  714. {
  715. if (window != null)
  716. return;
  717. try {
  718. //Set cursor key to application.
  719. //Console.Out.Write ("\x1b[?1h");
  720. //Console.Out.Flush ();
  721. window = Curses.initscr ();
  722. Curses.set_escdelay (10);
  723. } catch (Exception e) {
  724. throw new Exception ($"Curses failed to initialize, the exception is: {e.Message}");
  725. }
  726. // Ensures that all procedures are performed at some previous closing.
  727. Curses.doupdate ();
  728. //
  729. // We are setting Invisible as default so we could ignore XTerm DECSUSR setting
  730. //
  731. switch (Curses.curs_set (0)) {
  732. case 0:
  733. currentCursorVisibility = initialCursorVisibility = CursorVisibility.Invisible;
  734. break;
  735. case 1:
  736. currentCursorVisibility = initialCursorVisibility = CursorVisibility.Underline;
  737. Curses.curs_set (1);
  738. break;
  739. case 2:
  740. currentCursorVisibility = initialCursorVisibility = CursorVisibility.Box;
  741. Curses.curs_set (2);
  742. break;
  743. default:
  744. currentCursorVisibility = initialCursorVisibility = null;
  745. break;
  746. }
  747. if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX)) {
  748. clipboard = new MacOSXClipboard ();
  749. } else {
  750. if (Is_WSL_Platform ()) {
  751. clipboard = new WSLClipboard ();
  752. } else {
  753. clipboard = new CursesClipboard ();
  754. }
  755. }
  756. Curses.raw ();
  757. Curses.noecho ();
  758. Curses.Window.Standard.keypad (true);
  759. reportableMouseEvents = Curses.mousemask (Curses.Event.AllEvents | Curses.Event.ReportMousePosition, out oldMouseEvents);
  760. TerminalResized = terminalResized;
  761. if (reportableMouseEvents.HasFlag (Curses.Event.ReportMousePosition))
  762. StartReportingMouseMoves ();
  763. ResizeScreen ();
  764. UpdateOffScreen ();
  765. //HLine = Curses.ACS_HLINE;
  766. //VLine = Curses.ACS_VLINE;
  767. //Stipple = Curses.ACS_CKBOARD;
  768. //Diamond = Curses.ACS_DIAMOND;
  769. //ULCorner = Curses.ACS_ULCORNER;
  770. //LLCorner = Curses.ACS_LLCORNER;
  771. //URCorner = Curses.ACS_URCORNER;
  772. //LRCorner = Curses.ACS_LRCORNER;
  773. //LeftTee = Curses.ACS_LTEE;
  774. //RightTee = Curses.ACS_RTEE;
  775. //TopTee = Curses.ACS_TTEE;
  776. //BottomTee = Curses.ACS_BTEE;
  777. //RightArrow = Curses.ACS_RARROW;
  778. //LeftArrow = Curses.ACS_LARROW;
  779. //UpArrow = Curses.ACS_UARROW;
  780. //DownArrow = Curses.ACS_DARROW;
  781. if (Curses.HasColors) {
  782. Curses.StartColor ();
  783. Curses.UseDefaultColors ();
  784. CreateColors ();
  785. } else {
  786. CreateColors (false);
  787. Colors.TopLevel.Normal = Curses.COLOR_GREEN;
  788. Colors.TopLevel.Focus = Curses.COLOR_WHITE;
  789. Colors.TopLevel.HotNormal = Curses.COLOR_YELLOW;
  790. Colors.TopLevel.HotFocus = Curses.COLOR_YELLOW;
  791. Colors.TopLevel.Disabled = Curses.A_BOLD | Curses.COLOR_GRAY;
  792. Colors.Base.Normal = Curses.A_NORMAL;
  793. Colors.Base.Focus = Curses.A_REVERSE;
  794. Colors.Base.HotNormal = Curses.A_BOLD;
  795. Colors.Base.HotFocus = Curses.A_BOLD | Curses.A_REVERSE;
  796. Colors.Base.Disabled = Curses.A_BOLD | Curses.COLOR_GRAY;
  797. Colors.Menu.Normal = Curses.A_REVERSE;
  798. Colors.Menu.Focus = Curses.A_NORMAL;
  799. Colors.Menu.HotNormal = Curses.A_BOLD;
  800. Colors.Menu.HotFocus = Curses.A_NORMAL;
  801. Colors.Menu.Disabled = Curses.A_BOLD | Curses.COLOR_GRAY;
  802. Colors.Dialog.Normal = Curses.A_REVERSE;
  803. Colors.Dialog.Focus = Curses.A_NORMAL;
  804. Colors.Dialog.HotNormal = Curses.A_BOLD;
  805. Colors.Dialog.HotFocus = Curses.A_NORMAL;
  806. Colors.Dialog.Disabled = Curses.A_BOLD | Curses.COLOR_GRAY;
  807. Colors.Error.Normal = Curses.A_BOLD;
  808. Colors.Error.Focus = Curses.A_BOLD | Curses.A_REVERSE;
  809. Colors.Error.HotNormal = Curses.A_BOLD | Curses.A_REVERSE;
  810. Colors.Error.HotFocus = Curses.A_REVERSE;
  811. Colors.Error.Disabled = Curses.A_BOLD | Curses.COLOR_GRAY;
  812. }
  813. }
  814. public override void ResizeScreen ()
  815. {
  816. Clip = new Rect (0, 0, Cols, Rows);
  817. Console.Out.Write ("\x1b[3J");
  818. Console.Out.Flush ();
  819. }
  820. public override void UpdateOffScreen ()
  821. {
  822. contents = new int [Rows, Cols, 3];
  823. for (int row = 0; row < Rows; row++) {
  824. for (int col = 0; col < Cols; col++) {
  825. //Curses.move (row, col);
  826. //Curses.attrset (Colors.TopLevel.Normal);
  827. //Curses.addch ((int)(uint)' ');
  828. contents [row, col, 0] = ' ';
  829. contents [row, col, 1] = Colors.TopLevel.Normal;
  830. contents [row, col, 2] = 0;
  831. }
  832. }
  833. }
  834. public static bool Is_WSL_Platform ()
  835. {
  836. if (new CursesClipboard ().IsSupported) {
  837. // If xclip is installed on Linux under WSL, this will return true.
  838. return false;
  839. }
  840. var (exitCode, result) = ClipboardProcessRunner.Bash ("uname -a", runCurses: false);
  841. if (exitCode == 0 && result.Contains ("microsoft") && result.Contains ("WSL")) {
  842. return true;
  843. }
  844. return false;
  845. }
  846. static int MapColor (Color color)
  847. {
  848. switch (color) {
  849. case Color.Black:
  850. return Curses.COLOR_BLACK;
  851. case Color.Blue:
  852. return Curses.COLOR_BLUE;
  853. case Color.Green:
  854. return Curses.COLOR_GREEN;
  855. case Color.Cyan:
  856. return Curses.COLOR_CYAN;
  857. case Color.Red:
  858. return Curses.COLOR_RED;
  859. case Color.Magenta:
  860. return Curses.COLOR_MAGENTA;
  861. case Color.Brown:
  862. return Curses.COLOR_YELLOW;
  863. case Color.Gray:
  864. return Curses.COLOR_WHITE;
  865. case Color.DarkGray:
  866. //return Curses.COLOR_BLACK | Curses.A_BOLD;
  867. return Curses.COLOR_GRAY;
  868. case Color.BrightBlue:
  869. return Curses.COLOR_BLUE | Curses.A_BOLD | Curses.COLOR_GRAY;
  870. case Color.BrightGreen:
  871. return Curses.COLOR_GREEN | Curses.A_BOLD | Curses.COLOR_GRAY;
  872. case Color.BrightCyan:
  873. return Curses.COLOR_CYAN | Curses.A_BOLD | Curses.COLOR_GRAY;
  874. case Color.BrightRed:
  875. return Curses.COLOR_RED | Curses.A_BOLD | Curses.COLOR_GRAY;
  876. case Color.BrightMagenta:
  877. return Curses.COLOR_MAGENTA | Curses.A_BOLD | Curses.COLOR_GRAY;
  878. case Color.BrightYellow:
  879. return Curses.COLOR_YELLOW | Curses.A_BOLD | Curses.COLOR_GRAY;
  880. case Color.White:
  881. return Curses.COLOR_WHITE | Curses.A_BOLD | Curses.COLOR_GRAY;
  882. }
  883. throw new ArgumentException ("Invalid color code");
  884. }
  885. static Color MapCursesColor (int color)
  886. {
  887. switch (color) {
  888. case Curses.COLOR_BLACK:
  889. return Color.Black;
  890. case Curses.COLOR_BLUE:
  891. return Color.Blue;
  892. case Curses.COLOR_GREEN:
  893. return Color.Green;
  894. case Curses.COLOR_CYAN:
  895. return Color.Cyan;
  896. case Curses.COLOR_RED:
  897. return Color.Red;
  898. case Curses.COLOR_MAGENTA:
  899. return Color.Magenta;
  900. case Curses.COLOR_YELLOW:
  901. return Color.Brown;
  902. case Curses.COLOR_WHITE:
  903. return Color.Gray;
  904. case Curses.COLOR_GRAY:
  905. return Color.DarkGray;
  906. case Curses.COLOR_BLUE | Curses.COLOR_GRAY:
  907. return Color.BrightBlue;
  908. case Curses.COLOR_GREEN | Curses.COLOR_GRAY:
  909. return Color.BrightGreen;
  910. case Curses.COLOR_CYAN | Curses.COLOR_GRAY:
  911. return Color.BrightCyan;
  912. case Curses.COLOR_RED | Curses.COLOR_GRAY:
  913. return Color.BrightRed;
  914. case Curses.COLOR_MAGENTA | Curses.COLOR_GRAY:
  915. return Color.BrightMagenta;
  916. case Curses.COLOR_YELLOW | Curses.COLOR_GRAY:
  917. return Color.BrightYellow;
  918. case Curses.COLOR_WHITE | Curses.COLOR_GRAY:
  919. return Color.White;
  920. }
  921. throw new ArgumentException ("Invalid curses color code");
  922. }
  923. public override Attribute MakeAttribute (Color fore, Color back)
  924. {
  925. var f = MapColor (fore);
  926. //return MakeColor ((short)(f & 0xffff), (short)MapColor (back)) | ((f & Curses.A_BOLD) != 0 ? Curses.A_BOLD : 0);
  927. return MakeColor ((short)(f & 0xffff), (short)MapColor (back));
  928. }
  929. public override void Suspend ()
  930. {
  931. if (reportableMouseEvents.HasFlag (Curses.Event.ReportMousePosition))
  932. StopReportingMouseMoves ();
  933. Platform.Suspend ();
  934. Curses.Window.Standard.redrawwin ();
  935. Curses.refresh ();
  936. if (reportableMouseEvents.HasFlag (Curses.Event.ReportMousePosition))
  937. StartReportingMouseMoves ();
  938. }
  939. public override void StartReportingMouseMoves ()
  940. {
  941. Console.Out.Write ("\x1b[?1003h");
  942. Console.Out.Flush ();
  943. }
  944. public override void StopReportingMouseMoves ()
  945. {
  946. Console.Out.Write ("\x1b[?1003l");
  947. Console.Out.Flush ();
  948. }
  949. //int lastMouseInterval;
  950. //bool mouseGrabbed;
  951. public override void UncookMouse ()
  952. {
  953. //if (mouseGrabbed)
  954. // return;
  955. //lastMouseInterval = Curses.mouseinterval (0);
  956. //mouseGrabbed = true;
  957. }
  958. public override void CookMouse ()
  959. {
  960. //mouseGrabbed = false;
  961. //Curses.mouseinterval (lastMouseInterval);
  962. }
  963. public override Attribute GetAttribute ()
  964. {
  965. return currentAttribute;
  966. }
  967. /// <inheritdoc/>
  968. public override bool GetCursorVisibility (out CursorVisibility visibility)
  969. {
  970. visibility = CursorVisibility.Invisible;
  971. if (!currentCursorVisibility.HasValue)
  972. return false;
  973. visibility = currentCursorVisibility.Value;
  974. return true;
  975. }
  976. /// <inheritdoc/>
  977. public override bool SetCursorVisibility (CursorVisibility visibility)
  978. {
  979. if (initialCursorVisibility.HasValue == false)
  980. return false;
  981. Curses.curs_set (((int)visibility >> 16) & 0x000000FF);
  982. if (visibility != CursorVisibility.Invisible) {
  983. Console.Out.Write ("\x1b[{0} q", ((int)visibility >> 24) & 0xFF);
  984. Console.Out.Flush ();
  985. }
  986. currentCursorVisibility = visibility;
  987. return true;
  988. }
  989. /// <inheritdoc/>
  990. public override bool EnsureCursorVisibility ()
  991. {
  992. return false;
  993. }
  994. public override void SendKeys (char keyChar, ConsoleKey consoleKey, bool shift, bool alt, bool control)
  995. {
  996. Key key;
  997. if (consoleKey == ConsoleKey.Packet) {
  998. ConsoleModifiers mod = new ConsoleModifiers ();
  999. if (shift) {
  1000. mod |= ConsoleModifiers.Shift;
  1001. }
  1002. if (alt) {
  1003. mod |= ConsoleModifiers.Alt;
  1004. }
  1005. if (control) {
  1006. mod |= ConsoleModifiers.Control;
  1007. }
  1008. var kchar = ConsoleKeyMapping.GetKeyCharFromConsoleKey (keyChar, mod, out uint ckey, out _);
  1009. key = ConsoleKeyMapping.MapConsoleKeyToKey ((ConsoleKey)ckey, out bool mappable);
  1010. if (mappable) {
  1011. key = (Key)kchar;
  1012. }
  1013. } else {
  1014. key = (Key)keyChar;
  1015. }
  1016. KeyModifiers km = new KeyModifiers ();
  1017. if (shift) {
  1018. if (keyChar == 0) {
  1019. key |= Key.ShiftMask;
  1020. }
  1021. km.Shift = shift;
  1022. }
  1023. if (alt) {
  1024. key |= Key.AltMask;
  1025. km.Alt = alt;
  1026. }
  1027. if (control) {
  1028. key |= Key.CtrlMask;
  1029. km.Ctrl = control;
  1030. }
  1031. keyDownHandler (new KeyEvent (key, km));
  1032. keyHandler (new KeyEvent (key, km));
  1033. keyUpHandler (new KeyEvent (key, km));
  1034. }
  1035. public override bool GetColors (int value, out Color foreground, out Color background)
  1036. {
  1037. bool hasColor = false;
  1038. foreground = default;
  1039. background = default;
  1040. int back = -1;
  1041. IEnumerable<int> values = Enum.GetValues (typeof (ConsoleColor))
  1042. .OfType<ConsoleColor> ()
  1043. .Select (s => (int)s);
  1044. if (values.Contains ((value >> 12) & 0xffff)) {
  1045. hasColor = true;
  1046. back = (value >> 12) & 0xffff;
  1047. background = MapCursesColor (back);
  1048. }
  1049. if (values.Contains ((value - (back << 12)) >> 8)) {
  1050. hasColor = true;
  1051. foreground = MapCursesColor ((value - (back << 12)) >> 8);
  1052. }
  1053. return hasColor;
  1054. }
  1055. }
  1056. internal static class Platform {
  1057. [DllImport ("libc")]
  1058. static extern int uname (IntPtr buf);
  1059. [DllImport ("libc")]
  1060. static extern int killpg (int pgrp, int pid);
  1061. static int suspendSignal;
  1062. static int GetSuspendSignal ()
  1063. {
  1064. if (suspendSignal != 0)
  1065. return suspendSignal;
  1066. IntPtr buf = Marshal.AllocHGlobal (8192);
  1067. if (uname (buf) != 0) {
  1068. Marshal.FreeHGlobal (buf);
  1069. suspendSignal = -1;
  1070. return suspendSignal;
  1071. }
  1072. try {
  1073. switch (Marshal.PtrToStringAnsi (buf)) {
  1074. case "Darwin":
  1075. case "DragonFly":
  1076. case "FreeBSD":
  1077. case "NetBSD":
  1078. case "OpenBSD":
  1079. suspendSignal = 18;
  1080. break;
  1081. case "Linux":
  1082. // TODO: should fetch the machine name and
  1083. // if it is MIPS return 24
  1084. suspendSignal = 20;
  1085. break;
  1086. case "Solaris":
  1087. suspendSignal = 24;
  1088. break;
  1089. default:
  1090. suspendSignal = -1;
  1091. break;
  1092. }
  1093. return suspendSignal;
  1094. } finally {
  1095. Marshal.FreeHGlobal (buf);
  1096. }
  1097. }
  1098. /// <summary>
  1099. /// Suspends the process by sending SIGTSTP to itself
  1100. /// </summary>
  1101. /// <returns>The suspend.</returns>
  1102. static public bool Suspend ()
  1103. {
  1104. int signal = GetSuspendSignal ();
  1105. if (signal == -1)
  1106. return false;
  1107. killpg (0, signal);
  1108. return true;
  1109. }
  1110. }
  1111. /// <summary>
  1112. /// A clipboard implementation for Linux.
  1113. /// This implementation uses the xclip command to access the clipboard.
  1114. /// </summary>
  1115. /// <remarks>
  1116. /// If xclip is not installed, this implementation will not work.
  1117. /// </remarks>
  1118. class CursesClipboard : ClipboardBase {
  1119. public CursesClipboard ()
  1120. {
  1121. IsSupported = CheckSupport ();
  1122. }
  1123. string xclipPath = string.Empty;
  1124. public override bool IsSupported { get; }
  1125. bool CheckSupport ()
  1126. {
  1127. try {
  1128. var (exitCode, result) = ClipboardProcessRunner.Bash ("which xclip", runCurses: false);
  1129. if (exitCode == 0 && result.FileExists ()) {
  1130. xclipPath = result;
  1131. return true;
  1132. }
  1133. } catch (Exception) {
  1134. // Permissions issue.
  1135. }
  1136. return false;
  1137. }
  1138. protected override string GetClipboardDataImpl ()
  1139. {
  1140. var tempFileName = System.IO.Path.GetTempFileName ();
  1141. try {
  1142. var (exitCode, result) = ClipboardProcessRunner.Bash ($"{xclipPath} -selection clipboard -o > {tempFileName}");
  1143. if (exitCode == 0) {
  1144. return System.IO.File.ReadAllText (tempFileName);
  1145. }
  1146. } catch (Exception e) {
  1147. throw new NotSupportedException ($"{xclipPath} -selection clipboard -o failed.", e);
  1148. } finally {
  1149. System.IO.File.Delete (tempFileName);
  1150. }
  1151. return string.Empty;
  1152. }
  1153. protected override void SetClipboardDataImpl (string text)
  1154. {
  1155. try {
  1156. ClipboardProcessRunner.Bash ($"{xclipPath} - selection clipboard -i", false, text);
  1157. } catch (Exception e) {
  1158. throw new NotSupportedException ($"{xclipPath} -selection clipboard -o failed", e);
  1159. }
  1160. }
  1161. }
  1162. internal static class ClipboardProcessRunner {
  1163. public static (int exitCode, string result) Bash (string commandLine, bool output = true, string inputText = "", bool runCurses = true)
  1164. {
  1165. var arguments = $"-c \"{commandLine}\"";
  1166. var (exitCode, result) = Process ("bash", arguments, inputText);
  1167. if (exitCode == 0) {
  1168. if (runCurses && Application.Driver is CursesDriver) {
  1169. Curses.raw ();
  1170. Curses.noecho ();
  1171. }
  1172. }
  1173. return (exitCode, result.TrimEnd ());
  1174. }
  1175. public static (int exitCode, string result) Process (string cmd, string arguments, string input = null)
  1176. {
  1177. var errorBuilder = new System.Text.StringBuilder ();
  1178. var outputBuilder = new System.Text.StringBuilder ();
  1179. var output = string.Empty;
  1180. using (Process process = new Process {
  1181. StartInfo = new ProcessStartInfo {
  1182. FileName = cmd,
  1183. Arguments = arguments,
  1184. RedirectStandardOutput = true,
  1185. RedirectStandardError = true,
  1186. RedirectStandardInput = true,
  1187. UseShellExecute = false,
  1188. CreateNoWindow = true,
  1189. }
  1190. }) {
  1191. var eventHandled = new TaskCompletionSource<bool> ();
  1192. process.Start ();
  1193. if (!string.IsNullOrEmpty (input)) {
  1194. process.StandardInput.Write (input);
  1195. process.StandardInput.Close ();
  1196. }
  1197. //process.OutputDataReceived += (sender, args) => { outputBuilder.AppendLine (args.Data); };
  1198. //process.BeginOutputReadLine ();
  1199. //process.ErrorDataReceived += (sender, args) => { errorBuilder.AppendLine (args.Data); };
  1200. //process.BeginErrorReadLine ();
  1201. if (!process.WaitForExit (5000)) {
  1202. var timeoutError = $@"Process timed out. Command line: {process.StartInfo.FileName} {process.StartInfo.Arguments}.
  1203. Output: {outputBuilder}
  1204. Error: {errorBuilder}";
  1205. throw new TimeoutException (timeoutError);
  1206. }
  1207. if (process.ExitCode > 0) {
  1208. output = $@"Process failed to run. Command line: {cmd} {arguments}.
  1209. Output: {process.StandardOutput.ReadToEnd()}
  1210. Error: {process.StandardOutput.ReadToEnd ()}";
  1211. } else {
  1212. output = process.StandardOutput.ReadToEnd ().TrimEnd ();
  1213. }
  1214. return (process.ExitCode, output);
  1215. }
  1216. }
  1217. public static bool DoubleWaitForExit (this System.Diagnostics.Process process)
  1218. {
  1219. var result = process.WaitForExit (500);
  1220. if (result) {
  1221. process.WaitForExit ();
  1222. }
  1223. return result;
  1224. }
  1225. public static bool FileExists (this string value)
  1226. {
  1227. return !string.IsNullOrEmpty (value) && !value.Contains ("not found");
  1228. }
  1229. }
  1230. /// <summary>
  1231. /// A clipboard implementation for MacOSX.
  1232. /// This implementation uses the Mac clipboard API (via P/Invoke) to copy/paste.
  1233. /// The existance of the Mac pbcopy and pbpaste commands
  1234. /// is used to determine if copy/paste is supported.
  1235. /// </summary>
  1236. class MacOSXClipboard : ClipboardBase {
  1237. IntPtr nsString = objc_getClass ("NSString");
  1238. IntPtr nsPasteboard = objc_getClass ("NSPasteboard");
  1239. IntPtr utfTextType;
  1240. IntPtr generalPasteboard;
  1241. IntPtr initWithUtf8Register = sel_registerName ("initWithUTF8String:");
  1242. IntPtr allocRegister = sel_registerName ("alloc");
  1243. IntPtr setStringRegister = sel_registerName ("setString:forType:");
  1244. IntPtr stringForTypeRegister = sel_registerName ("stringForType:");
  1245. IntPtr utf8Register = sel_registerName ("UTF8String");
  1246. IntPtr nsStringPboardType;
  1247. IntPtr generalPasteboardRegister = sel_registerName ("generalPasteboard");
  1248. IntPtr clearContentsRegister = sel_registerName ("clearContents");
  1249. public MacOSXClipboard ()
  1250. {
  1251. utfTextType = objc_msgSend (objc_msgSend (nsString, allocRegister), initWithUtf8Register, "public.utf8-plain-text");
  1252. nsStringPboardType = objc_msgSend (objc_msgSend (nsString, allocRegister), initWithUtf8Register, "NSStringPboardType");
  1253. generalPasteboard = objc_msgSend (nsPasteboard, generalPasteboardRegister);
  1254. IsSupported = CheckSupport ();
  1255. }
  1256. public override bool IsSupported { get; }
  1257. bool CheckSupport ()
  1258. {
  1259. var (exitCode, result) = ClipboardProcessRunner.Bash ("which pbcopy");
  1260. if (exitCode != 0 || !result.FileExists ()) {
  1261. return false;
  1262. }
  1263. (exitCode, result) = ClipboardProcessRunner.Bash ("which pbpaste");
  1264. return exitCode == 0 && result.FileExists ();
  1265. }
  1266. protected override string GetClipboardDataImpl ()
  1267. {
  1268. var ptr = objc_msgSend (generalPasteboard, stringForTypeRegister, nsStringPboardType);
  1269. var charArray = objc_msgSend (ptr, utf8Register);
  1270. return Marshal.PtrToStringAnsi (charArray);
  1271. }
  1272. protected override void SetClipboardDataImpl (string text)
  1273. {
  1274. IntPtr str = default;
  1275. try {
  1276. str = objc_msgSend (objc_msgSend (nsString, allocRegister), initWithUtf8Register, text);
  1277. objc_msgSend (generalPasteboard, clearContentsRegister);
  1278. objc_msgSend (generalPasteboard, setStringRegister, str, utfTextType);
  1279. } finally {
  1280. if (str != default) {
  1281. objc_msgSend (str, sel_registerName ("release"));
  1282. }
  1283. }
  1284. }
  1285. [DllImport ("/System/Library/Frameworks/AppKit.framework/AppKit")]
  1286. static extern IntPtr objc_getClass (string className);
  1287. [DllImport ("/System/Library/Frameworks/AppKit.framework/AppKit")]
  1288. static extern IntPtr objc_msgSend (IntPtr receiver, IntPtr selector);
  1289. [DllImport ("/System/Library/Frameworks/AppKit.framework/AppKit")]
  1290. static extern IntPtr objc_msgSend (IntPtr receiver, IntPtr selector, string arg1);
  1291. [DllImport ("/System/Library/Frameworks/AppKit.framework/AppKit")]
  1292. static extern IntPtr objc_msgSend (IntPtr receiver, IntPtr selector, IntPtr arg1);
  1293. [DllImport ("/System/Library/Frameworks/AppKit.framework/AppKit")]
  1294. static extern IntPtr objc_msgSend (IntPtr receiver, IntPtr selector, IntPtr arg1, IntPtr arg2);
  1295. [DllImport ("/System/Library/Frameworks/AppKit.framework/AppKit")]
  1296. static extern IntPtr sel_registerName (string selectorName);
  1297. }
  1298. /// <summary>
  1299. /// A clipboard implementation for Linux, when running under WSL.
  1300. /// This implementation uses the Windows clipboard to store the data, and uses Windows'
  1301. /// powershell.exe (launched via WSL interop services) to set/get the Windows
  1302. /// clipboard.
  1303. /// </summary>
  1304. class WSLClipboard : ClipboardBase {
  1305. bool isSupported = false;
  1306. public WSLClipboard ()
  1307. {
  1308. isSupported = CheckSupport ();
  1309. }
  1310. public override bool IsSupported {
  1311. get {
  1312. return isSupported = CheckSupport ();
  1313. }
  1314. }
  1315. private string powershellPath = string.Empty;
  1316. bool CheckSupport ()
  1317. {
  1318. if (string.IsNullOrEmpty (powershellPath)) {
  1319. // Specify pwsh.exe (not pwsh) to ensure we get the Windows version (invoked via WSL)
  1320. var (exitCode, result) = ClipboardProcessRunner.Bash ("which pwsh.exe");
  1321. if (exitCode > 0) {
  1322. (exitCode, result) = ClipboardProcessRunner.Bash ("which powershell.exe");
  1323. }
  1324. if (exitCode == 0) {
  1325. powershellPath = result;
  1326. }
  1327. }
  1328. return !string.IsNullOrEmpty (powershellPath);
  1329. }
  1330. protected override string GetClipboardDataImpl ()
  1331. {
  1332. var (exitCode, output) = ClipboardProcessRunner.Process (powershellPath, "-noprofile -command \"Get-Clipboard\"");
  1333. if (exitCode == 0) {
  1334. if (Application.Driver is CursesDriver) {
  1335. Curses.raw ();
  1336. Curses.noecho ();
  1337. }
  1338. if (output.EndsWith ("\r\n")) {
  1339. output = output.Substring (0, output.Length - 2);
  1340. }
  1341. return output;
  1342. }
  1343. return string.Empty;
  1344. }
  1345. protected override void SetClipboardDataImpl (string text)
  1346. {
  1347. var (exitCode, output) = ClipboardProcessRunner.Process (powershellPath, $"-noprofile -command \"Set-Clipboard -Value \\\"{text}\\\"\"");
  1348. if (exitCode == 0) {
  1349. if (Application.Driver is CursesDriver) {
  1350. Curses.raw ();
  1351. Curses.noecho ();
  1352. }
  1353. }
  1354. }
  1355. }
  1356. }