WindowsDriver.cs 42 KB

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