WindowsDriver.cs 48 KB

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