WindowsDriver.cs 39 KB

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