WindowsDriver.cs 42 KB

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