WindowsDriver.cs 82 KB

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