NetDriver.cs 65 KB

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