WindowsDriver.cs 39 KB

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