NetDriver.cs 60 KB

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