WindowsDriver.cs 48 KB

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