NetDriver.cs 60 KB

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