WindowsDriver.cs 79 KB

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