WindowsDriver.cs 37 KB

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