WindowsDriver.cs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467
  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. ReadFromConsoleOutput (new Size (Console.WindowWidth, Console.WindowHeight), coords, ref window);
  57. }
  58. return WriteConsoleOutput (ScreenBuffer, charInfoBuffer, coords, new Coord () { X = window.Left, Y = window.Top }, ref window);
  59. }
  60. public void ReadFromConsoleOutput (Size size, Coord coords, ref SmallRect window)
  61. {
  62. ScreenBuffer = CreateConsoleScreenBuffer (
  63. DesiredAccess.GenericRead | DesiredAccess.GenericWrite,
  64. ShareMode.FileShareRead | ShareMode.FileShareWrite,
  65. IntPtr.Zero,
  66. 1,
  67. IntPtr.Zero
  68. );
  69. if (ScreenBuffer == INVALID_HANDLE_VALUE) {
  70. var err = Marshal.GetLastWin32Error ();
  71. if (err != 0)
  72. throw new System.ComponentModel.Win32Exception (err);
  73. }
  74. if (!SetConsoleActiveScreenBuffer (ScreenBuffer)) {
  75. var err = Marshal.GetLastWin32Error ();
  76. throw new System.ComponentModel.Win32Exception (err);
  77. }
  78. OriginalStdOutChars = new CharInfo [size.Height * size.Width];
  79. ReadConsoleOutput (OutputHandle, OriginalStdOutChars, coords, new Coord () { X = 0, Y = 0 }, ref window);
  80. }
  81. public bool SetCursorPosition (Coord position)
  82. {
  83. return SetConsoleCursorPosition (ScreenBuffer, position);
  84. }
  85. public void Cleanup ()
  86. {
  87. ConsoleMode = originalConsoleMode;
  88. //ContinueListeningForConsoleEvents = false;
  89. if (!SetConsoleActiveScreenBuffer (OutputHandle)) {
  90. var err = Marshal.GetLastWin32Error ();
  91. Console.WriteLine ("Error: {0}", err);
  92. }
  93. if (ScreenBuffer != IntPtr.Zero)
  94. CloseHandle (ScreenBuffer);
  95. ScreenBuffer = IntPtr.Zero;
  96. }
  97. //bool ContinueListeningForConsoleEvents = true;
  98. public uint ConsoleMode {
  99. get {
  100. uint v;
  101. GetConsoleMode (InputHandle, out v);
  102. return v;
  103. }
  104. set {
  105. SetConsoleMode (InputHandle, value);
  106. }
  107. }
  108. public bool HeightAsBuffer { get; set; }
  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. var p = new Point () {
  619. X = mouseEvent.MousePosition.X,
  620. Y = mouseEvent.MousePosition.Y
  621. };
  622. if ((mouseEvent.ButtonState != 0 && mouseEvent.EventFlags == 0 && LastMouseButtonPressed == null && !IsButtonDoubleClicked) ||
  623. (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved &&
  624. mouseEvent.ButtonState != 0 && !IsButtonReleased && !IsButtonDoubleClicked)) {
  625. switch (mouseEvent.ButtonState) {
  626. case WindowsConsole.ButtonState.Button1Pressed:
  627. mouseFlag = MouseFlags.Button1Pressed;
  628. break;
  629. case WindowsConsole.ButtonState.Button2Pressed:
  630. mouseFlag = MouseFlags.Button2Pressed;
  631. break;
  632. case WindowsConsole.ButtonState.RightmostButtonPressed:
  633. mouseFlag = MouseFlags.Button3Pressed;
  634. break;
  635. }
  636. if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  637. mouseFlag |= MouseFlags.ReportMousePosition;
  638. point = new Point ();
  639. IsButtonReleased = false;
  640. } else {
  641. point = new Point () {
  642. X = mouseEvent.MousePosition.X,
  643. Y = mouseEvent.MousePosition.Y
  644. };
  645. }
  646. LastMouseButtonPressed = mouseEvent.ButtonState;
  647. IsButtonPressed = true;
  648. if ((mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  649. Application.MainLoop.AddIdle (() => {
  650. ProcessContinuousButtonPressedAsync (mouseEvent, mouseFlag).ConfigureAwait (false);
  651. return false;
  652. });
  653. }
  654. } else if ((mouseEvent.EventFlags == 0 || mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) &&
  655. LastMouseButtonPressed != null && !IsButtonReleased && !IsButtonDoubleClicked) {
  656. switch (LastMouseButtonPressed) {
  657. case WindowsConsole.ButtonState.Button1Pressed:
  658. mouseFlag = MouseFlags.Button1Released;
  659. break;
  660. case WindowsConsole.ButtonState.Button2Pressed:
  661. mouseFlag = MouseFlags.Button2Released;
  662. break;
  663. case WindowsConsole.ButtonState.RightmostButtonPressed:
  664. mouseFlag = MouseFlags.Button3Released;
  665. break;
  666. }
  667. IsButtonPressed = false;
  668. IsButtonReleased = true;
  669. } else if ((mouseEvent.EventFlags == 0 || mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) &&
  670. IsButtonReleased && p == point) {
  671. switch (LastMouseButtonPressed) {
  672. case WindowsConsole.ButtonState.Button1Pressed:
  673. mouseFlag = MouseFlags.Button1Clicked;
  674. break;
  675. case WindowsConsole.ButtonState.Button2Pressed:
  676. mouseFlag = MouseFlags.Button2Clicked;
  677. break;
  678. case WindowsConsole.ButtonState.RightmostButtonPressed:
  679. mouseFlag = MouseFlags.Button3Clicked;
  680. break;
  681. }
  682. point = new Point () {
  683. X = mouseEvent.MousePosition.X,
  684. Y = mouseEvent.MousePosition.Y
  685. };
  686. LastMouseButtonPressed = null;
  687. IsButtonReleased = false;
  688. } else if (mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.DoubleClick)) {
  689. switch (mouseEvent.ButtonState) {
  690. case WindowsConsole.ButtonState.Button1Pressed:
  691. mouseFlag = MouseFlags.Button1DoubleClicked;
  692. break;
  693. case WindowsConsole.ButtonState.Button2Pressed:
  694. mouseFlag = MouseFlags.Button2DoubleClicked;
  695. break;
  696. case WindowsConsole.ButtonState.RightmostButtonPressed:
  697. mouseFlag = MouseFlags.Button3DoubleClicked;
  698. break;
  699. }
  700. IsButtonDoubleClicked = true;
  701. } else if (mouseEvent.EventFlags == 0 && mouseEvent.ButtonState != 0 && IsButtonDoubleClicked) {
  702. switch (mouseEvent.ButtonState) {
  703. case WindowsConsole.ButtonState.Button1Pressed:
  704. mouseFlag = MouseFlags.Button1TripleClicked;
  705. break;
  706. case WindowsConsole.ButtonState.Button2Pressed:
  707. mouseFlag = MouseFlags.Button2TripleClicked;
  708. break;
  709. case WindowsConsole.ButtonState.RightmostButtonPressed:
  710. mouseFlag = MouseFlags.Button3TripleClicked;
  711. break;
  712. }
  713. IsButtonDoubleClicked = false;
  714. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled) {
  715. switch (mouseEvent.ButtonState) {
  716. case WindowsConsole.ButtonState.WheeledUp:
  717. mouseFlag = MouseFlags.WheeledUp;
  718. break;
  719. case WindowsConsole.ButtonState.WheeledDown:
  720. mouseFlag = MouseFlags.WheeledDown;
  721. break;
  722. }
  723. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled &&
  724. mouseEvent.ControlKeyState == WindowsConsole.ControlKeyState.ShiftPressed) {
  725. switch (mouseEvent.ButtonState) {
  726. case WindowsConsole.ButtonState.WheeledUp:
  727. mouseFlag = MouseFlags.WheeledLeft;
  728. break;
  729. case WindowsConsole.ButtonState.WheeledDown:
  730. mouseFlag = MouseFlags.WheeledRight;
  731. break;
  732. }
  733. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  734. if (mouseEvent.MousePosition.X != point.X || mouseEvent.MousePosition.Y != point.Y) {
  735. mouseFlag = MouseFlags.ReportMousePosition;
  736. point = new Point ();
  737. } else {
  738. mouseFlag = 0;
  739. }
  740. } else if (mouseEvent.ButtonState == 0 && mouseEvent.EventFlags == 0) {
  741. mouseFlag = 0;
  742. }
  743. mouseFlag = SetControlKeyStates (mouseEvent, mouseFlag);
  744. return new MouseEvent () {
  745. X = mouseEvent.MousePosition.X,
  746. Y = mouseEvent.MousePosition.Y,
  747. Flags = mouseFlag
  748. };
  749. }
  750. async Task ProcessButtonDoubleClickedAsync ()
  751. {
  752. await Task.Delay (200);
  753. IsButtonDoubleClicked = false;
  754. }
  755. async Task ProcessContinuousButtonPressedAsync (WindowsConsole.MouseEventRecord mouseEvent, MouseFlags mouseFlag)
  756. {
  757. while (IsButtonPressed) {
  758. await Task.Delay (100);
  759. var me = new MouseEvent () {
  760. X = mouseEvent.MousePosition.X,
  761. Y = mouseEvent.MousePosition.Y,
  762. Flags = mouseFlag
  763. };
  764. var view = Application.wantContinuousButtonPressedView;
  765. if (view == null) {
  766. break;
  767. }
  768. if (IsButtonPressed && (mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  769. mouseHandler (me);
  770. }
  771. }
  772. }
  773. static MouseFlags SetControlKeyStates (WindowsConsole.MouseEventRecord mouseEvent, MouseFlags mouseFlag)
  774. {
  775. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed) ||
  776. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed))
  777. mouseFlag |= MouseFlags.ButtonCtrl;
  778. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed))
  779. mouseFlag |= MouseFlags.ButtonShift;
  780. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed) ||
  781. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed))
  782. mouseFlag |= MouseFlags.ButtonAlt;
  783. return mouseFlag;
  784. }
  785. KeyModifiers keyModifiers;
  786. public WindowsConsole.ConsoleKeyInfoEx ToConsoleKeyInfoEx (WindowsConsole.KeyEventRecord keyEvent)
  787. {
  788. var state = keyEvent.dwControlKeyState;
  789. bool shift = (state & WindowsConsole.ControlKeyState.ShiftPressed) != 0;
  790. bool alt = (state & (WindowsConsole.ControlKeyState.LeftAltPressed | WindowsConsole.ControlKeyState.RightAltPressed)) != 0;
  791. bool control = (state & (WindowsConsole.ControlKeyState.LeftControlPressed | WindowsConsole.ControlKeyState.RightControlPressed)) != 0;
  792. bool capslock = (state & (WindowsConsole.ControlKeyState.CapslockOn)) != 0;
  793. bool numlock = (state & (WindowsConsole.ControlKeyState.NumlockOn)) != 0;
  794. bool scrolllock = (state & (WindowsConsole.ControlKeyState.ScrolllockOn)) != 0;
  795. if (keyModifiers == null)
  796. keyModifiers = new KeyModifiers ();
  797. if (shift)
  798. keyModifiers.Shift = shift;
  799. if (alt)
  800. keyModifiers.Alt = alt;
  801. if (control)
  802. keyModifiers.Ctrl = control;
  803. if (capslock)
  804. keyModifiers.Capslock = capslock;
  805. if (numlock)
  806. keyModifiers.Numlock = numlock;
  807. if (scrolllock)
  808. keyModifiers.Scrolllock = scrolllock;
  809. var ConsoleKeyInfo = new ConsoleKeyInfo (keyEvent.UnicodeChar, (ConsoleKey)keyEvent.wVirtualKeyCode, shift, alt, control);
  810. return new WindowsConsole.ConsoleKeyInfoEx (ConsoleKeyInfo, capslock, numlock);
  811. }
  812. public Key MapKey (WindowsConsole.ConsoleKeyInfoEx keyInfoEx)
  813. {
  814. var keyInfo = keyInfoEx.consoleKeyInfo;
  815. switch (keyInfo.Key) {
  816. case ConsoleKey.Escape:
  817. return MapKeyModifiers (keyInfo, Key.Esc);
  818. case ConsoleKey.Tab:
  819. return keyInfo.Modifiers == ConsoleModifiers.Shift ? Key.BackTab : Key.Tab;
  820. case ConsoleKey.Home:
  821. return MapKeyModifiers (keyInfo, Key.Home);
  822. case ConsoleKey.End:
  823. return MapKeyModifiers (keyInfo, Key.End);
  824. case ConsoleKey.LeftArrow:
  825. return MapKeyModifiers (keyInfo, Key.CursorLeft);
  826. case ConsoleKey.RightArrow:
  827. return MapKeyModifiers (keyInfo, Key.CursorRight);
  828. case ConsoleKey.UpArrow:
  829. return MapKeyModifiers (keyInfo, Key.CursorUp);
  830. case ConsoleKey.DownArrow:
  831. return MapKeyModifiers (keyInfo, Key.CursorDown);
  832. case ConsoleKey.PageUp:
  833. return MapKeyModifiers (keyInfo, Key.PageUp);
  834. case ConsoleKey.PageDown:
  835. return MapKeyModifiers (keyInfo, Key.PageDown);
  836. case ConsoleKey.Enter:
  837. return MapKeyModifiers (keyInfo, Key.Enter);
  838. case ConsoleKey.Spacebar:
  839. return MapKeyModifiers (keyInfo, Key.Space);
  840. case ConsoleKey.Backspace:
  841. return MapKeyModifiers (keyInfo, Key.Backspace);
  842. case ConsoleKey.Delete:
  843. return MapKeyModifiers (keyInfo, Key.DeleteChar);
  844. case ConsoleKey.Insert:
  845. return MapKeyModifiers (keyInfo, Key.InsertChar);
  846. case ConsoleKey.NumPad0:
  847. return keyInfoEx.NumLock ? Key.D0 : Key.InsertChar;
  848. case ConsoleKey.NumPad1:
  849. return keyInfoEx.NumLock ? Key.D1 : Key.End;
  850. case ConsoleKey.NumPad2:
  851. return keyInfoEx.NumLock ? Key.D2 : Key.CursorDown;
  852. case ConsoleKey.NumPad3:
  853. return keyInfoEx.NumLock ? Key.D3 : Key.PageDown;
  854. case ConsoleKey.NumPad4:
  855. return keyInfoEx.NumLock ? Key.D4 : Key.CursorLeft;
  856. case ConsoleKey.NumPad5:
  857. return keyInfoEx.NumLock ? Key.D5 : (Key)((uint)keyInfo.KeyChar);
  858. case ConsoleKey.NumPad6:
  859. return keyInfoEx.NumLock ? Key.D6 : Key.CursorRight;
  860. case ConsoleKey.NumPad7:
  861. return keyInfoEx.NumLock ? Key.D7 : Key.Home;
  862. case ConsoleKey.NumPad8:
  863. return keyInfoEx.NumLock ? Key.D8 : Key.CursorUp;
  864. case ConsoleKey.NumPad9:
  865. return keyInfoEx.NumLock ? Key.D9 : Key.PageUp;
  866. case ConsoleKey.Oem1:
  867. case ConsoleKey.Oem2:
  868. case ConsoleKey.Oem3:
  869. case ConsoleKey.Oem4:
  870. case ConsoleKey.Oem5:
  871. case ConsoleKey.Oem6:
  872. case ConsoleKey.Oem7:
  873. case ConsoleKey.Oem8:
  874. case ConsoleKey.Oem102:
  875. case ConsoleKey.OemPeriod:
  876. case ConsoleKey.OemComma:
  877. case ConsoleKey.OemPlus:
  878. case ConsoleKey.OemMinus:
  879. if (keyInfo.KeyChar == 0)
  880. return Key.Unknown;
  881. return (Key)((uint)keyInfo.KeyChar);
  882. }
  883. var key = keyInfo.Key;
  884. //var alphaBase = ((keyInfo.Modifiers == ConsoleModifiers.Shift) ^ (keyInfoEx.CapsLock)) ? 'A' : 'a';
  885. if (key >= ConsoleKey.A && key <= ConsoleKey.Z) {
  886. var delta = key - ConsoleKey.A;
  887. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  888. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.A + delta));
  889. }
  890. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  891. return (Key)(((uint)Key.AltMask) | ((uint)Key.A + delta));
  892. }
  893. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  894. if (keyInfo.KeyChar == 0 || (keyInfo.KeyChar != 0 && keyInfo.KeyChar >= 1 && keyInfo.KeyChar <= 26)) {
  895. return MapKeyModifiers (keyInfo, (Key)((uint)Key.A + delta));
  896. }
  897. }
  898. //return (Key)((uint)alphaBase + delta);
  899. return (Key)((uint)keyInfo.KeyChar);
  900. }
  901. if (key >= ConsoleKey.D0 && key <= ConsoleKey.D9) {
  902. var delta = key - ConsoleKey.D0;
  903. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  904. return (Key)(((uint)Key.AltMask) | ((uint)Key.D0 + delta));
  905. }
  906. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  907. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.D0 + delta));
  908. }
  909. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  910. if (keyInfo.KeyChar == 0 || keyInfo.KeyChar == 30) {
  911. return MapKeyModifiers (keyInfo, (Key)((uint)Key.D0 + delta));
  912. }
  913. }
  914. return (Key)((uint)keyInfo.KeyChar);
  915. }
  916. if (key >= ConsoleKey.F1 && key <= ConsoleKey.F12) {
  917. var delta = key - ConsoleKey.F1;
  918. if ((keyInfo.Modifiers & (ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  919. return MapKeyModifiers (keyInfo, (Key)((uint)Key.F1 + delta));
  920. }
  921. return (Key)((uint)Key.F1 + delta);
  922. }
  923. if (keyInfo.KeyChar != 0) {
  924. return (Key)((uint)keyInfo.KeyChar);
  925. }
  926. return (Key)(0xffffffff);
  927. }
  928. Key MapKeyModifiers (ConsoleKeyInfo keyInfo, Key key)
  929. {
  930. Key keyMod = new Key ();
  931. if ((keyInfo.Modifiers & ConsoleModifiers.Shift) != 0)
  932. keyMod = Key.ShiftMask;
  933. if ((keyInfo.Modifiers & ConsoleModifiers.Control) != 0)
  934. keyMod |= Key.CtrlMask;
  935. if ((keyInfo.Modifiers & ConsoleModifiers.Alt) != 0)
  936. keyMod |= Key.AltMask;
  937. return keyMod != Key.Null ? keyMod | key : key;
  938. }
  939. public override void Init (Action terminalResized)
  940. {
  941. TerminalResized = terminalResized;
  942. cols = Console.WindowWidth;
  943. rows = Console.WindowHeight;
  944. #if false
  945. winConsole.ShowWindow (WindowsConsole.RESTORE);
  946. #endif
  947. WindowsConsole.SmallRect.MakeEmpty (ref damageRegion);
  948. ResizeScreen ();
  949. UpdateOffScreen ();
  950. Colors.TopLevel = new ColorScheme ();
  951. Colors.Base = new ColorScheme ();
  952. Colors.Dialog = new ColorScheme ();
  953. Colors.Menu = new ColorScheme ();
  954. Colors.Error = new ColorScheme ();
  955. Colors.TopLevel.Normal = MakeColor (ConsoleColor.Green, ConsoleColor.Black);
  956. Colors.TopLevel.Focus = MakeColor (ConsoleColor.White, ConsoleColor.DarkCyan);
  957. Colors.TopLevel.HotNormal = MakeColor (ConsoleColor.DarkYellow, ConsoleColor.Black);
  958. Colors.TopLevel.HotFocus = MakeColor (ConsoleColor.DarkBlue, ConsoleColor.DarkCyan);
  959. Colors.Base.Normal = MakeColor (ConsoleColor.White, ConsoleColor.DarkBlue);
  960. Colors.Base.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
  961. Colors.Base.HotNormal = MakeColor (ConsoleColor.DarkCyan, ConsoleColor.DarkBlue);
  962. Colors.Base.HotFocus = MakeColor (ConsoleColor.Blue, ConsoleColor.Gray);
  963. Colors.Menu.Normal = MakeColor (ConsoleColor.White, ConsoleColor.DarkGray);
  964. Colors.Menu.Focus = MakeColor (ConsoleColor.White, ConsoleColor.Black);
  965. Colors.Menu.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.DarkGray);
  966. Colors.Menu.HotFocus = MakeColor (ConsoleColor.Yellow, ConsoleColor.Black);
  967. Colors.Menu.Disabled = MakeColor (ConsoleColor.Gray, ConsoleColor.DarkGray);
  968. Colors.Dialog.Normal = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
  969. Colors.Dialog.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.DarkGray);
  970. Colors.Dialog.HotNormal = MakeColor (ConsoleColor.DarkBlue, ConsoleColor.Gray);
  971. Colors.Dialog.HotFocus = MakeColor (ConsoleColor.DarkBlue, ConsoleColor.DarkGray);
  972. Colors.Error.Normal = MakeColor (ConsoleColor.DarkRed, ConsoleColor.White);
  973. Colors.Error.Focus = MakeColor (ConsoleColor.White, ConsoleColor.DarkRed);
  974. Colors.Error.HotNormal = MakeColor (ConsoleColor.Black, ConsoleColor.White);
  975. Colors.Error.HotFocus = MakeColor (ConsoleColor.Black, ConsoleColor.DarkRed);
  976. }
  977. void ResizeScreen ()
  978. {
  979. OutputBuffer = new WindowsConsole.CharInfo [Rows * Cols];
  980. Clip = new Rect (0, 0, Cols, Rows);
  981. damageRegion = new WindowsConsole.SmallRect () {
  982. Top = 0,
  983. Left = 0,
  984. Bottom = (short)Rows,
  985. Right = (short)Cols
  986. };
  987. }
  988. void UpdateOffScreen ()
  989. {
  990. for (int row = 0; row < rows; row++) {
  991. for (int col = 0; col < cols; col++) {
  992. int position = row * cols + col;
  993. OutputBuffer [position].Attributes = (ushort)Colors.TopLevel.Normal;
  994. OutputBuffer [position].Char.UnicodeChar = ' ';
  995. }
  996. }
  997. winChanging = false;
  998. }
  999. int ccol, crow;
  1000. public override void Move (int col, int row)
  1001. {
  1002. ccol = col;
  1003. crow = row;
  1004. }
  1005. public override void AddRune (Rune rune)
  1006. {
  1007. rune = MakePrintable (rune);
  1008. var position = crow * Cols + ccol;
  1009. if (Clip.Contains (ccol, crow)) {
  1010. OutputBuffer [position].Attributes = (ushort)currentAttribute;
  1011. OutputBuffer [position].Char.UnicodeChar = (char)rune;
  1012. WindowsConsole.SmallRect.Update (ref damageRegion, (short)ccol, (short)crow);
  1013. }
  1014. ccol++;
  1015. var runeWidth = Rune.ColumnWidth (rune);
  1016. if (runeWidth > 1) {
  1017. for (int i = 1; i < runeWidth; i++) {
  1018. AddStr (" ");
  1019. }
  1020. }
  1021. //if (ccol == Cols) {
  1022. // ccol = 0;
  1023. // if (crow + 1 < Rows)
  1024. // crow++;
  1025. //}
  1026. if (sync)
  1027. UpdateScreen ();
  1028. }
  1029. public override void AddStr (ustring str)
  1030. {
  1031. foreach (var rune in str)
  1032. AddRune (rune);
  1033. }
  1034. int currentAttribute;
  1035. public override void SetAttribute (Attribute c)
  1036. {
  1037. currentAttribute = c.Value;
  1038. }
  1039. Attribute MakeColor (ConsoleColor f, ConsoleColor b)
  1040. {
  1041. // Encode the colors into the int value.
  1042. return new Attribute (
  1043. value: ((int)f | (int)b << 4),
  1044. foreground: (Color)f,
  1045. background: (Color)b
  1046. );
  1047. }
  1048. public override Attribute MakeAttribute (Color fore, Color back)
  1049. {
  1050. return MakeColor ((ConsoleColor)fore, (ConsoleColor)back);
  1051. }
  1052. public override void Refresh ()
  1053. {
  1054. UpdateScreen ();
  1055. #if false
  1056. var bufferCoords = new WindowsConsole.Coord (){
  1057. X = (short)Clip.Width,
  1058. Y = (short)Clip.Height
  1059. };
  1060. var window = new WindowsConsole.SmallRect (){
  1061. Top = 0,
  1062. Left = 0,
  1063. Right = (short)Clip.Right,
  1064. Bottom = (short)Clip.Bottom
  1065. };
  1066. UpdateCursor();
  1067. winConsole.WriteToConsole (OutputBuffer, bufferCoords, window);
  1068. #endif
  1069. }
  1070. public override void UpdateScreen ()
  1071. {
  1072. if (damageRegion.Left == -1)
  1073. return;
  1074. var bufferCoords = new WindowsConsole.Coord () {
  1075. X = (short)Clip.Width,
  1076. Y = (short)Clip.Height
  1077. };
  1078. //var window = new WindowsConsole.SmallRect () {
  1079. // Top = 0,
  1080. // Left = 0,
  1081. // Right = (short)Clip.Right,
  1082. // Bottom = (short)Clip.Bottom
  1083. //};
  1084. UpdateCursor ();
  1085. winConsole.WriteToConsole (OutputBuffer, bufferCoords, damageRegion);
  1086. // System.Diagnostics.Debugger.Log(0, "debug", $"Region={damageRegion.Right - damageRegion.Left},{damageRegion.Bottom - damageRegion.Top}\n");
  1087. WindowsConsole.SmallRect.MakeEmpty (ref damageRegion);
  1088. }
  1089. public override void UpdateCursor ()
  1090. {
  1091. var position = new WindowsConsole.Coord () {
  1092. X = (short)ccol,
  1093. Y = (short)crow
  1094. };
  1095. winConsole.SetCursorPosition (position);
  1096. }
  1097. public override void End ()
  1098. {
  1099. winConsole.Cleanup ();
  1100. }
  1101. public override Attribute GetAttribute ()
  1102. {
  1103. return currentAttribute;
  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. // Nor working yet.
  1169. //Task.Run (CheckWinChange);
  1170. }
  1171. void WindowsInputHandler ()
  1172. {
  1173. while (true) {
  1174. waitForProbe.Wait ();
  1175. waitForProbe.Reset ();
  1176. result = winConsole.ReadConsoleInput ();
  1177. eventReady.Set ();
  1178. }
  1179. }
  1180. //void CheckWinChange ()
  1181. //{
  1182. // while (true) {
  1183. // winChange.Wait ();
  1184. // winChange.Reset ();
  1185. // WaitWinChange ();
  1186. // winChanged = true;
  1187. // eventReady.Set ();
  1188. // }
  1189. //}
  1190. //void WaitWinChange ()
  1191. //{
  1192. // while (true) {
  1193. // if (!consoleDriver.HeightAsBuffer) {
  1194. // windowSize = new Size (Console.WindowWidth, Console.WindowHeight);
  1195. // if (windowSize.Height < consoleDriver.Rows) {
  1196. // // I still haven't been able to find a way to capture the shrinking in height.
  1197. // //return;
  1198. // }
  1199. // }
  1200. // }
  1201. //}
  1202. void IMainLoopDriver.Wakeup ()
  1203. {
  1204. //tokenSource.Cancel ();
  1205. eventReady.Set ();
  1206. }
  1207. bool IMainLoopDriver.EventsPending (bool wait)
  1208. {
  1209. if (CheckTimers (wait, out var waitTimeout)) {
  1210. return true;
  1211. }
  1212. result = null;
  1213. waitForProbe.Set ();
  1214. // Nor working yet.
  1215. //winChange.Set ();
  1216. try {
  1217. if (!tokenSource.IsCancellationRequested) {
  1218. eventReady.Wait (waitTimeout, tokenSource.Token);
  1219. }
  1220. } catch (OperationCanceledException) {
  1221. return true;
  1222. } finally {
  1223. eventReady.Reset ();
  1224. }
  1225. if (!tokenSource.IsCancellationRequested) {
  1226. //return result != null || CheckTimers (wait, out _) || winChanged;
  1227. return result != null || CheckTimers (wait, out _);
  1228. }
  1229. tokenSource.Dispose ();
  1230. tokenSource = new CancellationTokenSource ();
  1231. return true;
  1232. }
  1233. bool CheckTimers (bool wait, out int waitTimeout)
  1234. {
  1235. long now = DateTime.UtcNow.Ticks;
  1236. if (mainLoop.timeouts.Count > 0) {
  1237. waitTimeout = (int)((mainLoop.timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  1238. if (waitTimeout < 0)
  1239. return true;
  1240. } else {
  1241. waitTimeout = -1;
  1242. }
  1243. if (!wait)
  1244. waitTimeout = 0;
  1245. int ic;
  1246. lock (mainLoop.idleHandlers) {
  1247. ic = mainLoop.idleHandlers.Count;
  1248. }
  1249. return ic > 0;
  1250. }
  1251. void IMainLoopDriver.MainIteration ()
  1252. {
  1253. if (result != null) {
  1254. var inputEvent = result [0];
  1255. result = null;
  1256. ProcessInput?.Invoke (inputEvent);
  1257. }
  1258. //if (winChanged) {
  1259. // winChanged = false;
  1260. // WinChanged?.Invoke (windowSize);
  1261. //}
  1262. }
  1263. }
  1264. }