NetDriver.cs 47 KB

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