CursesDriver.cs 51 KB

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