WindowsDriver.cs 26 KB

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