WindowsDriver.cs 64 KB

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