NetDriver.cs 44 KB

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