NetDriver.cs 57 KB

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