WindowsDriver.cs 61 KB

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