WindowsDriver.cs 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684
  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. [StructLayout (LayoutKind.Sequential, CharSet = CharSet.Unicode)]
  458. public class ConsoleFontInfoEx {
  459. private int cbSize;
  460. public ConsoleFontInfoEx ()
  461. {
  462. cbSize = Marshal.SizeOf (typeof (ConsoleFontInfoEx));
  463. }
  464. public int FontIndex;
  465. public short FontWidth;
  466. public short FontHeight;
  467. public int FontFamily;
  468. public int FontWeight;
  469. [MarshalAs (UnmanagedType.ByValTStr, SizeConst = 32)]
  470. public string FaceName;
  471. }
  472. [DllImport ("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  473. extern static bool GetCurrentConsoleFontEx (
  474. IntPtr hConsoleOutput,
  475. bool bMaximumWindow,
  476. [In, Out] ConsoleFontInfoEx lpConsoleCurrentFont);
  477. internal ConsoleFontInfoEx GetCurrentFontSize ()
  478. {
  479. //IntPtr _consoleOutputHandle = GetStdHandle (STD_OUTPUT_HANDLE);
  480. IntPtr _consoleOutputHandle = OutputHandle;
  481. ConsoleFontInfoEx currentFont = new ConsoleFontInfoEx ();
  482. GetCurrentConsoleFontEx (
  483. _consoleOutputHandle,
  484. false,
  485. currentFont);
  486. return currentFont;
  487. }
  488. #if false
  489. // size of a device name string
  490. private const int CCHDEVICENAME = 32;
  491. [StructLayout (LayoutKind.Sequential, CharSet = CharSet.Auto)]
  492. internal struct MonitorInfoEx {
  493. public uint cbSize;
  494. public System.Drawing.Rectangle rcMonitor;
  495. public System.Drawing.Rectangle rcWork;
  496. public int dwFlags;
  497. [MarshalAs (UnmanagedType.ByValTStr, SizeConst = CCHDEVICENAME)]
  498. public string szDevice;
  499. }
  500. [DllImport ("user32.dll", CharSet = CharSet.Auto)]
  501. static extern bool GetMonitorInfo (IntPtr hMonitor, ref MonitorInfoEx lpmi);
  502. internal bool GetMonitor(IntPtr hMonitor, ref MonitorInfoEx minfo)
  503. {
  504. minfo.cbSize = (uint)Marshal.SizeOf (minfo);
  505. return GetMonitorInfo (hMonitor, ref minfo);
  506. }
  507. [DllImport ("user32.dll")]
  508. static extern IntPtr MonitorFromWindow (IntPtr hwnd, uint dwFlags);
  509. public const int MONITOR_DEFAULTTONULL = 0;
  510. public const int MONITOR_DEFAULTTOPRIMARY = 1;
  511. public const int MONITOR_DEFAULTTONEAREST = 2;
  512. internal IntPtr GetMonitorWindow (IntPtr hwnd, uint dwFlag)
  513. {
  514. return MonitorFromWindow (hwnd, dwFlag);
  515. }
  516. [DllImport ("kernel32.dll", SetLastError = true)]
  517. static extern bool GetConsoleScreenBufferInfo (IntPtr hConsoleOutput, out ConsoleScreenBufferInfo ConsoleScreenBufferInfo);
  518. // Theoretically GetConsoleScreenBuffer height should give the console Window size, but the Top is always 0.
  519. // It does not work, however, and always returns the size the window was initially created at
  520. internal Size GetWindowSize (IntPtr handle)
  521. {
  522. GetConsoleScreenBufferInfo (handle, out ConsoleScreenBufferInfo consoleScreenBufferInfo);
  523. return new Size (consoleScreenBufferInfo.srWindow.Right - consoleScreenBufferInfo.srWindow.Left + 1,
  524. consoleScreenBufferInfo.srWindow.Bottom - consoleScreenBufferInfo.srWindow.Top + 1);
  525. }
  526. #endif
  527. }
  528. internal class WindowsDriver : ConsoleDriver {
  529. static bool sync = false;
  530. WindowsConsole.CharInfo [] OutputBuffer;
  531. int cols, rows, top;
  532. WindowsConsole winConsole;
  533. WindowsConsole.SmallRect damageRegion;
  534. public override int Cols => cols;
  535. public override int Rows => rows;
  536. public override int Top => top;
  537. bool heightAsBuffer;
  538. public override bool HeightAsBuffer {
  539. get => heightAsBuffer;
  540. set {
  541. heightAsBuffer = value;
  542. if (heightAsBuffer) {
  543. ResizeScreen ();
  544. UpdateOffScreen ();
  545. var bufferCoords = new WindowsConsole.Coord () {
  546. X = (short)cols,
  547. Y = (short)rows
  548. };
  549. winConsole.ReadFromConsoleOutput (new Size (cols, rows), bufferCoords, damageRegion);
  550. }
  551. Refresh ();
  552. }
  553. }
  554. public WindowsConsole WinConsole {
  555. get => winConsole;
  556. private set => winConsole = value;
  557. }
  558. Action<KeyEvent> keyHandler;
  559. Action<KeyEvent> keyDownHandler;
  560. Action<KeyEvent> keyUpHandler;
  561. Action<MouseEvent> mouseHandler;
  562. public WindowsDriver ()
  563. {
  564. winConsole = new WindowsConsole () {
  565. HeightAsBuffer = this.HeightAsBuffer
  566. };
  567. }
  568. MainLoop mainLoop;
  569. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
  570. {
  571. this.keyHandler = keyHandler;
  572. this.keyDownHandler = keyDownHandler;
  573. this.keyUpHandler = keyUpHandler;
  574. this.mouseHandler = mouseHandler;
  575. this.mainLoop = mainLoop;
  576. var mLoop = mainLoop.Driver as WindowsMainLoop;
  577. mLoop.ProcessInput = (e) => ProcessInput (e);
  578. mLoop.WinChanged = (e) => ChangeWin (e);
  579. }
  580. bool winChanging;
  581. bool wasChangeWin;
  582. void ChangeWin (Size size)
  583. {
  584. if (!HeightAsBuffer) {
  585. winChanging = true;
  586. top = 0;
  587. cols = size.Width;
  588. rows = size.Height;
  589. ResizeScreen ();
  590. UpdateOffScreen ();
  591. var bufferCoords = new WindowsConsole.Coord () {
  592. X = (short)cols,
  593. Y = (short)rows
  594. };
  595. winConsole.ReadFromConsoleOutput (size, bufferCoords, damageRegion);
  596. if (!winChanging) {
  597. TerminalResized.Invoke ();
  598. }
  599. wasChangeWin = true;
  600. }
  601. }
  602. bool isFromRestore;
  603. void ProcessInput (WindowsConsole.InputRecord inputEvent)
  604. {
  605. switch (inputEvent.EventType) {
  606. case WindowsConsole.EventType.Key:
  607. var map = MapKey (ToConsoleKeyInfoEx (inputEvent.KeyEvent));
  608. if (map == (Key)0xffffffff) {
  609. KeyEvent key = new KeyEvent ();
  610. // Shift = VK_SHIFT = 0x10
  611. // Ctrl = VK_CONTROL = 0x11
  612. // Alt = VK_MENU = 0x12
  613. if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.CapslockOn)) {
  614. inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.CapslockOn;
  615. }
  616. if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ScrolllockOn)) {
  617. inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.ScrolllockOn;
  618. }
  619. if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.NumlockOn)) {
  620. inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.NumlockOn;
  621. }
  622. switch (inputEvent.KeyEvent.dwControlKeyState) {
  623. case WindowsConsole.ControlKeyState.RightAltPressed:
  624. case WindowsConsole.ControlKeyState.RightAltPressed |
  625. WindowsConsole.ControlKeyState.LeftControlPressed |
  626. WindowsConsole.ControlKeyState.EnhancedKey:
  627. case WindowsConsole.ControlKeyState.EnhancedKey:
  628. key = new KeyEvent (Key.CtrlMask | Key.AltMask, keyModifiers);
  629. break;
  630. case WindowsConsole.ControlKeyState.LeftAltPressed:
  631. key = new KeyEvent (Key.AltMask, keyModifiers);
  632. break;
  633. case WindowsConsole.ControlKeyState.RightControlPressed:
  634. case WindowsConsole.ControlKeyState.LeftControlPressed:
  635. key = new KeyEvent (Key.CtrlMask, keyModifiers);
  636. break;
  637. case WindowsConsole.ControlKeyState.ShiftPressed:
  638. key = new KeyEvent (Key.ShiftMask, keyModifiers);
  639. break;
  640. case WindowsConsole.ControlKeyState.NumlockOn:
  641. break;
  642. case WindowsConsole.ControlKeyState.ScrolllockOn:
  643. break;
  644. case WindowsConsole.ControlKeyState.CapslockOn:
  645. break;
  646. default:
  647. switch (inputEvent.KeyEvent.wVirtualKeyCode) {
  648. case 0x10:
  649. key = new KeyEvent (Key.ShiftMask, keyModifiers);
  650. break;
  651. case 0x11:
  652. key = new KeyEvent (Key.CtrlMask, keyModifiers);
  653. break;
  654. case 0x12:
  655. key = new KeyEvent (Key.AltMask, keyModifiers);
  656. break;
  657. default:
  658. key = new KeyEvent (Key.Unknown, keyModifiers);
  659. break;
  660. }
  661. break;
  662. }
  663. if (inputEvent.KeyEvent.bKeyDown)
  664. keyDownHandler (key);
  665. else
  666. keyUpHandler (key);
  667. } else {
  668. if (inputEvent.KeyEvent.bKeyDown) {
  669. // Key Down - Fire KeyDown Event and KeyStroke (ProcessKey) Event
  670. keyDownHandler (new KeyEvent (map, keyModifiers));
  671. keyHandler (new KeyEvent (map, keyModifiers));
  672. } else {
  673. keyUpHandler (new KeyEvent (map, keyModifiers));
  674. }
  675. }
  676. if (!inputEvent.KeyEvent.bKeyDown) {
  677. keyModifiers = null;
  678. }
  679. break;
  680. case WindowsConsole.EventType.Mouse:
  681. mouseHandler (ToDriverMouse (inputEvent.MouseEvent));
  682. if (IsButtonReleased)
  683. mouseHandler (ToDriverMouse (inputEvent.MouseEvent));
  684. break;
  685. case WindowsConsole.EventType.WindowBufferSize:
  686. if (HeightAsBuffer) {
  687. cols = inputEvent.WindowBufferSizeEvent.size.X;
  688. rows = inputEvent.WindowBufferSizeEvent.size.Y;
  689. ResizeScreen ();
  690. UpdateOffScreen ();
  691. TerminalResized?.Invoke ();
  692. } else if (!HeightAsBuffer && !wasChangeWin && !(mainLoop.Driver as WindowsMainLoop).Maximized
  693. && !isFromRestore) {
  694. ChangeWin (new Size (inputEvent.WindowBufferSizeEvent.size.X,
  695. inputEvent.WindowBufferSizeEvent.size.Y));
  696. } else if (!HeightAsBuffer && wasChangeWin && (mainLoop.Driver as WindowsMainLoop).Restored) {
  697. (mainLoop.Driver as WindowsMainLoop).Restored = false;
  698. isFromRestore = true;
  699. } else if (!HeightAsBuffer && wasChangeWin && !(mainLoop.Driver as WindowsMainLoop).Maximized
  700. && !(mainLoop.Driver as WindowsMainLoop).Restored && !isFromRestore) {
  701. wasChangeWin = false;
  702. } else if (isFromRestore) {
  703. isFromRestore = false;
  704. }
  705. break;
  706. case WindowsConsole.EventType.Focus:
  707. break;
  708. }
  709. }
  710. WindowsConsole.ButtonState? LastMouseButtonPressed = null;
  711. bool IsButtonPressed = false;
  712. bool IsButtonReleased = false;
  713. bool IsButtonDoubleClicked = false;
  714. Point point;
  715. MouseEvent ToDriverMouse (WindowsConsole.MouseEventRecord mouseEvent)
  716. {
  717. MouseFlags mouseFlag = MouseFlags.AllEvents;
  718. if (IsButtonDoubleClicked) {
  719. Application.MainLoop.AddIdle (() => {
  720. ProcessButtonDoubleClickedAsync ().ConfigureAwait (false);
  721. return false;
  722. });
  723. }
  724. // The ButtonState member of the MouseEvent structure has bit corresponding to each mouse button.
  725. // This will tell when a mouse button is pressed. When the button is released this event will
  726. // be fired with it's bit set to 0. So when the button is up ButtonState will be 0.
  727. // To map to the correct driver events we save the last pressed mouse button so we can
  728. // map to the correct clicked event.
  729. if ((LastMouseButtonPressed != null || IsButtonReleased) && mouseEvent.ButtonState != 0) {
  730. LastMouseButtonPressed = null;
  731. IsButtonPressed = false;
  732. IsButtonReleased = false;
  733. }
  734. var p = new Point () {
  735. X = mouseEvent.MousePosition.X,
  736. Y = mouseEvent.MousePosition.Y
  737. };
  738. if ((mouseEvent.ButtonState != 0 && mouseEvent.EventFlags == 0 && LastMouseButtonPressed == null && !IsButtonDoubleClicked) ||
  739. (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved &&
  740. mouseEvent.ButtonState != 0 && !IsButtonReleased && !IsButtonDoubleClicked)) {
  741. switch (mouseEvent.ButtonState) {
  742. case WindowsConsole.ButtonState.Button1Pressed:
  743. mouseFlag = MouseFlags.Button1Pressed;
  744. break;
  745. case WindowsConsole.ButtonState.Button2Pressed:
  746. mouseFlag = MouseFlags.Button2Pressed;
  747. break;
  748. case WindowsConsole.ButtonState.RightmostButtonPressed:
  749. mouseFlag = MouseFlags.Button3Pressed;
  750. break;
  751. }
  752. if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  753. mouseFlag |= MouseFlags.ReportMousePosition;
  754. point = new Point ();
  755. IsButtonReleased = false;
  756. } else {
  757. point = new Point () {
  758. X = mouseEvent.MousePosition.X,
  759. Y = mouseEvent.MousePosition.Y
  760. };
  761. }
  762. LastMouseButtonPressed = mouseEvent.ButtonState;
  763. IsButtonPressed = true;
  764. if ((mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  765. Application.MainLoop.AddIdle (() => {
  766. ProcessContinuousButtonPressedAsync (mouseEvent, mouseFlag).ConfigureAwait (false);
  767. return false;
  768. });
  769. }
  770. } else if ((mouseEvent.EventFlags == 0 || mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) &&
  771. LastMouseButtonPressed != null && !IsButtonReleased && !IsButtonDoubleClicked) {
  772. switch (LastMouseButtonPressed) {
  773. case WindowsConsole.ButtonState.Button1Pressed:
  774. mouseFlag = MouseFlags.Button1Released;
  775. break;
  776. case WindowsConsole.ButtonState.Button2Pressed:
  777. mouseFlag = MouseFlags.Button2Released;
  778. break;
  779. case WindowsConsole.ButtonState.RightmostButtonPressed:
  780. mouseFlag = MouseFlags.Button3Released;
  781. break;
  782. }
  783. IsButtonPressed = false;
  784. IsButtonReleased = true;
  785. } else if ((mouseEvent.EventFlags == 0 || mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) &&
  786. IsButtonReleased && p == point) {
  787. switch (LastMouseButtonPressed) {
  788. case WindowsConsole.ButtonState.Button1Pressed:
  789. mouseFlag = MouseFlags.Button1Clicked;
  790. break;
  791. case WindowsConsole.ButtonState.Button2Pressed:
  792. mouseFlag = MouseFlags.Button2Clicked;
  793. break;
  794. case WindowsConsole.ButtonState.RightmostButtonPressed:
  795. mouseFlag = MouseFlags.Button3Clicked;
  796. break;
  797. }
  798. point = new Point () {
  799. X = mouseEvent.MousePosition.X,
  800. Y = mouseEvent.MousePosition.Y
  801. };
  802. LastMouseButtonPressed = null;
  803. IsButtonReleased = false;
  804. } else if (mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.DoubleClick)) {
  805. switch (mouseEvent.ButtonState) {
  806. case WindowsConsole.ButtonState.Button1Pressed:
  807. mouseFlag = MouseFlags.Button1DoubleClicked;
  808. break;
  809. case WindowsConsole.ButtonState.Button2Pressed:
  810. mouseFlag = MouseFlags.Button2DoubleClicked;
  811. break;
  812. case WindowsConsole.ButtonState.RightmostButtonPressed:
  813. mouseFlag = MouseFlags.Button3DoubleClicked;
  814. break;
  815. }
  816. IsButtonDoubleClicked = true;
  817. } else if (mouseEvent.EventFlags == 0 && mouseEvent.ButtonState != 0 && IsButtonDoubleClicked) {
  818. switch (mouseEvent.ButtonState) {
  819. case WindowsConsole.ButtonState.Button1Pressed:
  820. mouseFlag = MouseFlags.Button1TripleClicked;
  821. break;
  822. case WindowsConsole.ButtonState.Button2Pressed:
  823. mouseFlag = MouseFlags.Button2TripleClicked;
  824. break;
  825. case WindowsConsole.ButtonState.RightmostButtonPressed:
  826. mouseFlag = MouseFlags.Button3TripleClicked;
  827. break;
  828. }
  829. IsButtonDoubleClicked = false;
  830. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled) {
  831. switch (mouseEvent.ButtonState) {
  832. case WindowsConsole.ButtonState.WheeledUp:
  833. mouseFlag = MouseFlags.WheeledUp;
  834. break;
  835. case WindowsConsole.ButtonState.WheeledDown:
  836. mouseFlag = MouseFlags.WheeledDown;
  837. break;
  838. }
  839. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled &&
  840. mouseEvent.ControlKeyState == WindowsConsole.ControlKeyState.ShiftPressed) {
  841. switch (mouseEvent.ButtonState) {
  842. case WindowsConsole.ButtonState.WheeledUp:
  843. mouseFlag = MouseFlags.WheeledLeft;
  844. break;
  845. case WindowsConsole.ButtonState.WheeledDown:
  846. mouseFlag = MouseFlags.WheeledRight;
  847. break;
  848. }
  849. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  850. if (mouseEvent.MousePosition.X != point.X || mouseEvent.MousePosition.Y != point.Y) {
  851. mouseFlag = MouseFlags.ReportMousePosition;
  852. point = new Point ();
  853. } else {
  854. mouseFlag = 0;
  855. }
  856. } else if (mouseEvent.ButtonState == 0 && mouseEvent.EventFlags == 0) {
  857. mouseFlag = 0;
  858. }
  859. mouseFlag = SetControlKeyStates (mouseEvent, mouseFlag);
  860. return new MouseEvent () {
  861. X = mouseEvent.MousePosition.X,
  862. Y = mouseEvent.MousePosition.Y,
  863. Flags = mouseFlag
  864. };
  865. }
  866. async Task ProcessButtonDoubleClickedAsync ()
  867. {
  868. await Task.Delay (200);
  869. IsButtonDoubleClicked = false;
  870. }
  871. async Task ProcessContinuousButtonPressedAsync (WindowsConsole.MouseEventRecord mouseEvent, MouseFlags mouseFlag)
  872. {
  873. while (IsButtonPressed) {
  874. await Task.Delay (100);
  875. var me = new MouseEvent () {
  876. X = mouseEvent.MousePosition.X,
  877. Y = mouseEvent.MousePosition.Y,
  878. Flags = mouseFlag
  879. };
  880. var view = Application.wantContinuousButtonPressedView;
  881. if (view == null) {
  882. break;
  883. }
  884. if (IsButtonPressed && (mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  885. mouseHandler (me);
  886. }
  887. }
  888. }
  889. static MouseFlags SetControlKeyStates (WindowsConsole.MouseEventRecord mouseEvent, MouseFlags mouseFlag)
  890. {
  891. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed) ||
  892. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed))
  893. mouseFlag |= MouseFlags.ButtonCtrl;
  894. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed))
  895. mouseFlag |= MouseFlags.ButtonShift;
  896. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed) ||
  897. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed))
  898. mouseFlag |= MouseFlags.ButtonAlt;
  899. return mouseFlag;
  900. }
  901. KeyModifiers keyModifiers;
  902. public WindowsConsole.ConsoleKeyInfoEx ToConsoleKeyInfoEx (WindowsConsole.KeyEventRecord keyEvent)
  903. {
  904. var state = keyEvent.dwControlKeyState;
  905. bool shift = (state & WindowsConsole.ControlKeyState.ShiftPressed) != 0;
  906. bool alt = (state & (WindowsConsole.ControlKeyState.LeftAltPressed | WindowsConsole.ControlKeyState.RightAltPressed)) != 0;
  907. bool control = (state & (WindowsConsole.ControlKeyState.LeftControlPressed | WindowsConsole.ControlKeyState.RightControlPressed)) != 0;
  908. bool capslock = (state & (WindowsConsole.ControlKeyState.CapslockOn)) != 0;
  909. bool numlock = (state & (WindowsConsole.ControlKeyState.NumlockOn)) != 0;
  910. bool scrolllock = (state & (WindowsConsole.ControlKeyState.ScrolllockOn)) != 0;
  911. if (keyModifiers == null)
  912. keyModifiers = new KeyModifiers ();
  913. if (shift)
  914. keyModifiers.Shift = shift;
  915. if (alt)
  916. keyModifiers.Alt = alt;
  917. if (control)
  918. keyModifiers.Ctrl = control;
  919. if (capslock)
  920. keyModifiers.Capslock = capslock;
  921. if (numlock)
  922. keyModifiers.Numlock = numlock;
  923. if (scrolllock)
  924. keyModifiers.Scrolllock = scrolllock;
  925. var ConsoleKeyInfo = new ConsoleKeyInfo (keyEvent.UnicodeChar, (ConsoleKey)keyEvent.wVirtualKeyCode, shift, alt, control);
  926. return new WindowsConsole.ConsoleKeyInfoEx (ConsoleKeyInfo, capslock, numlock);
  927. }
  928. public Key MapKey (WindowsConsole.ConsoleKeyInfoEx keyInfoEx)
  929. {
  930. var keyInfo = keyInfoEx.consoleKeyInfo;
  931. switch (keyInfo.Key) {
  932. case ConsoleKey.Escape:
  933. return MapKeyModifiers (keyInfo, Key.Esc);
  934. case ConsoleKey.Tab:
  935. return keyInfo.Modifiers == ConsoleModifiers.Shift ? Key.BackTab : Key.Tab;
  936. case ConsoleKey.Home:
  937. return MapKeyModifiers (keyInfo, Key.Home);
  938. case ConsoleKey.End:
  939. return MapKeyModifiers (keyInfo, Key.End);
  940. case ConsoleKey.LeftArrow:
  941. return MapKeyModifiers (keyInfo, Key.CursorLeft);
  942. case ConsoleKey.RightArrow:
  943. return MapKeyModifiers (keyInfo, Key.CursorRight);
  944. case ConsoleKey.UpArrow:
  945. return MapKeyModifiers (keyInfo, Key.CursorUp);
  946. case ConsoleKey.DownArrow:
  947. return MapKeyModifiers (keyInfo, Key.CursorDown);
  948. case ConsoleKey.PageUp:
  949. return MapKeyModifiers (keyInfo, Key.PageUp);
  950. case ConsoleKey.PageDown:
  951. return MapKeyModifiers (keyInfo, Key.PageDown);
  952. case ConsoleKey.Enter:
  953. return MapKeyModifiers (keyInfo, Key.Enter);
  954. case ConsoleKey.Spacebar:
  955. return MapKeyModifiers (keyInfo, Key.Space);
  956. case ConsoleKey.Backspace:
  957. return MapKeyModifiers (keyInfo, Key.Backspace);
  958. case ConsoleKey.Delete:
  959. return MapKeyModifiers (keyInfo, Key.DeleteChar);
  960. case ConsoleKey.Insert:
  961. return MapKeyModifiers (keyInfo, Key.InsertChar);
  962. case ConsoleKey.NumPad0:
  963. return keyInfoEx.NumLock ? Key.D0 : Key.InsertChar;
  964. case ConsoleKey.NumPad1:
  965. return keyInfoEx.NumLock ? Key.D1 : Key.End;
  966. case ConsoleKey.NumPad2:
  967. return keyInfoEx.NumLock ? Key.D2 : Key.CursorDown;
  968. case ConsoleKey.NumPad3:
  969. return keyInfoEx.NumLock ? Key.D3 : Key.PageDown;
  970. case ConsoleKey.NumPad4:
  971. return keyInfoEx.NumLock ? Key.D4 : Key.CursorLeft;
  972. case ConsoleKey.NumPad5:
  973. return keyInfoEx.NumLock ? Key.D5 : (Key)((uint)keyInfo.KeyChar);
  974. case ConsoleKey.NumPad6:
  975. return keyInfoEx.NumLock ? Key.D6 : Key.CursorRight;
  976. case ConsoleKey.NumPad7:
  977. return keyInfoEx.NumLock ? Key.D7 : Key.Home;
  978. case ConsoleKey.NumPad8:
  979. return keyInfoEx.NumLock ? Key.D8 : Key.CursorUp;
  980. case ConsoleKey.NumPad9:
  981. return keyInfoEx.NumLock ? Key.D9 : Key.PageUp;
  982. case ConsoleKey.Oem1:
  983. case ConsoleKey.Oem2:
  984. case ConsoleKey.Oem3:
  985. case ConsoleKey.Oem4:
  986. case ConsoleKey.Oem5:
  987. case ConsoleKey.Oem6:
  988. case ConsoleKey.Oem7:
  989. case ConsoleKey.Oem8:
  990. case ConsoleKey.Oem102:
  991. case ConsoleKey.OemPeriod:
  992. case ConsoleKey.OemComma:
  993. case ConsoleKey.OemPlus:
  994. case ConsoleKey.OemMinus:
  995. if (keyInfo.KeyChar == 0)
  996. return Key.Unknown;
  997. return (Key)((uint)keyInfo.KeyChar);
  998. }
  999. var key = keyInfo.Key;
  1000. //var alphaBase = ((keyInfo.Modifiers == ConsoleModifiers.Shift) ^ (keyInfoEx.CapsLock)) ? 'A' : 'a';
  1001. if (key >= ConsoleKey.A && key <= ConsoleKey.Z) {
  1002. var delta = key - ConsoleKey.A;
  1003. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  1004. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.A + delta));
  1005. }
  1006. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  1007. return (Key)(((uint)Key.AltMask) | ((uint)Key.A + delta));
  1008. }
  1009. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1010. if (keyInfo.KeyChar == 0 || (keyInfo.KeyChar != 0 && keyInfo.KeyChar >= 1 && keyInfo.KeyChar <= 26)) {
  1011. return MapKeyModifiers (keyInfo, (Key)((uint)Key.A + delta));
  1012. }
  1013. }
  1014. //return (Key)((uint)alphaBase + delta);
  1015. return (Key)((uint)keyInfo.KeyChar);
  1016. }
  1017. if (key >= ConsoleKey.D0 && key <= ConsoleKey.D9) {
  1018. var delta = key - ConsoleKey.D0;
  1019. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  1020. return (Key)(((uint)Key.AltMask) | ((uint)Key.D0 + delta));
  1021. }
  1022. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  1023. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.D0 + delta));
  1024. }
  1025. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1026. if (keyInfo.KeyChar == 0 || keyInfo.KeyChar == 30) {
  1027. return MapKeyModifiers (keyInfo, (Key)((uint)Key.D0 + delta));
  1028. }
  1029. }
  1030. return (Key)((uint)keyInfo.KeyChar);
  1031. }
  1032. if (key >= ConsoleKey.F1 && key <= ConsoleKey.F12) {
  1033. var delta = key - ConsoleKey.F1;
  1034. if ((keyInfo.Modifiers & (ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  1035. return MapKeyModifiers (keyInfo, (Key)((uint)Key.F1 + delta));
  1036. }
  1037. return (Key)((uint)Key.F1 + delta);
  1038. }
  1039. if (keyInfo.KeyChar != 0) {
  1040. return (Key)((uint)keyInfo.KeyChar);
  1041. }
  1042. return (Key)(0xffffffff);
  1043. }
  1044. Key MapKeyModifiers (ConsoleKeyInfo keyInfo, Key key)
  1045. {
  1046. Key keyMod = new Key ();
  1047. if ((keyInfo.Modifiers & ConsoleModifiers.Shift) != 0)
  1048. keyMod = Key.ShiftMask;
  1049. if ((keyInfo.Modifiers & ConsoleModifiers.Control) != 0)
  1050. keyMod |= Key.CtrlMask;
  1051. if ((keyInfo.Modifiers & ConsoleModifiers.Alt) != 0)
  1052. keyMod |= Key.AltMask;
  1053. return keyMod != Key.Null ? keyMod | key : key;
  1054. }
  1055. public override void Init (Action terminalResized)
  1056. {
  1057. TerminalResized = terminalResized;
  1058. cols = Console.WindowWidth;
  1059. rows = Console.WindowHeight;
  1060. #if false
  1061. winConsole.ShowWindow (WindowsConsole.RESTORE);
  1062. #endif
  1063. WindowsConsole.SmallRect.MakeEmpty (ref damageRegion);
  1064. ResizeScreen ();
  1065. UpdateOffScreen ();
  1066. Colors.TopLevel = new ColorScheme ();
  1067. Colors.Base = new ColorScheme ();
  1068. Colors.Dialog = new ColorScheme ();
  1069. Colors.Menu = new ColorScheme ();
  1070. Colors.Error = new ColorScheme ();
  1071. Colors.TopLevel.Normal = MakeColor (ConsoleColor.Green, ConsoleColor.Black);
  1072. Colors.TopLevel.Focus = MakeColor (ConsoleColor.White, ConsoleColor.DarkCyan);
  1073. Colors.TopLevel.HotNormal = MakeColor (ConsoleColor.DarkYellow, ConsoleColor.Black);
  1074. Colors.TopLevel.HotFocus = MakeColor (ConsoleColor.DarkBlue, ConsoleColor.DarkCyan);
  1075. Colors.Base.Normal = MakeColor (ConsoleColor.White, ConsoleColor.DarkBlue);
  1076. Colors.Base.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
  1077. Colors.Base.HotNormal = MakeColor (ConsoleColor.DarkCyan, ConsoleColor.DarkBlue);
  1078. Colors.Base.HotFocus = MakeColor (ConsoleColor.Blue, ConsoleColor.Gray);
  1079. Colors.Menu.Normal = MakeColor (ConsoleColor.White, ConsoleColor.DarkGray);
  1080. Colors.Menu.Focus = MakeColor (ConsoleColor.White, ConsoleColor.Black);
  1081. Colors.Menu.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.DarkGray);
  1082. Colors.Menu.HotFocus = MakeColor (ConsoleColor.Yellow, ConsoleColor.Black);
  1083. Colors.Menu.Disabled = MakeColor (ConsoleColor.Gray, ConsoleColor.DarkGray);
  1084. Colors.Dialog.Normal = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
  1085. Colors.Dialog.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.DarkGray);
  1086. Colors.Dialog.HotNormal = MakeColor (ConsoleColor.DarkBlue, ConsoleColor.Gray);
  1087. Colors.Dialog.HotFocus = MakeColor (ConsoleColor.DarkBlue, ConsoleColor.DarkGray);
  1088. Colors.Error.Normal = MakeColor (ConsoleColor.DarkRed, ConsoleColor.White);
  1089. Colors.Error.Focus = MakeColor (ConsoleColor.White, ConsoleColor.DarkRed);
  1090. Colors.Error.HotNormal = MakeColor (ConsoleColor.Black, ConsoleColor.White);
  1091. Colors.Error.HotFocus = MakeColor (ConsoleColor.Black, ConsoleColor.DarkRed);
  1092. }
  1093. void ResizeScreen ()
  1094. {
  1095. OutputBuffer = new WindowsConsole.CharInfo [Rows * Cols];
  1096. Clip = new Rect (0, 0, Cols, Rows);
  1097. damageRegion = new WindowsConsole.SmallRect () {
  1098. Top = 0,
  1099. Left = 0,
  1100. Bottom = (short)Rows,
  1101. Right = (short)Cols
  1102. };
  1103. }
  1104. void UpdateOffScreen ()
  1105. {
  1106. for (int row = 0; row < rows; row++) {
  1107. for (int col = 0; col < cols; col++) {
  1108. int position = row * cols + col;
  1109. OutputBuffer [position].Attributes = (ushort)Colors.TopLevel.Normal;
  1110. OutputBuffer [position].Char.UnicodeChar = ' ';
  1111. }
  1112. }
  1113. winChanging = false;
  1114. }
  1115. int ccol, crow;
  1116. public override void Move (int col, int row)
  1117. {
  1118. ccol = col;
  1119. crow = row;
  1120. }
  1121. public override void AddRune (Rune rune)
  1122. {
  1123. rune = MakePrintable (rune);
  1124. var position = crow * Cols + ccol;
  1125. if (Clip.Contains (ccol, crow)) {
  1126. OutputBuffer [position].Attributes = (ushort)currentAttribute;
  1127. OutputBuffer [position].Char.UnicodeChar = (char)rune;
  1128. WindowsConsole.SmallRect.Update (ref damageRegion, (short)ccol, (short)crow);
  1129. }
  1130. ccol++;
  1131. var runeWidth = Rune.ColumnWidth (rune);
  1132. if (runeWidth > 1) {
  1133. for (int i = 1; i < runeWidth; i++) {
  1134. AddStr (" ");
  1135. }
  1136. }
  1137. //if (ccol == Cols) {
  1138. // ccol = 0;
  1139. // if (crow + 1 < Rows)
  1140. // crow++;
  1141. //}
  1142. if (sync)
  1143. UpdateScreen ();
  1144. }
  1145. public override void AddStr (ustring str)
  1146. {
  1147. foreach (var rune in str)
  1148. AddRune (rune);
  1149. }
  1150. int currentAttribute;
  1151. public override void SetAttribute (Attribute c)
  1152. {
  1153. currentAttribute = c.Value;
  1154. }
  1155. Attribute MakeColor (ConsoleColor f, ConsoleColor b)
  1156. {
  1157. // Encode the colors into the int value.
  1158. return new Attribute (
  1159. value: ((int)f | (int)b << 4),
  1160. foreground: (Color)f,
  1161. background: (Color)b
  1162. );
  1163. }
  1164. public override Attribute MakeAttribute (Color fore, Color back)
  1165. {
  1166. return MakeColor ((ConsoleColor)fore, (ConsoleColor)back);
  1167. }
  1168. public override void Refresh ()
  1169. {
  1170. UpdateScreen ();
  1171. #if false
  1172. var bufferCoords = new WindowsConsole.Coord (){
  1173. X = (short)Clip.Width,
  1174. Y = (short)Clip.Height
  1175. };
  1176. var window = new WindowsConsole.SmallRect (){
  1177. Top = 0,
  1178. Left = 0,
  1179. Right = (short)Clip.Right,
  1180. Bottom = (short)Clip.Bottom
  1181. };
  1182. UpdateCursor();
  1183. winConsole.WriteToConsole (OutputBuffer, bufferCoords, window);
  1184. #endif
  1185. }
  1186. public override void UpdateScreen ()
  1187. {
  1188. if (damageRegion.Left == -1)
  1189. return;
  1190. var bufferCoords = new WindowsConsole.Coord () {
  1191. X = (short)Clip.Width,
  1192. Y = (short)Clip.Height
  1193. };
  1194. //var window = new WindowsConsole.SmallRect () {
  1195. // Top = 0,
  1196. // Left = 0,
  1197. // Right = (short)Clip.Right,
  1198. // Bottom = (short)Clip.Bottom
  1199. //};
  1200. UpdateCursor ();
  1201. winConsole.WriteToConsole (OutputBuffer, bufferCoords, damageRegion);
  1202. //System.Diagnostics.Debugger.Log(0, "debug", $"Region={damageRegion.Right - damageRegion.Left},{damageRegion.Bottom - damageRegion.Top}\n");
  1203. WindowsConsole.SmallRect.MakeEmpty (ref damageRegion);
  1204. }
  1205. public override void UpdateCursor ()
  1206. {
  1207. var position = new WindowsConsole.Coord () {
  1208. X = (short)ccol,
  1209. Y = (short)crow
  1210. };
  1211. winConsole.SetCursorPosition (position);
  1212. }
  1213. public override void End ()
  1214. {
  1215. winConsole.Cleanup ();
  1216. }
  1217. public override Attribute GetAttribute ()
  1218. {
  1219. return currentAttribute;
  1220. }
  1221. #region Unused
  1222. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  1223. {
  1224. }
  1225. public override void SetColors (short foregroundColorId, short backgroundColorId)
  1226. {
  1227. }
  1228. public override void Suspend ()
  1229. {
  1230. }
  1231. public override void StartReportingMouseMoves ()
  1232. {
  1233. }
  1234. public override void StopReportingMouseMoves ()
  1235. {
  1236. }
  1237. public override void UncookMouse ()
  1238. {
  1239. }
  1240. public override void CookMouse ()
  1241. {
  1242. }
  1243. #endregion
  1244. }
  1245. /// <summary>
  1246. /// Mainloop intended to be used with the <see cref="WindowsDriver"/>, and can
  1247. /// only be used on Windows.
  1248. /// </summary>
  1249. /// <remarks>
  1250. /// This implementation is used for WindowsDriver.
  1251. /// </remarks>
  1252. internal class WindowsMainLoop : IMainLoopDriver {
  1253. ManualResetEventSlim eventReady = new ManualResetEventSlim (false);
  1254. ManualResetEventSlim waitForProbe = new ManualResetEventSlim (false);
  1255. ManualResetEventSlim winChange = new ManualResetEventSlim (false);
  1256. MainLoop mainLoop;
  1257. ConsoleDriver consoleDriver;
  1258. WindowsConsole winConsole;
  1259. bool winChanged;
  1260. Size windowSize;
  1261. CancellationTokenSource tokenSource = new CancellationTokenSource ();
  1262. // The records that we keep fetching
  1263. WindowsConsole.InputRecord [] result = new WindowsConsole.InputRecord [1];
  1264. /// <summary>
  1265. /// Invoked when a Key is pressed or released.
  1266. /// </summary>
  1267. public Action<WindowsConsole.InputRecord> ProcessInput;
  1268. /// <summary>
  1269. /// Invoked when the window is changed.
  1270. /// </summary>
  1271. public Action<Size> WinChanged;
  1272. public bool Maximized;
  1273. public bool Restored;
  1274. public WindowsMainLoop (ConsoleDriver consoleDriver = null)
  1275. {
  1276. if (consoleDriver == null) {
  1277. throw new ArgumentNullException ("Console driver instance must be provided.");
  1278. }
  1279. this.consoleDriver = consoleDriver;
  1280. winConsole = ((WindowsDriver)consoleDriver).WinConsole;
  1281. }
  1282. void IMainLoopDriver.Setup (MainLoop mainLoop)
  1283. {
  1284. this.mainLoop = mainLoop;
  1285. Task.Run (WindowsInputHandler);
  1286. Task.Run (CheckWinChange);
  1287. }
  1288. void WindowsInputHandler ()
  1289. {
  1290. while (true) {
  1291. waitForProbe.Wait ();
  1292. waitForProbe.Reset ();
  1293. result = winConsole.ReadConsoleInput ();
  1294. eventReady.Set ();
  1295. }
  1296. }
  1297. void CheckWinChange ()
  1298. {
  1299. while (true) {
  1300. winChange.Wait ();
  1301. winChange.Reset ();
  1302. WaitWinChange ();
  1303. winChanged = true;
  1304. eventReady.Set ();
  1305. }
  1306. }
  1307. bool docked;
  1308. void WaitWinChange ()
  1309. {
  1310. var handle = winConsole.GetConsole ();
  1311. var fontSize = winConsole.GetCurrentFontSize ();
  1312. while (!consoleDriver.HeightAsBuffer) {
  1313. WindowsConsole.WindowPlacement windowPlacement = new WindowsConsole.WindowPlacement ();
  1314. winConsole.GetWindow (handle, ref windowPlacement);
  1315. if (windowPlacement.rcNormalPosition.Size.Height > -1) {
  1316. windowSize = SetWindowSize (windowPlacement.rcNormalPosition);
  1317. if (windowPlacement.showCmd != WindowsConsole.SHOW_MAXIMIZED && !Maximized && !Restored && !docked
  1318. && (windowSize.Width != consoleDriver.Cols || windowSize.Height != consoleDriver.Rows)) {
  1319. docked = false;
  1320. return;
  1321. } else if (windowPlacement.showCmd == WindowsConsole.SHOW_MAXIMIZED && !Maximized
  1322. && (Console.LargestWindowWidth != consoleDriver.Cols || Console.LargestWindowHeight != consoleDriver.Rows)) {
  1323. windowSize = new Size (Console.LargestWindowWidth, Console.LargestWindowHeight);
  1324. Maximized = true;
  1325. docked = false;
  1326. return;
  1327. } else if (windowPlacement.showCmd != WindowsConsole.SHOW_MAXIMIZED && Maximized) {
  1328. windowPlacement = new WindowsConsole.WindowPlacement () {
  1329. showCmd = WindowsConsole.RESTORE
  1330. };
  1331. winConsole.SetWindow (handle, ref windowPlacement);
  1332. Restored = true;
  1333. Maximized = false;
  1334. docked = false;
  1335. return;
  1336. } else if (!Maximized && IsDockedToMonitor (handle, windowPlacement)) {
  1337. return;
  1338. }
  1339. }
  1340. }
  1341. Size SetWindowSize (System.Drawing.Rectangle rect)
  1342. {
  1343. var fontHDividerW = fontSize.FontHeight / fontSize.FontWidth;
  1344. var w = (rect.Width - rect.X) / fontSize.FontWidth;
  1345. var h = (rect.Height - rect.Y) / fontSize.FontHeight;
  1346. return new Size (Math.Max ((w) - (fontHDividerW * 3) - (w < (Console.LargestWindowWidth / 2) ? -1 : 2), 0),
  1347. Math.Max ((h) - fontHDividerW - (w < (Console.LargestWindowHeight / 2) ? -1 : 1), 0));
  1348. }
  1349. bool IsDockedToMonitor (IntPtr hWnd, WindowsConsole.WindowPlacement placement)
  1350. {
  1351. System.Drawing.Rectangle rc;
  1352. winConsole.GetRect (hWnd, out rc);
  1353. var changed = placement.showCmd == WindowsConsole.SHOW_NORMAL
  1354. && (rc.Left != placement.rcNormalPosition.Left ||
  1355. rc.Top != placement.rcNormalPosition.Top ||
  1356. rc.Right != placement.rcNormalPosition.Right ||
  1357. rc.Bottom != placement.rcNormalPosition.Bottom);
  1358. if (changed) {
  1359. var pSize = new Size (placement.rcNormalPosition.Size.Width - placement.rcNormalPosition.X,
  1360. placement.rcNormalPosition.Size.Height - placement.rcNormalPosition.Y);
  1361. var rSize = new Size (rc.Width - rc.X,
  1362. rc.Height - rc.Y);
  1363. windowSize = SetWindowSize (rc);
  1364. if ((rc.X < 0) || (rc.Y == 0) || (rc.Y == 0 && rc.X < 0)
  1365. || (rc.Y == 0 && rc.Right / fontSize.FontWidth >= Console.LargestWindowWidth)
  1366. || (rc.X < 0 && rc.Bottom / fontSize.FontHeight >= Console.LargestWindowHeight)
  1367. || (rc.X / fontSize.FontWidth >= Console.LargestWindowWidth / 2 - 1 && rc.Bottom / fontSize.FontHeight >= Console.LargestWindowHeight)) {
  1368. if (!docked || consoleDriver.Cols != windowSize.Width
  1369. || consoleDriver.Rows != windowSize.Height) {
  1370. docked = true;
  1371. } else {
  1372. changed = false;
  1373. }
  1374. } else {
  1375. if (!docked && (pSize == rSize || rSize.Width / fontSize.FontWidth >= Console.LargestWindowWidth
  1376. || rSize.Height / fontSize.FontHeight >= Console.LargestWindowHeight)) {
  1377. changed = false;
  1378. }
  1379. docked = false;
  1380. }
  1381. } else {
  1382. docked = false;
  1383. }
  1384. return changed;
  1385. }
  1386. }
  1387. void IMainLoopDriver.Wakeup ()
  1388. {
  1389. //tokenSource.Cancel ();
  1390. eventReady.Set ();
  1391. }
  1392. bool IMainLoopDriver.EventsPending (bool wait)
  1393. {
  1394. if (CheckTimers (wait, out var waitTimeout)) {
  1395. return true;
  1396. }
  1397. //result = null;
  1398. waitForProbe.Set ();
  1399. if (!consoleDriver.HeightAsBuffer) {
  1400. winChange.Set ();
  1401. }
  1402. try {
  1403. if (!tokenSource.IsCancellationRequested) {
  1404. eventReady.Wait (waitTimeout, tokenSource.Token);
  1405. }
  1406. } catch (OperationCanceledException) {
  1407. return true;
  1408. } finally {
  1409. eventReady.Reset ();
  1410. }
  1411. if (!tokenSource.IsCancellationRequested) {
  1412. return result != null || CheckTimers (wait, out _) || winChanged;
  1413. }
  1414. tokenSource.Dispose ();
  1415. tokenSource = new CancellationTokenSource ();
  1416. return true;
  1417. }
  1418. bool CheckTimers (bool wait, out int waitTimeout)
  1419. {
  1420. long now = DateTime.UtcNow.Ticks;
  1421. if (mainLoop.timeouts.Count > 0) {
  1422. waitTimeout = (int)((mainLoop.timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  1423. if (waitTimeout < 0)
  1424. return true;
  1425. } else {
  1426. waitTimeout = -1;
  1427. }
  1428. if (!wait)
  1429. waitTimeout = 0;
  1430. int ic;
  1431. lock (mainLoop.idleHandlers) {
  1432. ic = mainLoop.idleHandlers.Count;
  1433. }
  1434. return ic > 0;
  1435. }
  1436. void IMainLoopDriver.MainIteration ()
  1437. {
  1438. if (result != null) {
  1439. var inputEvent = result [0];
  1440. result = null;
  1441. ProcessInput?.Invoke (inputEvent);
  1442. }
  1443. if (winChanged) {
  1444. winChanged = false;
  1445. WinChanged?.Invoke (windowSize);
  1446. }
  1447. }
  1448. }
  1449. }