WindowsDriver.cs 88 KB

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