NetDriver.cs 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935
  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. foreach (var s in Application.Sixel)
  872. {
  873. if (!string.IsNullOrWhiteSpace (s.SixelData))
  874. {
  875. SetCursorPosition (s.ScreenPosition.X, s.ScreenPosition.Y);
  876. Console.Write (s.SixelData);
  877. }
  878. }
  879. }
  880. SetCursorPosition (0, 0);
  881. _cachedCursorVisibility = savedVisibility;
  882. void WriteToConsole (StringBuilder output, ref int lastCol, int row, ref int outputWidth)
  883. {
  884. SetCursorPosition (lastCol, row);
  885. Console.Write (output);
  886. output.Clear ();
  887. lastCol += outputWidth;
  888. outputWidth = 0;
  889. }
  890. }
  891. internal override void End ()
  892. {
  893. if (IsWinPlatform)
  894. {
  895. NetWinConsole?.Cleanup ();
  896. }
  897. StopReportingMouseMoves ();
  898. _ansiResponseTokenSource?.Cancel ();
  899. _ansiResponseTokenSource?.Dispose ();
  900. _waitAnsiResponse?.Dispose ();
  901. if (!RunningUnitTests)
  902. {
  903. Console.ResetColor ();
  904. //Disable alternative screen buffer.
  905. Console.Out.Write (EscSeqUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll);
  906. //Set cursor key to cursor.
  907. Console.Out.Write (EscSeqUtils.CSI_ShowCursor);
  908. Console.Out.Close ();
  909. }
  910. }
  911. internal override MainLoop Init ()
  912. {
  913. PlatformID p = Environment.OSVersion.Platform;
  914. if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows)
  915. {
  916. IsWinPlatform = true;
  917. try
  918. {
  919. NetWinConsole = new NetWinVTConsole ();
  920. }
  921. catch (ApplicationException)
  922. {
  923. // Likely running as a unit test, or in a non-interactive session.
  924. }
  925. }
  926. if (IsWinPlatform)
  927. {
  928. Clipboard = new WindowsClipboard ();
  929. }
  930. else if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX))
  931. {
  932. Clipboard = new MacOSXClipboard ();
  933. }
  934. else
  935. {
  936. if (CursesDriver.Is_WSL_Platform ())
  937. {
  938. Clipboard = new WSLClipboard ();
  939. }
  940. else
  941. {
  942. Clipboard = new CursesClipboard ();
  943. }
  944. }
  945. if (!RunningUnitTests)
  946. {
  947. Console.TreatControlCAsInput = true;
  948. Cols = Console.WindowWidth;
  949. Rows = Console.WindowHeight;
  950. //Enable alternative screen buffer.
  951. Console.Out.Write (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll);
  952. //Set cursor key to application.
  953. Console.Out.Write (EscSeqUtils.CSI_HideCursor);
  954. }
  955. else
  956. {
  957. // We are being run in an environment that does not support a console
  958. // such as a unit test, or a pipe.
  959. Cols = 80;
  960. Rows = 24;
  961. }
  962. ResizeScreen ();
  963. ClearContents ();
  964. CurrentAttribute = new Attribute (Color.White, Color.Black);
  965. StartReportingMouseMoves ();
  966. _mainLoopDriver = new NetMainLoop (this);
  967. _mainLoopDriver.ProcessInput = ProcessInput;
  968. return new MainLoop (_mainLoopDriver);
  969. }
  970. private void ProcessInput (InputResult inputEvent)
  971. {
  972. switch (inputEvent.EventType)
  973. {
  974. case EventType.Key:
  975. ConsoleKeyInfo consoleKeyInfo = inputEvent.ConsoleKeyInfo;
  976. //if (consoleKeyInfo.Key == ConsoleKey.Packet) {
  977. // consoleKeyInfo = FromVKPacketToKConsoleKeyInfo (consoleKeyInfo);
  978. //}
  979. //Debug.WriteLine ($"event: {inputEvent}");
  980. KeyCode map = MapKey (consoleKeyInfo);
  981. if (map == KeyCode.Null)
  982. {
  983. break;
  984. }
  985. OnKeyDown (new Key (map));
  986. OnKeyUp (new Key (map));
  987. break;
  988. case EventType.Mouse:
  989. MouseEventArgs me = ToDriverMouse (inputEvent.MouseEvent);
  990. //Debug.WriteLine ($"NetDriver: ({me.X},{me.Y}) - {me.Flags}");
  991. OnMouseEvent (me);
  992. break;
  993. case EventType.WindowSize:
  994. _winSizeChanging = true;
  995. Top = 0;
  996. Left = 0;
  997. Cols = inputEvent.WindowSizeEvent.Size.Width;
  998. Rows = Math.Max (inputEvent.WindowSizeEvent.Size.Height, 0);
  999. ;
  1000. ResizeScreen ();
  1001. ClearContents ();
  1002. _winSizeChanging = false;
  1003. OnSizeChanged (new SizeChangedEventArgs (new (Cols, Rows)));
  1004. break;
  1005. case EventType.RequestResponse:
  1006. break;
  1007. case EventType.WindowPosition:
  1008. break;
  1009. default:
  1010. throw new ArgumentOutOfRangeException ();
  1011. }
  1012. }
  1013. #region Size and Position Handling
  1014. private volatile bool _winSizeChanging;
  1015. private void SetWindowPosition (int col, int row)
  1016. {
  1017. if (!RunningUnitTests)
  1018. {
  1019. Top = Console.WindowTop;
  1020. Left = Console.WindowLeft;
  1021. }
  1022. else
  1023. {
  1024. Top = row;
  1025. Left = col;
  1026. }
  1027. }
  1028. public virtual void ResizeScreen ()
  1029. {
  1030. // Not supported on Unix.
  1031. if (IsWinPlatform)
  1032. {
  1033. // Can raise an exception while is still resizing.
  1034. try
  1035. {
  1036. #pragma warning disable CA1416
  1037. if (Console.WindowHeight > 0)
  1038. {
  1039. Console.CursorTop = 0;
  1040. Console.CursorLeft = 0;
  1041. Console.WindowTop = 0;
  1042. Console.WindowLeft = 0;
  1043. if (Console.WindowHeight > Rows)
  1044. {
  1045. Console.SetWindowSize (Cols, Rows);
  1046. }
  1047. Console.SetBufferSize (Cols, Rows);
  1048. }
  1049. #pragma warning restore CA1416
  1050. }
  1051. // INTENT: Why are these eating the exceptions?
  1052. // Comments would be good here.
  1053. catch (IOException)
  1054. {
  1055. // CONCURRENCY: Unsynchronized access to Clip is not safe.
  1056. Clip = new (0, 0, Cols, Rows);
  1057. }
  1058. catch (ArgumentOutOfRangeException)
  1059. {
  1060. // CONCURRENCY: Unsynchronized access to Clip is not safe.
  1061. Clip = new (0, 0, Cols, Rows);
  1062. }
  1063. }
  1064. else
  1065. {
  1066. Console.Out.Write (EscSeqUtils.CSI_SetTerminalWindowSize (Rows, Cols));
  1067. }
  1068. // CONCURRENCY: Unsynchronized access to Clip is not safe.
  1069. Clip = new (0, 0, Cols, Rows);
  1070. }
  1071. #endregion
  1072. #region Color Handling
  1073. // Cache the list of ConsoleColor values.
  1074. [UnconditionalSuppressMessage ("AOT", "IL3050:Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.", Justification = "<Pending>")]
  1075. private static readonly HashSet<int> ConsoleColorValues = new (
  1076. Enum.GetValues (typeof (ConsoleColor))
  1077. .OfType<ConsoleColor> ()
  1078. .Select (c => (int)c)
  1079. );
  1080. // Dictionary for mapping ConsoleColor values to the values used by System.Net.Console.
  1081. private static readonly Dictionary<ConsoleColor, int> colorMap = new ()
  1082. {
  1083. { ConsoleColor.Black, COLOR_BLACK },
  1084. { ConsoleColor.DarkBlue, COLOR_BLUE },
  1085. { ConsoleColor.DarkGreen, COLOR_GREEN },
  1086. { ConsoleColor.DarkCyan, COLOR_CYAN },
  1087. { ConsoleColor.DarkRed, COLOR_RED },
  1088. { ConsoleColor.DarkMagenta, COLOR_MAGENTA },
  1089. { ConsoleColor.DarkYellow, COLOR_YELLOW },
  1090. { ConsoleColor.Gray, COLOR_WHITE },
  1091. { ConsoleColor.DarkGray, COLOR_BRIGHT_BLACK },
  1092. { ConsoleColor.Blue, COLOR_BRIGHT_BLUE },
  1093. { ConsoleColor.Green, COLOR_BRIGHT_GREEN },
  1094. { ConsoleColor.Cyan, COLOR_BRIGHT_CYAN },
  1095. { ConsoleColor.Red, COLOR_BRIGHT_RED },
  1096. { ConsoleColor.Magenta, COLOR_BRIGHT_MAGENTA },
  1097. { ConsoleColor.Yellow, COLOR_BRIGHT_YELLOW },
  1098. { ConsoleColor.White, COLOR_BRIGHT_WHITE }
  1099. };
  1100. // Map a ConsoleColor to a platform dependent value.
  1101. private int MapColors (ConsoleColor color, bool isForeground = true)
  1102. {
  1103. return colorMap.TryGetValue (color, out int colorValue) ? colorValue + (isForeground ? 0 : 10) : 0;
  1104. }
  1105. ///// <remarks>
  1106. ///// In the NetDriver, colors are encoded as an int.
  1107. ///// However, the foreground color is stored in the most significant 16 bits,
  1108. ///// and the background color is stored in the least significant 16 bits.
  1109. ///// </remarks>
  1110. //public override Attribute MakeColor (Color foreground, Color background)
  1111. //{
  1112. // // Encode the colors into the int value.
  1113. // return new Attribute (
  1114. // platformColor: ((((int)foreground.ColorName) & 0xffff) << 16) | (((int)background.ColorName) & 0xffff),
  1115. // foreground: foreground,
  1116. // background: background
  1117. // );
  1118. //}
  1119. #endregion
  1120. #region Cursor Handling
  1121. private bool SetCursorPosition (int col, int row)
  1122. {
  1123. if (IsWinPlatform)
  1124. {
  1125. // Could happens that the windows is still resizing and the col is bigger than Console.WindowWidth.
  1126. try
  1127. {
  1128. Console.SetCursorPosition (col, row);
  1129. return true;
  1130. }
  1131. catch (Exception)
  1132. {
  1133. return false;
  1134. }
  1135. }
  1136. // + 1 is needed because non-Windows is based on 1 instead of 0 and
  1137. // Console.CursorTop/CursorLeft isn't reliable.
  1138. Console.Out.Write (EscSeqUtils.CSI_SetCursorPosition (row + 1, col + 1));
  1139. return true;
  1140. }
  1141. private CursorVisibility? _cachedCursorVisibility;
  1142. public override void UpdateCursor ()
  1143. {
  1144. EnsureCursorVisibility ();
  1145. if (Col >= 0 && Col < Cols && Row >= 0 && Row <= Rows)
  1146. {
  1147. SetCursorPosition (Col, Row);
  1148. SetWindowPosition (0, Row);
  1149. }
  1150. }
  1151. public override bool GetCursorVisibility (out CursorVisibility visibility)
  1152. {
  1153. visibility = _cachedCursorVisibility ?? CursorVisibility.Default;
  1154. return visibility == CursorVisibility.Default;
  1155. }
  1156. public override bool SetCursorVisibility (CursorVisibility visibility)
  1157. {
  1158. _cachedCursorVisibility = visibility;
  1159. Console.Out.Write (visibility == CursorVisibility.Default ? EscSeqUtils.CSI_ShowCursor : EscSeqUtils.CSI_HideCursor);
  1160. return visibility == CursorVisibility.Default;
  1161. }
  1162. public override bool EnsureCursorVisibility ()
  1163. {
  1164. if (!(Col >= 0 && Row >= 0 && Col < Cols && Row < Rows))
  1165. {
  1166. GetCursorVisibility (out CursorVisibility cursorVisibility);
  1167. _cachedCursorVisibility = cursorVisibility;
  1168. SetCursorVisibility (CursorVisibility.Invisible);
  1169. return false;
  1170. }
  1171. SetCursorVisibility (_cachedCursorVisibility ?? CursorVisibility.Default);
  1172. return _cachedCursorVisibility == CursorVisibility.Default;
  1173. }
  1174. #endregion
  1175. #region Mouse Handling
  1176. public void StartReportingMouseMoves ()
  1177. {
  1178. if (!RunningUnitTests)
  1179. {
  1180. Console.Out.Write (EscSeqUtils.CSI_EnableMouseEvents);
  1181. }
  1182. }
  1183. public void StopReportingMouseMoves ()
  1184. {
  1185. if (!RunningUnitTests)
  1186. {
  1187. Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents);
  1188. }
  1189. }
  1190. private readonly ManualResetEventSlim _waitAnsiResponse = new (false);
  1191. private readonly CancellationTokenSource _ansiResponseTokenSource = new ();
  1192. /// <inheritdoc/>
  1193. public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest)
  1194. {
  1195. if (_mainLoopDriver is null)
  1196. {
  1197. return string.Empty;
  1198. }
  1199. var response = string.Empty;
  1200. try
  1201. {
  1202. lock (ansiRequest._responseLock)
  1203. {
  1204. ansiRequest.ResponseFromInput += (s, e) =>
  1205. {
  1206. Debug.Assert (s == ansiRequest);
  1207. ansiRequest.Response = response = e;
  1208. _waitAnsiResponse.Set ();
  1209. };
  1210. _mainLoopDriver._netEvents.EscSeqRequests.Add (ansiRequest);
  1211. }
  1212. if (!_ansiResponseTokenSource.IsCancellationRequested && Console.KeyAvailable)
  1213. {
  1214. _mainLoopDriver._netEvents._forceRead = true;
  1215. _mainLoopDriver._netEvents._waitForStart.Set ();
  1216. if (!_mainLoopDriver._waitForProbe.IsSet)
  1217. {
  1218. _mainLoopDriver._waitForProbe.Set ();
  1219. }
  1220. _waitAnsiResponse.Wait (_ansiResponseTokenSource.Token);
  1221. }
  1222. }
  1223. catch (OperationCanceledException)
  1224. {
  1225. return string.Empty;
  1226. }
  1227. finally
  1228. {
  1229. _mainLoopDriver._netEvents._forceRead = false;
  1230. if (_mainLoopDriver._netEvents.EscSeqRequests.Statuses.TryPeek (out EscSeqReqStatus request))
  1231. {
  1232. if (_mainLoopDriver._netEvents.EscSeqRequests.Statuses.Count > 0
  1233. && string.IsNullOrEmpty (request.AnsiRequest.Response))
  1234. {
  1235. // Bad request or no response at all
  1236. _mainLoopDriver._netEvents.EscSeqRequests.Statuses.TryDequeue (out _);
  1237. }
  1238. }
  1239. _waitAnsiResponse.Reset ();
  1240. }
  1241. return response;
  1242. }
  1243. private MouseEventArgs ToDriverMouse (NetEvents.MouseEvent me)
  1244. {
  1245. //System.Diagnostics.Debug.WriteLine ($"X: {me.Position.X}; Y: {me.Position.Y}; ButtonState: {me.ButtonState}");
  1246. MouseFlags mouseFlag = 0;
  1247. if ((me.ButtonState & MouseButtonState.Button1Pressed) != 0)
  1248. {
  1249. mouseFlag |= MouseFlags.Button1Pressed;
  1250. }
  1251. if ((me.ButtonState & MouseButtonState.Button1Released) != 0)
  1252. {
  1253. mouseFlag |= MouseFlags.Button1Released;
  1254. }
  1255. if ((me.ButtonState & MouseButtonState.Button1Clicked) != 0)
  1256. {
  1257. mouseFlag |= MouseFlags.Button1Clicked;
  1258. }
  1259. if ((me.ButtonState & MouseButtonState.Button1DoubleClicked) != 0)
  1260. {
  1261. mouseFlag |= MouseFlags.Button1DoubleClicked;
  1262. }
  1263. if ((me.ButtonState & MouseButtonState.Button1TripleClicked) != 0)
  1264. {
  1265. mouseFlag |= MouseFlags.Button1TripleClicked;
  1266. }
  1267. if ((me.ButtonState & MouseButtonState.Button2Pressed) != 0)
  1268. {
  1269. mouseFlag |= MouseFlags.Button2Pressed;
  1270. }
  1271. if ((me.ButtonState & MouseButtonState.Button2Released) != 0)
  1272. {
  1273. mouseFlag |= MouseFlags.Button2Released;
  1274. }
  1275. if ((me.ButtonState & MouseButtonState.Button2Clicked) != 0)
  1276. {
  1277. mouseFlag |= MouseFlags.Button2Clicked;
  1278. }
  1279. if ((me.ButtonState & MouseButtonState.Button2DoubleClicked) != 0)
  1280. {
  1281. mouseFlag |= MouseFlags.Button2DoubleClicked;
  1282. }
  1283. if ((me.ButtonState & MouseButtonState.Button2TripleClicked) != 0)
  1284. {
  1285. mouseFlag |= MouseFlags.Button2TripleClicked;
  1286. }
  1287. if ((me.ButtonState & MouseButtonState.Button3Pressed) != 0)
  1288. {
  1289. mouseFlag |= MouseFlags.Button3Pressed;
  1290. }
  1291. if ((me.ButtonState & MouseButtonState.Button3Released) != 0)
  1292. {
  1293. mouseFlag |= MouseFlags.Button3Released;
  1294. }
  1295. if ((me.ButtonState & MouseButtonState.Button3Clicked) != 0)
  1296. {
  1297. mouseFlag |= MouseFlags.Button3Clicked;
  1298. }
  1299. if ((me.ButtonState & MouseButtonState.Button3DoubleClicked) != 0)
  1300. {
  1301. mouseFlag |= MouseFlags.Button3DoubleClicked;
  1302. }
  1303. if ((me.ButtonState & MouseButtonState.Button3TripleClicked) != 0)
  1304. {
  1305. mouseFlag |= MouseFlags.Button3TripleClicked;
  1306. }
  1307. if ((me.ButtonState & MouseButtonState.ButtonWheeledUp) != 0)
  1308. {
  1309. mouseFlag |= MouseFlags.WheeledUp;
  1310. }
  1311. if ((me.ButtonState & MouseButtonState.ButtonWheeledDown) != 0)
  1312. {
  1313. mouseFlag |= MouseFlags.WheeledDown;
  1314. }
  1315. if ((me.ButtonState & MouseButtonState.ButtonWheeledLeft) != 0)
  1316. {
  1317. mouseFlag |= MouseFlags.WheeledLeft;
  1318. }
  1319. if ((me.ButtonState & MouseButtonState.ButtonWheeledRight) != 0)
  1320. {
  1321. mouseFlag |= MouseFlags.WheeledRight;
  1322. }
  1323. if ((me.ButtonState & MouseButtonState.Button4Pressed) != 0)
  1324. {
  1325. mouseFlag |= MouseFlags.Button4Pressed;
  1326. }
  1327. if ((me.ButtonState & MouseButtonState.Button4Released) != 0)
  1328. {
  1329. mouseFlag |= MouseFlags.Button4Released;
  1330. }
  1331. if ((me.ButtonState & MouseButtonState.Button4Clicked) != 0)
  1332. {
  1333. mouseFlag |= MouseFlags.Button4Clicked;
  1334. }
  1335. if ((me.ButtonState & MouseButtonState.Button4DoubleClicked) != 0)
  1336. {
  1337. mouseFlag |= MouseFlags.Button4DoubleClicked;
  1338. }
  1339. if ((me.ButtonState & MouseButtonState.Button4TripleClicked) != 0)
  1340. {
  1341. mouseFlag |= MouseFlags.Button4TripleClicked;
  1342. }
  1343. if ((me.ButtonState & MouseButtonState.ReportMousePosition) != 0)
  1344. {
  1345. mouseFlag |= MouseFlags.ReportMousePosition;
  1346. }
  1347. if ((me.ButtonState & MouseButtonState.ButtonShift) != 0)
  1348. {
  1349. mouseFlag |= MouseFlags.ButtonShift;
  1350. }
  1351. if ((me.ButtonState & MouseButtonState.ButtonCtrl) != 0)
  1352. {
  1353. mouseFlag |= MouseFlags.ButtonCtrl;
  1354. }
  1355. if ((me.ButtonState & MouseButtonState.ButtonAlt) != 0)
  1356. {
  1357. mouseFlag |= MouseFlags.ButtonAlt;
  1358. }
  1359. return new MouseEventArgs { Position = me.Position, Flags = mouseFlag };
  1360. }
  1361. #endregion Mouse Handling
  1362. #region Keyboard Handling
  1363. private ConsoleKeyInfo FromVKPacketToKConsoleKeyInfo (ConsoleKeyInfo consoleKeyInfo)
  1364. {
  1365. if (consoleKeyInfo.Key != ConsoleKey.Packet)
  1366. {
  1367. return consoleKeyInfo;
  1368. }
  1369. ConsoleModifiers mod = consoleKeyInfo.Modifiers;
  1370. bool shift = (mod & ConsoleModifiers.Shift) != 0;
  1371. bool alt = (mod & ConsoleModifiers.Alt) != 0;
  1372. bool control = (mod & ConsoleModifiers.Control) != 0;
  1373. ConsoleKeyInfo cKeyInfo = DecodeVKPacketToKConsoleKeyInfo (consoleKeyInfo);
  1374. return new ConsoleKeyInfo (cKeyInfo.KeyChar, cKeyInfo.Key, shift, alt, control);
  1375. }
  1376. private KeyCode MapKey (ConsoleKeyInfo keyInfo)
  1377. {
  1378. switch (keyInfo.Key)
  1379. {
  1380. case ConsoleKey.OemPeriod:
  1381. case ConsoleKey.OemComma:
  1382. case ConsoleKey.OemPlus:
  1383. case ConsoleKey.OemMinus:
  1384. case ConsoleKey.Packet:
  1385. case ConsoleKey.Oem1:
  1386. case ConsoleKey.Oem2:
  1387. case ConsoleKey.Oem3:
  1388. case ConsoleKey.Oem4:
  1389. case ConsoleKey.Oem5:
  1390. case ConsoleKey.Oem6:
  1391. case ConsoleKey.Oem7:
  1392. case ConsoleKey.Oem8:
  1393. case ConsoleKey.Oem102:
  1394. if (keyInfo.KeyChar == 0)
  1395. {
  1396. // If the keyChar is 0, keyInfo.Key value is not a printable character.
  1397. return KeyCode.Null; // MapToKeyCodeModifiers (keyInfo.Modifiers, KeyCode)keyInfo.Key);
  1398. }
  1399. if (keyInfo.Modifiers != ConsoleModifiers.Shift)
  1400. {
  1401. // If Shift wasn't down we don't need to do anything but return the keyInfo.KeyChar
  1402. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar);
  1403. }
  1404. // Strip off Shift - We got here because they KeyChar from Windows is the shifted char (e.g. "Ç")
  1405. // and passing on Shift would be redundant.
  1406. return MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.KeyChar);
  1407. }
  1408. // Handle control keys whose VK codes match the related ASCII value (those below ASCII 33) like ESC
  1409. if (keyInfo.Key != ConsoleKey.None && Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key))
  1410. {
  1411. if (keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control) && keyInfo.Key == ConsoleKey.I)
  1412. {
  1413. return KeyCode.Tab;
  1414. }
  1415. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)((uint)keyInfo.Key));
  1416. }
  1417. // Handle control keys (e.g. CursorUp)
  1418. if (keyInfo.Key != ConsoleKey.None
  1419. && Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint))
  1420. {
  1421. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)((uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint));
  1422. }
  1423. if (((ConsoleKey)keyInfo.KeyChar) is >= ConsoleKey.A and <= ConsoleKey.Z)
  1424. {
  1425. // Shifted
  1426. keyInfo = new ConsoleKeyInfo (
  1427. keyInfo.KeyChar,
  1428. (ConsoleKey)keyInfo.KeyChar,
  1429. true,
  1430. keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt),
  1431. keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control));
  1432. }
  1433. if ((ConsoleKey)keyInfo.KeyChar - 32 is >= ConsoleKey.A and <= ConsoleKey.Z)
  1434. {
  1435. // Unshifted
  1436. keyInfo = new ConsoleKeyInfo (
  1437. keyInfo.KeyChar,
  1438. (ConsoleKey)(keyInfo.KeyChar - 32),
  1439. false,
  1440. keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt),
  1441. keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control));
  1442. }
  1443. if (keyInfo.Key is >= ConsoleKey.A and <= ConsoleKey.Z )
  1444. {
  1445. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt)
  1446. || keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control))
  1447. {
  1448. // NetDriver doesn't support Shift-Ctrl/Shift-Alt combos
  1449. return MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.Key);
  1450. }
  1451. if (keyInfo.Modifiers == ConsoleModifiers.Shift)
  1452. {
  1453. // If ShiftMask is on add the ShiftMask
  1454. if (char.IsUpper (keyInfo.KeyChar))
  1455. {
  1456. return (KeyCode)keyInfo.Key | KeyCode.ShiftMask;
  1457. }
  1458. }
  1459. return (KeyCode)keyInfo.Key;
  1460. }
  1461. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)((uint)keyInfo.KeyChar));
  1462. }
  1463. #endregion Keyboard Handling
  1464. }
  1465. /// <summary>
  1466. /// Mainloop intended to be used with the .NET System.Console API, and can be used on Windows and Unix, it is
  1467. /// cross-platform but lacks things like file descriptor monitoring.
  1468. /// </summary>
  1469. /// <remarks>This implementation is used for NetDriver.</remarks>
  1470. internal class NetMainLoop : IMainLoopDriver
  1471. {
  1472. internal NetEvents _netEvents;
  1473. /// <summary>Invoked when a Key is pressed.</summary>
  1474. internal Action<InputResult> ProcessInput;
  1475. private readonly ManualResetEventSlim _eventReady = new (false);
  1476. private readonly CancellationTokenSource _inputHandlerTokenSource = new ();
  1477. private readonly Queue<InputResult?> _resultQueue = new ();
  1478. internal readonly ManualResetEventSlim _waitForProbe = new (false);
  1479. private readonly CancellationTokenSource _eventReadyTokenSource = new ();
  1480. private MainLoop _mainLoop;
  1481. /// <summary>Initializes the class with the console driver.</summary>
  1482. /// <remarks>Passing a consoleDriver is provided to capture windows resizing.</remarks>
  1483. /// <param name="consoleDriver">The console driver used by this Net main loop.</param>
  1484. /// <exception cref="ArgumentNullException"></exception>
  1485. public NetMainLoop (ConsoleDriver consoleDriver = null)
  1486. {
  1487. if (consoleDriver is null)
  1488. {
  1489. throw new ArgumentNullException (nameof (consoleDriver));
  1490. }
  1491. _netEvents = new NetEvents (consoleDriver);
  1492. }
  1493. void IMainLoopDriver.Setup (MainLoop mainLoop)
  1494. {
  1495. _mainLoop = mainLoop;
  1496. Task.Run (NetInputHandler, _inputHandlerTokenSource.Token);
  1497. }
  1498. void IMainLoopDriver.Wakeup () { _eventReady.Set (); }
  1499. bool IMainLoopDriver.EventsPending ()
  1500. {
  1501. _waitForProbe.Set ();
  1502. if (_mainLoop.CheckTimersAndIdleHandlers (out int waitTimeout))
  1503. {
  1504. return true;
  1505. }
  1506. try
  1507. {
  1508. if (!_eventReadyTokenSource.IsCancellationRequested)
  1509. {
  1510. // Note: ManualResetEventSlim.Wait will wait indefinitely if the timeout is -1. The timeout is -1 when there
  1511. // are no timers, but there IS an idle handler waiting.
  1512. _eventReady.Wait (waitTimeout, _eventReadyTokenSource.Token);
  1513. }
  1514. }
  1515. catch (OperationCanceledException)
  1516. {
  1517. return true;
  1518. }
  1519. finally
  1520. {
  1521. _eventReady.Reset ();
  1522. }
  1523. _eventReadyTokenSource.Token.ThrowIfCancellationRequested ();
  1524. if (!_eventReadyTokenSource.IsCancellationRequested)
  1525. {
  1526. return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _);
  1527. }
  1528. return true;
  1529. }
  1530. void IMainLoopDriver.Iteration ()
  1531. {
  1532. while (_resultQueue.Count > 0)
  1533. {
  1534. // Always dequeue even if it's null and invoke if isn't null
  1535. InputResult? dequeueResult = _resultQueue.Dequeue ();
  1536. if (dequeueResult is { })
  1537. {
  1538. ProcessInput?.Invoke (dequeueResult.Value);
  1539. }
  1540. }
  1541. }
  1542. void IMainLoopDriver.TearDown ()
  1543. {
  1544. _inputHandlerTokenSource?.Cancel ();
  1545. _inputHandlerTokenSource?.Dispose ();
  1546. _eventReadyTokenSource?.Cancel ();
  1547. _eventReadyTokenSource?.Dispose ();
  1548. _eventReady?.Dispose ();
  1549. _resultQueue?.Clear ();
  1550. _waitForProbe?.Dispose ();
  1551. _netEvents?.Dispose ();
  1552. _netEvents = null;
  1553. _mainLoop = null;
  1554. }
  1555. private void NetInputHandler ()
  1556. {
  1557. while (_mainLoop is { })
  1558. {
  1559. try
  1560. {
  1561. if (!_netEvents._forceRead && !_inputHandlerTokenSource.IsCancellationRequested)
  1562. {
  1563. _waitForProbe.Wait (_inputHandlerTokenSource.Token);
  1564. }
  1565. }
  1566. catch (OperationCanceledException)
  1567. {
  1568. return;
  1569. }
  1570. finally
  1571. {
  1572. if (_waitForProbe.IsSet)
  1573. {
  1574. _waitForProbe.Reset ();
  1575. }
  1576. }
  1577. if (_inputHandlerTokenSource.IsCancellationRequested)
  1578. {
  1579. return;
  1580. }
  1581. _inputHandlerTokenSource.Token.ThrowIfCancellationRequested ();
  1582. if (_resultQueue.Count == 0)
  1583. {
  1584. _resultQueue.Enqueue (_netEvents.DequeueInput ());
  1585. }
  1586. try
  1587. {
  1588. while (_resultQueue.Count > 0 && _resultQueue.Peek () is null)
  1589. {
  1590. // Dequeue null values
  1591. _resultQueue.Dequeue ();
  1592. }
  1593. }
  1594. catch (InvalidOperationException) // Peek can raise an exception
  1595. { }
  1596. if (_resultQueue.Count > 0)
  1597. {
  1598. _eventReady.Set ();
  1599. }
  1600. }
  1601. }
  1602. }