WindowsDriver.cs 88 KB

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