NetDriver.cs 63 KB

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