CursesDriver.cs 51 KB

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