WindowsDriver.cs 38 KB

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