NetDriver.cs 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748
  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 Refresh ()
  636. {
  637. UpdateScreen ();
  638. UpdateCursor ();
  639. }
  640. public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control)
  641. {
  642. var input = new InputResult
  643. {
  644. EventType = EventType.Key, ConsoleKeyInfo = new ConsoleKeyInfo (keyChar, key, shift, alt, control)
  645. };
  646. try
  647. {
  648. ProcessInput (input);
  649. }
  650. catch (OverflowException)
  651. { }
  652. }
  653. public override void Suspend ()
  654. {
  655. if (Environment.OSVersion.Platform != PlatformID.Unix)
  656. {
  657. return;
  658. }
  659. StopReportingMouseMoves ();
  660. if (!RunningUnitTests)
  661. {
  662. Console.ResetColor ();
  663. Console.Clear ();
  664. //Disable alternative screen buffer.
  665. Console.Out.Write (EscSeqUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll);
  666. //Set cursor key to cursor.
  667. Console.Out.Write (EscSeqUtils.CSI_ShowCursor);
  668. Platform.Suspend ();
  669. //Enable alternative screen buffer.
  670. Console.Out.Write (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll);
  671. SetContentsAsDirty ();
  672. Refresh ();
  673. }
  674. StartReportingMouseMoves ();
  675. }
  676. public override void UpdateScreen ()
  677. {
  678. if (RunningUnitTests
  679. || _winSizeChanging
  680. || Console.WindowHeight < 1
  681. || Contents.Length != Rows * Cols
  682. || Rows != Console.WindowHeight)
  683. {
  684. return;
  685. }
  686. var top = 0;
  687. var left = 0;
  688. int rows = Rows;
  689. int cols = Cols;
  690. var output = new StringBuilder ();
  691. Attribute? redrawAttr = null;
  692. int lastCol = -1;
  693. CursorVisibility? savedVisibility = _cachedCursorVisibility;
  694. SetCursorVisibility (CursorVisibility.Invisible);
  695. for (int row = top; row < rows; row++)
  696. {
  697. if (Console.WindowHeight < 1)
  698. {
  699. return;
  700. }
  701. if (!_dirtyLines [row])
  702. {
  703. continue;
  704. }
  705. if (!SetCursorPosition (0, row))
  706. {
  707. return;
  708. }
  709. _dirtyLines [row] = false;
  710. output.Clear ();
  711. for (int col = left; col < cols; col++)
  712. {
  713. lastCol = -1;
  714. var outputWidth = 0;
  715. for (; col < cols; col++)
  716. {
  717. if (!Contents [row, col].IsDirty)
  718. {
  719. if (output.Length > 0)
  720. {
  721. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  722. }
  723. else if (lastCol == -1)
  724. {
  725. lastCol = col;
  726. }
  727. if (lastCol + 1 < cols)
  728. {
  729. lastCol++;
  730. }
  731. continue;
  732. }
  733. if (lastCol == -1)
  734. {
  735. lastCol = col;
  736. }
  737. Attribute attr = Contents [row, col].Attribute.Value;
  738. // Performance: Only send the escape sequence if the attribute has changed.
  739. if (attr != redrawAttr)
  740. {
  741. redrawAttr = attr;
  742. if (Force16Colors)
  743. {
  744. output.Append (
  745. EscSeqUtils.CSI_SetGraphicsRendition (
  746. MapColors (
  747. (ConsoleColor)attr.Background.GetClosestNamedColor16 (),
  748. false
  749. ),
  750. MapColors ((ConsoleColor)attr.Foreground.GetClosestNamedColor16 ())
  751. )
  752. );
  753. }
  754. else
  755. {
  756. output.Append (
  757. EscSeqUtils.CSI_SetForegroundColorRGB (
  758. attr.Foreground.R,
  759. attr.Foreground.G,
  760. attr.Foreground.B
  761. )
  762. );
  763. output.Append (
  764. EscSeqUtils.CSI_SetBackgroundColorRGB (
  765. attr.Background.R,
  766. attr.Background.G,
  767. attr.Background.B
  768. )
  769. );
  770. }
  771. }
  772. outputWidth++;
  773. Rune rune = Contents [row, col].Rune;
  774. output.Append (rune);
  775. if (Contents [row, col].CombiningMarks.Count > 0)
  776. {
  777. // AtlasEngine does not support NON-NORMALIZED combining marks in a way
  778. // compatible with the driver architecture. Any CMs (except in the first col)
  779. // are correctly combined with the base char, but are ALSO treated as 1 column
  780. // width codepoints E.g. `echo "[e`u{0301}`u{0301}]"` will output `[é ]`.
  781. //
  782. // For now, we just ignore the list of CMs.
  783. //foreach (var combMark in Contents [row, col].CombiningMarks) {
  784. // output.Append (combMark);
  785. //}
  786. // WriteToConsole (output, ref lastCol, row, ref outputWidth);
  787. }
  788. else if (rune.IsSurrogatePair () && rune.GetColumns () < 2)
  789. {
  790. WriteToConsole (output, ref lastCol, row, ref outputWidth);
  791. SetCursorPosition (col - 1, row);
  792. }
  793. Contents [row, col].IsDirty = false;
  794. }
  795. }
  796. if (output.Length > 0)
  797. {
  798. SetCursorPosition (lastCol, row);
  799. Console.Write (output);
  800. }
  801. foreach (var s in Application.Sixel)
  802. {
  803. if (!string.IsNullOrWhiteSpace (s.SixelData))
  804. {
  805. SetCursorPosition (s.ScreenPosition.X, s.ScreenPosition.Y);
  806. Console.Write (s.SixelData);
  807. }
  808. }
  809. }
  810. SetCursorPosition (0, 0);
  811. _cachedCursorVisibility = savedVisibility;
  812. void WriteToConsole (StringBuilder output, ref int lastCol, int row, ref int outputWidth)
  813. {
  814. SetCursorPosition (lastCol, row);
  815. Console.Write (output);
  816. output.Clear ();
  817. lastCol += outputWidth;
  818. outputWidth = 0;
  819. }
  820. }
  821. /// <inheritdoc />
  822. protected override IAnsiResponseParser GetParser () => _mainLoopDriver._netEvents.Parser;
  823. /// <inheritdoc />
  824. internal override void RawWrite (string str)
  825. {
  826. Console.Write (str);
  827. }
  828. internal override void End ()
  829. {
  830. if (IsWinPlatform)
  831. {
  832. NetWinConsole?.Cleanup ();
  833. }
  834. StopReportingMouseMoves ();
  835. if (!RunningUnitTests)
  836. {
  837. Console.ResetColor ();
  838. //Disable alternative screen buffer.
  839. Console.Out.Write (EscSeqUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll);
  840. //Set cursor key to cursor.
  841. Console.Out.Write (EscSeqUtils.CSI_ShowCursor);
  842. Console.Out.Close ();
  843. }
  844. }
  845. internal override MainLoop Init ()
  846. {
  847. PlatformID p = Environment.OSVersion.Platform;
  848. if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows)
  849. {
  850. IsWinPlatform = true;
  851. try
  852. {
  853. NetWinConsole = new NetWinVTConsole ();
  854. }
  855. catch (ApplicationException)
  856. {
  857. // Likely running as a unit test, or in a non-interactive session.
  858. }
  859. }
  860. if (IsWinPlatform)
  861. {
  862. Clipboard = new WindowsClipboard ();
  863. }
  864. else if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX))
  865. {
  866. Clipboard = new MacOSXClipboard ();
  867. }
  868. else
  869. {
  870. if (CursesDriver.Is_WSL_Platform ())
  871. {
  872. Clipboard = new WSLClipboard ();
  873. }
  874. else
  875. {
  876. Clipboard = new CursesClipboard ();
  877. }
  878. }
  879. if (!RunningUnitTests)
  880. {
  881. Console.TreatControlCAsInput = true;
  882. Cols = Console.WindowWidth;
  883. Rows = Console.WindowHeight;
  884. //Enable alternative screen buffer.
  885. Console.Out.Write (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll);
  886. //Set cursor key to application.
  887. Console.Out.Write (EscSeqUtils.CSI_HideCursor);
  888. }
  889. else
  890. {
  891. // We are being run in an environment that does not support a console
  892. // such as a unit test, or a pipe.
  893. Cols = 80;
  894. Rows = 24;
  895. }
  896. ResizeScreen ();
  897. ClearContents ();
  898. CurrentAttribute = new Attribute (Color.White, Color.Black);
  899. StartReportingMouseMoves ();
  900. _mainLoopDriver = new NetMainLoop (this);
  901. _mainLoopDriver.ProcessInput = ProcessInput;
  902. return new MainLoop (_mainLoopDriver);
  903. }
  904. private void ProcessInput (InputResult inputEvent)
  905. {
  906. switch (inputEvent.EventType)
  907. {
  908. case EventType.Key:
  909. ConsoleKeyInfo consoleKeyInfo = inputEvent.ConsoleKeyInfo;
  910. //if (consoleKeyInfo.Key == ConsoleKey.Packet) {
  911. // consoleKeyInfo = FromVKPacketToKConsoleKeyInfo (consoleKeyInfo);
  912. //}
  913. //Debug.WriteLine ($"event: {inputEvent}");
  914. KeyCode map = MapKey (consoleKeyInfo);
  915. if (map == KeyCode.Null)
  916. {
  917. break;
  918. }
  919. OnKeyDown (new Key (map));
  920. OnKeyUp (new Key (map));
  921. break;
  922. case EventType.Mouse:
  923. MouseEventArgs me = ToDriverMouse (inputEvent.MouseEvent);
  924. //Debug.WriteLine ($"NetDriver: ({me.X},{me.Y}) - {me.Flags}");
  925. OnMouseEvent (me);
  926. break;
  927. case EventType.WindowSize:
  928. _winSizeChanging = true;
  929. Top = 0;
  930. Left = 0;
  931. Cols = inputEvent.WindowSizeEvent.Size.Width;
  932. Rows = Math.Max (inputEvent.WindowSizeEvent.Size.Height, 0);
  933. ;
  934. ResizeScreen ();
  935. ClearContents ();
  936. _winSizeChanging = false;
  937. OnSizeChanged (new SizeChangedEventArgs (new (Cols, Rows)));
  938. break;
  939. case EventType.RequestResponse:
  940. break;
  941. case EventType.WindowPosition:
  942. break;
  943. default:
  944. throw new ArgumentOutOfRangeException ();
  945. }
  946. }
  947. #region Size and Position Handling
  948. private volatile bool _winSizeChanging;
  949. private void SetWindowPosition (int col, int row)
  950. {
  951. if (!RunningUnitTests)
  952. {
  953. Top = Console.WindowTop;
  954. Left = Console.WindowLeft;
  955. }
  956. else
  957. {
  958. Top = row;
  959. Left = col;
  960. }
  961. }
  962. public virtual void ResizeScreen ()
  963. {
  964. // Not supported on Unix.
  965. if (IsWinPlatform)
  966. {
  967. // Can raise an exception while is still resizing.
  968. try
  969. {
  970. #pragma warning disable CA1416
  971. if (Console.WindowHeight > 0)
  972. {
  973. Console.CursorTop = 0;
  974. Console.CursorLeft = 0;
  975. Console.WindowTop = 0;
  976. Console.WindowLeft = 0;
  977. if (Console.WindowHeight > Rows)
  978. {
  979. Console.SetWindowSize (Cols, Rows);
  980. }
  981. Console.SetBufferSize (Cols, Rows);
  982. }
  983. #pragma warning restore CA1416
  984. }
  985. // INTENT: Why are these eating the exceptions?
  986. // Comments would be good here.
  987. catch (IOException)
  988. {
  989. // CONCURRENCY: Unsynchronized access to Clip is not safe.
  990. Clip = new (0, 0, Cols, Rows);
  991. }
  992. catch (ArgumentOutOfRangeException)
  993. {
  994. // CONCURRENCY: Unsynchronized access to Clip is not safe.
  995. Clip = new (0, 0, Cols, Rows);
  996. }
  997. }
  998. else
  999. {
  1000. Console.Out.Write (EscSeqUtils.CSI_SetTerminalWindowSize (Rows, Cols));
  1001. }
  1002. // CONCURRENCY: Unsynchronized access to Clip is not safe.
  1003. Clip = new (0, 0, Cols, Rows);
  1004. }
  1005. #endregion
  1006. #region Color Handling
  1007. // Cache the list of ConsoleColor values.
  1008. [UnconditionalSuppressMessage ("AOT", "IL3050:Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.", Justification = "<Pending>")]
  1009. private static readonly HashSet<int> ConsoleColorValues = new (
  1010. Enum.GetValues (typeof (ConsoleColor))
  1011. .OfType<ConsoleColor> ()
  1012. .Select (c => (int)c)
  1013. );
  1014. // Dictionary for mapping ConsoleColor values to the values used by System.Net.Console.
  1015. private static readonly Dictionary<ConsoleColor, int> colorMap = new ()
  1016. {
  1017. { ConsoleColor.Black, COLOR_BLACK },
  1018. { ConsoleColor.DarkBlue, COLOR_BLUE },
  1019. { ConsoleColor.DarkGreen, COLOR_GREEN },
  1020. { ConsoleColor.DarkCyan, COLOR_CYAN },
  1021. { ConsoleColor.DarkRed, COLOR_RED },
  1022. { ConsoleColor.DarkMagenta, COLOR_MAGENTA },
  1023. { ConsoleColor.DarkYellow, COLOR_YELLOW },
  1024. { ConsoleColor.Gray, COLOR_WHITE },
  1025. { ConsoleColor.DarkGray, COLOR_BRIGHT_BLACK },
  1026. { ConsoleColor.Blue, COLOR_BRIGHT_BLUE },
  1027. { ConsoleColor.Green, COLOR_BRIGHT_GREEN },
  1028. { ConsoleColor.Cyan, COLOR_BRIGHT_CYAN },
  1029. { ConsoleColor.Red, COLOR_BRIGHT_RED },
  1030. { ConsoleColor.Magenta, COLOR_BRIGHT_MAGENTA },
  1031. { ConsoleColor.Yellow, COLOR_BRIGHT_YELLOW },
  1032. { ConsoleColor.White, COLOR_BRIGHT_WHITE }
  1033. };
  1034. // Map a ConsoleColor to a platform dependent value.
  1035. private int MapColors (ConsoleColor color, bool isForeground = true)
  1036. {
  1037. return colorMap.TryGetValue (color, out int colorValue) ? colorValue + (isForeground ? 0 : 10) : 0;
  1038. }
  1039. ///// <remarks>
  1040. ///// In the NetDriver, colors are encoded as an int.
  1041. ///// However, the foreground color is stored in the most significant 16 bits,
  1042. ///// and the background color is stored in the least significant 16 bits.
  1043. ///// </remarks>
  1044. //public override Attribute MakeColor (Color foreground, Color background)
  1045. //{
  1046. // // Encode the colors into the int value.
  1047. // return new Attribute (
  1048. // platformColor: ((((int)foreground.ColorName) & 0xffff) << 16) | (((int)background.ColorName) & 0xffff),
  1049. // foreground: foreground,
  1050. // background: background
  1051. // );
  1052. //}
  1053. #endregion
  1054. #region Cursor Handling
  1055. private bool SetCursorPosition (int col, int row)
  1056. {
  1057. if (IsWinPlatform)
  1058. {
  1059. // Could happens that the windows is still resizing and the col is bigger than Console.WindowWidth.
  1060. try
  1061. {
  1062. Console.SetCursorPosition (col, row);
  1063. return true;
  1064. }
  1065. catch (Exception)
  1066. {
  1067. return false;
  1068. }
  1069. }
  1070. // + 1 is needed because non-Windows is based on 1 instead of 0 and
  1071. // Console.CursorTop/CursorLeft isn't reliable.
  1072. Console.Out.Write (EscSeqUtils.CSI_SetCursorPosition (row + 1, col + 1));
  1073. return true;
  1074. }
  1075. private CursorVisibility? _cachedCursorVisibility;
  1076. public override void UpdateCursor ()
  1077. {
  1078. EnsureCursorVisibility ();
  1079. if (Col >= 0 && Col < Cols && Row >= 0 && Row <= Rows)
  1080. {
  1081. SetCursorPosition (Col, Row);
  1082. SetWindowPosition (0, Row);
  1083. }
  1084. }
  1085. public override bool GetCursorVisibility (out CursorVisibility visibility)
  1086. {
  1087. visibility = _cachedCursorVisibility ?? CursorVisibility.Default;
  1088. return visibility == CursorVisibility.Default;
  1089. }
  1090. public override bool SetCursorVisibility (CursorVisibility visibility)
  1091. {
  1092. _cachedCursorVisibility = visibility;
  1093. Console.Out.Write (visibility == CursorVisibility.Default ? EscSeqUtils.CSI_ShowCursor : EscSeqUtils.CSI_HideCursor);
  1094. return visibility == CursorVisibility.Default;
  1095. }
  1096. public override bool EnsureCursorVisibility ()
  1097. {
  1098. if (!(Col >= 0 && Row >= 0 && Col < Cols && Row < Rows))
  1099. {
  1100. GetCursorVisibility (out CursorVisibility cursorVisibility);
  1101. _cachedCursorVisibility = cursorVisibility;
  1102. SetCursorVisibility (CursorVisibility.Invisible);
  1103. return false;
  1104. }
  1105. SetCursorVisibility (_cachedCursorVisibility ?? CursorVisibility.Default);
  1106. return _cachedCursorVisibility == CursorVisibility.Default;
  1107. }
  1108. #endregion
  1109. #region Mouse Handling
  1110. public void StartReportingMouseMoves ()
  1111. {
  1112. if (!RunningUnitTests)
  1113. {
  1114. Console.Out.Write (EscSeqUtils.CSI_EnableMouseEvents);
  1115. }
  1116. }
  1117. public void StopReportingMouseMoves ()
  1118. {
  1119. if (!RunningUnitTests)
  1120. {
  1121. Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents);
  1122. }
  1123. }
  1124. private MouseEventArgs ToDriverMouse (NetEvents.MouseEvent me)
  1125. {
  1126. //System.Diagnostics.Debug.WriteLine ($"X: {me.Position.X}; Y: {me.Position.Y}; ButtonState: {me.ButtonState}");
  1127. MouseFlags mouseFlag = 0;
  1128. if ((me.ButtonState & MouseButtonState.Button1Pressed) != 0)
  1129. {
  1130. mouseFlag |= MouseFlags.Button1Pressed;
  1131. }
  1132. if ((me.ButtonState & MouseButtonState.Button1Released) != 0)
  1133. {
  1134. mouseFlag |= MouseFlags.Button1Released;
  1135. }
  1136. if ((me.ButtonState & MouseButtonState.Button1Clicked) != 0)
  1137. {
  1138. mouseFlag |= MouseFlags.Button1Clicked;
  1139. }
  1140. if ((me.ButtonState & MouseButtonState.Button1DoubleClicked) != 0)
  1141. {
  1142. mouseFlag |= MouseFlags.Button1DoubleClicked;
  1143. }
  1144. if ((me.ButtonState & MouseButtonState.Button1TripleClicked) != 0)
  1145. {
  1146. mouseFlag |= MouseFlags.Button1TripleClicked;
  1147. }
  1148. if ((me.ButtonState & MouseButtonState.Button2Pressed) != 0)
  1149. {
  1150. mouseFlag |= MouseFlags.Button2Pressed;
  1151. }
  1152. if ((me.ButtonState & MouseButtonState.Button2Released) != 0)
  1153. {
  1154. mouseFlag |= MouseFlags.Button2Released;
  1155. }
  1156. if ((me.ButtonState & MouseButtonState.Button2Clicked) != 0)
  1157. {
  1158. mouseFlag |= MouseFlags.Button2Clicked;
  1159. }
  1160. if ((me.ButtonState & MouseButtonState.Button2DoubleClicked) != 0)
  1161. {
  1162. mouseFlag |= MouseFlags.Button2DoubleClicked;
  1163. }
  1164. if ((me.ButtonState & MouseButtonState.Button2TripleClicked) != 0)
  1165. {
  1166. mouseFlag |= MouseFlags.Button2TripleClicked;
  1167. }
  1168. if ((me.ButtonState & MouseButtonState.Button3Pressed) != 0)
  1169. {
  1170. mouseFlag |= MouseFlags.Button3Pressed;
  1171. }
  1172. if ((me.ButtonState & MouseButtonState.Button3Released) != 0)
  1173. {
  1174. mouseFlag |= MouseFlags.Button3Released;
  1175. }
  1176. if ((me.ButtonState & MouseButtonState.Button3Clicked) != 0)
  1177. {
  1178. mouseFlag |= MouseFlags.Button3Clicked;
  1179. }
  1180. if ((me.ButtonState & MouseButtonState.Button3DoubleClicked) != 0)
  1181. {
  1182. mouseFlag |= MouseFlags.Button3DoubleClicked;
  1183. }
  1184. if ((me.ButtonState & MouseButtonState.Button3TripleClicked) != 0)
  1185. {
  1186. mouseFlag |= MouseFlags.Button3TripleClicked;
  1187. }
  1188. if ((me.ButtonState & MouseButtonState.ButtonWheeledUp) != 0)
  1189. {
  1190. mouseFlag |= MouseFlags.WheeledUp;
  1191. }
  1192. if ((me.ButtonState & MouseButtonState.ButtonWheeledDown) != 0)
  1193. {
  1194. mouseFlag |= MouseFlags.WheeledDown;
  1195. }
  1196. if ((me.ButtonState & MouseButtonState.ButtonWheeledLeft) != 0)
  1197. {
  1198. mouseFlag |= MouseFlags.WheeledLeft;
  1199. }
  1200. if ((me.ButtonState & MouseButtonState.ButtonWheeledRight) != 0)
  1201. {
  1202. mouseFlag |= MouseFlags.WheeledRight;
  1203. }
  1204. if ((me.ButtonState & MouseButtonState.Button4Pressed) != 0)
  1205. {
  1206. mouseFlag |= MouseFlags.Button4Pressed;
  1207. }
  1208. if ((me.ButtonState & MouseButtonState.Button4Released) != 0)
  1209. {
  1210. mouseFlag |= MouseFlags.Button4Released;
  1211. }
  1212. if ((me.ButtonState & MouseButtonState.Button4Clicked) != 0)
  1213. {
  1214. mouseFlag |= MouseFlags.Button4Clicked;
  1215. }
  1216. if ((me.ButtonState & MouseButtonState.Button4DoubleClicked) != 0)
  1217. {
  1218. mouseFlag |= MouseFlags.Button4DoubleClicked;
  1219. }
  1220. if ((me.ButtonState & MouseButtonState.Button4TripleClicked) != 0)
  1221. {
  1222. mouseFlag |= MouseFlags.Button4TripleClicked;
  1223. }
  1224. if ((me.ButtonState & MouseButtonState.ReportMousePosition) != 0)
  1225. {
  1226. mouseFlag |= MouseFlags.ReportMousePosition;
  1227. }
  1228. if ((me.ButtonState & MouseButtonState.ButtonShift) != 0)
  1229. {
  1230. mouseFlag |= MouseFlags.ButtonShift;
  1231. }
  1232. if ((me.ButtonState & MouseButtonState.ButtonCtrl) != 0)
  1233. {
  1234. mouseFlag |= MouseFlags.ButtonCtrl;
  1235. }
  1236. if ((me.ButtonState & MouseButtonState.ButtonAlt) != 0)
  1237. {
  1238. mouseFlag |= MouseFlags.ButtonAlt;
  1239. }
  1240. return new MouseEventArgs { Position = me.Position, Flags = mouseFlag };
  1241. }
  1242. #endregion Mouse Handling
  1243. #region Keyboard Handling
  1244. private ConsoleKeyInfo FromVKPacketToKConsoleKeyInfo (ConsoleKeyInfo consoleKeyInfo)
  1245. {
  1246. if (consoleKeyInfo.Key != ConsoleKey.Packet)
  1247. {
  1248. return consoleKeyInfo;
  1249. }
  1250. ConsoleModifiers mod = consoleKeyInfo.Modifiers;
  1251. bool shift = (mod & ConsoleModifiers.Shift) != 0;
  1252. bool alt = (mod & ConsoleModifiers.Alt) != 0;
  1253. bool control = (mod & ConsoleModifiers.Control) != 0;
  1254. ConsoleKeyInfo cKeyInfo = DecodeVKPacketToKConsoleKeyInfo (consoleKeyInfo);
  1255. return new ConsoleKeyInfo (cKeyInfo.KeyChar, cKeyInfo.Key, shift, alt, control);
  1256. }
  1257. private KeyCode MapKey (ConsoleKeyInfo keyInfo)
  1258. {
  1259. switch (keyInfo.Key)
  1260. {
  1261. case ConsoleKey.OemPeriod:
  1262. case ConsoleKey.OemComma:
  1263. case ConsoleKey.OemPlus:
  1264. case ConsoleKey.OemMinus:
  1265. case ConsoleKey.Packet:
  1266. case ConsoleKey.Oem1:
  1267. case ConsoleKey.Oem2:
  1268. case ConsoleKey.Oem3:
  1269. case ConsoleKey.Oem4:
  1270. case ConsoleKey.Oem5:
  1271. case ConsoleKey.Oem6:
  1272. case ConsoleKey.Oem7:
  1273. case ConsoleKey.Oem8:
  1274. case ConsoleKey.Oem102:
  1275. if (keyInfo.KeyChar == 0)
  1276. {
  1277. // If the keyChar is 0, keyInfo.Key value is not a printable character.
  1278. return KeyCode.Null; // MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode)keyInfo.Key);
  1279. }
  1280. if (keyInfo.Modifiers != ConsoleModifiers.Shift)
  1281. {
  1282. // If Shift wasn't down we don't need to do anything but return the keyInfo.KeyChar
  1283. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar);
  1284. }
  1285. // Strip off Shift - We got here because they KeyChar from Windows is the shifted char (e.g. "Ç")
  1286. // and passing on Shift would be redundant.
  1287. return MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.KeyChar);
  1288. }
  1289. // Handle control keys whose VK codes match the related ASCII value (those below ASCII 33) like ESC
  1290. if (keyInfo.Key != ConsoleKey.None && Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key))
  1291. {
  1292. if (keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control) && keyInfo.Key == ConsoleKey.I)
  1293. {
  1294. return KeyCode.Tab;
  1295. }
  1296. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)((uint)keyInfo.Key));
  1297. }
  1298. // Handle control keys (e.g. CursorUp)
  1299. if (keyInfo.Key != ConsoleKey.None
  1300. && Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint))
  1301. {
  1302. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)((uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint));
  1303. }
  1304. if (((ConsoleKey)keyInfo.KeyChar) is >= ConsoleKey.A and <= ConsoleKey.Z)
  1305. {
  1306. // Shifted
  1307. keyInfo = new ConsoleKeyInfo (
  1308. keyInfo.KeyChar,
  1309. (ConsoleKey)keyInfo.KeyChar,
  1310. true,
  1311. keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt),
  1312. keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control));
  1313. }
  1314. if ((ConsoleKey)keyInfo.KeyChar - 32 is >= ConsoleKey.A and <= ConsoleKey.Z)
  1315. {
  1316. // Unshifted
  1317. keyInfo = new ConsoleKeyInfo (
  1318. keyInfo.KeyChar,
  1319. (ConsoleKey)(keyInfo.KeyChar - 32),
  1320. false,
  1321. keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt),
  1322. keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control));
  1323. }
  1324. if (keyInfo.Key is >= ConsoleKey.A and <= ConsoleKey.Z )
  1325. {
  1326. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt)
  1327. || keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control))
  1328. {
  1329. // NetDriver doesn't support Shift-Ctrl/Shift-Alt combos
  1330. return MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.Key);
  1331. }
  1332. if (keyInfo.Modifiers == ConsoleModifiers.Shift)
  1333. {
  1334. // If ShiftMask is on add the ShiftMask
  1335. if (char.IsUpper (keyInfo.KeyChar))
  1336. {
  1337. return (KeyCode)keyInfo.Key | KeyCode.ShiftMask;
  1338. }
  1339. }
  1340. return (KeyCode)keyInfo.Key;
  1341. }
  1342. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)((uint)keyInfo.KeyChar));
  1343. }
  1344. #endregion Keyboard Handling
  1345. }
  1346. /// <summary>
  1347. /// Mainloop intended to be used with the .NET System.Console API, and can be used on Windows and Unix, it is
  1348. /// cross-platform but lacks things like file descriptor monitoring.
  1349. /// </summary>
  1350. /// <remarks>This implementation is used for NetDriver.</remarks>
  1351. internal class NetMainLoop : IMainLoopDriver
  1352. {
  1353. internal NetEvents _netEvents;
  1354. /// <summary>Invoked when a Key is pressed.</summary>
  1355. internal Action<InputResult> ProcessInput;
  1356. private readonly CancellationTokenSource _inputHandlerTokenSource = new ();
  1357. // Wrap ConcurrentQueue in a BlockingCollection to enable blocking with timeout
  1358. private readonly BlockingCollection<InputResult> _resultQueue = new (new ConcurrentQueue<InputResult> ());
  1359. private readonly ManualResetEventSlim _waitForProbe = new (false);
  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. bool IMainLoopDriver.EventsPending ()
  1380. {
  1381. _waitForProbe.Set ();
  1382. if (_mainLoop.CheckTimersAndIdleHandlers (out _))
  1383. {
  1384. return true;
  1385. }
  1386. return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _);
  1387. }
  1388. void IMainLoopDriver.Iteration ()
  1389. {
  1390. while (_resultQueue.TryTake (out InputResult v))
  1391. {
  1392. ProcessInput?.Invoke (v);
  1393. }
  1394. }
  1395. void IMainLoopDriver.TearDown ()
  1396. {
  1397. _inputHandlerTokenSource?.Cancel ();
  1398. _inputHandlerTokenSource?.Dispose ();
  1399. _waitForProbe?.Dispose ();
  1400. _netEvents?.Dispose ();
  1401. _netEvents = null;
  1402. _mainLoop = null;
  1403. }
  1404. private void NetInputHandler ()
  1405. {
  1406. while (_mainLoop is { })
  1407. {
  1408. try
  1409. {
  1410. if (!_inputHandlerTokenSource.IsCancellationRequested)
  1411. {
  1412. _waitForProbe.Wait (_inputHandlerTokenSource.Token);
  1413. }
  1414. }
  1415. catch (OperationCanceledException)
  1416. {
  1417. return;
  1418. }
  1419. finally
  1420. {
  1421. if (_waitForProbe.IsSet)
  1422. {
  1423. _waitForProbe.Reset ();
  1424. }
  1425. }
  1426. if (_inputHandlerTokenSource.IsCancellationRequested)
  1427. {
  1428. return;
  1429. }
  1430. _inputHandlerTokenSource.Token.ThrowIfCancellationRequested ();
  1431. var input = _netEvents.DequeueInput ();
  1432. if (input.HasValue)
  1433. {
  1434. _resultQueue.Add (input.Value);
  1435. }
  1436. }
  1437. }
  1438. }