WindowsDriver.cs 81 KB

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