WindowsDriver.cs 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219
  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 NStack;
  33. namespace Terminal.Gui {
  34. internal class WindowsConsole {
  35. public const int STD_OUTPUT_HANDLE = -11;
  36. public const int STD_INPUT_HANDLE = -10;
  37. public const int STD_ERROR_HANDLE = -12;
  38. internal IntPtr InputHandle, OutputHandle;
  39. IntPtr ScreenBuffer;
  40. uint originalConsoleMode;
  41. public WindowsConsole ()
  42. {
  43. InputHandle = GetStdHandle (STD_INPUT_HANDLE);
  44. OutputHandle = GetStdHandle (STD_OUTPUT_HANDLE);
  45. originalConsoleMode = ConsoleMode;
  46. var newConsoleMode = originalConsoleMode;
  47. newConsoleMode |= (uint)(ConsoleModes.EnableMouseInput | ConsoleModes.EnableExtendedFlags);
  48. newConsoleMode &= ~(uint)ConsoleModes.EnableQuickEditMode;
  49. newConsoleMode &= ~(uint)ConsoleModes.EnableProcessedInput;
  50. ConsoleMode = newConsoleMode;
  51. }
  52. public CharInfo [] OriginalStdOutChars;
  53. public bool WriteToConsole (CharInfo [] charInfoBuffer, Coord coords, SmallRect window)
  54. {
  55. if (ScreenBuffer == IntPtr.Zero) {
  56. ScreenBuffer = CreateConsoleScreenBuffer (
  57. DesiredAccess.GenericRead | DesiredAccess.GenericWrite,
  58. ShareMode.FileShareRead | ShareMode.FileShareWrite,
  59. IntPtr.Zero,
  60. 1,
  61. IntPtr.Zero
  62. );
  63. if (ScreenBuffer == INVALID_HANDLE_VALUE) {
  64. var err = Marshal.GetLastWin32Error ();
  65. if (err != 0)
  66. throw new System.ComponentModel.Win32Exception (err);
  67. }
  68. if (!SetConsoleActiveScreenBuffer (ScreenBuffer)) {
  69. var err = Marshal.GetLastWin32Error ();
  70. throw new System.ComponentModel.Win32Exception (err);
  71. }
  72. OriginalStdOutChars = new CharInfo [Console.WindowHeight * Console.WindowWidth];
  73. ReadConsoleOutput (OutputHandle, OriginalStdOutChars, coords, new Coord () { X = 0, Y = 0 }, ref window);
  74. }
  75. return WriteConsoleOutput (ScreenBuffer, charInfoBuffer, coords, new Coord () { X = window.Left, Y = window.Top }, ref window);
  76. }
  77. public bool SetCursorPosition (Coord position)
  78. {
  79. return SetConsoleCursorPosition (ScreenBuffer, position);
  80. }
  81. public void Cleanup ()
  82. {
  83. ConsoleMode = originalConsoleMode;
  84. //ContinueListeningForConsoleEvents = false;
  85. if (!SetConsoleActiveScreenBuffer (OutputHandle)) {
  86. var err = Marshal.GetLastWin32Error ();
  87. Console.WriteLine ("Error: {0}", err);
  88. }
  89. if (ScreenBuffer != IntPtr.Zero)
  90. CloseHandle (ScreenBuffer);
  91. ScreenBuffer = IntPtr.Zero;
  92. }
  93. //bool ContinueListeningForConsoleEvents = true;
  94. public uint ConsoleMode {
  95. get {
  96. uint v;
  97. GetConsoleMode (InputHandle, out v);
  98. return v;
  99. }
  100. set {
  101. SetConsoleMode (InputHandle, value);
  102. }
  103. }
  104. [Flags]
  105. public enum ConsoleModes : uint {
  106. EnableProcessedInput = 1,
  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, IMainLoopDriver {
  364. static bool sync = false;
  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. winConsole = new WindowsConsole ();
  377. SetupColorsAndBorders ();
  378. cols = Console.WindowWidth;
  379. rows = Console.WindowHeight;
  380. WindowsConsole.SmallRect.MakeEmpty (ref damageRegion);
  381. ResizeScreen ();
  382. UpdateOffScreen ();
  383. Task.Run ((Action)WindowsInputHandler);
  384. }
  385. private void SetupColorsAndBorders ()
  386. {
  387. Colors.TopLevel = new ColorScheme ();
  388. Colors.Base = new ColorScheme ();
  389. Colors.Dialog = new ColorScheme ();
  390. Colors.Menu = new ColorScheme ();
  391. Colors.Error = new ColorScheme ();
  392. Colors.TopLevel.Normal = MakeColor (ConsoleColor.Green, ConsoleColor.Black);
  393. Colors.TopLevel.Focus = MakeColor (ConsoleColor.White, ConsoleColor.DarkCyan);
  394. Colors.TopLevel.HotNormal = MakeColor (ConsoleColor.DarkYellow, ConsoleColor.Black);
  395. Colors.TopLevel.HotFocus = MakeColor (ConsoleColor.DarkBlue, ConsoleColor.DarkCyan);
  396. Colors.Base.Normal = MakeColor (ConsoleColor.White, ConsoleColor.DarkBlue);
  397. Colors.Base.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
  398. Colors.Base.HotNormal = MakeColor (ConsoleColor.DarkCyan, ConsoleColor.DarkBlue);
  399. Colors.Base.HotFocus = MakeColor (ConsoleColor.Blue, ConsoleColor.Gray);
  400. Colors.Menu.Normal = MakeColor (ConsoleColor.White, ConsoleColor.DarkGray);
  401. Colors.Menu.Focus = MakeColor (ConsoleColor.White, ConsoleColor.Black);
  402. Colors.Menu.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.DarkGray);
  403. Colors.Menu.HotFocus = MakeColor (ConsoleColor.Yellow, ConsoleColor.Black);
  404. Colors.Menu.Disabled = MakeColor (ConsoleColor.Gray, ConsoleColor.DarkGray);
  405. Colors.Dialog.Normal = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
  406. Colors.Dialog.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.DarkGray);
  407. Colors.Dialog.HotNormal = MakeColor (ConsoleColor.DarkBlue, ConsoleColor.Gray);
  408. Colors.Dialog.HotFocus = MakeColor (ConsoleColor.DarkBlue, ConsoleColor.DarkGray);
  409. Colors.Error.Normal = MakeColor (ConsoleColor.DarkRed, ConsoleColor.White);
  410. Colors.Error.Focus = MakeColor (ConsoleColor.White, ConsoleColor.DarkRed);
  411. Colors.Error.HotNormal = MakeColor (ConsoleColor.Black, ConsoleColor.White);
  412. Colors.Error.HotFocus = MakeColor (ConsoleColor.Black, ConsoleColor.DarkRed);
  413. HLine = '\u2500';
  414. VLine = '\u2502';
  415. Stipple = '\u2592';
  416. Diamond = '\u25c6';
  417. ULCorner = '\u250C';
  418. LLCorner = '\u2514';
  419. URCorner = '\u2510';
  420. LRCorner = '\u2518';
  421. LeftTee = '\u251c';
  422. RightTee = '\u2524';
  423. TopTee = '\u22a4';
  424. BottomTee = '\u22a5';
  425. }
  426. [StructLayout (LayoutKind.Sequential)]
  427. public struct ConsoleKeyInfoEx {
  428. public ConsoleKeyInfo consoleKeyInfo;
  429. public bool CapsLock;
  430. public bool NumLock;
  431. public ConsoleKeyInfoEx (ConsoleKeyInfo consoleKeyInfo, bool capslock, bool numlock)
  432. {
  433. this.consoleKeyInfo = consoleKeyInfo;
  434. CapsLock = capslock;
  435. NumLock = numlock;
  436. }
  437. }
  438. // The records that we keep fetching
  439. WindowsConsole.InputRecord [] result, records = new WindowsConsole.InputRecord [1];
  440. void WindowsInputHandler ()
  441. {
  442. while (true) {
  443. waitForProbe.Wait ();
  444. waitForProbe.Reset ();
  445. uint numberEventsRead = 0;
  446. WindowsConsole.ReadConsoleInput (winConsole.InputHandle, records, 1, out numberEventsRead);
  447. if (numberEventsRead == 0)
  448. result = null;
  449. else
  450. result = records;
  451. eventReady.Set ();
  452. }
  453. }
  454. void IMainLoopDriver.Setup (MainLoop mainLoop)
  455. {
  456. this.mainLoop = mainLoop;
  457. }
  458. void IMainLoopDriver.Wakeup ()
  459. {
  460. //tokenSource.Cancel ();
  461. eventReady.Reset ();
  462. eventReady.Set ();
  463. }
  464. bool IMainLoopDriver.EventsPending (bool wait)
  465. {
  466. long now = DateTime.UtcNow.Ticks;
  467. int waitTimeout;
  468. if (mainLoop.timeouts.Count > 0) {
  469. waitTimeout = (int)((mainLoop.timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  470. if (waitTimeout < 0)
  471. return true;
  472. } else
  473. waitTimeout = -1;
  474. if (!wait)
  475. waitTimeout = 0;
  476. result = null;
  477. waitForProbe.Set ();
  478. try {
  479. while (result == null) {
  480. if (wait && waitTimeout == -1) {
  481. waitTimeout = 0;
  482. }
  483. if (!tokenSource.IsCancellationRequested)
  484. eventReady.Wait (waitTimeout, tokenSource.Token);
  485. if (result != null) {
  486. break;
  487. }
  488. if (mainLoop.timeouts.Count > 0 || mainLoop.idleHandlers.Count > 0) {
  489. return true;
  490. }
  491. }
  492. } catch (OperationCanceledException) {
  493. return true;
  494. } finally {
  495. eventReady.Reset ();
  496. }
  497. if (!tokenSource.IsCancellationRequested)
  498. return result != null;
  499. tokenSource.Dispose ();
  500. tokenSource = new CancellationTokenSource ();
  501. return true;
  502. }
  503. Action<KeyEvent> keyHandler;
  504. Action<KeyEvent> keyDownHandler;
  505. Action<KeyEvent> keyUpHandler;
  506. Action<MouseEvent> mouseHandler;
  507. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
  508. {
  509. this.keyHandler = keyHandler;
  510. this.keyDownHandler = keyDownHandler;
  511. this.keyUpHandler = keyUpHandler;
  512. this.mouseHandler = mouseHandler;
  513. }
  514. void IMainLoopDriver.MainIteration ()
  515. {
  516. if (result == null)
  517. return;
  518. var inputEvent = result [0];
  519. switch (inputEvent.EventType) {
  520. case WindowsConsole.EventType.Key:
  521. var map = MapKey (ToConsoleKeyInfoEx (inputEvent.KeyEvent));
  522. if (map == (Key)0xffffffff) {
  523. KeyEvent key = new KeyEvent ();
  524. // Shift = VK_SHIFT = 0x10
  525. // Ctrl = VK_CONTROL = 0x11
  526. // Alt = VK_MENU = 0x12
  527. if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.CapslockOn)) {
  528. inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.CapslockOn;
  529. }
  530. if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ScrolllockOn)) {
  531. inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.ScrolllockOn;
  532. }
  533. if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.NumlockOn)) {
  534. inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.NumlockOn;
  535. }
  536. switch (inputEvent.KeyEvent.dwControlKeyState) {
  537. case WindowsConsole.ControlKeyState.RightAltPressed:
  538. case WindowsConsole.ControlKeyState.RightAltPressed |
  539. WindowsConsole.ControlKeyState.LeftControlPressed |
  540. WindowsConsole.ControlKeyState.EnhancedKey:
  541. case WindowsConsole.ControlKeyState.EnhancedKey:
  542. key = new KeyEvent (Key.CtrlMask | Key.AltMask);
  543. break;
  544. case WindowsConsole.ControlKeyState.LeftAltPressed:
  545. key = new KeyEvent (Key.AltMask);
  546. break;
  547. case WindowsConsole.ControlKeyState.RightControlPressed:
  548. case WindowsConsole.ControlKeyState.LeftControlPressed:
  549. key = new KeyEvent (Key.CtrlMask);
  550. break;
  551. case WindowsConsole.ControlKeyState.ShiftPressed:
  552. key = new KeyEvent (Key.ShiftMask);
  553. break;
  554. case WindowsConsole.ControlKeyState.NumlockOn:
  555. break;
  556. case WindowsConsole.ControlKeyState.ScrolllockOn:
  557. break;
  558. case WindowsConsole.ControlKeyState.CapslockOn:
  559. break;
  560. default:
  561. switch (inputEvent.KeyEvent.wVirtualKeyCode) {
  562. case 0x10:
  563. key = new KeyEvent (Key.ShiftMask);
  564. break;
  565. case 0x11:
  566. key = new KeyEvent (Key.CtrlMask);
  567. break;
  568. case 0x12:
  569. key = new KeyEvent (Key.AltMask);
  570. break;
  571. default:
  572. key = new KeyEvent (Key.Unknown);
  573. break;
  574. }
  575. break;
  576. }
  577. if (inputEvent.KeyEvent.bKeyDown)
  578. keyDownHandler (key);
  579. else
  580. keyUpHandler (key);
  581. } else {
  582. if (inputEvent.KeyEvent.bKeyDown) {
  583. // Key Down - Fire KeyDown Event and KeyStroke (ProcessKey) Event
  584. keyDownHandler (new KeyEvent (map));
  585. keyHandler (new KeyEvent (map));
  586. } else {
  587. keyUpHandler (new KeyEvent (map));
  588. }
  589. }
  590. break;
  591. case WindowsConsole.EventType.Mouse:
  592. mouseHandler (ToDriverMouse (inputEvent.MouseEvent));
  593. if (IsButtonReleased)
  594. mouseHandler (ToDriverMouse (inputEvent.MouseEvent));
  595. break;
  596. case WindowsConsole.EventType.WindowBufferSize:
  597. cols = inputEvent.WindowBufferSizeEvent.size.X;
  598. rows = inputEvent.WindowBufferSizeEvent.size.Y;
  599. ResizeScreen ();
  600. UpdateOffScreen ();
  601. TerminalResized?.Invoke ();
  602. break;
  603. }
  604. result = null;
  605. }
  606. WindowsConsole.ButtonState? LastMouseButtonPressed = null;
  607. bool IsButtonPressed = false;
  608. bool IsButtonReleased = false;
  609. bool IsButtonDoubleClicked = false;
  610. Point point;
  611. MouseEvent ToDriverMouse (WindowsConsole.MouseEventRecord mouseEvent)
  612. {
  613. MouseFlags mouseFlag = MouseFlags.AllEvents;
  614. if (IsButtonDoubleClicked) {
  615. Task.Run (async () => {
  616. await Task.Delay (100);
  617. IsButtonDoubleClicked = false;
  618. });
  619. }
  620. // The ButtonState member of the MouseEvent structure has bit corresponding to each mouse button.
  621. // This will tell when a mouse button is pressed. When the button is released this event will
  622. // be fired with it's bit set to 0. So when the button is up ButtonState will be 0.
  623. // To map to the correct driver events we save the last pressed mouse button so we can
  624. // map to the correct clicked event.
  625. if ((LastMouseButtonPressed != null || IsButtonReleased) && mouseEvent.ButtonState != 0) {
  626. LastMouseButtonPressed = null;
  627. IsButtonPressed = false;
  628. IsButtonReleased = false;
  629. }
  630. if ((mouseEvent.EventFlags == 0 && LastMouseButtonPressed == null && !IsButtonDoubleClicked) ||
  631. (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved &&
  632. mouseEvent.ButtonState != 0 && !IsButtonReleased && !IsButtonDoubleClicked)) {
  633. switch (mouseEvent.ButtonState) {
  634. case WindowsConsole.ButtonState.Button1Pressed:
  635. mouseFlag = MouseFlags.Button1Pressed;
  636. break;
  637. case WindowsConsole.ButtonState.Button2Pressed:
  638. mouseFlag = MouseFlags.Button2Pressed;
  639. break;
  640. case WindowsConsole.ButtonState.RightmostButtonPressed:
  641. mouseFlag = MouseFlags.Button3Pressed;
  642. break;
  643. }
  644. if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  645. mouseFlag |= MouseFlags.ReportMousePosition;
  646. point = new Point ();
  647. IsButtonReleased = false;
  648. } else {
  649. point = new Point () {
  650. X = mouseEvent.MousePosition.X,
  651. Y = mouseEvent.MousePosition.Y
  652. };
  653. }
  654. LastMouseButtonPressed = mouseEvent.ButtonState;
  655. IsButtonPressed = true;
  656. if ((mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  657. Task.Run (async () => {
  658. while (IsButtonPressed) {
  659. await Task.Delay (200);
  660. var me = new MouseEvent () {
  661. X = mouseEvent.MousePosition.X,
  662. Y = mouseEvent.MousePosition.Y,
  663. Flags = mouseFlag
  664. };
  665. var view = Application.wantContinuousButtonPressedView;
  666. if (view == null)
  667. break;
  668. if (IsButtonPressed && (mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  669. mouseHandler (me);
  670. mainLoop.Driver.Wakeup ();
  671. }
  672. }
  673. });
  674. }
  675. } else if ((mouseEvent.EventFlags == 0 || mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) &&
  676. LastMouseButtonPressed != null && !IsButtonReleased && !IsButtonDoubleClicked) {
  677. switch (LastMouseButtonPressed) {
  678. case WindowsConsole.ButtonState.Button1Pressed:
  679. mouseFlag = MouseFlags.Button1Released;
  680. break;
  681. case WindowsConsole.ButtonState.Button2Pressed:
  682. mouseFlag = MouseFlags.Button2Released;
  683. break;
  684. case WindowsConsole.ButtonState.RightmostButtonPressed:
  685. mouseFlag = MouseFlags.Button3Released;
  686. break;
  687. }
  688. IsButtonPressed = false;
  689. IsButtonReleased = true;
  690. } else if ((mouseEvent.EventFlags == 0 || mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) &&
  691. IsButtonReleased) {
  692. var p = new Point () {
  693. X = mouseEvent.MousePosition.X,
  694. Y = mouseEvent.MousePosition.Y
  695. };
  696. if (p == point) {
  697. switch (LastMouseButtonPressed) {
  698. case WindowsConsole.ButtonState.Button1Pressed:
  699. mouseFlag = MouseFlags.Button1Clicked;
  700. break;
  701. case WindowsConsole.ButtonState.Button2Pressed:
  702. mouseFlag = MouseFlags.Button2Clicked;
  703. break;
  704. case WindowsConsole.ButtonState.RightmostButtonPressed:
  705. mouseFlag = MouseFlags.Button3Clicked;
  706. break;
  707. }
  708. } else {
  709. mouseFlag = 0;
  710. }
  711. LastMouseButtonPressed = null;
  712. IsButtonReleased = false;
  713. } else if (mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.DoubleClick)) {
  714. switch (mouseEvent.ButtonState) {
  715. case WindowsConsole.ButtonState.Button1Pressed:
  716. mouseFlag = MouseFlags.Button1DoubleClicked;
  717. break;
  718. case WindowsConsole.ButtonState.Button2Pressed:
  719. mouseFlag = MouseFlags.Button2DoubleClicked;
  720. break;
  721. case WindowsConsole.ButtonState.RightmostButtonPressed:
  722. mouseFlag = MouseFlags.Button3DoubleClicked;
  723. break;
  724. }
  725. IsButtonDoubleClicked = true;
  726. } else if (mouseEvent.EventFlags == 0 && mouseEvent.ButtonState != 0 && IsButtonDoubleClicked) {
  727. switch (mouseEvent.ButtonState) {
  728. case WindowsConsole.ButtonState.Button1Pressed:
  729. mouseFlag = MouseFlags.Button1TripleClicked;
  730. break;
  731. case WindowsConsole.ButtonState.Button2Pressed:
  732. mouseFlag = MouseFlags.Button2TripleClicked;
  733. break;
  734. case WindowsConsole.ButtonState.RightmostButtonPressed:
  735. mouseFlag = MouseFlags.Button3TripleClicked;
  736. break;
  737. }
  738. IsButtonDoubleClicked = false;
  739. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled) {
  740. switch (mouseEvent.ButtonState) {
  741. case WindowsConsole.ButtonState.WheeledUp:
  742. mouseFlag = MouseFlags.WheeledUp;
  743. break;
  744. case WindowsConsole.ButtonState.WheeledDown:
  745. mouseFlag = MouseFlags.WheeledDown;
  746. break;
  747. }
  748. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  749. mouseFlag = MouseFlags.ReportMousePosition;
  750. } else if (mouseEvent.ButtonState == 0 && mouseEvent.EventFlags == 0) {
  751. mouseFlag = 0;
  752. }
  753. mouseFlag = SetControlKeyStates (mouseEvent, mouseFlag);
  754. return new MouseEvent () {
  755. X = mouseEvent.MousePosition.X,
  756. Y = mouseEvent.MousePosition.Y,
  757. Flags = mouseFlag
  758. };
  759. }
  760. static MouseFlags SetControlKeyStates (WindowsConsole.MouseEventRecord mouseEvent, MouseFlags mouseFlag)
  761. {
  762. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed) ||
  763. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed))
  764. mouseFlag |= MouseFlags.ButtonCtrl;
  765. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed))
  766. mouseFlag |= MouseFlags.ButtonShift;
  767. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed) ||
  768. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed))
  769. mouseFlag |= MouseFlags.ButtonAlt;
  770. return mouseFlag;
  771. }
  772. public ConsoleKeyInfoEx ToConsoleKeyInfoEx (WindowsConsole.KeyEventRecord keyEvent)
  773. {
  774. var state = keyEvent.dwControlKeyState;
  775. bool shift = (state & WindowsConsole.ControlKeyState.ShiftPressed) != 0;
  776. bool alt = (state & (WindowsConsole.ControlKeyState.LeftAltPressed | WindowsConsole.ControlKeyState.RightAltPressed)) != 0;
  777. bool control = (state & (WindowsConsole.ControlKeyState.LeftControlPressed | WindowsConsole.ControlKeyState.RightControlPressed)) != 0;
  778. bool capslock = (state & (WindowsConsole.ControlKeyState.CapslockOn)) != 0;
  779. bool numlock = (state & (WindowsConsole.ControlKeyState.NumlockOn)) != 0;
  780. var ConsoleKeyInfo = new ConsoleKeyInfo (keyEvent.UnicodeChar, (ConsoleKey)keyEvent.wVirtualKeyCode, shift, alt, control);
  781. return new ConsoleKeyInfoEx (ConsoleKeyInfo, capslock, numlock);
  782. }
  783. public Key MapKey (ConsoleKeyInfoEx keyInfoEx)
  784. {
  785. var keyInfo = keyInfoEx.consoleKeyInfo;
  786. switch (keyInfo.Key) {
  787. case ConsoleKey.Escape:
  788. return MapKeyModifiers (keyInfo, Key.Esc);
  789. case ConsoleKey.Tab:
  790. return keyInfo.Modifiers == ConsoleModifiers.Shift ? Key.BackTab : Key.Tab;
  791. case ConsoleKey.Home:
  792. return MapKeyModifiers (keyInfo, Key.Home);
  793. case ConsoleKey.End:
  794. return MapKeyModifiers (keyInfo, Key.End);
  795. case ConsoleKey.LeftArrow:
  796. return MapKeyModifiers (keyInfo, Key.CursorLeft);
  797. case ConsoleKey.RightArrow:
  798. return MapKeyModifiers (keyInfo, Key.CursorRight);
  799. case ConsoleKey.UpArrow:
  800. return MapKeyModifiers (keyInfo, Key.CursorUp);
  801. case ConsoleKey.DownArrow:
  802. return MapKeyModifiers (keyInfo, Key.CursorDown);
  803. case ConsoleKey.PageUp:
  804. return MapKeyModifiers (keyInfo, Key.PageUp);
  805. case ConsoleKey.PageDown:
  806. return MapKeyModifiers (keyInfo, Key.PageDown);
  807. case ConsoleKey.Enter:
  808. return MapKeyModifiers (keyInfo, Key.Enter);
  809. case ConsoleKey.Spacebar:
  810. return MapKeyModifiers (keyInfo, Key.Space);
  811. case ConsoleKey.Backspace:
  812. return MapKeyModifiers (keyInfo, Key.Backspace);
  813. case ConsoleKey.Delete:
  814. return MapKeyModifiers (keyInfo, Key.DeleteChar);
  815. case ConsoleKey.Insert:
  816. return MapKeyModifiers (keyInfo, Key.InsertChar);
  817. case ConsoleKey.NumPad0:
  818. return keyInfoEx.NumLock ? (Key)(uint)'0' : Key.InsertChar;
  819. case ConsoleKey.NumPad1:
  820. return keyInfoEx.NumLock ? (Key)(uint)'1' : Key.End;
  821. case ConsoleKey.NumPad2:
  822. return keyInfoEx.NumLock ? (Key)(uint)'2' : Key.CursorDown;
  823. case ConsoleKey.NumPad3:
  824. return keyInfoEx.NumLock ? (Key)(uint)'3' : Key.PageDown;
  825. case ConsoleKey.NumPad4:
  826. return keyInfoEx.NumLock ? (Key)(uint)'4' : Key.CursorLeft;
  827. case ConsoleKey.NumPad5:
  828. return keyInfoEx.NumLock ? (Key)(uint)'5' : (Key)((uint)keyInfo.KeyChar);
  829. case ConsoleKey.NumPad6:
  830. return keyInfoEx.NumLock ? (Key)(uint)'6' : Key.CursorRight;
  831. case ConsoleKey.NumPad7:
  832. return keyInfoEx.NumLock ? (Key)(uint)'7' : Key.Home;
  833. case ConsoleKey.NumPad8:
  834. return keyInfoEx.NumLock ? (Key)(uint)'8' : Key.CursorUp;
  835. case ConsoleKey.NumPad9:
  836. return keyInfoEx.NumLock ? (Key)(uint)'9' : Key.PageUp;
  837. case ConsoleKey.Oem1:
  838. case ConsoleKey.Oem2:
  839. case ConsoleKey.Oem3:
  840. case ConsoleKey.Oem4:
  841. case ConsoleKey.Oem5:
  842. case ConsoleKey.Oem6:
  843. case ConsoleKey.Oem7:
  844. case ConsoleKey.Oem8:
  845. case ConsoleKey.Oem102:
  846. case ConsoleKey.OemPeriod:
  847. case ConsoleKey.OemComma:
  848. case ConsoleKey.OemPlus:
  849. case ConsoleKey.OemMinus:
  850. if (keyInfo.KeyChar == 0)
  851. return Key.Unknown;
  852. return (Key)((uint)keyInfo.KeyChar);
  853. }
  854. var key = keyInfo.Key;
  855. //var alphaBase = ((keyInfo.Modifiers == ConsoleModifiers.Shift) ^ (keyInfoEx.CapsLock)) ? 'A' : 'a';
  856. if (key >= ConsoleKey.A && key <= ConsoleKey.Z) {
  857. var delta = key - ConsoleKey.A;
  858. if (keyInfo.Modifiers == ConsoleModifiers.Control)
  859. return (Key)((uint)Key.ControlA + delta);
  860. if (keyInfo.Modifiers == ConsoleModifiers.Alt)
  861. return (Key)(((uint)Key.AltMask) | ((uint)'A' + delta));
  862. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  863. if (keyInfo.KeyChar == 0)
  864. return (Key)(((uint)Key.AltMask) + ((uint)Key.ControlA + delta));
  865. else
  866. return (Key)((uint)keyInfo.KeyChar);
  867. }
  868. //return (Key)((uint)alphaBase + delta);
  869. return (Key)((uint)keyInfo.KeyChar);
  870. }
  871. if (key >= ConsoleKey.D0 && key <= ConsoleKey.D9) {
  872. var delta = key - ConsoleKey.D0;
  873. if (keyInfo.Modifiers == ConsoleModifiers.Alt)
  874. return (Key)(((uint)Key.AltMask) | ((uint)'0' + delta));
  875. return (Key)((uint)keyInfo.KeyChar);
  876. }
  877. if (key >= ConsoleKey.F1 && key <= ConsoleKey.F12) {
  878. var delta = key - ConsoleKey.F1;
  879. return (Key)((int)Key.F1 + delta);
  880. }
  881. return (Key)(0xffffffff);
  882. }
  883. private static Key MapKeyModifiers (ConsoleKeyInfo keyInfo, Key key)
  884. {
  885. Key keyMod = new Key ();
  886. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Shift))
  887. keyMod = Key.ShiftMask;
  888. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control))
  889. keyMod |= Key.CtrlMask;
  890. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt))
  891. keyMod |= Key.AltMask;
  892. return keyMod != Key.ControlSpace ? keyMod | key : key;
  893. }
  894. public override void Init (Action terminalResized)
  895. {
  896. TerminalResized = terminalResized;
  897. SetupColorsAndBorders ();
  898. }
  899. void ResizeScreen ()
  900. {
  901. OutputBuffer = new WindowsConsole.CharInfo [Rows * Cols];
  902. Clip = new Rect (0, 0, Cols, Rows);
  903. damageRegion = new WindowsConsole.SmallRect () {
  904. Top = 0,
  905. Left = 0,
  906. Bottom = (short)Rows,
  907. Right = (short)Cols
  908. };
  909. }
  910. void UpdateOffScreen ()
  911. {
  912. for (int row = 0; row < rows; row++)
  913. for (int col = 0; col < cols; col++) {
  914. int position = row * cols + col;
  915. OutputBuffer [position].Attributes = (ushort)Colors.TopLevel.Normal;
  916. OutputBuffer [position].Char.UnicodeChar = ' ';
  917. }
  918. }
  919. int ccol, crow;
  920. public override void Move (int col, int row)
  921. {
  922. ccol = col;
  923. crow = row;
  924. }
  925. public override void AddRune (Rune rune)
  926. {
  927. var position = crow * Cols + ccol;
  928. if (Clip.Contains (ccol, crow)) {
  929. OutputBuffer [position].Attributes = (ushort)currentAttribute;
  930. OutputBuffer [position].Char.UnicodeChar = (char)rune;
  931. WindowsConsole.SmallRect.Update (ref damageRegion, (short)ccol, (short)crow);
  932. }
  933. ccol++;
  934. var runeWidth = Rune.ColumnWidth (rune);
  935. if (runeWidth > 1) {
  936. for (int i = 1; i < runeWidth; i++) {
  937. AddStr (" ");
  938. }
  939. }
  940. //if (ccol == Cols) {
  941. // ccol = 0;
  942. // if (crow + 1 < Rows)
  943. // crow++;
  944. //}
  945. if (sync)
  946. UpdateScreen ();
  947. }
  948. public override void AddStr (ustring str)
  949. {
  950. foreach (var rune in str)
  951. AddRune (rune);
  952. }
  953. int currentAttribute;
  954. CancellationTokenSource tokenSource = new CancellationTokenSource ();
  955. public override void SetAttribute (Attribute c)
  956. {
  957. currentAttribute = c.value;
  958. }
  959. Attribute MakeColor (ConsoleColor f, ConsoleColor b)
  960. {
  961. // Encode the colors into the int value.
  962. return new Attribute () {
  963. value = ((int)f | (int)b << 4),
  964. foreground = (Color)f,
  965. background = (Color)b
  966. };
  967. }
  968. public override Attribute MakeAttribute (Color fore, Color back)
  969. {
  970. return MakeColor ((ConsoleColor)fore, (ConsoleColor)back);
  971. }
  972. public override void Refresh ()
  973. {
  974. UpdateScreen ();
  975. #if false
  976. var bufferCoords = new WindowsConsole.Coord (){
  977. X = (short)Clip.Width,
  978. Y = (short)Clip.Height
  979. };
  980. var window = new WindowsConsole.SmallRect (){
  981. Top = 0,
  982. Left = 0,
  983. Right = (short)Clip.Right,
  984. Bottom = (short)Clip.Bottom
  985. };
  986. UpdateCursor();
  987. winConsole.WriteToConsole (OutputBuffer, bufferCoords, window);
  988. #endif
  989. }
  990. public override void UpdateScreen ()
  991. {
  992. if (damageRegion.Left == -1)
  993. return;
  994. var bufferCoords = new WindowsConsole.Coord () {
  995. X = (short)Clip.Width,
  996. Y = (short)Clip.Height
  997. };
  998. var window = new WindowsConsole.SmallRect () {
  999. Top = 0,
  1000. Left = 0,
  1001. Right = (short)Clip.Right,
  1002. Bottom = (short)Clip.Bottom
  1003. };
  1004. UpdateCursor ();
  1005. winConsole.WriteToConsole (OutputBuffer, bufferCoords, damageRegion);
  1006. // System.Diagnostics.Debugger.Log(0, "debug", $"Region={damageRegion.Right - damageRegion.Left},{damageRegion.Bottom - damageRegion.Top}\n");
  1007. WindowsConsole.SmallRect.MakeEmpty (ref damageRegion);
  1008. }
  1009. public override void UpdateCursor ()
  1010. {
  1011. var position = new WindowsConsole.Coord () {
  1012. X = (short)ccol,
  1013. Y = (short)crow
  1014. };
  1015. winConsole.SetCursorPosition (position);
  1016. }
  1017. public override void End ()
  1018. {
  1019. winConsole.Cleanup ();
  1020. }
  1021. #region Unused
  1022. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  1023. {
  1024. }
  1025. public override void SetColors (short foregroundColorId, short backgroundColorId)
  1026. {
  1027. }
  1028. public override void Suspend ()
  1029. {
  1030. }
  1031. public override void StartReportingMouseMoves ()
  1032. {
  1033. }
  1034. public override void StopReportingMouseMoves ()
  1035. {
  1036. }
  1037. public override void UncookMouse ()
  1038. {
  1039. }
  1040. public override void CookMouse ()
  1041. {
  1042. }
  1043. #endregion
  1044. }
  1045. }