WindowsDriver.cs 76 KB

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