CursesDriver.cs 51 KB

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