WindowsDriver.cs 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960
  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.Runtime.InteropServices;
  20. using System.Threading;
  21. using System.Threading.Tasks;
  22. using System.Diagnostics;
  23. using Terminal.Gui.ConsoleDrivers;
  24. using static Unix.Terminal.Delegates;
  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)(((int)info.Attribute.Foreground.ColorName) | ((int)info.Attribute.Background.ColorName << 4))
  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. public override readonly string ToString () => $"[KeyEventRecord({(bKeyDown ? "down" : "up")},{wRepeatCount},{wVirtualKeyCode},{wVirtualScanCode},{new Rune (UnicodeChar).MakePrintable ()},{dwControlKeyState})]";
  319. }
  320. [Flags]
  321. public enum ButtonState {
  322. Button1Pressed = 1,
  323. Button2Pressed = 4,
  324. Button3Pressed = 8,
  325. Button4Pressed = 16,
  326. RightmostButtonPressed = 2
  327. }
  328. [Flags]
  329. public enum ControlKeyState {
  330. RightAltPressed = 1,
  331. LeftAltPressed = 2,
  332. RightControlPressed = 4,
  333. LeftControlPressed = 8,
  334. ShiftPressed = 16,
  335. NumlockOn = 32,
  336. ScrolllockOn = 64,
  337. CapslockOn = 128,
  338. EnhancedKey = 256
  339. }
  340. [Flags]
  341. public enum EventFlags {
  342. MouseMoved = 1,
  343. DoubleClick = 2,
  344. MouseWheeled = 4,
  345. MouseHorizontalWheeled = 8
  346. }
  347. [StructLayout (LayoutKind.Explicit)]
  348. public struct MouseEventRecord {
  349. [FieldOffset (0)]
  350. public Coord MousePosition;
  351. [FieldOffset (4)]
  352. public ButtonState ButtonState;
  353. [FieldOffset (8)]
  354. public ControlKeyState ControlKeyState;
  355. [FieldOffset (12)]
  356. public EventFlags EventFlags;
  357. public override readonly string ToString () => $"[Mouse({MousePosition},{ButtonState},{ControlKeyState},{EventFlags}";
  358. }
  359. public struct WindowBufferSizeRecord {
  360. public Coord _size;
  361. public WindowBufferSizeRecord (short x, short y)
  362. {
  363. _size = new Coord (x, y);
  364. }
  365. public override readonly string ToString () => $"[WindowBufferSize{_size}";
  366. }
  367. [StructLayout (LayoutKind.Sequential)]
  368. public struct MenuEventRecord {
  369. public uint dwCommandId;
  370. }
  371. [StructLayout (LayoutKind.Sequential)]
  372. public struct FocusEventRecord {
  373. public uint bSetFocus;
  374. }
  375. public enum EventType : ushort {
  376. Focus = 0x10,
  377. Key = 0x1,
  378. Menu = 0x8,
  379. Mouse = 2,
  380. WindowBufferSize = 4
  381. }
  382. [StructLayout (LayoutKind.Explicit)]
  383. public struct InputRecord {
  384. [FieldOffset (0)]
  385. public EventType EventType;
  386. [FieldOffset (4)]
  387. public KeyEventRecord KeyEvent;
  388. [FieldOffset (4)]
  389. public MouseEventRecord MouseEvent;
  390. [FieldOffset (4)]
  391. public WindowBufferSizeRecord WindowBufferSizeEvent;
  392. [FieldOffset (4)]
  393. public MenuEventRecord MenuEvent;
  394. [FieldOffset (4)]
  395. public FocusEventRecord FocusEvent;
  396. public override readonly string ToString ()
  397. {
  398. return EventType switch {
  399. EventType.Focus => FocusEvent.ToString (),
  400. EventType.Key => KeyEvent.ToString (),
  401. EventType.Menu => MenuEvent.ToString (),
  402. EventType.Mouse => MouseEvent.ToString (),
  403. EventType.WindowBufferSize => WindowBufferSizeEvent.ToString (),
  404. _ => "Unknown event type: " + EventType
  405. };
  406. }
  407. };
  408. [Flags]
  409. enum ShareMode : uint {
  410. FileShareRead = 1,
  411. FileShareWrite = 2,
  412. }
  413. [Flags]
  414. enum DesiredAccess : uint {
  415. GenericRead = 2147483648,
  416. GenericWrite = 1073741824,
  417. }
  418. [StructLayout (LayoutKind.Sequential)]
  419. public struct ConsoleScreenBufferInfo {
  420. public Coord dwSize;
  421. public Coord dwCursorPosition;
  422. public ushort wAttributes;
  423. public SmallRect srWindow;
  424. public Coord dwMaximumWindowSize;
  425. }
  426. [StructLayout (LayoutKind.Sequential)]
  427. public struct Coord {
  428. public short X;
  429. public short Y;
  430. public Coord (short x, short y)
  431. {
  432. X = x;
  433. Y = y;
  434. }
  435. public override readonly string ToString () => $"({X},{Y})";
  436. };
  437. [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
  438. public struct CharUnion {
  439. [FieldOffset (0)] public char UnicodeChar;
  440. [FieldOffset (0)] public byte AsciiChar;
  441. }
  442. [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
  443. public struct CharInfo {
  444. [FieldOffset (0)] public CharUnion Char;
  445. [FieldOffset (2)] public ushort Attributes;
  446. }
  447. public struct ExtendedCharInfo {
  448. public char Char { get; set; }
  449. public Attribute Attribute { get; set; }
  450. public bool Empty { get; set; } // TODO: Temp hack until virutal terminal sequences
  451. public ExtendedCharInfo (char character, Attribute attribute)
  452. {
  453. Char = character;
  454. Attribute = attribute;
  455. Empty = false;
  456. }
  457. }
  458. [StructLayout (LayoutKind.Sequential)]
  459. public struct SmallRect {
  460. public short Left;
  461. public short Top;
  462. public short Right;
  463. public short Bottom;
  464. public SmallRect (short left, short top, short right, short bottom)
  465. {
  466. Left = left;
  467. Top = top;
  468. Right = right;
  469. Bottom = bottom;
  470. }
  471. public static void MakeEmpty (ref SmallRect rect)
  472. {
  473. rect.Left = -1;
  474. }
  475. public static void Update (ref SmallRect rect, short col, short row)
  476. {
  477. if (rect.Left == -1) {
  478. rect.Left = rect.Right = col;
  479. rect.Bottom = rect.Top = row;
  480. return;
  481. }
  482. if (col >= rect.Left && col <= rect.Right && row >= rect.Top && row <= rect.Bottom)
  483. return;
  484. if (col < rect.Left)
  485. rect.Left = col;
  486. if (col > rect.Right)
  487. rect.Right = col;
  488. if (row < rect.Top)
  489. rect.Top = row;
  490. if (row > rect.Bottom)
  491. rect.Bottom = row;
  492. }
  493. public override readonly string ToString () => $"Left={Left},Top={Top},Right={Right},Bottom={Bottom}";
  494. }
  495. [StructLayout (LayoutKind.Sequential)]
  496. public struct ConsoleKeyInfoEx {
  497. public ConsoleKeyInfo ConsoleKeyInfo;
  498. public bool CapsLock;
  499. public bool NumLock;
  500. public bool ScrollLock;
  501. public ConsoleKeyInfoEx (ConsoleKeyInfo consoleKeyInfo, bool capslock, bool numlock, bool scrolllock)
  502. {
  503. ConsoleKeyInfo = consoleKeyInfo;
  504. CapsLock = capslock;
  505. NumLock = numlock;
  506. ScrollLock = scrolllock;
  507. }
  508. /// <summary>
  509. /// Prints a ConsoleKeyInfoEx structure
  510. /// </summary>
  511. /// <param name="ex"></param>
  512. /// <returns></returns>
  513. public readonly string ToString (ConsoleKeyInfoEx ex)
  514. {
  515. var ke = new Key ((KeyCode)ex.ConsoleKeyInfo.KeyChar);
  516. var sb = new StringBuilder ();
  517. sb.Append ($"Key: {(KeyCode)ex.ConsoleKeyInfo.Key} ({ex.ConsoleKeyInfo.Key})");
  518. sb.Append ((ex.ConsoleKeyInfo.Modifiers & ConsoleModifiers.Shift) != 0 ? " | Shift" : string.Empty);
  519. sb.Append ((ex.ConsoleKeyInfo.Modifiers & ConsoleModifiers.Control) != 0 ? " | Control" : string.Empty);
  520. sb.Append ((ex.ConsoleKeyInfo.Modifiers & ConsoleModifiers.Alt) != 0 ? " | Alt" : string.Empty);
  521. sb.Append ($", KeyChar: {ke.AsRune.MakePrintable ()} ({(uint)ex.ConsoleKeyInfo.KeyChar}) ");
  522. sb.Append ((ex.CapsLock ? "caps," : string.Empty));
  523. sb.Append ((ex.NumLock ? "num," : string.Empty));
  524. sb.Append ((ex.ScrollLock ? "scroll," : string.Empty));
  525. var s = sb.ToString ().TrimEnd (',').TrimEnd (' ');
  526. return $"[ConsoleKeyInfoEx({s})]";
  527. }
  528. }
  529. [DllImport ("kernel32.dll", SetLastError = true)]
  530. static extern IntPtr GetStdHandle (int nStdHandle);
  531. [DllImport ("kernel32.dll", SetLastError = true)]
  532. static extern bool CloseHandle (IntPtr handle);
  533. [DllImport ("kernel32.dll", EntryPoint = "ReadConsoleInputW", CharSet = CharSet.Unicode)]
  534. public static extern bool ReadConsoleInput (
  535. IntPtr hConsoleInput,
  536. IntPtr lpBuffer,
  537. uint nLength,
  538. out uint lpNumberOfEventsRead);
  539. [DllImport ("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
  540. static extern bool ReadConsoleOutput (
  541. IntPtr hConsoleOutput,
  542. [Out] CharInfo [] lpBuffer,
  543. Coord dwBufferSize,
  544. Coord dwBufferCoord,
  545. ref SmallRect lpReadRegion
  546. );
  547. // TODO: This API is obsolete. See https://learn.microsoft.com/en-us/windows/console/writeconsoleoutput
  548. [DllImport ("kernel32.dll", EntryPoint = "WriteConsoleOutputW", SetLastError = true, CharSet = CharSet.Unicode)]
  549. static extern bool WriteConsoleOutput (
  550. IntPtr hConsoleOutput,
  551. CharInfo [] lpBuffer,
  552. Coord dwBufferSize,
  553. Coord dwBufferCoord,
  554. ref SmallRect lpWriteRegion
  555. );
  556. [DllImport ("kernel32.dll", EntryPoint = "WriteConsole", SetLastError = true, CharSet = CharSet.Unicode)]
  557. static extern bool WriteConsole (
  558. IntPtr hConsoleOutput,
  559. String lpbufer,
  560. UInt32 NumberOfCharsToWriten,
  561. out UInt32 lpNumberOfCharsWritten,
  562. object lpReserved
  563. );
  564. [DllImport ("kernel32.dll")]
  565. static extern bool SetConsoleCursorPosition (IntPtr hConsoleOutput, Coord dwCursorPosition);
  566. [StructLayout (LayoutKind.Sequential)]
  567. public struct ConsoleCursorInfo {
  568. public uint dwSize;
  569. public bool bVisible;
  570. }
  571. [DllImport ("kernel32.dll", SetLastError = true)]
  572. static extern bool SetConsoleCursorInfo (IntPtr hConsoleOutput, [In] ref ConsoleCursorInfo lpConsoleCursorInfo);
  573. [DllImport ("kernel32.dll", SetLastError = true)]
  574. static extern bool GetConsoleCursorInfo (IntPtr hConsoleOutput, out ConsoleCursorInfo lpConsoleCursorInfo);
  575. [DllImport ("kernel32.dll")]
  576. static extern bool GetConsoleMode (IntPtr hConsoleHandle, out uint lpMode);
  577. [DllImport ("kernel32.dll")]
  578. static extern bool SetConsoleMode (IntPtr hConsoleHandle, uint dwMode);
  579. [DllImport ("kernel32.dll", SetLastError = true)]
  580. static extern IntPtr CreateConsoleScreenBuffer (
  581. DesiredAccess dwDesiredAccess,
  582. ShareMode dwShareMode,
  583. IntPtr secutiryAttributes,
  584. uint flags,
  585. IntPtr screenBufferData
  586. );
  587. internal static IntPtr INVALID_HANDLE_VALUE = new IntPtr (-1);
  588. [DllImport ("kernel32.dll", SetLastError = true)]
  589. static extern bool SetConsoleActiveScreenBuffer (IntPtr Handle);
  590. [DllImport ("kernel32.dll", SetLastError = true)]
  591. static extern bool GetNumberOfConsoleInputEvents (IntPtr handle, out uint lpcNumberOfEvents);
  592. public InputRecord [] ReadConsoleInput ()
  593. {
  594. const int bufferSize = 1;
  595. var pRecord = Marshal.AllocHGlobal (Marshal.SizeOf<InputRecord> () * bufferSize);
  596. try {
  597. ReadConsoleInput (_inputHandle, pRecord, bufferSize,
  598. out var numberEventsRead);
  599. return numberEventsRead == 0
  600. ? null
  601. : new [] { Marshal.PtrToStructure<InputRecord> (pRecord) };
  602. } catch (Exception) {
  603. return null;
  604. } finally {
  605. Marshal.FreeHGlobal (pRecord);
  606. }
  607. }
  608. #if false // Not needed on the constructor. Perhaps could be used on resizing. To study.
  609. [DllImport ("kernel32.dll", ExactSpelling = true)]
  610. static extern IntPtr GetConsoleWindow ();
  611. [DllImport ("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  612. static extern bool ShowWindow (IntPtr hWnd, int nCmdShow);
  613. public const int HIDE = 0;
  614. public const int MAXIMIZE = 3;
  615. public const int MINIMIZE = 6;
  616. public const int RESTORE = 9;
  617. internal void ShowWindow (int state)
  618. {
  619. IntPtr thisConsole = GetConsoleWindow ();
  620. ShowWindow (thisConsole, state);
  621. }
  622. #endif
  623. // See: https://github.com/gui-cs/Terminal.Gui/issues/357
  624. [StructLayout (LayoutKind.Sequential)]
  625. public struct CONSOLE_SCREEN_BUFFER_INFOEX {
  626. public uint cbSize;
  627. public Coord dwSize;
  628. public Coord dwCursorPosition;
  629. public ushort wAttributes;
  630. public SmallRect srWindow;
  631. public Coord dwMaximumWindowSize;
  632. public ushort wPopupAttributes;
  633. public bool bFullscreenSupported;
  634. [MarshalAs (UnmanagedType.ByValArray, SizeConst = 16)]
  635. public COLORREF [] ColorTable;
  636. }
  637. [StructLayout (LayoutKind.Explicit, Size = 4)]
  638. public struct COLORREF {
  639. public COLORREF (byte r, byte g, byte b)
  640. {
  641. Value = 0;
  642. R = r;
  643. G = g;
  644. B = b;
  645. }
  646. public COLORREF (uint value)
  647. {
  648. R = 0;
  649. G = 0;
  650. B = 0;
  651. Value = value & 0x00FFFFFF;
  652. }
  653. [FieldOffset (0)]
  654. public byte R;
  655. [FieldOffset (1)]
  656. public byte G;
  657. [FieldOffset (2)]
  658. public byte B;
  659. [FieldOffset (0)]
  660. public uint Value;
  661. }
  662. [DllImport ("kernel32.dll", SetLastError = true)]
  663. static extern bool GetConsoleScreenBufferInfoEx (IntPtr hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFOEX csbi);
  664. [DllImport ("kernel32.dll", SetLastError = true)]
  665. static extern bool SetConsoleScreenBufferInfoEx (IntPtr hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFOEX ConsoleScreenBufferInfo);
  666. [DllImport ("kernel32.dll", SetLastError = true)]
  667. static extern bool SetConsoleWindowInfo (
  668. IntPtr hConsoleOutput,
  669. bool bAbsolute,
  670. [In] ref SmallRect lpConsoleWindow);
  671. [DllImport ("kernel32.dll", SetLastError = true)]
  672. static extern Coord GetLargestConsoleWindowSize (
  673. IntPtr hConsoleOutput);
  674. }
  675. internal class WindowsDriver : ConsoleDriver {
  676. WindowsConsole.ExtendedCharInfo [] _outputBuffer;
  677. WindowsConsole.SmallRect _damageRegion;
  678. public WindowsConsole WinConsole { get; private set; }
  679. public override bool SupportsTrueColor => RunningUnitTests || (Environment.OSVersion.Version.Build >= 14931 && _isWindowsTerminal);
  680. readonly bool _isWindowsTerminal = false;
  681. WindowsMainLoop _mainLoopDriver = null;
  682. public WindowsDriver ()
  683. {
  684. if (Environment.OSVersion.Platform == PlatformID.Win32NT) {
  685. WinConsole = new WindowsConsole ();
  686. // otherwise we're probably running in unit tests
  687. Clipboard = new WindowsClipboard ();
  688. } else {
  689. Clipboard = new FakeDriver.FakeClipboard ();
  690. }
  691. // TODO: if some other Windows-based terminal supports true color, update this logic to not
  692. // force 16color mode (.e.g ConEmu which really doesn't work well at all).
  693. _isWindowsTerminal = Environment.GetEnvironmentVariable ("WT_SESSION") != null;
  694. if (!_isWindowsTerminal) {
  695. Force16Colors = true;
  696. }
  697. }
  698. internal override MainLoop Init ()
  699. {
  700. _mainLoopDriver = new WindowsMainLoop (this);
  701. if (!RunningUnitTests) {
  702. try {
  703. if (WinConsole != null) {
  704. // BUGBUG: The results from GetConsoleOutputWindow are incorrect when called from Init.
  705. // Our thread in WindowsMainLoop.CheckWin will get the correct results. See #if HACK_CHECK_WINCHANGED
  706. var winSize = WinConsole.GetConsoleOutputWindow (out Point pos);
  707. Cols = winSize.Width;
  708. Rows = winSize.Height;
  709. }
  710. WindowsConsole.SmallRect.MakeEmpty (ref _damageRegion);
  711. if (_isWindowsTerminal) {
  712. Console.Out.Write (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll);
  713. }
  714. } catch (Win32Exception e) {
  715. // We are being run in an environment that does not support a console
  716. // such as a unit test, or a pipe.
  717. Debug.WriteLine ($"Likely running unit tests. Setting WinConsole to null so we can test it elsewhere. Exception: {e}");
  718. WinConsole = null;
  719. }
  720. }
  721. CurrentAttribute = new Attribute (Color.White, Color.Black);
  722. _outputBuffer = new WindowsConsole.ExtendedCharInfo [Rows * Cols];
  723. Clip = new Rect (0, 0, Cols, Rows);
  724. _damageRegion = new WindowsConsole.SmallRect () {
  725. Top = 0,
  726. Left = 0,
  727. Bottom = (short)Rows,
  728. Right = (short)Cols
  729. };
  730. ClearContents ();
  731. #if HACK_CHECK_WINCHANGED
  732. _mainLoopDriver.WinChanged = ChangeWin;
  733. #endif
  734. return new MainLoop (_mainLoopDriver);
  735. }
  736. #if HACK_CHECK_WINCHANGED
  737. private void ChangeWin (Object s, SizeChangedEventArgs e)
  738. {
  739. var w = e.Size.Width;
  740. if (w == Cols - 3 && e.Size.Height < Rows) {
  741. w += 3;
  742. }
  743. Left = 0;
  744. Top = 0;
  745. Cols = e.Size.Width;
  746. Rows = e.Size.Height;
  747. if (!RunningUnitTests) {
  748. var newSize = WinConsole.SetConsoleWindow (
  749. (short)Math.Max (w, 16), (short)Math.Max (e.Size.Height, 0));
  750. Cols = newSize.Width;
  751. Rows = newSize.Height;
  752. }
  753. ResizeScreen ();
  754. ClearContents ();
  755. OnSizeChanged (new SizeChangedEventArgs (new Size (Cols, Rows)));
  756. }
  757. #endif
  758. KeyCode MapKey (WindowsConsole.ConsoleKeyInfoEx keyInfoEx)
  759. {
  760. var keyInfo = keyInfoEx.ConsoleKeyInfo;
  761. switch (keyInfo.Key) {
  762. case ConsoleKey.Escape:
  763. return ConsoleKeyMapping.MapKeyModifiers (keyInfo, KeyCode.Esc);
  764. case ConsoleKey.Tab:
  765. return ConsoleKeyMapping.MapKeyModifiers (keyInfo, KeyCode.Tab);
  766. case ConsoleKey.Clear:
  767. return ConsoleKeyMapping.MapKeyModifiers (keyInfo, KeyCode.Clear);
  768. case ConsoleKey.Home:
  769. return ConsoleKeyMapping.MapKeyModifiers (keyInfo, KeyCode.Home);
  770. case ConsoleKey.End:
  771. return ConsoleKeyMapping.MapKeyModifiers (keyInfo, KeyCode.End);
  772. case ConsoleKey.LeftArrow:
  773. return ConsoleKeyMapping.MapKeyModifiers (keyInfo, KeyCode.CursorLeft);
  774. case ConsoleKey.RightArrow:
  775. return ConsoleKeyMapping.MapKeyModifiers (keyInfo, KeyCode.CursorRight);
  776. case ConsoleKey.UpArrow:
  777. return ConsoleKeyMapping.MapKeyModifiers (keyInfo, KeyCode.CursorUp);
  778. case ConsoleKey.DownArrow:
  779. return ConsoleKeyMapping.MapKeyModifiers (keyInfo, KeyCode.CursorDown);
  780. case ConsoleKey.PageUp:
  781. return ConsoleKeyMapping.MapKeyModifiers (keyInfo, KeyCode.PageUp);
  782. case ConsoleKey.PageDown:
  783. return ConsoleKeyMapping.MapKeyModifiers (keyInfo, KeyCode.PageDown);
  784. case ConsoleKey.Enter:
  785. return ConsoleKeyMapping.MapKeyModifiers (keyInfo, KeyCode.Enter);
  786. case ConsoleKey.Spacebar:
  787. return ConsoleKeyMapping.MapKeyModifiers (keyInfo, keyInfo.KeyChar == 0 ? KeyCode.Space : (KeyCode)keyInfo.KeyChar);
  788. case ConsoleKey.Backspace:
  789. return ConsoleKeyMapping.MapKeyModifiers (keyInfo, KeyCode.Backspace);
  790. case ConsoleKey.Delete:
  791. return ConsoleKeyMapping.MapKeyModifiers (keyInfo, KeyCode.DeleteChar);
  792. case ConsoleKey.Insert:
  793. return ConsoleKeyMapping.MapKeyModifiers (keyInfo, KeyCode.InsertChar);
  794. case ConsoleKey.PrintScreen:
  795. return ConsoleKeyMapping.MapKeyModifiers (keyInfo, KeyCode.PrintScreen);
  796. //case ConsoleKey.NumPad0:
  797. // return keyInfoEx.NumLock ? Key.D0 : Key.InsertChar;
  798. //case ConsoleKey.NumPad1:
  799. // return keyInfoEx.NumLock ? Key.D1 : Key.End;
  800. //case ConsoleKey.NumPad2:
  801. // return keyInfoEx.NumLock ? Key.D2 : Key.CursorDown;
  802. //case ConsoleKey.NumPad3:
  803. // return keyInfoEx.NumLock ? Key.D3 : Key.PageDown;
  804. //case ConsoleKey.NumPad4:
  805. // return keyInfoEx.NumLock ? Key.D4 : Key.CursorLeft;
  806. //case ConsoleKey.NumPad5:
  807. // return keyInfoEx.NumLock ? Key.D5 : (Key)((uint)keyInfo.KeyChar);
  808. //case ConsoleKey.NumPad6:
  809. // return keyInfoEx.NumLock ? Key.D6 : Key.CursorRight;
  810. //case ConsoleKey.NumPad7:
  811. // return keyInfoEx.NumLock ? Key.D7 : Key.Home;
  812. //case ConsoleKey.NumPad8:
  813. // return keyInfoEx.NumLock ? Key.D8 : Key.CursorUp;
  814. //case ConsoleKey.NumPad9:
  815. // return keyInfoEx.NumLock ? Key.D9 : Key.PageUp;
  816. case ConsoleKey.Oem1:
  817. case ConsoleKey.Oem2:
  818. case ConsoleKey.Oem3:
  819. case ConsoleKey.Oem4:
  820. case ConsoleKey.Oem5:
  821. case ConsoleKey.Oem6:
  822. case ConsoleKey.Oem7:
  823. case ConsoleKey.Oem8:
  824. case ConsoleKey.Oem102:
  825. var ret = ConsoleKeyMapping.MapKeyModifiers (keyInfo, (KeyCode)((uint)keyInfo.KeyChar));
  826. if (ret.HasFlag (KeyCode.ShiftMask)) {
  827. ret &= ~KeyCode.ShiftMask;
  828. }
  829. return ret;
  830. case ConsoleKey.OemPeriod:
  831. case ConsoleKey.OemComma:
  832. case ConsoleKey.OemPlus:
  833. case ConsoleKey.OemMinus:
  834. return (KeyCode)((uint)keyInfo.KeyChar);
  835. }
  836. var key = keyInfo.Key;
  837. if (key >= ConsoleKey.A && key <= ConsoleKey.Z) {
  838. var delta = key - ConsoleKey.A;
  839. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  840. return (KeyCode)(((uint)KeyCode.CtrlMask) | ((uint)KeyCode.A + delta));
  841. }
  842. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  843. return (KeyCode)(((uint)KeyCode.AltMask) | ((uint)KeyCode.A + delta));
  844. }
  845. if (keyInfo.Modifiers == (ConsoleModifiers.Shift | ConsoleModifiers.Alt)) {
  846. return ConsoleKeyMapping.MapKeyModifiers (keyInfo, (KeyCode)((uint)KeyCode.A + delta));
  847. }
  848. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  849. if (keyInfo.KeyChar == 0 || (keyInfo.KeyChar != 0 && keyInfo.KeyChar >= 1 && keyInfo.KeyChar <= 26)) {
  850. return ConsoleKeyMapping.MapKeyModifiers (keyInfo, (KeyCode)((uint)KeyCode.A + delta));
  851. }
  852. }
  853. if (((keyInfo.Modifiers == ConsoleModifiers.Shift) ^ (keyInfoEx.CapsLock))) {
  854. if (keyInfo.KeyChar <= (uint)KeyCode.Z) {
  855. return (KeyCode)((uint)KeyCode.A + delta) | KeyCode.ShiftMask;
  856. }
  857. }
  858. if (((KeyCode)((uint)keyInfo.KeyChar) & KeyCode.Space) == 0) {
  859. return (KeyCode)((uint)keyInfo.KeyChar) & ~KeyCode.Space;
  860. }
  861. if (((KeyCode)((uint)keyInfo.KeyChar) & KeyCode.Space) != 0) {
  862. if (((KeyCode)((uint)keyInfo.KeyChar) & ~KeyCode.Space) == (KeyCode)keyInfo.Key) {
  863. return (KeyCode)((uint)keyInfo.KeyChar) & ~KeyCode.Space;
  864. }
  865. return (KeyCode)((uint)keyInfo.KeyChar);
  866. }
  867. return (KeyCode)(uint)keyInfo.KeyChar;
  868. }
  869. if (key >= ConsoleKey.D0 && key <= ConsoleKey.D9) {
  870. var delta = key - ConsoleKey.D0;
  871. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  872. return (KeyCode)(((uint)KeyCode.AltMask) | ((uint)KeyCode.D0 + delta));
  873. }
  874. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  875. return (KeyCode)(((uint)KeyCode.CtrlMask) | ((uint)KeyCode.D0 + delta));
  876. }
  877. if (keyInfo.Modifiers == (ConsoleModifiers.Shift | ConsoleModifiers.Alt)) {
  878. return ConsoleKeyMapping.MapKeyModifiers (keyInfo, (KeyCode)((uint)KeyCode.D0 + delta));
  879. }
  880. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  881. if (keyInfo.KeyChar == 0 || keyInfo.KeyChar == 30 || keyInfo.KeyChar == ((uint)KeyCode.D0 + delta)) {
  882. return ConsoleKeyMapping.MapKeyModifiers (keyInfo, (KeyCode)((uint)KeyCode.D0 + delta));
  883. }
  884. }
  885. return (KeyCode)((uint)keyInfo.KeyChar);
  886. }
  887. if (key >= ConsoleKey.F1 && key <= ConsoleKey.F12) {
  888. var delta = key - ConsoleKey.F1;
  889. if ((keyInfo.Modifiers & (ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  890. return ConsoleKeyMapping.MapKeyModifiers (keyInfo, (KeyCode)((uint)KeyCode.F1 + delta));
  891. }
  892. return (KeyCode)((uint)KeyCode.F1 + delta);
  893. }
  894. if (key == (ConsoleKey)16) { // Shift
  895. return KeyCode.Null | KeyCode.ShiftMask;
  896. }
  897. if (key == (ConsoleKey)17) { // Ctrl
  898. return KeyCode.Null | KeyCode.CtrlMask;
  899. }
  900. if (key == (ConsoleKey)18) { // Alt
  901. return KeyCode.Null | KeyCode.AltMask;
  902. }
  903. return ConsoleKeyMapping.MapKeyModifiers (keyInfo, (KeyCode)((uint)keyInfo.KeyChar));
  904. }
  905. bool _altDown = false;
  906. internal void ProcessInput (WindowsConsole.InputRecord inputEvent)
  907. {
  908. switch (inputEvent.EventType) {
  909. case WindowsConsole.EventType.Key:
  910. var fromPacketKey = inputEvent.KeyEvent.wVirtualKeyCode == (uint)ConsoleKey.Packet;
  911. if (fromPacketKey) {
  912. inputEvent.KeyEvent = FromVKPacketToKeyEventRecord (inputEvent.KeyEvent);
  913. }
  914. var keyInfo = ToConsoleKeyInfoEx (inputEvent.KeyEvent);
  915. //Debug.WriteLine ($"event: {inputEvent.ToString ()} {keyInfo.ToString (keyInfo)}");
  916. var map = MapKey (keyInfo);
  917. if (inputEvent.KeyEvent.bKeyDown) {
  918. _altDown = keyInfo.ConsoleKeyInfo.Modifiers == ConsoleModifiers.Alt;
  919. // Avoid sending repeat keydowns
  920. OnKeyDown (new Key (map));
  921. } else {
  922. var keyPressedEventArgs = new Key (map);
  923. // PROTOTYPE: This logic enables `Alt` key presses (down, up, pressed).
  924. // However, if while the 'Alt' key is down, if another key is pressed and
  925. // released, there will be a keypressed event for that and the
  926. // keypressed event for just `Alt` will be suppressed.
  927. // This allows MenuBar to have `Alt` as a keybinding
  928. if (map != KeyCode.AltMask) {
  929. if (keyInfo.ConsoleKeyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt)) {
  930. if (_altDown) {
  931. _altDown = false;
  932. OnKeyUp (new Key (map));
  933. }
  934. }
  935. _altDown = false;
  936. // KeyUp of an Alt-key press.
  937. OnKeyUp (keyPressedEventArgs);
  938. } else {
  939. OnKeyUp (keyPressedEventArgs);
  940. if (_altDown) {
  941. _altDown = false;
  942. }
  943. }
  944. }
  945. break;
  946. case WindowsConsole.EventType.Mouse:
  947. var me = ToDriverMouse (inputEvent.MouseEvent);
  948. OnMouseEvent (new MouseEventEventArgs (me));
  949. if (_processButtonClick) {
  950. OnMouseEvent (new MouseEventEventArgs (new MouseEvent () {
  951. X = me.X,
  952. Y = me.Y,
  953. Flags = ProcessButtonClick (inputEvent.MouseEvent)
  954. }));
  955. }
  956. break;
  957. case WindowsConsole.EventType.Focus:
  958. break;
  959. #if !HACK_CHECK_WINCHANGED
  960. case WindowsConsole.EventType.WindowBufferSize:
  961. Cols = inputEvent.WindowBufferSizeEvent._size.X;
  962. Rows = inputEvent.WindowBufferSizeEvent._size.Y;
  963. ResizeScreen ();
  964. ClearContents ();
  965. TerminalResized.Invoke ();
  966. break;
  967. #endif
  968. }
  969. }
  970. WindowsConsole.ButtonState? _lastMouseButtonPressed = null;
  971. bool _isButtonPressed = false;
  972. bool _isButtonReleased = false;
  973. bool _isButtonDoubleClicked = false;
  974. Point? _point;
  975. Point _pointMove;
  976. bool _isOneFingerDoubleClicked = false;
  977. bool _processButtonClick;
  978. MouseEvent ToDriverMouse (WindowsConsole.MouseEventRecord mouseEvent)
  979. {
  980. MouseFlags mouseFlag = MouseFlags.AllEvents;
  981. //System.Diagnostics.Debug.WriteLine (
  982. // $"X:{mouseEvent.MousePosition.X};Y:{mouseEvent.MousePosition.Y};ButtonState:{mouseEvent.ButtonState};EventFlags:{mouseEvent.EventFlags}");
  983. if (_isButtonDoubleClicked || _isOneFingerDoubleClicked) {
  984. Application.MainLoop.AddIdle (() => {
  985. Task.Run (async () => await ProcessButtonDoubleClickedAsync ());
  986. return false;
  987. });
  988. }
  989. // The ButtonState member of the MouseEvent structure has bit corresponding to each mouse button.
  990. // This will tell when a mouse button is pressed. When the button is released this event will
  991. // be fired with it's bit set to 0. So when the button is up ButtonState will be 0.
  992. // To map to the correct driver events we save the last pressed mouse button so we can
  993. // map to the correct clicked event.
  994. if ((_lastMouseButtonPressed != null || _isButtonReleased) && mouseEvent.ButtonState != 0) {
  995. _lastMouseButtonPressed = null;
  996. //isButtonPressed = false;
  997. _isButtonReleased = false;
  998. }
  999. var p = new Point () {
  1000. X = mouseEvent.MousePosition.X,
  1001. Y = mouseEvent.MousePosition.Y
  1002. };
  1003. if ((mouseEvent.ButtonState != 0 && mouseEvent.EventFlags == 0 && _lastMouseButtonPressed == null && !_isButtonDoubleClicked) ||
  1004. (_lastMouseButtonPressed == null && mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.MouseMoved) &&
  1005. mouseEvent.ButtonState != 0 && !_isButtonReleased && !_isButtonDoubleClicked)) {
  1006. switch (mouseEvent.ButtonState) {
  1007. case WindowsConsole.ButtonState.Button1Pressed:
  1008. mouseFlag = MouseFlags.Button1Pressed;
  1009. break;
  1010. case WindowsConsole.ButtonState.Button2Pressed:
  1011. mouseFlag = MouseFlags.Button2Pressed;
  1012. break;
  1013. case WindowsConsole.ButtonState.RightmostButtonPressed:
  1014. mouseFlag = MouseFlags.Button3Pressed;
  1015. break;
  1016. }
  1017. if (_point == null) {
  1018. _point = p;
  1019. }
  1020. if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  1021. mouseFlag |= MouseFlags.ReportMousePosition;
  1022. _isButtonReleased = false;
  1023. _processButtonClick = false;
  1024. }
  1025. _lastMouseButtonPressed = mouseEvent.ButtonState;
  1026. _isButtonPressed = true;
  1027. if ((mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  1028. Application.MainLoop.AddIdle (() => {
  1029. Task.Run (async () => await ProcessContinuousButtonPressedAsync (mouseFlag));
  1030. return false;
  1031. });
  1032. }
  1033. } else if (_lastMouseButtonPressed != null && mouseEvent.EventFlags == 0
  1034. && !_isButtonReleased && !_isButtonDoubleClicked && !_isOneFingerDoubleClicked) {
  1035. switch (_lastMouseButtonPressed) {
  1036. case WindowsConsole.ButtonState.Button1Pressed:
  1037. mouseFlag = MouseFlags.Button1Released;
  1038. break;
  1039. case WindowsConsole.ButtonState.Button2Pressed:
  1040. mouseFlag = MouseFlags.Button2Released;
  1041. break;
  1042. case WindowsConsole.ButtonState.RightmostButtonPressed:
  1043. mouseFlag = MouseFlags.Button3Released;
  1044. break;
  1045. }
  1046. _isButtonPressed = false;
  1047. _isButtonReleased = true;
  1048. if (_point != null && (((Point)_point).X == mouseEvent.MousePosition.X && ((Point)_point).Y == mouseEvent.MousePosition.Y)) {
  1049. _processButtonClick = true;
  1050. } else {
  1051. _point = null;
  1052. }
  1053. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved
  1054. && !_isOneFingerDoubleClicked && _isButtonReleased && p == _point) {
  1055. mouseFlag = ProcessButtonClick (mouseEvent);
  1056. } else if (mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.DoubleClick)) {
  1057. switch (mouseEvent.ButtonState) {
  1058. case WindowsConsole.ButtonState.Button1Pressed:
  1059. mouseFlag = MouseFlags.Button1DoubleClicked;
  1060. break;
  1061. case WindowsConsole.ButtonState.Button2Pressed:
  1062. mouseFlag = MouseFlags.Button2DoubleClicked;
  1063. break;
  1064. case WindowsConsole.ButtonState.RightmostButtonPressed:
  1065. mouseFlag = MouseFlags.Button3DoubleClicked;
  1066. break;
  1067. }
  1068. _isButtonDoubleClicked = true;
  1069. } else if (mouseEvent.EventFlags == 0 && mouseEvent.ButtonState != 0 && _isButtonDoubleClicked) {
  1070. switch (mouseEvent.ButtonState) {
  1071. case WindowsConsole.ButtonState.Button1Pressed:
  1072. mouseFlag = MouseFlags.Button1TripleClicked;
  1073. break;
  1074. case WindowsConsole.ButtonState.Button2Pressed:
  1075. mouseFlag = MouseFlags.Button2TripleClicked;
  1076. break;
  1077. case WindowsConsole.ButtonState.RightmostButtonPressed:
  1078. mouseFlag = MouseFlags.Button3TripleClicked;
  1079. break;
  1080. }
  1081. _isButtonDoubleClicked = false;
  1082. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled) {
  1083. switch ((int)mouseEvent.ButtonState) {
  1084. case int v when v > 0:
  1085. mouseFlag = MouseFlags.WheeledUp;
  1086. break;
  1087. case int v when v < 0:
  1088. mouseFlag = MouseFlags.WheeledDown;
  1089. break;
  1090. }
  1091. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled &&
  1092. mouseEvent.ControlKeyState == WindowsConsole.ControlKeyState.ShiftPressed) {
  1093. switch ((int)mouseEvent.ButtonState) {
  1094. case int v when v > 0:
  1095. mouseFlag = MouseFlags.WheeledLeft;
  1096. break;
  1097. case int v when v < 0:
  1098. mouseFlag = MouseFlags.WheeledRight;
  1099. break;
  1100. }
  1101. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseHorizontalWheeled) {
  1102. switch ((int)mouseEvent.ButtonState) {
  1103. case int v when v < 0:
  1104. mouseFlag = MouseFlags.WheeledLeft;
  1105. break;
  1106. case int v when v > 0:
  1107. mouseFlag = MouseFlags.WheeledRight;
  1108. break;
  1109. }
  1110. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  1111. mouseFlag = MouseFlags.ReportMousePosition;
  1112. if (mouseEvent.MousePosition.X != _pointMove.X || mouseEvent.MousePosition.Y != _pointMove.Y) {
  1113. _pointMove = new Point (mouseEvent.MousePosition.X, mouseEvent.MousePosition.Y);
  1114. }
  1115. } else if (mouseEvent.ButtonState == 0 && mouseEvent.EventFlags == 0) {
  1116. mouseFlag = 0;
  1117. }
  1118. mouseFlag = SetControlKeyStates (mouseEvent, mouseFlag);
  1119. //System.Diagnostics.Debug.WriteLine (
  1120. // $"point.X:{(point != null ? ((Point)point).X : -1)};point.Y:{(point != null ? ((Point)point).Y : -1)}");
  1121. return new MouseEvent () {
  1122. X = mouseEvent.MousePosition.X,
  1123. Y = mouseEvent.MousePosition.Y,
  1124. Flags = mouseFlag
  1125. };
  1126. }
  1127. MouseFlags ProcessButtonClick (WindowsConsole.MouseEventRecord mouseEvent)
  1128. {
  1129. MouseFlags mouseFlag = 0;
  1130. switch (_lastMouseButtonPressed) {
  1131. case WindowsConsole.ButtonState.Button1Pressed:
  1132. mouseFlag = MouseFlags.Button1Clicked;
  1133. break;
  1134. case WindowsConsole.ButtonState.Button2Pressed:
  1135. mouseFlag = MouseFlags.Button2Clicked;
  1136. break;
  1137. case WindowsConsole.ButtonState.RightmostButtonPressed:
  1138. mouseFlag = MouseFlags.Button3Clicked;
  1139. break;
  1140. }
  1141. _point = new Point () {
  1142. X = mouseEvent.MousePosition.X,
  1143. Y = mouseEvent.MousePosition.Y
  1144. };
  1145. _lastMouseButtonPressed = null;
  1146. _isButtonReleased = false;
  1147. _processButtonClick = false;
  1148. _point = null;
  1149. return mouseFlag;
  1150. }
  1151. async Task ProcessButtonDoubleClickedAsync ()
  1152. {
  1153. await Task.Delay (300);
  1154. _isButtonDoubleClicked = false;
  1155. _isOneFingerDoubleClicked = false;
  1156. //buttonPressedCount = 0;
  1157. }
  1158. async Task ProcessContinuousButtonPressedAsync (MouseFlags mouseFlag)
  1159. {
  1160. while (_isButtonPressed) {
  1161. await Task.Delay (100);
  1162. var me = new MouseEvent () {
  1163. X = _pointMove.X,
  1164. Y = _pointMove.Y,
  1165. Flags = mouseFlag
  1166. };
  1167. var view = Application.WantContinuousButtonPressedView;
  1168. if (view == null) {
  1169. break;
  1170. }
  1171. if (_isButtonPressed && (mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  1172. Application.Invoke (() => OnMouseEvent (new MouseEventEventArgs (me)));
  1173. }
  1174. }
  1175. }
  1176. static MouseFlags SetControlKeyStates (WindowsConsole.MouseEventRecord mouseEvent, MouseFlags mouseFlag)
  1177. {
  1178. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed) ||
  1179. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed)) {
  1180. mouseFlag |= MouseFlags.ButtonCtrl;
  1181. }
  1182. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed)) {
  1183. mouseFlag |= MouseFlags.ButtonShift;
  1184. }
  1185. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed) ||
  1186. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed)) {
  1187. mouseFlag |= MouseFlags.ButtonAlt;
  1188. }
  1189. return mouseFlag;
  1190. }
  1191. public WindowsConsole.ConsoleKeyInfoEx ToConsoleKeyInfoEx (WindowsConsole.KeyEventRecord keyEvent)
  1192. {
  1193. var state = keyEvent.dwControlKeyState;
  1194. var shift = (state & WindowsConsole.ControlKeyState.ShiftPressed) != 0;
  1195. var alt = (state & (WindowsConsole.ControlKeyState.LeftAltPressed | WindowsConsole.ControlKeyState.RightAltPressed)) != 0;
  1196. var control = (state & (WindowsConsole.ControlKeyState.LeftControlPressed | WindowsConsole.ControlKeyState.RightControlPressed)) != 0;
  1197. var capslock = (state & WindowsConsole.ControlKeyState.CapslockOn) != 0;
  1198. var numlock = (state & WindowsConsole.ControlKeyState.NumlockOn) != 0;
  1199. var scrolllock = (state & WindowsConsole.ControlKeyState.ScrolllockOn) != 0;
  1200. var cki = new ConsoleKeyInfo (keyEvent.UnicodeChar, (ConsoleKey)keyEvent.wVirtualKeyCode, shift, alt, control);
  1201. return new WindowsConsole.ConsoleKeyInfoEx (cki, capslock, numlock, scrolllock);
  1202. }
  1203. public WindowsConsole.KeyEventRecord FromVKPacketToKeyEventRecord (WindowsConsole.KeyEventRecord keyEvent)
  1204. {
  1205. if (keyEvent.wVirtualKeyCode != (uint)ConsoleKey.Packet) {
  1206. return keyEvent;
  1207. }
  1208. var mod = new ConsoleModifiers ();
  1209. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed)) {
  1210. mod |= ConsoleModifiers.Shift;
  1211. }
  1212. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed) ||
  1213. keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed)) {
  1214. mod |= ConsoleModifiers.Alt;
  1215. }
  1216. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed) ||
  1217. keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed)) {
  1218. mod |= ConsoleModifiers.Control;
  1219. }
  1220. var cKeyInfo = ConsoleKeyMapping.GetConsoleKeyFromKey (keyEvent.UnicodeChar, mod, out uint scanCode);
  1221. return new WindowsConsole.KeyEventRecord {
  1222. UnicodeChar = cKeyInfo.KeyChar,
  1223. bKeyDown = keyEvent.bKeyDown,
  1224. dwControlKeyState = keyEvent.dwControlKeyState,
  1225. wRepeatCount = keyEvent.wRepeatCount,
  1226. wVirtualKeyCode = (ushort)cKeyInfo.Key,
  1227. wVirtualScanCode = (ushort)scanCode
  1228. };
  1229. }
  1230. public override bool IsRuneSupported (Rune rune)
  1231. {
  1232. return base.IsRuneSupported (rune) && rune.IsBmp;
  1233. }
  1234. void ResizeScreen ()
  1235. {
  1236. _outputBuffer = new WindowsConsole.ExtendedCharInfo [Rows * Cols];
  1237. Clip = new Rect (0, 0, Cols, Rows);
  1238. _damageRegion = new WindowsConsole.SmallRect () {
  1239. Top = 0,
  1240. Left = 0,
  1241. Bottom = (short)Rows,
  1242. Right = (short)Cols
  1243. };
  1244. _dirtyLines = new bool [Rows];
  1245. WinConsole?.ForceRefreshCursorVisibility ();
  1246. }
  1247. public override void UpdateScreen ()
  1248. {
  1249. var windowSize = WinConsole?.GetConsoleBufferWindow (out var _) ?? new Size (Cols, Rows);
  1250. if (!windowSize.IsEmpty && (windowSize.Width != Cols || windowSize.Height != Rows)) {
  1251. return;
  1252. }
  1253. var bufferCoords = new WindowsConsole.Coord () {
  1254. X = (short)Clip.Width,
  1255. Y = (short)Clip.Height
  1256. };
  1257. for (int row = 0; row < Rows; row++) {
  1258. if (!_dirtyLines [row]) {
  1259. continue;
  1260. }
  1261. _dirtyLines [row] = false;
  1262. for (int col = 0; col < Cols; col++) {
  1263. int position = row * Cols + col;
  1264. _outputBuffer [position].Attribute = Contents [row, col].Attribute.GetValueOrDefault ();
  1265. if (Contents [row, col].IsDirty == false) {
  1266. _outputBuffer [position].Empty = true;
  1267. _outputBuffer [position].Char = (char)Rune.ReplacementChar.Value;
  1268. continue;
  1269. }
  1270. _outputBuffer [position].Empty = false;
  1271. if (Contents [row, col].Rune.IsBmp) {
  1272. _outputBuffer [position].Char = (char)Contents [row, col].Rune.Value;
  1273. } else {
  1274. //_outputBuffer [position].Empty = true;
  1275. _outputBuffer [position].Char = (char)Rune.ReplacementChar.Value;
  1276. if (Contents [row, col].Rune.GetColumns () > 1 && col + 1 < Cols) {
  1277. // TODO: This is a hack to deal with non-BMP and wide characters.
  1278. col++;
  1279. position = row * Cols + col;
  1280. _outputBuffer [position].Empty = false;
  1281. _outputBuffer [position].Char = ' ';
  1282. }
  1283. }
  1284. }
  1285. }
  1286. _damageRegion = new WindowsConsole.SmallRect () {
  1287. Top = 0,
  1288. Left = 0,
  1289. Bottom = (short)Rows,
  1290. Right = (short)Cols
  1291. };
  1292. if (!RunningUnitTests && WinConsole != null && !WinConsole.WriteToConsole (new Size (Cols, Rows), _outputBuffer, bufferCoords, _damageRegion, Force16Colors)) {
  1293. var err = Marshal.GetLastWin32Error ();
  1294. if (err != 0) {
  1295. throw new System.ComponentModel.Win32Exception (err);
  1296. }
  1297. }
  1298. WindowsConsole.SmallRect.MakeEmpty (ref _damageRegion);
  1299. }
  1300. public override void Refresh ()
  1301. {
  1302. UpdateScreen ();
  1303. WinConsole?.SetInitialCursorVisibility ();
  1304. UpdateCursor ();
  1305. }
  1306. CursorVisibility _cachedCursorVisibility;
  1307. public override void UpdateCursor ()
  1308. {
  1309. if (Col < 0 || Row < 0 || Col > Cols || Row > Rows) {
  1310. GetCursorVisibility (out CursorVisibility cursorVisibility);
  1311. _cachedCursorVisibility = cursorVisibility;
  1312. SetCursorVisibility (CursorVisibility.Invisible);
  1313. return;
  1314. }
  1315. SetCursorVisibility (_cachedCursorVisibility);
  1316. var position = new WindowsConsole.Coord () {
  1317. X = (short)Col,
  1318. Y = (short)Row
  1319. };
  1320. WinConsole?.SetCursorPosition (position);
  1321. }
  1322. /// <inheritdoc/>
  1323. public override bool GetCursorVisibility (out CursorVisibility visibility)
  1324. {
  1325. if (WinConsole != null) {
  1326. return WinConsole.GetCursorVisibility (out visibility);
  1327. }
  1328. visibility = _cachedCursorVisibility;
  1329. return true;
  1330. }
  1331. /// <inheritdoc/>
  1332. public override bool SetCursorVisibility (CursorVisibility visibility)
  1333. {
  1334. _cachedCursorVisibility = visibility;
  1335. return WinConsole == null || WinConsole.SetCursorVisibility (visibility);
  1336. }
  1337. /// <inheritdoc/>
  1338. public override bool EnsureCursorVisibility ()
  1339. {
  1340. return WinConsole == null || WinConsole.EnsureCursorVisibility ();
  1341. }
  1342. public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control)
  1343. {
  1344. WindowsConsole.InputRecord input = new WindowsConsole.InputRecord {
  1345. EventType = WindowsConsole.EventType.Key
  1346. };
  1347. WindowsConsole.KeyEventRecord keyEvent = new WindowsConsole.KeyEventRecord {
  1348. bKeyDown = true
  1349. };
  1350. WindowsConsole.ControlKeyState controlKey = new WindowsConsole.ControlKeyState ();
  1351. if (shift) {
  1352. controlKey |= WindowsConsole.ControlKeyState.ShiftPressed;
  1353. keyEvent.UnicodeChar = '\0';
  1354. keyEvent.wVirtualKeyCode = 16;
  1355. }
  1356. if (alt) {
  1357. controlKey |= WindowsConsole.ControlKeyState.LeftAltPressed;
  1358. controlKey |= WindowsConsole.ControlKeyState.RightAltPressed;
  1359. keyEvent.UnicodeChar = '\0';
  1360. keyEvent.wVirtualKeyCode = 18;
  1361. }
  1362. if (control) {
  1363. controlKey |= WindowsConsole.ControlKeyState.LeftControlPressed;
  1364. controlKey |= WindowsConsole.ControlKeyState.RightControlPressed;
  1365. keyEvent.UnicodeChar = '\0';
  1366. keyEvent.wVirtualKeyCode = 17;
  1367. }
  1368. keyEvent.dwControlKeyState = controlKey;
  1369. input.KeyEvent = keyEvent;
  1370. if (shift || alt || control) {
  1371. ProcessInput (input);
  1372. }
  1373. keyEvent.UnicodeChar = keyChar;
  1374. if ((uint)key < 255) {
  1375. keyEvent.wVirtualKeyCode = (ushort)key;
  1376. } else {
  1377. keyEvent.wVirtualKeyCode = '\0';
  1378. }
  1379. input.KeyEvent = keyEvent;
  1380. try {
  1381. ProcessInput (input);
  1382. } catch (OverflowException) { } finally {
  1383. keyEvent.bKeyDown = false;
  1384. input.KeyEvent = keyEvent;
  1385. ProcessInput (input);
  1386. }
  1387. }
  1388. internal override void End ()
  1389. {
  1390. if (_mainLoopDriver != null) {
  1391. #if HACK_CHECK_WINCHANGED
  1392. //_mainLoop.WinChanged -= ChangeWin;
  1393. #endif
  1394. }
  1395. _mainLoopDriver = null;
  1396. WinConsole?.Cleanup ();
  1397. WinConsole = null;
  1398. if (!RunningUnitTests && _isWindowsTerminal) {
  1399. // Disable alternative screen buffer.
  1400. Console.Out.Write (EscSeqUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll);
  1401. }
  1402. }
  1403. #region Not Implemented
  1404. public override void Suspend ()
  1405. {
  1406. throw new NotImplementedException ();
  1407. }
  1408. #endregion
  1409. }
  1410. /// <summary>
  1411. /// Mainloop intended to be used with the <see cref="WindowsDriver"/>, and can
  1412. /// only be used on Windows.
  1413. /// </summary>
  1414. /// <remarks>
  1415. /// This implementation is used for WindowsDriver.
  1416. /// </remarks>
  1417. internal class WindowsMainLoop : IMainLoopDriver {
  1418. readonly ManualResetEventSlim _eventReady = new ManualResetEventSlim (false);
  1419. readonly ManualResetEventSlim _waitForProbe = new ManualResetEventSlim (false);
  1420. MainLoop _mainLoop;
  1421. readonly ConsoleDriver _consoleDriver;
  1422. readonly WindowsConsole _winConsole;
  1423. CancellationTokenSource _eventReadyTokenSource = new CancellationTokenSource ();
  1424. CancellationTokenSource _inputHandlerTokenSource = new CancellationTokenSource ();
  1425. // The records that we keep fetching
  1426. readonly Queue<WindowsConsole.InputRecord []> _resultQueue = new Queue<WindowsConsole.InputRecord []> ();
  1427. /// <summary>
  1428. /// Invoked when the window is changed.
  1429. /// </summary>
  1430. public EventHandler<SizeChangedEventArgs> WinChanged;
  1431. public WindowsMainLoop (ConsoleDriver consoleDriver = null)
  1432. {
  1433. _consoleDriver = consoleDriver ?? throw new ArgumentNullException (nameof (consoleDriver));
  1434. _winConsole = ((WindowsDriver)consoleDriver).WinConsole;
  1435. }
  1436. void IMainLoopDriver.Setup (MainLoop mainLoop)
  1437. {
  1438. _mainLoop = mainLoop;
  1439. Task.Run (WindowsInputHandler, _inputHandlerTokenSource.Token);
  1440. #if HACK_CHECK_WINCHANGED
  1441. Task.Run (CheckWinChange);
  1442. #endif
  1443. }
  1444. void WindowsInputHandler ()
  1445. {
  1446. while (_mainLoop != null) {
  1447. try {
  1448. if (!_inputHandlerTokenSource.IsCancellationRequested) {
  1449. _waitForProbe.Wait (_inputHandlerTokenSource.Token);
  1450. }
  1451. } catch (OperationCanceledException) {
  1452. return;
  1453. } finally {
  1454. _waitForProbe.Reset ();
  1455. }
  1456. if (_resultQueue?.Count == 0) {
  1457. _resultQueue.Enqueue (_winConsole.ReadConsoleInput ());
  1458. }
  1459. _eventReady.Set ();
  1460. }
  1461. }
  1462. #if HACK_CHECK_WINCHANGED
  1463. readonly ManualResetEventSlim _winChange = new ManualResetEventSlim (false);
  1464. bool _winChanged;
  1465. Size _windowSize;
  1466. void CheckWinChange ()
  1467. {
  1468. while (_mainLoop != null) {
  1469. _winChange.Wait ();
  1470. _winChange.Reset ();
  1471. // Check if the window size changed every half second.
  1472. // We do this to minimize the weird tearing seen on Windows when resizing the console
  1473. while (_mainLoop != null) {
  1474. Task.Delay (500).Wait ();
  1475. _windowSize = _winConsole.GetConsoleBufferWindow (out _);
  1476. if (_windowSize != Size.Empty && (_windowSize.Width != _consoleDriver.Cols
  1477. || _windowSize.Height != _consoleDriver.Rows)) {
  1478. break;
  1479. }
  1480. }
  1481. _winChanged = true;
  1482. _eventReady.Set ();
  1483. }
  1484. }
  1485. #endif
  1486. void IMainLoopDriver.Wakeup ()
  1487. {
  1488. _eventReady.Set ();
  1489. }
  1490. bool IMainLoopDriver.EventsPending ()
  1491. {
  1492. _waitForProbe.Set ();
  1493. #if HACK_CHECK_WINCHANGED
  1494. _winChange.Set ();
  1495. #endif
  1496. if (_mainLoop.CheckTimersAndIdleHandlers (out var waitTimeout)) {
  1497. return true;
  1498. }
  1499. try {
  1500. if (!_eventReadyTokenSource.IsCancellationRequested) {
  1501. // Note: ManualResetEventSlim.Wait will wait indefinitely if the timeout is -1. The timeout is -1 when there
  1502. // are no timers, but there IS an idle handler waiting.
  1503. _eventReady.Wait (waitTimeout, _eventReadyTokenSource.Token);
  1504. }
  1505. } catch (OperationCanceledException) {
  1506. return true;
  1507. } finally {
  1508. _eventReady.Reset ();
  1509. }
  1510. if (!_eventReadyTokenSource.IsCancellationRequested) {
  1511. #if HACK_CHECK_WINCHANGED
  1512. return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _) || _winChanged;
  1513. #else
  1514. return _resultQueue.Count > 0 || _mainLoop.CheckTimersAndIdleHandlers (out _);
  1515. #endif
  1516. }
  1517. _eventReadyTokenSource.Dispose ();
  1518. _eventReadyTokenSource = new CancellationTokenSource ();
  1519. return true;
  1520. }
  1521. void IMainLoopDriver.Iteration ()
  1522. {
  1523. while (_resultQueue.Count > 0) {
  1524. var inputRecords = _resultQueue.Dequeue ();
  1525. if (inputRecords is { Length: > 0 }) {
  1526. ((WindowsDriver)_consoleDriver).ProcessInput (inputRecords [0]);
  1527. }
  1528. }
  1529. #if HACK_CHECK_WINCHANGED
  1530. if (_winChanged) {
  1531. _winChanged = false;
  1532. WinChanged?.Invoke (this, new SizeChangedEventArgs (_windowSize));
  1533. }
  1534. #endif
  1535. }
  1536. void IMainLoopDriver.TearDown ()
  1537. {
  1538. _inputHandlerTokenSource?.Cancel ();
  1539. _inputHandlerTokenSource?.Dispose ();
  1540. _eventReadyTokenSource?.Cancel ();
  1541. _eventReadyTokenSource?.Dispose ();
  1542. _eventReady?.Dispose ();
  1543. _resultQueue?.Clear ();
  1544. #if HACK_CHECK_WINCHANGED
  1545. _winChange?.Dispose ();
  1546. #endif
  1547. //_waitForProbe?.Dispose ();
  1548. _mainLoop = null;
  1549. }
  1550. }
  1551. class WindowsClipboard : ClipboardBase {
  1552. public WindowsClipboard ()
  1553. {
  1554. IsSupported = IsClipboardFormatAvailable (_cfUnicodeText);
  1555. }
  1556. public override bool IsSupported { get; }
  1557. protected override string GetClipboardDataImpl ()
  1558. {
  1559. try {
  1560. if (!OpenClipboard (IntPtr.Zero)) {
  1561. return string.Empty;
  1562. }
  1563. IntPtr handle = GetClipboardData (_cfUnicodeText);
  1564. if (handle == IntPtr.Zero) {
  1565. return string.Empty;
  1566. }
  1567. IntPtr pointer = IntPtr.Zero;
  1568. try {
  1569. pointer = GlobalLock (handle);
  1570. if (pointer == IntPtr.Zero) {
  1571. return string.Empty;
  1572. }
  1573. int size = GlobalSize (handle);
  1574. byte [] buff = new byte [size];
  1575. Marshal.Copy (pointer, buff, 0, size);
  1576. return System.Text.Encoding.Unicode.GetString (buff).TrimEnd ('\0');
  1577. } finally {
  1578. if (pointer != IntPtr.Zero) {
  1579. GlobalUnlock (handle);
  1580. }
  1581. }
  1582. } finally {
  1583. CloseClipboard ();
  1584. }
  1585. }
  1586. protected override void SetClipboardDataImpl (string text)
  1587. {
  1588. OpenClipboard ();
  1589. EmptyClipboard ();
  1590. IntPtr hGlobal = default;
  1591. try {
  1592. var bytes = (text.Length + 1) * 2;
  1593. hGlobal = Marshal.AllocHGlobal (bytes);
  1594. if (hGlobal == default) {
  1595. ThrowWin32 ();
  1596. }
  1597. var target = GlobalLock (hGlobal);
  1598. if (target == default) {
  1599. ThrowWin32 ();
  1600. }
  1601. try {
  1602. Marshal.Copy (text.ToCharArray (), 0, target, text.Length);
  1603. } finally {
  1604. GlobalUnlock (target);
  1605. }
  1606. if (SetClipboardData (_cfUnicodeText, hGlobal) == default) {
  1607. ThrowWin32 ();
  1608. }
  1609. hGlobal = default;
  1610. } finally {
  1611. if (hGlobal != default) {
  1612. Marshal.FreeHGlobal (hGlobal);
  1613. }
  1614. CloseClipboard ();
  1615. }
  1616. }
  1617. void OpenClipboard ()
  1618. {
  1619. var num = 10;
  1620. while (true) {
  1621. if (OpenClipboard (default)) {
  1622. break;
  1623. }
  1624. if (--num == 0) {
  1625. ThrowWin32 ();
  1626. }
  1627. Thread.Sleep (100);
  1628. }
  1629. }
  1630. const uint _cfUnicodeText = 13;
  1631. void ThrowWin32 ()
  1632. {
  1633. throw new Win32Exception (Marshal.GetLastWin32Error ());
  1634. }
  1635. [DllImport ("User32.dll", SetLastError = true)]
  1636. [return: MarshalAs (UnmanagedType.Bool)]
  1637. static extern bool IsClipboardFormatAvailable (uint format);
  1638. [DllImport ("kernel32.dll", SetLastError = true)]
  1639. static extern int GlobalSize (IntPtr handle);
  1640. [DllImport ("kernel32.dll", SetLastError = true)]
  1641. static extern IntPtr GlobalLock (IntPtr hMem);
  1642. [DllImport ("kernel32.dll", SetLastError = true)]
  1643. [return: MarshalAs (UnmanagedType.Bool)]
  1644. static extern bool GlobalUnlock (IntPtr hMem);
  1645. [DllImport ("user32.dll", SetLastError = true)]
  1646. [return: MarshalAs (UnmanagedType.Bool)]
  1647. static extern bool OpenClipboard (IntPtr hWndNewOwner);
  1648. [DllImport ("user32.dll", SetLastError = true)]
  1649. [return: MarshalAs (UnmanagedType.Bool)]
  1650. static extern bool CloseClipboard ();
  1651. [DllImport ("user32.dll", SetLastError = true)]
  1652. static extern IntPtr SetClipboardData (uint uFormat, IntPtr data);
  1653. [DllImport ("user32.dll")]
  1654. static extern bool EmptyClipboard ();
  1655. [DllImport ("user32.dll", SetLastError = true)]
  1656. static extern IntPtr GetClipboardData (uint uFormat);
  1657. }