CursesDriver.cs 51 KB

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