WindowsDriver.cs 54 KB

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