WindowsDriver.cs 44 KB

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