WindowsDriver.cs 30 KB

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