WindowsDriver.cs.orig 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  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. {
  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 = 0, Y = 0 }, ref window);
  77. }
  78. public bool SetCursorPosition(Coord position)
  79. {
  80. return SetConsoleCursorPosition (ScreenBuffer, position);
  81. }
  82. public void Cleanup ()
  83. {
  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. {
  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 {
  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. {
  234. FileShareRead = 1,
  235. FileShareWrite = 2,
  236. }
  237. [Flags]
  238. enum DesiredAccess : uint
  239. {
  240. GenericRead = 2147483648,
  241. GenericWrite = 1073741824,
  242. }
  243. [StructLayout(LayoutKind.Sequential)]
  244. public struct ConsoleScreenBufferInfo
  245. {
  246. public Coord dwSize;
  247. public Coord dwCursorPosition;
  248. public ushort wAttributes;
  249. public SmallRect srWindow;
  250. public Coord dwMaximumWindowSize;
  251. }
  252. [StructLayout(LayoutKind.Sequential)]
  253. public struct Coord
  254. {
  255. public short X;
  256. public short Y;
  257. public Coord(short X, short Y)
  258. {
  259. this.X = X;
  260. this.Y = Y;
  261. }
  262. };
  263. [StructLayout(LayoutKind.Explicit, CharSet=CharSet.Unicode)]
  264. public struct CharUnion
  265. {
  266. [FieldOffset(0)] public char UnicodeChar;
  267. [FieldOffset(0)] public byte AsciiChar;
  268. }
  269. [StructLayout(LayoutKind.Explicit, CharSet=CharSet.Unicode)]
  270. public struct CharInfo
  271. {
  272. [FieldOffset(0)] public CharUnion Char;
  273. [FieldOffset(2)] public ushort Attributes;
  274. }
  275. [StructLayout(LayoutKind.Sequential)]
  276. public struct SmallRect
  277. {
  278. public short Left;
  279. public short Top;
  280. public short Right;
  281. public short Bottom;
  282. }
  283. [DllImport ("kernel32.dll", SetLastError = true)]
  284. static extern IntPtr GetStdHandle (int nStdHandle);
  285. [DllImport ("kernel32.dll", EntryPoint = "ReadConsoleInputW", CharSet = CharSet.Unicode)]
  286. public static extern bool ReadConsoleInput (
  287. IntPtr hConsoleInput,
  288. [Out] InputRecord [] lpBuffer,
  289. uint nLength,
  290. out uint lpNumberOfEventsRead);
  291. [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
  292. static extern bool ReadConsoleOutput(
  293. IntPtr hConsoleOutput,
  294. [Out] CharInfo[] lpBuffer,
  295. Coord dwBufferSize,
  296. Coord dwBufferCoord,
  297. ref SmallRect lpReadRegion
  298. );
  299. [DllImport("kernel32.dll", EntryPoint="WriteConsoleOutput", SetLastError=true, CharSet=CharSet.Unicode)]
  300. static extern bool WriteConsoleOutput(
  301. IntPtr hConsoleOutput,
  302. CharInfo[] lpBuffer,
  303. Coord dwBufferSize,
  304. Coord dwBufferCoord,
  305. ref SmallRect lpWriteRegion
  306. );
  307. [DllImport ("kernel32.dll")]
  308. static extern bool SetConsoleCursorPosition(IntPtr hConsoleOutput, Coord dwCursorPosition);
  309. [DllImport ("kernel32.dll")]
  310. static extern bool GetConsoleMode (IntPtr hConsoleHandle, out uint lpMode);
  311. [DllImport ("kernel32.dll")]
  312. static extern bool SetConsoleMode (IntPtr hConsoleHandle, uint dwMode);
  313. [DllImport("kernel32.dll", SetLastError = true)]
  314. static extern IntPtr CreateConsoleScreenBuffer(
  315. DesiredAccess dwDesiredAccess,
  316. ShareMode dwShareMode,
  317. IntPtr secutiryAttributes,
  318. UInt32 flags,
  319. IntPtr screenBufferData
  320. );
  321. internal static IntPtr INVALID_HANDLE_VALUE = new IntPtr (-1);
  322. [DllImport("kernel32.dll", SetLastError = true)]
  323. static extern bool SetConsoleActiveScreenBuffer(IntPtr Handle);
  324. [DllImport ("kernel32.dll", SetLastError = true)]
  325. static extern bool GetNumberOfConsoleInputEvents (IntPtr handle, out uint lpcNumberOfEvents);
  326. public uint InputEventCount {
  327. get {
  328. uint v;
  329. GetNumberOfConsoleInputEvents (InputHandle, out v);
  330. return v;
  331. }
  332. }
  333. }
  334. internal class WindowsDriver : ConsoleDriver, Mono.Terminal.IMainLoopDriver {
  335. static bool sync;
  336. AutoResetEvent eventReady = new AutoResetEvent (false);
  337. AutoResetEvent waitForProbe = new AutoResetEvent (false);
  338. MainLoop mainLoop;
  339. Action TerminalResized;
  340. WindowsConsole.CharInfo[] OutputBuffer;
  341. int cols, rows;
  342. WindowsConsole winConsole;
  343. public override int Cols => cols;
  344. public override int Rows => rows;
  345. public WindowsDriver ()
  346. {
  347. winConsole = new WindowsConsole();
  348. cols = Console.WindowWidth;
  349. rows = Console.WindowHeight - 1;
  350. ResizeScreen ();
  351. UpdateOffScreen ();
  352. Task.Run ((Action)WindowsInputHandler);
  353. }
  354. // The records that we keep fetching
  355. WindowsConsole.InputRecord [] result, records = new WindowsConsole.InputRecord [1];
  356. void WindowsInputHandler ()
  357. {
  358. while (true) {
  359. waitForProbe.WaitOne ();
  360. uint numberEventsRead = 0;
  361. WindowsConsole.ReadConsoleInput (winConsole.InputHandle, records, 1, out numberEventsRead);
  362. if (numberEventsRead == 0)
  363. result = null;
  364. else
  365. result = records;
  366. eventReady.Set ();
  367. }
  368. }
  369. void IMainLoopDriver.Setup (MainLoop mainLoop)
  370. {
  371. this.mainLoop = mainLoop;
  372. }
  373. void IMainLoopDriver.Wakeup ()
  374. {
  375. }
  376. bool IMainLoopDriver.EventsPending (bool wait)
  377. {
  378. long now = DateTime.UtcNow.Ticks;
  379. int waitTimeout;
  380. if (mainLoop.timeouts.Count > 0) {
  381. waitTimeout = (int)((mainLoop.timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  382. if (waitTimeout < 0)
  383. return true;
  384. } else
  385. waitTimeout = -1;
  386. if (!wait)
  387. waitTimeout = 0;
  388. result = null;
  389. waitForProbe.Set ();
  390. eventReady.WaitOne (waitTimeout);
  391. return result != null;
  392. }
  393. Action<KeyEvent> keyHandler;
  394. Action<MouseEvent> mouseHandler;
  395. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<MouseEvent> mouseHandler)
  396. {
  397. this.keyHandler = keyHandler;
  398. this.mouseHandler = mouseHandler;
  399. }
  400. void IMainLoopDriver.MainIteration ()
  401. {
  402. if (result == null)
  403. return;
  404. var inputEvent = result [0];
  405. switch (inputEvent.EventType) {
  406. case WindowsConsole.EventType.Key:
  407. if (inputEvent.KeyEvent.bKeyDown == false)
  408. return;
  409. var map = MapKey (ToConsoleKeyInfo (inputEvent.KeyEvent));
  410. if (map == (Key)0xffffffff)
  411. return;
  412. keyHandler (new KeyEvent (map));
  413. break;
  414. case WindowsConsole.EventType.Mouse:
  415. mouseHandler (ToDriverMouse (inputEvent.MouseEvent));
  416. break;
  417. case WindowsConsole.EventType.WindowBufferSize:
  418. cols = inputEvent.WindowBufferSizeEvent.size.X;
  419. rows = inputEvent.WindowBufferSizeEvent.size.Y - 1;
  420. ResizeScreen ();
  421. UpdateOffScreen ();
  422. TerminalResized ();
  423. break;
  424. }
  425. result = null;
  426. }
  427. private WindowsConsole.ButtonState? LastMouseButtonPressed = null;
  428. private MouseEvent ToDriverMouse(WindowsConsole.MouseEventRecord mouseEvent)
  429. {
  430. MouseFlags mouseFlag = MouseFlags.AllEvents;
  431. // The ButtonState member of the MouseEvent structure has bit corresponding to each mouse button.
  432. // This will tell when a mouse button is pressed. When the button is released this event will
  433. // be fired with it's bit set to 0. So when the button is up ButtonState will be 0.
  434. // To map to the correct driver events we save the last pressed mouse button so we can
  435. // map to the correct clicked event.
  436. if (LastMouseButtonPressed != null && mouseEvent.ButtonState != 0)
  437. {
  438. LastMouseButtonPressed = null;
  439. }
  440. if (mouseEvent.EventFlags == 0 && LastMouseButtonPressed == null){
  441. switch (mouseEvent.ButtonState){
  442. case WindowsConsole.ButtonState.Button1Pressed:
  443. mouseFlag = MouseFlags.Button1Pressed;
  444. break;
  445. case WindowsConsole.ButtonState.Button2Pressed:
  446. mouseFlag = MouseFlags.Button2Pressed;
  447. break;
  448. case WindowsConsole.ButtonState.Button3Pressed:
  449. mouseFlag = MouseFlags.Button3Pressed;
  450. break;
  451. }
  452. LastMouseButtonPressed = mouseEvent.ButtonState;
  453. } else if (mouseEvent.EventFlags == 0 && LastMouseButtonPressed != null){
  454. switch (LastMouseButtonPressed){
  455. case WindowsConsole.ButtonState.Button1Pressed:
  456. mouseFlag = MouseFlags.Button1Clicked;
  457. break;
  458. case WindowsConsole.ButtonState.Button2Pressed:
  459. mouseFlag = MouseFlags.Button2Clicked;
  460. break;
  461. case WindowsConsole.ButtonState.Button3Pressed:
  462. mouseFlag = MouseFlags.Button3Clicked;
  463. break;
  464. }
  465. LastMouseButtonPressed = null;
  466. } else if(mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved){
  467. mouseFlag = MouseFlags.ReportMousePosition;
  468. }
  469. return new MouseEvent () {
  470. X = mouseEvent.MousePosition.X,
  471. Y = mouseEvent.MousePosition.Y,
  472. Flags = mouseFlag
  473. };
  474. }
  475. private ConsoleKeyInfo ToConsoleKeyInfo (WindowsConsole.KeyEventRecord keyEvent)
  476. {
  477. var state = keyEvent.dwControlKeyState;
  478. bool shift = (state & WindowsConsole.ControlKeyState.ShiftPressed) != 0;
  479. bool alt = (state & (WindowsConsole.ControlKeyState.LeftAltPressed | WindowsConsole.ControlKeyState.RightAltPressed)) != 0;
  480. bool control = (state & (WindowsConsole.ControlKeyState.LeftControlPressed | WindowsConsole.ControlKeyState.RightControlPressed)) != 0;
  481. return new ConsoleKeyInfo(keyEvent.UnicodeChar, (ConsoleKey)keyEvent.wVirtualKeyCode, shift, alt, control);
  482. }
  483. public Key MapKey (ConsoleKeyInfo keyInfo)
  484. {
  485. switch (keyInfo.Key) {
  486. case ConsoleKey.Escape:
  487. return Key.Esc;
  488. case ConsoleKey.Tab:
  489. return Key.Tab;
  490. case ConsoleKey.Home:
  491. return Key.Home;
  492. case ConsoleKey.End:
  493. return Key.End;
  494. case ConsoleKey.LeftArrow:
  495. return Key.CursorLeft;
  496. case ConsoleKey.RightArrow:
  497. return Key.CursorRight;
  498. case ConsoleKey.UpArrow:
  499. return Key.CursorUp;
  500. case ConsoleKey.DownArrow:
  501. return Key.CursorDown;
  502. case ConsoleKey.PageUp:
  503. return Key.PageUp;
  504. case ConsoleKey.PageDown:
  505. return Key.PageDown;
  506. case ConsoleKey.Enter:
  507. return Key.Enter;
  508. case ConsoleKey.Spacebar:
  509. return Key.Space;
  510. case ConsoleKey.Backspace:
  511. return Key.Backspace;
  512. case ConsoleKey.Delete:
  513. return Key.DeleteChar;
  514. case ConsoleKey.Oem1:
  515. case ConsoleKey.Oem2:
  516. case ConsoleKey.Oem3:
  517. case ConsoleKey.Oem4:
  518. case ConsoleKey.Oem5:
  519. case ConsoleKey.Oem6:
  520. case ConsoleKey.Oem7:
  521. case ConsoleKey.Oem8:
  522. case ConsoleKey.Oem102:
  523. case ConsoleKey.OemPeriod:
  524. case ConsoleKey.OemComma:
  525. case ConsoleKey.OemPlus:
  526. case ConsoleKey.OemMinus:
  527. return (Key)((uint)keyInfo.KeyChar);
  528. }
  529. var key = keyInfo.Key;
  530. if (key >= ConsoleKey.A && key <= ConsoleKey.Z) {
  531. var delta = key - ConsoleKey.A;
  532. if (keyInfo.Modifiers == ConsoleModifiers.Control)
  533. return (Key)((uint)Key.ControlA + delta);
  534. if (keyInfo.Modifiers == ConsoleModifiers.Alt)
  535. return (Key)(((uint)Key.AltMask) | ((uint)'A' + delta));
  536. if (keyInfo.Modifiers == ConsoleModifiers.Shift)
  537. return (Key)((uint)'A' + delta);
  538. else
  539. return (Key)((uint)'a' + delta);
  540. }
  541. if (key >= ConsoleKey.D0 && key <= ConsoleKey.D9) {
  542. var delta = key - ConsoleKey.D0;
  543. if (keyInfo.Modifiers == ConsoleModifiers.Alt)
  544. return (Key)(((uint)Key.AltMask) | ((uint)'0' + delta));
  545. if (keyInfo.Modifiers == ConsoleModifiers.Shift)
  546. return (Key)((uint)keyInfo.KeyChar);
  547. return (Key)((uint)'0' + delta);
  548. }
  549. if (key >= ConsoleKey.F1 && key <= ConsoleKey.F10) {
  550. var delta = key - ConsoleKey.F1;
  551. return (Key)((int)Key.F1 + delta);
  552. }
  553. return (Key)(0xffffffff);
  554. }
  555. public override void Init (Action terminalResized)
  556. {
  557. TerminalResized = terminalResized;
  558. Colors.Base = new ColorScheme ();
  559. Colors.Dialog = new ColorScheme ();
  560. Colors.Menu = new ColorScheme ();
  561. Colors.Error = new ColorScheme ();
  562. HLine = '\u2500';
  563. VLine = '\u2502';
  564. Stipple = '\u2592';
  565. Diamond = '\u25c6';
  566. ULCorner = '\u250C';
  567. LLCorner = '\u2514';
  568. URCorner = '\u2510';
  569. LRCorner = '\u2518';
  570. LeftTee = '\u251c';
  571. RightTee = '\u2524';
  572. TopTee = '\u22a4';
  573. BottomTee = '\u22a5';
  574. Colors.Base.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Blue);
  575. Colors.Base.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Cyan);
  576. Colors.Base.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Blue);
  577. Colors.Base.HotFocus = MakeColor (ConsoleColor.Yellow, ConsoleColor.Cyan);
  578. Colors.Menu.HotFocus = MakeColor (ConsoleColor.Yellow, ConsoleColor.Black);
  579. Colors.Menu.Focus = MakeColor (ConsoleColor.White, ConsoleColor.Black);
  580. Colors.Menu.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Cyan);
  581. Colors.Menu.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Cyan);
  582. Colors.Dialog.Normal = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
  583. Colors.Dialog.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Cyan);
  584. Colors.Dialog.HotNormal = MakeColor (ConsoleColor.Blue, ConsoleColor.Gray);
  585. Colors.Dialog.HotFocus = MakeColor (ConsoleColor.Blue, ConsoleColor.Cyan);
  586. Colors.Error.Normal = MakeColor (ConsoleColor.White, ConsoleColor.Red);
  587. Colors.Error.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
  588. Colors.Error.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.Red);
  589. Colors.Error.HotFocus = Colors.Error.HotNormal;
  590. Console.Clear ();
  591. }
  592. void ResizeScreen ()
  593. {
  594. OutputBuffer = new WindowsConsole.CharInfo[Rows * Cols];
  595. Clip = new Rect (0, 0, Cols, Rows);
  596. }
  597. void UpdateOffScreen ()
  598. {
  599. for (int row = 0; row < rows; row++)
  600. for (int col = 0; col < cols; col++){
  601. int position = row * cols + col;
  602. OutputBuffer[position].Attributes = (ushort)MakeColor(ConsoleColor.White, ConsoleColor.Blue);
  603. OutputBuffer[position].Char.UnicodeChar = ' ';
  604. }
  605. }
  606. int ccol, crow;
  607. public override void Move (int col, int row)
  608. {
  609. ccol = col;
  610. crow = row;
  611. }
  612. public override void AddRune (Rune rune)
  613. {
  614. var position = crow * Cols + ccol;
  615. if (Clip.Contains (ccol, crow)){
  616. OutputBuffer[position].Attributes = (ushort)currentAttribute;
  617. OutputBuffer[position].Char.UnicodeChar = (char)rune;
  618. }
  619. ccol++;
  620. if (ccol == Cols) {
  621. ccol = 0;
  622. if (crow + 1 < Rows)
  623. crow++;
  624. }
  625. if (sync)
  626. UpdateScreen ();
  627. }
  628. public override void AddStr (ustring str)
  629. {
  630. foreach (var rune in str)
  631. AddRune (rune);
  632. }
  633. int currentAttribute;
  634. public override void SetAttribute (Attribute c)
  635. {
  636. currentAttribute = c.value;
  637. }
  638. private Attribute MakeColor (ConsoleColor f, ConsoleColor b)
  639. {
  640. // Encode the colors into the int value.
  641. return new Attribute (){
  642. value = ((int)f | (int)b << 4)
  643. };
  644. }
  645. public override void Refresh()
  646. {
  647. var bufferCoords = new WindowsConsole.Coord (){
  648. X = (short)Clip.Width,
  649. Y = (short)Clip.Height
  650. };
  651. var window = new WindowsConsole.SmallRect (){
  652. Top = 0,
  653. Left = 0,
  654. Right = (short)Clip.Right,
  655. Bottom = (short)Clip.Bottom
  656. };
  657. UpdateCursor();
  658. winConsole.WriteToConsole (OutputBuffer, bufferCoords, window);
  659. }
  660. public override void UpdateScreen ()
  661. {
  662. var bufferCoords = new WindowsConsole.Coord (){
  663. X = (short)Clip.Width,
  664. Y = (short)Clip.Height
  665. };
  666. var window = new WindowsConsole.SmallRect (){
  667. Top = 0,
  668. Left = 0,
  669. Right = (short)Clip.Right,
  670. Bottom = (short)Clip.Bottom
  671. };
  672. UpdateCursor();
  673. winConsole.WriteToConsole (OutputBuffer, bufferCoords, window);
  674. }
  675. public override void UpdateCursor()
  676. {
  677. var position = new WindowsConsole.Coord(){
  678. X = (short)ccol,
  679. Y = (short)crow
  680. };
  681. winConsole.SetCursorPosition(position);
  682. }
  683. public override void End ()
  684. {
  685. winConsole.Cleanup();
  686. }
  687. #region Unused
  688. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  689. {
  690. }
  691. public override void SetColors (short foregroundColorId, short backgroundColorId)
  692. {
  693. }
  694. public override void Suspend ()
  695. {
  696. }
  697. public override void StartReportingMouseMoves ()
  698. {
  699. }
  700. public override void StopReportingMouseMoves ()
  701. {
  702. }
  703. public override void UncookMouse ()
  704. {
  705. }
  706. public override void CookMouse ()
  707. {
  708. }
  709. #endregion
  710. }
  711. }