WindowsDriver.cs 26 KB

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