WindowsDriver.cs 58 KB

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