WindowsDriver.cs 31 KB

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