NetDriver.cs 61 KB

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