WindowsDriver.cs 23 KB

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