WindowsDriver.cs 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112
  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 System;
  29. using System.CodeDom;
  30. using System.Diagnostics;
  31. using System.Runtime.InteropServices;
  32. using System.Threading;
  33. using System.Threading.Tasks;
  34. using Mono.Terminal;
  35. using NStack;
  36. namespace Terminal.Gui {
  37. internal class WindowsConsole {
  38. public const int STD_OUTPUT_HANDLE = -11;
  39. public const int STD_INPUT_HANDLE = -10;
  40. public const int STD_ERROR_HANDLE = -12;
  41. internal IntPtr InputHandle, OutputHandle;
  42. IntPtr ScreenBuffer;
  43. uint originalConsoleMode;
  44. public WindowsConsole ()
  45. {
  46. InputHandle = GetStdHandle (STD_INPUT_HANDLE);
  47. OutputHandle = GetStdHandle (STD_OUTPUT_HANDLE);
  48. originalConsoleMode = ConsoleMode;
  49. var newConsoleMode = originalConsoleMode;
  50. newConsoleMode |= (uint)(ConsoleModes.EnableMouseInput | ConsoleModes.EnableExtendedFlags);
  51. newConsoleMode &= ~(uint)ConsoleModes.EnableQuickEditMode;
  52. ConsoleMode = newConsoleMode;
  53. }
  54. public CharInfo [] OriginalStdOutChars;
  55. public bool WriteToConsole (CharInfo [] charInfoBuffer, Coord coords, SmallRect window)
  56. {
  57. if (ScreenBuffer == IntPtr.Zero) {
  58. ScreenBuffer = CreateConsoleScreenBuffer (
  59. DesiredAccess.GenericRead | DesiredAccess.GenericWrite,
  60. ShareMode.FileShareRead | ShareMode.FileShareWrite,
  61. IntPtr.Zero,
  62. 1,
  63. IntPtr.Zero
  64. );
  65. if (ScreenBuffer == INVALID_HANDLE_VALUE) {
  66. var err = Marshal.GetLastWin32Error ();
  67. if (err != 0)
  68. throw new System.ComponentModel.Win32Exception (err);
  69. }
  70. if (!SetConsoleActiveScreenBuffer (ScreenBuffer)) {
  71. var err = Marshal.GetLastWin32Error ();
  72. throw new System.ComponentModel.Win32Exception (err);
  73. }
  74. OriginalStdOutChars = new CharInfo [Console.WindowHeight * Console.WindowWidth];
  75. ReadConsoleOutput (OutputHandle, OriginalStdOutChars, coords, new Coord () { X = 0, Y = 0 }, ref window);
  76. }
  77. return WriteConsoleOutput (ScreenBuffer, charInfoBuffer, coords, new Coord () { X = window.Left, Y = window.Top }, ref window);
  78. }
  79. public bool SetCursorPosition (Coord position)
  80. {
  81. return SetConsoleCursorPosition (ScreenBuffer, position);
  82. }
  83. public void Cleanup ()
  84. {
  85. ConsoleMode = originalConsoleMode;
  86. ContinueListeningForConsoleEvents = false;
  87. if (!SetConsoleActiveScreenBuffer (OutputHandle)) {
  88. var err = Marshal.GetLastWin32Error ();
  89. Console.WriteLine ("Error: {0}", err);
  90. }
  91. if (ScreenBuffer != IntPtr.Zero)
  92. CloseHandle (ScreenBuffer);
  93. ScreenBuffer = IntPtr.Zero;
  94. }
  95. bool ContinueListeningForConsoleEvents = true;
  96. public uint ConsoleMode {
  97. get {
  98. uint v;
  99. GetConsoleMode (InputHandle, out v);
  100. return v;
  101. }
  102. set {
  103. SetConsoleMode (InputHandle, value);
  104. }
  105. }
  106. [Flags]
  107. public enum ConsoleModes : uint {
  108. EnableMouseInput = 16,
  109. EnableQuickEditMode = 64,
  110. EnableExtendedFlags = 128,
  111. }
  112. [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
  113. public struct KeyEventRecord {
  114. [FieldOffset (0), MarshalAs (UnmanagedType.Bool)]
  115. public bool bKeyDown;
  116. [FieldOffset (4), MarshalAs (UnmanagedType.U2)]
  117. public ushort wRepeatCount;
  118. [FieldOffset (6), MarshalAs (UnmanagedType.U2)]
  119. public ushort wVirtualKeyCode;
  120. [FieldOffset (8), MarshalAs (UnmanagedType.U2)]
  121. public ushort wVirtualScanCode;
  122. [FieldOffset (10)]
  123. public char UnicodeChar;
  124. [FieldOffset (12), MarshalAs (UnmanagedType.U4)]
  125. public ControlKeyState dwControlKeyState;
  126. }
  127. [Flags]
  128. public enum ButtonState {
  129. Button1Pressed = 1,
  130. Button2Pressed = 4,
  131. Button3Pressed = 8,
  132. Button4Pressed = 16,
  133. RightmostButtonPressed = 2,
  134. WheeledUp = unchecked((int)0x780000),
  135. WheeledDown = unchecked((int)0xFF880000),
  136. }
  137. [Flags]
  138. public enum ControlKeyState {
  139. RightAltPressed = 1,
  140. LeftAltPressed = 2,
  141. RightControlPressed = 4,
  142. LeftControlPressed = 8,
  143. ShiftPressed = 16,
  144. NumlockOn = 32,
  145. ScrolllockOn = 64,
  146. CapslockOn = 128,
  147. EnhancedKey = 256
  148. }
  149. [Flags]
  150. public enum EventFlags {
  151. MouseMoved = 1,
  152. DoubleClick = 2,
  153. MouseWheeled = 4,
  154. MouseHorizontalWheeled = 8
  155. }
  156. [StructLayout (LayoutKind.Explicit)]
  157. public struct MouseEventRecord {
  158. [FieldOffset (0)]
  159. public Coordinate MousePosition;
  160. [FieldOffset (4)]
  161. public ButtonState ButtonState;
  162. [FieldOffset (8)]
  163. public ControlKeyState ControlKeyState;
  164. [FieldOffset (12)]
  165. public EventFlags EventFlags;
  166. public override string ToString ()
  167. {
  168. return $"[Mouse({MousePosition},{ButtonState},{ControlKeyState},{EventFlags}";
  169. }
  170. }
  171. [StructLayout (LayoutKind.Sequential)]
  172. public struct Coordinate {
  173. public short X;
  174. public short Y;
  175. public Coordinate (short X, short Y)
  176. {
  177. this.X = X;
  178. this.Y = Y;
  179. }
  180. public override string ToString () => $"({X},{Y})";
  181. };
  182. internal struct WindowBufferSizeRecord {
  183. public Coordinate size;
  184. public WindowBufferSizeRecord (short x, short y)
  185. {
  186. this.size = new Coordinate (x, y);
  187. }
  188. public override string ToString () => $"[WindowBufferSize{size}";
  189. }
  190. [StructLayout (LayoutKind.Sequential)]
  191. public struct MenuEventRecord {
  192. public uint dwCommandId;
  193. }
  194. [StructLayout (LayoutKind.Sequential)]
  195. public struct FocusEventRecord {
  196. public uint bSetFocus;
  197. }
  198. public enum EventType : ushort {
  199. Focus = 0x10,
  200. Key = 0x1,
  201. Menu = 0x8,
  202. Mouse = 2,
  203. WindowBufferSize = 4
  204. }
  205. [StructLayout (LayoutKind.Explicit)]
  206. public struct InputRecord {
  207. [FieldOffset (0)]
  208. public EventType EventType;
  209. [FieldOffset (4)]
  210. public KeyEventRecord KeyEvent;
  211. [FieldOffset (4)]
  212. public MouseEventRecord MouseEvent;
  213. [FieldOffset (4)]
  214. public WindowBufferSizeRecord WindowBufferSizeEvent;
  215. [FieldOffset (4)]
  216. public MenuEventRecord MenuEvent;
  217. [FieldOffset (4)]
  218. public FocusEventRecord FocusEvent;
  219. public override string ToString ()
  220. {
  221. switch (EventType) {
  222. case EventType.Focus:
  223. return FocusEvent.ToString ();
  224. case EventType.Key:
  225. return KeyEvent.ToString ();
  226. case EventType.Menu:
  227. return MenuEvent.ToString ();
  228. case EventType.Mouse:
  229. return MouseEvent.ToString ();
  230. case EventType.WindowBufferSize:
  231. return WindowBufferSizeEvent.ToString ();
  232. default:
  233. return "Unknown event type: " + EventType;
  234. }
  235. }
  236. };
  237. [Flags]
  238. enum ShareMode : uint {
  239. FileShareRead = 1,
  240. FileShareWrite = 2,
  241. }
  242. [Flags]
  243. enum DesiredAccess : uint {
  244. GenericRead = 2147483648,
  245. GenericWrite = 1073741824,
  246. }
  247. [StructLayout (LayoutKind.Sequential)]
  248. public struct ConsoleScreenBufferInfo {
  249. public Coord dwSize;
  250. public Coord dwCursorPosition;
  251. public ushort wAttributes;
  252. public SmallRect srWindow;
  253. public Coord dwMaximumWindowSize;
  254. }
  255. [StructLayout (LayoutKind.Sequential)]
  256. public struct Coord {
  257. public short X;
  258. public short Y;
  259. public Coord (short X, short Y)
  260. {
  261. this.X = X;
  262. this.Y = Y;
  263. }
  264. public override string ToString () => $"({X},{Y})";
  265. };
  266. [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
  267. public struct CharUnion {
  268. [FieldOffset (0)] public char UnicodeChar;
  269. [FieldOffset (0)] public byte AsciiChar;
  270. }
  271. [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
  272. public struct CharInfo {
  273. [FieldOffset (0)] public CharUnion Char;
  274. [FieldOffset (2)] public ushort Attributes;
  275. }
  276. [StructLayout (LayoutKind.Sequential)]
  277. public struct SmallRect {
  278. public short Left;
  279. public short Top;
  280. public short Right;
  281. public short Bottom;
  282. public static void MakeEmpty (ref SmallRect rect)
  283. {
  284. rect.Left = -1;
  285. }
  286. public static void Update (ref SmallRect rect, short col, short row)
  287. {
  288. if (rect.Left == -1) {
  289. //System.Diagnostics.Debugger.Log (0, "debug", $"damager From Empty {col},{row}\n");
  290. rect.Left = rect.Right = col;
  291. rect.Bottom = rect.Top = row;
  292. return;
  293. }
  294. if (col >= rect.Left && col <= rect.Right && row >= rect.Top && row <= rect.Bottom)
  295. return;
  296. if (col < rect.Left)
  297. rect.Left = col;
  298. if (col > rect.Right)
  299. rect.Right = col;
  300. if (row < rect.Top)
  301. rect.Top = row;
  302. if (row > rect.Bottom)
  303. rect.Bottom = row;
  304. //System.Diagnostics.Debugger.Log (0, "debug", $"Expanding {rect.ToString ()}\n");
  305. }
  306. public override string ToString ()
  307. {
  308. return $"Left={Left},Top={Top},Right={Right},Bottom={Bottom}";
  309. }
  310. }
  311. [DllImport ("kernel32.dll", SetLastError = true)]
  312. static extern IntPtr GetStdHandle (int nStdHandle);
  313. [DllImport ("kernel32.dll", SetLastError = true)]
  314. static extern bool CloseHandle (IntPtr handle);
  315. [DllImport ("kernel32.dll", EntryPoint = "ReadConsoleInputW", CharSet = CharSet.Unicode)]
  316. public static extern bool ReadConsoleInput (
  317. IntPtr hConsoleInput,
  318. [Out] InputRecord [] lpBuffer,
  319. uint nLength,
  320. out uint lpNumberOfEventsRead);
  321. [DllImport ("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
  322. static extern bool ReadConsoleOutput (
  323. IntPtr hConsoleOutput,
  324. [Out] CharInfo [] lpBuffer,
  325. Coord dwBufferSize,
  326. Coord dwBufferCoord,
  327. ref SmallRect lpReadRegion
  328. );
  329. [DllImport ("kernel32.dll", EntryPoint = "WriteConsoleOutput", SetLastError = true, CharSet = CharSet.Unicode)]
  330. static extern bool WriteConsoleOutput (
  331. IntPtr hConsoleOutput,
  332. CharInfo [] lpBuffer,
  333. Coord dwBufferSize,
  334. Coord dwBufferCoord,
  335. ref SmallRect lpWriteRegion
  336. );
  337. [DllImport ("kernel32.dll")]
  338. static extern bool SetConsoleCursorPosition (IntPtr hConsoleOutput, Coord dwCursorPosition);
  339. [DllImport ("kernel32.dll")]
  340. static extern bool GetConsoleMode (IntPtr hConsoleHandle, out uint lpMode);
  341. [DllImport ("kernel32.dll")]
  342. static extern bool SetConsoleMode (IntPtr hConsoleHandle, uint dwMode);
  343. [DllImport ("kernel32.dll", SetLastError = true)]
  344. static extern IntPtr CreateConsoleScreenBuffer (
  345. DesiredAccess dwDesiredAccess,
  346. ShareMode dwShareMode,
  347. IntPtr secutiryAttributes,
  348. UInt32 flags,
  349. IntPtr screenBufferData
  350. );
  351. internal static IntPtr INVALID_HANDLE_VALUE = new IntPtr (-1);
  352. [DllImport ("kernel32.dll", SetLastError = true)]
  353. static extern bool SetConsoleActiveScreenBuffer (IntPtr Handle);
  354. [DllImport ("kernel32.dll", SetLastError = true)]
  355. static extern bool GetNumberOfConsoleInputEvents (IntPtr handle, out uint lpcNumberOfEvents);
  356. public uint InputEventCount {
  357. get {
  358. uint v;
  359. GetNumberOfConsoleInputEvents (InputHandle, out v);
  360. return v;
  361. }
  362. }
  363. }
  364. internal class WindowsDriver : ConsoleDriver, Mono.Terminal.IMainLoopDriver {
  365. static bool sync;
  366. ManualResetEventSlim eventReady = new ManualResetEventSlim (false);
  367. ManualResetEventSlim waitForProbe = new ManualResetEventSlim (false);
  368. MainLoop mainLoop;
  369. WindowsConsole.CharInfo [] OutputBuffer;
  370. int cols, rows;
  371. WindowsConsole winConsole;
  372. WindowsConsole.SmallRect damageRegion;
  373. public override int Cols => cols;
  374. public override int Rows => rows;
  375. public WindowsDriver ()
  376. {
  377. Colors.TopLevel = new ColorScheme ();
  378. Colors.TopLevel.Normal = MakeColor (ConsoleColor.Green, ConsoleColor.Black);
  379. Colors.TopLevel.Focus = MakeColor (ConsoleColor.White, ConsoleColor.DarkCyan);
  380. Colors.TopLevel.HotNormal = MakeColor (ConsoleColor.DarkYellow, ConsoleColor.Black);
  381. Colors.TopLevel.HotFocus = MakeColor (ConsoleColor.DarkYellow, ConsoleColor.DarkCyan);
  382. winConsole = new WindowsConsole ();
  383. cols = Console.WindowWidth;
  384. rows = Console.WindowHeight;
  385. WindowsConsole.SmallRect.MakeEmpty (ref damageRegion);
  386. ResizeScreen ();
  387. UpdateOffScreen ();
  388. Task.Run ((Action)WindowsInputHandler);
  389. }
  390. [StructLayout (LayoutKind.Sequential)]
  391. public struct ConsoleKeyInfoEx {
  392. public ConsoleKeyInfo consoleKeyInfo;
  393. public bool CapsLock;
  394. public bool NumLock;
  395. public ConsoleKeyInfoEx (ConsoleKeyInfo consoleKeyInfo, bool capslock, bool numlock)
  396. {
  397. this.consoleKeyInfo = consoleKeyInfo;
  398. CapsLock = capslock;
  399. NumLock = numlock;
  400. }
  401. }
  402. // The records that we keep fetching
  403. WindowsConsole.InputRecord [] result, records = new WindowsConsole.InputRecord [1];
  404. void WindowsInputHandler ()
  405. {
  406. while (true) {
  407. waitForProbe.Wait ();
  408. waitForProbe.Reset ();
  409. uint numberEventsRead = 0;
  410. WindowsConsole.ReadConsoleInput (winConsole.InputHandle, records, 1, out numberEventsRead);
  411. if (numberEventsRead == 0)
  412. result = null;
  413. else
  414. result = records;
  415. eventReady.Set ();
  416. }
  417. }
  418. void IMainLoopDriver.Setup (MainLoop mainLoop)
  419. {
  420. this.mainLoop = mainLoop;
  421. }
  422. void IMainLoopDriver.Wakeup ()
  423. {
  424. tokenSource.Cancel ();
  425. }
  426. bool IMainLoopDriver.EventsPending (bool wait)
  427. {
  428. long now = DateTime.UtcNow.Ticks;
  429. int waitTimeout;
  430. if (mainLoop.timeouts.Count > 0) {
  431. waitTimeout = (int)((mainLoop.timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  432. if (waitTimeout < 0)
  433. return true;
  434. } else
  435. waitTimeout = -1;
  436. if (!wait)
  437. waitTimeout = 0;
  438. result = null;
  439. waitForProbe.Set ();
  440. try {
  441. if (!tokenSource.IsCancellationRequested)
  442. eventReady.Wait (waitTimeout, tokenSource.Token);
  443. } catch (OperationCanceledException) {
  444. return true;
  445. } finally {
  446. eventReady.Reset ();
  447. }
  448. if (!tokenSource.IsCancellationRequested)
  449. return result != null;
  450. tokenSource.Dispose ();
  451. tokenSource = new CancellationTokenSource ();
  452. return true;
  453. }
  454. Action<KeyEvent> keyHandler;
  455. Action<KeyEvent> keyDownHandler;
  456. Action<KeyEvent> keyUpHandler;
  457. Action<MouseEvent> mouseHandler;
  458. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
  459. {
  460. this.keyHandler = keyHandler;
  461. this.keyDownHandler = keyDownHandler;
  462. this.keyUpHandler = keyUpHandler;
  463. this.mouseHandler = mouseHandler;
  464. }
  465. void IMainLoopDriver.MainIteration ()
  466. {
  467. if (result == null)
  468. return;
  469. var inputEvent = result [0];
  470. switch (inputEvent.EventType) {
  471. case WindowsConsole.EventType.Key:
  472. var map = MapKey (ToConsoleKeyInfoEx (inputEvent.KeyEvent));
  473. if (map == (Key)0xffffffff) {
  474. KeyEvent key;
  475. // Shift = VK_SHIFT = 0x10
  476. // Ctrl = VK_CONTROL = 0x11
  477. // Alt = VK_MENU = 0x12
  478. switch (inputEvent.KeyEvent.wVirtualKeyCode) {
  479. case 0x11:
  480. key = new KeyEvent (Key.CtrlMask);
  481. break;
  482. case 0x12:
  483. key = new KeyEvent (Key.AltMask);
  484. break;
  485. default:
  486. key = new KeyEvent (Key.Unknown);
  487. break;
  488. }
  489. if (inputEvent.KeyEvent.bKeyDown)
  490. keyDownHandler (key);
  491. else
  492. keyUpHandler (key);
  493. } else {
  494. if (inputEvent.KeyEvent.bKeyDown) {
  495. // Key Down - Fire KeyDown Event and KeyStroke (ProcessKey) Event
  496. keyDownHandler (new KeyEvent (map));
  497. keyHandler (new KeyEvent (map));
  498. } else {
  499. keyUpHandler (new KeyEvent (map));
  500. }
  501. }
  502. break;
  503. case WindowsConsole.EventType.Mouse:
  504. mouseHandler (ToDriverMouse (inputEvent.MouseEvent));
  505. if (IsButtonReleased)
  506. mouseHandler (ToDriverMouse (inputEvent.MouseEvent));
  507. break;
  508. case WindowsConsole.EventType.WindowBufferSize:
  509. cols = inputEvent.WindowBufferSizeEvent.size.X;
  510. rows = inputEvent.WindowBufferSizeEvent.size.Y;
  511. ResizeScreen ();
  512. UpdateOffScreen ();
  513. TerminalResized?.Invoke ();
  514. break;
  515. }
  516. result = null;
  517. }
  518. WindowsConsole.ButtonState? LastMouseButtonPressed = null;
  519. bool IsButtonReleased = false;
  520. bool IsButtonDoubleClicked = false;
  521. Point point;
  522. MouseEvent ToDriverMouse (WindowsConsole.MouseEventRecord mouseEvent)
  523. {
  524. MouseFlags mouseFlag = MouseFlags.AllEvents;
  525. if (IsButtonDoubleClicked) {
  526. Task.Run (async () => {
  527. await Task.Delay (100);
  528. IsButtonDoubleClicked = false;
  529. });
  530. }
  531. // The ButtonState member of the MouseEvent structure has bit corresponding to each mouse button.
  532. // This will tell when a mouse button is pressed. When the button is released this event will
  533. // be fired with it's bit set to 0. So when the button is up ButtonState will be 0.
  534. // To map to the correct driver events we save the last pressed mouse button so we can
  535. // map to the correct clicked event.
  536. if ((LastMouseButtonPressed != null || IsButtonReleased) && mouseEvent.ButtonState != 0) {
  537. LastMouseButtonPressed = null;
  538. IsButtonReleased = false;
  539. }
  540. if ((mouseEvent.EventFlags == 0 && LastMouseButtonPressed == null && !IsButtonDoubleClicked) ||
  541. (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved &&
  542. mouseEvent.ButtonState != 0 && !IsButtonReleased && !IsButtonDoubleClicked)) {
  543. switch (mouseEvent.ButtonState) {
  544. case WindowsConsole.ButtonState.Button1Pressed:
  545. mouseFlag = MouseFlags.Button1Pressed;
  546. break;
  547. case WindowsConsole.ButtonState.Button2Pressed:
  548. mouseFlag = MouseFlags.Button2Pressed;
  549. break;
  550. case WindowsConsole.ButtonState.RightmostButtonPressed:
  551. mouseFlag = MouseFlags.Button4Pressed;
  552. break;
  553. }
  554. if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  555. mouseFlag |= MouseFlags.ReportMousePosition;
  556. point = new Point ();
  557. IsButtonReleased = false;
  558. } else {
  559. point = new Point () {
  560. X = mouseEvent.MousePosition.X,
  561. Y = mouseEvent.MousePosition.Y
  562. };
  563. }
  564. LastMouseButtonPressed = mouseEvent.ButtonState;
  565. } else if ((mouseEvent.EventFlags == 0 || mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) &&
  566. LastMouseButtonPressed != null && !IsButtonReleased && !IsButtonDoubleClicked) {
  567. switch (LastMouseButtonPressed) {
  568. case WindowsConsole.ButtonState.Button1Pressed:
  569. mouseFlag = MouseFlags.Button1Released;
  570. break;
  571. case WindowsConsole.ButtonState.Button2Pressed:
  572. mouseFlag = MouseFlags.Button2Released;
  573. break;
  574. case WindowsConsole.ButtonState.RightmostButtonPressed:
  575. mouseFlag = MouseFlags.Button4Released;
  576. break;
  577. }
  578. IsButtonReleased = true;
  579. } else if ((mouseEvent.EventFlags == 0 || mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) &&
  580. IsButtonReleased) {
  581. var p = new Point () {
  582. X = mouseEvent.MousePosition.X,
  583. Y = mouseEvent.MousePosition.Y
  584. };
  585. if (p == point) {
  586. switch (LastMouseButtonPressed) {
  587. case WindowsConsole.ButtonState.Button1Pressed:
  588. mouseFlag = MouseFlags.Button1Clicked;
  589. break;
  590. case WindowsConsole.ButtonState.Button2Pressed:
  591. mouseFlag = MouseFlags.Button2Clicked;
  592. break;
  593. case WindowsConsole.ButtonState.RightmostButtonPressed:
  594. mouseFlag = MouseFlags.Button4Clicked;
  595. break;
  596. }
  597. } else {
  598. mouseFlag = 0;
  599. }
  600. LastMouseButtonPressed = null;
  601. IsButtonReleased = false;
  602. } else if (mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.DoubleClick)) {
  603. switch (mouseEvent.ButtonState) {
  604. case WindowsConsole.ButtonState.Button1Pressed:
  605. mouseFlag = MouseFlags.Button1DoubleClicked;
  606. break;
  607. case WindowsConsole.ButtonState.Button2Pressed:
  608. mouseFlag = MouseFlags.Button2DoubleClicked;
  609. break;
  610. case WindowsConsole.ButtonState.RightmostButtonPressed:
  611. mouseFlag = MouseFlags.Button4DoubleClicked;
  612. break;
  613. }
  614. IsButtonDoubleClicked = true;
  615. } else if (mouseEvent.EventFlags == 0 && mouseEvent.ButtonState != 0 && IsButtonDoubleClicked) {
  616. switch (mouseEvent.ButtonState) {
  617. case WindowsConsole.ButtonState.Button1Pressed:
  618. mouseFlag = MouseFlags.Button1TripleClicked;
  619. break;
  620. case WindowsConsole.ButtonState.Button2Pressed:
  621. mouseFlag = MouseFlags.Button2TripleClicked;
  622. break;
  623. case WindowsConsole.ButtonState.RightmostButtonPressed:
  624. mouseFlag = MouseFlags.Button4TripleClicked;
  625. break;
  626. }
  627. IsButtonDoubleClicked = false;
  628. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled) {
  629. switch (mouseEvent.ButtonState) {
  630. case WindowsConsole.ButtonState.WheeledUp:
  631. mouseFlag = MouseFlags.WheeledUp;
  632. break;
  633. case WindowsConsole.ButtonState.WheeledDown:
  634. mouseFlag = MouseFlags.WheeledDown;
  635. break;
  636. }
  637. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  638. mouseFlag = MouseFlags.ReportMousePosition;
  639. }
  640. mouseFlag = SetControlKeyStates (mouseEvent, mouseFlag);
  641. return new MouseEvent () {
  642. X = mouseEvent.MousePosition.X,
  643. Y = mouseEvent.MousePosition.Y,
  644. Flags = mouseFlag
  645. };
  646. }
  647. static MouseFlags SetControlKeyStates (WindowsConsole.MouseEventRecord mouseEvent, MouseFlags mouseFlag)
  648. {
  649. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed) ||
  650. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed))
  651. mouseFlag |= MouseFlags.ButtonCtrl;
  652. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed))
  653. mouseFlag |= MouseFlags.ButtonShift;
  654. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed) ||
  655. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed))
  656. mouseFlag |= MouseFlags.ButtonAlt;
  657. return mouseFlag;
  658. }
  659. public ConsoleKeyInfoEx ToConsoleKeyInfoEx (WindowsConsole.KeyEventRecord keyEvent)
  660. {
  661. var state = keyEvent.dwControlKeyState;
  662. bool shift = (state & WindowsConsole.ControlKeyState.ShiftPressed) != 0;
  663. bool alt = (state & (WindowsConsole.ControlKeyState.LeftAltPressed | WindowsConsole.ControlKeyState.RightAltPressed)) != 0;
  664. bool control = (state & (WindowsConsole.ControlKeyState.LeftControlPressed | WindowsConsole.ControlKeyState.RightControlPressed)) != 0;
  665. bool capslock = (state & (WindowsConsole.ControlKeyState.CapslockOn)) != 0;
  666. bool numlock = (state & (WindowsConsole.ControlKeyState.NumlockOn)) != 0;
  667. var ConsoleKeyInfo = new ConsoleKeyInfo (keyEvent.UnicodeChar, (ConsoleKey)keyEvent.wVirtualKeyCode, shift, alt, control);
  668. return new ConsoleKeyInfoEx (ConsoleKeyInfo, capslock, numlock);
  669. }
  670. public Key MapKey (ConsoleKeyInfoEx keyInfoEx)
  671. {
  672. var keyInfo = keyInfoEx.consoleKeyInfo;
  673. switch (keyInfo.Key) {
  674. case ConsoleKey.Escape:
  675. return Key.Esc;
  676. case ConsoleKey.Tab:
  677. return keyInfo.Modifiers == ConsoleModifiers.Shift ? Key.BackTab : Key.Tab;
  678. case ConsoleKey.Home:
  679. return Key.Home;
  680. case ConsoleKey.End:
  681. return Key.End;
  682. case ConsoleKey.LeftArrow:
  683. return Key.CursorLeft;
  684. case ConsoleKey.RightArrow:
  685. return Key.CursorRight;
  686. case ConsoleKey.UpArrow:
  687. return Key.CursorUp;
  688. case ConsoleKey.DownArrow:
  689. return Key.CursorDown;
  690. case ConsoleKey.PageUp:
  691. return Key.PageUp;
  692. case ConsoleKey.PageDown:
  693. return Key.PageDown;
  694. case ConsoleKey.Enter:
  695. return Key.Enter;
  696. case ConsoleKey.Spacebar:
  697. return Key.Space;
  698. case ConsoleKey.Backspace:
  699. return Key.Backspace;
  700. case ConsoleKey.Delete:
  701. return Key.DeleteChar;
  702. case ConsoleKey.NumPad0:
  703. return keyInfoEx.NumLock ? (Key)(uint)'0' : Key.InsertChar;
  704. case ConsoleKey.NumPad1:
  705. return keyInfoEx.NumLock ? (Key)(uint)'1' : Key.End;
  706. case ConsoleKey.NumPad2:
  707. return keyInfoEx.NumLock ? (Key)(uint)'2' : Key.CursorDown;
  708. case ConsoleKey.NumPad3:
  709. return keyInfoEx.NumLock ? (Key)(uint)'3' : Key.PageDown;
  710. case ConsoleKey.NumPad4:
  711. return keyInfoEx.NumLock ? (Key)(uint)'4' : Key.CursorLeft;
  712. case ConsoleKey.NumPad5:
  713. return keyInfoEx.NumLock ? (Key)(uint)'5' : (Key)((uint)keyInfo.KeyChar);
  714. case ConsoleKey.NumPad6:
  715. return keyInfoEx.NumLock ? (Key)(uint)'6' : Key.CursorRight;
  716. case ConsoleKey.NumPad7:
  717. return keyInfoEx.NumLock ? (Key)(uint)'7' : Key.Home;
  718. case ConsoleKey.NumPad8:
  719. return keyInfoEx.NumLock ? (Key)(uint)'8' : Key.CursorUp;
  720. case ConsoleKey.NumPad9:
  721. return keyInfoEx.NumLock ? (Key)(uint)'9' : Key.PageUp;
  722. case ConsoleKey.Oem1:
  723. case ConsoleKey.Oem2:
  724. case ConsoleKey.Oem3:
  725. case ConsoleKey.Oem4:
  726. case ConsoleKey.Oem5:
  727. case ConsoleKey.Oem6:
  728. case ConsoleKey.Oem7:
  729. case ConsoleKey.Oem8:
  730. case ConsoleKey.Oem102:
  731. case ConsoleKey.OemPeriod:
  732. case ConsoleKey.OemComma:
  733. case ConsoleKey.OemPlus:
  734. case ConsoleKey.OemMinus:
  735. return (Key)((uint)keyInfo.KeyChar);
  736. }
  737. var key = keyInfo.Key;
  738. var alphaBase = ((keyInfo.Modifiers == ConsoleModifiers.Shift) ^ (keyInfoEx.CapsLock)) ? 'A' : 'a';
  739. if (key >= ConsoleKey.A && key <= ConsoleKey.Z) {
  740. var delta = key - ConsoleKey.A;
  741. if (keyInfo.Modifiers == ConsoleModifiers.Control)
  742. return (Key)((uint)Key.ControlA + delta);
  743. if (keyInfo.Modifiers == ConsoleModifiers.Alt)
  744. return (Key)(((uint)Key.AltMask) | ((uint)'A' + delta));
  745. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  746. if (keyInfo.KeyChar == 0)
  747. return (Key)(((uint)Key.AltMask) + ((uint)Key.ControlA + delta));
  748. else
  749. return (Key)((uint)keyInfo.KeyChar);
  750. }
  751. return (Key)((uint)alphaBase + delta);
  752. }
  753. if (key >= ConsoleKey.D0 && key <= ConsoleKey.D9) {
  754. var delta = key - ConsoleKey.D0;
  755. if (keyInfo.Modifiers == ConsoleModifiers.Alt)
  756. return (Key)(((uint)Key.AltMask) | ((uint)'0' + delta));
  757. return (Key)((uint)keyInfo.KeyChar);
  758. }
  759. if (key >= ConsoleKey.F1 && key <= ConsoleKey.F10) {
  760. var delta = key - ConsoleKey.F1;
  761. return (Key)((int)Key.F1 + delta);
  762. }
  763. return (Key)(0xffffffff);
  764. }
  765. public override void Init (Action terminalResized)
  766. {
  767. TerminalResized = terminalResized;
  768. Colors.Base = new ColorScheme ();
  769. Colors.Dialog = new ColorScheme ();
  770. Colors.Menu = new ColorScheme ();
  771. Colors.Error = new ColorScheme ();
  772. HLine = '\u2500';
  773. VLine = '\u2502';
  774. Stipple = '\u2592';
  775. Diamond = '\u25c6';
  776. ULCorner = '\u250C';
  777. LLCorner = '\u2514';
  778. URCorner = '\u2510';
  779. LRCorner = '\u2518';
  780. LeftTee = '\u251c';
  781. RightTee = '\u2524';
  782. TopTee = '\u22a4';
  783. BottomTee = '\u22a5';
  784. Colors.Base.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Blue);
  785. Colors.Base.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Cyan);
  786. Colors.Base.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Blue);
  787. Colors.Base.HotFocus = MakeColor (ConsoleColor.Yellow, ConsoleColor.Cyan);
  788. Colors.Menu.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Cyan);
  789. Colors.Menu.Focus = MakeColor (ConsoleColor.White, ConsoleColor.Black);
  790. Colors.Menu.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Cyan);
  791. Colors.Menu.HotFocus = MakeColor (ConsoleColor.Yellow, ConsoleColor.Black);
  792. Colors.Menu.Disabled = MakeColor (ConsoleColor.DarkGray, ConsoleColor.Cyan);
  793. Colors.Dialog.Normal = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
  794. Colors.Dialog.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Cyan);
  795. Colors.Dialog.HotNormal = MakeColor (ConsoleColor.Blue, ConsoleColor.Gray);
  796. Colors.Dialog.HotFocus = MakeColor (ConsoleColor.Blue, ConsoleColor.Cyan);
  797. Colors.Error.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Red);
  798. Colors.Error.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
  799. Colors.Error.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Red);
  800. Colors.Error.HotFocus = Colors.Error.HotNormal;
  801. Console.Clear ();
  802. }
  803. void ResizeScreen ()
  804. {
  805. OutputBuffer = new WindowsConsole.CharInfo [Rows * Cols];
  806. Clip = new Rect (0, 0, Cols, Rows);
  807. damageRegion = new WindowsConsole.SmallRect () {
  808. Top = 0,
  809. Left = 0,
  810. Bottom = (short)Rows,
  811. Right = (short)Cols
  812. };
  813. }
  814. void UpdateOffScreen ()
  815. {
  816. for (int row = 0; row < rows; row++)
  817. for (int col = 0; col < cols; col++) {
  818. int position = row * cols + col;
  819. OutputBuffer [position].Attributes = (ushort)Colors.TopLevel.Normal;
  820. OutputBuffer [position].Char.UnicodeChar = ' ';
  821. }
  822. }
  823. int ccol, crow;
  824. public override void Move (int col, int row)
  825. {
  826. ccol = col;
  827. crow = row;
  828. }
  829. public override void AddRune (Rune rune)
  830. {
  831. var position = crow * Cols + ccol;
  832. if (Clip.Contains (ccol, crow)) {
  833. OutputBuffer [position].Attributes = (ushort)currentAttribute;
  834. OutputBuffer [position].Char.UnicodeChar = (char)rune;
  835. WindowsConsole.SmallRect.Update (ref damageRegion, (short)ccol, (short)crow);
  836. }
  837. ccol++;
  838. var runeWidth = Rune.ColumnWidth (rune);
  839. if (runeWidth > 1) {
  840. for (int i = 1; i < runeWidth; i++) {
  841. AddStr (" ");
  842. }
  843. }
  844. if (ccol == Cols) {
  845. ccol = 0;
  846. if (crow + 1 < Rows)
  847. crow++;
  848. }
  849. if (sync)
  850. UpdateScreen ();
  851. }
  852. public override void AddStr (ustring str)
  853. {
  854. foreach (var rune in str)
  855. AddRune (rune);
  856. }
  857. int currentAttribute;
  858. CancellationTokenSource tokenSource = new CancellationTokenSource ();
  859. public override void SetAttribute (Attribute c)
  860. {
  861. currentAttribute = c.value;
  862. }
  863. Attribute MakeColor (ConsoleColor f, ConsoleColor b)
  864. {
  865. // Encode the colors into the int value.
  866. return new Attribute () {
  867. value = ((int)f | (int)b << 4),
  868. foreground = (Color)f,
  869. background = (Color)b
  870. };
  871. }
  872. public override Attribute MakeAttribute (Color fore, Color back)
  873. {
  874. return MakeColor ((ConsoleColor)fore, (ConsoleColor)back);
  875. }
  876. public override void Refresh ()
  877. {
  878. UpdateScreen ();
  879. #if false
  880. var bufferCoords = new WindowsConsole.Coord (){
  881. X = (short)Clip.Width,
  882. Y = (short)Clip.Height
  883. };
  884. var window = new WindowsConsole.SmallRect (){
  885. Top = 0,
  886. Left = 0,
  887. Right = (short)Clip.Right,
  888. Bottom = (short)Clip.Bottom
  889. };
  890. UpdateCursor();
  891. winConsole.WriteToConsole (OutputBuffer, bufferCoords, window);
  892. #endif
  893. }
  894. public override void UpdateScreen ()
  895. {
  896. if (damageRegion.Left == -1)
  897. return;
  898. var bufferCoords = new WindowsConsole.Coord () {
  899. X = (short)Clip.Width,
  900. Y = (short)Clip.Height
  901. };
  902. var window = new WindowsConsole.SmallRect () {
  903. Top = 0,
  904. Left = 0,
  905. Right = (short)Clip.Right,
  906. Bottom = (short)Clip.Bottom
  907. };
  908. UpdateCursor ();
  909. winConsole.WriteToConsole (OutputBuffer, bufferCoords, damageRegion);
  910. // System.Diagnostics.Debugger.Log(0, "debug", $"Region={damageRegion.Right - damageRegion.Left},{damageRegion.Bottom - damageRegion.Top}\n");
  911. WindowsConsole.SmallRect.MakeEmpty (ref damageRegion);
  912. }
  913. public override void UpdateCursor ()
  914. {
  915. var position = new WindowsConsole.Coord () {
  916. X = (short)ccol,
  917. Y = (short)crow
  918. };
  919. winConsole.SetCursorPosition (position);
  920. }
  921. public override void End ()
  922. {
  923. winConsole.Cleanup ();
  924. }
  925. #region Unused
  926. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  927. {
  928. }
  929. public override void SetColors (short foregroundColorId, short backgroundColorId)
  930. {
  931. }
  932. public override void Suspend ()
  933. {
  934. }
  935. public override void StartReportingMouseMoves ()
  936. {
  937. }
  938. public override void StopReportingMouseMoves ()
  939. {
  940. }
  941. public override void UncookMouse ()
  942. {
  943. }
  944. public override void CookMouse ()
  945. {
  946. }
  947. #endregion
  948. }
  949. }