NetDriver.cs 59 KB

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