WindowsDriver.cs 36 KB

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