WindowsDriver.cs 35 KB

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