WindowsDriver.cs 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020
  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/migueldeicaza/gui.cs/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. internal 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)e.Height);
  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. processButtonClick = false;
  755. }
  756. break;
  757. case WindowsConsole.EventType.WindowBufferSize:
  758. var winSize = WinConsole.GetConsoleBufferWindow (out Point pos);
  759. left = pos.X;
  760. top = pos.Y;
  761. cols = inputEvent.WindowBufferSizeEvent.size.X;
  762. rows = inputEvent.WindowBufferSizeEvent.size.Y;
  763. //System.Diagnostics.Debug.WriteLine ($"{HeightAsBuffer},{cols},{rows}");
  764. ResizeScreen ();
  765. UpdateOffScreen ();
  766. TerminalResized?.Invoke ();
  767. break;
  768. case WindowsConsole.EventType.Focus:
  769. break;
  770. }
  771. }
  772. WindowsConsole.ButtonState? lastMouseButtonPressed = null;
  773. bool isButtonPressed = false;
  774. bool isButtonReleased = false;
  775. bool isButtonDoubleClicked = false;
  776. Point point;
  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 ($"ButtonState: {mouseEvent.ButtonState};EventFlags: {mouseEvent.EventFlags}");
  784. if (isButtonDoubleClicked || isOneFingerDoubleClicked) {
  785. Application.MainLoop.AddIdle (() => {
  786. Task.Run (async () => await ProcessButtonDoubleClickedAsync ());
  787. return false;
  788. });
  789. }
  790. // The ButtonState member of the MouseEvent structure has bit corresponding to each mouse button.
  791. // This will tell when a mouse button is pressed. When the button is released this event will
  792. // be fired with it's bit set to 0. So when the button is up ButtonState will be 0.
  793. // To map to the correct driver events we save the last pressed mouse button so we can
  794. // map to the correct clicked event.
  795. if ((lastMouseButtonPressed != null || isButtonReleased) && mouseEvent.ButtonState != 0) {
  796. lastMouseButtonPressed = null;
  797. //isButtonPressed = false;
  798. isButtonReleased = false;
  799. }
  800. var p = new Point () {
  801. X = mouseEvent.MousePosition.X,
  802. Y = mouseEvent.MousePosition.Y
  803. };
  804. //if (!isButtonPressed && buttonPressedCount < 2
  805. // && mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved
  806. // && (mouseEvent.ButtonState == WindowsConsole.ButtonState.Button1Pressed
  807. // || mouseEvent.ButtonState == WindowsConsole.ButtonState.Button2Pressed
  808. // || mouseEvent.ButtonState == WindowsConsole.ButtonState.Button3Pressed)) {
  809. // lastMouseButtonPressed = mouseEvent.ButtonState;
  810. // buttonPressedCount++;
  811. //} else if (!isButtonPressed && buttonPressedCount > 0 && mouseEvent.ButtonState == 0
  812. // && mouseEvent.EventFlags == 0) {
  813. // buttonPressedCount++;
  814. //}
  815. //System.Diagnostics.Debug.WriteLine ($"isButtonPressed: {isButtonPressed};buttonPressedCount: {buttonPressedCount};lastMouseButtonPressed: {lastMouseButtonPressed}");
  816. //System.Diagnostics.Debug.WriteLine ($"isOneFingerDoubleClicked: {isOneFingerDoubleClicked}");
  817. //if (buttonPressedCount == 1 && lastMouseButtonPressed != null && p == point
  818. // && lastMouseButtonPressed == WindowsConsole.ButtonState.Button1Pressed
  819. // || lastMouseButtonPressed == WindowsConsole.ButtonState.Button2Pressed
  820. // || lastMouseButtonPressed == WindowsConsole.ButtonState.Button3Pressed) {
  821. // switch (lastMouseButtonPressed) {
  822. // case WindowsConsole.ButtonState.Button1Pressed:
  823. // mouseFlag = MouseFlags.Button1DoubleClicked;
  824. // break;
  825. // case WindowsConsole.ButtonState.Button2Pressed:
  826. // mouseFlag = MouseFlags.Button2DoubleClicked;
  827. // break;
  828. // case WindowsConsole.ButtonState.Button3Pressed:
  829. // mouseFlag = MouseFlags.Button3DoubleClicked;
  830. // break;
  831. // }
  832. // isOneFingerDoubleClicked = true;
  833. //} else if (buttonPressedCount == 3 && lastMouseButtonPressed != null && isOneFingerDoubleClicked && p == point
  834. // && lastMouseButtonPressed == WindowsConsole.ButtonState.Button1Pressed
  835. // || lastMouseButtonPressed == WindowsConsole.ButtonState.Button2Pressed
  836. // || lastMouseButtonPressed == WindowsConsole.ButtonState.Button3Pressed) {
  837. // switch (lastMouseButtonPressed) {
  838. // case WindowsConsole.ButtonState.Button1Pressed:
  839. // mouseFlag = MouseFlags.Button1TripleClicked;
  840. // break;
  841. // case WindowsConsole.ButtonState.Button2Pressed:
  842. // mouseFlag = MouseFlags.Button2TripleClicked;
  843. // break;
  844. // case WindowsConsole.ButtonState.Button3Pressed:
  845. // mouseFlag = MouseFlags.Button3TripleClicked;
  846. // break;
  847. // }
  848. // buttonPressedCount = 0;
  849. // lastMouseButtonPressed = null;
  850. // isOneFingerDoubleClicked = false;
  851. // isButtonReleased = false;
  852. //}
  853. if ((mouseEvent.ButtonState != 0 && mouseEvent.EventFlags == 0 && lastMouseButtonPressed == null && !isButtonDoubleClicked) ||
  854. (lastMouseButtonPressed == null && mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved &&
  855. mouseEvent.ButtonState != 0 && !isButtonReleased && !isButtonDoubleClicked)) {
  856. switch (mouseEvent.ButtonState) {
  857. case WindowsConsole.ButtonState.Button1Pressed:
  858. mouseFlag = MouseFlags.Button1Pressed;
  859. break;
  860. case WindowsConsole.ButtonState.Button2Pressed:
  861. mouseFlag = MouseFlags.Button2Pressed;
  862. break;
  863. case WindowsConsole.ButtonState.RightmostButtonPressed:
  864. mouseFlag = MouseFlags.Button3Pressed;
  865. break;
  866. }
  867. if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  868. mouseFlag |= MouseFlags.ReportMousePosition;
  869. point = new Point ();
  870. isButtonReleased = false;
  871. processButtonClick = false;
  872. } else {
  873. point = new Point () {
  874. X = mouseEvent.MousePosition.X,
  875. Y = mouseEvent.MousePosition.Y
  876. };
  877. }
  878. lastMouseButtonPressed = mouseEvent.ButtonState;
  879. isButtonPressed = true;
  880. if ((mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  881. Application.MainLoop.AddIdle (() => {
  882. Task.Run (async () => await ProcessContinuousButtonPressedAsync (mouseEvent, mouseFlag));
  883. return false;
  884. });
  885. }
  886. } else if (lastMouseButtonPressed != null && mouseEvent.EventFlags == 0
  887. && !isButtonReleased && !isButtonDoubleClicked && !isOneFingerDoubleClicked) {
  888. switch (lastMouseButtonPressed) {
  889. case WindowsConsole.ButtonState.Button1Pressed:
  890. mouseFlag = MouseFlags.Button1Released;
  891. break;
  892. case WindowsConsole.ButtonState.Button2Pressed:
  893. mouseFlag = MouseFlags.Button2Released;
  894. break;
  895. case WindowsConsole.ButtonState.RightmostButtonPressed:
  896. mouseFlag = MouseFlags.Button3Released;
  897. break;
  898. }
  899. isButtonPressed = false;
  900. isButtonReleased = true;
  901. if (point.X == mouseEvent.MousePosition.X && point.Y == mouseEvent.MousePosition.Y) {
  902. processButtonClick = true;
  903. }
  904. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved
  905. && !isOneFingerDoubleClicked && isButtonReleased && p == point) {
  906. mouseFlag = ProcessButtonClick (mouseEvent);
  907. } else if (mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.DoubleClick)) {
  908. switch (mouseEvent.ButtonState) {
  909. case WindowsConsole.ButtonState.Button1Pressed:
  910. mouseFlag = MouseFlags.Button1DoubleClicked;
  911. break;
  912. case WindowsConsole.ButtonState.Button2Pressed:
  913. mouseFlag = MouseFlags.Button2DoubleClicked;
  914. break;
  915. case WindowsConsole.ButtonState.RightmostButtonPressed:
  916. mouseFlag = MouseFlags.Button3DoubleClicked;
  917. break;
  918. }
  919. isButtonDoubleClicked = true;
  920. } else if (mouseEvent.EventFlags == 0 && mouseEvent.ButtonState != 0 && isButtonDoubleClicked) {
  921. switch (mouseEvent.ButtonState) {
  922. case WindowsConsole.ButtonState.Button1Pressed:
  923. mouseFlag = MouseFlags.Button1TripleClicked;
  924. break;
  925. case WindowsConsole.ButtonState.Button2Pressed:
  926. mouseFlag = MouseFlags.Button2TripleClicked;
  927. break;
  928. case WindowsConsole.ButtonState.RightmostButtonPressed:
  929. mouseFlag = MouseFlags.Button3TripleClicked;
  930. break;
  931. }
  932. isButtonDoubleClicked = false;
  933. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled) {
  934. switch ((int)mouseEvent.ButtonState) {
  935. case int v when v > 0:
  936. mouseFlag = MouseFlags.WheeledUp;
  937. break;
  938. case int v when v < 0:
  939. mouseFlag = MouseFlags.WheeledDown;
  940. break;
  941. }
  942. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled &&
  943. mouseEvent.ControlKeyState == WindowsConsole.ControlKeyState.ShiftPressed) {
  944. switch ((int)mouseEvent.ButtonState) {
  945. case int v when v > 0:
  946. mouseFlag = MouseFlags.WheeledLeft;
  947. break;
  948. case int v when v < 0:
  949. mouseFlag = MouseFlags.WheeledRight;
  950. break;
  951. }
  952. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseHorizontalWheeled) {
  953. switch ((int)mouseEvent.ButtonState) {
  954. case int v when v < 0:
  955. mouseFlag = MouseFlags.WheeledLeft;
  956. break;
  957. case int v when v > 0:
  958. mouseFlag = MouseFlags.WheeledRight;
  959. break;
  960. }
  961. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  962. if (mouseEvent.MousePosition.X != point.X || mouseEvent.MousePosition.Y != point.Y) {
  963. mouseFlag = MouseFlags.ReportMousePosition;
  964. point = new Point ();
  965. } else {
  966. mouseFlag = 0;
  967. }
  968. } else if (mouseEvent.ButtonState == 0 && mouseEvent.EventFlags == 0) {
  969. mouseFlag = 0;
  970. }
  971. mouseFlag = SetControlKeyStates (mouseEvent, mouseFlag);
  972. return new MouseEvent () {
  973. X = mouseEvent.MousePosition.X,
  974. Y = mouseEvent.MousePosition.Y,
  975. Flags = mouseFlag
  976. };
  977. }
  978. MouseFlags ProcessButtonClick (WindowsConsole.MouseEventRecord mouseEvent)
  979. {
  980. MouseFlags mouseFlag = 0;
  981. switch (lastMouseButtonPressed) {
  982. case WindowsConsole.ButtonState.Button1Pressed:
  983. mouseFlag = MouseFlags.Button1Clicked;
  984. break;
  985. case WindowsConsole.ButtonState.Button2Pressed:
  986. mouseFlag = MouseFlags.Button2Clicked;
  987. break;
  988. case WindowsConsole.ButtonState.RightmostButtonPressed:
  989. mouseFlag = MouseFlags.Button3Clicked;
  990. break;
  991. }
  992. point = new Point () {
  993. X = mouseEvent.MousePosition.X,
  994. Y = mouseEvent.MousePosition.Y
  995. };
  996. lastMouseButtonPressed = null;
  997. isButtonReleased = false;
  998. return mouseFlag;
  999. }
  1000. async Task ProcessButtonDoubleClickedAsync ()
  1001. {
  1002. await Task.Delay (300);
  1003. isButtonDoubleClicked = false;
  1004. isOneFingerDoubleClicked = false;
  1005. //buttonPressedCount = 0;
  1006. }
  1007. async Task ProcessContinuousButtonPressedAsync (WindowsConsole.MouseEventRecord mouseEvent, MouseFlags mouseFlag)
  1008. {
  1009. await Task.Delay (200);
  1010. while (isButtonPressed) {
  1011. await Task.Delay (100);
  1012. var me = new MouseEvent () {
  1013. X = mouseEvent.MousePosition.X,
  1014. Y = mouseEvent.MousePosition.Y,
  1015. Flags = mouseFlag
  1016. };
  1017. var view = Application.wantContinuousButtonPressedView;
  1018. if (view == null) {
  1019. break;
  1020. }
  1021. if (isButtonPressed && (mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  1022. Application.MainLoop.Invoke (() => mouseHandler (me));
  1023. }
  1024. }
  1025. }
  1026. static MouseFlags SetControlKeyStates (WindowsConsole.MouseEventRecord mouseEvent, MouseFlags mouseFlag)
  1027. {
  1028. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed) ||
  1029. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed))
  1030. mouseFlag |= MouseFlags.ButtonCtrl;
  1031. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed))
  1032. mouseFlag |= MouseFlags.ButtonShift;
  1033. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed) ||
  1034. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed))
  1035. mouseFlag |= MouseFlags.ButtonAlt;
  1036. return mouseFlag;
  1037. }
  1038. KeyModifiers keyModifiers;
  1039. public WindowsConsole.ConsoleKeyInfoEx ToConsoleKeyInfoEx (WindowsConsole.KeyEventRecord keyEvent)
  1040. {
  1041. var state = keyEvent.dwControlKeyState;
  1042. bool shift = (state & WindowsConsole.ControlKeyState.ShiftPressed) != 0;
  1043. bool alt = (state & (WindowsConsole.ControlKeyState.LeftAltPressed | WindowsConsole.ControlKeyState.RightAltPressed)) != 0;
  1044. bool control = (state & (WindowsConsole.ControlKeyState.LeftControlPressed | WindowsConsole.ControlKeyState.RightControlPressed)) != 0;
  1045. bool capslock = (state & (WindowsConsole.ControlKeyState.CapslockOn)) != 0;
  1046. bool numlock = (state & (WindowsConsole.ControlKeyState.NumlockOn)) != 0;
  1047. bool scrolllock = (state & (WindowsConsole.ControlKeyState.ScrolllockOn)) != 0;
  1048. if (keyModifiers == null)
  1049. keyModifiers = new KeyModifiers ();
  1050. if (shift)
  1051. keyModifiers.Shift = shift;
  1052. if (alt)
  1053. keyModifiers.Alt = alt;
  1054. if (control)
  1055. keyModifiers.Ctrl = control;
  1056. if (capslock)
  1057. keyModifiers.Capslock = capslock;
  1058. if (numlock)
  1059. keyModifiers.Numlock = numlock;
  1060. if (scrolllock)
  1061. keyModifiers.Scrolllock = scrolllock;
  1062. var ConsoleKeyInfo = new ConsoleKeyInfo (keyEvent.UnicodeChar, (ConsoleKey)keyEvent.wVirtualKeyCode, shift, alt, control);
  1063. return new WindowsConsole.ConsoleKeyInfoEx (ConsoleKeyInfo, capslock, numlock);
  1064. }
  1065. public Key MapKey (WindowsConsole.ConsoleKeyInfoEx keyInfoEx)
  1066. {
  1067. var keyInfo = keyInfoEx.consoleKeyInfo;
  1068. switch (keyInfo.Key) {
  1069. case ConsoleKey.Escape:
  1070. return MapKeyModifiers (keyInfo, Key.Esc);
  1071. case ConsoleKey.Tab:
  1072. return keyInfo.Modifiers == ConsoleModifiers.Shift ? Key.BackTab : Key.Tab;
  1073. case ConsoleKey.Home:
  1074. return MapKeyModifiers (keyInfo, Key.Home);
  1075. case ConsoleKey.End:
  1076. return MapKeyModifiers (keyInfo, Key.End);
  1077. case ConsoleKey.LeftArrow:
  1078. return MapKeyModifiers (keyInfo, Key.CursorLeft);
  1079. case ConsoleKey.RightArrow:
  1080. return MapKeyModifiers (keyInfo, Key.CursorRight);
  1081. case ConsoleKey.UpArrow:
  1082. return MapKeyModifiers (keyInfo, Key.CursorUp);
  1083. case ConsoleKey.DownArrow:
  1084. return MapKeyModifiers (keyInfo, Key.CursorDown);
  1085. case ConsoleKey.PageUp:
  1086. return MapKeyModifiers (keyInfo, Key.PageUp);
  1087. case ConsoleKey.PageDown:
  1088. return MapKeyModifiers (keyInfo, Key.PageDown);
  1089. case ConsoleKey.Enter:
  1090. return MapKeyModifiers (keyInfo, Key.Enter);
  1091. case ConsoleKey.Spacebar:
  1092. return MapKeyModifiers (keyInfo, keyInfo.KeyChar == 0 ? Key.Space : (Key)keyInfo.KeyChar);
  1093. case ConsoleKey.Backspace:
  1094. return MapKeyModifiers (keyInfo, Key.Backspace);
  1095. case ConsoleKey.Delete:
  1096. return MapKeyModifiers (keyInfo, Key.DeleteChar);
  1097. case ConsoleKey.Insert:
  1098. return MapKeyModifiers (keyInfo, Key.InsertChar);
  1099. case ConsoleKey.NumPad0:
  1100. return keyInfoEx.NumLock ? Key.D0 : Key.InsertChar;
  1101. case ConsoleKey.NumPad1:
  1102. return keyInfoEx.NumLock ? Key.D1 : Key.End;
  1103. case ConsoleKey.NumPad2:
  1104. return keyInfoEx.NumLock ? Key.D2 : Key.CursorDown;
  1105. case ConsoleKey.NumPad3:
  1106. return keyInfoEx.NumLock ? Key.D3 : Key.PageDown;
  1107. case ConsoleKey.NumPad4:
  1108. return keyInfoEx.NumLock ? Key.D4 : Key.CursorLeft;
  1109. case ConsoleKey.NumPad5:
  1110. return keyInfoEx.NumLock ? Key.D5 : (Key)((uint)keyInfo.KeyChar);
  1111. case ConsoleKey.NumPad6:
  1112. return keyInfoEx.NumLock ? Key.D6 : Key.CursorRight;
  1113. case ConsoleKey.NumPad7:
  1114. return keyInfoEx.NumLock ? Key.D7 : Key.Home;
  1115. case ConsoleKey.NumPad8:
  1116. return keyInfoEx.NumLock ? Key.D8 : Key.CursorUp;
  1117. case ConsoleKey.NumPad9:
  1118. return keyInfoEx.NumLock ? Key.D9 : Key.PageUp;
  1119. case ConsoleKey.Oem1:
  1120. case ConsoleKey.Oem2:
  1121. case ConsoleKey.Oem3:
  1122. case ConsoleKey.Oem4:
  1123. case ConsoleKey.Oem5:
  1124. case ConsoleKey.Oem6:
  1125. case ConsoleKey.Oem7:
  1126. case ConsoleKey.Oem8:
  1127. case ConsoleKey.Oem102:
  1128. case ConsoleKey.OemPeriod:
  1129. case ConsoleKey.OemComma:
  1130. case ConsoleKey.OemPlus:
  1131. case ConsoleKey.OemMinus:
  1132. if (keyInfo.KeyChar == 0)
  1133. return Key.Unknown;
  1134. return (Key)((uint)keyInfo.KeyChar);
  1135. }
  1136. var key = keyInfo.Key;
  1137. //var alphaBase = ((keyInfo.Modifiers == ConsoleModifiers.Shift) ^ (keyInfoEx.CapsLock)) ? 'A' : 'a';
  1138. if (key >= ConsoleKey.A && key <= ConsoleKey.Z) {
  1139. var delta = key - ConsoleKey.A;
  1140. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  1141. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.A + delta));
  1142. }
  1143. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  1144. return (Key)(((uint)Key.AltMask) | ((uint)Key.A + delta));
  1145. }
  1146. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1147. if (keyInfo.KeyChar == 0 || (keyInfo.KeyChar != 0 && keyInfo.KeyChar >= 1 && keyInfo.KeyChar <= 26)) {
  1148. return MapKeyModifiers (keyInfo, (Key)((uint)Key.A + delta));
  1149. }
  1150. }
  1151. //return (Key)((uint)alphaBase + delta);
  1152. return (Key)((uint)keyInfo.KeyChar);
  1153. }
  1154. if (key >= ConsoleKey.D0 && key <= ConsoleKey.D9) {
  1155. var delta = key - ConsoleKey.D0;
  1156. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  1157. return (Key)(((uint)Key.AltMask) | ((uint)Key.D0 + delta));
  1158. }
  1159. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  1160. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.D0 + delta));
  1161. }
  1162. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1163. if (keyInfo.KeyChar == 0 || keyInfo.KeyChar == 30) {
  1164. return MapKeyModifiers (keyInfo, (Key)((uint)Key.D0 + delta));
  1165. }
  1166. }
  1167. return (Key)((uint)keyInfo.KeyChar);
  1168. }
  1169. if (key >= ConsoleKey.F1 && key <= ConsoleKey.F12) {
  1170. var delta = key - ConsoleKey.F1;
  1171. if ((keyInfo.Modifiers & (ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1172. return MapKeyModifiers (keyInfo, (Key)((uint)Key.F1 + delta));
  1173. }
  1174. return (Key)((uint)Key.F1 + delta);
  1175. }
  1176. if (keyInfo.KeyChar != 0) {
  1177. return MapKeyModifiers (keyInfo, (Key)((uint)keyInfo.KeyChar));
  1178. }
  1179. return (Key)(0xffffffff);
  1180. }
  1181. Key MapKeyModifiers (ConsoleKeyInfo keyInfo, Key key)
  1182. {
  1183. Key keyMod = new Key ();
  1184. if ((keyInfo.Modifiers & ConsoleModifiers.Shift) != 0)
  1185. keyMod = Key.ShiftMask;
  1186. if ((keyInfo.Modifiers & ConsoleModifiers.Control) != 0)
  1187. keyMod |= Key.CtrlMask;
  1188. if ((keyInfo.Modifiers & ConsoleModifiers.Alt) != 0)
  1189. keyMod |= Key.AltMask;
  1190. return keyMod != Key.Null ? keyMod | key : key;
  1191. }
  1192. public override void Init (Action terminalResized)
  1193. {
  1194. TerminalResized = terminalResized;
  1195. var winSize = WinConsole.GetConsoleOutputWindow (out Point pos);
  1196. cols = winSize.Width;
  1197. rows = winSize.Height;
  1198. WindowsConsole.SmallRect.MakeEmpty (ref damageRegion);
  1199. ResizeScreen ();
  1200. UpdateOffScreen ();
  1201. Colors.TopLevel = new ColorScheme ();
  1202. Colors.Base = new ColorScheme ();
  1203. Colors.Dialog = new ColorScheme ();
  1204. Colors.Menu = new ColorScheme ();
  1205. Colors.Error = new ColorScheme ();
  1206. Colors.TopLevel.Normal = MakeColor (ConsoleColor.Green, ConsoleColor.Black);
  1207. Colors.TopLevel.Focus = MakeColor (ConsoleColor.White, ConsoleColor.DarkCyan);
  1208. Colors.TopLevel.HotNormal = MakeColor (ConsoleColor.DarkYellow, ConsoleColor.Black);
  1209. Colors.TopLevel.HotFocus = MakeColor (ConsoleColor.DarkBlue, ConsoleColor.DarkCyan);
  1210. Colors.TopLevel.Disabled = MakeColor (ConsoleColor.DarkGray, ConsoleColor.Black);
  1211. Colors.Base.Normal = MakeColor (ConsoleColor.White, ConsoleColor.DarkBlue);
  1212. Colors.Base.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
  1213. Colors.Base.HotNormal = MakeColor (ConsoleColor.DarkCyan, ConsoleColor.DarkBlue);
  1214. Colors.Base.HotFocus = MakeColor (ConsoleColor.Blue, ConsoleColor.Gray);
  1215. Colors.Base.Disabled = MakeColor (ConsoleColor.DarkGray, ConsoleColor.DarkBlue);
  1216. Colors.Menu.Normal = MakeColor (ConsoleColor.White, ConsoleColor.DarkGray);
  1217. Colors.Menu.Focus = MakeColor (ConsoleColor.White, ConsoleColor.Black);
  1218. Colors.Menu.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.DarkGray);
  1219. Colors.Menu.HotFocus = MakeColor (ConsoleColor.Yellow, ConsoleColor.Black);
  1220. Colors.Menu.Disabled = MakeColor (ConsoleColor.Gray, ConsoleColor.DarkGray);
  1221. Colors.Dialog.Normal = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
  1222. Colors.Dialog.Focus = MakeColor (ConsoleColor.White, ConsoleColor.DarkGray);
  1223. Colors.Dialog.HotNormal = MakeColor (ConsoleColor.DarkBlue, ConsoleColor.Gray);
  1224. Colors.Dialog.HotFocus = MakeColor (ConsoleColor.DarkBlue, ConsoleColor.DarkGray);
  1225. Colors.Dialog.Disabled = MakeColor (ConsoleColor.DarkGray, ConsoleColor.Gray);
  1226. Colors.Error.Normal = MakeColor (ConsoleColor.DarkRed, ConsoleColor.White);
  1227. Colors.Error.Focus = MakeColor (ConsoleColor.White, ConsoleColor.DarkRed);
  1228. Colors.Error.HotNormal = MakeColor (ConsoleColor.Black, ConsoleColor.White);
  1229. Colors.Error.HotFocus = MakeColor (ConsoleColor.Black, ConsoleColor.DarkRed);
  1230. Colors.Error.Disabled = MakeColor (ConsoleColor.DarkGray, ConsoleColor.White);
  1231. }
  1232. void ResizeScreen ()
  1233. {
  1234. OutputBuffer = new WindowsConsole.CharInfo [Rows * Cols];
  1235. Clip = new Rect (0, 0, Cols, Rows);
  1236. damageRegion = new WindowsConsole.SmallRect () {
  1237. Top = 0,
  1238. Left = 0,
  1239. Bottom = (short)Rows,
  1240. Right = (short)Cols
  1241. };
  1242. WinConsole.ForceRefreshCursorVisibility ();
  1243. }
  1244. void UpdateOffScreen ()
  1245. {
  1246. contents = new int [rows, cols, 3];
  1247. for (int row = 0; row < rows; row++) {
  1248. for (int col = 0; col < cols; col++) {
  1249. int position = row * cols + col;
  1250. OutputBuffer [position].Attributes = (ushort)Colors.TopLevel.Normal;
  1251. OutputBuffer [position].Char.UnicodeChar = ' ';
  1252. contents [row, col, 0] = OutputBuffer [position].Char.UnicodeChar;
  1253. contents [row, col, 1] = OutputBuffer [position].Attributes;
  1254. contents [row, col, 2] = 0;
  1255. }
  1256. }
  1257. }
  1258. int ccol, crow;
  1259. public override void Move (int col, int row)
  1260. {
  1261. ccol = col;
  1262. crow = row;
  1263. }
  1264. public override void AddRune (Rune rune)
  1265. {
  1266. rune = MakePrintable (rune);
  1267. var position = crow * Cols + ccol;
  1268. if (Clip.Contains (ccol, crow)) {
  1269. OutputBuffer [position].Attributes = (ushort)currentAttribute;
  1270. OutputBuffer [position].Char.UnicodeChar = (char)rune;
  1271. contents [crow, ccol, 0] = (int)(uint)rune;
  1272. contents [crow, ccol, 1] = currentAttribute;
  1273. contents [crow, ccol, 2] = 1;
  1274. WindowsConsole.SmallRect.Update (ref damageRegion, (short)ccol, (short)crow);
  1275. }
  1276. ccol++;
  1277. var runeWidth = Rune.ColumnWidth (rune);
  1278. if (runeWidth > 1) {
  1279. for (int i = 1; i < runeWidth; i++) {
  1280. AddStr (" ");
  1281. }
  1282. }
  1283. //if (ccol == Cols) {
  1284. // ccol = 0;
  1285. // if (crow + 1 < Rows)
  1286. // crow++;
  1287. //}
  1288. if (sync)
  1289. UpdateScreen ();
  1290. }
  1291. public override void AddStr (ustring str)
  1292. {
  1293. foreach (var rune in str)
  1294. AddRune (rune);
  1295. }
  1296. Attribute currentAttribute;
  1297. public override void SetAttribute (Attribute c)
  1298. {
  1299. currentAttribute = c;
  1300. }
  1301. Attribute MakeColor (ConsoleColor f, ConsoleColor b)
  1302. {
  1303. // Encode the colors into the int value.
  1304. return new Attribute (
  1305. value: ((int)f | (int)b << 4),
  1306. foreground: (Color)f,
  1307. background: (Color)b
  1308. );
  1309. }
  1310. public override Attribute MakeAttribute (Color fore, Color back)
  1311. {
  1312. return MakeColor ((ConsoleColor)fore, (ConsoleColor)back);
  1313. }
  1314. public override void Refresh ()
  1315. {
  1316. UpdateScreen ();
  1317. WinConsole.SetInitialCursorVisibility ();
  1318. #if false
  1319. var bufferCoords = new WindowsConsole.Coord (){
  1320. X = (short)Clip.Width,
  1321. Y = (short)Clip.Height
  1322. };
  1323. var window = new WindowsConsole.SmallRect (){
  1324. Top = 0,
  1325. Left = 0,
  1326. Right = (short)Clip.Right,
  1327. Bottom = (short)Clip.Bottom
  1328. };
  1329. UpdateCursor();
  1330. WinConsole.WriteToConsole (OutputBuffer, bufferCoords, window);
  1331. #endif
  1332. }
  1333. public override void UpdateScreen ()
  1334. {
  1335. if (damageRegion.Left == -1)
  1336. return;
  1337. var bufferCoords = new WindowsConsole.Coord () {
  1338. X = (short)Clip.Width,
  1339. Y = (short)Clip.Height
  1340. };
  1341. //var window = new WindowsConsole.SmallRect () {
  1342. // Top = 0,
  1343. // Left = 0,
  1344. // Right = (short)Clip.Right,
  1345. // Bottom = (short)Clip.Bottom
  1346. //};
  1347. WinConsole.WriteToConsole (new Size (Cols, Rows), OutputBuffer, bufferCoords, damageRegion);
  1348. // The views that wants to display the cursor must call UpdateCursor explicitly.
  1349. //UpdateCursor ();
  1350. // System.Diagnostics.Debugger.Log (0, "debug", $"Region={damageRegion.Right - damageRegion.Left},{damageRegion.Bottom - damageRegion.Top}\n");
  1351. WindowsConsole.SmallRect.MakeEmpty (ref damageRegion);
  1352. }
  1353. CursorVisibility savedCursorVisibility;
  1354. public override void UpdateCursor ()
  1355. {
  1356. if (ccol < 0 || crow < 0 || ccol > Cols || crow > Rows) {
  1357. GetCursorVisibility (out CursorVisibility cursorVisibility);
  1358. savedCursorVisibility = cursorVisibility;
  1359. SetCursorVisibility (CursorVisibility.Invisible);
  1360. return;
  1361. }
  1362. SetCursorVisibility (savedCursorVisibility);
  1363. var position = new WindowsConsole.Coord () {
  1364. X = (short)ccol,
  1365. Y = (short)crow
  1366. };
  1367. WinConsole.SetCursorPosition (position);
  1368. }
  1369. public override void End ()
  1370. {
  1371. WinConsole.Cleanup ();
  1372. WinConsole = null;
  1373. }
  1374. public override Attribute GetAttribute ()
  1375. {
  1376. return currentAttribute;
  1377. }
  1378. /// <inheritdoc/>
  1379. public override bool GetCursorVisibility (out CursorVisibility visibility)
  1380. {
  1381. return WinConsole.GetCursorVisibility (out visibility);
  1382. }
  1383. /// <inheritdoc/>
  1384. public override bool SetCursorVisibility (CursorVisibility visibility)
  1385. {
  1386. return WinConsole.SetCursorVisibility (visibility);
  1387. }
  1388. /// <inheritdoc/>
  1389. public override bool EnsureCursorVisibility ()
  1390. {
  1391. return WinConsole.EnsureCursorVisibility ();
  1392. }
  1393. public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control)
  1394. {
  1395. WindowsConsole.InputRecord input = new WindowsConsole.InputRecord {
  1396. EventType = WindowsConsole.EventType.Key
  1397. };
  1398. WindowsConsole.KeyEventRecord keyEvent = new WindowsConsole.KeyEventRecord {
  1399. bKeyDown = true
  1400. };
  1401. WindowsConsole.ControlKeyState controlKey = new WindowsConsole.ControlKeyState ();
  1402. if (shift) {
  1403. controlKey |= WindowsConsole.ControlKeyState.ShiftPressed;
  1404. keyEvent.UnicodeChar = '\0';
  1405. keyEvent.wVirtualKeyCode = 16;
  1406. }
  1407. if (alt) {
  1408. controlKey |= WindowsConsole.ControlKeyState.LeftAltPressed;
  1409. controlKey |= WindowsConsole.ControlKeyState.RightAltPressed;
  1410. keyEvent.UnicodeChar = '\0';
  1411. keyEvent.wVirtualKeyCode = 18;
  1412. }
  1413. if (control) {
  1414. controlKey |= WindowsConsole.ControlKeyState.LeftControlPressed;
  1415. controlKey |= WindowsConsole.ControlKeyState.RightControlPressed;
  1416. keyEvent.UnicodeChar = '\0';
  1417. keyEvent.wVirtualKeyCode = 17;
  1418. }
  1419. keyEvent.dwControlKeyState = controlKey;
  1420. input.KeyEvent = keyEvent;
  1421. if (shift || alt || control) {
  1422. ProcessInput (input);
  1423. }
  1424. keyEvent.UnicodeChar = keyChar;
  1425. if ((shift || alt || control)
  1426. && (key >= ConsoleKey.A && key <= ConsoleKey.Z
  1427. || key >= ConsoleKey.D0 && key <= ConsoleKey.D9)) {
  1428. keyEvent.wVirtualKeyCode = (ushort)key;
  1429. } else {
  1430. keyEvent.wVirtualKeyCode = '\0';
  1431. }
  1432. input.KeyEvent = keyEvent;
  1433. try {
  1434. ProcessInput (input);
  1435. } catch (OverflowException) { } finally {
  1436. keyEvent.bKeyDown = false;
  1437. input.KeyEvent = keyEvent;
  1438. ProcessInput (input);
  1439. }
  1440. }
  1441. public override bool GetColors (int value, out Color foreground, out Color background)
  1442. {
  1443. bool hasColor = false;
  1444. foreground = default;
  1445. background = default;
  1446. IEnumerable<int> values = Enum.GetValues (typeof (ConsoleColor))
  1447. .OfType<ConsoleColor> ()
  1448. .Select (s => (int)s);
  1449. if (values.Contains ((value >> 4) & 0xffff)) {
  1450. hasColor = true;
  1451. background = (Color)(ConsoleColor)((value >> 4) & 0xffff);
  1452. }
  1453. if (values.Contains (value - ((int)background << 4))) {
  1454. hasColor = true;
  1455. foreground = (Color)(ConsoleColor)(value - ((int)background << 4));
  1456. }
  1457. return hasColor;
  1458. }
  1459. #region Unused
  1460. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  1461. {
  1462. }
  1463. public override void SetColors (short foregroundColorId, short backgroundColorId)
  1464. {
  1465. }
  1466. public override void Suspend ()
  1467. {
  1468. }
  1469. public override void StartReportingMouseMoves ()
  1470. {
  1471. }
  1472. public override void StopReportingMouseMoves ()
  1473. {
  1474. }
  1475. public override void UncookMouse ()
  1476. {
  1477. }
  1478. public override void CookMouse ()
  1479. {
  1480. }
  1481. #endregion
  1482. }
  1483. /// <summary>
  1484. /// Mainloop intended to be used with the <see cref="WindowsDriver"/>, and can
  1485. /// only be used on Windows.
  1486. /// </summary>
  1487. /// <remarks>
  1488. /// This implementation is used for WindowsDriver.
  1489. /// </remarks>
  1490. internal class WindowsMainLoop : IMainLoopDriver {
  1491. ManualResetEventSlim eventReady = new ManualResetEventSlim (false);
  1492. ManualResetEventSlim waitForProbe = new ManualResetEventSlim (false);
  1493. ManualResetEventSlim winChange = new ManualResetEventSlim (false);
  1494. MainLoop mainLoop;
  1495. ConsoleDriver consoleDriver;
  1496. WindowsConsole winConsole;
  1497. bool winChanged;
  1498. Size windowSize;
  1499. CancellationTokenSource tokenSource = new CancellationTokenSource ();
  1500. // The records that we keep fetching
  1501. Queue<WindowsConsole.InputRecord []> resultQueue = new Queue<WindowsConsole.InputRecord []> ();
  1502. /// <summary>
  1503. /// Invoked when a Key is pressed or released.
  1504. /// </summary>
  1505. public Action<WindowsConsole.InputRecord> ProcessInput;
  1506. /// <summary>
  1507. /// Invoked when the window is changed.
  1508. /// </summary>
  1509. public Action<Size> WinChanged;
  1510. public WindowsMainLoop (ConsoleDriver consoleDriver = null)
  1511. {
  1512. this.consoleDriver = consoleDriver ?? throw new ArgumentNullException ("Console driver instance must be provided.");
  1513. winConsole = ((WindowsDriver)consoleDriver).WinConsole;
  1514. }
  1515. void IMainLoopDriver.Setup (MainLoop mainLoop)
  1516. {
  1517. this.mainLoop = mainLoop;
  1518. Task.Run (WindowsInputHandler);
  1519. Task.Run (CheckWinChange);
  1520. }
  1521. void WindowsInputHandler ()
  1522. {
  1523. while (true) {
  1524. waitForProbe.Wait ();
  1525. waitForProbe.Reset ();
  1526. if (resultQueue?.Count == 0) {
  1527. resultQueue.Enqueue (winConsole.ReadConsoleInput ());
  1528. }
  1529. eventReady.Set ();
  1530. }
  1531. }
  1532. void CheckWinChange ()
  1533. {
  1534. while (true) {
  1535. winChange.Wait ();
  1536. winChange.Reset ();
  1537. WaitWinChange ();
  1538. winChanged = true;
  1539. eventReady.Set ();
  1540. }
  1541. }
  1542. void WaitWinChange ()
  1543. {
  1544. while (true) {
  1545. Thread.Sleep (100);
  1546. if (!consoleDriver.HeightAsBuffer) {
  1547. windowSize = winConsole.GetConsoleBufferWindow (out _);
  1548. //System.Diagnostics.Debug.WriteLine ($"{consoleDriver.HeightAsBuffer},{windowSize.Width},{windowSize.Height}");
  1549. if (windowSize != Size.Empty && windowSize.Width != consoleDriver.Cols
  1550. || windowSize.Height != consoleDriver.Rows) {
  1551. return;
  1552. }
  1553. }
  1554. }
  1555. }
  1556. void IMainLoopDriver.Wakeup ()
  1557. {
  1558. //tokenSource.Cancel ();
  1559. eventReady.Set ();
  1560. }
  1561. bool IMainLoopDriver.EventsPending (bool wait)
  1562. {
  1563. if (CheckTimers (wait, out var waitTimeout)) {
  1564. return true;
  1565. }
  1566. waitForProbe.Set ();
  1567. winChange.Set ();
  1568. try {
  1569. if (!tokenSource.IsCancellationRequested) {
  1570. eventReady.Wait (waitTimeout, tokenSource.Token);
  1571. }
  1572. } catch (OperationCanceledException) {
  1573. return true;
  1574. } finally {
  1575. eventReady.Reset ();
  1576. }
  1577. if (!tokenSource.IsCancellationRequested) {
  1578. return resultQueue.Count > 0 || CheckTimers (wait, out _) || winChanged;
  1579. }
  1580. tokenSource.Dispose ();
  1581. tokenSource = new CancellationTokenSource ();
  1582. return true;
  1583. }
  1584. bool CheckTimers (bool wait, out int waitTimeout)
  1585. {
  1586. long now = DateTime.UtcNow.Ticks;
  1587. if (mainLoop.timeouts.Count > 0) {
  1588. waitTimeout = (int)((mainLoop.timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  1589. if (waitTimeout < 0)
  1590. return true;
  1591. } else {
  1592. waitTimeout = -1;
  1593. }
  1594. if (!wait)
  1595. waitTimeout = 0;
  1596. int ic;
  1597. lock (mainLoop.idleHandlers) {
  1598. ic = mainLoop.idleHandlers.Count;
  1599. }
  1600. return ic > 0;
  1601. }
  1602. void IMainLoopDriver.MainIteration ()
  1603. {
  1604. while (resultQueue.Count > 0) {
  1605. var inputEvent = resultQueue.Dequeue () [0];
  1606. ProcessInput?.Invoke (inputEvent);
  1607. }
  1608. if (winChanged) {
  1609. winChanged = false;
  1610. WinChanged?.Invoke (windowSize);
  1611. }
  1612. }
  1613. }
  1614. class WindowsClipboard : ClipboardBase {
  1615. public WindowsClipboard ()
  1616. {
  1617. IsSupported = IsClipboardFormatAvailable (cfUnicodeText);
  1618. }
  1619. public override bool IsSupported { get; }
  1620. protected override string GetClipboardDataImpl ()
  1621. {
  1622. //if (!IsClipboardFormatAvailable (cfUnicodeText))
  1623. // return null;
  1624. try {
  1625. if (!OpenClipboard (IntPtr.Zero))
  1626. return null;
  1627. IntPtr handle = GetClipboardData (cfUnicodeText);
  1628. if (handle == IntPtr.Zero)
  1629. return null;
  1630. IntPtr pointer = IntPtr.Zero;
  1631. try {
  1632. pointer = GlobalLock (handle);
  1633. if (pointer == IntPtr.Zero)
  1634. return null;
  1635. int size = GlobalSize (handle);
  1636. byte [] buff = new byte [size];
  1637. Marshal.Copy (pointer, buff, 0, size);
  1638. return System.Text.Encoding.Unicode.GetString (buff)
  1639. .TrimEnd ('\0');
  1640. } finally {
  1641. if (pointer != IntPtr.Zero)
  1642. GlobalUnlock (handle);
  1643. }
  1644. } finally {
  1645. CloseClipboard ();
  1646. }
  1647. }
  1648. protected override void SetClipboardDataImpl (string text)
  1649. {
  1650. OpenClipboard ();
  1651. EmptyClipboard ();
  1652. IntPtr hGlobal = default;
  1653. try {
  1654. var bytes = (text.Length + 1) * 2;
  1655. hGlobal = Marshal.AllocHGlobal (bytes);
  1656. if (hGlobal == default) {
  1657. ThrowWin32 ();
  1658. }
  1659. var target = GlobalLock (hGlobal);
  1660. if (target == default) {
  1661. ThrowWin32 ();
  1662. }
  1663. try {
  1664. Marshal.Copy (text.ToCharArray (), 0, target, text.Length);
  1665. } finally {
  1666. GlobalUnlock (target);
  1667. }
  1668. if (SetClipboardData (cfUnicodeText, hGlobal) == default) {
  1669. ThrowWin32 ();
  1670. }
  1671. hGlobal = default;
  1672. } finally {
  1673. if (hGlobal != default) {
  1674. Marshal.FreeHGlobal (hGlobal);
  1675. }
  1676. CloseClipboard ();
  1677. }
  1678. }
  1679. void OpenClipboard ()
  1680. {
  1681. var num = 10;
  1682. while (true) {
  1683. if (OpenClipboard (default)) {
  1684. break;
  1685. }
  1686. if (--num == 0) {
  1687. ThrowWin32 ();
  1688. }
  1689. Thread.Sleep (100);
  1690. }
  1691. }
  1692. const uint cfUnicodeText = 13;
  1693. void ThrowWin32 ()
  1694. {
  1695. throw new Win32Exception (Marshal.GetLastWin32Error ());
  1696. }
  1697. [DllImport ("User32.dll", SetLastError = true)]
  1698. [return: MarshalAs (UnmanagedType.Bool)]
  1699. static extern bool IsClipboardFormatAvailable (uint format);
  1700. [DllImport ("kernel32.dll", SetLastError = true)]
  1701. static extern int GlobalSize (IntPtr handle);
  1702. [DllImport ("kernel32.dll", SetLastError = true)]
  1703. static extern IntPtr GlobalLock (IntPtr hMem);
  1704. [DllImport ("kernel32.dll", SetLastError = true)]
  1705. [return: MarshalAs (UnmanagedType.Bool)]
  1706. static extern bool GlobalUnlock (IntPtr hMem);
  1707. [DllImport ("user32.dll", SetLastError = true)]
  1708. [return: MarshalAs (UnmanagedType.Bool)]
  1709. static extern bool OpenClipboard (IntPtr hWndNewOwner);
  1710. [DllImport ("user32.dll", SetLastError = true)]
  1711. [return: MarshalAs (UnmanagedType.Bool)]
  1712. static extern bool CloseClipboard ();
  1713. [DllImport ("user32.dll", SetLastError = true)]
  1714. static extern IntPtr SetClipboardData (uint uFormat, IntPtr data);
  1715. [DllImport ("user32.dll")]
  1716. static extern bool EmptyClipboard ();
  1717. [DllImport ("user32.dll", SetLastError = true)]
  1718. static extern IntPtr GetClipboardData (uint uFormat);
  1719. }
  1720. }