WindowsDriver.cs 59 KB

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