NetDriver.cs 67 KB

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