2
0

NetDriver.cs 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583
  1. //
  2. // NetDriver.cs: The System.Console-based .NET driver, works on Windows and Unix, but is not particularly efficient.
  3. //
  4. // Authors:
  5. // Miguel de Icaza ([email protected])
  6. //
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Diagnostics;
  10. using System.Linq;
  11. using System.Runtime.InteropServices;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using NStack;
  15. namespace Terminal.Gui {
  16. internal class NetWinVTConsole {
  17. IntPtr InputHandle, OutputHandle, ErrorHandle;
  18. uint originalInputConsoleMode, originalOutputConsoleMode, originalErrorConsoleMode;
  19. public NetWinVTConsole ()
  20. {
  21. InputHandle = GetStdHandle (STD_INPUT_HANDLE);
  22. if (!GetConsoleMode (InputHandle, out uint mode)) {
  23. throw new ApplicationException ($"Failed to get input console mode, error code: {GetLastError ()}.");
  24. }
  25. originalInputConsoleMode = mode;
  26. if ((mode & ENABLE_VIRTUAL_TERMINAL_INPUT) < ENABLE_VIRTUAL_TERMINAL_INPUT) {
  27. mode |= ENABLE_VIRTUAL_TERMINAL_INPUT;
  28. if (!SetConsoleMode (InputHandle, mode)) {
  29. throw new ApplicationException ($"Failed to set input console mode, error code: {GetLastError ()}.");
  30. }
  31. }
  32. OutputHandle = GetStdHandle (STD_OUTPUT_HANDLE);
  33. if (!GetConsoleMode (OutputHandle, out mode)) {
  34. throw new ApplicationException ($"Failed to get output console mode, error code: {GetLastError ()}.");
  35. }
  36. originalOutputConsoleMode = mode;
  37. if ((mode & (ENABLE_VIRTUAL_TERMINAL_PROCESSING | DISABLE_NEWLINE_AUTO_RETURN)) < DISABLE_NEWLINE_AUTO_RETURN) {
  38. mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING | DISABLE_NEWLINE_AUTO_RETURN;
  39. if (!SetConsoleMode (OutputHandle, mode)) {
  40. throw new ApplicationException ($"Failed to set output console mode, error code: {GetLastError ()}.");
  41. }
  42. }
  43. ErrorHandle = GetStdHandle (STD_ERROR_HANDLE);
  44. if (!GetConsoleMode (ErrorHandle, out mode)) {
  45. throw new ApplicationException ($"Failed to get error console mode, error code: {GetLastError ()}.");
  46. }
  47. originalErrorConsoleMode = mode;
  48. if ((mode & (DISABLE_NEWLINE_AUTO_RETURN)) < DISABLE_NEWLINE_AUTO_RETURN) {
  49. mode |= DISABLE_NEWLINE_AUTO_RETURN;
  50. if (!SetConsoleMode (ErrorHandle, mode)) {
  51. throw new ApplicationException ($"Failed to set error console mode, error code: {GetLastError ()}.");
  52. }
  53. }
  54. }
  55. public void Cleanup ()
  56. {
  57. if (!SetConsoleMode (InputHandle, originalInputConsoleMode)) {
  58. throw new ApplicationException ($"Failed to restore input console mode, error code: {GetLastError ()}.");
  59. }
  60. if (!SetConsoleMode (OutputHandle, originalOutputConsoleMode)) {
  61. throw new ApplicationException ($"Failed to restore output console mode, error code: {GetLastError ()}.");
  62. }
  63. if (!SetConsoleMode (ErrorHandle, originalErrorConsoleMode)) {
  64. throw new ApplicationException ($"Failed to restore error console mode, error code: {GetLastError ()}.");
  65. }
  66. }
  67. const int STD_INPUT_HANDLE = -10;
  68. const int STD_OUTPUT_HANDLE = -11;
  69. const int STD_ERROR_HANDLE = -12;
  70. // Input modes.
  71. const uint ENABLE_PROCESSED_INPUT = 1;
  72. const uint ENABLE_LINE_INPUT = 2;
  73. const uint ENABLE_ECHO_INPUT = 4;
  74. const uint ENABLE_WINDOW_INPUT = 8;
  75. const uint ENABLE_MOUSE_INPUT = 16;
  76. const uint ENABLE_INSERT_MODE = 32;
  77. const uint ENABLE_QUICK_EDIT_MODE = 64;
  78. const uint ENABLE_EXTENDED_FLAGS = 128;
  79. const uint ENABLE_VIRTUAL_TERMINAL_INPUT = 512;
  80. // Output modes.
  81. const uint ENABLE_PROCESSED_OUTPUT = 1;
  82. const uint ENABLE_WRAP_AT_EOL_OUTPUT = 2;
  83. const uint ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4;
  84. const uint DISABLE_NEWLINE_AUTO_RETURN = 8;
  85. const uint ENABLE_LVB_GRID_WORLDWIDE = 10;
  86. [DllImport ("kernel32.dll", SetLastError = true)]
  87. static extern IntPtr GetStdHandle (int nStdHandle);
  88. [DllImport ("kernel32.dll")]
  89. static extern bool GetConsoleMode (IntPtr hConsoleHandle, out uint lpMode);
  90. [DllImport ("kernel32.dll")]
  91. static extern bool SetConsoleMode (IntPtr hConsoleHandle, uint dwMode);
  92. [DllImport ("kernel32.dll")]
  93. static extern uint GetLastError ();
  94. }
  95. internal class NetEvents {
  96. ManualResetEventSlim inputReady = new ManualResetEventSlim (false);
  97. ManualResetEventSlim waitForStart = new ManualResetEventSlim (false);
  98. ManualResetEventSlim winChange = new ManualResetEventSlim (false);
  99. Queue<InputResult?> inputResultQueue = new Queue<InputResult?> ();
  100. ConsoleDriver consoleDriver;
  101. volatile ConsoleKeyInfo [] cki = null;
  102. static volatile bool isEscSeq;
  103. internal CancellationTokenSource TokenSource = new CancellationTokenSource ();
  104. #if PROCESS_REQUEST
  105. bool neededProcessRequest;
  106. #endif
  107. public EscSeqReqProc EscSeqReqProc { get; } = new EscSeqReqProc ();
  108. public NetEvents (ConsoleDriver consoleDriver)
  109. {
  110. if (consoleDriver == null) {
  111. throw new ArgumentNullException ("Console driver instance must be provided.");
  112. }
  113. this.consoleDriver = consoleDriver;
  114. Task.Run (ProcessInputResultQueue, TokenSource.Token);
  115. Task.Run (CheckWinChange, TokenSource.Token);
  116. }
  117. public InputResult? ReadConsoleInput ()
  118. {
  119. while (!TokenSource.IsCancellationRequested) {
  120. waitForStart.Set ();
  121. winChange.Set ();
  122. if (inputResultQueue.Count == 0) {
  123. inputReady.Wait ();
  124. inputReady.Reset ();
  125. }
  126. #if PROCESS_REQUEST
  127. neededProcessRequest = false;
  128. #endif
  129. if (inputResultQueue.Count > 0) {
  130. return inputResultQueue.Dequeue ();
  131. }
  132. }
  133. return null;
  134. }
  135. void ProcessInputResultQueue ()
  136. {
  137. while (!TokenSource.IsCancellationRequested) {
  138. waitForStart.Wait ();
  139. waitForStart.Reset ();
  140. if (inputResultQueue.Count == 0) {
  141. GetConsoleKey ();
  142. }
  143. inputReady.Set ();
  144. }
  145. }
  146. void GetConsoleKey ()
  147. {
  148. ConsoleKey key = 0;
  149. ConsoleModifiers mod = 0;
  150. ConsoleKeyInfo newConsoleKeyInfo = default;
  151. while (!TokenSource.IsCancellationRequested) {
  152. ConsoleKeyInfo consoleKeyInfo = default;
  153. try {
  154. if (Console.KeyAvailable) {
  155. consoleKeyInfo = Console.ReadKey (true);
  156. } else {
  157. Task.Delay (100, TokenSource.Token).Wait (TokenSource.Token);
  158. if (Console.KeyAvailable) {
  159. consoleKeyInfo = Console.ReadKey (true);
  160. }
  161. }
  162. } catch (OperationCanceledException) {
  163. return;
  164. }
  165. if ((consoleKeyInfo.KeyChar == (char)Key.Esc && !isEscSeq)
  166. || (consoleKeyInfo.KeyChar != (char)Key.Esc && isEscSeq)) {
  167. if (cki == null && consoleKeyInfo.KeyChar != (char)Key.Esc && isEscSeq) {
  168. cki = EscSeqUtils.ResizeArray (new ConsoleKeyInfo ((char)Key.Esc, 0,
  169. false, false, false), cki);
  170. }
  171. isEscSeq = true;
  172. newConsoleKeyInfo = consoleKeyInfo;
  173. cki = EscSeqUtils.ResizeArray (consoleKeyInfo, cki);
  174. if (!Console.KeyAvailable) {
  175. DecodeEscSeq (ref newConsoleKeyInfo, ref key, cki, ref mod);
  176. cki = null;
  177. isEscSeq = false;
  178. break;
  179. }
  180. } else if (consoleKeyInfo.KeyChar == (char)Key.Esc && isEscSeq) {
  181. DecodeEscSeq (ref newConsoleKeyInfo, ref key, cki, ref mod);
  182. cki = null;
  183. if (!Console.KeyAvailable) {
  184. isEscSeq = false;
  185. }
  186. break;
  187. } else {
  188. if (consoleKeyInfo != default) {
  189. GetConsoleInputType (consoleKeyInfo);
  190. break;
  191. }
  192. }
  193. TokenSource.Token.ThrowIfCancellationRequested ();
  194. }
  195. }
  196. void CheckWinChange ()
  197. {
  198. while (!TokenSource.IsCancellationRequested) {
  199. winChange.Wait ();
  200. winChange.Reset ();
  201. WaitWinChange ();
  202. inputReady.Set ();
  203. }
  204. }
  205. void WaitWinChange ()
  206. {
  207. while (!TokenSource.IsCancellationRequested) {
  208. try {
  209. // Wait for a while then check if screen has changed sizes
  210. Task.Delay (500, TokenSource.Token).Wait (TokenSource.Token);
  211. } catch (OperationCanceledException) {
  212. return;
  213. }
  214. int buffHeight, buffWidth;
  215. if (((NetDriver)consoleDriver).IsWinPlatform) {
  216. buffHeight = Math.Max (Console.BufferHeight, 0);
  217. buffWidth = Math.Max (Console.BufferWidth, 0);
  218. } else {
  219. buffHeight = consoleDriver.Rows;
  220. buffWidth = consoleDriver.Cols;
  221. }
  222. if (IsWinChanged (
  223. Math.Max (Console.WindowHeight, 0),
  224. Math.Max (Console.WindowWidth, 0),
  225. buffHeight,
  226. buffWidth)) {
  227. return;
  228. }
  229. }
  230. }
  231. bool IsWinChanged (int winHeight, int winWidth, int buffHeight, int buffWidth)
  232. {
  233. if (winWidth != consoleDriver.Cols || winHeight != consoleDriver.Rows) {
  234. var w = Math.Max (winWidth, 0);
  235. var h = Math.Max (winHeight, 0);
  236. GetWindowSizeEvent (new Size (w, h));
  237. return true;
  238. }
  239. return false;
  240. }
  241. void GetWindowSizeEvent (Size size)
  242. {
  243. WindowSizeEvent windowSizeEvent = new WindowSizeEvent () {
  244. Size = size
  245. };
  246. inputResultQueue.Enqueue (new InputResult () {
  247. EventType = EventType.WindowSize,
  248. WindowSizeEvent = windowSizeEvent
  249. });
  250. }
  251. void GetConsoleInputType (ConsoleKeyInfo consoleKeyInfo)
  252. {
  253. InputResult inputResult = new InputResult {
  254. EventType = EventType.Key
  255. };
  256. MouseEvent mouseEvent = new MouseEvent ();
  257. ConsoleKeyInfo newConsoleKeyInfo = EscSeqUtils.GetConsoleInputKey (consoleKeyInfo);
  258. if (inputResult.EventType == EventType.Key) {
  259. inputResult.ConsoleKeyInfo = newConsoleKeyInfo;
  260. } else {
  261. inputResult.MouseEvent = mouseEvent;
  262. }
  263. inputResultQueue.Enqueue (inputResult);
  264. }
  265. void DecodeEscSeq (ref ConsoleKeyInfo newConsoleKeyInfo, ref ConsoleKey key, ConsoleKeyInfo [] cki, ref ConsoleModifiers mod)
  266. {
  267. string c1Control, code, terminating;
  268. string [] values;
  269. // isKeyMouse is true if it's CSI<, false otherwise
  270. bool isKeyMouse;
  271. bool isReq;
  272. List<MouseFlags> mouseFlags;
  273. Point pos;
  274. EscSeqUtils.DecodeEscSeq (EscSeqReqProc, ref newConsoleKeyInfo, ref key, cki, ref mod, out c1Control, out code, out values, out terminating, out isKeyMouse, out mouseFlags, out pos, out isReq, ProcessContinuousButtonPressed);
  275. if (isKeyMouse) {
  276. foreach (var mf in mouseFlags) {
  277. GetMouseEvent (MapMouseFlags (mf), pos);
  278. }
  279. return;
  280. } else if (isReq) {
  281. GetRequestEvent (c1Control, code, values, terminating);
  282. return;
  283. }
  284. InputResult inputResult = new InputResult {
  285. EventType = EventType.Key,
  286. ConsoleKeyInfo = newConsoleKeyInfo
  287. };
  288. inputResultQueue.Enqueue (inputResult);
  289. }
  290. void ProcessContinuousButtonPressed (MouseFlags mouseFlag, Point pos)
  291. {
  292. GetMouseEvent (MapMouseFlags (mouseFlag), pos);
  293. }
  294. MouseButtonState MapMouseFlags (MouseFlags mouseFlags)
  295. {
  296. MouseButtonState mbs = default;
  297. foreach (var flag in Enum.GetValues (mouseFlags.GetType ())) {
  298. if (mouseFlags.HasFlag ((MouseFlags)flag)) {
  299. switch (flag) {
  300. case MouseFlags.Button1Pressed:
  301. mbs |= MouseButtonState.Button1Pressed;
  302. break;
  303. case MouseFlags.Button1Released:
  304. mbs |= MouseButtonState.Button1Released;
  305. break;
  306. case MouseFlags.Button1Clicked:
  307. mbs |= MouseButtonState.Button1Clicked;
  308. break;
  309. case MouseFlags.Button1DoubleClicked:
  310. mbs |= MouseButtonState.Button1DoubleClicked;
  311. break;
  312. case MouseFlags.Button1TripleClicked:
  313. mbs |= MouseButtonState.Button1TripleClicked;
  314. break;
  315. case MouseFlags.Button2Pressed:
  316. mbs |= MouseButtonState.Button2Pressed;
  317. break;
  318. case MouseFlags.Button2Released:
  319. mbs |= MouseButtonState.Button2Released;
  320. break;
  321. case MouseFlags.Button2Clicked:
  322. mbs |= MouseButtonState.Button2Clicked;
  323. break;
  324. case MouseFlags.Button2DoubleClicked:
  325. mbs |= MouseButtonState.Button2DoubleClicked;
  326. break;
  327. case MouseFlags.Button2TripleClicked:
  328. mbs |= MouseButtonState.Button2TripleClicked;
  329. break;
  330. case MouseFlags.Button3Pressed:
  331. mbs |= MouseButtonState.Button3Pressed;
  332. break;
  333. case MouseFlags.Button3Released:
  334. mbs |= MouseButtonState.Button3Released;
  335. break;
  336. case MouseFlags.Button3Clicked:
  337. mbs |= MouseButtonState.Button3Clicked;
  338. break;
  339. case MouseFlags.Button3DoubleClicked:
  340. mbs |= MouseButtonState.Button3DoubleClicked;
  341. break;
  342. case MouseFlags.Button3TripleClicked:
  343. mbs |= MouseButtonState.Button3TripleClicked;
  344. break;
  345. case MouseFlags.WheeledUp:
  346. mbs |= MouseButtonState.ButtonWheeledUp;
  347. break;
  348. case MouseFlags.WheeledDown:
  349. mbs |= MouseButtonState.ButtonWheeledDown;
  350. break;
  351. case MouseFlags.WheeledLeft:
  352. mbs |= MouseButtonState.ButtonWheeledLeft;
  353. break;
  354. case MouseFlags.WheeledRight:
  355. mbs |= MouseButtonState.ButtonWheeledRight;
  356. break;
  357. case MouseFlags.Button4Pressed:
  358. mbs |= MouseButtonState.Button4Pressed;
  359. break;
  360. case MouseFlags.Button4Released:
  361. mbs |= MouseButtonState.Button4Released;
  362. break;
  363. case MouseFlags.Button4Clicked:
  364. mbs |= MouseButtonState.Button4Clicked;
  365. break;
  366. case MouseFlags.Button4DoubleClicked:
  367. mbs |= MouseButtonState.Button4DoubleClicked;
  368. break;
  369. case MouseFlags.Button4TripleClicked:
  370. mbs |= MouseButtonState.Button4TripleClicked;
  371. break;
  372. case MouseFlags.ButtonShift:
  373. mbs |= MouseButtonState.ButtonShift;
  374. break;
  375. case MouseFlags.ButtonCtrl:
  376. mbs |= MouseButtonState.ButtonCtrl;
  377. break;
  378. case MouseFlags.ButtonAlt:
  379. mbs |= MouseButtonState.ButtonAlt;
  380. break;
  381. case MouseFlags.ReportMousePosition:
  382. mbs |= MouseButtonState.ReportMousePosition;
  383. break;
  384. case MouseFlags.AllEvents:
  385. mbs |= MouseButtonState.AllEvents;
  386. break;
  387. }
  388. }
  389. }
  390. return mbs;
  391. }
  392. Point lastCursorPosition;
  393. void GetRequestEvent (string c1Control, string code, string [] values, string terminating)
  394. {
  395. EventType eventType = new EventType ();
  396. switch (terminating) {
  397. case "R": // Reports cursor position as CSI r ; c R
  398. Point point = new Point {
  399. X = int.Parse (values [1]) - 1,
  400. Y = int.Parse (values [0]) - 1
  401. };
  402. if (lastCursorPosition.Y != point.Y) {
  403. lastCursorPosition = point;
  404. eventType = EventType.WindowPosition;
  405. var winPositionEv = new WindowPositionEvent () {
  406. CursorPosition = point
  407. };
  408. inputResultQueue.Enqueue (new InputResult () {
  409. EventType = eventType,
  410. WindowPositionEvent = winPositionEv
  411. });
  412. } else {
  413. return;
  414. }
  415. break;
  416. default:
  417. SetRequestedEvent (c1Control, code, values, terminating);
  418. break;
  419. }
  420. inputReady.Set ();
  421. }
  422. void SetRequestedEvent (string c1Control, string code, string [] values, string terminating)
  423. {
  424. EventType eventType = EventType.RequestResponse;
  425. var requestRespEv = new RequestResponseEvent () {
  426. ResultTuple = (c1Control, code, values, terminating)
  427. };
  428. inputResultQueue.Enqueue (new InputResult () {
  429. EventType = eventType,
  430. RequestResponseEvent = requestRespEv
  431. });
  432. }
  433. void GetMouseEvent (MouseButtonState buttonState, Point pos)
  434. {
  435. MouseEvent mouseEvent = new MouseEvent () {
  436. Position = pos,
  437. ButtonState = buttonState,
  438. };
  439. inputResultQueue.Enqueue (new InputResult () {
  440. EventType = EventType.Mouse,
  441. MouseEvent = mouseEvent
  442. });
  443. inputReady.Set ();
  444. }
  445. public enum EventType {
  446. Key = 1,
  447. Mouse = 2,
  448. WindowSize = 3,
  449. WindowPosition = 4,
  450. RequestResponse = 5
  451. }
  452. [Flags]
  453. public enum MouseButtonState {
  454. Button1Pressed = 0x1,
  455. Button1Released = 0x2,
  456. Button1Clicked = 0x4,
  457. Button1DoubleClicked = 0x8,
  458. Button1TripleClicked = 0x10,
  459. Button2Pressed = 0x20,
  460. Button2Released = 0x40,
  461. Button2Clicked = 0x80,
  462. Button2DoubleClicked = 0x100,
  463. Button2TripleClicked = 0x200,
  464. Button3Pressed = 0x400,
  465. Button3Released = 0x800,
  466. Button3Clicked = 0x1000,
  467. Button3DoubleClicked = 0x2000,
  468. Button3TripleClicked = 0x4000,
  469. ButtonWheeledUp = 0x8000,
  470. ButtonWheeledDown = 0x10000,
  471. ButtonWheeledLeft = 0x20000,
  472. ButtonWheeledRight = 0x40000,
  473. Button4Pressed = 0x80000,
  474. Button4Released = 0x100000,
  475. Button4Clicked = 0x200000,
  476. Button4DoubleClicked = 0x400000,
  477. Button4TripleClicked = 0x800000,
  478. ButtonShift = 0x1000000,
  479. ButtonCtrl = 0x2000000,
  480. ButtonAlt = 0x4000000,
  481. ReportMousePosition = 0x8000000,
  482. AllEvents = -1
  483. }
  484. public struct MouseEvent {
  485. public Point Position;
  486. public MouseButtonState ButtonState;
  487. }
  488. public struct WindowSizeEvent {
  489. public Size Size;
  490. }
  491. public struct WindowPositionEvent {
  492. public int Top;
  493. public int Left;
  494. public Point CursorPosition;
  495. }
  496. public struct RequestResponseEvent {
  497. public (string c1Control, string code, string [] values, string terminating) ResultTuple;
  498. }
  499. public struct InputResult {
  500. public EventType EventType;
  501. public ConsoleKeyInfo ConsoleKeyInfo;
  502. public MouseEvent MouseEvent;
  503. public WindowSizeEvent WindowSizeEvent;
  504. public WindowPositionEvent WindowPositionEvent;
  505. public RequestResponseEvent RequestResponseEvent;
  506. }
  507. }
  508. internal class NetDriver : ConsoleDriver {
  509. const int COLOR_BLACK = 30;
  510. const int COLOR_RED = 31;
  511. const int COLOR_GREEN = 32;
  512. const int COLOR_YELLOW = 33;
  513. const int COLOR_BLUE = 34;
  514. const int COLOR_MAGENTA = 35;
  515. const int COLOR_CYAN = 36;
  516. const int COLOR_WHITE = 37;
  517. const int COLOR_BRIGHT_BLACK = 90;
  518. const int COLOR_BRIGHT_RED = 91;
  519. const int COLOR_BRIGHT_GREEN = 92;
  520. const int COLOR_BRIGHT_YELLOW = 93;
  521. const int COLOR_BRIGHT_BLUE = 94;
  522. const int COLOR_BRIGHT_MAGENTA = 95;
  523. const int COLOR_BRIGHT_CYAN = 96;
  524. const int COLOR_BRIGHT_WHITE = 97;
  525. int cols, rows, left, top;
  526. public override int Cols => cols;
  527. public override int Rows => rows;
  528. public override int Left => left;
  529. public override int Top => top;
  530. [Obsolete ("This API is deprecated", false)]
  531. public override bool EnableConsoleScrolling { get; set; }
  532. [Obsolete ("This API is deprecated", false)]
  533. public override bool HeightAsBuffer { get; set; }
  534. public NetWinVTConsole NetWinConsole { get; }
  535. public bool IsWinPlatform { get; }
  536. public override IClipboard Clipboard { get; }
  537. public override int [,,] Contents => contents;
  538. public NetDriver ()
  539. {
  540. var p = Environment.OSVersion.Platform;
  541. if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows) {
  542. IsWinPlatform = true;
  543. NetWinConsole = new NetWinVTConsole ();
  544. }
  545. if (IsWinPlatform) {
  546. Clipboard = new WindowsClipboard ();
  547. } else if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX)) {
  548. Clipboard = new MacOSXClipboard ();
  549. } else {
  550. if (CursesDriver.Is_WSL_Platform ()) {
  551. Clipboard = new WSLClipboard ();
  552. } else {
  553. Clipboard = new CursesClipboard ();
  554. }
  555. }
  556. }
  557. // The format is rows, columns and 3 values on the last column: Rune, Attribute and Dirty Flag
  558. int [,,] contents;
  559. bool [] dirtyLine;
  560. static bool sync = false;
  561. // Current row, and current col, tracked by Move/AddCh only
  562. int ccol, crow;
  563. public override void Move (int col, int row)
  564. {
  565. ccol = col;
  566. crow = row;
  567. }
  568. public override void AddRune (Rune rune)
  569. {
  570. if (contents.Length != Rows * Cols * 3) {
  571. return;
  572. }
  573. rune = MakePrintable (rune);
  574. var runeWidth = Rune.ColumnWidth (rune);
  575. var validClip = IsValidContent (ccol, crow, Clip);
  576. if (validClip) {
  577. if (runeWidth == 0 && ccol > 0) {
  578. var r = contents [crow, ccol - 1, 0];
  579. var s = new string (new char [] { (char)r, (char)rune });
  580. string sn;
  581. if (!s.IsNormalized ()) {
  582. sn = s.Normalize ();
  583. } else {
  584. sn = s;
  585. }
  586. var c = sn [0];
  587. contents [crow, ccol - 1, 0] = c;
  588. contents [crow, ccol - 1, 1] = CurrentAttribute;
  589. contents [crow, ccol - 1, 2] = 1;
  590. } else {
  591. if (runeWidth < 2 && ccol > 0
  592. && Rune.ColumnWidth ((char)contents [crow, ccol - 1, 0]) > 1) {
  593. contents [crow, ccol - 1, 0] = (int)(uint)' ';
  594. } else if (runeWidth < 2 && ccol <= Clip.Right - 1
  595. && Rune.ColumnWidth ((char)contents [crow, ccol, 0]) > 1) {
  596. contents [crow, ccol + 1, 0] = (int)(uint)' ';
  597. contents [crow, ccol + 1, 2] = 1;
  598. }
  599. if (runeWidth > 1 && ccol == Clip.Right - 1) {
  600. contents [crow, ccol, 0] = (int)(uint)' ';
  601. } else {
  602. contents [crow, ccol, 0] = (int)(uint)rune;
  603. }
  604. contents [crow, ccol, 1] = CurrentAttribute;
  605. contents [crow, ccol, 2] = 1;
  606. }
  607. dirtyLine [crow] = true;
  608. }
  609. if (runeWidth < 0 || runeWidth > 0) {
  610. ccol++;
  611. }
  612. if (runeWidth > 1) {
  613. if (validClip && ccol < Clip.Right) {
  614. contents [crow, ccol, 1] = CurrentAttribute;
  615. contents [crow, ccol, 2] = 0;
  616. }
  617. ccol++;
  618. }
  619. if (sync) {
  620. UpdateScreen ();
  621. }
  622. }
  623. public override void AddStr (ustring str)
  624. {
  625. foreach (var rune in str)
  626. AddRune (rune);
  627. }
  628. public override void End ()
  629. {
  630. mainLoop.Dispose ();
  631. if (IsWinPlatform) {
  632. NetWinConsole.Cleanup ();
  633. }
  634. StopReportingMouseMoves ();
  635. Console.ResetColor ();
  636. //Disable alternative screen buffer.
  637. Console.Out.Write ("\x1b[?1049l");
  638. //Set cursor key to cursor.
  639. Console.Out.Write ("\x1b[?25h");
  640. Console.Out.Close ();
  641. }
  642. public override Attribute MakeColor (Color foreground, Color background)
  643. {
  644. return MakeColor ((ConsoleColor)foreground, (ConsoleColor)background);
  645. }
  646. static Attribute MakeColor (ConsoleColor f, ConsoleColor b)
  647. {
  648. // Encode the colors into the int value.
  649. return new Attribute (
  650. value: ((((int)f) & 0xffff) << 16) | (((int)b) & 0xffff),
  651. foreground: (Color)f,
  652. background: (Color)b
  653. );
  654. }
  655. public override void Init (Action terminalResized)
  656. {
  657. TerminalResized = terminalResized;
  658. //Enable alternative screen buffer.
  659. Console.Out.Write ("\x1b[?1049h");
  660. //Set cursor key to application.
  661. Console.Out.Write ("\x1b[?25l");
  662. Console.TreatControlCAsInput = true;
  663. cols = Console.WindowWidth;
  664. rows = Console.WindowHeight;
  665. CurrentAttribute = MakeColor (Color.White, Color.Black);
  666. InitalizeColorSchemes ();
  667. CurrentAttribute = MakeColor (Color.White, Color.Black);
  668. InitalizeColorSchemes ();
  669. ResizeScreen ();
  670. UpdateOffScreen ();
  671. StartReportingMouseMoves ();
  672. }
  673. public override void ResizeScreen ()
  674. {
  675. if (Console.WindowHeight > 0) {
  676. // Not supported on Unix.
  677. if (IsWinPlatform) {
  678. // Can raise an exception while is still resizing.
  679. try {
  680. #pragma warning disable CA1416
  681. Console.CursorTop = 0;
  682. Console.CursorLeft = 0;
  683. Console.WindowTop = 0;
  684. Console.WindowLeft = 0;
  685. if (Console.WindowHeight > Rows) {
  686. Console.SetWindowSize (Cols, Rows);
  687. }
  688. Console.SetBufferSize (Cols, Rows);
  689. #pragma warning restore CA1416
  690. } catch (System.IO.IOException) {
  691. setClip ();
  692. } catch (ArgumentOutOfRangeException) {
  693. setClip ();
  694. }
  695. } else {
  696. Console.Out.Write ($"\x1b[8;{Rows};{Cols}t");
  697. }
  698. }
  699. setClip ();
  700. void setClip ()
  701. {
  702. Clip = new Rect (0, 0, Cols, Rows);
  703. }
  704. }
  705. public override void UpdateOffScreen ()
  706. {
  707. contents = new int [Rows, Cols, 3];
  708. dirtyLine = new bool [Rows];
  709. lock (contents) {
  710. // Can raise an exception while is still resizing.
  711. try {
  712. for (int row = 0; row < rows; row++) {
  713. for (int c = 0; c < cols; c++) {
  714. contents [row, c, 0] = ' ';
  715. contents [row, c, 1] = (ushort)Colors.TopLevel.Normal;
  716. contents [row, c, 2] = 0;
  717. dirtyLine [row] = true;
  718. }
  719. }
  720. } catch (IndexOutOfRangeException) { }
  721. }
  722. }
  723. public override Attribute MakeAttribute (Color fore, Color back)
  724. {
  725. return MakeColor ((ConsoleColor)fore, (ConsoleColor)back);
  726. }
  727. public override void Refresh ()
  728. {
  729. UpdateScreen ();
  730. UpdateCursor ();
  731. }
  732. public override void UpdateScreen ()
  733. {
  734. if (winChanging || Console.WindowHeight < 1 || contents.Length != Rows * Cols * 3 || Rows != Console.WindowHeight) {
  735. return;
  736. }
  737. int top = 0;
  738. int left = 0;
  739. int rows = Rows;
  740. int cols = Cols;
  741. System.Text.StringBuilder output = new System.Text.StringBuilder ();
  742. int redrawAttr = -1;
  743. var lastCol = -1;
  744. Console.CursorVisible = false;
  745. for (int row = top; row < rows; row++) {
  746. if (Console.WindowHeight < 1) {
  747. return;
  748. }
  749. if (!dirtyLine [row]) {
  750. continue;
  751. }
  752. if (!SetCursorPosition (0, row)) {
  753. return;
  754. }
  755. dirtyLine [row] = false;
  756. output.Clear ();
  757. for (int col = left; col < cols; col++) {
  758. lastCol = -1;
  759. var outputWidth = 0;
  760. for (; col < cols; col++) {
  761. if (contents [row, col, 2] == 0) {
  762. if (output.Length > 0) {
  763. SetCursorPosition (lastCol, row);
  764. Console.Write (output);
  765. output.Clear ();
  766. lastCol += outputWidth;
  767. outputWidth = 0;
  768. } else if (lastCol == -1) {
  769. lastCol = col;
  770. }
  771. if (lastCol + 1 < cols)
  772. lastCol++;
  773. continue;
  774. }
  775. if (lastCol == -1)
  776. lastCol = col;
  777. var attr = contents [row, col, 1];
  778. if (attr != redrawAttr) {
  779. redrawAttr = attr;
  780. output.Append (WriteAttributes (attr));
  781. }
  782. outputWidth++;
  783. var rune = contents [row, col, 0];
  784. char [] spair;
  785. if (Rune.DecodeSurrogatePair ((uint)rune, out spair)) {
  786. output.Append (spair);
  787. } else {
  788. output.Append ((char)rune);
  789. }
  790. contents [row, col, 2] = 0;
  791. }
  792. }
  793. if (output.Length > 0) {
  794. SetCursorPosition (lastCol, row);
  795. Console.Write (output);
  796. }
  797. }
  798. SetCursorPosition (0, 0);
  799. }
  800. void SetVirtualCursorPosition (int col, int row)
  801. {
  802. Console.Out.Write ($"\x1b[{row + 1};{col + 1}H");
  803. }
  804. System.Text.StringBuilder WriteAttributes (int attr)
  805. {
  806. const string CSI = "\x1b[";
  807. int bg = 0;
  808. int fg = 0;
  809. System.Text.StringBuilder sb = new System.Text.StringBuilder ();
  810. IEnumerable<int> values = Enum.GetValues (typeof (ConsoleColor))
  811. .OfType<ConsoleColor> ()
  812. .Select (s => (int)s);
  813. if (values.Contains (attr & 0xffff)) {
  814. bg = MapColors ((ConsoleColor)(attr & 0xffff), false);
  815. }
  816. if (values.Contains ((attr >> 16) & 0xffff)) {
  817. fg = MapColors ((ConsoleColor)((attr >> 16) & 0xffff));
  818. }
  819. sb.Append ($"{CSI}{bg};{fg}m");
  820. return sb;
  821. }
  822. int MapColors (ConsoleColor color, bool isForeground = true)
  823. {
  824. switch (color) {
  825. case ConsoleColor.Black:
  826. return isForeground ? COLOR_BLACK : COLOR_BLACK + 10;
  827. case ConsoleColor.DarkBlue:
  828. return isForeground ? COLOR_BLUE : COLOR_BLUE + 10;
  829. case ConsoleColor.DarkGreen:
  830. return isForeground ? COLOR_GREEN : COLOR_GREEN + 10;
  831. case ConsoleColor.DarkCyan:
  832. return isForeground ? COLOR_CYAN : COLOR_CYAN + 10;
  833. case ConsoleColor.DarkRed:
  834. return isForeground ? COLOR_RED : COLOR_RED + 10;
  835. case ConsoleColor.DarkMagenta:
  836. return isForeground ? COLOR_MAGENTA : COLOR_MAGENTA + 10;
  837. case ConsoleColor.DarkYellow:
  838. return isForeground ? COLOR_YELLOW : COLOR_YELLOW + 10;
  839. case ConsoleColor.Gray:
  840. return isForeground ? COLOR_WHITE : COLOR_WHITE + 10;
  841. case ConsoleColor.DarkGray:
  842. return isForeground ? COLOR_BRIGHT_BLACK : COLOR_BRIGHT_BLACK + 10;
  843. case ConsoleColor.Blue:
  844. return isForeground ? COLOR_BRIGHT_BLUE : COLOR_BRIGHT_BLUE + 10;
  845. case ConsoleColor.Green:
  846. return isForeground ? COLOR_BRIGHT_GREEN : COLOR_BRIGHT_GREEN + 10;
  847. case ConsoleColor.Cyan:
  848. return isForeground ? COLOR_BRIGHT_CYAN : COLOR_BRIGHT_CYAN + 10;
  849. case ConsoleColor.Red:
  850. return isForeground ? COLOR_BRIGHT_RED : COLOR_BRIGHT_RED + 10;
  851. case ConsoleColor.Magenta:
  852. return isForeground ? COLOR_BRIGHT_MAGENTA : COLOR_BRIGHT_MAGENTA + 10;
  853. case ConsoleColor.Yellow:
  854. return isForeground ? COLOR_BRIGHT_YELLOW : COLOR_BRIGHT_YELLOW + 10;
  855. case ConsoleColor.White:
  856. return isForeground ? COLOR_BRIGHT_WHITE : COLOR_BRIGHT_WHITE + 10;
  857. }
  858. return 0;
  859. }
  860. bool SetCursorPosition (int col, int row)
  861. {
  862. if (IsWinPlatform) {
  863. // Could happens that the windows is still resizing and the col is bigger than Console.WindowWidth.
  864. try {
  865. Console.SetCursorPosition (col, row);
  866. return true;
  867. } catch (Exception) {
  868. return false;
  869. }
  870. } else {
  871. SetVirtualCursorPosition (col, row);
  872. return true;
  873. }
  874. }
  875. private void SetWindowPosition (int col, int row)
  876. {
  877. top = Console.WindowTop;
  878. left = Console.WindowLeft;
  879. }
  880. private bool EnsureBufferSize ()
  881. {
  882. #pragma warning disable CA1416
  883. if (IsWinPlatform && Console.BufferHeight < Rows) {
  884. try {
  885. Console.SetBufferSize (Console.WindowWidth, Rows);
  886. } catch (Exception) {
  887. return false;
  888. }
  889. }
  890. #pragma warning restore CA1416
  891. return true;
  892. }
  893. private CursorVisibility? savedCursorVisibility;
  894. public override void UpdateCursor ()
  895. {
  896. EnsureCursorVisibility ();
  897. //Debug.WriteLine ($"Before - CursorTop: {Console.CursorTop};CursorLeft: {Console.CursorLeft}");
  898. if (ccol >= 0 && ccol < Cols && crow >= 0 && crow < Rows) {
  899. SetCursorPosition (ccol, crow);
  900. SetWindowPosition (0, crow);
  901. }
  902. //Debug.WriteLine ($"WindowTop: {Console.WindowTop};WindowLeft: {Console.WindowLeft}");
  903. //Debug.WriteLine ($"After - CursorTop: {Console.CursorTop};CursorLeft: {Console.CursorLeft}");
  904. }
  905. public override void StartReportingMouseMoves ()
  906. {
  907. Console.Out.Write (EscSeqUtils.EnableMouseEvents);
  908. }
  909. public override void StopReportingMouseMoves ()
  910. {
  911. Console.Out.Write (EscSeqUtils.DisableMouseEvents);
  912. }
  913. public override void Suspend ()
  914. {
  915. if (Environment.OSVersion.Platform != PlatformID.Unix) {
  916. return;
  917. }
  918. StopReportingMouseMoves ();
  919. Console.ResetColor ();
  920. Console.Clear ();
  921. //Disable alternative screen buffer.
  922. Console.Out.Write ("\x1b[?1049l");
  923. //Set cursor key to cursor.
  924. Console.Out.Write ("\x1b[?25h");
  925. Platform.Suspend ();
  926. //Enable alternative screen buffer.
  927. Console.Out.Write ("\x1b[?1049h");
  928. Application.Refresh ();
  929. StartReportingMouseMoves ();
  930. }
  931. public override void SetAttribute (Attribute c)
  932. {
  933. base.SetAttribute (c);
  934. }
  935. public ConsoleKeyInfo FromVKPacketToKConsoleKeyInfo (ConsoleKeyInfo consoleKeyInfo)
  936. {
  937. if (consoleKeyInfo.Key != ConsoleKey.Packet) {
  938. return consoleKeyInfo;
  939. }
  940. var mod = consoleKeyInfo.Modifiers;
  941. var shift = (mod & ConsoleModifiers.Shift) != 0;
  942. var alt = (mod & ConsoleModifiers.Alt) != 0;
  943. var control = (mod & ConsoleModifiers.Control) != 0;
  944. var keyChar = ConsoleKeyMapping.GetKeyCharFromConsoleKey (consoleKeyInfo.KeyChar, consoleKeyInfo.Modifiers, out uint virtualKey, out _);
  945. return new ConsoleKeyInfo ((char)keyChar, (ConsoleKey)virtualKey, shift, alt, control);
  946. }
  947. Key MapKey (ConsoleKeyInfo keyInfo)
  948. {
  949. MapKeyModifiers (keyInfo, (Key)keyInfo.Key);
  950. switch (keyInfo.Key) {
  951. case ConsoleKey.Escape:
  952. return MapKeyModifiers (keyInfo, Key.Esc);
  953. case ConsoleKey.Tab:
  954. return keyInfo.Modifiers == ConsoleModifiers.Shift ? Key.BackTab : Key.Tab;
  955. case ConsoleKey.Home:
  956. return MapKeyModifiers (keyInfo, Key.Home);
  957. case ConsoleKey.End:
  958. return MapKeyModifiers (keyInfo, Key.End);
  959. case ConsoleKey.LeftArrow:
  960. return MapKeyModifiers (keyInfo, Key.CursorLeft);
  961. case ConsoleKey.RightArrow:
  962. return MapKeyModifiers (keyInfo, Key.CursorRight);
  963. case ConsoleKey.UpArrow:
  964. return MapKeyModifiers (keyInfo, Key.CursorUp);
  965. case ConsoleKey.DownArrow:
  966. return MapKeyModifiers (keyInfo, Key.CursorDown);
  967. case ConsoleKey.PageUp:
  968. return MapKeyModifiers (keyInfo, Key.PageUp);
  969. case ConsoleKey.PageDown:
  970. return MapKeyModifiers (keyInfo, Key.PageDown);
  971. case ConsoleKey.Enter:
  972. return MapKeyModifiers (keyInfo, Key.Enter);
  973. case ConsoleKey.Spacebar:
  974. return MapKeyModifiers (keyInfo, keyInfo.KeyChar == 0 ? Key.Space : (Key)keyInfo.KeyChar);
  975. case ConsoleKey.Backspace:
  976. return MapKeyModifiers (keyInfo, Key.Backspace);
  977. case ConsoleKey.Delete:
  978. return MapKeyModifiers (keyInfo, Key.DeleteChar);
  979. case ConsoleKey.Insert:
  980. return MapKeyModifiers (keyInfo, Key.InsertChar);
  981. case ConsoleKey.Oem1:
  982. case ConsoleKey.Oem2:
  983. case ConsoleKey.Oem3:
  984. case ConsoleKey.Oem4:
  985. case ConsoleKey.Oem5:
  986. case ConsoleKey.Oem6:
  987. case ConsoleKey.Oem7:
  988. case ConsoleKey.Oem8:
  989. case ConsoleKey.Oem102:
  990. case ConsoleKey.OemPeriod:
  991. case ConsoleKey.OemComma:
  992. case ConsoleKey.OemPlus:
  993. case ConsoleKey.OemMinus:
  994. return (Key)((uint)keyInfo.KeyChar);
  995. }
  996. var key = keyInfo.Key;
  997. if (key >= ConsoleKey.A && key <= ConsoleKey.Z) {
  998. var delta = key - ConsoleKey.A;
  999. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  1000. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.A + delta));
  1001. }
  1002. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  1003. return (Key)(((uint)Key.AltMask) | ((uint)Key.A + delta));
  1004. }
  1005. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1006. if (keyInfo.KeyChar == 0 || (keyInfo.KeyChar != 0 && keyInfo.KeyChar >= 1 && keyInfo.KeyChar <= 26)) {
  1007. return MapKeyModifiers (keyInfo, (Key)((uint)Key.A + delta));
  1008. }
  1009. }
  1010. return (Key)((uint)keyInfo.KeyChar);
  1011. }
  1012. if (key >= ConsoleKey.D0 && key <= ConsoleKey.D9) {
  1013. var delta = key - ConsoleKey.D0;
  1014. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  1015. return (Key)(((uint)Key.AltMask) | ((uint)Key.D0 + delta));
  1016. }
  1017. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  1018. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.D0 + delta));
  1019. }
  1020. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1021. if (keyInfo.KeyChar == 0 || keyInfo.KeyChar == 30 || keyInfo.KeyChar == ((uint)Key.D0 + delta)) {
  1022. return MapKeyModifiers (keyInfo, (Key)((uint)Key.D0 + delta));
  1023. }
  1024. }
  1025. return (Key)((uint)keyInfo.KeyChar);
  1026. }
  1027. if (key >= ConsoleKey.F1 && key <= ConsoleKey.F12) {
  1028. var delta = key - ConsoleKey.F1;
  1029. if ((keyInfo.Modifiers & (ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1030. return MapKeyModifiers (keyInfo, (Key)((uint)Key.F1 + delta));
  1031. }
  1032. return (Key)((uint)Key.F1 + delta);
  1033. }
  1034. if (keyInfo.KeyChar != 0) {
  1035. return MapKeyModifiers (keyInfo, (Key)((uint)keyInfo.KeyChar));
  1036. }
  1037. return (Key)(0xffffffff);
  1038. }
  1039. KeyModifiers keyModifiers;
  1040. Key MapKeyModifiers (ConsoleKeyInfo keyInfo, Key key)
  1041. {
  1042. if (keyModifiers == null) {
  1043. keyModifiers = new KeyModifiers ();
  1044. }
  1045. Key keyMod = new Key ();
  1046. if ((keyInfo.Modifiers & ConsoleModifiers.Shift) != 0) {
  1047. keyMod = Key.ShiftMask;
  1048. keyModifiers.Shift = true;
  1049. }
  1050. if ((keyInfo.Modifiers & ConsoleModifiers.Control) != 0) {
  1051. keyMod |= Key.CtrlMask;
  1052. keyModifiers.Ctrl = true;
  1053. }
  1054. if ((keyInfo.Modifiers & ConsoleModifiers.Alt) != 0) {
  1055. keyMod |= Key.AltMask;
  1056. keyModifiers.Alt = true;
  1057. }
  1058. return keyMod != Key.Null ? keyMod | key : key;
  1059. }
  1060. Action<KeyEvent> keyHandler;
  1061. Action<KeyEvent> keyDownHandler;
  1062. Action<KeyEvent> keyUpHandler;
  1063. Action<MouseEvent> mouseHandler;
  1064. NetMainLoop mainLoop;
  1065. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
  1066. {
  1067. this.keyHandler = keyHandler;
  1068. this.keyDownHandler = keyDownHandler;
  1069. this.keyUpHandler = keyUpHandler;
  1070. this.mouseHandler = mouseHandler;
  1071. var mLoop = this.mainLoop = mainLoop.Driver as NetMainLoop;
  1072. // Note: Net doesn't support keydown/up events and thus any passed keyDown/UpHandlers will be simulated to be called.
  1073. mLoop.ProcessInput = (e) => ProcessInput (e);
  1074. }
  1075. void ProcessInput (NetEvents.InputResult inputEvent)
  1076. {
  1077. switch (inputEvent.EventType) {
  1078. case NetEvents.EventType.Key:
  1079. ConsoleKeyInfo consoleKeyInfo = inputEvent.ConsoleKeyInfo;
  1080. if (consoleKeyInfo.Key == ConsoleKey.Packet) {
  1081. consoleKeyInfo = FromVKPacketToKConsoleKeyInfo (consoleKeyInfo);
  1082. }
  1083. keyModifiers = new KeyModifiers ();
  1084. var map = MapKey (consoleKeyInfo);
  1085. if (map == (Key)0xffffffff) {
  1086. return;
  1087. }
  1088. if (map == Key.Null) {
  1089. keyDownHandler (new KeyEvent (map, keyModifiers));
  1090. keyUpHandler (new KeyEvent (map, keyModifiers));
  1091. } else {
  1092. keyDownHandler (new KeyEvent (map, keyModifiers));
  1093. keyHandler (new KeyEvent (map, keyModifiers));
  1094. keyUpHandler (new KeyEvent (map, keyModifiers));
  1095. }
  1096. break;
  1097. case NetEvents.EventType.Mouse:
  1098. mouseHandler (ToDriverMouse (inputEvent.MouseEvent));
  1099. break;
  1100. case NetEvents.EventType.WindowSize:
  1101. ChangeWin (inputEvent.WindowSizeEvent.Size);
  1102. break;
  1103. case NetEvents.EventType.RequestResponse:
  1104. Application.Top.Data = inputEvent.RequestResponseEvent.ResultTuple;
  1105. break;
  1106. }
  1107. }
  1108. volatile bool winChanging;
  1109. void ChangeWin (Size size)
  1110. {
  1111. winChanging = true;
  1112. top = 0;
  1113. left = 0;
  1114. cols = size.Width;
  1115. rows = Math.Max (size.Height, 0);
  1116. ResizeScreen ();
  1117. UpdateOffScreen ();
  1118. winChanging = false;
  1119. TerminalResized?.Invoke ();
  1120. }
  1121. MouseEvent ToDriverMouse (NetEvents.MouseEvent me)
  1122. {
  1123. //System.Diagnostics.Debug.WriteLine ($"X: {me.Position.X}; Y: {me.Position.Y}; ButtonState: {me.ButtonState}");
  1124. MouseFlags mouseFlag = 0;
  1125. if ((me.ButtonState & NetEvents.MouseButtonState.Button1Pressed) != 0) {
  1126. mouseFlag |= MouseFlags.Button1Pressed;
  1127. }
  1128. if ((me.ButtonState & NetEvents.MouseButtonState.Button1Released) != 0) {
  1129. mouseFlag |= MouseFlags.Button1Released;
  1130. }
  1131. if ((me.ButtonState & NetEvents.MouseButtonState.Button1Clicked) != 0) {
  1132. mouseFlag |= MouseFlags.Button1Clicked;
  1133. }
  1134. if ((me.ButtonState & NetEvents.MouseButtonState.Button1DoubleClicked) != 0) {
  1135. mouseFlag |= MouseFlags.Button1DoubleClicked;
  1136. }
  1137. if ((me.ButtonState & NetEvents.MouseButtonState.Button1TripleClicked) != 0) {
  1138. mouseFlag |= MouseFlags.Button1TripleClicked;
  1139. }
  1140. if ((me.ButtonState & NetEvents.MouseButtonState.Button2Pressed) != 0) {
  1141. mouseFlag |= MouseFlags.Button2Pressed;
  1142. }
  1143. if ((me.ButtonState & NetEvents.MouseButtonState.Button2Released) != 0) {
  1144. mouseFlag |= MouseFlags.Button2Released;
  1145. }
  1146. if ((me.ButtonState & NetEvents.MouseButtonState.Button2Clicked) != 0) {
  1147. mouseFlag |= MouseFlags.Button2Clicked;
  1148. }
  1149. if ((me.ButtonState & NetEvents.MouseButtonState.Button2DoubleClicked) != 0) {
  1150. mouseFlag |= MouseFlags.Button2DoubleClicked;
  1151. }
  1152. if ((me.ButtonState & NetEvents.MouseButtonState.Button2TripleClicked) != 0) {
  1153. mouseFlag |= MouseFlags.Button2TripleClicked;
  1154. }
  1155. if ((me.ButtonState & NetEvents.MouseButtonState.Button3Pressed) != 0) {
  1156. mouseFlag |= MouseFlags.Button3Pressed;
  1157. }
  1158. if ((me.ButtonState & NetEvents.MouseButtonState.Button3Released) != 0) {
  1159. mouseFlag |= MouseFlags.Button3Released;
  1160. }
  1161. if ((me.ButtonState & NetEvents.MouseButtonState.Button3Clicked) != 0) {
  1162. mouseFlag |= MouseFlags.Button3Clicked;
  1163. }
  1164. if ((me.ButtonState & NetEvents.MouseButtonState.Button3DoubleClicked) != 0) {
  1165. mouseFlag |= MouseFlags.Button3DoubleClicked;
  1166. }
  1167. if ((me.ButtonState & NetEvents.MouseButtonState.Button3TripleClicked) != 0) {
  1168. mouseFlag |= MouseFlags.Button3TripleClicked;
  1169. }
  1170. if ((me.ButtonState & NetEvents.MouseButtonState.ButtonWheeledUp) != 0) {
  1171. mouseFlag |= MouseFlags.WheeledUp;
  1172. }
  1173. if ((me.ButtonState & NetEvents.MouseButtonState.ButtonWheeledDown) != 0) {
  1174. mouseFlag |= MouseFlags.WheeledDown;
  1175. }
  1176. if ((me.ButtonState & NetEvents.MouseButtonState.ButtonWheeledLeft) != 0) {
  1177. mouseFlag |= MouseFlags.WheeledLeft;
  1178. }
  1179. if ((me.ButtonState & NetEvents.MouseButtonState.ButtonWheeledRight) != 0) {
  1180. mouseFlag |= MouseFlags.WheeledRight;
  1181. }
  1182. if ((me.ButtonState & NetEvents.MouseButtonState.Button4Pressed) != 0) {
  1183. mouseFlag |= MouseFlags.Button4Pressed;
  1184. }
  1185. if ((me.ButtonState & NetEvents.MouseButtonState.Button4Released) != 0) {
  1186. mouseFlag |= MouseFlags.Button4Released;
  1187. }
  1188. if ((me.ButtonState & NetEvents.MouseButtonState.Button4Clicked) != 0) {
  1189. mouseFlag |= MouseFlags.Button4Clicked;
  1190. }
  1191. if ((me.ButtonState & NetEvents.MouseButtonState.Button4DoubleClicked) != 0) {
  1192. mouseFlag |= MouseFlags.Button4DoubleClicked;
  1193. }
  1194. if ((me.ButtonState & NetEvents.MouseButtonState.Button4TripleClicked) != 0) {
  1195. mouseFlag |= MouseFlags.Button4TripleClicked;
  1196. }
  1197. if ((me.ButtonState & NetEvents.MouseButtonState.ReportMousePosition) != 0) {
  1198. mouseFlag |= MouseFlags.ReportMousePosition;
  1199. }
  1200. if ((me.ButtonState & NetEvents.MouseButtonState.ButtonShift) != 0) {
  1201. mouseFlag |= MouseFlags.ButtonShift;
  1202. }
  1203. if ((me.ButtonState & NetEvents.MouseButtonState.ButtonCtrl) != 0) {
  1204. mouseFlag |= MouseFlags.ButtonCtrl;
  1205. }
  1206. if ((me.ButtonState & NetEvents.MouseButtonState.ButtonAlt) != 0) {
  1207. mouseFlag |= MouseFlags.ButtonAlt;
  1208. }
  1209. return new MouseEvent () {
  1210. X = me.Position.X,
  1211. Y = me.Position.Y,
  1212. Flags = mouseFlag
  1213. };
  1214. }
  1215. /// <inheritdoc/>
  1216. public override bool GetCursorVisibility (out CursorVisibility visibility)
  1217. {
  1218. visibility = savedCursorVisibility ?? CursorVisibility.Default;
  1219. return visibility == CursorVisibility.Default;
  1220. }
  1221. /// <inheritdoc/>
  1222. public override bool SetCursorVisibility (CursorVisibility visibility)
  1223. {
  1224. savedCursorVisibility = visibility;
  1225. Console.Out.Write (visibility == CursorVisibility.Default
  1226. ? "\x1b[?25h"
  1227. : "\x1b[?25l");
  1228. return visibility == CursorVisibility.Default;
  1229. }
  1230. /// <inheritdoc/>
  1231. public override bool EnsureCursorVisibility ()
  1232. {
  1233. if (!(ccol >= 0 && crow >= 0 && ccol < Cols && crow < Rows)) {
  1234. GetCursorVisibility (out CursorVisibility cursorVisibility);
  1235. savedCursorVisibility = cursorVisibility;
  1236. SetCursorVisibility (CursorVisibility.Invisible);
  1237. return false;
  1238. }
  1239. SetCursorVisibility (savedCursorVisibility ?? CursorVisibility.Default);
  1240. return savedCursorVisibility == CursorVisibility.Default;
  1241. }
  1242. public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control)
  1243. {
  1244. NetEvents.InputResult input = new NetEvents.InputResult ();
  1245. input.EventType = NetEvents.EventType.Key;
  1246. input.ConsoleKeyInfo = new ConsoleKeyInfo (keyChar, key, shift, alt, control);
  1247. try {
  1248. ProcessInput (input);
  1249. } catch (OverflowException) { }
  1250. }
  1251. public override bool GetColors (int value, out Color foreground, out Color background)
  1252. {
  1253. bool hasColor = false;
  1254. foreground = default;
  1255. background = default;
  1256. IEnumerable<int> values = Enum.GetValues (typeof (ConsoleColor))
  1257. .OfType<ConsoleColor> ()
  1258. .Select (s => (int)s);
  1259. if (values.Contains (value & 0xffff)) {
  1260. hasColor = true;
  1261. background = (Color)(ConsoleColor)(value & 0xffff);
  1262. }
  1263. if (values.Contains ((value >> 16) & 0xffff)) {
  1264. hasColor = true;
  1265. foreground = (Color)(ConsoleColor)((value >> 16) & 0xffff);
  1266. }
  1267. return hasColor;
  1268. }
  1269. #region Unused
  1270. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  1271. {
  1272. }
  1273. public override void SetColors (short foregroundColorId, short backgroundColorId)
  1274. {
  1275. }
  1276. public override void CookMouse ()
  1277. {
  1278. }
  1279. public override void UncookMouse ()
  1280. {
  1281. }
  1282. #endregion
  1283. //
  1284. // These are for the .NET driver, but running natively on Windows, wont run
  1285. // on the Mono emulation
  1286. //
  1287. }
  1288. /// <summary>
  1289. /// Mainloop intended to be used with the .NET System.Console API, and can
  1290. /// be used on Windows and Unix, it is cross platform but lacks things like
  1291. /// file descriptor monitoring.
  1292. /// </summary>
  1293. /// <remarks>
  1294. /// This implementation is used for NetDriver.
  1295. /// </remarks>
  1296. internal class NetMainLoop : IMainLoopDriver, IDisposable {
  1297. ManualResetEventSlim keyReady = new ManualResetEventSlim (false);
  1298. ManualResetEventSlim waitForProbe = new ManualResetEventSlim (false);
  1299. Queue<NetEvents.InputResult?> inputResult = new Queue<NetEvents.InputResult?> ();
  1300. MainLoop mainLoop;
  1301. CancellationTokenSource tokenSource = new CancellationTokenSource ();
  1302. internal NetEvents netEvents;
  1303. /// <summary>
  1304. /// Invoked when a Key is pressed.
  1305. /// </summary>
  1306. public Action<NetEvents.InputResult> ProcessInput;
  1307. /// <summary>
  1308. /// Initializes the class with the console driver.
  1309. /// </summary>
  1310. /// <remarks>
  1311. /// Passing a consoleDriver is provided to capture windows resizing.
  1312. /// </remarks>
  1313. /// <param name="consoleDriver">The console driver used by this Net main loop.</param>
  1314. public NetMainLoop (ConsoleDriver consoleDriver = null)
  1315. {
  1316. if (consoleDriver == null) {
  1317. throw new ArgumentNullException ("Console driver instance must be provided.");
  1318. }
  1319. netEvents = new NetEvents (consoleDriver);
  1320. }
  1321. void NetInputHandler ()
  1322. {
  1323. while (!tokenSource.IsCancellationRequested) {
  1324. waitForProbe.Wait ();
  1325. waitForProbe.Reset ();
  1326. if (inputResult.Count == 0) {
  1327. inputResult.Enqueue (netEvents.ReadConsoleInput ());
  1328. }
  1329. while (inputResult.Count > 0 && inputResult.Peek () == null) {
  1330. inputResult.Dequeue ();
  1331. }
  1332. if (inputResult.Count > 0) {
  1333. keyReady.Set ();
  1334. }
  1335. }
  1336. }
  1337. void IMainLoopDriver.Setup (MainLoop mainLoop)
  1338. {
  1339. this.mainLoop = mainLoop;
  1340. Task.Run (NetInputHandler, tokenSource.Token);
  1341. }
  1342. void IMainLoopDriver.Wakeup ()
  1343. {
  1344. keyReady.Set ();
  1345. }
  1346. bool IMainLoopDriver.EventsPending (bool wait)
  1347. {
  1348. waitForProbe.Set ();
  1349. if (CheckTimers (wait, out var waitTimeout)) {
  1350. return true;
  1351. }
  1352. try {
  1353. if (!tokenSource.IsCancellationRequested) {
  1354. keyReady.Wait (waitTimeout, tokenSource.Token);
  1355. }
  1356. } catch (OperationCanceledException) {
  1357. return true;
  1358. } finally {
  1359. keyReady.Reset ();
  1360. }
  1361. if (!tokenSource.IsCancellationRequested) {
  1362. return inputResult.Count > 0 || CheckTimers (wait, out _);
  1363. }
  1364. tokenSource.Token.ThrowIfCancellationRequested ();
  1365. return true;
  1366. }
  1367. bool CheckTimers (bool wait, out int waitTimeout)
  1368. {
  1369. long now = DateTime.UtcNow.Ticks;
  1370. if (mainLoop.timeouts.Count > 0) {
  1371. waitTimeout = (int)((mainLoop.timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  1372. if (waitTimeout < 0)
  1373. return true;
  1374. } else {
  1375. waitTimeout = -1;
  1376. }
  1377. if (!wait)
  1378. waitTimeout = 0;
  1379. int ic;
  1380. lock (mainLoop.idleHandlers) {
  1381. ic = mainLoop.idleHandlers.Count;
  1382. }
  1383. return ic > 0;
  1384. }
  1385. void IMainLoopDriver.MainIteration ()
  1386. {
  1387. while (inputResult.Count > 0) {
  1388. ProcessInput?.Invoke (inputResult.Dequeue ().Value);
  1389. }
  1390. }
  1391. public void Dispose ()
  1392. {
  1393. tokenSource.Cancel ();
  1394. netEvents.TokenSource.Cancel ();
  1395. }
  1396. }
  1397. }