NetDriver.cs 58 KB

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