WindowsDriver.cs 59 KB

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