WindowsDriver.cs 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093
  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. break;
  506. case WindowsConsole.EventType.WindowBufferSize:
  507. cols = inputEvent.WindowBufferSizeEvent.size.X;
  508. rows = inputEvent.WindowBufferSizeEvent.size.Y;
  509. ResizeScreen ();
  510. UpdateOffScreen ();
  511. TerminalResized?.Invoke ();
  512. break;
  513. }
  514. result = null;
  515. }
  516. WindowsConsole.ButtonState? LastMouseButtonPressed = null;
  517. bool IsButtonReleased = false;
  518. bool IsButtonDoubleClicked = false;
  519. MouseEvent ToDriverMouse (WindowsConsole.MouseEventRecord mouseEvent)
  520. {
  521. MouseFlags mouseFlag = MouseFlags.AllEvents;
  522. if (IsButtonDoubleClicked) {
  523. Task.Run (async () => {
  524. await Task.Delay (300);
  525. _ = new Action (() => IsButtonDoubleClicked = false);
  526. });
  527. }
  528. // The ButtonState member of the MouseEvent structure has bit corresponding to each mouse button.
  529. // This will tell when a mouse button is pressed. When the button is released this event will
  530. // be fired with it's bit set to 0. So when the button is up ButtonState will be 0.
  531. // To map to the correct driver events we save the last pressed mouse button so we can
  532. // map to the correct clicked event.
  533. if ((LastMouseButtonPressed != null || IsButtonReleased) && mouseEvent.ButtonState != 0) {
  534. LastMouseButtonPressed = null;
  535. IsButtonReleased = false;
  536. }
  537. if ((mouseEvent.EventFlags == 0 && LastMouseButtonPressed == null && !IsButtonDoubleClicked) ||
  538. (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved &&
  539. mouseEvent.ButtonState != 0 && !IsButtonDoubleClicked)) {
  540. switch (mouseEvent.ButtonState) {
  541. case WindowsConsole.ButtonState.Button1Pressed:
  542. mouseFlag = MouseFlags.Button1Pressed;
  543. break;
  544. case WindowsConsole.ButtonState.Button2Pressed:
  545. mouseFlag = MouseFlags.Button2Pressed;
  546. break;
  547. case WindowsConsole.ButtonState.RightmostButtonPressed:
  548. mouseFlag = MouseFlags.Button4Pressed;
  549. break;
  550. }
  551. if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved)
  552. mouseFlag |= MouseFlags.ReportMousePosition;
  553. LastMouseButtonPressed = mouseEvent.ButtonState;
  554. } else if (mouseEvent.EventFlags == 0 && LastMouseButtonPressed != null && !IsButtonReleased &&
  555. !IsButtonDoubleClicked) {
  556. switch (LastMouseButtonPressed) {
  557. case WindowsConsole.ButtonState.Button1Pressed:
  558. mouseFlag = MouseFlags.Button1Released;
  559. break;
  560. case WindowsConsole.ButtonState.Button2Pressed:
  561. mouseFlag = MouseFlags.Button2Released;
  562. break;
  563. case WindowsConsole.ButtonState.RightmostButtonPressed:
  564. mouseFlag = MouseFlags.Button4Released;
  565. break;
  566. }
  567. IsButtonReleased = true;
  568. } else if ((mouseEvent.EventFlags == 0 || mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) &&
  569. IsButtonReleased) {
  570. switch (LastMouseButtonPressed) {
  571. case WindowsConsole.ButtonState.Button1Pressed:
  572. mouseFlag = MouseFlags.Button1Clicked;
  573. break;
  574. case WindowsConsole.ButtonState.Button2Pressed:
  575. mouseFlag = MouseFlags.Button2Clicked;
  576. break;
  577. case WindowsConsole.ButtonState.RightmostButtonPressed:
  578. mouseFlag = MouseFlags.Button4Clicked;
  579. break;
  580. }
  581. LastMouseButtonPressed = null;
  582. IsButtonReleased = false;
  583. } else if (mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.DoubleClick)) {
  584. switch (mouseEvent.ButtonState) {
  585. case WindowsConsole.ButtonState.Button1Pressed:
  586. mouseFlag = MouseFlags.Button1DoubleClicked;
  587. break;
  588. case WindowsConsole.ButtonState.Button2Pressed:
  589. mouseFlag = MouseFlags.Button2DoubleClicked;
  590. break;
  591. case WindowsConsole.ButtonState.RightmostButtonPressed:
  592. mouseFlag = MouseFlags.Button4DoubleClicked;
  593. break;
  594. }
  595. IsButtonDoubleClicked = true;
  596. } else if (mouseEvent.EventFlags == 0 && mouseEvent.ButtonState != 0 && IsButtonDoubleClicked) {
  597. switch (mouseEvent.ButtonState) {
  598. case WindowsConsole.ButtonState.Button1Pressed:
  599. mouseFlag = MouseFlags.Button1TripleClicked;
  600. break;
  601. case WindowsConsole.ButtonState.Button2Pressed:
  602. mouseFlag = MouseFlags.Button2TripleClicked;
  603. break;
  604. case WindowsConsole.ButtonState.RightmostButtonPressed:
  605. mouseFlag = MouseFlags.Button4TripleClicked;
  606. break;
  607. }
  608. IsButtonDoubleClicked = false;
  609. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled) {
  610. switch (mouseEvent.ButtonState) {
  611. case WindowsConsole.ButtonState.WheeledUp:
  612. mouseFlag = MouseFlags.WheeledUp;
  613. break;
  614. case WindowsConsole.ButtonState.WheeledDown:
  615. mouseFlag = MouseFlags.WheeledDown;
  616. break;
  617. }
  618. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  619. mouseFlag = MouseFlags.ReportMousePosition;
  620. }
  621. mouseFlag = SetControlKeyStates (mouseEvent, mouseFlag);
  622. return new MouseEvent () {
  623. X = mouseEvent.MousePosition.X,
  624. Y = mouseEvent.MousePosition.Y,
  625. Flags = mouseFlag
  626. };
  627. }
  628. static MouseFlags SetControlKeyStates (WindowsConsole.MouseEventRecord mouseEvent, MouseFlags mouseFlag)
  629. {
  630. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed) ||
  631. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed))
  632. mouseFlag |= MouseFlags.ButtonCtrl;
  633. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed))
  634. mouseFlag |= MouseFlags.ButtonShift;
  635. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed) ||
  636. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed))
  637. mouseFlag |= MouseFlags.ButtonAlt;
  638. return mouseFlag;
  639. }
  640. public ConsoleKeyInfoEx ToConsoleKeyInfoEx (WindowsConsole.KeyEventRecord keyEvent)
  641. {
  642. var state = keyEvent.dwControlKeyState;
  643. bool shift = (state & WindowsConsole.ControlKeyState.ShiftPressed) != 0;
  644. bool alt = (state & (WindowsConsole.ControlKeyState.LeftAltPressed | WindowsConsole.ControlKeyState.RightAltPressed)) != 0;
  645. bool control = (state & (WindowsConsole.ControlKeyState.LeftControlPressed | WindowsConsole.ControlKeyState.RightControlPressed)) != 0;
  646. bool capslock = (state & (WindowsConsole.ControlKeyState.CapslockOn)) != 0;
  647. bool numlock = (state & (WindowsConsole.ControlKeyState.NumlockOn)) != 0;
  648. var ConsoleKeyInfo = new ConsoleKeyInfo (keyEvent.UnicodeChar, (ConsoleKey)keyEvent.wVirtualKeyCode, shift, alt, control);
  649. return new ConsoleKeyInfoEx (ConsoleKeyInfo, capslock, numlock);
  650. }
  651. public Key MapKey (ConsoleKeyInfoEx keyInfoEx)
  652. {
  653. var keyInfo = keyInfoEx.consoleKeyInfo;
  654. switch (keyInfo.Key) {
  655. case ConsoleKey.Escape:
  656. return Key.Esc;
  657. case ConsoleKey.Tab:
  658. return keyInfo.Modifiers == ConsoleModifiers.Shift ? Key.BackTab : Key.Tab;
  659. case ConsoleKey.Home:
  660. return Key.Home;
  661. case ConsoleKey.End:
  662. return Key.End;
  663. case ConsoleKey.LeftArrow:
  664. return Key.CursorLeft;
  665. case ConsoleKey.RightArrow:
  666. return Key.CursorRight;
  667. case ConsoleKey.UpArrow:
  668. return Key.CursorUp;
  669. case ConsoleKey.DownArrow:
  670. return Key.CursorDown;
  671. case ConsoleKey.PageUp:
  672. return Key.PageUp;
  673. case ConsoleKey.PageDown:
  674. return Key.PageDown;
  675. case ConsoleKey.Enter:
  676. return Key.Enter;
  677. case ConsoleKey.Spacebar:
  678. return Key.Space;
  679. case ConsoleKey.Backspace:
  680. return Key.Backspace;
  681. case ConsoleKey.Delete:
  682. return Key.DeleteChar;
  683. case ConsoleKey.NumPad0:
  684. return keyInfoEx.NumLock ? (Key)(uint)'0' : Key.InsertChar;
  685. case ConsoleKey.NumPad1:
  686. return keyInfoEx.NumLock ? (Key)(uint)'1' : Key.End;
  687. case ConsoleKey.NumPad2:
  688. return keyInfoEx.NumLock ? (Key)(uint)'2' : Key.CursorDown;
  689. case ConsoleKey.NumPad3:
  690. return keyInfoEx.NumLock ? (Key)(uint)'3' : Key.PageDown;
  691. case ConsoleKey.NumPad4:
  692. return keyInfoEx.NumLock ? (Key)(uint)'4' : Key.CursorLeft;
  693. case ConsoleKey.NumPad5:
  694. return keyInfoEx.NumLock ? (Key)(uint)'5' : (Key)((uint)keyInfo.KeyChar);
  695. case ConsoleKey.NumPad6:
  696. return keyInfoEx.NumLock ? (Key)(uint)'6' : Key.CursorRight;
  697. case ConsoleKey.NumPad7:
  698. return keyInfoEx.NumLock ? (Key)(uint)'7' : Key.Home;
  699. case ConsoleKey.NumPad8:
  700. return keyInfoEx.NumLock ? (Key)(uint)'8' : Key.CursorUp;
  701. case ConsoleKey.NumPad9:
  702. return keyInfoEx.NumLock ? (Key)(uint)'9' : Key.PageUp;
  703. case ConsoleKey.Oem1:
  704. case ConsoleKey.Oem2:
  705. case ConsoleKey.Oem3:
  706. case ConsoleKey.Oem4:
  707. case ConsoleKey.Oem5:
  708. case ConsoleKey.Oem6:
  709. case ConsoleKey.Oem7:
  710. case ConsoleKey.Oem8:
  711. case ConsoleKey.Oem102:
  712. case ConsoleKey.OemPeriod:
  713. case ConsoleKey.OemComma:
  714. case ConsoleKey.OemPlus:
  715. case ConsoleKey.OemMinus:
  716. return (Key)((uint)keyInfo.KeyChar);
  717. }
  718. var key = keyInfo.Key;
  719. var alphaBase = ((keyInfo.Modifiers == ConsoleModifiers.Shift) ^ (keyInfoEx.CapsLock)) ? 'A' : 'a';
  720. if (key >= ConsoleKey.A && key <= ConsoleKey.Z) {
  721. var delta = key - ConsoleKey.A;
  722. if (keyInfo.Modifiers == ConsoleModifiers.Control)
  723. return (Key)((uint)Key.ControlA + delta);
  724. if (keyInfo.Modifiers == ConsoleModifiers.Alt)
  725. return (Key)(((uint)Key.AltMask) | ((uint)'A' + delta));
  726. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  727. if (keyInfo.KeyChar == 0)
  728. return (Key)(((uint)Key.AltMask) + ((uint)Key.ControlA + delta));
  729. else
  730. return (Key)((uint)keyInfo.KeyChar);
  731. }
  732. return (Key)((uint)alphaBase + delta);
  733. }
  734. if (key >= ConsoleKey.D0 && key <= ConsoleKey.D9) {
  735. var delta = key - ConsoleKey.D0;
  736. if (keyInfo.Modifiers == ConsoleModifiers.Alt)
  737. return (Key)(((uint)Key.AltMask) | ((uint)'0' + delta));
  738. return (Key)((uint)keyInfo.KeyChar);
  739. }
  740. if (key >= ConsoleKey.F1 && key <= ConsoleKey.F10) {
  741. var delta = key - ConsoleKey.F1;
  742. return (Key)((int)Key.F1 + delta);
  743. }
  744. return (Key)(0xffffffff);
  745. }
  746. public override void Init (Action terminalResized)
  747. {
  748. TerminalResized = terminalResized;
  749. Colors.Base = new ColorScheme ();
  750. Colors.Dialog = new ColorScheme ();
  751. Colors.Menu = new ColorScheme ();
  752. Colors.Error = new ColorScheme ();
  753. HLine = '\u2500';
  754. VLine = '\u2502';
  755. Stipple = '\u2592';
  756. Diamond = '\u25c6';
  757. ULCorner = '\u250C';
  758. LLCorner = '\u2514';
  759. URCorner = '\u2510';
  760. LRCorner = '\u2518';
  761. LeftTee = '\u251c';
  762. RightTee = '\u2524';
  763. TopTee = '\u22a4';
  764. BottomTee = '\u22a5';
  765. Colors.Base.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Blue);
  766. Colors.Base.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Cyan);
  767. Colors.Base.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Blue);
  768. Colors.Base.HotFocus = MakeColor (ConsoleColor.Yellow, ConsoleColor.Cyan);
  769. Colors.Menu.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Cyan);
  770. Colors.Menu.Focus = MakeColor (ConsoleColor.White, ConsoleColor.Black);
  771. Colors.Menu.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Cyan);
  772. Colors.Menu.HotFocus = MakeColor (ConsoleColor.Yellow, ConsoleColor.Black);
  773. Colors.Menu.Disabled = MakeColor (ConsoleColor.DarkGray, ConsoleColor.Cyan);
  774. Colors.Dialog.Normal = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
  775. Colors.Dialog.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Cyan);
  776. Colors.Dialog.HotNormal = MakeColor (ConsoleColor.Blue, ConsoleColor.Gray);
  777. Colors.Dialog.HotFocus = MakeColor (ConsoleColor.Blue, ConsoleColor.Cyan);
  778. Colors.Error.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Red);
  779. Colors.Error.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
  780. Colors.Error.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Red);
  781. Colors.Error.HotFocus = Colors.Error.HotNormal;
  782. Console.Clear ();
  783. }
  784. void ResizeScreen ()
  785. {
  786. OutputBuffer = new WindowsConsole.CharInfo [Rows * Cols];
  787. Clip = new Rect (0, 0, Cols, Rows);
  788. damageRegion = new WindowsConsole.SmallRect () {
  789. Top = 0,
  790. Left = 0,
  791. Bottom = (short)Rows,
  792. Right = (short)Cols
  793. };
  794. }
  795. void UpdateOffScreen ()
  796. {
  797. for (int row = 0; row < rows; row++)
  798. for (int col = 0; col < cols; col++) {
  799. int position = row * cols + col;
  800. OutputBuffer [position].Attributes = (ushort)Colors.TopLevel.Normal;
  801. OutputBuffer [position].Char.UnicodeChar = ' ';
  802. }
  803. }
  804. int ccol, crow;
  805. public override void Move (int col, int row)
  806. {
  807. ccol = col;
  808. crow = row;
  809. }
  810. public override void AddRune (Rune rune)
  811. {
  812. var position = crow * Cols + ccol;
  813. if (Clip.Contains (ccol, crow)) {
  814. OutputBuffer [position].Attributes = (ushort)currentAttribute;
  815. OutputBuffer [position].Char.UnicodeChar = (char)rune;
  816. WindowsConsole.SmallRect.Update (ref damageRegion, (short)ccol, (short)crow);
  817. }
  818. ccol++;
  819. var runeWidth = Rune.ColumnWidth (rune);
  820. if (runeWidth > 1) {
  821. for (int i = 1; i < runeWidth; i++) {
  822. AddStr (" ");
  823. }
  824. }
  825. if (ccol == Cols) {
  826. ccol = 0;
  827. if (crow + 1 < Rows)
  828. crow++;
  829. }
  830. if (sync)
  831. UpdateScreen ();
  832. }
  833. public override void AddStr (ustring str)
  834. {
  835. foreach (var rune in str)
  836. AddRune (rune);
  837. }
  838. int currentAttribute;
  839. CancellationTokenSource tokenSource = new CancellationTokenSource ();
  840. public override void SetAttribute (Attribute c)
  841. {
  842. currentAttribute = c.value;
  843. }
  844. Attribute MakeColor (ConsoleColor f, ConsoleColor b)
  845. {
  846. // Encode the colors into the int value.
  847. return new Attribute () {
  848. value = ((int)f | (int)b << 4),
  849. foreground = (Color)f,
  850. background = (Color)b
  851. };
  852. }
  853. public override Attribute MakeAttribute (Color fore, Color back)
  854. {
  855. return MakeColor ((ConsoleColor)fore, (ConsoleColor)back);
  856. }
  857. public override void Refresh ()
  858. {
  859. UpdateScreen ();
  860. #if false
  861. var bufferCoords = new WindowsConsole.Coord (){
  862. X = (short)Clip.Width,
  863. Y = (short)Clip.Height
  864. };
  865. var window = new WindowsConsole.SmallRect (){
  866. Top = 0,
  867. Left = 0,
  868. Right = (short)Clip.Right,
  869. Bottom = (short)Clip.Bottom
  870. };
  871. UpdateCursor();
  872. winConsole.WriteToConsole (OutputBuffer, bufferCoords, window);
  873. #endif
  874. }
  875. public override void UpdateScreen ()
  876. {
  877. if (damageRegion.Left == -1)
  878. return;
  879. var bufferCoords = new WindowsConsole.Coord () {
  880. X = (short)Clip.Width,
  881. Y = (short)Clip.Height
  882. };
  883. var window = new WindowsConsole.SmallRect () {
  884. Top = 0,
  885. Left = 0,
  886. Right = (short)Clip.Right,
  887. Bottom = (short)Clip.Bottom
  888. };
  889. UpdateCursor ();
  890. winConsole.WriteToConsole (OutputBuffer, bufferCoords, damageRegion);
  891. // System.Diagnostics.Debugger.Log(0, "debug", $"Region={damageRegion.Right - damageRegion.Left},{damageRegion.Bottom - damageRegion.Top}\n");
  892. WindowsConsole.SmallRect.MakeEmpty (ref damageRegion);
  893. }
  894. public override void UpdateCursor ()
  895. {
  896. var position = new WindowsConsole.Coord () {
  897. X = (short)ccol,
  898. Y = (short)crow
  899. };
  900. winConsole.SetCursorPosition (position);
  901. }
  902. public override void End ()
  903. {
  904. winConsole.Cleanup ();
  905. }
  906. #region Unused
  907. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  908. {
  909. }
  910. public override void SetColors (short foregroundColorId, short backgroundColorId)
  911. {
  912. }
  913. public override void Suspend ()
  914. {
  915. }
  916. public override void StartReportingMouseMoves ()
  917. {
  918. }
  919. public override void StopReportingMouseMoves ()
  920. {
  921. }
  922. public override void UncookMouse ()
  923. {
  924. }
  925. public override void CookMouse ()
  926. {
  927. }
  928. #endregion
  929. }
  930. }