NetDriver.cs 63 KB

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