NetDriver.cs 65 KB

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