2
0

WindowsDriver.cs 58 KB

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