WindowsDriver.cs 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229
  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. int waitTimeout = 0;
  470. if (CkeckTimeout (wait, ref waitTimeout))
  471. return true;
  472. result = null;
  473. waitForProbe.Set ();
  474. try {
  475. while (result == null) {
  476. if (!tokenSource.IsCancellationRequested)
  477. eventReady.Wait (0, tokenSource.Token);
  478. if (result != null) {
  479. break;
  480. }
  481. if (mainLoop.idleHandlers.Count > 0 || CkeckTimeout (wait, ref waitTimeout)) {
  482. return true;
  483. }
  484. }
  485. } catch (OperationCanceledException) {
  486. return true;
  487. } finally {
  488. eventReady.Reset ();
  489. }
  490. if (!tokenSource.IsCancellationRequested)
  491. return result != null;
  492. tokenSource.Dispose ();
  493. tokenSource = new CancellationTokenSource ();
  494. return true;
  495. }
  496. bool CkeckTimeout (bool wait, ref int waitTimeout)
  497. {
  498. long now = DateTime.UtcNow.Ticks;
  499. if (mainLoop.timeouts.Count > 0) {
  500. waitTimeout = (int)((mainLoop.timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  501. if (waitTimeout < 0)
  502. return true;
  503. } else {
  504. waitTimeout = -1;
  505. }
  506. if (!wait)
  507. waitTimeout = 0;
  508. return false;
  509. }
  510. Action<KeyEvent> keyHandler;
  511. Action<KeyEvent> keyDownHandler;
  512. Action<KeyEvent> keyUpHandler;
  513. Action<MouseEvent> mouseHandler;
  514. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
  515. {
  516. this.keyHandler = keyHandler;
  517. this.keyDownHandler = keyDownHandler;
  518. this.keyUpHandler = keyUpHandler;
  519. this.mouseHandler = mouseHandler;
  520. }
  521. void IMainLoopDriver.MainIteration ()
  522. {
  523. if (result == null)
  524. return;
  525. var inputEvent = result [0];
  526. switch (inputEvent.EventType) {
  527. case WindowsConsole.EventType.Key:
  528. var map = MapKey (ToConsoleKeyInfoEx (inputEvent.KeyEvent));
  529. if (map == (Key)0xffffffff) {
  530. KeyEvent key = new KeyEvent ();
  531. // Shift = VK_SHIFT = 0x10
  532. // Ctrl = VK_CONTROL = 0x11
  533. // Alt = VK_MENU = 0x12
  534. if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.CapslockOn)) {
  535. inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.CapslockOn;
  536. }
  537. if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ScrolllockOn)) {
  538. inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.ScrolllockOn;
  539. }
  540. if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.NumlockOn)) {
  541. inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.NumlockOn;
  542. }
  543. switch (inputEvent.KeyEvent.dwControlKeyState) {
  544. case WindowsConsole.ControlKeyState.RightAltPressed:
  545. case WindowsConsole.ControlKeyState.RightAltPressed |
  546. WindowsConsole.ControlKeyState.LeftControlPressed |
  547. WindowsConsole.ControlKeyState.EnhancedKey:
  548. case WindowsConsole.ControlKeyState.EnhancedKey:
  549. key = new KeyEvent (Key.CtrlMask | Key.AltMask);
  550. break;
  551. case WindowsConsole.ControlKeyState.LeftAltPressed:
  552. key = new KeyEvent (Key.AltMask);
  553. break;
  554. case WindowsConsole.ControlKeyState.RightControlPressed:
  555. case WindowsConsole.ControlKeyState.LeftControlPressed:
  556. key = new KeyEvent (Key.CtrlMask);
  557. break;
  558. case WindowsConsole.ControlKeyState.ShiftPressed:
  559. key = new KeyEvent (Key.ShiftMask);
  560. break;
  561. case WindowsConsole.ControlKeyState.NumlockOn:
  562. break;
  563. case WindowsConsole.ControlKeyState.ScrolllockOn:
  564. break;
  565. case WindowsConsole.ControlKeyState.CapslockOn:
  566. break;
  567. default:
  568. switch (inputEvent.KeyEvent.wVirtualKeyCode) {
  569. case 0x10:
  570. key = new KeyEvent (Key.ShiftMask);
  571. break;
  572. case 0x11:
  573. key = new KeyEvent (Key.CtrlMask);
  574. break;
  575. case 0x12:
  576. key = new KeyEvent (Key.AltMask);
  577. break;
  578. default:
  579. key = new KeyEvent (Key.Unknown);
  580. break;
  581. }
  582. break;
  583. }
  584. if (inputEvent.KeyEvent.bKeyDown)
  585. keyDownHandler (key);
  586. else
  587. keyUpHandler (key);
  588. } else {
  589. if (inputEvent.KeyEvent.bKeyDown) {
  590. // Key Down - Fire KeyDown Event and KeyStroke (ProcessKey) Event
  591. keyDownHandler (new KeyEvent (map));
  592. keyHandler (new KeyEvent (map));
  593. } else {
  594. keyUpHandler (new KeyEvent (map));
  595. }
  596. }
  597. break;
  598. case WindowsConsole.EventType.Mouse:
  599. mouseHandler (ToDriverMouse (inputEvent.MouseEvent));
  600. if (IsButtonReleased)
  601. mouseHandler (ToDriverMouse (inputEvent.MouseEvent));
  602. break;
  603. case WindowsConsole.EventType.WindowBufferSize:
  604. cols = inputEvent.WindowBufferSizeEvent.size.X;
  605. rows = inputEvent.WindowBufferSizeEvent.size.Y;
  606. ResizeScreen ();
  607. UpdateOffScreen ();
  608. TerminalResized?.Invoke ();
  609. break;
  610. }
  611. result = null;
  612. }
  613. WindowsConsole.ButtonState? LastMouseButtonPressed = null;
  614. bool IsButtonPressed = false;
  615. bool IsButtonReleased = false;
  616. bool IsButtonDoubleClicked = false;
  617. Point point;
  618. MouseEvent ToDriverMouse (WindowsConsole.MouseEventRecord mouseEvent)
  619. {
  620. MouseFlags mouseFlag = MouseFlags.AllEvents;
  621. if (IsButtonDoubleClicked) {
  622. Task.Run (async () => {
  623. await Task.Delay (100);
  624. IsButtonDoubleClicked = false;
  625. });
  626. }
  627. // The ButtonState member of the MouseEvent structure has bit corresponding to each mouse button.
  628. // This will tell when a mouse button is pressed. When the button is released this event will
  629. // be fired with it's bit set to 0. So when the button is up ButtonState will be 0.
  630. // To map to the correct driver events we save the last pressed mouse button so we can
  631. // map to the correct clicked event.
  632. if ((LastMouseButtonPressed != null || IsButtonReleased) && mouseEvent.ButtonState != 0) {
  633. LastMouseButtonPressed = null;
  634. IsButtonPressed = false;
  635. IsButtonReleased = false;
  636. }
  637. if ((mouseEvent.EventFlags == 0 && LastMouseButtonPressed == null && !IsButtonDoubleClicked) ||
  638. (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved &&
  639. mouseEvent.ButtonState != 0 && !IsButtonReleased && !IsButtonDoubleClicked)) {
  640. switch (mouseEvent.ButtonState) {
  641. case WindowsConsole.ButtonState.Button1Pressed:
  642. mouseFlag = MouseFlags.Button1Pressed;
  643. break;
  644. case WindowsConsole.ButtonState.Button2Pressed:
  645. mouseFlag = MouseFlags.Button2Pressed;
  646. break;
  647. case WindowsConsole.ButtonState.RightmostButtonPressed:
  648. mouseFlag = MouseFlags.Button3Pressed;
  649. break;
  650. }
  651. if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  652. mouseFlag |= MouseFlags.ReportMousePosition;
  653. point = new Point ();
  654. IsButtonReleased = false;
  655. } else {
  656. point = new Point () {
  657. X = mouseEvent.MousePosition.X,
  658. Y = mouseEvent.MousePosition.Y
  659. };
  660. }
  661. LastMouseButtonPressed = mouseEvent.ButtonState;
  662. IsButtonPressed = true;
  663. if ((mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  664. Task.Run (async () => {
  665. while (IsButtonPressed) {
  666. await Task.Delay (200);
  667. var me = new MouseEvent () {
  668. X = mouseEvent.MousePosition.X,
  669. Y = mouseEvent.MousePosition.Y,
  670. Flags = mouseFlag
  671. };
  672. var view = Application.wantContinuousButtonPressedView;
  673. if (view == null)
  674. break;
  675. if (IsButtonPressed && (mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  676. mouseHandler (me);
  677. //mainLoop.Driver.Wakeup ();
  678. }
  679. }
  680. });
  681. }
  682. } else if ((mouseEvent.EventFlags == 0 || mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) &&
  683. LastMouseButtonPressed != null && !IsButtonReleased && !IsButtonDoubleClicked) {
  684. switch (LastMouseButtonPressed) {
  685. case WindowsConsole.ButtonState.Button1Pressed:
  686. mouseFlag = MouseFlags.Button1Released;
  687. break;
  688. case WindowsConsole.ButtonState.Button2Pressed:
  689. mouseFlag = MouseFlags.Button2Released;
  690. break;
  691. case WindowsConsole.ButtonState.RightmostButtonPressed:
  692. mouseFlag = MouseFlags.Button3Released;
  693. break;
  694. }
  695. IsButtonPressed = false;
  696. IsButtonReleased = true;
  697. } else if ((mouseEvent.EventFlags == 0 || mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) &&
  698. IsButtonReleased) {
  699. var p = new Point () {
  700. X = mouseEvent.MousePosition.X,
  701. Y = mouseEvent.MousePosition.Y
  702. };
  703. if (p == point) {
  704. switch (LastMouseButtonPressed) {
  705. case WindowsConsole.ButtonState.Button1Pressed:
  706. mouseFlag = MouseFlags.Button1Clicked;
  707. break;
  708. case WindowsConsole.ButtonState.Button2Pressed:
  709. mouseFlag = MouseFlags.Button2Clicked;
  710. break;
  711. case WindowsConsole.ButtonState.RightmostButtonPressed:
  712. mouseFlag = MouseFlags.Button3Clicked;
  713. break;
  714. }
  715. } else {
  716. mouseFlag = 0;
  717. }
  718. LastMouseButtonPressed = null;
  719. IsButtonReleased = false;
  720. } else if (mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.DoubleClick)) {
  721. switch (mouseEvent.ButtonState) {
  722. case WindowsConsole.ButtonState.Button1Pressed:
  723. mouseFlag = MouseFlags.Button1DoubleClicked;
  724. break;
  725. case WindowsConsole.ButtonState.Button2Pressed:
  726. mouseFlag = MouseFlags.Button2DoubleClicked;
  727. break;
  728. case WindowsConsole.ButtonState.RightmostButtonPressed:
  729. mouseFlag = MouseFlags.Button3DoubleClicked;
  730. break;
  731. }
  732. IsButtonDoubleClicked = true;
  733. } else if (mouseEvent.EventFlags == 0 && mouseEvent.ButtonState != 0 && IsButtonDoubleClicked) {
  734. switch (mouseEvent.ButtonState) {
  735. case WindowsConsole.ButtonState.Button1Pressed:
  736. mouseFlag = MouseFlags.Button1TripleClicked;
  737. break;
  738. case WindowsConsole.ButtonState.Button2Pressed:
  739. mouseFlag = MouseFlags.Button2TripleClicked;
  740. break;
  741. case WindowsConsole.ButtonState.RightmostButtonPressed:
  742. mouseFlag = MouseFlags.Button3TripleClicked;
  743. break;
  744. }
  745. IsButtonDoubleClicked = false;
  746. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled) {
  747. switch (mouseEvent.ButtonState) {
  748. case WindowsConsole.ButtonState.WheeledUp:
  749. mouseFlag = MouseFlags.WheeledUp;
  750. break;
  751. case WindowsConsole.ButtonState.WheeledDown:
  752. mouseFlag = MouseFlags.WheeledDown;
  753. break;
  754. }
  755. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  756. mouseFlag = MouseFlags.ReportMousePosition;
  757. } else if (mouseEvent.ButtonState == 0 && mouseEvent.EventFlags == 0) {
  758. mouseFlag = 0;
  759. }
  760. mouseFlag = SetControlKeyStates (mouseEvent, mouseFlag);
  761. return new MouseEvent () {
  762. X = mouseEvent.MousePosition.X,
  763. Y = mouseEvent.MousePosition.Y,
  764. Flags = mouseFlag
  765. };
  766. }
  767. static MouseFlags SetControlKeyStates (WindowsConsole.MouseEventRecord mouseEvent, MouseFlags mouseFlag)
  768. {
  769. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed) ||
  770. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed))
  771. mouseFlag |= MouseFlags.ButtonCtrl;
  772. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed))
  773. mouseFlag |= MouseFlags.ButtonShift;
  774. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed) ||
  775. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed))
  776. mouseFlag |= MouseFlags.ButtonAlt;
  777. return mouseFlag;
  778. }
  779. public ConsoleKeyInfoEx ToConsoleKeyInfoEx (WindowsConsole.KeyEventRecord keyEvent)
  780. {
  781. var state = keyEvent.dwControlKeyState;
  782. bool shift = (state & WindowsConsole.ControlKeyState.ShiftPressed) != 0;
  783. bool alt = (state & (WindowsConsole.ControlKeyState.LeftAltPressed | WindowsConsole.ControlKeyState.RightAltPressed)) != 0;
  784. bool control = (state & (WindowsConsole.ControlKeyState.LeftControlPressed | WindowsConsole.ControlKeyState.RightControlPressed)) != 0;
  785. bool capslock = (state & (WindowsConsole.ControlKeyState.CapslockOn)) != 0;
  786. bool numlock = (state & (WindowsConsole.ControlKeyState.NumlockOn)) != 0;
  787. var ConsoleKeyInfo = new ConsoleKeyInfo (keyEvent.UnicodeChar, (ConsoleKey)keyEvent.wVirtualKeyCode, shift, alt, control);
  788. return new ConsoleKeyInfoEx (ConsoleKeyInfo, capslock, numlock);
  789. }
  790. public Key MapKey (ConsoleKeyInfoEx keyInfoEx)
  791. {
  792. var keyInfo = keyInfoEx.consoleKeyInfo;
  793. switch (keyInfo.Key) {
  794. case ConsoleKey.Escape:
  795. return MapKeyModifiers (keyInfo, Key.Esc);
  796. case ConsoleKey.Tab:
  797. return keyInfo.Modifiers == ConsoleModifiers.Shift ? Key.BackTab : Key.Tab;
  798. case ConsoleKey.Home:
  799. return MapKeyModifiers (keyInfo, Key.Home);
  800. case ConsoleKey.End:
  801. return MapKeyModifiers (keyInfo, Key.End);
  802. case ConsoleKey.LeftArrow:
  803. return MapKeyModifiers (keyInfo, Key.CursorLeft);
  804. case ConsoleKey.RightArrow:
  805. return MapKeyModifiers (keyInfo, Key.CursorRight);
  806. case ConsoleKey.UpArrow:
  807. return MapKeyModifiers (keyInfo, Key.CursorUp);
  808. case ConsoleKey.DownArrow:
  809. return MapKeyModifiers (keyInfo, Key.CursorDown);
  810. case ConsoleKey.PageUp:
  811. return MapKeyModifiers (keyInfo, Key.PageUp);
  812. case ConsoleKey.PageDown:
  813. return MapKeyModifiers (keyInfo, Key.PageDown);
  814. case ConsoleKey.Enter:
  815. return MapKeyModifiers (keyInfo, Key.Enter);
  816. case ConsoleKey.Spacebar:
  817. return MapKeyModifiers (keyInfo, Key.Space);
  818. case ConsoleKey.Backspace:
  819. return MapKeyModifiers (keyInfo, Key.Backspace);
  820. case ConsoleKey.Delete:
  821. return MapKeyModifiers (keyInfo, Key.DeleteChar);
  822. case ConsoleKey.Insert:
  823. return MapKeyModifiers (keyInfo, Key.InsertChar);
  824. case ConsoleKey.NumPad0:
  825. return keyInfoEx.NumLock ? (Key)(uint)'0' : Key.InsertChar;
  826. case ConsoleKey.NumPad1:
  827. return keyInfoEx.NumLock ? (Key)(uint)'1' : Key.End;
  828. case ConsoleKey.NumPad2:
  829. return keyInfoEx.NumLock ? (Key)(uint)'2' : Key.CursorDown;
  830. case ConsoleKey.NumPad3:
  831. return keyInfoEx.NumLock ? (Key)(uint)'3' : Key.PageDown;
  832. case ConsoleKey.NumPad4:
  833. return keyInfoEx.NumLock ? (Key)(uint)'4' : Key.CursorLeft;
  834. case ConsoleKey.NumPad5:
  835. return keyInfoEx.NumLock ? (Key)(uint)'5' : (Key)((uint)keyInfo.KeyChar);
  836. case ConsoleKey.NumPad6:
  837. return keyInfoEx.NumLock ? (Key)(uint)'6' : Key.CursorRight;
  838. case ConsoleKey.NumPad7:
  839. return keyInfoEx.NumLock ? (Key)(uint)'7' : Key.Home;
  840. case ConsoleKey.NumPad8:
  841. return keyInfoEx.NumLock ? (Key)(uint)'8' : Key.CursorUp;
  842. case ConsoleKey.NumPad9:
  843. return keyInfoEx.NumLock ? (Key)(uint)'9' : Key.PageUp;
  844. case ConsoleKey.Oem1:
  845. case ConsoleKey.Oem2:
  846. case ConsoleKey.Oem3:
  847. case ConsoleKey.Oem4:
  848. case ConsoleKey.Oem5:
  849. case ConsoleKey.Oem6:
  850. case ConsoleKey.Oem7:
  851. case ConsoleKey.Oem8:
  852. case ConsoleKey.Oem102:
  853. case ConsoleKey.OemPeriod:
  854. case ConsoleKey.OemComma:
  855. case ConsoleKey.OemPlus:
  856. case ConsoleKey.OemMinus:
  857. if (keyInfo.KeyChar == 0)
  858. return Key.Unknown;
  859. return (Key)((uint)keyInfo.KeyChar);
  860. }
  861. var key = keyInfo.Key;
  862. //var alphaBase = ((keyInfo.Modifiers == ConsoleModifiers.Shift) ^ (keyInfoEx.CapsLock)) ? 'A' : 'a';
  863. if (key >= ConsoleKey.A && key <= ConsoleKey.Z) {
  864. var delta = key - ConsoleKey.A;
  865. if (keyInfo.Modifiers == ConsoleModifiers.Control)
  866. return (Key)((uint)Key.ControlA + delta);
  867. if (keyInfo.Modifiers == ConsoleModifiers.Alt)
  868. return (Key)(((uint)Key.AltMask) | ((uint)'A' + delta));
  869. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  870. if (keyInfo.KeyChar == 0)
  871. return (Key)(((uint)Key.AltMask) + ((uint)Key.ControlA + delta));
  872. else
  873. return (Key)((uint)keyInfo.KeyChar);
  874. }
  875. //return (Key)((uint)alphaBase + delta);
  876. return (Key)((uint)keyInfo.KeyChar);
  877. }
  878. if (key >= ConsoleKey.D0 && key <= ConsoleKey.D9) {
  879. var delta = key - ConsoleKey.D0;
  880. if (keyInfo.Modifiers == ConsoleModifiers.Alt)
  881. return (Key)(((uint)Key.AltMask) | ((uint)'0' + delta));
  882. return (Key)((uint)keyInfo.KeyChar);
  883. }
  884. if (key >= ConsoleKey.F1 && key <= ConsoleKey.F12) {
  885. var delta = key - ConsoleKey.F1;
  886. return (Key)((int)Key.F1 + delta);
  887. }
  888. return (Key)(0xffffffff);
  889. }
  890. private static Key MapKeyModifiers (ConsoleKeyInfo keyInfo, Key key)
  891. {
  892. Key keyMod = new Key ();
  893. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Shift))
  894. keyMod = Key.ShiftMask;
  895. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control))
  896. keyMod |= Key.CtrlMask;
  897. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt))
  898. keyMod |= Key.AltMask;
  899. return keyMod != Key.ControlSpace ? keyMod | key : key;
  900. }
  901. public override void Init (Action terminalResized)
  902. {
  903. TerminalResized = terminalResized;
  904. SetupColorsAndBorders ();
  905. }
  906. void ResizeScreen ()
  907. {
  908. OutputBuffer = new WindowsConsole.CharInfo [Rows * Cols];
  909. Clip = new Rect (0, 0, Cols, Rows);
  910. damageRegion = new WindowsConsole.SmallRect () {
  911. Top = 0,
  912. Left = 0,
  913. Bottom = (short)Rows,
  914. Right = (short)Cols
  915. };
  916. }
  917. void UpdateOffScreen ()
  918. {
  919. for (int row = 0; row < rows; row++)
  920. for (int col = 0; col < cols; col++) {
  921. int position = row * cols + col;
  922. OutputBuffer [position].Attributes = (ushort)Colors.TopLevel.Normal;
  923. OutputBuffer [position].Char.UnicodeChar = ' ';
  924. }
  925. }
  926. int ccol, crow;
  927. public override void Move (int col, int row)
  928. {
  929. ccol = col;
  930. crow = row;
  931. }
  932. public override void AddRune (Rune rune)
  933. {
  934. var position = crow * Cols + ccol;
  935. if (Clip.Contains (ccol, crow)) {
  936. OutputBuffer [position].Attributes = (ushort)currentAttribute;
  937. OutputBuffer [position].Char.UnicodeChar = (char)rune;
  938. WindowsConsole.SmallRect.Update (ref damageRegion, (short)ccol, (short)crow);
  939. }
  940. ccol++;
  941. var runeWidth = Rune.ColumnWidth (rune);
  942. if (runeWidth > 1) {
  943. for (int i = 1; i < runeWidth; i++) {
  944. AddStr (" ");
  945. }
  946. }
  947. //if (ccol == Cols) {
  948. // ccol = 0;
  949. // if (crow + 1 < Rows)
  950. // crow++;
  951. //}
  952. if (sync)
  953. UpdateScreen ();
  954. }
  955. public override void AddStr (ustring str)
  956. {
  957. foreach (var rune in str)
  958. AddRune (rune);
  959. }
  960. int currentAttribute;
  961. CancellationTokenSource tokenSource = new CancellationTokenSource ();
  962. public override void SetAttribute (Attribute c)
  963. {
  964. currentAttribute = c.value;
  965. }
  966. Attribute MakeColor (ConsoleColor f, ConsoleColor b)
  967. {
  968. // Encode the colors into the int value.
  969. return new Attribute () {
  970. value = ((int)f | (int)b << 4),
  971. foreground = (Color)f,
  972. background = (Color)b
  973. };
  974. }
  975. public override Attribute MakeAttribute (Color fore, Color back)
  976. {
  977. return MakeColor ((ConsoleColor)fore, (ConsoleColor)back);
  978. }
  979. public override void Refresh ()
  980. {
  981. UpdateScreen ();
  982. #if false
  983. var bufferCoords = new WindowsConsole.Coord (){
  984. X = (short)Clip.Width,
  985. Y = (short)Clip.Height
  986. };
  987. var window = new WindowsConsole.SmallRect (){
  988. Top = 0,
  989. Left = 0,
  990. Right = (short)Clip.Right,
  991. Bottom = (short)Clip.Bottom
  992. };
  993. UpdateCursor();
  994. winConsole.WriteToConsole (OutputBuffer, bufferCoords, window);
  995. #endif
  996. }
  997. public override void UpdateScreen ()
  998. {
  999. if (damageRegion.Left == -1)
  1000. return;
  1001. var bufferCoords = new WindowsConsole.Coord () {
  1002. X = (short)Clip.Width,
  1003. Y = (short)Clip.Height
  1004. };
  1005. var window = new WindowsConsole.SmallRect () {
  1006. Top = 0,
  1007. Left = 0,
  1008. Right = (short)Clip.Right,
  1009. Bottom = (short)Clip.Bottom
  1010. };
  1011. UpdateCursor ();
  1012. winConsole.WriteToConsole (OutputBuffer, bufferCoords, damageRegion);
  1013. // System.Diagnostics.Debugger.Log(0, "debug", $"Region={damageRegion.Right - damageRegion.Left},{damageRegion.Bottom - damageRegion.Top}\n");
  1014. WindowsConsole.SmallRect.MakeEmpty (ref damageRegion);
  1015. }
  1016. public override void UpdateCursor ()
  1017. {
  1018. var position = new WindowsConsole.Coord () {
  1019. X = (short)ccol,
  1020. Y = (short)crow
  1021. };
  1022. winConsole.SetCursorPosition (position);
  1023. }
  1024. public override void End ()
  1025. {
  1026. winConsole.Cleanup ();
  1027. }
  1028. #region Unused
  1029. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  1030. {
  1031. }
  1032. public override void SetColors (short foregroundColorId, short backgroundColorId)
  1033. {
  1034. }
  1035. public override void Suspend ()
  1036. {
  1037. }
  1038. public override void StartReportingMouseMoves ()
  1039. {
  1040. }
  1041. public override void StopReportingMouseMoves ()
  1042. {
  1043. }
  1044. public override void UncookMouse ()
  1045. {
  1046. }
  1047. public override void CookMouse ()
  1048. {
  1049. }
  1050. #endregion
  1051. }
  1052. }