NetDriver.cs 61 KB

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