NetDriver.cs 61 KB

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