NetDriver.cs 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007
  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. try
  1254. {
  1255. lock (ansiRequest._responseLock)
  1256. {
  1257. ansiRequest.ResponseFromInput += (s, e) =>
  1258. {
  1259. Debug.Assert (s == ansiRequest);
  1260. Debug.Assert (e == ansiRequest.Response);
  1261. _waitAnsiResponse.Set ();
  1262. };
  1263. _mainLoopDriver._netEvents.EscSeqRequests.Add (ansiRequest);
  1264. _mainLoopDriver._netEvents._forceRead = true;
  1265. }
  1266. if (!_ansiResponseTokenSource.IsCancellationRequested)
  1267. {
  1268. _mainLoopDriver._netEvents._waitForStart.Set ();
  1269. if (!_mainLoopDriver._waitForProbe.IsSet)
  1270. {
  1271. _mainLoopDriver._waitForProbe.Set ();
  1272. }
  1273. _waitAnsiResponse.Wait (_ansiResponseTokenSource.Token);
  1274. }
  1275. }
  1276. catch (OperationCanceledException)
  1277. {
  1278. return string.Empty;
  1279. }
  1280. lock (ansiRequest._responseLock)
  1281. {
  1282. _mainLoopDriver._netEvents._forceRead = false;
  1283. if (_mainLoopDriver._netEvents.EscSeqRequests.Statuses.TryPeek (out EscSeqReqStatus request))
  1284. {
  1285. if (_mainLoopDriver._netEvents.EscSeqRequests.Statuses.Count > 0
  1286. && string.IsNullOrEmpty (request.AnsiRequest.Response))
  1287. {
  1288. lock (request!.AnsiRequest._responseLock)
  1289. {
  1290. // Bad request or no response at all
  1291. _mainLoopDriver._netEvents.EscSeqRequests.Statuses.TryDequeue (out _);
  1292. }
  1293. }
  1294. }
  1295. _waitAnsiResponse.Reset ();
  1296. return ansiRequest.Response;
  1297. }
  1298. }
  1299. /// <inheritdoc />
  1300. public override void WriteRaw (string ansi) { throw new NotImplementedException (); }
  1301. private MouseEventArgs ToDriverMouse (NetEvents.MouseEvent me)
  1302. {
  1303. //System.Diagnostics.Debug.WriteLine ($"X: {me.Position.X}; Y: {me.Position.Y}; ButtonState: {me.ButtonState}");
  1304. MouseFlags mouseFlag = 0;
  1305. if ((me.ButtonState & MouseButtonState.Button1Pressed) != 0)
  1306. {
  1307. mouseFlag |= MouseFlags.Button1Pressed;
  1308. }
  1309. if ((me.ButtonState & MouseButtonState.Button1Released) != 0)
  1310. {
  1311. mouseFlag |= MouseFlags.Button1Released;
  1312. }
  1313. if ((me.ButtonState & MouseButtonState.Button1Clicked) != 0)
  1314. {
  1315. mouseFlag |= MouseFlags.Button1Clicked;
  1316. }
  1317. if ((me.ButtonState & MouseButtonState.Button1DoubleClicked) != 0)
  1318. {
  1319. mouseFlag |= MouseFlags.Button1DoubleClicked;
  1320. }
  1321. if ((me.ButtonState & MouseButtonState.Button1TripleClicked) != 0)
  1322. {
  1323. mouseFlag |= MouseFlags.Button1TripleClicked;
  1324. }
  1325. if ((me.ButtonState & MouseButtonState.Button2Pressed) != 0)
  1326. {
  1327. mouseFlag |= MouseFlags.Button2Pressed;
  1328. }
  1329. if ((me.ButtonState & MouseButtonState.Button2Released) != 0)
  1330. {
  1331. mouseFlag |= MouseFlags.Button2Released;
  1332. }
  1333. if ((me.ButtonState & MouseButtonState.Button2Clicked) != 0)
  1334. {
  1335. mouseFlag |= MouseFlags.Button2Clicked;
  1336. }
  1337. if ((me.ButtonState & MouseButtonState.Button2DoubleClicked) != 0)
  1338. {
  1339. mouseFlag |= MouseFlags.Button2DoubleClicked;
  1340. }
  1341. if ((me.ButtonState & MouseButtonState.Button2TripleClicked) != 0)
  1342. {
  1343. mouseFlag |= MouseFlags.Button2TripleClicked;
  1344. }
  1345. if ((me.ButtonState & MouseButtonState.Button3Pressed) != 0)
  1346. {
  1347. mouseFlag |= MouseFlags.Button3Pressed;
  1348. }
  1349. if ((me.ButtonState & MouseButtonState.Button3Released) != 0)
  1350. {
  1351. mouseFlag |= MouseFlags.Button3Released;
  1352. }
  1353. if ((me.ButtonState & MouseButtonState.Button3Clicked) != 0)
  1354. {
  1355. mouseFlag |= MouseFlags.Button3Clicked;
  1356. }
  1357. if ((me.ButtonState & MouseButtonState.Button3DoubleClicked) != 0)
  1358. {
  1359. mouseFlag |= MouseFlags.Button3DoubleClicked;
  1360. }
  1361. if ((me.ButtonState & MouseButtonState.Button3TripleClicked) != 0)
  1362. {
  1363. mouseFlag |= MouseFlags.Button3TripleClicked;
  1364. }
  1365. if ((me.ButtonState & MouseButtonState.ButtonWheeledUp) != 0)
  1366. {
  1367. mouseFlag |= MouseFlags.WheeledUp;
  1368. }
  1369. if ((me.ButtonState & MouseButtonState.ButtonWheeledDown) != 0)
  1370. {
  1371. mouseFlag |= MouseFlags.WheeledDown;
  1372. }
  1373. if ((me.ButtonState & MouseButtonState.ButtonWheeledLeft) != 0)
  1374. {
  1375. mouseFlag |= MouseFlags.WheeledLeft;
  1376. }
  1377. if ((me.ButtonState & MouseButtonState.ButtonWheeledRight) != 0)
  1378. {
  1379. mouseFlag |= MouseFlags.WheeledRight;
  1380. }
  1381. if ((me.ButtonState & MouseButtonState.Button4Pressed) != 0)
  1382. {
  1383. mouseFlag |= MouseFlags.Button4Pressed;
  1384. }
  1385. if ((me.ButtonState & MouseButtonState.Button4Released) != 0)
  1386. {
  1387. mouseFlag |= MouseFlags.Button4Released;
  1388. }
  1389. if ((me.ButtonState & MouseButtonState.Button4Clicked) != 0)
  1390. {
  1391. mouseFlag |= MouseFlags.Button4Clicked;
  1392. }
  1393. if ((me.ButtonState & MouseButtonState.Button4DoubleClicked) != 0)
  1394. {
  1395. mouseFlag |= MouseFlags.Button4DoubleClicked;
  1396. }
  1397. if ((me.ButtonState & MouseButtonState.Button4TripleClicked) != 0)
  1398. {
  1399. mouseFlag |= MouseFlags.Button4TripleClicked;
  1400. }
  1401. if ((me.ButtonState & MouseButtonState.ReportMousePosition) != 0)
  1402. {
  1403. mouseFlag |= MouseFlags.ReportMousePosition;
  1404. }
  1405. if ((me.ButtonState & MouseButtonState.ButtonShift) != 0)
  1406. {
  1407. mouseFlag |= MouseFlags.ButtonShift;
  1408. }
  1409. if ((me.ButtonState & MouseButtonState.ButtonCtrl) != 0)
  1410. {
  1411. mouseFlag |= MouseFlags.ButtonCtrl;
  1412. }
  1413. if ((me.ButtonState & MouseButtonState.ButtonAlt) != 0)
  1414. {
  1415. mouseFlag |= MouseFlags.ButtonAlt;
  1416. }
  1417. return new MouseEventArgs { Position = me.Position, Flags = mouseFlag };
  1418. }
  1419. #endregion Mouse Handling
  1420. #region Keyboard Handling
  1421. private ConsoleKeyInfo FromVKPacketToKConsoleKeyInfo (ConsoleKeyInfo consoleKeyInfo)
  1422. {
  1423. if (consoleKeyInfo.Key != ConsoleKey.Packet)
  1424. {
  1425. return consoleKeyInfo;
  1426. }
  1427. ConsoleModifiers mod = consoleKeyInfo.Modifiers;
  1428. bool shift = (mod & ConsoleModifiers.Shift) != 0;
  1429. bool alt = (mod & ConsoleModifiers.Alt) != 0;
  1430. bool control = (mod & ConsoleModifiers.Control) != 0;
  1431. ConsoleKeyInfo cKeyInfo = DecodeVKPacketToKConsoleKeyInfo (consoleKeyInfo);
  1432. return new ConsoleKeyInfo (cKeyInfo.KeyChar, cKeyInfo.Key, shift, alt, control);
  1433. }
  1434. private KeyCode MapKey (ConsoleKeyInfo keyInfo)
  1435. {
  1436. switch (keyInfo.Key)
  1437. {
  1438. case ConsoleKey.OemPeriod:
  1439. case ConsoleKey.OemComma:
  1440. case ConsoleKey.OemPlus:
  1441. case ConsoleKey.OemMinus:
  1442. case ConsoleKey.Packet:
  1443. case ConsoleKey.Oem1:
  1444. case ConsoleKey.Oem2:
  1445. case ConsoleKey.Oem3:
  1446. case ConsoleKey.Oem4:
  1447. case ConsoleKey.Oem5:
  1448. case ConsoleKey.Oem6:
  1449. case ConsoleKey.Oem7:
  1450. case ConsoleKey.Oem8:
  1451. case ConsoleKey.Oem102:
  1452. if (keyInfo.KeyChar == 0)
  1453. {
  1454. // If the keyChar is 0, keyInfo.Key value is not a printable character.
  1455. return KeyCode.Null; // MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode)keyInfo.Key);
  1456. }
  1457. if (keyInfo.Modifiers != ConsoleModifiers.Shift)
  1458. {
  1459. // If Shift wasn't down we don't need to do anything but return the keyInfo.KeyChar
  1460. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar);
  1461. }
  1462. // Strip off Shift - We got here because they KeyChar from Windows is the shifted char (e.g. "Ç")
  1463. // and passing on Shift would be redundant.
  1464. return MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.KeyChar);
  1465. }
  1466. // Handle control keys whose VK codes match the related ASCII value (those below ASCII 33) like ESC
  1467. if (keyInfo.Key != ConsoleKey.None && Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key))
  1468. {
  1469. if (keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control) && keyInfo.Key == ConsoleKey.I)
  1470. {
  1471. return KeyCode.Tab;
  1472. }
  1473. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)((uint)keyInfo.Key));
  1474. }
  1475. // Handle control keys (e.g. CursorUp)
  1476. if (keyInfo.Key != ConsoleKey.None
  1477. && Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint))
  1478. {
  1479. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)((uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint));
  1480. }
  1481. if (((ConsoleKey)keyInfo.KeyChar) is >= ConsoleKey.A and <= ConsoleKey.Z)
  1482. {
  1483. // Shifted
  1484. keyInfo = new ConsoleKeyInfo (
  1485. keyInfo.KeyChar,
  1486. (ConsoleKey)keyInfo.KeyChar,
  1487. true,
  1488. keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt),
  1489. keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control));
  1490. }
  1491. if ((ConsoleKey)keyInfo.KeyChar - 32 is >= ConsoleKey.A and <= ConsoleKey.Z)
  1492. {
  1493. // Unshifted
  1494. keyInfo = new ConsoleKeyInfo (
  1495. keyInfo.KeyChar,
  1496. (ConsoleKey)(keyInfo.KeyChar - 32),
  1497. false,
  1498. keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt),
  1499. keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control));
  1500. }
  1501. if (keyInfo.Key is >= ConsoleKey.A and <= ConsoleKey.Z )
  1502. {
  1503. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt)
  1504. || keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control))
  1505. {
  1506. // NetDriver doesn't support Shift-Ctrl/Shift-Alt combos
  1507. return MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.Key);
  1508. }
  1509. if (keyInfo.Modifiers == ConsoleModifiers.Shift)
  1510. {
  1511. // If ShiftMask is on add the ShiftMask
  1512. if (char.IsUpper (keyInfo.KeyChar))
  1513. {
  1514. return (KeyCode)keyInfo.Key | KeyCode.ShiftMask;
  1515. }
  1516. }
  1517. return (KeyCode)keyInfo.Key;
  1518. }
  1519. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)((uint)keyInfo.KeyChar));
  1520. }
  1521. #endregion Keyboard Handling
  1522. }
  1523. /// <summary>
  1524. /// Mainloop intended to be used with the .NET System.Console API, and can be used on Windows and Unix, it is
  1525. /// cross-platform but lacks things like file descriptor monitoring.
  1526. /// </summary>
  1527. /// <remarks>This implementation is used for NetDriver.</remarks>
  1528. internal class NetMainLoop : IMainLoopDriver
  1529. {
  1530. internal NetEvents _netEvents;
  1531. /// <summary>Invoked when a Key is pressed.</summary>
  1532. internal Action<InputResult> ProcessInput;
  1533. private readonly ManualResetEventSlim _eventReady = new (false);
  1534. private readonly CancellationTokenSource _inputHandlerTokenSource = new ();
  1535. private readonly ConcurrentQueue<InputResult?> _resultQueue = new ();
  1536. internal readonly ManualResetEventSlim _waitForProbe = new (false);
  1537. private readonly CancellationTokenSource _eventReadyTokenSource = new ();
  1538. private MainLoop _mainLoop;
  1539. /// <summary>Initializes the class with the console driver.</summary>
  1540. /// <remarks>Passing a consoleDriver is provided to capture windows resizing.</remarks>
  1541. /// <param name="consoleDriver">The console driver used by this Net main loop.</param>
  1542. /// <exception cref="ArgumentNullException"></exception>
  1543. public NetMainLoop (ConsoleDriver consoleDriver = null)
  1544. {
  1545. if (consoleDriver is null)
  1546. {
  1547. throw new ArgumentNullException (nameof (consoleDriver));
  1548. }
  1549. _netEvents = new NetEvents (consoleDriver);
  1550. }
  1551. void IMainLoopDriver.Setup (MainLoop mainLoop)
  1552. {
  1553. _mainLoop = mainLoop;
  1554. if (ConsoleDriver.RunningUnitTests)
  1555. {
  1556. return;
  1557. }
  1558. Task.Run (NetInputHandler, _inputHandlerTokenSource.Token);
  1559. }
  1560. void IMainLoopDriver.Wakeup () { _eventReady.Set (); }
  1561. bool IMainLoopDriver.EventsPending ()
  1562. {
  1563. _waitForProbe.Set ();
  1564. if (_mainLoop.CheckTimersAndIdleHandlers (out int waitTimeout))
  1565. {
  1566. return true;
  1567. }
  1568. try
  1569. {
  1570. if (!_eventReadyTokenSource.IsCancellationRequested)
  1571. {
  1572. // Note: ManualResetEventSlim.Wait will wait indefinitely if the timeout is -1. The timeout is -1 when there
  1573. // are no timers, but there IS an idle handler waiting.
  1574. _eventReady.Wait (waitTimeout, _eventReadyTokenSource.Token);
  1575. }
  1576. }
  1577. catch (OperationCanceledException)
  1578. {
  1579. return true;
  1580. }
  1581. finally
  1582. {
  1583. _eventReady.Reset ();
  1584. }
  1585. _eventReadyTokenSource.Token.ThrowIfCancellationRequested ();
  1586. if (!_eventReadyTokenSource.IsCancellationRequested)
  1587. {
  1588. return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _);
  1589. }
  1590. return true;
  1591. }
  1592. void IMainLoopDriver.Iteration ()
  1593. {
  1594. while (_resultQueue.Count > 0)
  1595. {
  1596. // Always dequeue even if it's null and invoke if isn't null
  1597. if (_resultQueue.TryDequeue (out InputResult? dequeueResult))
  1598. {
  1599. if (dequeueResult is { })
  1600. {
  1601. ProcessInput?.Invoke (dequeueResult.Value);
  1602. }
  1603. }
  1604. }
  1605. }
  1606. void IMainLoopDriver.TearDown ()
  1607. {
  1608. _inputHandlerTokenSource?.Cancel ();
  1609. _inputHandlerTokenSource?.Dispose ();
  1610. _eventReadyTokenSource?.Cancel ();
  1611. _eventReadyTokenSource?.Dispose ();
  1612. _eventReady?.Dispose ();
  1613. _resultQueue?.Clear ();
  1614. _waitForProbe?.Dispose ();
  1615. _netEvents?.Dispose ();
  1616. _netEvents = null;
  1617. _mainLoop = null;
  1618. }
  1619. private void NetInputHandler ()
  1620. {
  1621. while (_mainLoop is { })
  1622. {
  1623. try
  1624. {
  1625. if (!_netEvents._forceRead && !_inputHandlerTokenSource.IsCancellationRequested)
  1626. {
  1627. _waitForProbe.Wait (_inputHandlerTokenSource.Token);
  1628. }
  1629. }
  1630. catch (OperationCanceledException)
  1631. {
  1632. return;
  1633. }
  1634. finally
  1635. {
  1636. if (_waitForProbe.IsSet)
  1637. {
  1638. _waitForProbe.Reset ();
  1639. }
  1640. }
  1641. if (_inputHandlerTokenSource.IsCancellationRequested)
  1642. {
  1643. return;
  1644. }
  1645. _inputHandlerTokenSource.Token.ThrowIfCancellationRequested ();
  1646. if (_resultQueue.Count == 0)
  1647. {
  1648. _resultQueue.Enqueue (_netEvents.DequeueInput ());
  1649. }
  1650. try
  1651. {
  1652. while (_resultQueue.Count > 0 && _resultQueue.TryPeek (out InputResult? result) && result is null)
  1653. {
  1654. // Dequeue null values
  1655. _resultQueue.TryDequeue (out _);
  1656. }
  1657. }
  1658. catch (InvalidOperationException) // Peek can raise an exception
  1659. { }
  1660. if (_resultQueue.Count > 0)
  1661. {
  1662. _eventReady.Set ();
  1663. }
  1664. }
  1665. }
  1666. }