NetDriver.cs 62 KB

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