WindowsDriver.cs 62 KB

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