WindowsDriver.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  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. WindowsConsole.CharInfo [] OutputBuffer;
  362. int cols, rows;
  363. WindowsConsole winConsole;
  364. WindowsConsole.SmallRect damageRegion;
  365. public override int Cols => cols;
  366. public override int Rows => rows;
  367. public WindowsDriver ()
  368. {
  369. winConsole = new WindowsConsole ();
  370. cols = Console.WindowWidth;
  371. rows = Console.WindowHeight - 1;
  372. WindowsConsole.SmallRect.MakeEmpty (ref damageRegion);
  373. ResizeScreen ();
  374. UpdateOffScreen ();
  375. Task.Run ((Action)WindowsInputHandler);
  376. }
  377. [StructLayout(LayoutKind.Sequential)]
  378. public struct ConsoleKeyInfoEx {
  379. public ConsoleKeyInfo consoleKeyInfo;
  380. public bool CapsLock;
  381. public bool NumLock;
  382. public ConsoleKeyInfoEx(ConsoleKeyInfo consoleKeyInfo, bool capslock, bool numlock)
  383. {
  384. this.consoleKeyInfo = consoleKeyInfo;
  385. CapsLock = capslock;
  386. NumLock = numlock;
  387. }
  388. }
  389. // The records that we keep fetching
  390. WindowsConsole.InputRecord [] result, records = new WindowsConsole.InputRecord [1];
  391. void WindowsInputHandler ()
  392. {
  393. while (true) {
  394. waitForProbe.Wait();
  395. waitForProbe.Reset();
  396. uint numberEventsRead = 0;
  397. WindowsConsole.ReadConsoleInput (winConsole.InputHandle, records, 1, out numberEventsRead);
  398. if (numberEventsRead == 0)
  399. result = null;
  400. else
  401. result = records;
  402. eventReady.Set();
  403. }
  404. }
  405. void IMainLoopDriver.Setup (MainLoop mainLoop)
  406. {
  407. this.mainLoop = mainLoop;
  408. }
  409. void IMainLoopDriver.Wakeup ()
  410. {
  411. tokenSource.Cancel();
  412. }
  413. bool IMainLoopDriver.EventsPending (bool wait)
  414. {
  415. long now = DateTime.UtcNow.Ticks;
  416. int waitTimeout;
  417. if (mainLoop.timeouts.Count > 0) {
  418. waitTimeout = (int)((mainLoop.timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  419. if (waitTimeout < 0)
  420. return true;
  421. } else
  422. waitTimeout = -1;
  423. if (!wait)
  424. waitTimeout = 0;
  425. result = null;
  426. waitForProbe.Set();
  427. try {
  428. eventReady.Wait(waitTimeout, tokenSource.Token);
  429. } catch (OperationCanceledException) {
  430. return true;
  431. } finally {
  432. eventReady.Reset();
  433. }
  434. Debug.WriteLine("Events ready");
  435. if (!tokenSource.IsCancellationRequested)
  436. return result != null;
  437. tokenSource.Dispose();
  438. tokenSource = new CancellationTokenSource();
  439. return true;
  440. }
  441. Action<KeyEvent> keyHandler;
  442. Action<MouseEvent> mouseHandler;
  443. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<MouseEvent> mouseHandler)
  444. {
  445. this.keyHandler = keyHandler;
  446. this.mouseHandler = mouseHandler;
  447. }
  448. void IMainLoopDriver.MainIteration ()
  449. {
  450. if (result == null)
  451. return;
  452. var inputEvent = result [0];
  453. switch (inputEvent.EventType) {
  454. case WindowsConsole.EventType.Key:
  455. if (inputEvent.KeyEvent.bKeyDown == false)
  456. return;
  457. var map = MapKey (ToConsoleKeyInfoEx (inputEvent.KeyEvent));
  458. if (inputEvent.KeyEvent.UnicodeChar == 0 && map == (Key)0xffffffff)
  459. return;
  460. keyHandler (new KeyEvent (map));
  461. break;
  462. case WindowsConsole.EventType.Mouse:
  463. mouseHandler (ToDriverMouse (inputEvent.MouseEvent));
  464. break;
  465. case WindowsConsole.EventType.WindowBufferSize:
  466. cols = inputEvent.WindowBufferSizeEvent.size.X;
  467. rows = inputEvent.WindowBufferSizeEvent.size.Y - 1;
  468. ResizeScreen ();
  469. UpdateOffScreen ();
  470. TerminalResized?.Invoke();
  471. break;
  472. }
  473. result = null;
  474. }
  475. private WindowsConsole.ButtonState? LastMouseButtonPressed = null;
  476. private MouseEvent ToDriverMouse (WindowsConsole.MouseEventRecord mouseEvent)
  477. {
  478. MouseFlags mouseFlag = MouseFlags.AllEvents;
  479. // The ButtonState member of the MouseEvent structure has bit corresponding to each mouse button.
  480. // This will tell when a mouse button is pressed. When the button is released this event will
  481. // be fired with it's bit set to 0. So when the button is up ButtonState will be 0.
  482. // To map to the correct driver events we save the last pressed mouse button so we can
  483. // map to the correct clicked event.
  484. if (LastMouseButtonPressed != null && mouseEvent.ButtonState != 0) {
  485. LastMouseButtonPressed = null;
  486. }
  487. if (mouseEvent.EventFlags == 0 && LastMouseButtonPressed == null) {
  488. switch (mouseEvent.ButtonState) {
  489. case WindowsConsole.ButtonState.Button1Pressed:
  490. mouseFlag = MouseFlags.Button1Pressed;
  491. break;
  492. case WindowsConsole.ButtonState.Button2Pressed:
  493. mouseFlag = MouseFlags.Button2Pressed;
  494. break;
  495. case WindowsConsole.ButtonState.Button3Pressed:
  496. mouseFlag = MouseFlags.Button3Pressed;
  497. break;
  498. }
  499. LastMouseButtonPressed = mouseEvent.ButtonState;
  500. } else if (mouseEvent.EventFlags == 0 && LastMouseButtonPressed != null) {
  501. switch (LastMouseButtonPressed) {
  502. case WindowsConsole.ButtonState.Button1Pressed:
  503. mouseFlag = MouseFlags.Button1Clicked;
  504. break;
  505. case WindowsConsole.ButtonState.Button2Pressed:
  506. mouseFlag = MouseFlags.Button2Clicked;
  507. break;
  508. case WindowsConsole.ButtonState.Button3Pressed:
  509. mouseFlag = MouseFlags.Button3Clicked;
  510. break;
  511. }
  512. LastMouseButtonPressed = null;
  513. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  514. mouseFlag = MouseFlags.ReportMousePosition;
  515. }
  516. return new MouseEvent () {
  517. X = mouseEvent.MousePosition.X,
  518. Y = mouseEvent.MousePosition.Y,
  519. Flags = mouseFlag
  520. };
  521. }
  522. public ConsoleKeyInfoEx ToConsoleKeyInfoEx (WindowsConsole.KeyEventRecord keyEvent)
  523. {
  524. var state = keyEvent.dwControlKeyState;
  525. bool shift = (state & WindowsConsole.ControlKeyState.ShiftPressed) != 0;
  526. bool alt = (state & (WindowsConsole.ControlKeyState.LeftAltPressed | WindowsConsole.ControlKeyState.RightAltPressed)) != 0;
  527. bool control = (state & (WindowsConsole.ControlKeyState.LeftControlPressed | WindowsConsole.ControlKeyState.RightControlPressed)) != 0;
  528. bool capslock = (state & (WindowsConsole.ControlKeyState.CapslockOn)) != 0;
  529. bool numlock = (state & (WindowsConsole.ControlKeyState.NumlockOn)) != 0;
  530. var ConsoleKeyInfo = new ConsoleKeyInfo(keyEvent.UnicodeChar, (ConsoleKey)keyEvent.wVirtualKeyCode, shift, alt, control);
  531. return new ConsoleKeyInfoEx(ConsoleKeyInfo, capslock, numlock);
  532. }
  533. public Key MapKey (ConsoleKeyInfoEx keyInfoEx)
  534. {
  535. var keyInfo = keyInfoEx.consoleKeyInfo;
  536. switch (keyInfo.Key) {
  537. case ConsoleKey.Escape:
  538. return Key.Esc;
  539. case ConsoleKey.Tab:
  540. return keyInfo.Modifiers == ConsoleModifiers.Shift ? Key.BackTab : Key.Tab;
  541. case ConsoleKey.Home:
  542. return Key.Home;
  543. case ConsoleKey.End:
  544. return Key.End;
  545. case ConsoleKey.LeftArrow:
  546. return Key.CursorLeft;
  547. case ConsoleKey.RightArrow:
  548. return Key.CursorRight;
  549. case ConsoleKey.UpArrow:
  550. return Key.CursorUp;
  551. case ConsoleKey.DownArrow:
  552. return Key.CursorDown;
  553. case ConsoleKey.PageUp:
  554. return Key.PageUp;
  555. case ConsoleKey.PageDown:
  556. return Key.PageDown;
  557. case ConsoleKey.Enter:
  558. return Key.Enter;
  559. case ConsoleKey.Spacebar:
  560. return Key.Space;
  561. case ConsoleKey.Backspace:
  562. return Key.Backspace;
  563. case ConsoleKey.Delete:
  564. return Key.DeleteChar;
  565. case ConsoleKey.NumPad0:
  566. return keyInfoEx.NumLock ? (Key)(uint)'0' : Key.InsertChar;
  567. case ConsoleKey.NumPad1:
  568. return keyInfoEx.NumLock ? (Key)(uint)'1' : Key.End;
  569. case ConsoleKey.NumPad2:
  570. return keyInfoEx.NumLock ? (Key)(uint)'2' : Key.CursorDown;
  571. case ConsoleKey.NumPad3:
  572. return keyInfoEx.NumLock ? (Key)(uint)'3' : Key.PageDown;
  573. case ConsoleKey.NumPad4:
  574. return keyInfoEx.NumLock ? (Key)(uint)'4' : Key.CursorLeft;
  575. case ConsoleKey.NumPad5:
  576. return keyInfoEx.NumLock ? (Key)(uint)'5' : (Key)((uint)keyInfo.KeyChar);
  577. case ConsoleKey.NumPad6:
  578. return keyInfoEx.NumLock ? (Key)(uint)'6' : Key.CursorRight;
  579. case ConsoleKey.NumPad7:
  580. return keyInfoEx.NumLock ? (Key)(uint)'7' : Key.Home;
  581. case ConsoleKey.NumPad8:
  582. return keyInfoEx.NumLock ? (Key)(uint)'8' : Key.CursorUp;
  583. case ConsoleKey.NumPad9:
  584. return keyInfoEx.NumLock ? (Key)(uint)'9' : Key.PageUp;
  585. case ConsoleKey.Oem1:
  586. case ConsoleKey.Oem2:
  587. case ConsoleKey.Oem3:
  588. case ConsoleKey.Oem4:
  589. case ConsoleKey.Oem5:
  590. case ConsoleKey.Oem6:
  591. case ConsoleKey.Oem7:
  592. case ConsoleKey.Oem8:
  593. case ConsoleKey.Oem102:
  594. case ConsoleKey.OemPeriod:
  595. case ConsoleKey.OemComma:
  596. case ConsoleKey.OemPlus:
  597. case ConsoleKey.OemMinus:
  598. return (Key)((uint)keyInfo.KeyChar);
  599. }
  600. var key = keyInfo.Key;
  601. var alphaBase = ((keyInfo.Modifiers == ConsoleModifiers.Shift) ^ (keyInfoEx.CapsLock)) ? 'A' : 'a';
  602. if (key >= ConsoleKey.A && key <= ConsoleKey.Z) {
  603. var delta = key - ConsoleKey.A;
  604. if (keyInfo.Modifiers == ConsoleModifiers.Control)
  605. return (Key)((uint)Key.ControlA + delta);
  606. if (keyInfo.Modifiers == ConsoleModifiers.Alt)
  607. return (Key)(((uint)Key.AltMask) | ((uint)'A' + delta));
  608. return (Key)((uint)alphaBase + delta);
  609. }
  610. if (key >= ConsoleKey.D0 && key <= ConsoleKey.D9) {
  611. var delta = key - ConsoleKey.D0;
  612. if (keyInfo.Modifiers == ConsoleModifiers.Alt)
  613. return (Key)(((uint)Key.AltMask) | ((uint)'0' + delta));
  614. return (Key)((uint)keyInfo.KeyChar);
  615. }
  616. if (key >= ConsoleKey.F1 && key <= ConsoleKey.F10) {
  617. var delta = key - ConsoleKey.F1;
  618. return (Key)((int)Key.F1 + delta);
  619. }
  620. return (Key)(0xffffffff);
  621. }
  622. public override void Init (Action terminalResized)
  623. {
  624. TerminalResized = terminalResized;
  625. Colors.Base = new ColorScheme ();
  626. Colors.Dialog = new ColorScheme ();
  627. Colors.Menu = new ColorScheme ();
  628. Colors.Error = new ColorScheme ();
  629. HLine = '\u2500';
  630. VLine = '\u2502';
  631. Stipple = '\u2592';
  632. Diamond = '\u25c6';
  633. ULCorner = '\u250C';
  634. LLCorner = '\u2514';
  635. URCorner = '\u2510';
  636. LRCorner = '\u2518';
  637. LeftTee = '\u251c';
  638. RightTee = '\u2524';
  639. TopTee = '\u22a4';
  640. BottomTee = '\u22a5';
  641. Colors.Base.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Blue);
  642. Colors.Base.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Cyan);
  643. Colors.Base.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Blue);
  644. Colors.Base.HotFocus = MakeColor (ConsoleColor.Yellow, ConsoleColor.Cyan);
  645. Colors.Menu.HotFocus = MakeColor (ConsoleColor.Yellow, ConsoleColor.Black);
  646. Colors.Menu.Focus = MakeColor (ConsoleColor.White, ConsoleColor.Black);
  647. Colors.Menu.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Cyan);
  648. Colors.Menu.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Cyan);
  649. Colors.Dialog.Normal = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
  650. Colors.Dialog.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Cyan);
  651. Colors.Dialog.HotNormal = MakeColor (ConsoleColor.Blue, ConsoleColor.Gray);
  652. Colors.Dialog.HotFocus = MakeColor (ConsoleColor.Blue, ConsoleColor.Cyan);
  653. Colors.Error.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Red);
  654. Colors.Error.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
  655. Colors.Error.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Red);
  656. Colors.Error.HotFocus = Colors.Error.HotNormal;
  657. Console.Clear ();
  658. }
  659. void ResizeScreen ()
  660. {
  661. OutputBuffer = new WindowsConsole.CharInfo [Rows * Cols];
  662. Clip = new Rect (0, 0, Cols, Rows);
  663. damageRegion = new WindowsConsole.SmallRect () {
  664. Top = 0,
  665. Left = 0,
  666. Bottom = (short)Rows,
  667. Right = (short)Cols
  668. };
  669. }
  670. void UpdateOffScreen ()
  671. {
  672. for (int row = 0; row < rows; row++)
  673. for (int col = 0; col < cols; col++) {
  674. int position = row * cols + col;
  675. OutputBuffer [position].Attributes = (ushort)MakeColor (ConsoleColor.White, ConsoleColor.Blue);
  676. OutputBuffer [position].Char.UnicodeChar = ' ';
  677. }
  678. }
  679. int ccol, crow;
  680. public override void Move (int col, int row)
  681. {
  682. ccol = col;
  683. crow = row;
  684. }
  685. public override void AddRune (Rune rune)
  686. {
  687. var position = crow * Cols + ccol;
  688. if (Clip.Contains (ccol, crow)) {
  689. OutputBuffer [position].Attributes = (ushort)currentAttribute;
  690. OutputBuffer [position].Char.UnicodeChar = (char)rune;
  691. WindowsConsole.SmallRect.Update (ref damageRegion, (short)ccol, (short)crow);
  692. }
  693. ccol++;
  694. if (ccol == Cols) {
  695. ccol = 0;
  696. if (crow + 1 < Rows)
  697. crow++;
  698. }
  699. if (sync)
  700. UpdateScreen ();
  701. }
  702. public override void AddStr (ustring str)
  703. {
  704. foreach (var rune in str)
  705. AddRune (rune);
  706. }
  707. int currentAttribute;
  708. CancellationTokenSource tokenSource = new CancellationTokenSource();
  709. public override void SetAttribute (Attribute c)
  710. {
  711. currentAttribute = c.value;
  712. }
  713. private Attribute MakeColor (ConsoleColor f, ConsoleColor b)
  714. {
  715. // Encode the colors into the int value.
  716. return new Attribute () {
  717. value = ((int)f | (int)b << 4)
  718. };
  719. }
  720. public override Attribute MakeAttribute (Color fore, Color back)
  721. {
  722. return MakeColor ((ConsoleColor)fore, (ConsoleColor)back);
  723. }
  724. public override void Refresh ()
  725. {
  726. UpdateScreen ();
  727. #if false
  728. var bufferCoords = new WindowsConsole.Coord (){
  729. X = (short)Clip.Width,
  730. Y = (short)Clip.Height
  731. };
  732. var window = new WindowsConsole.SmallRect (){
  733. Top = 0,
  734. Left = 0,
  735. Right = (short)Clip.Right,
  736. Bottom = (short)Clip.Bottom
  737. };
  738. UpdateCursor();
  739. winConsole.WriteToConsole (OutputBuffer, bufferCoords, window);
  740. #endif
  741. }
  742. public override void UpdateScreen ()
  743. {
  744. if (damageRegion.Left == -1)
  745. return;
  746. var bufferCoords = new WindowsConsole.Coord (){
  747. X = (short)Clip.Width,
  748. Y = (short)Clip.Height
  749. };
  750. var window = new WindowsConsole.SmallRect (){
  751. Top = 0,
  752. Left = 0,
  753. Right = (short)Clip.Right,
  754. Bottom = (short)Clip.Bottom
  755. };
  756. UpdateCursor();
  757. winConsole.WriteToConsole (OutputBuffer, bufferCoords, damageRegion);
  758. // System.Diagnostics.Debugger.Log(0, "debug", $"Region={damageRegion.Right - damageRegion.Left},{damageRegion.Bottom - damageRegion.Top}\n");
  759. WindowsConsole.SmallRect.MakeEmpty (ref damageRegion);
  760. }
  761. public override void UpdateCursor()
  762. {
  763. var position = new WindowsConsole.Coord(){
  764. X = (short)ccol,
  765. Y = (short)crow
  766. };
  767. winConsole.SetCursorPosition(position);
  768. }
  769. public override void End ()
  770. {
  771. winConsole.Cleanup();
  772. }
  773. #region Unused
  774. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  775. {
  776. }
  777. public override void SetColors (short foregroundColorId, short backgroundColorId)
  778. {
  779. }
  780. public override void Suspend ()
  781. {
  782. }
  783. public override void StartReportingMouseMoves ()
  784. {
  785. }
  786. public override void StopReportingMouseMoves ()
  787. {
  788. }
  789. public override void UncookMouse ()
  790. {
  791. }
  792. public override void CookMouse ()
  793. {
  794. }
  795. #endregion
  796. }
  797. }