NetDriver.cs 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768
  1. //
  2. // NetDriver.cs: The System.Console-based .NET driver, works on Windows and Unix, but is not particularly efficient.
  3. //
  4. using System.Collections.Concurrent;
  5. using System.Diagnostics;
  6. using System.Diagnostics.CodeAnalysis;
  7. using System.Runtime.InteropServices;
  8. using static Terminal.Gui.ConsoleDrivers.ConsoleKeyMapping;
  9. using static Terminal.Gui.NetEvents;
  10. namespace Terminal.Gui;
  11. internal class NetWinVTConsole
  12. {
  13. private const uint DISABLE_NEWLINE_AUTO_RETURN = 8;
  14. private const uint ENABLE_ECHO_INPUT = 4;
  15. private const uint ENABLE_EXTENDED_FLAGS = 128;
  16. private const uint ENABLE_INSERT_MODE = 32;
  17. private const uint ENABLE_LINE_INPUT = 2;
  18. private const uint ENABLE_LVB_GRID_WORLDWIDE = 10;
  19. private const uint ENABLE_MOUSE_INPUT = 16;
  20. // Input modes.
  21. private const uint ENABLE_PROCESSED_INPUT = 1;
  22. // Output modes.
  23. private const uint ENABLE_PROCESSED_OUTPUT = 1;
  24. private const uint ENABLE_QUICK_EDIT_MODE = 64;
  25. private const uint ENABLE_VIRTUAL_TERMINAL_INPUT = 512;
  26. private const uint ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4;
  27. private const uint ENABLE_WINDOW_INPUT = 8;
  28. private const uint ENABLE_WRAP_AT_EOL_OUTPUT = 2;
  29. private const int STD_ERROR_HANDLE = -12;
  30. private const int STD_INPUT_HANDLE = -10;
  31. private const int STD_OUTPUT_HANDLE = -11;
  32. private readonly nint _errorHandle;
  33. private readonly nint _inputHandle;
  34. private readonly uint _originalErrorConsoleMode;
  35. private readonly uint _originalInputConsoleMode;
  36. private readonly uint _originalOutputConsoleMode;
  37. private readonly nint _outputHandle;
  38. public NetWinVTConsole ()
  39. {
  40. _inputHandle = GetStdHandle (STD_INPUT_HANDLE);
  41. if (!GetConsoleMode (_inputHandle, out uint mode))
  42. {
  43. throw new ApplicationException ($"Failed to get input console mode, error code: {GetLastError ()}.");
  44. }
  45. _originalInputConsoleMode = mode;
  46. if ((mode & ENABLE_VIRTUAL_TERMINAL_INPUT) < ENABLE_VIRTUAL_TERMINAL_INPUT)
  47. {
  48. mode |= ENABLE_VIRTUAL_TERMINAL_INPUT;
  49. if (!SetConsoleMode (_inputHandle, mode))
  50. {
  51. throw new ApplicationException ($"Failed to set input console mode, error code: {GetLastError ()}.");
  52. }
  53. }
  54. _outputHandle = GetStdHandle (STD_OUTPUT_HANDLE);
  55. if (!GetConsoleMode (_outputHandle, out mode))
  56. {
  57. throw new ApplicationException ($"Failed to get output console mode, error code: {GetLastError ()}.");
  58. }
  59. _originalOutputConsoleMode = mode;
  60. if ((mode & (ENABLE_VIRTUAL_TERMINAL_PROCESSING | DISABLE_NEWLINE_AUTO_RETURN)) < DISABLE_NEWLINE_AUTO_RETURN)
  61. {
  62. mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING | DISABLE_NEWLINE_AUTO_RETURN;
  63. if (!SetConsoleMode (_outputHandle, mode))
  64. {
  65. throw new ApplicationException ($"Failed to set output console mode, error code: {GetLastError ()}.");
  66. }
  67. }
  68. _errorHandle = GetStdHandle (STD_ERROR_HANDLE);
  69. if (!GetConsoleMode (_errorHandle, out mode))
  70. {
  71. throw new ApplicationException ($"Failed to get error console mode, error code: {GetLastError ()}.");
  72. }
  73. _originalErrorConsoleMode = mode;
  74. if ((mode & DISABLE_NEWLINE_AUTO_RETURN) < DISABLE_NEWLINE_AUTO_RETURN)
  75. {
  76. mode |= DISABLE_NEWLINE_AUTO_RETURN;
  77. if (!SetConsoleMode (_errorHandle, mode))
  78. {
  79. throw new ApplicationException ($"Failed to set error console mode, error code: {GetLastError ()}.");
  80. }
  81. }
  82. }
  83. public void Cleanup ()
  84. {
  85. if (!SetConsoleMode (_inputHandle, _originalInputConsoleMode))
  86. {
  87. throw new ApplicationException ($"Failed to restore input console mode, error code: {GetLastError ()}.");
  88. }
  89. if (!SetConsoleMode (_outputHandle, _originalOutputConsoleMode))
  90. {
  91. throw new ApplicationException ($"Failed to restore output console mode, error code: {GetLastError ()}.");
  92. }
  93. if (!SetConsoleMode (_errorHandle, _originalErrorConsoleMode))
  94. {
  95. throw new ApplicationException ($"Failed to restore error console mode, error code: {GetLastError ()}.");
  96. }
  97. }
  98. [DllImport ("kernel32.dll")]
  99. private static extern bool GetConsoleMode (nint hConsoleHandle, out uint lpMode);
  100. [DllImport ("kernel32.dll")]
  101. private static extern uint GetLastError ();
  102. [DllImport ("kernel32.dll", SetLastError = true)]
  103. private static extern nint GetStdHandle (int nStdHandle);
  104. [DllImport ("kernel32.dll")]
  105. private static extern bool SetConsoleMode (nint hConsoleHandle, uint dwMode);
  106. }
  107. internal class NetEvents : IDisposable
  108. {
  109. private readonly CancellationTokenSource _netEventsDisposed = new CancellationTokenSource ();
  110. //CancellationTokenSource _waitForStartCancellationTokenSource;
  111. private readonly ManualResetEventSlim _winChange = new (false);
  112. private readonly BlockingCollection<InputResult?> _inputQueue = new (new ConcurrentQueue<InputResult?> ());
  113. private readonly ConsoleDriver _consoleDriver;
  114. public EscSeqRequests EscSeqRequests { get; } = new ();
  115. public AnsiResponseParser<ConsoleKeyInfo> Parser { get; private set; } = new ();
  116. public NetEvents (ConsoleDriver consoleDriver)
  117. {
  118. _consoleDriver = consoleDriver ?? throw new ArgumentNullException (nameof (consoleDriver));
  119. Task.Run (() =>
  120. {
  121. try
  122. {
  123. ProcessInputQueue ();
  124. }
  125. catch (OperationCanceledException)
  126. { }
  127. }, _netEventsDisposed.Token);
  128. Task.Run (()=>{
  129. try
  130. {
  131. CheckWindowSizeChange();
  132. }
  133. catch (OperationCanceledException)
  134. { }}, _netEventsDisposed.Token);
  135. Parser.UnexpectedResponseHandler = ProcessRequestResponse;
  136. }
  137. public InputResult? DequeueInput ()
  138. {
  139. while (!_netEventsDisposed.Token.IsCancellationRequested)
  140. {
  141. _winChange.Set ();
  142. try
  143. {
  144. if (_inputQueue.TryTake (out var item, -1, _netEventsDisposed.Token))
  145. {
  146. return item;
  147. }
  148. }
  149. catch (OperationCanceledException)
  150. {
  151. return null;
  152. }
  153. }
  154. return null;
  155. }
  156. private ConsoleKeyInfo ReadConsoleKeyInfo ( bool intercept = true)
  157. {
  158. // if there is a key available, return it without waiting
  159. // (or dispatching work to the thread queue)
  160. if (Console.KeyAvailable)
  161. {
  162. return Console.ReadKey (intercept);
  163. }
  164. while (!_netEventsDisposed.IsCancellationRequested)
  165. {
  166. Task.Delay (100, _netEventsDisposed.Token).Wait (_netEventsDisposed.Token);
  167. foreach (var k in ShouldRelease ())
  168. {
  169. ProcessMapConsoleKeyInfo (k);
  170. }
  171. if (Console.KeyAvailable)
  172. {
  173. return Console.ReadKey (intercept);
  174. }
  175. }
  176. _netEventsDisposed.Token.ThrowIfCancellationRequested ();
  177. return default (ConsoleKeyInfo);
  178. }
  179. public IEnumerable<ConsoleKeyInfo> ShouldRelease ()
  180. {
  181. if (Parser.State == AnsiResponseParserState.ExpectingBracket &&
  182. DateTime.Now - Parser.StateChangedAt > _consoleDriver.EscTimeout)
  183. {
  184. return Parser.Release ().Select (o => o.Item2);
  185. }
  186. return [];
  187. }
  188. private void ProcessInputQueue ()
  189. {
  190. while (!_netEventsDisposed.IsCancellationRequested)
  191. {
  192. if (_inputQueue.Count == 0)
  193. {
  194. while (!_netEventsDisposed.IsCancellationRequested)
  195. {
  196. ConsoleKeyInfo consoleKeyInfo;
  197. consoleKeyInfo = ReadConsoleKeyInfo ();
  198. // Parse
  199. foreach (var k in Parser.ProcessInput (Tuple.Create (consoleKeyInfo.KeyChar, consoleKeyInfo)))
  200. {
  201. ProcessMapConsoleKeyInfo (k.Item2);
  202. }
  203. }
  204. }
  205. }
  206. }
  207. void ProcessMapConsoleKeyInfo (ConsoleKeyInfo consoleKeyInfo)
  208. {
  209. _inputQueue.Add (
  210. new InputResult
  211. {
  212. EventType = EventType.Key, ConsoleKeyInfo = EscSeqUtils.MapConsoleKeyInfo (consoleKeyInfo)
  213. }
  214. );
  215. }
  216. private void CheckWindowSizeChange ()
  217. {
  218. void RequestWindowSize ()
  219. {
  220. while (!_netEventsDisposed.IsCancellationRequested)
  221. {
  222. // Wait for a while then check if screen has changed sizes
  223. Task.Delay (500, _netEventsDisposed.Token).Wait (_netEventsDisposed.Token);
  224. int buffHeight, buffWidth;
  225. if (((NetDriver)_consoleDriver).IsWinPlatform)
  226. {
  227. buffHeight = Math.Max (Console.BufferHeight, 0);
  228. buffWidth = Math.Max (Console.BufferWidth, 0);
  229. }
  230. else
  231. {
  232. buffHeight = _consoleDriver.Rows;
  233. buffWidth = _consoleDriver.Cols;
  234. }
  235. if (EnqueueWindowSizeEvent (
  236. Math.Max (Console.WindowHeight, 0),
  237. Math.Max (Console.WindowWidth, 0),
  238. buffHeight,
  239. buffWidth
  240. ))
  241. {
  242. return;
  243. }
  244. }
  245. _netEventsDisposed.Token.ThrowIfCancellationRequested ();
  246. }
  247. while (!_netEventsDisposed.IsCancellationRequested)
  248. {
  249. try
  250. {
  251. _winChange.Wait (_netEventsDisposed.Token);
  252. _winChange.Reset ();
  253. RequestWindowSize ();
  254. }
  255. catch (OperationCanceledException)
  256. {
  257. return;
  258. }
  259. }
  260. }
  261. /// <summary>Enqueue a window size event if the window size has changed.</summary>
  262. /// <param name="winHeight"></param>
  263. /// <param name="winWidth"></param>
  264. /// <param name="buffHeight"></param>
  265. /// <param name="buffWidth"></param>
  266. /// <returns></returns>
  267. private bool EnqueueWindowSizeEvent (int winHeight, int winWidth, int buffHeight, int buffWidth)
  268. {
  269. if (winWidth == _consoleDriver.Cols && winHeight == _consoleDriver.Rows)
  270. {
  271. return false;
  272. }
  273. int w = Math.Max (winWidth, 0);
  274. int h = Math.Max (winHeight, 0);
  275. _inputQueue.Add (
  276. new InputResult
  277. {
  278. EventType = EventType.WindowSize, WindowSizeEvent = new WindowSizeEvent { Size = new (w, h) }
  279. }
  280. );
  281. return true;
  282. }
  283. private bool ProcessRequestResponse (IEnumerable<Tuple<char, ConsoleKeyInfo>> obj)
  284. {
  285. // Added for signature compatibility with existing method, not sure what they are even for.
  286. ConsoleKeyInfo newConsoleKeyInfo = default;
  287. ConsoleKey key = default;
  288. ConsoleModifiers mod = default;
  289. ProcessRequestResponse (ref newConsoleKeyInfo, ref key, obj.Select (v=>v.Item2).ToArray (),ref mod);
  290. // Handled
  291. return true;
  292. }
  293. // Process a CSI sequence received by the driver (key pressed, mouse event, or request/response event)
  294. private void ProcessRequestResponse (
  295. ref ConsoleKeyInfo newConsoleKeyInfo,
  296. ref ConsoleKey key,
  297. ConsoleKeyInfo [] cki,
  298. ref ConsoleModifiers mod
  299. )
  300. {
  301. // isMouse is true if it's CSI<, false otherwise
  302. EscSeqUtils.DecodeEscSeq (
  303. EscSeqRequests,
  304. ref newConsoleKeyInfo,
  305. ref key,
  306. cki,
  307. ref mod,
  308. out string c1Control,
  309. out string code,
  310. out string [] values,
  311. out string terminating,
  312. out bool isMouse,
  313. out List<MouseFlags> mouseFlags,
  314. out Point pos,
  315. out bool isReq,
  316. (f, p) => HandleMouseEvent (MapMouseFlags (f), p)
  317. );
  318. if (isMouse)
  319. {
  320. foreach (MouseFlags mf in mouseFlags)
  321. {
  322. HandleMouseEvent (MapMouseFlags (mf), pos);
  323. }
  324. return;
  325. }
  326. if (isReq)
  327. {
  328. HandleRequestResponseEvent (c1Control, code, values, terminating);
  329. return;
  330. }
  331. HandleKeyboardEvent (newConsoleKeyInfo);
  332. }
  333. [UnconditionalSuppressMessage ("AOT", "IL3050:Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.", Justification = "<Pending>")]
  334. private MouseButtonState MapMouseFlags (MouseFlags mouseFlags)
  335. {
  336. MouseButtonState mbs = default;
  337. foreach (object flag in Enum.GetValues (mouseFlags.GetType ()))
  338. {
  339. if (mouseFlags.HasFlag ((MouseFlags)flag))
  340. {
  341. switch (flag)
  342. {
  343. case MouseFlags.Button1Pressed:
  344. mbs |= MouseButtonState.Button1Pressed;
  345. break;
  346. case MouseFlags.Button1Released:
  347. mbs |= MouseButtonState.Button1Released;
  348. break;
  349. case MouseFlags.Button1Clicked:
  350. mbs |= MouseButtonState.Button1Clicked;
  351. break;
  352. case MouseFlags.Button1DoubleClicked:
  353. mbs |= MouseButtonState.Button1DoubleClicked;
  354. break;
  355. case MouseFlags.Button1TripleClicked:
  356. mbs |= MouseButtonState.Button1TripleClicked;
  357. break;
  358. case MouseFlags.Button2Pressed:
  359. mbs |= MouseButtonState.Button2Pressed;
  360. break;
  361. case MouseFlags.Button2Released:
  362. mbs |= MouseButtonState.Button2Released;
  363. break;
  364. case MouseFlags.Button2Clicked:
  365. mbs |= MouseButtonState.Button2Clicked;
  366. break;
  367. case MouseFlags.Button2DoubleClicked:
  368. mbs |= MouseButtonState.Button2DoubleClicked;
  369. break;
  370. case MouseFlags.Button2TripleClicked:
  371. mbs |= MouseButtonState.Button2TripleClicked;
  372. break;
  373. case MouseFlags.Button3Pressed:
  374. mbs |= MouseButtonState.Button3Pressed;
  375. break;
  376. case MouseFlags.Button3Released:
  377. mbs |= MouseButtonState.Button3Released;
  378. break;
  379. case MouseFlags.Button3Clicked:
  380. mbs |= MouseButtonState.Button3Clicked;
  381. break;
  382. case MouseFlags.Button3DoubleClicked:
  383. mbs |= MouseButtonState.Button3DoubleClicked;
  384. break;
  385. case MouseFlags.Button3TripleClicked:
  386. mbs |= MouseButtonState.Button3TripleClicked;
  387. break;
  388. case MouseFlags.WheeledUp:
  389. mbs |= MouseButtonState.ButtonWheeledUp;
  390. break;
  391. case MouseFlags.WheeledDown:
  392. mbs |= MouseButtonState.ButtonWheeledDown;
  393. break;
  394. case MouseFlags.WheeledLeft:
  395. mbs |= MouseButtonState.ButtonWheeledLeft;
  396. break;
  397. case MouseFlags.WheeledRight:
  398. mbs |= MouseButtonState.ButtonWheeledRight;
  399. break;
  400. case MouseFlags.Button4Pressed:
  401. mbs |= MouseButtonState.Button4Pressed;
  402. break;
  403. case MouseFlags.Button4Released:
  404. mbs |= MouseButtonState.Button4Released;
  405. break;
  406. case MouseFlags.Button4Clicked:
  407. mbs |= MouseButtonState.Button4Clicked;
  408. break;
  409. case MouseFlags.Button4DoubleClicked:
  410. mbs |= MouseButtonState.Button4DoubleClicked;
  411. break;
  412. case MouseFlags.Button4TripleClicked:
  413. mbs |= MouseButtonState.Button4TripleClicked;
  414. break;
  415. case MouseFlags.ButtonShift:
  416. mbs |= MouseButtonState.ButtonShift;
  417. break;
  418. case MouseFlags.ButtonCtrl:
  419. mbs |= MouseButtonState.ButtonCtrl;
  420. break;
  421. case MouseFlags.ButtonAlt:
  422. mbs |= MouseButtonState.ButtonAlt;
  423. break;
  424. case MouseFlags.ReportMousePosition:
  425. mbs |= MouseButtonState.ReportMousePosition;
  426. break;
  427. case MouseFlags.AllEvents:
  428. mbs |= MouseButtonState.AllEvents;
  429. break;
  430. }
  431. }
  432. }
  433. return mbs;
  434. }
  435. private Point _lastCursorPosition;
  436. private void HandleRequestResponseEvent (string c1Control, string code, string [] values, string terminating)
  437. {
  438. switch (terminating)
  439. {
  440. // BUGBUG: I can't find where we send a request for cursor position (ESC[?6n), so I'm not sure if this is needed.
  441. case EscSeqUtils.CSI_RequestCursorPositionReport_Terminator:
  442. var point = new Point { X = int.Parse (values [1]) - 1, Y = int.Parse (values [0]) - 1 };
  443. if (_lastCursorPosition.Y != point.Y)
  444. {
  445. _lastCursorPosition = point;
  446. var eventType = EventType.WindowPosition;
  447. var winPositionEv = new WindowPositionEvent { CursorPosition = point };
  448. _inputQueue.Add (
  449. new InputResult { EventType = eventType, WindowPositionEvent = winPositionEv }
  450. );
  451. }
  452. else
  453. {
  454. return;
  455. }
  456. break;
  457. case EscSeqUtils.CSI_ReportTerminalSizeInChars_Terminator:
  458. switch (values [0])
  459. {
  460. case EscSeqUtils.CSI_ReportTerminalSizeInChars_ResponseValue:
  461. EnqueueWindowSizeEvent (
  462. Math.Max (int.Parse (values [1]), 0),
  463. Math.Max (int.Parse (values [2]), 0),
  464. Math.Max (int.Parse (values [1]), 0),
  465. Math.Max (int.Parse (values [2]), 0)
  466. );
  467. break;
  468. default:
  469. EnqueueRequestResponseEvent (c1Control, code, values, terminating);
  470. break;
  471. }
  472. break;
  473. default:
  474. EnqueueRequestResponseEvent (c1Control, code, values, terminating);
  475. break;
  476. }
  477. }
  478. private void EnqueueRequestResponseEvent (string c1Control, string code, string [] values, string terminating)
  479. {
  480. var eventType = EventType.RequestResponse;
  481. var requestRespEv = new RequestResponseEvent { ResultTuple = (c1Control, code, values, terminating) };
  482. _inputQueue.Add (
  483. new InputResult { EventType = eventType, RequestResponseEvent = requestRespEv }
  484. );
  485. }
  486. private void HandleMouseEvent (MouseButtonState buttonState, Point pos)
  487. {
  488. var mouseEvent = new MouseEvent { Position = pos, ButtonState = buttonState };
  489. _inputQueue.Add (
  490. new InputResult { EventType = EventType.Mouse, MouseEvent = mouseEvent }
  491. );
  492. }
  493. public enum EventType
  494. {
  495. Key = 1,
  496. Mouse = 2,
  497. WindowSize = 3,
  498. WindowPosition = 4,
  499. RequestResponse = 5
  500. }
  501. [Flags]
  502. public enum MouseButtonState
  503. {
  504. Button1Pressed = 0x1,
  505. Button1Released = 0x2,
  506. Button1Clicked = 0x4,
  507. Button1DoubleClicked = 0x8,
  508. Button1TripleClicked = 0x10,
  509. Button2Pressed = 0x20,
  510. Button2Released = 0x40,
  511. Button2Clicked = 0x80,
  512. Button2DoubleClicked = 0x100,
  513. Button2TripleClicked = 0x200,
  514. Button3Pressed = 0x400,
  515. Button3Released = 0x800,
  516. Button3Clicked = 0x1000,
  517. Button3DoubleClicked = 0x2000,
  518. Button3TripleClicked = 0x4000,
  519. ButtonWheeledUp = 0x8000,
  520. ButtonWheeledDown = 0x10000,
  521. ButtonWheeledLeft = 0x20000,
  522. ButtonWheeledRight = 0x40000,
  523. Button4Pressed = 0x80000,
  524. Button4Released = 0x100000,
  525. Button4Clicked = 0x200000,
  526. Button4DoubleClicked = 0x400000,
  527. Button4TripleClicked = 0x800000,
  528. ButtonShift = 0x1000000,
  529. ButtonCtrl = 0x2000000,
  530. ButtonAlt = 0x4000000,
  531. ReportMousePosition = 0x8000000,
  532. AllEvents = -1
  533. }
  534. public struct MouseEvent
  535. {
  536. public Point Position;
  537. public MouseButtonState ButtonState;
  538. }
  539. public struct WindowSizeEvent
  540. {
  541. public Size Size;
  542. }
  543. public struct WindowPositionEvent
  544. {
  545. public int Top;
  546. public int Left;
  547. public Point CursorPosition;
  548. }
  549. public struct RequestResponseEvent
  550. {
  551. public (string c1Control, string code, string [] values, string terminating) ResultTuple;
  552. }
  553. public struct InputResult
  554. {
  555. public EventType EventType;
  556. public ConsoleKeyInfo ConsoleKeyInfo;
  557. public MouseEvent MouseEvent;
  558. public WindowSizeEvent WindowSizeEvent;
  559. public WindowPositionEvent WindowPositionEvent;
  560. public RequestResponseEvent RequestResponseEvent;
  561. public readonly override string ToString ()
  562. {
  563. return EventType switch
  564. {
  565. EventType.Key => ToString (ConsoleKeyInfo),
  566. EventType.Mouse => MouseEvent.ToString (),
  567. //EventType.WindowSize => WindowSize.ToString (),
  568. //EventType.RequestResponse => RequestResponse.ToString (),
  569. _ => "Unknown event type: " + EventType
  570. };
  571. }
  572. /// <summary>Prints a ConsoleKeyInfoEx structure</summary>
  573. /// <param name="cki"></param>
  574. /// <returns></returns>
  575. public readonly string ToString (ConsoleKeyInfo cki)
  576. {
  577. var ke = new Key ((KeyCode)cki.KeyChar);
  578. var sb = new StringBuilder ();
  579. sb.Append ($"Key: {(KeyCode)cki.Key} ({cki.Key})");
  580. sb.Append ((cki.Modifiers & ConsoleModifiers.Shift) != 0 ? " | Shift" : string.Empty);
  581. sb.Append ((cki.Modifiers & ConsoleModifiers.Control) != 0 ? " | Control" : string.Empty);
  582. sb.Append ((cki.Modifiers & ConsoleModifiers.Alt) != 0 ? " | Alt" : string.Empty);
  583. sb.Append ($", KeyChar: {ke.AsRune.MakePrintable ()} ({(uint)cki.KeyChar}) ");
  584. string s = sb.ToString ().TrimEnd (',').TrimEnd (' ');
  585. return $"[ConsoleKeyInfo({s})]";
  586. }
  587. }
  588. private void HandleKeyboardEvent (ConsoleKeyInfo cki)
  589. {
  590. var inputResult = new InputResult { EventType = EventType.Key, ConsoleKeyInfo = cki };
  591. _inputQueue.Add (inputResult);
  592. }
  593. public void Dispose ()
  594. {
  595. _netEventsDisposed?.Cancel ();
  596. _netEventsDisposed?.Dispose ();
  597. try
  598. {
  599. // throws away any typeahead that has been typed by
  600. // the user and has not yet been read by the program.
  601. while (Console.KeyAvailable)
  602. {
  603. Console.ReadKey (true);
  604. }
  605. }
  606. catch (InvalidOperationException)
  607. {
  608. // Ignore - Console input has already been closed
  609. }
  610. }
  611. }
  612. internal class NetDriver : ConsoleDriver
  613. {
  614. private const int COLOR_BLACK = 30;
  615. private const int COLOR_BLUE = 34;
  616. private const int COLOR_BRIGHT_BLACK = 90;
  617. private const int COLOR_BRIGHT_BLUE = 94;
  618. private const int COLOR_BRIGHT_CYAN = 96;
  619. private const int COLOR_BRIGHT_GREEN = 92;
  620. private const int COLOR_BRIGHT_MAGENTA = 95;
  621. private const int COLOR_BRIGHT_RED = 91;
  622. private const int COLOR_BRIGHT_WHITE = 97;
  623. private const int COLOR_BRIGHT_YELLOW = 93;
  624. private const int COLOR_CYAN = 36;
  625. private const int COLOR_GREEN = 32;
  626. private const int COLOR_MAGENTA = 35;
  627. private const int COLOR_RED = 31;
  628. private const int COLOR_WHITE = 37;
  629. private const int COLOR_YELLOW = 33;
  630. private NetMainLoop _mainLoopDriver;
  631. public bool IsWinPlatform { get; private set; }
  632. public NetWinVTConsole NetWinConsole { get; private set; }
  633. public override bool SupportsTrueColor => Environment.OSVersion.Platform == PlatformID.Unix
  634. || (IsWinPlatform && Environment.OSVersion.Version.Build >= 14931);
  635. public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control)
  636. {
  637. var input = new InputResult
  638. {
  639. EventType = EventType.Key, ConsoleKeyInfo = new ConsoleKeyInfo (keyChar, key, shift, alt, control)
  640. };
  641. try
  642. {
  643. ProcessInput (input);
  644. }
  645. catch (OverflowException)
  646. { }
  647. }
  648. public override void Suspend ()
  649. {
  650. if (Environment.OSVersion.Platform != PlatformID.Unix)
  651. {
  652. return;
  653. }
  654. StopReportingMouseMoves ();
  655. if (!RunningUnitTests)
  656. {
  657. Console.ResetColor ();
  658. Console.Clear ();
  659. //Disable alternative screen buffer.
  660. Console.Out.Write (EscSeqUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll);
  661. //Set cursor key to cursor.
  662. Console.Out.Write (EscSeqUtils.CSI_ShowCursor);
  663. Platform.Suspend ();
  664. //Enable alternative screen buffer.
  665. Console.Out.Write (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll);
  666. SetContentsAsDirty ();
  667. Refresh ();
  668. }
  669. StartReportingMouseMoves ();
  670. }
  671. public override bool UpdateScreen ()
  672. {
  673. bool updated = false;
  674. if (RunningUnitTests
  675. || _winSizeChanging
  676. || Console.WindowHeight < 1
  677. || Contents.Length != Rows * Cols
  678. || Rows != Console.WindowHeight)
  679. {
  680. return updated;
  681. }
  682. var top = 0;
  683. var left = 0;
  684. int rows = Rows;
  685. int cols = Cols;
  686. var output = new StringBuilder ();
  687. Attribute? redrawAttr = null;
  688. int lastCol = -1;
  689. CursorVisibility? savedVisibility = _cachedCursorVisibility;
  690. SetCursorVisibility (CursorVisibility.Invisible);
  691. for (int row = top; row < rows; row++)
  692. {
  693. if (Console.WindowHeight < 1)
  694. {
  695. return updated;
  696. }
  697. if (!_dirtyLines [row])
  698. {
  699. continue;
  700. }
  701. if (!SetCursorPosition (0, row))
  702. {
  703. return updated;
  704. }
  705. updated = true;
  706. _dirtyLines [row] = false;
  707. output.Clear ();
  708. for (int col = left; col < cols; col++)
  709. {
  710. lastCol = -1;
  711. var outputWidth = 0;
  712. for (; col < cols; col++)
  713. {
  714. if (!Contents [row, col].IsDirty)
  715. {
  716. if (output.Length > 0)
  717. {
  718. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  719. }
  720. else if (lastCol == -1)
  721. {
  722. lastCol = col;
  723. }
  724. if (lastCol + 1 < cols)
  725. {
  726. lastCol++;
  727. }
  728. continue;
  729. }
  730. if (lastCol == -1)
  731. {
  732. lastCol = col;
  733. }
  734. Attribute attr = Contents [row, col].Attribute.Value;
  735. // Performance: Only send the escape sequence if the attribute has changed.
  736. if (attr != redrawAttr)
  737. {
  738. redrawAttr = attr;
  739. if (Force16Colors)
  740. {
  741. output.Append (
  742. EscSeqUtils.CSI_SetGraphicsRendition (
  743. MapColors (
  744. (ConsoleColor)attr.Background.GetClosestNamedColor16 (),
  745. false
  746. ),
  747. MapColors ((ConsoleColor)attr.Foreground.GetClosestNamedColor16 ())
  748. )
  749. );
  750. }
  751. else
  752. {
  753. output.Append (
  754. EscSeqUtils.CSI_SetForegroundColorRGB (
  755. attr.Foreground.R,
  756. attr.Foreground.G,
  757. attr.Foreground.B
  758. )
  759. );
  760. output.Append (
  761. EscSeqUtils.CSI_SetBackgroundColorRGB (
  762. attr.Background.R,
  763. attr.Background.G,
  764. attr.Background.B
  765. )
  766. );
  767. }
  768. }
  769. outputWidth++;
  770. Rune rune = Contents [row, col].Rune;
  771. output.Append (rune);
  772. if (Contents [row, col].CombiningMarks.Count > 0)
  773. {
  774. // AtlasEngine does not support NON-NORMALIZED combining marks in a way
  775. // compatible with the driver architecture. Any CMs (except in the first col)
  776. // are correctly combined with the base char, but are ALSO treated as 1 column
  777. // width codepoints E.g. `echo "[e`u{0301}`u{0301}]"` will output `[é ]`.
  778. //
  779. // For now, we just ignore the list of CMs.
  780. //foreach (var combMark in Contents [row, col].CombiningMarks) {
  781. // output.Append (combMark);
  782. //}
  783. // WriteToConsole (output, ref lastCol, row, ref outputWidth);
  784. }
  785. else if (rune.IsSurrogatePair () && rune.GetColumns () < 2)
  786. {
  787. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  788. SetCursorPosition (col - 1, row);
  789. }
  790. Contents [row, col].IsDirty = false;
  791. }
  792. }
  793. if (output.Length > 0)
  794. {
  795. SetCursorPosition (lastCol, row);
  796. Console.Write (output);
  797. }
  798. foreach (var s in Application.Sixel)
  799. {
  800. if (!string.IsNullOrWhiteSpace (s.SixelData))
  801. {
  802. SetCursorPosition (s.ScreenPosition.X, s.ScreenPosition.Y);
  803. Console.Write (s.SixelData);
  804. }
  805. }
  806. }
  807. SetCursorPosition (0, 0);
  808. _cachedCursorVisibility = savedVisibility;
  809. void WriteToConsole (StringBuilder output, ref int lastCol, int row, ref int outputWidth)
  810. {
  811. SetCursorPosition (lastCol, row);
  812. Console.Write (output);
  813. output.Clear ();
  814. lastCol += outputWidth;
  815. outputWidth = 0;
  816. }
  817. return updated;
  818. }
  819. /// <inheritdoc />
  820. internal override IAnsiResponseParser GetParser () => _mainLoopDriver._netEvents.Parser;
  821. /// <inheritdoc />
  822. internal override void RawWrite (string str)
  823. {
  824. Console.Write (str);
  825. }
  826. internal override void End ()
  827. {
  828. if (IsWinPlatform)
  829. {
  830. NetWinConsole?.Cleanup ();
  831. }
  832. StopReportingMouseMoves ();
  833. if (!RunningUnitTests)
  834. {
  835. Console.ResetColor ();
  836. //Disable alternative screen buffer.
  837. Console.Out.Write (EscSeqUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll);
  838. //Set cursor key to cursor.
  839. Console.Out.Write (EscSeqUtils.CSI_ShowCursor);
  840. Console.Out.Close ();
  841. }
  842. }
  843. internal override MainLoop Init ()
  844. {
  845. PlatformID p = Environment.OSVersion.Platform;
  846. if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows)
  847. {
  848. IsWinPlatform = true;
  849. try
  850. {
  851. NetWinConsole = new NetWinVTConsole ();
  852. }
  853. catch (ApplicationException)
  854. {
  855. // Likely running as a unit test, or in a non-interactive session.
  856. }
  857. }
  858. if (IsWinPlatform)
  859. {
  860. Clipboard = new WindowsClipboard ();
  861. }
  862. else if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX))
  863. {
  864. Clipboard = new MacOSXClipboard ();
  865. }
  866. else
  867. {
  868. if (CursesDriver.Is_WSL_Platform ())
  869. {
  870. Clipboard = new WSLClipboard ();
  871. }
  872. else
  873. {
  874. Clipboard = new CursesClipboard ();
  875. }
  876. }
  877. if (!RunningUnitTests)
  878. {
  879. Console.TreatControlCAsInput = true;
  880. Cols = Console.WindowWidth;
  881. Rows = Console.WindowHeight;
  882. //Enable alternative screen buffer.
  883. Console.Out.Write (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll);
  884. //Set cursor key to application.
  885. Console.Out.Write (EscSeqUtils.CSI_HideCursor);
  886. }
  887. else
  888. {
  889. // We are being run in an environment that does not support a console
  890. // such as a unit test, or a pipe.
  891. Cols = 80;
  892. Rows = 24;
  893. }
  894. ResizeScreen ();
  895. ClearContents ();
  896. CurrentAttribute = new Attribute (Color.White, Color.Black);
  897. StartReportingMouseMoves ();
  898. _mainLoopDriver = new NetMainLoop (this);
  899. _mainLoopDriver.ProcessInput = ProcessInput;
  900. return new MainLoop (_mainLoopDriver);
  901. }
  902. private void ProcessInput (InputResult inputEvent)
  903. {
  904. switch (inputEvent.EventType)
  905. {
  906. case EventType.Key:
  907. ConsoleKeyInfo consoleKeyInfo = inputEvent.ConsoleKeyInfo;
  908. //if (consoleKeyInfo.Key == ConsoleKey.Packet) {
  909. // consoleKeyInfo = FromVKPacketToKConsoleKeyInfo (consoleKeyInfo);
  910. //}
  911. //Debug.WriteLine ($"event: {inputEvent}");
  912. KeyCode map = MapKey (consoleKeyInfo);
  913. if (map == KeyCode.Null)
  914. {
  915. break;
  916. }
  917. OnKeyDown (new Key (map));
  918. OnKeyUp (new Key (map));
  919. break;
  920. case EventType.Mouse:
  921. MouseEventArgs me = ToDriverMouse (inputEvent.MouseEvent);
  922. //Debug.WriteLine ($"NetDriver: ({me.X},{me.Y}) - {me.Flags}");
  923. OnMouseEvent (me);
  924. break;
  925. case EventType.WindowSize:
  926. _winSizeChanging = true;
  927. Top = 0;
  928. Left = 0;
  929. Cols = inputEvent.WindowSizeEvent.Size.Width;
  930. Rows = Math.Max (inputEvent.WindowSizeEvent.Size.Height, 0);
  931. ;
  932. ResizeScreen ();
  933. ClearContents ();
  934. _winSizeChanging = false;
  935. OnSizeChanged (new SizeChangedEventArgs (new (Cols, Rows)));
  936. break;
  937. case EventType.RequestResponse:
  938. break;
  939. case EventType.WindowPosition:
  940. break;
  941. default:
  942. throw new ArgumentOutOfRangeException ();
  943. }
  944. }
  945. #region Size and Position Handling
  946. private volatile bool _winSizeChanging;
  947. private void SetWindowPosition (int col, int row)
  948. {
  949. if (!RunningUnitTests)
  950. {
  951. Top = Console.WindowTop;
  952. Left = Console.WindowLeft;
  953. }
  954. else
  955. {
  956. Top = row;
  957. Left = col;
  958. }
  959. }
  960. public virtual void ResizeScreen ()
  961. {
  962. // Not supported on Unix.
  963. if (IsWinPlatform)
  964. {
  965. // Can raise an exception while is still resizing.
  966. try
  967. {
  968. #pragma warning disable CA1416
  969. if (Console.WindowHeight > 0)
  970. {
  971. Console.CursorTop = 0;
  972. Console.CursorLeft = 0;
  973. Console.WindowTop = 0;
  974. Console.WindowLeft = 0;
  975. if (Console.WindowHeight > Rows)
  976. {
  977. Console.SetWindowSize (Cols, Rows);
  978. }
  979. Console.SetBufferSize (Cols, Rows);
  980. }
  981. #pragma warning restore CA1416
  982. }
  983. // INTENT: Why are these eating the exceptions?
  984. // Comments would be good here.
  985. catch (IOException)
  986. {
  987. // CONCURRENCY: Unsynchronized access to Clip is not safe.
  988. Clip = new (Screen);
  989. }
  990. catch (ArgumentOutOfRangeException)
  991. {
  992. // CONCURRENCY: Unsynchronized access to Clip is not safe.
  993. Clip = new (Screen);
  994. }
  995. }
  996. else
  997. {
  998. Console.Out.Write (EscSeqUtils.CSI_SetTerminalWindowSize (Rows, Cols));
  999. }
  1000. // CONCURRENCY: Unsynchronized access to Clip is not safe.
  1001. Clip = new (Screen);
  1002. }
  1003. #endregion
  1004. #region Color Handling
  1005. // Cache the list of ConsoleColor values.
  1006. [UnconditionalSuppressMessage ("AOT", "IL3050:Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.", Justification = "<Pending>")]
  1007. private static readonly HashSet<int> ConsoleColorValues = new (
  1008. Enum.GetValues (typeof (ConsoleColor))
  1009. .OfType<ConsoleColor> ()
  1010. .Select (c => (int)c)
  1011. );
  1012. // Dictionary for mapping ConsoleColor values to the values used by System.Net.Console.
  1013. private static readonly Dictionary<ConsoleColor, int> colorMap = new ()
  1014. {
  1015. { ConsoleColor.Black, COLOR_BLACK },
  1016. { ConsoleColor.DarkBlue, COLOR_BLUE },
  1017. { ConsoleColor.DarkGreen, COLOR_GREEN },
  1018. { ConsoleColor.DarkCyan, COLOR_CYAN },
  1019. { ConsoleColor.DarkRed, COLOR_RED },
  1020. { ConsoleColor.DarkMagenta, COLOR_MAGENTA },
  1021. { ConsoleColor.DarkYellow, COLOR_YELLOW },
  1022. { ConsoleColor.Gray, COLOR_WHITE },
  1023. { ConsoleColor.DarkGray, COLOR_BRIGHT_BLACK },
  1024. { ConsoleColor.Blue, COLOR_BRIGHT_BLUE },
  1025. { ConsoleColor.Green, COLOR_BRIGHT_GREEN },
  1026. { ConsoleColor.Cyan, COLOR_BRIGHT_CYAN },
  1027. { ConsoleColor.Red, COLOR_BRIGHT_RED },
  1028. { ConsoleColor.Magenta, COLOR_BRIGHT_MAGENTA },
  1029. { ConsoleColor.Yellow, COLOR_BRIGHT_YELLOW },
  1030. { ConsoleColor.White, COLOR_BRIGHT_WHITE }
  1031. };
  1032. // Map a ConsoleColor to a platform dependent value.
  1033. private int MapColors (ConsoleColor color, bool isForeground = true)
  1034. {
  1035. return colorMap.TryGetValue (color, out int colorValue) ? colorValue + (isForeground ? 0 : 10) : 0;
  1036. }
  1037. ///// <remarks>
  1038. ///// In the NetDriver, colors are encoded as an int.
  1039. ///// However, the foreground color is stored in the most significant 16 bits,
  1040. ///// and the background color is stored in the least significant 16 bits.
  1041. ///// </remarks>
  1042. //public override Attribute MakeColor (Color foreground, Color background)
  1043. //{
  1044. // // Encode the colors into the int value.
  1045. // return new Attribute (
  1046. // platformColor: ((((int)foreground.ColorName) & 0xffff) << 16) | (((int)background.ColorName) & 0xffff),
  1047. // foreground: foreground,
  1048. // background: background
  1049. // );
  1050. //}
  1051. #endregion
  1052. #region Cursor Handling
  1053. private bool SetCursorPosition (int col, int row)
  1054. {
  1055. if (IsWinPlatform)
  1056. {
  1057. // Could happens that the windows is still resizing and the col is bigger than Console.WindowWidth.
  1058. try
  1059. {
  1060. Console.SetCursorPosition (col, row);
  1061. return true;
  1062. }
  1063. catch (Exception)
  1064. {
  1065. return false;
  1066. }
  1067. }
  1068. // + 1 is needed because non-Windows is based on 1 instead of 0 and
  1069. // Console.CursorTop/CursorLeft isn't reliable.
  1070. Console.Out.Write (EscSeqUtils.CSI_SetCursorPosition (row + 1, col + 1));
  1071. return true;
  1072. }
  1073. private CursorVisibility? _cachedCursorVisibility;
  1074. public override void UpdateCursor ()
  1075. {
  1076. EnsureCursorVisibility ();
  1077. if (Col >= 0 && Col < Cols && Row >= 0 && Row <= Rows)
  1078. {
  1079. SetCursorPosition (Col, Row);
  1080. SetWindowPosition (0, Row);
  1081. }
  1082. }
  1083. public override bool GetCursorVisibility (out CursorVisibility visibility)
  1084. {
  1085. visibility = _cachedCursorVisibility ?? CursorVisibility.Default;
  1086. return visibility == CursorVisibility.Default;
  1087. }
  1088. public override bool SetCursorVisibility (CursorVisibility visibility)
  1089. {
  1090. _cachedCursorVisibility = visibility;
  1091. Console.Out.Write (visibility == CursorVisibility.Default ? EscSeqUtils.CSI_ShowCursor : EscSeqUtils.CSI_HideCursor);
  1092. return visibility == CursorVisibility.Default;
  1093. }
  1094. public override bool EnsureCursorVisibility ()
  1095. {
  1096. if (!(Col >= 0 && Row >= 0 && Col < Cols && Row < Rows))
  1097. {
  1098. GetCursorVisibility (out CursorVisibility cursorVisibility);
  1099. _cachedCursorVisibility = cursorVisibility;
  1100. SetCursorVisibility (CursorVisibility.Invisible);
  1101. return false;
  1102. }
  1103. SetCursorVisibility (_cachedCursorVisibility ?? CursorVisibility.Default);
  1104. return _cachedCursorVisibility == CursorVisibility.Default;
  1105. }
  1106. #endregion
  1107. #region Mouse Handling
  1108. public void StartReportingMouseMoves ()
  1109. {
  1110. if (!RunningUnitTests)
  1111. {
  1112. Console.Out.Write (EscSeqUtils.CSI_EnableMouseEvents);
  1113. }
  1114. }
  1115. public void StopReportingMouseMoves ()
  1116. {
  1117. if (!RunningUnitTests)
  1118. {
  1119. Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents);
  1120. }
  1121. }
  1122. private MouseEventArgs ToDriverMouse (NetEvents.MouseEvent me)
  1123. {
  1124. //System.Diagnostics.Debug.WriteLine ($"X: {me.Position.X}; Y: {me.Position.Y}; ButtonState: {me.ButtonState}");
  1125. MouseFlags mouseFlag = 0;
  1126. if ((me.ButtonState & MouseButtonState.Button1Pressed) != 0)
  1127. {
  1128. mouseFlag |= MouseFlags.Button1Pressed;
  1129. }
  1130. if ((me.ButtonState & MouseButtonState.Button1Released) != 0)
  1131. {
  1132. mouseFlag |= MouseFlags.Button1Released;
  1133. }
  1134. if ((me.ButtonState & MouseButtonState.Button1Clicked) != 0)
  1135. {
  1136. mouseFlag |= MouseFlags.Button1Clicked;
  1137. }
  1138. if ((me.ButtonState & MouseButtonState.Button1DoubleClicked) != 0)
  1139. {
  1140. mouseFlag |= MouseFlags.Button1DoubleClicked;
  1141. }
  1142. if ((me.ButtonState & MouseButtonState.Button1TripleClicked) != 0)
  1143. {
  1144. mouseFlag |= MouseFlags.Button1TripleClicked;
  1145. }
  1146. if ((me.ButtonState & MouseButtonState.Button2Pressed) != 0)
  1147. {
  1148. mouseFlag |= MouseFlags.Button2Pressed;
  1149. }
  1150. if ((me.ButtonState & MouseButtonState.Button2Released) != 0)
  1151. {
  1152. mouseFlag |= MouseFlags.Button2Released;
  1153. }
  1154. if ((me.ButtonState & MouseButtonState.Button2Clicked) != 0)
  1155. {
  1156. mouseFlag |= MouseFlags.Button2Clicked;
  1157. }
  1158. if ((me.ButtonState & MouseButtonState.Button2DoubleClicked) != 0)
  1159. {
  1160. mouseFlag |= MouseFlags.Button2DoubleClicked;
  1161. }
  1162. if ((me.ButtonState & MouseButtonState.Button2TripleClicked) != 0)
  1163. {
  1164. mouseFlag |= MouseFlags.Button2TripleClicked;
  1165. }
  1166. if ((me.ButtonState & MouseButtonState.Button3Pressed) != 0)
  1167. {
  1168. mouseFlag |= MouseFlags.Button3Pressed;
  1169. }
  1170. if ((me.ButtonState & MouseButtonState.Button3Released) != 0)
  1171. {
  1172. mouseFlag |= MouseFlags.Button3Released;
  1173. }
  1174. if ((me.ButtonState & MouseButtonState.Button3Clicked) != 0)
  1175. {
  1176. mouseFlag |= MouseFlags.Button3Clicked;
  1177. }
  1178. if ((me.ButtonState & MouseButtonState.Button3DoubleClicked) != 0)
  1179. {
  1180. mouseFlag |= MouseFlags.Button3DoubleClicked;
  1181. }
  1182. if ((me.ButtonState & MouseButtonState.Button3TripleClicked) != 0)
  1183. {
  1184. mouseFlag |= MouseFlags.Button3TripleClicked;
  1185. }
  1186. if ((me.ButtonState & MouseButtonState.ButtonWheeledUp) != 0)
  1187. {
  1188. mouseFlag |= MouseFlags.WheeledUp;
  1189. }
  1190. if ((me.ButtonState & MouseButtonState.ButtonWheeledDown) != 0)
  1191. {
  1192. mouseFlag |= MouseFlags.WheeledDown;
  1193. }
  1194. if ((me.ButtonState & MouseButtonState.ButtonWheeledLeft) != 0)
  1195. {
  1196. mouseFlag |= MouseFlags.WheeledLeft;
  1197. }
  1198. if ((me.ButtonState & MouseButtonState.ButtonWheeledRight) != 0)
  1199. {
  1200. mouseFlag |= MouseFlags.WheeledRight;
  1201. }
  1202. if ((me.ButtonState & MouseButtonState.Button4Pressed) != 0)
  1203. {
  1204. mouseFlag |= MouseFlags.Button4Pressed;
  1205. }
  1206. if ((me.ButtonState & MouseButtonState.Button4Released) != 0)
  1207. {
  1208. mouseFlag |= MouseFlags.Button4Released;
  1209. }
  1210. if ((me.ButtonState & MouseButtonState.Button4Clicked) != 0)
  1211. {
  1212. mouseFlag |= MouseFlags.Button4Clicked;
  1213. }
  1214. if ((me.ButtonState & MouseButtonState.Button4DoubleClicked) != 0)
  1215. {
  1216. mouseFlag |= MouseFlags.Button4DoubleClicked;
  1217. }
  1218. if ((me.ButtonState & MouseButtonState.Button4TripleClicked) != 0)
  1219. {
  1220. mouseFlag |= MouseFlags.Button4TripleClicked;
  1221. }
  1222. if ((me.ButtonState & MouseButtonState.ReportMousePosition) != 0)
  1223. {
  1224. mouseFlag |= MouseFlags.ReportMousePosition;
  1225. }
  1226. if ((me.ButtonState & MouseButtonState.ButtonShift) != 0)
  1227. {
  1228. mouseFlag |= MouseFlags.ButtonShift;
  1229. }
  1230. if ((me.ButtonState & MouseButtonState.ButtonCtrl) != 0)
  1231. {
  1232. mouseFlag |= MouseFlags.ButtonCtrl;
  1233. }
  1234. if ((me.ButtonState & MouseButtonState.ButtonAlt) != 0)
  1235. {
  1236. mouseFlag |= MouseFlags.ButtonAlt;
  1237. }
  1238. return new MouseEventArgs { Position = me.Position, Flags = mouseFlag };
  1239. }
  1240. #endregion Mouse Handling
  1241. #region Keyboard Handling
  1242. private ConsoleKeyInfo FromVKPacketToKConsoleKeyInfo (ConsoleKeyInfo consoleKeyInfo)
  1243. {
  1244. if (consoleKeyInfo.Key != ConsoleKey.Packet)
  1245. {
  1246. return consoleKeyInfo;
  1247. }
  1248. ConsoleModifiers mod = consoleKeyInfo.Modifiers;
  1249. bool shift = (mod & ConsoleModifiers.Shift) != 0;
  1250. bool alt = (mod & ConsoleModifiers.Alt) != 0;
  1251. bool control = (mod & ConsoleModifiers.Control) != 0;
  1252. ConsoleKeyInfo cKeyInfo = DecodeVKPacketToKConsoleKeyInfo (consoleKeyInfo);
  1253. return new ConsoleKeyInfo (cKeyInfo.KeyChar, cKeyInfo.Key, shift, alt, control);
  1254. }
  1255. private KeyCode MapKey (ConsoleKeyInfo keyInfo)
  1256. {
  1257. switch (keyInfo.Key)
  1258. {
  1259. case ConsoleKey.OemPeriod:
  1260. case ConsoleKey.OemComma:
  1261. case ConsoleKey.OemPlus:
  1262. case ConsoleKey.OemMinus:
  1263. case ConsoleKey.Packet:
  1264. case ConsoleKey.Oem1:
  1265. case ConsoleKey.Oem2:
  1266. case ConsoleKey.Oem3:
  1267. case ConsoleKey.Oem4:
  1268. case ConsoleKey.Oem5:
  1269. case ConsoleKey.Oem6:
  1270. case ConsoleKey.Oem7:
  1271. case ConsoleKey.Oem8:
  1272. case ConsoleKey.Oem102:
  1273. if (keyInfo.KeyChar == 0)
  1274. {
  1275. // If the keyChar is 0, keyInfo.Key value is not a printable character.
  1276. return KeyCode.Null; // MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode)keyInfo.Key);
  1277. }
  1278. if (keyInfo.Modifiers != ConsoleModifiers.Shift)
  1279. {
  1280. // If Shift wasn't down we don't need to do anything but return the keyInfo.KeyChar
  1281. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar);
  1282. }
  1283. // Strip off Shift - We got here because they KeyChar from Windows is the shifted char (e.g. "Ç")
  1284. // and passing on Shift would be redundant.
  1285. return MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.KeyChar);
  1286. }
  1287. // Handle control keys whose VK codes match the related ASCII value (those below ASCII 33) like ESC
  1288. if (keyInfo.Key != ConsoleKey.None && Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key))
  1289. {
  1290. if (keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control) && keyInfo.Key == ConsoleKey.I)
  1291. {
  1292. return KeyCode.Tab;
  1293. }
  1294. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)((uint)keyInfo.Key));
  1295. }
  1296. // Handle control keys (e.g. CursorUp)
  1297. if (keyInfo.Key != ConsoleKey.None
  1298. && Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint))
  1299. {
  1300. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)((uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint));
  1301. }
  1302. if (((ConsoleKey)keyInfo.KeyChar) is >= ConsoleKey.A and <= ConsoleKey.Z)
  1303. {
  1304. // Shifted
  1305. keyInfo = new ConsoleKeyInfo (
  1306. keyInfo.KeyChar,
  1307. (ConsoleKey)keyInfo.KeyChar,
  1308. true,
  1309. keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt),
  1310. keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control));
  1311. }
  1312. if ((ConsoleKey)keyInfo.KeyChar - 32 is >= ConsoleKey.A and <= ConsoleKey.Z)
  1313. {
  1314. // Unshifted
  1315. keyInfo = new ConsoleKeyInfo (
  1316. keyInfo.KeyChar,
  1317. (ConsoleKey)(keyInfo.KeyChar - 32),
  1318. false,
  1319. keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt),
  1320. keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control));
  1321. }
  1322. if (keyInfo.Key is >= ConsoleKey.A and <= ConsoleKey.Z )
  1323. {
  1324. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt)
  1325. || keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control))
  1326. {
  1327. // NetDriver doesn't support Shift-Ctrl/Shift-Alt combos
  1328. return MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.Key);
  1329. }
  1330. if (keyInfo.Modifiers == ConsoleModifiers.Shift)
  1331. {
  1332. // If ShiftMask is on add the ShiftMask
  1333. if (char.IsUpper (keyInfo.KeyChar))
  1334. {
  1335. return (KeyCode)keyInfo.Key | KeyCode.ShiftMask;
  1336. }
  1337. }
  1338. return (KeyCode)keyInfo.Key;
  1339. }
  1340. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)((uint)keyInfo.KeyChar));
  1341. }
  1342. #endregion Keyboard Handling
  1343. }
  1344. /// <summary>
  1345. /// Mainloop intended to be used with the .NET System.Console API, and can be used on Windows and Unix, it is
  1346. /// cross-platform but lacks things like file descriptor monitoring.
  1347. /// </summary>
  1348. /// <remarks>This implementation is used for NetDriver.</remarks>
  1349. internal class NetMainLoop : IMainLoopDriver
  1350. {
  1351. internal NetEvents _netEvents;
  1352. /// <summary>Invoked when a Key is pressed.</summary>
  1353. internal Action<InputResult> ProcessInput;
  1354. private readonly ManualResetEventSlim _eventReady = new (false);
  1355. private readonly CancellationTokenSource _inputHandlerTokenSource = new ();
  1356. // Wrap ConcurrentQueue in a BlockingCollection to enable blocking with timeout
  1357. private readonly BlockingCollection<InputResult> _resultQueue = new (new ConcurrentQueue<InputResult> ());
  1358. private readonly ManualResetEventSlim _waitForProbe = new (false);
  1359. private readonly CancellationTokenSource _eventReadyTokenSource = new ();
  1360. private MainLoop _mainLoop;
  1361. /// <summary>Initializes the class with the console driver.</summary>
  1362. /// <remarks>Passing a consoleDriver is provided to capture windows resizing.</remarks>
  1363. /// <param name="consoleDriver">The console driver used by this Net main loop.</param>
  1364. /// <exception cref="ArgumentNullException"></exception>
  1365. public NetMainLoop (ConsoleDriver consoleDriver = null)
  1366. {
  1367. if (consoleDriver is null)
  1368. {
  1369. throw new ArgumentNullException (nameof (consoleDriver));
  1370. }
  1371. _netEvents = new NetEvents (consoleDriver);
  1372. }
  1373. void IMainLoopDriver.Setup (MainLoop mainLoop)
  1374. {
  1375. _mainLoop = mainLoop;
  1376. Task.Run (NetInputHandler, _inputHandlerTokenSource.Token);
  1377. }
  1378. void IMainLoopDriver.Wakeup ()
  1379. {
  1380. _eventReady.Set ();
  1381. }
  1382. bool IMainLoopDriver.EventsPending ()
  1383. {
  1384. _waitForProbe.Set ();
  1385. if (_mainLoop.CheckTimersAndIdleHandlers (out int waitTimeout))
  1386. {
  1387. // HACK: CheckTimers returns true even if the timer is not due i.e. it could be
  1388. // timer is due to run in 30s interval but even so it return true so we hammer main loop
  1389. // this avoids hammer CPU but better fix would be to only return true from CheckTimersAndIdleHandlers
  1390. // if the timeout is actually due
  1391. Task.Delay (50).Wait (_eventReadyTokenSource.Token);
  1392. return true;
  1393. }
  1394. // Required otherwise CPU gets high
  1395. _eventReady.Wait (waitTimeout, _eventReadyTokenSource.Token);
  1396. _eventReady.Reset ();
  1397. _eventReadyTokenSource.Token.ThrowIfCancellationRequested ();
  1398. return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _);
  1399. }
  1400. void IMainLoopDriver.Iteration ()
  1401. {
  1402. while (_resultQueue.TryTake (out InputResult v))
  1403. {
  1404. ProcessInput?.Invoke (v);
  1405. }
  1406. }
  1407. void IMainLoopDriver.TearDown ()
  1408. {
  1409. _inputHandlerTokenSource?.Cancel ();
  1410. _inputHandlerTokenSource?.Dispose ();
  1411. _eventReadyTokenSource?.Cancel ();
  1412. _eventReadyTokenSource?.Dispose ();
  1413. _eventReady?.Dispose ();
  1414. _waitForProbe?.Dispose ();
  1415. _netEvents?.Dispose ();
  1416. _netEvents = null;
  1417. _mainLoop = null;
  1418. }
  1419. private void NetInputHandler ()
  1420. {
  1421. while (_mainLoop is { })
  1422. {
  1423. try
  1424. {
  1425. if (!_inputHandlerTokenSource.IsCancellationRequested)
  1426. {
  1427. _waitForProbe.Wait (_inputHandlerTokenSource.Token);
  1428. }
  1429. }
  1430. catch (OperationCanceledException)
  1431. {
  1432. return;
  1433. }
  1434. finally
  1435. {
  1436. if (_waitForProbe.IsSet)
  1437. {
  1438. _waitForProbe.Reset ();
  1439. }
  1440. }
  1441. if (_inputHandlerTokenSource.IsCancellationRequested)
  1442. {
  1443. return;
  1444. }
  1445. _inputHandlerTokenSource.Token.ThrowIfCancellationRequested ();
  1446. var input = _netEvents.DequeueInput ();
  1447. if (input.HasValue)
  1448. {
  1449. _resultQueue.Add (input.Value);
  1450. _eventReady.Set ();
  1451. }
  1452. }
  1453. }
  1454. }