WindowsDriver.cs 81 KB

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