WindowsDriver.cs 24 KB

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