NetDriver.cs 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834
  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 CancellationTokenSource _inputHandlerTokenSource = new ();
  1433. // Wrap ConcurrentQueue in a BlockingCollection to enable blocking with timeout
  1434. private readonly BlockingCollection<InputResult> _resultQueue = new (new ConcurrentQueue<InputResult> ());
  1435. private readonly ManualResetEventSlim _waitForProbe = new (false);
  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 () { }
  1455. bool IMainLoopDriver.EventsPending ()
  1456. {
  1457. _waitForProbe.Set ();
  1458. if (_mainLoop.CheckTimersAndIdleHandlers (out _))
  1459. {
  1460. return true;
  1461. }
  1462. return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _);
  1463. }
  1464. void IMainLoopDriver.Iteration ()
  1465. {
  1466. while (_resultQueue.TryTake (out InputResult v))
  1467. {
  1468. ProcessInput?.Invoke (v);
  1469. }
  1470. }
  1471. void IMainLoopDriver.TearDown ()
  1472. {
  1473. _inputHandlerTokenSource?.Cancel ();
  1474. _inputHandlerTokenSource?.Dispose ();
  1475. _waitForProbe?.Dispose ();
  1476. _netEvents?.Dispose ();
  1477. _netEvents = null;
  1478. _mainLoop = null;
  1479. }
  1480. private void NetInputHandler ()
  1481. {
  1482. while (_mainLoop is { })
  1483. {
  1484. try
  1485. {
  1486. if (!_inputHandlerTokenSource.IsCancellationRequested)
  1487. {
  1488. _waitForProbe.Wait (_inputHandlerTokenSource.Token);
  1489. }
  1490. }
  1491. catch (OperationCanceledException)
  1492. {
  1493. return;
  1494. }
  1495. finally
  1496. {
  1497. if (_waitForProbe.IsSet)
  1498. {
  1499. _waitForProbe.Reset ();
  1500. }
  1501. }
  1502. if (_inputHandlerTokenSource.IsCancellationRequested)
  1503. {
  1504. return;
  1505. }
  1506. _inputHandlerTokenSource.Token.ThrowIfCancellationRequested ();
  1507. var input = _netEvents.DequeueInput ();
  1508. if (input.HasValue)
  1509. {
  1510. _resultQueue.Add (input.Value);
  1511. }
  1512. }
  1513. }
  1514. }