WindowsDriver.cs 42 KB

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