NetDriver.cs 61 KB

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