NetDriver.cs 61 KB

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