NetDriver.cs 60 KB

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