WindowsDriver.cs 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744
  1. //
  2. // WindowsDriver.cs: Windows specific driver
  3. //
  4. // HACK:
  5. // WindowsConsole/Terminal has two issues:
  6. // 1) Tearing can occur when the console is resized.
  7. // 2) The values provided during Init (and the first WindowsConsole.EventType.WindowBufferSize) are not correct.
  8. //
  9. // If HACK_CHECK_WINCHANGED is defined then we ignore WindowsConsole.EventType.WindowBufferSize events
  10. // and instead check the console size every every 500ms in a thread in WidowsMainLoop.
  11. // As of Windows 11 23H2 25947.1000 and/or WT 1.19.2682 tearing no longer occurs when using
  12. // the WindowsConsole.EventType.WindowBufferSize event. However, on Init the window size is
  13. // still incorrect so we still need this hack.
  14. #define HACK_CHECK_WINCHANGED
  15. using System.ComponentModel;
  16. using System.Diagnostics;
  17. using System.Runtime.InteropServices;
  18. using static Terminal.Gui.ConsoleDrivers.ConsoleKeyMapping;
  19. namespace Terminal.Gui;
  20. internal class WindowsConsole
  21. {
  22. internal WindowsMainLoop _mainLoop;
  23. public const int STD_OUTPUT_HANDLE = -11;
  24. public const int STD_INPUT_HANDLE = -10;
  25. private readonly nint _inputHandle;
  26. private nint _outputHandle;
  27. private nint _screenBuffer;
  28. private readonly uint _originalConsoleMode;
  29. private CursorVisibility? _initialCursorVisibility;
  30. private CursorVisibility? _currentCursorVisibility;
  31. private CursorVisibility? _pendingCursorVisibility;
  32. private readonly StringBuilder _stringBuilder = new (256 * 1024);
  33. private string _lastWrite = string.Empty;
  34. public WindowsConsole ()
  35. {
  36. _inputHandle = GetStdHandle (STD_INPUT_HANDLE);
  37. _outputHandle = GetStdHandle (STD_OUTPUT_HANDLE);
  38. _originalConsoleMode = ConsoleMode;
  39. uint newConsoleMode = _originalConsoleMode;
  40. newConsoleMode |= (uint)(ConsoleModes.EnableMouseInput | ConsoleModes.EnableExtendedFlags);
  41. newConsoleMode &= ~(uint)ConsoleModes.EnableQuickEditMode;
  42. newConsoleMode &= ~(uint)ConsoleModes.EnableProcessedInput;
  43. ConsoleMode = newConsoleMode;
  44. }
  45. private CharInfo [] _originalStdOutChars;
  46. public bool WriteToConsole (Size size, ExtendedCharInfo [] charInfoBuffer, Coord bufferSize, SmallRect window, bool force16Colors)
  47. {
  48. //Debug.WriteLine ("WriteToConsole");
  49. if (_screenBuffer == nint.Zero)
  50. {
  51. ReadFromConsoleOutput (size, bufferSize, ref window);
  52. }
  53. var result = false;
  54. if (force16Colors)
  55. {
  56. var i = 0;
  57. CharInfo [] ci = new CharInfo [charInfoBuffer.Length];
  58. foreach (ExtendedCharInfo info in charInfoBuffer)
  59. {
  60. ci [i++] = new CharInfo
  61. {
  62. Char = new CharUnion { UnicodeChar = info.Char },
  63. Attributes =
  64. (ushort)((int)info.Attribute.Foreground.GetClosestNamedColor16 () | ((int)info.Attribute.Background.GetClosestNamedColor16 () << 4))
  65. };
  66. }
  67. result = WriteConsoleOutput (_screenBuffer, ci, bufferSize, new Coord { X = window.Left, Y = window.Top }, ref window);
  68. }
  69. else
  70. {
  71. _stringBuilder.Clear ();
  72. _stringBuilder.Append (EscSeqUtils.CSI_SaveCursorPosition);
  73. _stringBuilder.Append (EscSeqUtils.CSI_SetCursorPosition (0, 0));
  74. Attribute? prev = null;
  75. foreach (ExtendedCharInfo info in charInfoBuffer)
  76. {
  77. Attribute attr = info.Attribute;
  78. if (attr != prev)
  79. {
  80. prev = attr;
  81. _stringBuilder.Append (EscSeqUtils.CSI_SetForegroundColorRGB (attr.Foreground.R, attr.Foreground.G, attr.Foreground.B));
  82. _stringBuilder.Append (EscSeqUtils.CSI_SetBackgroundColorRGB (attr.Background.R, attr.Background.G, attr.Background.B));
  83. }
  84. if (info.Char != '\x1b')
  85. {
  86. if (!info.Empty)
  87. {
  88. _stringBuilder.Append (info.Char);
  89. }
  90. }
  91. else
  92. {
  93. _stringBuilder.Append (' ');
  94. }
  95. }
  96. _stringBuilder.Append (EscSeqUtils.CSI_RestoreCursorPosition);
  97. _stringBuilder.Append (EscSeqUtils.CSI_HideCursor);
  98. var s = _stringBuilder.ToString ();
  99. // TODO: requires extensive testing if we go down this route
  100. // If console output has changed
  101. if (s != _lastWrite)
  102. {
  103. // supply console with the new content
  104. result = WriteConsole (_screenBuffer, s, (uint)s.Length, out uint _, nint.Zero);
  105. }
  106. _lastWrite = s;
  107. foreach (var sixel in Application.Sixel)
  108. {
  109. SetCursorPosition (new Coord ((short)sixel.ScreenPosition.X, (short)sixel.ScreenPosition.Y));
  110. WriteConsole (_screenBuffer, sixel.SixelData, (uint)sixel.SixelData.Length, out uint _, nint.Zero);
  111. }
  112. }
  113. if (!result)
  114. {
  115. int err = Marshal.GetLastWin32Error ();
  116. if (err != 0)
  117. {
  118. throw new Win32Exception (err);
  119. }
  120. }
  121. return result;
  122. }
  123. internal bool WriteANSI (string ansi)
  124. {
  125. if (WriteConsole (_screenBuffer, ansi, (uint)ansi.Length, out uint _, nint.Zero))
  126. {
  127. // Flush the output to make sure it's sent immediately
  128. return FlushFileBuffers (_screenBuffer);
  129. }
  130. return false;
  131. }
  132. public void ReadFromConsoleOutput (Size size, Coord coords, ref SmallRect window)
  133. {
  134. _screenBuffer = CreateConsoleScreenBuffer (
  135. DesiredAccess.GenericRead | DesiredAccess.GenericWrite,
  136. ShareMode.FileShareRead | ShareMode.FileShareWrite,
  137. nint.Zero,
  138. 1,
  139. nint.Zero
  140. );
  141. if (_screenBuffer == INVALID_HANDLE_VALUE)
  142. {
  143. int err = Marshal.GetLastWin32Error ();
  144. if (err != 0)
  145. {
  146. throw new Win32Exception (err);
  147. }
  148. }
  149. SetInitialCursorVisibility ();
  150. if (!SetConsoleActiveScreenBuffer (_screenBuffer))
  151. {
  152. throw new Win32Exception (Marshal.GetLastWin32Error ());
  153. }
  154. _originalStdOutChars = new CharInfo [size.Height * size.Width];
  155. if (!ReadConsoleOutput (_screenBuffer, _originalStdOutChars, coords, new Coord { X = 0, Y = 0 }, ref window))
  156. {
  157. throw new Win32Exception (Marshal.GetLastWin32Error ());
  158. }
  159. }
  160. public bool SetCursorPosition (Coord position)
  161. {
  162. return SetConsoleCursorPosition (_screenBuffer, position);
  163. }
  164. public void SetInitialCursorVisibility ()
  165. {
  166. if (_initialCursorVisibility.HasValue == false && GetCursorVisibility (out CursorVisibility visibility))
  167. {
  168. _initialCursorVisibility = visibility;
  169. }
  170. }
  171. public bool GetCursorVisibility (out CursorVisibility visibility)
  172. {
  173. if (_screenBuffer == nint.Zero)
  174. {
  175. visibility = CursorVisibility.Invisible;
  176. return false;
  177. }
  178. if (!GetConsoleCursorInfo (_screenBuffer, out ConsoleCursorInfo info))
  179. {
  180. int err = Marshal.GetLastWin32Error ();
  181. if (err != 0)
  182. {
  183. throw new Win32Exception (err);
  184. }
  185. visibility = CursorVisibility.Default;
  186. return false;
  187. }
  188. if (!info.bVisible)
  189. {
  190. visibility = CursorVisibility.Invisible;
  191. }
  192. else if (info.dwSize > 50)
  193. {
  194. visibility = CursorVisibility.Default;
  195. }
  196. else
  197. {
  198. visibility = CursorVisibility.Default;
  199. }
  200. return true;
  201. }
  202. public bool EnsureCursorVisibility ()
  203. {
  204. if (_initialCursorVisibility.HasValue && _pendingCursorVisibility.HasValue && SetCursorVisibility (_pendingCursorVisibility.Value))
  205. {
  206. _pendingCursorVisibility = null;
  207. return true;
  208. }
  209. return false;
  210. }
  211. public void ForceRefreshCursorVisibility ()
  212. {
  213. if (_currentCursorVisibility.HasValue)
  214. {
  215. _pendingCursorVisibility = _currentCursorVisibility;
  216. _currentCursorVisibility = null;
  217. }
  218. }
  219. public bool SetCursorVisibility (CursorVisibility visibility)
  220. {
  221. if (_initialCursorVisibility.HasValue == false)
  222. {
  223. _pendingCursorVisibility = visibility;
  224. return false;
  225. }
  226. if (_currentCursorVisibility.HasValue == false || _currentCursorVisibility.Value != visibility)
  227. {
  228. var info = new ConsoleCursorInfo
  229. {
  230. dwSize = (uint)visibility & 0x00FF,
  231. bVisible = ((uint)visibility & 0xFF00) != 0
  232. };
  233. if (!SetConsoleCursorInfo (_screenBuffer, ref info))
  234. {
  235. return false;
  236. }
  237. _currentCursorVisibility = visibility;
  238. }
  239. return true;
  240. }
  241. public void Cleanup ()
  242. {
  243. if (_initialCursorVisibility.HasValue)
  244. {
  245. SetCursorVisibility (_initialCursorVisibility.Value);
  246. }
  247. SetConsoleOutputWindow (out _);
  248. ConsoleMode = _originalConsoleMode;
  249. _outputHandle = CreateConsoleScreenBuffer (
  250. DesiredAccess.GenericRead | DesiredAccess.GenericWrite,
  251. ShareMode.FileShareRead | ShareMode.FileShareWrite,
  252. nint.Zero,
  253. 1,
  254. nint.Zero
  255. );
  256. if (!SetConsoleActiveScreenBuffer (_outputHandle))
  257. {
  258. int err = Marshal.GetLastWin32Error ();
  259. Console.WriteLine ("Error: {0}", err);
  260. }
  261. if (_screenBuffer != nint.Zero)
  262. {
  263. CloseHandle (_screenBuffer);
  264. }
  265. _screenBuffer = nint.Zero;
  266. }
  267. internal Size GetConsoleBufferWindow (out Point position)
  268. {
  269. if (_screenBuffer == nint.Zero)
  270. {
  271. position = Point.Empty;
  272. return Size.Empty;
  273. }
  274. var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
  275. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  276. if (!GetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi))
  277. {
  278. //throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  279. position = Point.Empty;
  280. return Size.Empty;
  281. }
  282. Size sz = new (
  283. csbi.srWindow.Right - csbi.srWindow.Left + 1,
  284. csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
  285. position = new (csbi.srWindow.Left, csbi.srWindow.Top);
  286. return sz;
  287. }
  288. internal Size GetConsoleOutputWindow (out Point position)
  289. {
  290. var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
  291. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  292. if (!GetConsoleScreenBufferInfoEx (_outputHandle, ref csbi))
  293. {
  294. throw new Win32Exception (Marshal.GetLastWin32Error ());
  295. }
  296. Size sz = new (
  297. csbi.srWindow.Right - csbi.srWindow.Left + 1,
  298. csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
  299. position = new (csbi.srWindow.Left, csbi.srWindow.Top);
  300. return sz;
  301. }
  302. internal Size SetConsoleWindow (short cols, short rows)
  303. {
  304. var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
  305. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  306. if (!GetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi))
  307. {
  308. throw new Win32Exception (Marshal.GetLastWin32Error ());
  309. }
  310. Coord maxWinSize = GetLargestConsoleWindowSize (_screenBuffer);
  311. short newCols = Math.Min (cols, maxWinSize.X);
  312. short newRows = Math.Min (rows, maxWinSize.Y);
  313. csbi.dwSize = new Coord (newCols, Math.Max (newRows, (short)1));
  314. csbi.srWindow = new SmallRect (0, 0, newCols, newRows);
  315. csbi.dwMaximumWindowSize = new Coord (newCols, newRows);
  316. if (!SetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi))
  317. {
  318. throw new Win32Exception (Marshal.GetLastWin32Error ());
  319. }
  320. var winRect = new SmallRect (0, 0, (short)(newCols - 1), (short)Math.Max (newRows - 1, 0));
  321. if (!SetConsoleWindowInfo (_outputHandle, true, ref winRect))
  322. {
  323. //throw new System.ComponentModel.Win32Exception (Marshal.GetLastWin32Error ());
  324. return new (cols, rows);
  325. }
  326. SetConsoleOutputWindow (csbi);
  327. return new (winRect.Right + 1, newRows - 1 < 0 ? 0 : winRect.Bottom + 1);
  328. }
  329. private void SetConsoleOutputWindow (CONSOLE_SCREEN_BUFFER_INFOEX csbi)
  330. {
  331. if (_screenBuffer != nint.Zero && !SetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi))
  332. {
  333. throw new Win32Exception (Marshal.GetLastWin32Error ());
  334. }
  335. }
  336. internal Size SetConsoleOutputWindow (out Point position)
  337. {
  338. if (_screenBuffer == nint.Zero)
  339. {
  340. position = Point.Empty;
  341. return Size.Empty;
  342. }
  343. var csbi = new CONSOLE_SCREEN_BUFFER_INFOEX ();
  344. csbi.cbSize = (uint)Marshal.SizeOf (csbi);
  345. if (!GetConsoleScreenBufferInfoEx (_screenBuffer, ref csbi))
  346. {
  347. throw new Win32Exception (Marshal.GetLastWin32Error ());
  348. }
  349. Size sz = new (
  350. csbi.srWindow.Right - csbi.srWindow.Left + 1,
  351. Math.Max (csbi.srWindow.Bottom - csbi.srWindow.Top + 1, 0));
  352. position = new (csbi.srWindow.Left, csbi.srWindow.Top);
  353. SetConsoleOutputWindow (csbi);
  354. var winRect = new SmallRect (0, 0, (short)(sz.Width - 1), (short)Math.Max (sz.Height - 1, 0));
  355. if (!SetConsoleScreenBufferInfoEx (_outputHandle, ref csbi))
  356. {
  357. throw new Win32Exception (Marshal.GetLastWin32Error ());
  358. }
  359. if (!SetConsoleWindowInfo (_outputHandle, true, ref winRect))
  360. {
  361. throw new Win32Exception (Marshal.GetLastWin32Error ());
  362. }
  363. return sz;
  364. }
  365. private uint ConsoleMode
  366. {
  367. get
  368. {
  369. GetConsoleMode (_inputHandle, out uint v);
  370. return v;
  371. }
  372. set => SetConsoleMode (_inputHandle, value);
  373. }
  374. [Flags]
  375. public enum ConsoleModes : uint
  376. {
  377. EnableProcessedInput = 1,
  378. EnableMouseInput = 16,
  379. EnableQuickEditMode = 64,
  380. EnableExtendedFlags = 128
  381. }
  382. [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
  383. public struct KeyEventRecord
  384. {
  385. [FieldOffset (0)]
  386. [MarshalAs (UnmanagedType.Bool)]
  387. public bool bKeyDown;
  388. [FieldOffset (4)]
  389. [MarshalAs (UnmanagedType.U2)]
  390. public ushort wRepeatCount;
  391. [FieldOffset (6)]
  392. [MarshalAs (UnmanagedType.U2)]
  393. public VK wVirtualKeyCode;
  394. [FieldOffset (8)]
  395. [MarshalAs (UnmanagedType.U2)]
  396. public ushort wVirtualScanCode;
  397. [FieldOffset (10)]
  398. public char UnicodeChar;
  399. [FieldOffset (12)]
  400. [MarshalAs (UnmanagedType.U4)]
  401. public ControlKeyState dwControlKeyState;
  402. public readonly override string ToString ()
  403. {
  404. return
  405. $"[KeyEventRecord({(bKeyDown ? "down" : "up")},{wRepeatCount},{wVirtualKeyCode},{wVirtualScanCode},{new Rune (UnicodeChar).MakePrintable ()},{dwControlKeyState})]";
  406. }
  407. }
  408. [Flags]
  409. public enum ButtonState
  410. {
  411. NoButtonPressed = 0,
  412. Button1Pressed = 1,
  413. Button2Pressed = 4,
  414. Button3Pressed = 8,
  415. Button4Pressed = 16,
  416. RightmostButtonPressed = 2
  417. }
  418. [Flags]
  419. public enum ControlKeyState
  420. {
  421. NoControlKeyPressed = 0,
  422. RightAltPressed = 1,
  423. LeftAltPressed = 2,
  424. RightControlPressed = 4,
  425. LeftControlPressed = 8,
  426. ShiftPressed = 16,
  427. NumlockOn = 32,
  428. ScrolllockOn = 64,
  429. CapslockOn = 128,
  430. EnhancedKey = 256
  431. }
  432. [Flags]
  433. public enum EventFlags
  434. {
  435. NoEvent = 0,
  436. MouseMoved = 1,
  437. DoubleClick = 2,
  438. MouseWheeled = 4,
  439. MouseHorizontalWheeled = 8
  440. }
  441. [StructLayout (LayoutKind.Explicit)]
  442. public struct MouseEventRecord
  443. {
  444. [FieldOffset (0)]
  445. public Coord MousePosition;
  446. [FieldOffset (4)]
  447. public ButtonState ButtonState;
  448. [FieldOffset (8)]
  449. public ControlKeyState ControlKeyState;
  450. [FieldOffset (12)]
  451. public EventFlags EventFlags;
  452. public readonly override string ToString () { return $"[Mouse{MousePosition},{ButtonState},{ControlKeyState},{EventFlags}]"; }
  453. }
  454. public struct WindowBufferSizeRecord
  455. {
  456. public Coord _size;
  457. public WindowBufferSizeRecord (short x, short y) { _size = new Coord (x, y); }
  458. public readonly override string ToString () { return $"[WindowBufferSize{_size}"; }
  459. }
  460. [StructLayout (LayoutKind.Sequential)]
  461. public struct MenuEventRecord
  462. {
  463. public uint dwCommandId;
  464. }
  465. [StructLayout (LayoutKind.Sequential)]
  466. public struct FocusEventRecord
  467. {
  468. public uint bSetFocus;
  469. }
  470. public enum EventType : ushort
  471. {
  472. Focus = 0x10,
  473. Key = 0x1,
  474. Menu = 0x8,
  475. Mouse = 2,
  476. WindowBufferSize = 4
  477. }
  478. [StructLayout (LayoutKind.Explicit)]
  479. public struct InputRecord
  480. {
  481. [FieldOffset (0)]
  482. public EventType EventType;
  483. [FieldOffset (4)]
  484. public KeyEventRecord KeyEvent;
  485. [FieldOffset (4)]
  486. public MouseEventRecord MouseEvent;
  487. [FieldOffset (4)]
  488. public WindowBufferSizeRecord WindowBufferSizeEvent;
  489. [FieldOffset (4)]
  490. public MenuEventRecord MenuEvent;
  491. [FieldOffset (4)]
  492. public FocusEventRecord FocusEvent;
  493. public readonly override string ToString ()
  494. {
  495. return EventType switch
  496. {
  497. EventType.Focus => FocusEvent.ToString (),
  498. EventType.Key => KeyEvent.ToString (),
  499. EventType.Menu => MenuEvent.ToString (),
  500. EventType.Mouse => MouseEvent.ToString (),
  501. EventType.WindowBufferSize => WindowBufferSizeEvent.ToString (),
  502. _ => "Unknown event type: " + EventType
  503. };
  504. }
  505. }
  506. [Flags]
  507. private enum ShareMode : uint
  508. {
  509. FileShareRead = 1,
  510. FileShareWrite = 2
  511. }
  512. [Flags]
  513. private enum DesiredAccess : uint
  514. {
  515. GenericRead = 2147483648,
  516. GenericWrite = 1073741824
  517. }
  518. [StructLayout (LayoutKind.Sequential)]
  519. public struct ConsoleScreenBufferInfo
  520. {
  521. public Coord dwSize;
  522. public Coord dwCursorPosition;
  523. public ushort wAttributes;
  524. public SmallRect srWindow;
  525. public Coord dwMaximumWindowSize;
  526. }
  527. [StructLayout (LayoutKind.Sequential)]
  528. public struct Coord
  529. {
  530. public short X;
  531. public short Y;
  532. public Coord (short x, short y)
  533. {
  534. X = x;
  535. Y = y;
  536. }
  537. public readonly override string ToString () { return $"({X},{Y})"; }
  538. }
  539. [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
  540. public struct CharUnion
  541. {
  542. [FieldOffset (0)]
  543. public char UnicodeChar;
  544. [FieldOffset (0)]
  545. public byte AsciiChar;
  546. }
  547. [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
  548. public struct CharInfo
  549. {
  550. [FieldOffset (0)]
  551. public CharUnion Char;
  552. [FieldOffset (2)]
  553. public ushort Attributes;
  554. }
  555. public struct ExtendedCharInfo
  556. {
  557. public char Char { get; set; }
  558. public Attribute Attribute { get; set; }
  559. public bool Empty { get; set; } // TODO: Temp hack until virtual terminal sequences
  560. public ExtendedCharInfo (char character, Attribute attribute)
  561. {
  562. Char = character;
  563. Attribute = attribute;
  564. Empty = false;
  565. }
  566. }
  567. [StructLayout (LayoutKind.Sequential)]
  568. public struct SmallRect
  569. {
  570. public short Left;
  571. public short Top;
  572. public short Right;
  573. public short Bottom;
  574. public SmallRect (short left, short top, short right, short bottom)
  575. {
  576. Left = left;
  577. Top = top;
  578. Right = right;
  579. Bottom = bottom;
  580. }
  581. public static void MakeEmpty (ref SmallRect rect) { rect.Left = -1; }
  582. public static void Update (ref SmallRect rect, short col, short row)
  583. {
  584. if (rect.Left == -1)
  585. {
  586. rect.Left = rect.Right = col;
  587. rect.Bottom = rect.Top = row;
  588. return;
  589. }
  590. if (col >= rect.Left && col <= rect.Right && row >= rect.Top && row <= rect.Bottom)
  591. {
  592. return;
  593. }
  594. if (col < rect.Left)
  595. {
  596. rect.Left = col;
  597. }
  598. if (col > rect.Right)
  599. {
  600. rect.Right = col;
  601. }
  602. if (row < rect.Top)
  603. {
  604. rect.Top = row;
  605. }
  606. if (row > rect.Bottom)
  607. {
  608. rect.Bottom = row;
  609. }
  610. }
  611. public readonly override string ToString () { return $"Left={Left},Top={Top},Right={Right},Bottom={Bottom}"; }
  612. }
  613. [StructLayout (LayoutKind.Sequential)]
  614. public struct ConsoleKeyInfoEx
  615. {
  616. public ConsoleKeyInfo ConsoleKeyInfo;
  617. public bool CapsLock;
  618. public bool NumLock;
  619. public bool ScrollLock;
  620. public ConsoleKeyInfoEx (ConsoleKeyInfo consoleKeyInfo, bool capslock, bool numlock, bool scrolllock)
  621. {
  622. ConsoleKeyInfo = consoleKeyInfo;
  623. CapsLock = capslock;
  624. NumLock = numlock;
  625. ScrollLock = scrolllock;
  626. }
  627. /// <summary>
  628. /// Prints a ConsoleKeyInfoEx structure
  629. /// </summary>
  630. /// <param name="ex"></param>
  631. /// <returns></returns>
  632. public readonly string ToString (ConsoleKeyInfoEx ex)
  633. {
  634. var ke = new Key ((KeyCode)ex.ConsoleKeyInfo.KeyChar);
  635. var sb = new StringBuilder ();
  636. sb.Append ($"Key: {(KeyCode)ex.ConsoleKeyInfo.Key} ({ex.ConsoleKeyInfo.Key})");
  637. sb.Append ((ex.ConsoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0 ? " | Shift" : string.Empty);
  638. sb.Append ((ex.ConsoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0 ? " | Control" : string.Empty);
  639. sb.Append ((ex.ConsoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0 ? " | Alt" : string.Empty);
  640. sb.Append ($", KeyChar: {ke.AsRune.MakePrintable ()} ({(uint)ex.ConsoleKeyInfo.KeyChar}) ");
  641. sb.Append (ex.CapsLock ? "caps," : string.Empty);
  642. sb.Append (ex.NumLock ? "num," : string.Empty);
  643. sb.Append (ex.ScrollLock ? "scroll," : string.Empty);
  644. string s = sb.ToString ().TrimEnd (',').TrimEnd (' ');
  645. return $"[ConsoleKeyInfoEx({s})]";
  646. }
  647. }
  648. [DllImport ("kernel32.dll", SetLastError = true)]
  649. private static extern nint GetStdHandle (int nStdHandle);
  650. [DllImport ("kernel32.dll", SetLastError = true)]
  651. private static extern bool CloseHandle (nint handle);
  652. [DllImport ("kernel32.dll", SetLastError = true)]
  653. public static extern bool PeekConsoleInput (nint hConsoleInput, out InputRecord lpBuffer, uint nLength, out uint lpNumberOfEventsRead);
  654. [DllImport ("kernel32.dll", EntryPoint = "ReadConsoleInputW", CharSet = CharSet.Unicode)]
  655. public static extern bool ReadConsoleInput (
  656. nint hConsoleInput,
  657. out InputRecord lpBuffer,
  658. uint nLength,
  659. out uint lpNumberOfEventsRead
  660. );
  661. [DllImport ("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
  662. private static extern bool ReadConsoleOutput (
  663. nint hConsoleOutput,
  664. [Out] CharInfo [] lpBuffer,
  665. Coord dwBufferSize,
  666. Coord dwBufferCoord,
  667. ref SmallRect lpReadRegion
  668. );
  669. // TODO: This API is obsolete. See https://learn.microsoft.com/en-us/windows/console/writeconsoleoutput
  670. [DllImport ("kernel32.dll", EntryPoint = "WriteConsoleOutputW", SetLastError = true, CharSet = CharSet.Unicode)]
  671. private static extern bool WriteConsoleOutput (
  672. nint hConsoleOutput,
  673. CharInfo [] lpBuffer,
  674. Coord dwBufferSize,
  675. Coord dwBufferCoord,
  676. ref SmallRect lpWriteRegion
  677. );
  678. [DllImport ("kernel32.dll", EntryPoint = "WriteConsole", SetLastError = true, CharSet = CharSet.Unicode)]
  679. private static extern bool WriteConsole (
  680. nint hConsoleOutput,
  681. string lpbufer,
  682. uint NumberOfCharsToWriten,
  683. out uint lpNumberOfCharsWritten,
  684. nint lpReserved
  685. );
  686. [DllImport ("kernel32.dll", SetLastError = true)]
  687. static extern bool FlushFileBuffers (nint hFile);
  688. [DllImport ("kernel32.dll")]
  689. private static extern bool SetConsoleCursorPosition (nint hConsoleOutput, Coord dwCursorPosition);
  690. [StructLayout (LayoutKind.Sequential)]
  691. public struct ConsoleCursorInfo
  692. {
  693. /// <summary>
  694. /// The percentage of the character cell that is filled by the cursor.This value is between 1 and 100.
  695. /// The cursor appearance varies, ranging from completely filling the cell to showing up as a horizontal
  696. /// line at the bottom of the cell.
  697. /// </summary>
  698. public uint dwSize;
  699. public bool bVisible;
  700. }
  701. [DllImport ("kernel32.dll", SetLastError = true)]
  702. private static extern bool SetConsoleCursorInfo (nint hConsoleOutput, [In] ref ConsoleCursorInfo lpConsoleCursorInfo);
  703. [DllImport ("kernel32.dll", SetLastError = true)]
  704. private static extern bool GetConsoleCursorInfo (nint hConsoleOutput, out ConsoleCursorInfo lpConsoleCursorInfo);
  705. [DllImport ("kernel32.dll")]
  706. private static extern bool GetConsoleMode (nint hConsoleHandle, out uint lpMode);
  707. [DllImport ("kernel32.dll")]
  708. private static extern bool SetConsoleMode (nint hConsoleHandle, uint dwMode);
  709. [DllImport ("kernel32.dll", SetLastError = true)]
  710. private static extern nint CreateConsoleScreenBuffer (
  711. DesiredAccess dwDesiredAccess,
  712. ShareMode dwShareMode,
  713. nint secutiryAttributes,
  714. uint flags,
  715. nint screenBufferData
  716. );
  717. internal static nint INVALID_HANDLE_VALUE = new (-1);
  718. [DllImport ("kernel32.dll", SetLastError = true)]
  719. private static extern bool SetConsoleActiveScreenBuffer (nint Handle);
  720. [DllImport ("kernel32.dll", SetLastError = true)]
  721. private static extern bool GetNumberOfConsoleInputEvents (nint handle, out uint lpcNumberOfEvents);
  722. internal uint GetNumberOfConsoleInputEvents ()
  723. {
  724. if (!GetNumberOfConsoleInputEvents (_inputHandle, out uint numOfEvents))
  725. {
  726. Console.WriteLine ($"Error: {Marshal.GetLastWin32Error ()}");
  727. return 0;
  728. }
  729. return numOfEvents;
  730. }
  731. [DllImport ("kernel32.dll", SetLastError = true)]
  732. private static extern bool FlushConsoleInputBuffer (nint handle);
  733. internal void FlushConsoleInputBuffer ()
  734. {
  735. if (!FlushConsoleInputBuffer (_inputHandle))
  736. {
  737. Console.WriteLine ($"Error: {Marshal.GetLastWin32Error ()}");
  738. }
  739. }
  740. private int _retries;
  741. public InputRecord [] ReadConsoleInput ()
  742. {
  743. const int bufferSize = 1;
  744. InputRecord inputRecord = default;
  745. uint numberEventsRead = 0;
  746. StringBuilder ansiSequence = new StringBuilder ();
  747. bool readingSequence = false;
  748. while (true)
  749. {
  750. try
  751. {
  752. // Peek to check if there is any input available
  753. if (PeekConsoleInput (_inputHandle, out _, bufferSize, out uint eventsRead) && eventsRead > 0)
  754. {
  755. // Read the input since it is available
  756. ReadConsoleInput (
  757. _inputHandle,
  758. out inputRecord,
  759. bufferSize,
  760. out numberEventsRead);
  761. if (inputRecord.EventType == EventType.Key)
  762. {
  763. KeyEventRecord keyEvent = inputRecord.KeyEvent;
  764. if (keyEvent.bKeyDown)
  765. {
  766. char inputChar = keyEvent.UnicodeChar;
  767. // Check if input is part of an ANSI escape sequence
  768. if (inputChar == '\u001B') // Escape character
  769. {
  770. // Peek to check if there is any input available with key event and bKeyDown
  771. if (PeekConsoleInput (_inputHandle, out InputRecord peekRecord, bufferSize, out eventsRead) && eventsRead > 0)
  772. {
  773. if (peekRecord is { EventType: EventType.Key, KeyEvent.bKeyDown: true })
  774. {
  775. // It's really an ANSI request response
  776. readingSequence = true;
  777. ansiSequence.Clear (); // Start a new sequence
  778. ansiSequence.Append (inputChar);
  779. continue;
  780. }
  781. }
  782. }
  783. else if (readingSequence)
  784. {
  785. ansiSequence.Append (inputChar);
  786. // Check if the sequence has ended with an expected command terminator
  787. if (_mainLoop.EscSeqRequests is { } && _mainLoop.EscSeqRequests.HasResponse (inputChar.ToString (), out EscSeqReqStatus seqReqStatus))
  788. {
  789. // Finished reading the sequence and remove the enqueued request
  790. _mainLoop.EscSeqRequests.Remove (seqReqStatus);
  791. lock (seqReqStatus!.AnsiRequest._responseLock)
  792. {
  793. seqReqStatus.AnsiRequest.Response = ansiSequence.ToString ();
  794. seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, seqReqStatus.AnsiRequest.Response);
  795. // Clear the terminator for not be enqueued
  796. inputRecord = default (InputRecord);
  797. }
  798. }
  799. continue;
  800. }
  801. }
  802. }
  803. }
  804. if (EscSeqUtils.IncompleteCkInfos is null && _mainLoop.EscSeqRequests is { Statuses.Count: > 0 })
  805. {
  806. if (_retries > 1)
  807. {
  808. _mainLoop.EscSeqRequests.Statuses.TryDequeue (out EscSeqReqStatus seqReqStatus);
  809. lock (seqReqStatus!.AnsiRequest._responseLock)
  810. {
  811. seqReqStatus.AnsiRequest.Response = string.Empty;
  812. seqReqStatus.AnsiRequest.RaiseResponseFromInput (seqReqStatus.AnsiRequest, string.Empty);
  813. }
  814. _retries = 0;
  815. }
  816. else
  817. {
  818. _retries++;
  819. }
  820. }
  821. else
  822. {
  823. _retries = 0;
  824. }
  825. return numberEventsRead == 0
  826. ? null
  827. : [inputRecord];
  828. }
  829. catch (Exception)
  830. {
  831. return null;
  832. }
  833. }
  834. }
  835. #if false // Not needed on the constructor. Perhaps could be used on resizing. To study.
  836. [DllImport ("kernel32.dll", ExactSpelling = true)]
  837. static extern IntPtr GetConsoleWindow ();
  838. [DllImport ("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  839. static extern bool ShowWindow (IntPtr hWnd, int nCmdShow);
  840. public const int HIDE = 0;
  841. public const int MAXIMIZE = 3;
  842. public const int MINIMIZE = 6;
  843. public const int RESTORE = 9;
  844. internal void ShowWindow (int state)
  845. {
  846. IntPtr thisConsole = GetConsoleWindow ();
  847. ShowWindow (thisConsole, state);
  848. }
  849. #endif
  850. // See: https://github.com/gui-cs/Terminal.Gui/issues/357
  851. [StructLayout (LayoutKind.Sequential)]
  852. public struct CONSOLE_SCREEN_BUFFER_INFOEX
  853. {
  854. public uint cbSize;
  855. public Coord dwSize;
  856. public Coord dwCursorPosition;
  857. public ushort wAttributes;
  858. public SmallRect srWindow;
  859. public Coord dwMaximumWindowSize;
  860. public ushort wPopupAttributes;
  861. public bool bFullscreenSupported;
  862. [MarshalAs (UnmanagedType.ByValArray, SizeConst = 16)]
  863. public COLORREF [] ColorTable;
  864. }
  865. [StructLayout (LayoutKind.Explicit, Size = 4)]
  866. public struct COLORREF
  867. {
  868. public COLORREF (byte r, byte g, byte b)
  869. {
  870. Value = 0;
  871. R = r;
  872. G = g;
  873. B = b;
  874. }
  875. public COLORREF (uint value)
  876. {
  877. R = 0;
  878. G = 0;
  879. B = 0;
  880. Value = value & 0x00FFFFFF;
  881. }
  882. [FieldOffset (0)]
  883. public byte R;
  884. [FieldOffset (1)]
  885. public byte G;
  886. [FieldOffset (2)]
  887. public byte B;
  888. [FieldOffset (0)]
  889. public uint Value;
  890. }
  891. [DllImport ("kernel32.dll", SetLastError = true)]
  892. private static extern bool GetConsoleScreenBufferInfoEx (nint hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFOEX csbi);
  893. [DllImport ("kernel32.dll", SetLastError = true)]
  894. private static extern bool SetConsoleScreenBufferInfoEx (nint hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFOEX ConsoleScreenBufferInfo);
  895. [DllImport ("kernel32.dll", SetLastError = true)]
  896. private static extern bool SetConsoleWindowInfo (
  897. nint hConsoleOutput,
  898. bool bAbsolute,
  899. [In] ref SmallRect lpConsoleWindow
  900. );
  901. [DllImport ("kernel32.dll", SetLastError = true)]
  902. private static extern Coord GetLargestConsoleWindowSize (
  903. nint hConsoleOutput
  904. );
  905. }
  906. internal class WindowsDriver : ConsoleDriver
  907. {
  908. private readonly bool _isWindowsTerminal;
  909. private WindowsConsole.SmallRect _damageRegion;
  910. private bool _isButtonDoubleClicked;
  911. private bool _isButtonPressed;
  912. private bool _isButtonReleased;
  913. private bool _isOneFingerDoubleClicked;
  914. private WindowsConsole.ButtonState? _lastMouseButtonPressed;
  915. private WindowsMainLoop _mainLoopDriver;
  916. private WindowsConsole.ExtendedCharInfo [] _outputBuffer;
  917. private Point? _point;
  918. private Point _pointMove;
  919. private bool _processButtonClick;
  920. public WindowsDriver ()
  921. {
  922. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  923. {
  924. WinConsole = new WindowsConsole ();
  925. // otherwise we're probably running in unit tests
  926. Clipboard = new WindowsClipboard ();
  927. }
  928. else
  929. {
  930. Clipboard = new FakeDriver.FakeClipboard ();
  931. }
  932. // TODO: if some other Windows-based terminal supports true color, update this logic to not
  933. // force 16color mode (.e.g ConEmu which really doesn't work well at all).
  934. _isWindowsTerminal = _isWindowsTerminal =
  935. Environment.GetEnvironmentVariable ("WT_SESSION") is { } || Environment.GetEnvironmentVariable ("VSAPPIDNAME") != null;
  936. if (!_isWindowsTerminal)
  937. {
  938. Force16Colors = true;
  939. }
  940. }
  941. public override bool SupportsTrueColor => RunningUnitTests || (Environment.OSVersion.Version.Build >= 14931 && _isWindowsTerminal);
  942. public WindowsConsole WinConsole { get; private set; }
  943. public WindowsConsole.KeyEventRecord FromVKPacketToKeyEventRecord (WindowsConsole.KeyEventRecord keyEvent)
  944. {
  945. if (keyEvent.wVirtualKeyCode != (VK)ConsoleKey.Packet)
  946. {
  947. return keyEvent;
  948. }
  949. var mod = new ConsoleModifiers ();
  950. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed))
  951. {
  952. mod |= ConsoleModifiers.Shift;
  953. }
  954. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed)
  955. || keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed))
  956. {
  957. mod |= ConsoleModifiers.Alt;
  958. }
  959. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed)
  960. || keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed))
  961. {
  962. mod |= ConsoleModifiers.Control;
  963. }
  964. var cKeyInfo = new ConsoleKeyInfo (
  965. keyEvent.UnicodeChar,
  966. (ConsoleKey)keyEvent.wVirtualKeyCode,
  967. mod.HasFlag (ConsoleModifiers.Shift),
  968. mod.HasFlag (ConsoleModifiers.Alt),
  969. mod.HasFlag (ConsoleModifiers.Control));
  970. cKeyInfo = DecodeVKPacketToKConsoleKeyInfo (cKeyInfo);
  971. uint scanCode = GetScanCodeFromConsoleKeyInfo (cKeyInfo);
  972. return new WindowsConsole.KeyEventRecord
  973. {
  974. UnicodeChar = cKeyInfo.KeyChar,
  975. bKeyDown = keyEvent.bKeyDown,
  976. dwControlKeyState = keyEvent.dwControlKeyState,
  977. wRepeatCount = keyEvent.wRepeatCount,
  978. wVirtualKeyCode = (VK)cKeyInfo.Key,
  979. wVirtualScanCode = (ushort)scanCode
  980. };
  981. }
  982. public override bool IsRuneSupported (Rune rune) { return base.IsRuneSupported (rune) && rune.IsBmp; }
  983. public override void Refresh ()
  984. {
  985. UpdateScreen ();
  986. //WinConsole?.SetInitialCursorVisibility ();
  987. UpdateCursor ();
  988. }
  989. public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control)
  990. {
  991. var input = new WindowsConsole.InputRecord
  992. {
  993. EventType = WindowsConsole.EventType.Key
  994. };
  995. var keyEvent = new WindowsConsole.KeyEventRecord
  996. {
  997. bKeyDown = true
  998. };
  999. var controlKey = new WindowsConsole.ControlKeyState ();
  1000. if (shift)
  1001. {
  1002. controlKey |= WindowsConsole.ControlKeyState.ShiftPressed;
  1003. keyEvent.UnicodeChar = '\0';
  1004. keyEvent.wVirtualKeyCode = VK.SHIFT;
  1005. }
  1006. if (alt)
  1007. {
  1008. controlKey |= WindowsConsole.ControlKeyState.LeftAltPressed;
  1009. controlKey |= WindowsConsole.ControlKeyState.RightAltPressed;
  1010. keyEvent.UnicodeChar = '\0';
  1011. keyEvent.wVirtualKeyCode = VK.MENU;
  1012. }
  1013. if (control)
  1014. {
  1015. controlKey |= WindowsConsole.ControlKeyState.LeftControlPressed;
  1016. controlKey |= WindowsConsole.ControlKeyState.RightControlPressed;
  1017. keyEvent.UnicodeChar = '\0';
  1018. keyEvent.wVirtualKeyCode = VK.CONTROL;
  1019. }
  1020. keyEvent.dwControlKeyState = controlKey;
  1021. input.KeyEvent = keyEvent;
  1022. if (shift || alt || control)
  1023. {
  1024. ProcessInput (input);
  1025. }
  1026. keyEvent.UnicodeChar = keyChar;
  1027. //if ((uint)key < 255) {
  1028. // keyEvent.wVirtualKeyCode = (ushort)key;
  1029. //} else {
  1030. // keyEvent.wVirtualKeyCode = '\0';
  1031. //}
  1032. keyEvent.wVirtualKeyCode = (VK)key;
  1033. input.KeyEvent = keyEvent;
  1034. try
  1035. {
  1036. ProcessInput (input);
  1037. }
  1038. catch (OverflowException)
  1039. { }
  1040. finally
  1041. {
  1042. keyEvent.bKeyDown = false;
  1043. input.KeyEvent = keyEvent;
  1044. ProcessInput (input);
  1045. }
  1046. }
  1047. private readonly ManualResetEventSlim _waitAnsiResponse = new (false);
  1048. private readonly CancellationTokenSource _ansiResponseTokenSource = new ();
  1049. /// <inheritdoc/>
  1050. public override string WriteAnsiRequest (AnsiEscapeSequenceRequest ansiRequest)
  1051. {
  1052. if (_mainLoopDriver is null)
  1053. {
  1054. return string.Empty;
  1055. }
  1056. var response = string.Empty;
  1057. try
  1058. {
  1059. lock (ansiRequest._responseLock)
  1060. {
  1061. ansiRequest.ResponseFromInput += (s, e) =>
  1062. {
  1063. Debug.Assert (s == ansiRequest);
  1064. ansiRequest.Response = response = e;
  1065. _waitAnsiResponse.Set ();
  1066. };
  1067. _mainLoopDriver.EscSeqRequests.Add (ansiRequest, this);
  1068. _mainLoopDriver._forceRead = true;
  1069. }
  1070. if (!_ansiResponseTokenSource.IsCancellationRequested)
  1071. {
  1072. _mainLoopDriver._waitForProbe.Set ();
  1073. _waitAnsiResponse.Wait (_ansiResponseTokenSource.Token);
  1074. }
  1075. }
  1076. catch (OperationCanceledException)
  1077. {
  1078. return string.Empty;
  1079. }
  1080. finally
  1081. {
  1082. _mainLoopDriver._forceRead = false;
  1083. if (_mainLoopDriver.EscSeqRequests.Statuses.TryPeek (out EscSeqReqStatus request))
  1084. {
  1085. if (_mainLoopDriver.EscSeqRequests.Statuses.Count > 0
  1086. && string.IsNullOrEmpty (request.AnsiRequest.Response))
  1087. {
  1088. // Bad request or no response at all
  1089. _mainLoopDriver.EscSeqRequests.Statuses.TryDequeue (out _);
  1090. }
  1091. }
  1092. _waitAnsiResponse.Reset ();
  1093. }
  1094. return response;
  1095. }
  1096. public override void WriteRaw (string ansi)
  1097. {
  1098. WinConsole?.WriteANSI (ansi);
  1099. }
  1100. #region Not Implemented
  1101. public override void Suspend () { throw new NotImplementedException (); }
  1102. #endregion
  1103. public WindowsConsole.ConsoleKeyInfoEx ToConsoleKeyInfoEx (WindowsConsole.KeyEventRecord keyEvent)
  1104. {
  1105. WindowsConsole.ControlKeyState state = keyEvent.dwControlKeyState;
  1106. bool shift = (state & WindowsConsole.ControlKeyState.ShiftPressed) != 0;
  1107. bool alt = (state & (WindowsConsole.ControlKeyState.LeftAltPressed | WindowsConsole.ControlKeyState.RightAltPressed)) != 0;
  1108. bool control = (state & (WindowsConsole.ControlKeyState.LeftControlPressed | WindowsConsole.ControlKeyState.RightControlPressed)) != 0;
  1109. bool capslock = (state & WindowsConsole.ControlKeyState.CapslockOn) != 0;
  1110. bool numlock = (state & WindowsConsole.ControlKeyState.NumlockOn) != 0;
  1111. bool scrolllock = (state & WindowsConsole.ControlKeyState.ScrolllockOn) != 0;
  1112. var cki = new ConsoleKeyInfo (keyEvent.UnicodeChar, (ConsoleKey)keyEvent.wVirtualKeyCode, shift, alt, control);
  1113. return new WindowsConsole.ConsoleKeyInfoEx (cki, capslock, numlock, scrolllock);
  1114. }
  1115. #region Cursor Handling
  1116. private CursorVisibility? _cachedCursorVisibility;
  1117. public override void UpdateCursor ()
  1118. {
  1119. if (Col < 0 || Row < 0 || Col >= Cols || Row >= Rows)
  1120. {
  1121. GetCursorVisibility (out CursorVisibility cursorVisibility);
  1122. _cachedCursorVisibility = cursorVisibility;
  1123. SetCursorVisibility (CursorVisibility.Invisible);
  1124. return;
  1125. }
  1126. var position = new WindowsConsole.Coord
  1127. {
  1128. X = (short)Col,
  1129. Y = (short)Row
  1130. };
  1131. if (Force16Colors)
  1132. {
  1133. WinConsole?.SetCursorPosition (position);
  1134. }
  1135. else
  1136. {
  1137. var sb = new StringBuilder ();
  1138. sb.Append (EscSeqUtils.CSI_SetCursorPosition (position.Y + 1, position.X + 1));
  1139. WinConsole?.WriteANSI (sb.ToString ());
  1140. }
  1141. if (_cachedCursorVisibility is { })
  1142. {
  1143. SetCursorVisibility (_cachedCursorVisibility.Value);
  1144. }
  1145. //EnsureCursorVisibility ();
  1146. }
  1147. /// <inheritdoc/>
  1148. public override bool GetCursorVisibility (out CursorVisibility visibility)
  1149. {
  1150. if (WinConsole is { })
  1151. {
  1152. return WinConsole.GetCursorVisibility (out visibility);
  1153. }
  1154. visibility = _cachedCursorVisibility ?? CursorVisibility.Default;
  1155. return true;
  1156. }
  1157. /// <inheritdoc/>
  1158. public override bool SetCursorVisibility (CursorVisibility visibility)
  1159. {
  1160. _cachedCursorVisibility = visibility;
  1161. if (Force16Colors)
  1162. {
  1163. return WinConsole is null || WinConsole.SetCursorVisibility (visibility);
  1164. }
  1165. else
  1166. {
  1167. var sb = new StringBuilder ();
  1168. sb.Append (visibility != CursorVisibility.Invisible ? EscSeqUtils.CSI_ShowCursor : EscSeqUtils.CSI_HideCursor);
  1169. return WinConsole?.WriteANSI (sb.ToString ()) ?? false;
  1170. }
  1171. }
  1172. /// <inheritdoc/>
  1173. public override bool EnsureCursorVisibility ()
  1174. {
  1175. if (Force16Colors)
  1176. {
  1177. return WinConsole is null || WinConsole.EnsureCursorVisibility ();
  1178. }
  1179. else
  1180. {
  1181. var sb = new StringBuilder ();
  1182. sb.Append (_cachedCursorVisibility != CursorVisibility.Invisible ? EscSeqUtils.CSI_ShowCursor : EscSeqUtils.CSI_HideCursor);
  1183. return WinConsole?.WriteANSI (sb.ToString ()) ?? false;
  1184. }
  1185. //if (!(Col >= 0 && Row >= 0 && Col < Cols && Row < Rows))
  1186. //{
  1187. // GetCursorVisibility (out CursorVisibility cursorVisibility);
  1188. // _cachedCursorVisibility = cursorVisibility;
  1189. // SetCursorVisibility (CursorVisibility.Invisible);
  1190. // return false;
  1191. //}
  1192. //SetCursorVisibility (_cachedCursorVisibility ?? CursorVisibility.Default);
  1193. //return _cachedCursorVisibility == CursorVisibility.Default;
  1194. }
  1195. #endregion Cursor Handling
  1196. public override void UpdateScreen ()
  1197. {
  1198. Size windowSize = WinConsole?.GetConsoleBufferWindow (out Point _) ?? new Size (Cols, Rows);
  1199. if (!windowSize.IsEmpty && (windowSize.Width != Cols || windowSize.Height != Rows))
  1200. {
  1201. return;
  1202. }
  1203. var bufferCoords = new WindowsConsole.Coord
  1204. {
  1205. X = (short)Cols, //Clip.Width,
  1206. Y = (short)Rows, //Clip.Height
  1207. };
  1208. for (var row = 0; row < Rows; row++)
  1209. {
  1210. if (!_dirtyLines [row])
  1211. {
  1212. continue;
  1213. }
  1214. _dirtyLines [row] = false;
  1215. for (var col = 0; col < Cols; col++)
  1216. {
  1217. int position = row * Cols + col;
  1218. _outputBuffer [position].Attribute = Contents [row, col].Attribute.GetValueOrDefault ();
  1219. if (Contents [row, col].IsDirty == false)
  1220. {
  1221. _outputBuffer [position].Empty = true;
  1222. _outputBuffer [position].Char = (char)Rune.ReplacementChar.Value;
  1223. continue;
  1224. }
  1225. _outputBuffer [position].Empty = false;
  1226. if (Contents [row, col].Rune.IsBmp)
  1227. {
  1228. _outputBuffer [position].Char = (char)Contents [row, col].Rune.Value;
  1229. }
  1230. else
  1231. {
  1232. //_outputBuffer [position].Empty = true;
  1233. _outputBuffer [position].Char = (char)Rune.ReplacementChar.Value;
  1234. if (Contents [row, col].Rune.GetColumns () > 1 && col + 1 < Cols)
  1235. {
  1236. // TODO: This is a hack to deal with non-BMP and wide characters.
  1237. col++;
  1238. position = row * Cols + col;
  1239. _outputBuffer [position].Empty = false;
  1240. _outputBuffer [position].Char = ' ';
  1241. }
  1242. }
  1243. }
  1244. }
  1245. _damageRegion = new WindowsConsole.SmallRect
  1246. {
  1247. Top = 0,
  1248. Left = 0,
  1249. Bottom = (short)Rows,
  1250. Right = (short)Cols
  1251. };
  1252. if (!RunningUnitTests
  1253. && WinConsole != null
  1254. && !WinConsole.WriteToConsole (new (Cols, Rows), _outputBuffer, bufferCoords, _damageRegion, Force16Colors))
  1255. {
  1256. int err = Marshal.GetLastWin32Error ();
  1257. if (err != 0)
  1258. {
  1259. throw new Win32Exception (err);
  1260. }
  1261. }
  1262. WindowsConsole.SmallRect.MakeEmpty (ref _damageRegion);
  1263. }
  1264. internal override void End ()
  1265. {
  1266. if (_mainLoopDriver is { })
  1267. {
  1268. #if HACK_CHECK_WINCHANGED
  1269. _mainLoopDriver.WinChanged -= ChangeWin;
  1270. #endif
  1271. }
  1272. _mainLoopDriver = null;
  1273. WinConsole?.Cleanup ();
  1274. WinConsole = null;
  1275. if (!RunningUnitTests && _isWindowsTerminal)
  1276. {
  1277. // Disable alternative screen buffer.
  1278. Console.Out.Write (EscSeqUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll);
  1279. }
  1280. }
  1281. internal override MainLoop Init ()
  1282. {
  1283. _mainLoopDriver = new WindowsMainLoop (this);
  1284. if (!RunningUnitTests)
  1285. {
  1286. try
  1287. {
  1288. if (WinConsole is { })
  1289. {
  1290. // BUGBUG: The results from GetConsoleOutputWindow are incorrect when called from Init.
  1291. // Our thread in WindowsMainLoop.CheckWin will get the correct results. See #if HACK_CHECK_WINCHANGED
  1292. Size winSize = WinConsole.GetConsoleOutputWindow (out Point pos);
  1293. Cols = winSize.Width;
  1294. Rows = winSize.Height;
  1295. }
  1296. WindowsConsole.SmallRect.MakeEmpty (ref _damageRegion);
  1297. if (_isWindowsTerminal)
  1298. {
  1299. Console.Out.Write (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll);
  1300. }
  1301. }
  1302. catch (Win32Exception e)
  1303. {
  1304. // We are being run in an environment that does not support a console
  1305. // such as a unit test, or a pipe.
  1306. Debug.WriteLine ($"Likely running unit tests. Setting WinConsole to null so we can test it elsewhere. Exception: {e}");
  1307. WinConsole = null;
  1308. }
  1309. }
  1310. CurrentAttribute = new Attribute (Color.White, Color.Black);
  1311. _outputBuffer = new WindowsConsole.ExtendedCharInfo [Rows * Cols];
  1312. // CONCURRENCY: Unsynchronized access to Clip is not safe.
  1313. Clip = new (0, 0, Cols, Rows);
  1314. _damageRegion = new WindowsConsole.SmallRect
  1315. {
  1316. Top = 0,
  1317. Left = 0,
  1318. Bottom = (short)Rows,
  1319. Right = (short)Cols
  1320. };
  1321. ClearContents ();
  1322. #if HACK_CHECK_WINCHANGED
  1323. _mainLoopDriver.WinChanged = ChangeWin;
  1324. #endif
  1325. WinConsole?.SetInitialCursorVisibility ();
  1326. return new MainLoop (_mainLoopDriver);
  1327. }
  1328. internal void ProcessInput (WindowsConsole.InputRecord inputEvent)
  1329. {
  1330. switch (inputEvent.EventType)
  1331. {
  1332. case WindowsConsole.EventType.Key:
  1333. if (inputEvent.KeyEvent.wVirtualKeyCode == (VK)ConsoleKey.Packet)
  1334. {
  1335. // Used to pass Unicode characters as if they were keystrokes.
  1336. // The VK_PACKET key is the low word of a 32-bit
  1337. // Virtual Key value used for non-keyboard input methods.
  1338. inputEvent.KeyEvent = FromVKPacketToKeyEventRecord (inputEvent.KeyEvent);
  1339. }
  1340. WindowsConsole.ConsoleKeyInfoEx keyInfo = ToConsoleKeyInfoEx (inputEvent.KeyEvent);
  1341. //Debug.WriteLine ($"event: KBD: {GetKeyboardLayoutName()} {inputEvent.ToString ()} {keyInfo.ToString (keyInfo)}");
  1342. KeyCode map = MapKey (keyInfo);
  1343. if (map == KeyCode.Null)
  1344. {
  1345. break;
  1346. }
  1347. if (inputEvent.KeyEvent.bKeyDown)
  1348. {
  1349. // Avoid sending repeat key down events
  1350. OnKeyDown (new Key (map));
  1351. }
  1352. else
  1353. {
  1354. OnKeyUp (new Key (map));
  1355. }
  1356. break;
  1357. case WindowsConsole.EventType.Mouse:
  1358. MouseEventArgs me = ToDriverMouse (inputEvent.MouseEvent);
  1359. if (me is null || me.Flags == MouseFlags.None)
  1360. {
  1361. break;
  1362. }
  1363. OnMouseEvent (me);
  1364. if (_processButtonClick)
  1365. {
  1366. OnMouseEvent (new ()
  1367. {
  1368. Position = me.Position,
  1369. Flags = ProcessButtonClick (inputEvent.MouseEvent)
  1370. });
  1371. }
  1372. break;
  1373. case WindowsConsole.EventType.Focus:
  1374. break;
  1375. #if !HACK_CHECK_WINCHANGED
  1376. case WindowsConsole.EventType.WindowBufferSize:
  1377. Cols = inputEvent.WindowBufferSizeEvent._size.X;
  1378. Rows = inputEvent.WindowBufferSizeEvent._size.Y;
  1379. ResizeScreen ();
  1380. ClearContents ();
  1381. TerminalResized.Invoke ();
  1382. break;
  1383. #endif
  1384. }
  1385. }
  1386. #if HACK_CHECK_WINCHANGED
  1387. private void ChangeWin (object s, SizeChangedEventArgs e)
  1388. {
  1389. if (e.Size is null)
  1390. {
  1391. return;
  1392. }
  1393. int w = e.Size.Value.Width;
  1394. if (w == Cols - 3 && e.Size.Value.Height < Rows)
  1395. {
  1396. w += 3;
  1397. }
  1398. Left = 0;
  1399. Top = 0;
  1400. Cols = e.Size.Value.Width;
  1401. Rows = e.Size.Value.Height;
  1402. if (!RunningUnitTests)
  1403. {
  1404. Size newSize = WinConsole.SetConsoleWindow (
  1405. (short)Math.Max (w, 16),
  1406. (short)Math.Max (e.Size.Value.Height, 0));
  1407. Cols = newSize.Width;
  1408. Rows = newSize.Height;
  1409. }
  1410. ResizeScreen ();
  1411. ClearContents ();
  1412. OnSizeChanged (new SizeChangedEventArgs (new (Cols, Rows)));
  1413. }
  1414. #endif
  1415. private KeyCode MapKey (WindowsConsole.ConsoleKeyInfoEx keyInfoEx)
  1416. {
  1417. ConsoleKeyInfo keyInfo = keyInfoEx.ConsoleKeyInfo;
  1418. switch (keyInfo.Key)
  1419. {
  1420. case ConsoleKey.D0:
  1421. case ConsoleKey.D1:
  1422. case ConsoleKey.D2:
  1423. case ConsoleKey.D3:
  1424. case ConsoleKey.D4:
  1425. case ConsoleKey.D5:
  1426. case ConsoleKey.D6:
  1427. case ConsoleKey.D7:
  1428. case ConsoleKey.D8:
  1429. case ConsoleKey.D9:
  1430. case ConsoleKey.NumPad0:
  1431. case ConsoleKey.NumPad1:
  1432. case ConsoleKey.NumPad2:
  1433. case ConsoleKey.NumPad3:
  1434. case ConsoleKey.NumPad4:
  1435. case ConsoleKey.NumPad5:
  1436. case ConsoleKey.NumPad6:
  1437. case ConsoleKey.NumPad7:
  1438. case ConsoleKey.NumPad8:
  1439. case ConsoleKey.NumPad9:
  1440. case ConsoleKey.Oem1:
  1441. case ConsoleKey.Oem2:
  1442. case ConsoleKey.Oem3:
  1443. case ConsoleKey.Oem4:
  1444. case ConsoleKey.Oem5:
  1445. case ConsoleKey.Oem6:
  1446. case ConsoleKey.Oem7:
  1447. case ConsoleKey.Oem8:
  1448. case ConsoleKey.Oem102:
  1449. case ConsoleKey.Multiply:
  1450. case ConsoleKey.Add:
  1451. case ConsoleKey.Separator:
  1452. case ConsoleKey.Subtract:
  1453. case ConsoleKey.Decimal:
  1454. case ConsoleKey.Divide:
  1455. case ConsoleKey.OemPeriod:
  1456. case ConsoleKey.OemComma:
  1457. case ConsoleKey.OemPlus:
  1458. case ConsoleKey.OemMinus:
  1459. // These virtual key codes are mapped differently depending on the keyboard layout in use.
  1460. // We use the Win32 API to map them to the correct character.
  1461. uint mapResult = MapVKtoChar ((VK)keyInfo.Key);
  1462. if (mapResult == 0)
  1463. {
  1464. // There is no mapping - this should not happen
  1465. Debug.Assert (mapResult != 0, $@"Unable to map the virtual key code {keyInfo.Key}.");
  1466. return KeyCode.Null;
  1467. }
  1468. // An un-shifted character value is in the low order word of the return value.
  1469. var mappedChar = (char)(mapResult & 0x0000FFFF);
  1470. if (keyInfo.KeyChar == 0)
  1471. {
  1472. // If the keyChar is 0, keyInfo.Key value is not a printable character.
  1473. // Dead keys (diacritics) are indicated by setting the top bit of the return value.
  1474. if ((mapResult & 0x80000000) != 0)
  1475. {
  1476. // Dead key (e.g. Oem2 '~'/'^' on POR keyboard)
  1477. // Option 1: Throw it out.
  1478. // - Apps will never see the dead keys
  1479. // - If user presses a key that can be combined with the dead key ('a'), the right thing happens (app will see '�').
  1480. // - NOTE: With Dead Keys, KeyDown != KeyUp. The KeyUp event will have just the base char ('a').
  1481. // - If user presses dead key again, the right thing happens (app will see `~~`)
  1482. // - This is what Notepad etc... appear to do
  1483. // Option 2: Expand the API to indicate the KeyCode is a dead key
  1484. // - Enables apps to do their own dead key processing
  1485. // - Adds complexity; no dev has asked for this (yet).
  1486. // We choose Option 1 for now.
  1487. return KeyCode.Null;
  1488. // Note: Ctrl-Deadkey (like Oem3 '`'/'~` on ENG) can't be supported.
  1489. // Sadly, the charVal is just the deadkey and subsequent key events do not contain
  1490. // any info that the previous event was a deadkey.
  1491. // Note WT does not support Ctrl-Deadkey either.
  1492. }
  1493. if (keyInfo.Modifiers != 0)
  1494. {
  1495. // These Oem keys have well-defined chars. We ensure the representative char is used.
  1496. // If we don't do this, then on some keyboard layouts the wrong char is
  1497. // returned (e.g. on ENG OemPlus un-shifted is =, not +). This is important
  1498. // for key persistence ("Ctrl++" vs. "Ctrl+=").
  1499. mappedChar = keyInfo.Key switch
  1500. {
  1501. ConsoleKey.OemPeriod => '.',
  1502. ConsoleKey.OemComma => ',',
  1503. ConsoleKey.OemPlus => '+',
  1504. ConsoleKey.OemMinus => '-',
  1505. _ => mappedChar
  1506. };
  1507. }
  1508. // Return the mappedChar with modifiers. Because mappedChar is un-shifted, if Shift was down
  1509. // we should keep it
  1510. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)mappedChar);
  1511. }
  1512. // KeyChar is printable
  1513. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt) && keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control))
  1514. {
  1515. // AltGr support - AltGr is equivalent to Ctrl+Alt - the correct char is in KeyChar
  1516. return (KeyCode)keyInfo.KeyChar;
  1517. }
  1518. if (keyInfo.Modifiers != ConsoleModifiers.Shift)
  1519. {
  1520. // If Shift wasn't down we don't need to do anything but return the mappedChar
  1521. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)mappedChar);
  1522. }
  1523. // Strip off Shift - We got here because they KeyChar from Windows is the shifted char (e.g. "�")
  1524. // and passing on Shift would be redundant.
  1525. return MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.KeyChar);
  1526. }
  1527. // A..Z are special cased:
  1528. // - Alone, they represent lowercase a...z
  1529. // - With ShiftMask they are A..Z
  1530. // - If CapsLock is on the above is reversed.
  1531. // - If Alt and/or Ctrl are present, treat as upper case
  1532. if (keyInfo.Key is >= ConsoleKey.A and <= ConsoleKey.Z)
  1533. {
  1534. if (keyInfo.KeyChar == 0)
  1535. {
  1536. // KeyChar is not printable - possibly an AltGr key?
  1537. // AltGr support - AltGr is equivalent to Ctrl+Alt
  1538. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt) && keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control))
  1539. {
  1540. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(uint)keyInfo.Key);
  1541. }
  1542. }
  1543. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt) || keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control))
  1544. {
  1545. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(uint)keyInfo.Key);
  1546. }
  1547. if ((keyInfo.Modifiers == ConsoleModifiers.Shift) ^ keyInfoEx.CapsLock)
  1548. {
  1549. // If (ShiftMask is on and CapsLock is off) or (ShiftMask is off and CapsLock is on) add the ShiftMask
  1550. if (char.IsUpper (keyInfo.KeyChar))
  1551. {
  1552. // Always return the KeyChar because it may be an Á, À with Oem1, etc
  1553. return (KeyCode)keyInfo.KeyChar | KeyCode.ShiftMask;
  1554. }
  1555. }
  1556. // Always return the KeyChar because it may be an á, à with Oem1, etc
  1557. return (KeyCode)keyInfo.KeyChar;
  1558. }
  1559. // Handle control keys whose VK codes match the related ASCII value (those below ASCII 33) like ESC
  1560. if (Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key))
  1561. {
  1562. // If the key is JUST a modifier, return it as just that key
  1563. if (keyInfo.Key == (ConsoleKey)VK.SHIFT)
  1564. { // Shift 16
  1565. return KeyCode.ShiftMask;
  1566. }
  1567. if (keyInfo.Key == (ConsoleKey)VK.CONTROL)
  1568. { // Ctrl 17
  1569. return KeyCode.CtrlMask;
  1570. }
  1571. if (keyInfo.Key == (ConsoleKey)VK.MENU)
  1572. { // Alt 18
  1573. return KeyCode.AltMask;
  1574. }
  1575. if (keyInfo.KeyChar == 0)
  1576. {
  1577. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar);
  1578. }
  1579. if (keyInfo.Key != ConsoleKey.None)
  1580. {
  1581. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar);
  1582. }
  1583. return MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.KeyChar);
  1584. }
  1585. // Handle control keys (e.g. CursorUp)
  1586. if (Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint))
  1587. {
  1588. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)((uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint));
  1589. }
  1590. return MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar);
  1591. }
  1592. private MouseFlags ProcessButtonClick (WindowsConsole.MouseEventRecord mouseEvent)
  1593. {
  1594. MouseFlags mouseFlag = 0;
  1595. switch (_lastMouseButtonPressed)
  1596. {
  1597. case WindowsConsole.ButtonState.Button1Pressed:
  1598. mouseFlag = MouseFlags.Button1Clicked;
  1599. break;
  1600. case WindowsConsole.ButtonState.Button2Pressed:
  1601. mouseFlag = MouseFlags.Button2Clicked;
  1602. break;
  1603. case WindowsConsole.ButtonState.RightmostButtonPressed:
  1604. mouseFlag = MouseFlags.Button3Clicked;
  1605. break;
  1606. }
  1607. _point = new Point
  1608. {
  1609. X = mouseEvent.MousePosition.X,
  1610. Y = mouseEvent.MousePosition.Y
  1611. };
  1612. _lastMouseButtonPressed = null;
  1613. _isButtonReleased = false;
  1614. _processButtonClick = false;
  1615. _point = null;
  1616. return mouseFlag;
  1617. }
  1618. private async Task ProcessButtonDoubleClickedAsync ()
  1619. {
  1620. await Task.Delay (200);
  1621. _isButtonDoubleClicked = false;
  1622. _isOneFingerDoubleClicked = false;
  1623. //buttonPressedCount = 0;
  1624. }
  1625. private async Task ProcessContinuousButtonPressedAsync (MouseFlags mouseFlag)
  1626. {
  1627. // When a user presses-and-holds, start generating pressed events every `startDelay`
  1628. // After `iterationsUntilFast` iterations, speed them up to `fastDelay` ms
  1629. const int startDelay = 500;
  1630. const int iterationsUntilFast = 4;
  1631. const int fastDelay = 50;
  1632. int iterations = 0;
  1633. int delay = startDelay;
  1634. while (_isButtonPressed)
  1635. {
  1636. // TODO: This makes ConsoleDriver dependent on Application, which is not ideal. This should be moved to Application.
  1637. View view = Application.WantContinuousButtonPressedView;
  1638. if (view is null)
  1639. {
  1640. break;
  1641. }
  1642. if (iterations++ >= iterationsUntilFast)
  1643. {
  1644. delay = fastDelay;
  1645. }
  1646. await Task.Delay (delay);
  1647. var me = new MouseEventArgs
  1648. {
  1649. ScreenPosition = _pointMove,
  1650. Flags = mouseFlag
  1651. };
  1652. //Debug.WriteLine($"ProcessContinuousButtonPressedAsync: {view}");
  1653. if (_isButtonPressed && (mouseFlag & MouseFlags.ReportMousePosition) == 0)
  1654. {
  1655. // TODO: This makes ConsoleDriver dependent on Application, which is not ideal. This should be moved to Application.
  1656. Application.Invoke (() => OnMouseEvent (me));
  1657. }
  1658. }
  1659. }
  1660. private void ResizeScreen ()
  1661. {
  1662. _outputBuffer = new WindowsConsole.ExtendedCharInfo [Rows * Cols];
  1663. // CONCURRENCY: Unsynchronized access to Clip is not safe.
  1664. Clip = new (0, 0, Cols, Rows);
  1665. _damageRegion = new WindowsConsole.SmallRect
  1666. {
  1667. Top = 0,
  1668. Left = 0,
  1669. Bottom = (short)Rows,
  1670. Right = (short)Cols
  1671. };
  1672. _dirtyLines = new bool [Rows];
  1673. WinConsole?.ForceRefreshCursorVisibility ();
  1674. }
  1675. private static MouseFlags SetControlKeyStates (WindowsConsole.MouseEventRecord mouseEvent, MouseFlags mouseFlag)
  1676. {
  1677. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed)
  1678. || mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed))
  1679. {
  1680. mouseFlag |= MouseFlags.ButtonCtrl;
  1681. }
  1682. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed))
  1683. {
  1684. mouseFlag |= MouseFlags.ButtonShift;
  1685. }
  1686. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed)
  1687. || mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed))
  1688. {
  1689. mouseFlag |= MouseFlags.ButtonAlt;
  1690. }
  1691. return mouseFlag;
  1692. }
  1693. [CanBeNull]
  1694. private MouseEventArgs ToDriverMouse (WindowsConsole.MouseEventRecord mouseEvent)
  1695. {
  1696. var mouseFlag = MouseFlags.AllEvents;
  1697. //Debug.WriteLine ($"ToDriverMouse: {mouseEvent}");
  1698. if (_isButtonDoubleClicked || _isOneFingerDoubleClicked)
  1699. {
  1700. // TODO: This makes ConsoleDriver dependent on Application, which is not ideal. This should be moved to Application.
  1701. Application.MainLoop.AddIdle (
  1702. () =>
  1703. {
  1704. Task.Run (async () => await ProcessButtonDoubleClickedAsync ());
  1705. return false;
  1706. });
  1707. }
  1708. // The ButtonState member of the MouseEvent structure has bit corresponding to each mouse button.
  1709. // This will tell when a mouse button is pressed. When the button is released this event will
  1710. // be fired with its bit set to 0. So when the button is up ButtonState will be 0.
  1711. // To map to the correct driver events we save the last pressed mouse button, so we can
  1712. // map to the correct clicked event.
  1713. if ((_lastMouseButtonPressed is { } || _isButtonReleased) && mouseEvent.ButtonState != 0)
  1714. {
  1715. _lastMouseButtonPressed = null;
  1716. //isButtonPressed = false;
  1717. _isButtonReleased = false;
  1718. }
  1719. var p = new Point
  1720. {
  1721. X = mouseEvent.MousePosition.X,
  1722. Y = mouseEvent.MousePosition.Y
  1723. };
  1724. if ((mouseEvent.ButtonState != 0 && mouseEvent.EventFlags == 0 && _lastMouseButtonPressed is null && !_isButtonDoubleClicked)
  1725. || (_lastMouseButtonPressed == null
  1726. && mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.MouseMoved)
  1727. && mouseEvent.ButtonState != 0
  1728. && !_isButtonReleased
  1729. && !_isButtonDoubleClicked))
  1730. {
  1731. switch (mouseEvent.ButtonState)
  1732. {
  1733. case WindowsConsole.ButtonState.Button1Pressed:
  1734. mouseFlag = MouseFlags.Button1Pressed;
  1735. break;
  1736. case WindowsConsole.ButtonState.Button2Pressed:
  1737. mouseFlag = MouseFlags.Button2Pressed;
  1738. break;
  1739. case WindowsConsole.ButtonState.RightmostButtonPressed:
  1740. mouseFlag = MouseFlags.Button3Pressed;
  1741. break;
  1742. }
  1743. if (_point is null)
  1744. {
  1745. _point = p;
  1746. }
  1747. if (mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.MouseMoved))
  1748. {
  1749. _pointMove = p;
  1750. mouseFlag |= MouseFlags.ReportMousePosition;
  1751. _isButtonReleased = false;
  1752. _processButtonClick = false;
  1753. }
  1754. _lastMouseButtonPressed = mouseEvent.ButtonState;
  1755. _isButtonPressed = true;
  1756. if ((mouseFlag & MouseFlags.ReportMousePosition) == 0)
  1757. {
  1758. // TODO: This makes ConsoleDriver dependent on Application, which is not ideal. This should be moved to Application.
  1759. Application.MainLoop.AddIdle (
  1760. () =>
  1761. {
  1762. Task.Run (async () => await ProcessContinuousButtonPressedAsync (mouseFlag));
  1763. return false;
  1764. });
  1765. }
  1766. }
  1767. else if (_lastMouseButtonPressed != null
  1768. && mouseEvent.EventFlags == 0
  1769. && !_isButtonReleased
  1770. && !_isButtonDoubleClicked
  1771. && !_isOneFingerDoubleClicked)
  1772. {
  1773. switch (_lastMouseButtonPressed)
  1774. {
  1775. case WindowsConsole.ButtonState.Button1Pressed:
  1776. mouseFlag = MouseFlags.Button1Released;
  1777. break;
  1778. case WindowsConsole.ButtonState.Button2Pressed:
  1779. mouseFlag = MouseFlags.Button2Released;
  1780. break;
  1781. case WindowsConsole.ButtonState.RightmostButtonPressed:
  1782. mouseFlag = MouseFlags.Button3Released;
  1783. break;
  1784. }
  1785. _isButtonPressed = false;
  1786. _isButtonReleased = true;
  1787. if (_point is { } && ((Point)_point).X == mouseEvent.MousePosition.X && ((Point)_point).Y == mouseEvent.MousePosition.Y)
  1788. {
  1789. _processButtonClick = true;
  1790. }
  1791. else
  1792. {
  1793. _point = null;
  1794. }
  1795. _processButtonClick = true;
  1796. }
  1797. else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved
  1798. && !_isOneFingerDoubleClicked
  1799. && _isButtonReleased
  1800. && p == _point)
  1801. {
  1802. mouseFlag = ProcessButtonClick (mouseEvent);
  1803. }
  1804. else if (mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.DoubleClick))
  1805. {
  1806. switch (mouseEvent.ButtonState)
  1807. {
  1808. case WindowsConsole.ButtonState.Button1Pressed:
  1809. mouseFlag = MouseFlags.Button1DoubleClicked;
  1810. break;
  1811. case WindowsConsole.ButtonState.Button2Pressed:
  1812. mouseFlag = MouseFlags.Button2DoubleClicked;
  1813. break;
  1814. case WindowsConsole.ButtonState.RightmostButtonPressed:
  1815. mouseFlag = MouseFlags.Button3DoubleClicked;
  1816. break;
  1817. }
  1818. _isButtonDoubleClicked = true;
  1819. }
  1820. else if (mouseEvent.EventFlags == 0 && mouseEvent.ButtonState != 0 && _isButtonDoubleClicked)
  1821. {
  1822. switch (mouseEvent.ButtonState)
  1823. {
  1824. case WindowsConsole.ButtonState.Button1Pressed:
  1825. mouseFlag = MouseFlags.Button1TripleClicked;
  1826. break;
  1827. case WindowsConsole.ButtonState.Button2Pressed:
  1828. mouseFlag = MouseFlags.Button2TripleClicked;
  1829. break;
  1830. case WindowsConsole.ButtonState.RightmostButtonPressed:
  1831. mouseFlag = MouseFlags.Button3TripleClicked;
  1832. break;
  1833. }
  1834. _isButtonDoubleClicked = false;
  1835. }
  1836. else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled)
  1837. {
  1838. switch ((int)mouseEvent.ButtonState)
  1839. {
  1840. case int v when v > 0:
  1841. mouseFlag = MouseFlags.WheeledUp;
  1842. break;
  1843. case int v when v < 0:
  1844. mouseFlag = MouseFlags.WheeledDown;
  1845. break;
  1846. }
  1847. }
  1848. else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled && mouseEvent.ControlKeyState == WindowsConsole.ControlKeyState.ShiftPressed)
  1849. {
  1850. switch ((int)mouseEvent.ButtonState)
  1851. {
  1852. case int v when v > 0:
  1853. mouseFlag = MouseFlags.WheeledLeft;
  1854. break;
  1855. case int v when v < 0:
  1856. mouseFlag = MouseFlags.WheeledRight;
  1857. break;
  1858. }
  1859. }
  1860. else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseHorizontalWheeled)
  1861. {
  1862. switch ((int)mouseEvent.ButtonState)
  1863. {
  1864. case int v when v < 0:
  1865. mouseFlag = MouseFlags.WheeledLeft;
  1866. break;
  1867. case int v when v > 0:
  1868. mouseFlag = MouseFlags.WheeledRight;
  1869. break;
  1870. }
  1871. }
  1872. else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved)
  1873. {
  1874. mouseFlag = MouseFlags.ReportMousePosition;
  1875. if (mouseEvent.MousePosition.X != _pointMove.X || mouseEvent.MousePosition.Y != _pointMove.Y)
  1876. {
  1877. _pointMove = new Point (mouseEvent.MousePosition.X, mouseEvent.MousePosition.Y);
  1878. }
  1879. }
  1880. else if (mouseEvent is { ButtonState: 0, EventFlags: 0 })
  1881. {
  1882. // This happens on a double or triple click event.
  1883. mouseFlag = MouseFlags.None;
  1884. }
  1885. mouseFlag = SetControlKeyStates (mouseEvent, mouseFlag);
  1886. //System.Diagnostics.Debug.WriteLine (
  1887. // $"point.X:{(point is { } ? ((Point)point).X : -1)};point.Y:{(point is { } ? ((Point)point).Y : -1)}");
  1888. return new MouseEventArgs
  1889. {
  1890. Position = new (mouseEvent.MousePosition.X, mouseEvent.MousePosition.Y),
  1891. Flags = mouseFlag
  1892. };
  1893. }
  1894. }
  1895. /// <summary>
  1896. /// Mainloop intended to be used with the <see cref="WindowsDriver"/>, and can
  1897. /// only be used on Windows.
  1898. /// </summary>
  1899. /// <remarks>
  1900. /// This implementation is used for WindowsDriver.
  1901. /// </remarks>
  1902. internal class WindowsMainLoop : IMainLoopDriver
  1903. {
  1904. /// <summary>
  1905. /// Invoked when the window is changed.
  1906. /// </summary>
  1907. public EventHandler<SizeChangedEventArgs> WinChanged;
  1908. private readonly ConsoleDriver _consoleDriver;
  1909. private readonly ManualResetEventSlim _eventReady = new (false);
  1910. // The records that we keep fetching
  1911. private readonly Queue<WindowsConsole.InputRecord []> _resultQueue = new ();
  1912. internal readonly ManualResetEventSlim _waitForProbe = new (false);
  1913. private readonly WindowsConsole _winConsole;
  1914. private CancellationTokenSource _eventReadyTokenSource = new ();
  1915. private readonly CancellationTokenSource _inputHandlerTokenSource = new ();
  1916. private MainLoop _mainLoop;
  1917. public WindowsMainLoop (ConsoleDriver consoleDriver = null)
  1918. {
  1919. _consoleDriver = consoleDriver ?? throw new ArgumentNullException (nameof (consoleDriver));
  1920. if (!ConsoleDriver.RunningUnitTests)
  1921. {
  1922. _winConsole = ((WindowsDriver)consoleDriver).WinConsole;
  1923. _winConsole._mainLoop = this;
  1924. }
  1925. }
  1926. public EscSeqRequests EscSeqRequests { get; } = new ();
  1927. void IMainLoopDriver.Setup (MainLoop mainLoop)
  1928. {
  1929. _mainLoop = mainLoop;
  1930. if (ConsoleDriver.RunningUnitTests)
  1931. {
  1932. return;
  1933. }
  1934. Task.Run (WindowsInputHandler, _inputHandlerTokenSource.Token);
  1935. #if HACK_CHECK_WINCHANGED
  1936. Task.Run (CheckWinChange);
  1937. #endif
  1938. }
  1939. void IMainLoopDriver.Wakeup () { _eventReady.Set (); }
  1940. bool IMainLoopDriver.EventsPending ()
  1941. {
  1942. _waitForProbe.Set ();
  1943. #if HACK_CHECK_WINCHANGED
  1944. _winChange.Set ();
  1945. #endif
  1946. if (_mainLoop.CheckTimersAndIdleHandlers (out int waitTimeout))
  1947. {
  1948. return true;
  1949. }
  1950. try
  1951. {
  1952. if (!_eventReadyTokenSource.IsCancellationRequested)
  1953. {
  1954. // Note: ManualResetEventSlim.Wait will wait indefinitely if the timeout is -1. The timeout is -1 when there
  1955. // are no timers, but there IS an idle handler waiting.
  1956. _eventReady.Wait (waitTimeout, _eventReadyTokenSource.Token);
  1957. }
  1958. }
  1959. catch (OperationCanceledException)
  1960. {
  1961. return true;
  1962. }
  1963. finally
  1964. {
  1965. _eventReady.Reset ();
  1966. }
  1967. if (!_eventReadyTokenSource.IsCancellationRequested)
  1968. {
  1969. #if HACK_CHECK_WINCHANGED
  1970. return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _) || _winChanged;
  1971. #else
  1972. return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _);
  1973. #endif
  1974. }
  1975. _eventReadyTokenSource.Dispose ();
  1976. _eventReadyTokenSource = new CancellationTokenSource ();
  1977. return true;
  1978. }
  1979. void IMainLoopDriver.Iteration ()
  1980. {
  1981. while (_resultQueue.Count > 0)
  1982. {
  1983. WindowsConsole.InputRecord [] inputRecords = _resultQueue.Dequeue ();
  1984. if (inputRecords is { Length: > 0 })
  1985. {
  1986. ((WindowsDriver)_consoleDriver).ProcessInput (inputRecords [0]);
  1987. }
  1988. }
  1989. #if HACK_CHECK_WINCHANGED
  1990. if (_winChanged)
  1991. {
  1992. _winChanged = false;
  1993. WinChanged?.Invoke (this, new SizeChangedEventArgs (_windowSize));
  1994. }
  1995. #endif
  1996. }
  1997. void IMainLoopDriver.TearDown ()
  1998. {
  1999. _inputHandlerTokenSource?.Cancel ();
  2000. _inputHandlerTokenSource?.Dispose ();
  2001. if (_winConsole is { })
  2002. {
  2003. var numOfEvents = _winConsole.GetNumberOfConsoleInputEvents ();
  2004. if (numOfEvents > 0)
  2005. {
  2006. _winConsole.FlushConsoleInputBuffer ();
  2007. //Debug.WriteLine ($"Flushed {numOfEvents} events.");
  2008. }
  2009. }
  2010. _waitForProbe?.Dispose ();
  2011. _resultQueue?.Clear ();
  2012. _eventReadyTokenSource?.Cancel ();
  2013. _eventReadyTokenSource?.Dispose ();
  2014. _eventReady?.Dispose ();
  2015. #if HACK_CHECK_WINCHANGED
  2016. _winChange?.Dispose ();
  2017. #endif
  2018. _mainLoop = null;
  2019. }
  2020. internal bool _forceRead;
  2021. private void WindowsInputHandler ()
  2022. {
  2023. while (_mainLoop is { })
  2024. {
  2025. try
  2026. {
  2027. if (!_inputHandlerTokenSource.IsCancellationRequested && !_forceRead)
  2028. {
  2029. _waitForProbe.Wait (_inputHandlerTokenSource.Token);
  2030. }
  2031. }
  2032. catch (OperationCanceledException)
  2033. {
  2034. // Wakes the _waitForProbe if it's waiting
  2035. _waitForProbe.Set ();
  2036. return;
  2037. }
  2038. finally
  2039. {
  2040. // If IsCancellationRequested is true the code after
  2041. // the `finally` block will not be executed.
  2042. if (!_inputHandlerTokenSource.IsCancellationRequested)
  2043. {
  2044. _waitForProbe.Reset ();
  2045. }
  2046. }
  2047. if (_resultQueue?.Count == 0 || _forceRead)
  2048. {
  2049. while (!_inputHandlerTokenSource.IsCancellationRequested)
  2050. {
  2051. WindowsConsole.InputRecord [] inpRec = _winConsole.ReadConsoleInput ();
  2052. if (inpRec is { })
  2053. {
  2054. _resultQueue!.Enqueue (inpRec);
  2055. break;
  2056. }
  2057. if (!_forceRead)
  2058. {
  2059. try
  2060. {
  2061. Task.Delay (100, _inputHandlerTokenSource.Token).Wait (_inputHandlerTokenSource.Token);
  2062. }
  2063. catch (OperationCanceledException)
  2064. { }
  2065. }
  2066. }
  2067. }
  2068. if (_eventReady.IsSet)
  2069. {
  2070. // it's already in an iteration and ensures set to iterate again
  2071. Application.Invoke (() => _eventReady.Set ());
  2072. }
  2073. else
  2074. {
  2075. _eventReady.Set ();
  2076. }
  2077. }
  2078. }
  2079. #if HACK_CHECK_WINCHANGED
  2080. private readonly ManualResetEventSlim _winChange = new (false);
  2081. private bool _winChanged;
  2082. private Size _windowSize;
  2083. private void CheckWinChange ()
  2084. {
  2085. while (_mainLoop is { })
  2086. {
  2087. _winChange.Wait ();
  2088. _winChange.Reset ();
  2089. // Check if the window size changed every half second.
  2090. // We do this to minimize the weird tearing seen on Windows when resizing the console
  2091. while (_mainLoop is { })
  2092. {
  2093. Task.Delay (500).Wait ();
  2094. _windowSize = _winConsole.GetConsoleBufferWindow (out _);
  2095. if (_windowSize != Size.Empty
  2096. && (_windowSize.Width != _consoleDriver.Cols
  2097. || _windowSize.Height != _consoleDriver.Rows))
  2098. {
  2099. break;
  2100. }
  2101. }
  2102. _winChanged = true;
  2103. _eventReady.Set ();
  2104. }
  2105. }
  2106. #endif
  2107. }
  2108. internal class WindowsClipboard : ClipboardBase
  2109. {
  2110. private const uint CF_UNICODE_TEXT = 13;
  2111. public override bool IsSupported { get; } = CheckClipboardIsAvailable ();
  2112. private static bool CheckClipboardIsAvailable ()
  2113. {
  2114. // Attempt to open the clipboard
  2115. if (OpenClipboard (nint.Zero))
  2116. {
  2117. // Clipboard is available
  2118. // Close the clipboard after use
  2119. CloseClipboard ();
  2120. return true;
  2121. }
  2122. // Clipboard is not available
  2123. return false;
  2124. }
  2125. protected override string GetClipboardDataImpl ()
  2126. {
  2127. try
  2128. {
  2129. if (!OpenClipboard (nint.Zero))
  2130. {
  2131. return string.Empty;
  2132. }
  2133. nint handle = GetClipboardData (CF_UNICODE_TEXT);
  2134. if (handle == nint.Zero)
  2135. {
  2136. return string.Empty;
  2137. }
  2138. nint pointer = nint.Zero;
  2139. try
  2140. {
  2141. pointer = GlobalLock (handle);
  2142. if (pointer == nint.Zero)
  2143. {
  2144. return string.Empty;
  2145. }
  2146. int size = GlobalSize (handle);
  2147. var buff = new byte [size];
  2148. Marshal.Copy (pointer, buff, 0, size);
  2149. return Encoding.Unicode.GetString (buff).TrimEnd ('\0');
  2150. }
  2151. finally
  2152. {
  2153. if (pointer != nint.Zero)
  2154. {
  2155. GlobalUnlock (handle);
  2156. }
  2157. }
  2158. }
  2159. finally
  2160. {
  2161. CloseClipboard ();
  2162. }
  2163. }
  2164. protected override void SetClipboardDataImpl (string text)
  2165. {
  2166. OpenClipboard ();
  2167. EmptyClipboard ();
  2168. nint hGlobal = default;
  2169. try
  2170. {
  2171. int bytes = (text.Length + 1) * 2;
  2172. hGlobal = Marshal.AllocHGlobal (bytes);
  2173. if (hGlobal == default (nint))
  2174. {
  2175. ThrowWin32 ();
  2176. }
  2177. nint target = GlobalLock (hGlobal);
  2178. if (target == default (nint))
  2179. {
  2180. ThrowWin32 ();
  2181. }
  2182. try
  2183. {
  2184. Marshal.Copy (text.ToCharArray (), 0, target, text.Length);
  2185. }
  2186. finally
  2187. {
  2188. GlobalUnlock (target);
  2189. }
  2190. if (SetClipboardData (CF_UNICODE_TEXT, hGlobal) == default (nint))
  2191. {
  2192. ThrowWin32 ();
  2193. }
  2194. hGlobal = default (nint);
  2195. }
  2196. finally
  2197. {
  2198. if (hGlobal != default (nint))
  2199. {
  2200. Marshal.FreeHGlobal (hGlobal);
  2201. }
  2202. CloseClipboard ();
  2203. }
  2204. }
  2205. [DllImport ("user32.dll", SetLastError = true)]
  2206. [return: MarshalAs (UnmanagedType.Bool)]
  2207. private static extern bool CloseClipboard ();
  2208. [DllImport ("user32.dll")]
  2209. private static extern bool EmptyClipboard ();
  2210. [DllImport ("user32.dll", SetLastError = true)]
  2211. private static extern nint GetClipboardData (uint uFormat);
  2212. [DllImport ("kernel32.dll", SetLastError = true)]
  2213. private static extern nint GlobalLock (nint hMem);
  2214. [DllImport ("kernel32.dll", SetLastError = true)]
  2215. private static extern int GlobalSize (nint handle);
  2216. [DllImport ("kernel32.dll", SetLastError = true)]
  2217. [return: MarshalAs (UnmanagedType.Bool)]
  2218. private static extern bool GlobalUnlock (nint hMem);
  2219. [DllImport ("User32.dll", SetLastError = true)]
  2220. [return: MarshalAs (UnmanagedType.Bool)]
  2221. private static extern bool IsClipboardFormatAvailable (uint format);
  2222. private void OpenClipboard ()
  2223. {
  2224. var num = 10;
  2225. while (true)
  2226. {
  2227. if (OpenClipboard (default (nint)))
  2228. {
  2229. break;
  2230. }
  2231. if (--num == 0)
  2232. {
  2233. ThrowWin32 ();
  2234. }
  2235. Thread.Sleep (100);
  2236. }
  2237. }
  2238. [DllImport ("user32.dll", SetLastError = true)]
  2239. [return: MarshalAs (UnmanagedType.Bool)]
  2240. private static extern bool OpenClipboard (nint hWndNewOwner);
  2241. [DllImport ("user32.dll", SetLastError = true)]
  2242. private static extern nint SetClipboardData (uint uFormat, nint data);
  2243. private void ThrowWin32 () { throw new Win32Exception (Marshal.GetLastWin32Error ()); }
  2244. }