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