NetDriver.cs 61 KB

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