WindowsDriver.cs 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628
  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. var p = new Point () {
  688. X = mouseEvent.MousePosition.X,
  689. Y = mouseEvent.MousePosition.Y
  690. };
  691. if ((mouseEvent.ButtonState != 0 && mouseEvent.EventFlags == 0 && LastMouseButtonPressed == null && !IsButtonDoubleClicked) ||
  692. (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved &&
  693. mouseEvent.ButtonState != 0 && !IsButtonReleased && !IsButtonDoubleClicked)) {
  694. switch (mouseEvent.ButtonState) {
  695. case WindowsConsole.ButtonState.Button1Pressed:
  696. mouseFlag = MouseFlags.Button1Pressed;
  697. break;
  698. case WindowsConsole.ButtonState.Button2Pressed:
  699. mouseFlag = MouseFlags.Button2Pressed;
  700. break;
  701. case WindowsConsole.ButtonState.RightmostButtonPressed:
  702. mouseFlag = MouseFlags.Button3Pressed;
  703. break;
  704. }
  705. if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  706. mouseFlag |= MouseFlags.ReportMousePosition;
  707. point = new Point ();
  708. IsButtonReleased = false;
  709. } else {
  710. point = new Point () {
  711. X = mouseEvent.MousePosition.X,
  712. Y = mouseEvent.MousePosition.Y
  713. };
  714. }
  715. LastMouseButtonPressed = mouseEvent.ButtonState;
  716. IsButtonPressed = true;
  717. if ((mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  718. Application.MainLoop.AddIdle (() => {
  719. ProcessContinuousButtonPressedAsync (mouseEvent, mouseFlag).ConfigureAwait (false);
  720. return false;
  721. });
  722. }
  723. } else if ((mouseEvent.EventFlags == 0 || mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) &&
  724. LastMouseButtonPressed != null && !IsButtonReleased && !IsButtonDoubleClicked) {
  725. switch (LastMouseButtonPressed) {
  726. case WindowsConsole.ButtonState.Button1Pressed:
  727. mouseFlag = MouseFlags.Button1Released;
  728. break;
  729. case WindowsConsole.ButtonState.Button2Pressed:
  730. mouseFlag = MouseFlags.Button2Released;
  731. break;
  732. case WindowsConsole.ButtonState.RightmostButtonPressed:
  733. mouseFlag = MouseFlags.Button3Released;
  734. break;
  735. }
  736. IsButtonPressed = false;
  737. IsButtonReleased = true;
  738. } else if ((mouseEvent.EventFlags == 0 || mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) &&
  739. IsButtonReleased && p == point) {
  740. switch (LastMouseButtonPressed) {
  741. case WindowsConsole.ButtonState.Button1Pressed:
  742. mouseFlag = MouseFlags.Button1Clicked;
  743. break;
  744. case WindowsConsole.ButtonState.Button2Pressed:
  745. mouseFlag = MouseFlags.Button2Clicked;
  746. break;
  747. case WindowsConsole.ButtonState.RightmostButtonPressed:
  748. mouseFlag = MouseFlags.Button3Clicked;
  749. break;
  750. }
  751. point = new Point () {
  752. X = mouseEvent.MousePosition.X,
  753. Y = mouseEvent.MousePosition.Y
  754. };
  755. LastMouseButtonPressed = null;
  756. IsButtonReleased = false;
  757. } else if (mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.DoubleClick)) {
  758. switch (mouseEvent.ButtonState) {
  759. case WindowsConsole.ButtonState.Button1Pressed:
  760. mouseFlag = MouseFlags.Button1DoubleClicked;
  761. break;
  762. case WindowsConsole.ButtonState.Button2Pressed:
  763. mouseFlag = MouseFlags.Button2DoubleClicked;
  764. break;
  765. case WindowsConsole.ButtonState.RightmostButtonPressed:
  766. mouseFlag = MouseFlags.Button3DoubleClicked;
  767. break;
  768. }
  769. IsButtonDoubleClicked = true;
  770. } else if (mouseEvent.EventFlags == 0 && mouseEvent.ButtonState != 0 && IsButtonDoubleClicked) {
  771. switch (mouseEvent.ButtonState) {
  772. case WindowsConsole.ButtonState.Button1Pressed:
  773. mouseFlag = MouseFlags.Button1TripleClicked;
  774. break;
  775. case WindowsConsole.ButtonState.Button2Pressed:
  776. mouseFlag = MouseFlags.Button2TripleClicked;
  777. break;
  778. case WindowsConsole.ButtonState.RightmostButtonPressed:
  779. mouseFlag = MouseFlags.Button3TripleClicked;
  780. break;
  781. }
  782. IsButtonDoubleClicked = false;
  783. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled) {
  784. switch (mouseEvent.ButtonState) {
  785. case WindowsConsole.ButtonState.WheeledUp:
  786. mouseFlag = MouseFlags.WheeledUp;
  787. break;
  788. case WindowsConsole.ButtonState.WheeledDown:
  789. mouseFlag = MouseFlags.WheeledDown;
  790. break;
  791. }
  792. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled &&
  793. mouseEvent.ControlKeyState == WindowsConsole.ControlKeyState.ShiftPressed) {
  794. switch (mouseEvent.ButtonState) {
  795. case WindowsConsole.ButtonState.WheeledUp:
  796. mouseFlag = MouseFlags.WheeledLeft;
  797. break;
  798. case WindowsConsole.ButtonState.WheeledDown:
  799. mouseFlag = MouseFlags.WheeledRight;
  800. break;
  801. }
  802. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  803. if (mouseEvent.MousePosition.X != point.X || mouseEvent.MousePosition.Y != point.Y) {
  804. mouseFlag = MouseFlags.ReportMousePosition;
  805. point = new Point ();
  806. } else {
  807. mouseFlag = 0;
  808. }
  809. } else if (mouseEvent.ButtonState == 0 && mouseEvent.EventFlags == 0) {
  810. mouseFlag = 0;
  811. }
  812. mouseFlag = SetControlKeyStates (mouseEvent, mouseFlag);
  813. return new MouseEvent () {
  814. X = mouseEvent.MousePosition.X,
  815. Y = mouseEvent.MousePosition.Y,
  816. Flags = mouseFlag
  817. };
  818. }
  819. async Task ProcessButtonDoubleClickedAsync ()
  820. {
  821. await Task.Delay (200);
  822. IsButtonDoubleClicked = false;
  823. }
  824. async Task ProcessContinuousButtonPressedAsync (WindowsConsole.MouseEventRecord mouseEvent, MouseFlags mouseFlag)
  825. {
  826. while (IsButtonPressed) {
  827. await Task.Delay (100);
  828. var me = new MouseEvent () {
  829. X = mouseEvent.MousePosition.X,
  830. Y = mouseEvent.MousePosition.Y,
  831. Flags = mouseFlag
  832. };
  833. var view = Application.wantContinuousButtonPressedView;
  834. if (view == null) {
  835. break;
  836. }
  837. if (IsButtonPressed && (mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  838. mouseHandler (me);
  839. }
  840. }
  841. }
  842. static MouseFlags SetControlKeyStates (WindowsConsole.MouseEventRecord mouseEvent, MouseFlags mouseFlag)
  843. {
  844. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed) ||
  845. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed))
  846. mouseFlag |= MouseFlags.ButtonCtrl;
  847. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed))
  848. mouseFlag |= MouseFlags.ButtonShift;
  849. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed) ||
  850. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed))
  851. mouseFlag |= MouseFlags.ButtonAlt;
  852. return mouseFlag;
  853. }
  854. KeyModifiers keyModifiers;
  855. public WindowsConsole.ConsoleKeyInfoEx ToConsoleKeyInfoEx (WindowsConsole.KeyEventRecord keyEvent)
  856. {
  857. var state = keyEvent.dwControlKeyState;
  858. bool shift = (state & WindowsConsole.ControlKeyState.ShiftPressed) != 0;
  859. bool alt = (state & (WindowsConsole.ControlKeyState.LeftAltPressed | WindowsConsole.ControlKeyState.RightAltPressed)) != 0;
  860. bool control = (state & (WindowsConsole.ControlKeyState.LeftControlPressed | WindowsConsole.ControlKeyState.RightControlPressed)) != 0;
  861. bool capslock = (state & (WindowsConsole.ControlKeyState.CapslockOn)) != 0;
  862. bool numlock = (state & (WindowsConsole.ControlKeyState.NumlockOn)) != 0;
  863. bool scrolllock = (state & (WindowsConsole.ControlKeyState.ScrolllockOn)) != 0;
  864. if (keyModifiers == null)
  865. keyModifiers = new KeyModifiers ();
  866. if (shift)
  867. keyModifiers.Shift = shift;
  868. if (alt)
  869. keyModifiers.Alt = alt;
  870. if (control)
  871. keyModifiers.Ctrl = control;
  872. if (capslock)
  873. keyModifiers.Capslock = capslock;
  874. if (numlock)
  875. keyModifiers.Numlock = numlock;
  876. if (scrolllock)
  877. keyModifiers.Scrolllock = scrolllock;
  878. var ConsoleKeyInfo = new ConsoleKeyInfo (keyEvent.UnicodeChar, (ConsoleKey)keyEvent.wVirtualKeyCode, shift, alt, control);
  879. return new WindowsConsole.ConsoleKeyInfoEx (ConsoleKeyInfo, capslock, numlock);
  880. }
  881. public Key MapKey (WindowsConsole.ConsoleKeyInfoEx keyInfoEx)
  882. {
  883. var keyInfo = keyInfoEx.consoleKeyInfo;
  884. switch (keyInfo.Key) {
  885. case ConsoleKey.Escape:
  886. return MapKeyModifiers (keyInfo, Key.Esc);
  887. case ConsoleKey.Tab:
  888. return keyInfo.Modifiers == ConsoleModifiers.Shift ? Key.BackTab : Key.Tab;
  889. case ConsoleKey.Home:
  890. return MapKeyModifiers (keyInfo, Key.Home);
  891. case ConsoleKey.End:
  892. return MapKeyModifiers (keyInfo, Key.End);
  893. case ConsoleKey.LeftArrow:
  894. return MapKeyModifiers (keyInfo, Key.CursorLeft);
  895. case ConsoleKey.RightArrow:
  896. return MapKeyModifiers (keyInfo, Key.CursorRight);
  897. case ConsoleKey.UpArrow:
  898. return MapKeyModifiers (keyInfo, Key.CursorUp);
  899. case ConsoleKey.DownArrow:
  900. return MapKeyModifiers (keyInfo, Key.CursorDown);
  901. case ConsoleKey.PageUp:
  902. return MapKeyModifiers (keyInfo, Key.PageUp);
  903. case ConsoleKey.PageDown:
  904. return MapKeyModifiers (keyInfo, Key.PageDown);
  905. case ConsoleKey.Enter:
  906. return MapKeyModifiers (keyInfo, Key.Enter);
  907. case ConsoleKey.Spacebar:
  908. return MapKeyModifiers (keyInfo, Key.Space);
  909. case ConsoleKey.Backspace:
  910. return MapKeyModifiers (keyInfo, Key.Backspace);
  911. case ConsoleKey.Delete:
  912. return MapKeyModifiers (keyInfo, Key.DeleteChar);
  913. case ConsoleKey.Insert:
  914. return MapKeyModifiers (keyInfo, Key.InsertChar);
  915. case ConsoleKey.NumPad0:
  916. return keyInfoEx.NumLock ? Key.D0 : Key.InsertChar;
  917. case ConsoleKey.NumPad1:
  918. return keyInfoEx.NumLock ? Key.D1 : Key.End;
  919. case ConsoleKey.NumPad2:
  920. return keyInfoEx.NumLock ? Key.D2 : Key.CursorDown;
  921. case ConsoleKey.NumPad3:
  922. return keyInfoEx.NumLock ? Key.D3 : Key.PageDown;
  923. case ConsoleKey.NumPad4:
  924. return keyInfoEx.NumLock ? Key.D4 : Key.CursorLeft;
  925. case ConsoleKey.NumPad5:
  926. return keyInfoEx.NumLock ? Key.D5 : (Key)((uint)keyInfo.KeyChar);
  927. case ConsoleKey.NumPad6:
  928. return keyInfoEx.NumLock ? Key.D6 : Key.CursorRight;
  929. case ConsoleKey.NumPad7:
  930. return keyInfoEx.NumLock ? Key.D7 : Key.Home;
  931. case ConsoleKey.NumPad8:
  932. return keyInfoEx.NumLock ? Key.D8 : Key.CursorUp;
  933. case ConsoleKey.NumPad9:
  934. return keyInfoEx.NumLock ? Key.D9 : Key.PageUp;
  935. case ConsoleKey.Oem1:
  936. case ConsoleKey.Oem2:
  937. case ConsoleKey.Oem3:
  938. case ConsoleKey.Oem4:
  939. case ConsoleKey.Oem5:
  940. case ConsoleKey.Oem6:
  941. case ConsoleKey.Oem7:
  942. case ConsoleKey.Oem8:
  943. case ConsoleKey.Oem102:
  944. case ConsoleKey.OemPeriod:
  945. case ConsoleKey.OemComma:
  946. case ConsoleKey.OemPlus:
  947. case ConsoleKey.OemMinus:
  948. if (keyInfo.KeyChar == 0)
  949. return Key.Unknown;
  950. return (Key)((uint)keyInfo.KeyChar);
  951. }
  952. var key = keyInfo.Key;
  953. //var alphaBase = ((keyInfo.Modifiers == ConsoleModifiers.Shift) ^ (keyInfoEx.CapsLock)) ? 'A' : 'a';
  954. if (key >= ConsoleKey.A && key <= ConsoleKey.Z) {
  955. var delta = key - ConsoleKey.A;
  956. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  957. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.A + delta));
  958. }
  959. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  960. return (Key)(((uint)Key.AltMask) | ((uint)Key.A + delta));
  961. }
  962. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  963. if (keyInfo.KeyChar == 0 || (keyInfo.KeyChar != 0 && keyInfo.KeyChar >= 1 && keyInfo.KeyChar <= 26)) {
  964. return MapKeyModifiers (keyInfo, (Key)((uint)Key.A + delta));
  965. }
  966. }
  967. //return (Key)((uint)alphaBase + delta);
  968. return (Key)((uint)keyInfo.KeyChar);
  969. }
  970. if (key >= ConsoleKey.D0 && key <= ConsoleKey.D9) {
  971. var delta = key - ConsoleKey.D0;
  972. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  973. return (Key)(((uint)Key.AltMask) | ((uint)Key.D0 + delta));
  974. }
  975. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  976. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.D0 + delta));
  977. }
  978. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  979. if (keyInfo.KeyChar == 0 || keyInfo.KeyChar == 30) {
  980. return MapKeyModifiers (keyInfo, (Key)((uint)Key.D0 + delta));
  981. }
  982. }
  983. return (Key)((uint)keyInfo.KeyChar);
  984. }
  985. if (key >= ConsoleKey.F1 && key <= ConsoleKey.F12) {
  986. var delta = key - ConsoleKey.F1;
  987. if ((keyInfo.Modifiers & (ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  988. return MapKeyModifiers (keyInfo, (Key)((uint)Key.F1 + delta));
  989. }
  990. return (Key)((uint)Key.F1 + delta);
  991. }
  992. if (keyInfo.KeyChar != 0) {
  993. return (Key)((uint)keyInfo.KeyChar);
  994. }
  995. return (Key)(0xffffffff);
  996. }
  997. Key MapKeyModifiers (ConsoleKeyInfo keyInfo, Key key)
  998. {
  999. Key keyMod = new Key ();
  1000. if ((keyInfo.Modifiers & ConsoleModifiers.Shift) != 0)
  1001. keyMod = Key.ShiftMask;
  1002. if ((keyInfo.Modifiers & ConsoleModifiers.Control) != 0)
  1003. keyMod |= Key.CtrlMask;
  1004. if ((keyInfo.Modifiers & ConsoleModifiers.Alt) != 0)
  1005. keyMod |= Key.AltMask;
  1006. return keyMod != Key.Null ? keyMod | key : key;
  1007. }
  1008. public override void Init (Action terminalResized)
  1009. {
  1010. TerminalResized = terminalResized;
  1011. cols = Console.WindowWidth;
  1012. rows = Console.WindowHeight;
  1013. #if false
  1014. winConsole.ShowWindow (WindowsConsole.RESTORE);
  1015. #endif
  1016. WindowsConsole.SmallRect.MakeEmpty (ref damageRegion);
  1017. ResizeScreen ();
  1018. UpdateOffScreen ();
  1019. Colors.TopLevel = new ColorScheme ();
  1020. Colors.Base = new ColorScheme ();
  1021. Colors.Dialog = new ColorScheme ();
  1022. Colors.Menu = new ColorScheme ();
  1023. Colors.Error = new ColorScheme ();
  1024. Colors.TopLevel.Normal = MakeColor (ConsoleColor.Green, ConsoleColor.Black);
  1025. Colors.TopLevel.Focus = MakeColor (ConsoleColor.White, ConsoleColor.DarkCyan);
  1026. Colors.TopLevel.HotNormal = MakeColor (ConsoleColor.DarkYellow, ConsoleColor.Black);
  1027. Colors.TopLevel.HotFocus = MakeColor (ConsoleColor.DarkBlue, ConsoleColor.DarkCyan);
  1028. Colors.Base.Normal = MakeColor (ConsoleColor.White, ConsoleColor.DarkBlue);
  1029. Colors.Base.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
  1030. Colors.Base.HotNormal = MakeColor (ConsoleColor.DarkCyan, ConsoleColor.DarkBlue);
  1031. Colors.Base.HotFocus = MakeColor (ConsoleColor.Blue, ConsoleColor.Gray);
  1032. Colors.Menu.Normal = MakeColor (ConsoleColor.White, ConsoleColor.DarkGray);
  1033. Colors.Menu.Focus = MakeColor (ConsoleColor.White, ConsoleColor.Black);
  1034. Colors.Menu.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.DarkGray);
  1035. Colors.Menu.HotFocus = MakeColor (ConsoleColor.Yellow, ConsoleColor.Black);
  1036. Colors.Menu.Disabled = MakeColor (ConsoleColor.Gray, ConsoleColor.DarkGray);
  1037. Colors.Dialog.Normal = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
  1038. Colors.Dialog.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.DarkGray);
  1039. Colors.Dialog.HotNormal = MakeColor (ConsoleColor.DarkBlue, ConsoleColor.Gray);
  1040. Colors.Dialog.HotFocus = MakeColor (ConsoleColor.DarkBlue, ConsoleColor.DarkGray);
  1041. Colors.Error.Normal = MakeColor (ConsoleColor.DarkRed, ConsoleColor.White);
  1042. Colors.Error.Focus = MakeColor (ConsoleColor.White, ConsoleColor.DarkRed);
  1043. Colors.Error.HotNormal = MakeColor (ConsoleColor.Black, ConsoleColor.White);
  1044. Colors.Error.HotFocus = MakeColor (ConsoleColor.Black, ConsoleColor.DarkRed);
  1045. }
  1046. void ResizeScreen ()
  1047. {
  1048. OutputBuffer = new WindowsConsole.CharInfo [Rows * Cols];
  1049. Clip = new Rect (0, 0, Cols, Rows);
  1050. damageRegion = new WindowsConsole.SmallRect () {
  1051. Top = 0,
  1052. Left = 0,
  1053. Bottom = (short)Rows,
  1054. Right = (short)Cols
  1055. };
  1056. }
  1057. void UpdateOffScreen ()
  1058. {
  1059. for (int row = 0; row < rows; row++) {
  1060. for (int col = 0; col < cols; col++) {
  1061. int position = row * cols + col;
  1062. OutputBuffer [position].Attributes = (ushort)Colors.TopLevel.Normal;
  1063. OutputBuffer [position].Char.UnicodeChar = ' ';
  1064. }
  1065. }
  1066. winChanging = false;
  1067. }
  1068. int ccol, crow;
  1069. public override void Move (int col, int row)
  1070. {
  1071. ccol = col;
  1072. crow = row;
  1073. }
  1074. public override void AddRune (Rune rune)
  1075. {
  1076. rune = MakePrintable (rune);
  1077. var position = crow * Cols + ccol;
  1078. if (Clip.Contains (ccol, crow)) {
  1079. OutputBuffer [position].Attributes = (ushort)currentAttribute;
  1080. OutputBuffer [position].Char.UnicodeChar = (char)rune;
  1081. WindowsConsole.SmallRect.Update (ref damageRegion, (short)ccol, (short)crow);
  1082. }
  1083. ccol++;
  1084. var runeWidth = Rune.ColumnWidth (rune);
  1085. if (runeWidth > 1) {
  1086. for (int i = 1; i < runeWidth; i++) {
  1087. AddStr (" ");
  1088. }
  1089. }
  1090. //if (ccol == Cols) {
  1091. // ccol = 0;
  1092. // if (crow + 1 < Rows)
  1093. // crow++;
  1094. //}
  1095. if (sync)
  1096. UpdateScreen ();
  1097. }
  1098. public override void AddStr (ustring str)
  1099. {
  1100. foreach (var rune in str)
  1101. AddRune (rune);
  1102. }
  1103. int currentAttribute;
  1104. public override void SetAttribute (Attribute c)
  1105. {
  1106. currentAttribute = c.Value;
  1107. }
  1108. Attribute MakeColor (ConsoleColor f, ConsoleColor b)
  1109. {
  1110. // Encode the colors into the int value.
  1111. return new Attribute (
  1112. value: ((int)f | (int)b << 4),
  1113. foreground: (Color)f,
  1114. background: (Color)b
  1115. );
  1116. }
  1117. public override Attribute MakeAttribute (Color fore, Color back)
  1118. {
  1119. return MakeColor ((ConsoleColor)fore, (ConsoleColor)back);
  1120. }
  1121. public override void Refresh ()
  1122. {
  1123. UpdateScreen ();
  1124. #if false
  1125. var bufferCoords = new WindowsConsole.Coord (){
  1126. X = (short)Clip.Width,
  1127. Y = (short)Clip.Height
  1128. };
  1129. var window = new WindowsConsole.SmallRect (){
  1130. Top = 0,
  1131. Left = 0,
  1132. Right = (short)Clip.Right,
  1133. Bottom = (short)Clip.Bottom
  1134. };
  1135. UpdateCursor();
  1136. winConsole.WriteToConsole (OutputBuffer, bufferCoords, window);
  1137. #endif
  1138. }
  1139. public override void UpdateScreen ()
  1140. {
  1141. if (damageRegion.Left == -1)
  1142. return;
  1143. var bufferCoords = new WindowsConsole.Coord () {
  1144. X = (short)Clip.Width,
  1145. Y = (short)Clip.Height
  1146. };
  1147. //var window = new WindowsConsole.SmallRect () {
  1148. // Top = 0,
  1149. // Left = 0,
  1150. // Right = (short)Clip.Right,
  1151. // Bottom = (short)Clip.Bottom
  1152. //};
  1153. UpdateCursor ();
  1154. winConsole.WriteToConsole (OutputBuffer, bufferCoords, damageRegion);
  1155. //System.Diagnostics.Debugger.Log(0, "debug", $"Region={damageRegion.Right - damageRegion.Left},{damageRegion.Bottom - damageRegion.Top}\n");
  1156. WindowsConsole.SmallRect.MakeEmpty (ref damageRegion);
  1157. }
  1158. public override void UpdateCursor ()
  1159. {
  1160. var position = new WindowsConsole.Coord () {
  1161. X = (short)ccol,
  1162. Y = (short)crow
  1163. };
  1164. winConsole.SetCursorPosition (position);
  1165. }
  1166. public override void End ()
  1167. {
  1168. winConsole.Cleanup ();
  1169. }
  1170. public override Attribute GetAttribute ()
  1171. {
  1172. return currentAttribute;
  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. }