CursesDriver.cs 51 KB

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