CursesDriver.cs 48 KB

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