NetDriver.cs 65 KB

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