WindowsDriver.cs 26 KB

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