WindowsDriver.cs 32 KB

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