WindowsDriver.cs 44 KB

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