NetDriver.cs 61 KB

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