NetDriver.cs 58 KB

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