WindowsDriver.cs 78 KB

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