WindowsDriver.cs 57 KB

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