WindowsDriver.cs 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177
  1. #nullable enable
  2. //
  3. // WindowsDriver.cs: Windows specific driver
  4. //
  5. // HACK:
  6. // WindowsConsole/Terminal has two issues:
  7. // 1) Tearing can occur when the console is resized.
  8. // 2) The values provided during Init (and the first WindowsConsole.EventType.WindowBufferSize) are not correct.
  9. //
  10. // If HACK_CHECK_WINCHANGED is defined then we ignore WindowsConsole.EventType.WindowBufferSize events
  11. // and instead check the console size every 500ms in a thread in WidowsMainLoop.
  12. // As of Windows 11 23H2 25947.1000 and/or WT 1.19.2682 tearing no longer occurs when using
  13. // the WindowsConsole.EventType.WindowBufferSize event. However, on Init the window size is
  14. // still incorrect so we still need this hack.
  15. #define HACK_CHECK_WINCHANGED
  16. using System.ComponentModel;
  17. using System.Diagnostics;
  18. using System.Runtime.InteropServices;
  19. namespace Terminal.Gui.Drivers;
  20. internal class WindowsDriver : ConsoleDriver
  21. {
  22. private readonly bool _isWindowsTerminal;
  23. private WindowsConsole.SmallRect _damageRegion;
  24. private bool _isButtonDoubleClicked;
  25. private bool _isButtonPressed;
  26. private bool _isButtonReleased;
  27. private bool _isOneFingerDoubleClicked;
  28. private WindowsConsole.ButtonState? _lastMouseButtonPressed;
  29. private WindowsMainLoop? _mainLoopDriver;
  30. private WindowsConsole.ExtendedCharInfo [] _outputBuffer = new WindowsConsole.ExtendedCharInfo [0 * 0];
  31. private Point? _point;
  32. private Point _pointMove;
  33. private bool _processButtonClick;
  34. public WindowsDriver ()
  35. {
  36. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  37. {
  38. WinConsole = new ();
  39. // otherwise we're probably running in unit tests
  40. Clipboard = new WindowsClipboard ();
  41. }
  42. else
  43. {
  44. Clipboard = new FakeDriver.FakeClipboard ();
  45. }
  46. // TODO: if some other Windows-based terminal supports true color, update this logic to not
  47. // force 16color mode (.e.g ConEmu which really doesn't work well at all).
  48. if (!RunningUnitTests)
  49. {
  50. WinConsole!.IsWindowsTerminal = _isWindowsTerminal =
  51. Environment.GetEnvironmentVariable ("WT_SESSION") is { }
  52. || Environment.GetEnvironmentVariable ("VSAPPIDNAME") != null;
  53. }
  54. if (!_isWindowsTerminal)
  55. {
  56. Force16Colors = true;
  57. }
  58. }
  59. public override bool SupportsTrueColor => RunningUnitTests || (Environment.OSVersion.Version.Build >= 14931 && _isWindowsTerminal);
  60. public WindowsConsole? WinConsole { get; private set; }
  61. public static WindowsConsole.KeyEventRecord FromVKPacketToKeyEventRecord (WindowsConsole.KeyEventRecord keyEvent)
  62. {
  63. if (keyEvent.wVirtualKeyCode != (ConsoleKeyMapping.VK)ConsoleKey.Packet)
  64. {
  65. return keyEvent;
  66. }
  67. var mod = new ConsoleModifiers ();
  68. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed))
  69. {
  70. mod |= ConsoleModifiers.Shift;
  71. }
  72. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed)
  73. || keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed))
  74. {
  75. mod |= ConsoleModifiers.Alt;
  76. }
  77. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed)
  78. || keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed))
  79. {
  80. mod |= ConsoleModifiers.Control;
  81. }
  82. var cKeyInfo = new ConsoleKeyInfo (
  83. keyEvent.UnicodeChar,
  84. (ConsoleKey)keyEvent.wVirtualKeyCode,
  85. mod.HasFlag (ConsoleModifiers.Shift),
  86. mod.HasFlag (ConsoleModifiers.Alt),
  87. mod.HasFlag (ConsoleModifiers.Control));
  88. cKeyInfo = ConsoleKeyMapping.DecodeVKPacketToKConsoleKeyInfo (cKeyInfo);
  89. uint scanCode = ConsoleKeyMapping.GetScanCodeFromConsoleKeyInfo (cKeyInfo);
  90. return new WindowsConsole.KeyEventRecord
  91. {
  92. UnicodeChar = cKeyInfo.KeyChar,
  93. bKeyDown = keyEvent.bKeyDown,
  94. dwControlKeyState = keyEvent.dwControlKeyState,
  95. wRepeatCount = keyEvent.wRepeatCount,
  96. wVirtualKeyCode = (ConsoleKeyMapping.VK)cKeyInfo.Key,
  97. wVirtualScanCode = (ushort)scanCode
  98. };
  99. }
  100. public override bool IsRuneSupported (Rune rune) { return base.IsRuneSupported (rune) && rune.IsBmp; }
  101. public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control)
  102. {
  103. var input = new WindowsConsole.InputRecord
  104. {
  105. EventType = WindowsConsole.EventType.Key
  106. };
  107. var keyEvent = new WindowsConsole.KeyEventRecord
  108. {
  109. bKeyDown = true
  110. };
  111. var controlKey = new WindowsConsole.ControlKeyState ();
  112. if (shift)
  113. {
  114. controlKey |= WindowsConsole.ControlKeyState.ShiftPressed;
  115. keyEvent.UnicodeChar = '\0';
  116. keyEvent.wVirtualKeyCode = ConsoleKeyMapping.VK.SHIFT;
  117. }
  118. if (alt)
  119. {
  120. controlKey |= WindowsConsole.ControlKeyState.LeftAltPressed;
  121. controlKey |= WindowsConsole.ControlKeyState.RightAltPressed;
  122. keyEvent.UnicodeChar = '\0';
  123. keyEvent.wVirtualKeyCode = ConsoleKeyMapping.VK.MENU;
  124. }
  125. if (control)
  126. {
  127. controlKey |= WindowsConsole.ControlKeyState.LeftControlPressed;
  128. controlKey |= WindowsConsole.ControlKeyState.RightControlPressed;
  129. keyEvent.UnicodeChar = '\0';
  130. keyEvent.wVirtualKeyCode = ConsoleKeyMapping.VK.CONTROL;
  131. }
  132. keyEvent.dwControlKeyState = controlKey;
  133. input.KeyEvent = keyEvent;
  134. if (shift || alt || control)
  135. {
  136. ProcessInput (input);
  137. }
  138. keyEvent.UnicodeChar = keyChar;
  139. //if ((uint)key < 255) {
  140. // keyEvent.wVirtualKeyCode = (ushort)key;
  141. //} else {
  142. // keyEvent.wVirtualKeyCode = '\0';
  143. //}
  144. keyEvent.wVirtualKeyCode = (ConsoleKeyMapping.VK)key;
  145. input.KeyEvent = keyEvent;
  146. try
  147. {
  148. ProcessInput (input);
  149. }
  150. catch (OverflowException)
  151. { }
  152. finally
  153. {
  154. keyEvent.bKeyDown = false;
  155. input.KeyEvent = keyEvent;
  156. ProcessInput (input);
  157. }
  158. }
  159. /// <inheritdoc />
  160. internal override IAnsiResponseParser GetParser () => _parser;
  161. public override void WriteRaw (string str)
  162. {
  163. WinConsole?.WriteANSI (str);
  164. }
  165. #region Not Implemented
  166. public override void Suspend () { throw new NotImplementedException (); }
  167. #endregion
  168. public static WindowsConsole.ConsoleKeyInfoEx ToConsoleKeyInfoEx (WindowsConsole.KeyEventRecord keyEvent)
  169. {
  170. WindowsConsole.ControlKeyState state = keyEvent.dwControlKeyState;
  171. bool shift = (state & WindowsConsole.ControlKeyState.ShiftPressed) != 0;
  172. bool alt = (state & (WindowsConsole.ControlKeyState.LeftAltPressed | WindowsConsole.ControlKeyState.RightAltPressed)) != 0;
  173. bool control = (state & (WindowsConsole.ControlKeyState.LeftControlPressed | WindowsConsole.ControlKeyState.RightControlPressed)) != 0;
  174. bool capslock = (state & WindowsConsole.ControlKeyState.CapslockOn) != 0;
  175. bool numlock = (state & WindowsConsole.ControlKeyState.NumlockOn) != 0;
  176. bool scrolllock = (state & WindowsConsole.ControlKeyState.ScrolllockOn) != 0;
  177. var cki = new ConsoleKeyInfo (keyEvent.UnicodeChar, (ConsoleKey)keyEvent.wVirtualKeyCode, shift, alt, control);
  178. return new WindowsConsole.ConsoleKeyInfoEx (cki, capslock, numlock, scrolllock);
  179. }
  180. #region Cursor Handling
  181. private CursorVisibility? _cachedCursorVisibility;
  182. public override void UpdateCursor ()
  183. {
  184. if (RunningUnitTests)
  185. {
  186. return;
  187. }
  188. if (Col < 0 || Row < 0 || Col >= Cols || Row >= Rows)
  189. {
  190. GetCursorVisibility (out CursorVisibility cursorVisibility);
  191. _cachedCursorVisibility = cursorVisibility;
  192. SetCursorVisibility (CursorVisibility.Invisible);
  193. return;
  194. }
  195. var position = new WindowsConsole.Coord
  196. {
  197. X = (short)Col,
  198. Y = (short)Row
  199. };
  200. if (Force16Colors)
  201. {
  202. WinConsole?.SetCursorPosition (position);
  203. }
  204. else
  205. {
  206. var sb = new StringBuilder ();
  207. EscSeqUtils.CSI_AppendCursorPosition (sb, position.Y + 1, position.X + 1);
  208. WinConsole?.WriteANSI (sb.ToString ());
  209. }
  210. if (_cachedCursorVisibility is { })
  211. {
  212. SetCursorVisibility (_cachedCursorVisibility.Value);
  213. }
  214. //EnsureCursorVisibility ();
  215. }
  216. /// <inheritdoc/>
  217. public override bool GetCursorVisibility (out CursorVisibility visibility)
  218. {
  219. if (WinConsole is { })
  220. {
  221. bool result = WinConsole.GetCursorVisibility (out visibility);
  222. if (_cachedCursorVisibility is { } && visibility != _cachedCursorVisibility)
  223. {
  224. _cachedCursorVisibility = visibility;
  225. }
  226. return result;
  227. }
  228. visibility = _cachedCursorVisibility ?? CursorVisibility.Default;
  229. return visibility != CursorVisibility.Invisible;
  230. }
  231. /// <inheritdoc/>
  232. public override bool SetCursorVisibility (CursorVisibility visibility)
  233. {
  234. _cachedCursorVisibility = visibility;
  235. if (Force16Colors)
  236. {
  237. return WinConsole is null || WinConsole.SetCursorVisibility (visibility);
  238. }
  239. else
  240. {
  241. var sb = new StringBuilder ();
  242. sb.Append (visibility != CursorVisibility.Invisible ? EscSeqUtils.CSI_ShowCursor : EscSeqUtils.CSI_HideCursor);
  243. return WinConsole?.WriteANSI (sb.ToString ()) ?? false;
  244. }
  245. }
  246. #endregion Cursor Handling
  247. public override bool UpdateScreen ()
  248. {
  249. bool updated = false;
  250. Size windowSize = WinConsole?.GetConsoleBufferWindow (out Point _) ?? new Size (Cols, Rows);
  251. if (!windowSize.IsEmpty && (windowSize.Width != Cols || windowSize.Height != Rows))
  252. {
  253. return updated;
  254. }
  255. var bufferCoords = new WindowsConsole.Coord
  256. {
  257. X = (short)Cols, //Clip.Width,
  258. Y = (short)Rows, //Clip.Height
  259. };
  260. for (var row = 0; row < Rows; row++)
  261. {
  262. if (!_dirtyLines! [row])
  263. {
  264. continue;
  265. }
  266. _dirtyLines [row] = false;
  267. updated = true;
  268. for (var col = 0; col < Cols; col++)
  269. {
  270. int position = row * Cols + col;
  271. _outputBuffer [position].Attribute = Contents! [row, col].Attribute.GetValueOrDefault ();
  272. if (Contents [row, col].IsDirty == false)
  273. {
  274. _outputBuffer [position].Empty = true;
  275. _outputBuffer [position].Char = (char)Rune.ReplacementChar.Value;
  276. continue;
  277. }
  278. _outputBuffer [position].Empty = false;
  279. if (Contents [row, col].Rune.IsBmp)
  280. {
  281. _outputBuffer [position].Char = (char)Contents [row, col].Rune.Value;
  282. }
  283. else
  284. {
  285. //_outputBuffer [position].Empty = true;
  286. _outputBuffer [position].Char = (char)Rune.ReplacementChar.Value;
  287. if (Contents [row, col].Rune.GetColumns () > 1 && col + 1 < Cols)
  288. {
  289. // TODO: This is a hack to deal with non-BMP and wide characters.
  290. col++;
  291. position = row * Cols + col;
  292. _outputBuffer [position].Empty = false;
  293. _outputBuffer [position].Char = ' ';
  294. }
  295. }
  296. }
  297. }
  298. _damageRegion = new WindowsConsole.SmallRect
  299. {
  300. Top = 0,
  301. Left = 0,
  302. Bottom = (short)Rows,
  303. Right = (short)Cols
  304. };
  305. if (!RunningUnitTests
  306. && WinConsole != null
  307. && !WinConsole.WriteToConsole (new (Cols, Rows), _outputBuffer, bufferCoords, _damageRegion, Force16Colors))
  308. {
  309. int err = Marshal.GetLastWin32Error ();
  310. if (err != 0)
  311. {
  312. throw new Win32Exception (err);
  313. }
  314. }
  315. WindowsConsole.SmallRect.MakeEmpty (ref _damageRegion);
  316. return updated;
  317. }
  318. public override void End ()
  319. {
  320. if (_mainLoopDriver is { })
  321. {
  322. #if HACK_CHECK_WINCHANGED
  323. _mainLoopDriver.WinChanged -= ChangeWin;
  324. #endif
  325. }
  326. _mainLoopDriver = null;
  327. WinConsole?.Cleanup ();
  328. WinConsole = null;
  329. if (!RunningUnitTests && _isWindowsTerminal)
  330. {
  331. // Disable alternative screen buffer.
  332. Console.Out.Write (EscSeqUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll);
  333. }
  334. }
  335. public override MainLoop Init ()
  336. {
  337. _mainLoopDriver = new WindowsMainLoop (this);
  338. if (!RunningUnitTests)
  339. {
  340. try
  341. {
  342. if (WinConsole is { })
  343. {
  344. // BUGBUG: The results from GetConsoleOutputWindow are incorrect when called from Init.
  345. // Our thread in WindowsMainLoop.CheckWin will get the correct results. See #if HACK_CHECK_WINCHANGED
  346. Size winSize = WinConsole.GetConsoleOutputWindow (out _);
  347. Cols = winSize.Width;
  348. Rows = winSize.Height;
  349. OnSizeChanged (new SizeChangedEventArgs (new (Cols, Rows)));
  350. }
  351. WindowsConsole.SmallRect.MakeEmpty (ref _damageRegion);
  352. if (_isWindowsTerminal)
  353. {
  354. Console.Out.Write (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll);
  355. }
  356. }
  357. catch (Win32Exception e)
  358. {
  359. // We are being run in an environment that does not support a console
  360. // such as a unit test, or a pipe.
  361. Debug.WriteLine ($"Likely running unit tests. Setting WinConsole to null so we can test it elsewhere. Exception: {e}");
  362. WinConsole = null;
  363. }
  364. }
  365. CurrentAttribute = new Attribute (Color.White, Color.Black);
  366. _outputBuffer = new WindowsConsole.ExtendedCharInfo [Rows * Cols];
  367. // CONCURRENCY: Unsynchronized access to Clip is not safe.
  368. Clip = new (Screen);
  369. _damageRegion = new WindowsConsole.SmallRect
  370. {
  371. Top = 0,
  372. Left = 0,
  373. Bottom = (short)Rows,
  374. Right = (short)Cols
  375. };
  376. ClearContents ();
  377. #if HACK_CHECK_WINCHANGED
  378. _mainLoopDriver.WinChanged = ChangeWin;
  379. #endif
  380. if (!RunningUnitTests)
  381. {
  382. WinConsole?.SetInitialCursorVisibility ();
  383. }
  384. return new MainLoop (_mainLoopDriver);
  385. }
  386. private AnsiResponseParser<WindowsConsole.InputRecord> _parser = new ();
  387. internal void ProcessInput (WindowsConsole.InputRecord inputEvent)
  388. {
  389. foreach (var e in Parse (inputEvent))
  390. {
  391. ProcessInputAfterParsing (e);
  392. }
  393. }
  394. internal void ProcessInputAfterParsing (WindowsConsole.InputRecord inputEvent)
  395. {
  396. switch (inputEvent.EventType)
  397. {
  398. case WindowsConsole.EventType.Key:
  399. if (inputEvent.KeyEvent.wVirtualKeyCode == (ConsoleKeyMapping.VK)ConsoleKey.Packet)
  400. {
  401. // Used to pass Unicode characters as if they were keystrokes.
  402. // The VK_PACKET key is the low word of a 32-bit
  403. // Virtual Key value used for non-keyboard input methods.
  404. inputEvent.KeyEvent = FromVKPacketToKeyEventRecord (inputEvent.KeyEvent);
  405. }
  406. WindowsConsole.ConsoleKeyInfoEx keyInfo = ToConsoleKeyInfoEx (inputEvent.KeyEvent);
  407. //Debug.WriteLine ($"event: KBD: {GetKeyboardLayoutName()} {inputEvent.ToString ()} {keyInfo.ToString (keyInfo)}");
  408. KeyCode map = MapKey (keyInfo);
  409. if (map == KeyCode.Null)
  410. {
  411. break;
  412. }
  413. if (IsValidInput (map, out map))
  414. {
  415. // This follows convention in NetDriver
  416. OnKeyDown (new (map));
  417. OnKeyUp (new (map));
  418. }
  419. break;
  420. case WindowsConsole.EventType.Mouse:
  421. MouseEventArgs me = ToDriverMouse (inputEvent.MouseEvent);
  422. if (/*me is null ||*/ me.Flags == MouseFlags.None)
  423. {
  424. break;
  425. }
  426. OnMouseEvent (me);
  427. if (_processButtonClick)
  428. {
  429. OnMouseEvent (new ()
  430. {
  431. Position = me.Position,
  432. Flags = ProcessButtonClick (inputEvent.MouseEvent)
  433. });
  434. }
  435. break;
  436. case WindowsConsole.EventType.Focus:
  437. break;
  438. #if !HACK_CHECK_WINCHANGED
  439. case WindowsConsole.EventType.WindowBufferSize:
  440. Cols = inputEvent.WindowBufferSizeEvent._size.X;
  441. Rows = inputEvent.WindowBufferSizeEvent._size.Y;
  442. Application.Screen = new (0, 0, Cols, Rows);
  443. ResizeScreen ();
  444. ClearContents ();
  445. Application.Top?.SetNeedsLayout ();
  446. Application.LayoutAndDraw ();
  447. break;
  448. #endif
  449. }
  450. }
  451. private IEnumerable<WindowsConsole.InputRecord> Parse (WindowsConsole.InputRecord inputEvent)
  452. {
  453. if (inputEvent.EventType != WindowsConsole.EventType.Key)
  454. {
  455. yield return inputEvent;
  456. yield break;
  457. }
  458. // Swallow key up events - they are unreliable
  459. if (!inputEvent.KeyEvent.bKeyDown)
  460. {
  461. yield break;
  462. }
  463. foreach (var i in ShouldReleaseParserHeldKeys ())
  464. {
  465. yield return i;
  466. }
  467. foreach (Tuple<char, WindowsConsole.InputRecord> output in
  468. _parser.ProcessInput (Tuple.Create (inputEvent.KeyEvent.UnicodeChar, inputEvent)))
  469. {
  470. yield return output.Item2;
  471. }
  472. }
  473. public IEnumerable<WindowsConsole.InputRecord> ShouldReleaseParserHeldKeys ()
  474. {
  475. if (_parser.State == AnsiResponseParserState.ExpectingEscapeSequence &&
  476. DateTime.Now - _parser.StateChangedAt > EscTimeout)
  477. {
  478. return _parser.Release ().Select (o => o.Item2);
  479. }
  480. return [];
  481. }
  482. #if HACK_CHECK_WINCHANGED
  483. private void ChangeWin (object s, SizeChangedEventArgs e)
  484. {
  485. if (e.Size is null)
  486. {
  487. return;
  488. }
  489. int w = e.Size.Value.Width;
  490. if (w == Cols - 3 && e.Size.Value.Height < Rows)
  491. {
  492. w += 3;
  493. }
  494. Left = 0;
  495. Top = 0;
  496. Cols = e.Size.Value.Width;
  497. Rows = e.Size.Value.Height;
  498. if (!RunningUnitTests)
  499. {
  500. Size newSize = WinConsole.SetConsoleWindow (
  501. (short)Math.Max (w, 16),
  502. (short)Math.Max (e.Size.Value.Height, 0));
  503. Cols = newSize.Width;
  504. Rows = newSize.Height;
  505. }
  506. ResizeScreen ();
  507. ClearContents ();
  508. OnSizeChanged (new SizeChangedEventArgs (new (Cols, Rows)));
  509. }
  510. #endif
  511. public static KeyCode MapKey (WindowsConsole.ConsoleKeyInfoEx keyInfoEx)
  512. {
  513. ConsoleKeyInfo keyInfo = keyInfoEx.ConsoleKeyInfo;
  514. switch (keyInfo.Key)
  515. {
  516. case ConsoleKey.D0:
  517. case ConsoleKey.D1:
  518. case ConsoleKey.D2:
  519. case ConsoleKey.D3:
  520. case ConsoleKey.D4:
  521. case ConsoleKey.D5:
  522. case ConsoleKey.D6:
  523. case ConsoleKey.D7:
  524. case ConsoleKey.D8:
  525. case ConsoleKey.D9:
  526. case ConsoleKey.NumPad0:
  527. case ConsoleKey.NumPad1:
  528. case ConsoleKey.NumPad2:
  529. case ConsoleKey.NumPad3:
  530. case ConsoleKey.NumPad4:
  531. case ConsoleKey.NumPad5:
  532. case ConsoleKey.NumPad6:
  533. case ConsoleKey.NumPad7:
  534. case ConsoleKey.NumPad8:
  535. case ConsoleKey.NumPad9:
  536. case ConsoleKey.Oem1:
  537. case ConsoleKey.Oem2:
  538. case ConsoleKey.Oem3:
  539. case ConsoleKey.Oem4:
  540. case ConsoleKey.Oem5:
  541. case ConsoleKey.Oem6:
  542. case ConsoleKey.Oem7:
  543. case ConsoleKey.Oem8:
  544. case ConsoleKey.Oem102:
  545. case ConsoleKey.Multiply:
  546. case ConsoleKey.Add:
  547. case ConsoleKey.Separator:
  548. case ConsoleKey.Subtract:
  549. case ConsoleKey.Decimal:
  550. case ConsoleKey.Divide:
  551. case ConsoleKey.OemPeriod:
  552. case ConsoleKey.OemComma:
  553. case ConsoleKey.OemPlus:
  554. case ConsoleKey.OemMinus:
  555. // These virtual key codes are mapped differently depending on the keyboard layout in use.
  556. // We use the Win32 API to map them to the correct character.
  557. uint mapResult = ConsoleKeyMapping.MapVKtoChar ((ConsoleKeyMapping.VK)keyInfo.Key);
  558. if (mapResult == 0)
  559. {
  560. // There is no mapping - this should not happen
  561. Debug.Assert (true, $@"Unable to map the virtual key code {keyInfo.Key}.");
  562. return KeyCode.Null;
  563. }
  564. // An un-shifted character value is in the low order word of the return value.
  565. var mappedChar = (char)(mapResult & 0x0000FFFF);
  566. if (keyInfo.KeyChar == 0)
  567. {
  568. // If the keyChar is 0, keyInfo.Key value is not a printable character.
  569. // Dead keys (diacritics) are indicated by setting the top bit of the return value.
  570. if ((mapResult & 0x80000000) != 0)
  571. {
  572. // Dead key (e.g. Oem2 '~'/'^' on POR keyboard)
  573. // Option 1: Throw it out.
  574. // - Apps will never see the dead keys
  575. // - If user presses a key that can be combined with the dead key ('a'), the right thing happens (app will see '�').
  576. // - NOTE: With Dead Keys, KeyDown != KeyUp. The KeyUp event will have just the base char ('a').
  577. // - If user presses dead key again, the right thing happens (app will see `~~`)
  578. // - This is what Notepad etc... appear to do
  579. // Option 2: Expand the API to indicate the KeyCode is a dead key
  580. // - Enables apps to do their own dead key processing
  581. // - Adds complexity; no dev has asked for this (yet).
  582. // We choose Option 1 for now.
  583. return KeyCode.Null;
  584. // Note: Ctrl-Deadkey (like Oem3 '`'/'~` on ENG) can't be supported.
  585. // Sadly, the charVal is just the deadkey and subsequent key events do not contain
  586. // any info that the previous event was a deadkey.
  587. // Note WT does not support Ctrl-Deadkey either.
  588. }
  589. if (keyInfo.Modifiers != 0)
  590. {
  591. // These Oem keys have well-defined chars. We ensure the representative char is used.
  592. // If we don't do this, then on some keyboard layouts the wrong char is
  593. // returned (e.g. on ENG OemPlus un-shifted is =, not +). This is important
  594. // for key persistence ("Ctrl++" vs. "Ctrl+=").
  595. mappedChar = keyInfo.Key switch
  596. {
  597. ConsoleKey.OemPeriod => '.',
  598. ConsoleKey.OemComma => ',',
  599. ConsoleKey.OemPlus => '+',
  600. ConsoleKey.OemMinus => '-',
  601. _ => mappedChar
  602. };
  603. }
  604. // Return the mappedChar with modifiers. Because mappedChar is un-shifted, if Shift was down
  605. // we should keep it
  606. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)mappedChar);
  607. }
  608. // KeyChar is printable
  609. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt) && keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control))
  610. {
  611. // AltGr support - AltGr is equivalent to Ctrl+Alt - the correct char is in KeyChar
  612. return (KeyCode)keyInfo.KeyChar;
  613. }
  614. if (keyInfo.Modifiers != ConsoleModifiers.Shift)
  615. {
  616. // If Shift wasn't down we don't need to do anything but return the mappedChar
  617. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)mappedChar);
  618. }
  619. // Strip off Shift - We got here because they KeyChar from Windows is the shifted char (e.g. "�")
  620. // and passing on Shift would be redundant.
  621. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.KeyChar);
  622. }
  623. // A..Z are special cased:
  624. // - Alone, they represent lowercase a...z
  625. // - With ShiftMask they are A..Z
  626. // - If CapsLock is on the above is reversed.
  627. // - If Alt and/or Ctrl are present, treat as upper case
  628. if (keyInfo.Key is >= ConsoleKey.A and <= ConsoleKey.Z)
  629. {
  630. if (keyInfo.KeyChar == 0)
  631. {
  632. // KeyChar is not printable - possibly an AltGr key?
  633. // AltGr support - AltGr is equivalent to Ctrl+Alt
  634. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt) && keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control))
  635. {
  636. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(uint)keyInfo.Key);
  637. }
  638. }
  639. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt) || keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control))
  640. {
  641. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(uint)keyInfo.Key);
  642. }
  643. if ((keyInfo.Modifiers == ConsoleModifiers.Shift) ^ keyInfoEx.CapsLock)
  644. {
  645. // If (ShiftMask is on and CapsLock is off) or (ShiftMask is off and CapsLock is on) add the ShiftMask
  646. if (char.IsUpper (keyInfo.KeyChar))
  647. {
  648. if (keyInfo.KeyChar <= 'Z')
  649. {
  650. return (KeyCode)keyInfo.Key | KeyCode.ShiftMask;
  651. }
  652. // Always return the KeyChar because it may be an Á, À with Oem1, etc
  653. return (KeyCode)keyInfo.KeyChar;
  654. }
  655. }
  656. if (keyInfo.KeyChar <= 'z')
  657. {
  658. return (KeyCode)keyInfo.Key;
  659. }
  660. // Always return the KeyChar because it may be an á, à with Oem1, etc
  661. return (KeyCode)keyInfo.KeyChar;
  662. }
  663. // Handle control keys whose VK codes match the related ASCII value (those below ASCII 33) like ESC
  664. // Also handle the key ASCII value 127 (BACK)
  665. if (Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key))
  666. {
  667. // If the key is JUST a modifier, return it as just that key
  668. if (keyInfo.Key == (ConsoleKey)ConsoleKeyMapping.VK.SHIFT)
  669. { // Shift 16
  670. return KeyCode.ShiftMask;
  671. }
  672. if (keyInfo.Key == (ConsoleKey)ConsoleKeyMapping.VK.CONTROL)
  673. { // Ctrl 17
  674. return KeyCode.CtrlMask;
  675. }
  676. if (keyInfo.Key == (ConsoleKey)ConsoleKeyMapping.VK.MENU)
  677. { // Alt 18
  678. return KeyCode.AltMask;
  679. }
  680. if (keyInfo.KeyChar == 0)
  681. {
  682. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar);
  683. }
  684. // Backspace (ASCII 127)
  685. if (keyInfo.KeyChar == '\u007f')
  686. {
  687. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.Key);
  688. }
  689. if (keyInfo.Key != ConsoleKey.None)
  690. {
  691. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar);
  692. }
  693. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.KeyChar);
  694. }
  695. // Handle control keys (e.g. CursorUp)
  696. if (Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint))
  697. {
  698. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)((uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint));
  699. }
  700. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar);
  701. }
  702. private MouseFlags ProcessButtonClick (WindowsConsole.MouseEventRecord mouseEvent)
  703. {
  704. MouseFlags mouseFlag = 0;
  705. switch (_lastMouseButtonPressed)
  706. {
  707. case WindowsConsole.ButtonState.Button1Pressed:
  708. mouseFlag = MouseFlags.Button1Clicked;
  709. break;
  710. case WindowsConsole.ButtonState.Button2Pressed:
  711. mouseFlag = MouseFlags.Button2Clicked;
  712. break;
  713. case WindowsConsole.ButtonState.RightmostButtonPressed:
  714. mouseFlag = MouseFlags.Button3Clicked;
  715. break;
  716. }
  717. _point = new Point
  718. {
  719. X = mouseEvent.MousePosition.X,
  720. Y = mouseEvent.MousePosition.Y
  721. };
  722. _lastMouseButtonPressed = null;
  723. _isButtonReleased = false;
  724. _processButtonClick = false;
  725. _point = null;
  726. return mouseFlag;
  727. }
  728. private async Task ProcessButtonDoubleClickedAsync ()
  729. {
  730. await Task.Delay (200);
  731. _isButtonDoubleClicked = false;
  732. _isOneFingerDoubleClicked = false;
  733. //buttonPressedCount = 0;
  734. }
  735. private void ResizeScreen ()
  736. {
  737. _outputBuffer = new WindowsConsole.ExtendedCharInfo [Rows * Cols];
  738. // CONCURRENCY: Unsynchronized access to Clip is not safe.
  739. Clip = new (Screen);
  740. _damageRegion = new WindowsConsole.SmallRect
  741. {
  742. Top = 0,
  743. Left = 0,
  744. Bottom = (short)Rows,
  745. Right = (short)Cols
  746. };
  747. _dirtyLines = new bool [Rows];
  748. WinConsole?.ForceRefreshCursorVisibility ();
  749. }
  750. private static MouseFlags SetControlKeyStates (WindowsConsole.MouseEventRecord mouseEvent, MouseFlags mouseFlag)
  751. {
  752. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed)
  753. || mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed))
  754. {
  755. mouseFlag |= MouseFlags.ButtonCtrl;
  756. }
  757. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed))
  758. {
  759. mouseFlag |= MouseFlags.ButtonShift;
  760. }
  761. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed)
  762. || mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed))
  763. {
  764. mouseFlag |= MouseFlags.ButtonAlt;
  765. }
  766. return mouseFlag;
  767. }
  768. [CanBeNull]
  769. private MouseEventArgs ToDriverMouse (WindowsConsole.MouseEventRecord mouseEvent)
  770. {
  771. var mouseFlag = MouseFlags.AllEvents;
  772. //Debug.WriteLine ($"ToDriverMouse: {mouseEvent}");
  773. if (_isButtonDoubleClicked || _isOneFingerDoubleClicked)
  774. {
  775. // TODO: This makes IConsoleDriver dependent on Application, which is not ideal. This should be moved to Application.
  776. Application.MainLoop!.TimedEvents.Add (TimeSpan.Zero,
  777. () =>
  778. {
  779. Task.Run (async () => await ProcessButtonDoubleClickedAsync ());
  780. return false;
  781. });
  782. }
  783. // The ButtonState member of the MouseEvent structure has bit corresponding to each mouse button.
  784. // This will tell when a mouse button is pressed. When the button is released this event will
  785. // be fired with its bit set to 0. So when the button is up ButtonState will be 0.
  786. // To map to the correct driver events we save the last pressed mouse button, so we can
  787. // map to the correct clicked event.
  788. if ((_lastMouseButtonPressed is { } || _isButtonReleased) && mouseEvent.ButtonState != 0)
  789. {
  790. _lastMouseButtonPressed = null;
  791. //isButtonPressed = false;
  792. _isButtonReleased = false;
  793. }
  794. var p = new Point
  795. {
  796. X = mouseEvent.MousePosition.X,
  797. Y = mouseEvent.MousePosition.Y
  798. };
  799. if ((mouseEvent.ButtonState != 0 && mouseEvent.EventFlags == 0 && _lastMouseButtonPressed is null && !_isButtonDoubleClicked)
  800. || (_lastMouseButtonPressed == null
  801. && mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.MouseMoved)
  802. && mouseEvent.ButtonState != 0
  803. && !_isButtonReleased
  804. && !_isButtonDoubleClicked))
  805. {
  806. switch (mouseEvent.ButtonState)
  807. {
  808. case WindowsConsole.ButtonState.Button1Pressed:
  809. mouseFlag = MouseFlags.Button1Pressed;
  810. break;
  811. case WindowsConsole.ButtonState.Button2Pressed:
  812. mouseFlag = MouseFlags.Button2Pressed;
  813. break;
  814. case WindowsConsole.ButtonState.RightmostButtonPressed:
  815. mouseFlag = MouseFlags.Button3Pressed;
  816. break;
  817. }
  818. if (_point is null)
  819. {
  820. _point = p;
  821. }
  822. if (mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.MouseMoved))
  823. {
  824. _pointMove = p;
  825. mouseFlag |= MouseFlags.ReportMousePosition;
  826. _isButtonReleased = false;
  827. _processButtonClick = false;
  828. }
  829. _lastMouseButtonPressed = mouseEvent.ButtonState;
  830. _isButtonPressed = true;
  831. }
  832. else if (_lastMouseButtonPressed != null
  833. && mouseEvent.EventFlags == 0
  834. && !_isButtonReleased
  835. && !_isButtonDoubleClicked
  836. && !_isOneFingerDoubleClicked)
  837. {
  838. switch (_lastMouseButtonPressed)
  839. {
  840. case WindowsConsole.ButtonState.Button1Pressed:
  841. mouseFlag = MouseFlags.Button1Released;
  842. break;
  843. case WindowsConsole.ButtonState.Button2Pressed:
  844. mouseFlag = MouseFlags.Button2Released;
  845. break;
  846. case WindowsConsole.ButtonState.RightmostButtonPressed:
  847. mouseFlag = MouseFlags.Button3Released;
  848. break;
  849. }
  850. _isButtonPressed = false;
  851. _isButtonReleased = true;
  852. if (_point is { } && ((Point)_point).X == mouseEvent.MousePosition.X && ((Point)_point).Y == mouseEvent.MousePosition.Y)
  853. {
  854. _processButtonClick = true;
  855. }
  856. else
  857. {
  858. _point = null;
  859. }
  860. _processButtonClick = true;
  861. }
  862. else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved
  863. && !_isOneFingerDoubleClicked
  864. && _isButtonReleased
  865. && p == _point)
  866. {
  867. mouseFlag = ProcessButtonClick (mouseEvent);
  868. }
  869. else if (mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.DoubleClick))
  870. {
  871. switch (mouseEvent.ButtonState)
  872. {
  873. case WindowsConsole.ButtonState.Button1Pressed:
  874. mouseFlag = MouseFlags.Button1DoubleClicked;
  875. break;
  876. case WindowsConsole.ButtonState.Button2Pressed:
  877. mouseFlag = MouseFlags.Button2DoubleClicked;
  878. break;
  879. case WindowsConsole.ButtonState.RightmostButtonPressed:
  880. mouseFlag = MouseFlags.Button3DoubleClicked;
  881. break;
  882. }
  883. _isButtonDoubleClicked = true;
  884. }
  885. else if (mouseEvent.EventFlags == 0 && mouseEvent.ButtonState != 0 && _isButtonDoubleClicked)
  886. {
  887. switch (mouseEvent.ButtonState)
  888. {
  889. case WindowsConsole.ButtonState.Button1Pressed:
  890. mouseFlag = MouseFlags.Button1TripleClicked;
  891. break;
  892. case WindowsConsole.ButtonState.Button2Pressed:
  893. mouseFlag = MouseFlags.Button2TripleClicked;
  894. break;
  895. case WindowsConsole.ButtonState.RightmostButtonPressed:
  896. mouseFlag = MouseFlags.Button3TripleClicked;
  897. break;
  898. }
  899. _isButtonDoubleClicked = false;
  900. }
  901. else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled)
  902. {
  903. switch ((int)mouseEvent.ButtonState)
  904. {
  905. case int v when v > 0:
  906. mouseFlag = MouseFlags.WheeledUp;
  907. break;
  908. case int v when v < 0:
  909. mouseFlag = MouseFlags.WheeledDown;
  910. break;
  911. }
  912. }
  913. else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled && mouseEvent.ControlKeyState == WindowsConsole.ControlKeyState.ShiftPressed)
  914. {
  915. switch ((int)mouseEvent.ButtonState)
  916. {
  917. case int v when v > 0:
  918. mouseFlag = MouseFlags.WheeledLeft;
  919. break;
  920. case int v when v < 0:
  921. mouseFlag = MouseFlags.WheeledRight;
  922. break;
  923. }
  924. }
  925. else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseHorizontalWheeled)
  926. {
  927. switch ((int)mouseEvent.ButtonState)
  928. {
  929. case int v when v < 0:
  930. mouseFlag = MouseFlags.WheeledLeft;
  931. break;
  932. case int v when v > 0:
  933. mouseFlag = MouseFlags.WheeledRight;
  934. break;
  935. }
  936. }
  937. else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved)
  938. {
  939. mouseFlag = MouseFlags.ReportMousePosition;
  940. if (mouseEvent.MousePosition.X != _pointMove.X || mouseEvent.MousePosition.Y != _pointMove.Y)
  941. {
  942. _pointMove = new Point (mouseEvent.MousePosition.X, mouseEvent.MousePosition.Y);
  943. }
  944. }
  945. else if (mouseEvent is { ButtonState: 0, EventFlags: 0 })
  946. {
  947. // This happens on a double or triple click event.
  948. mouseFlag = MouseFlags.None;
  949. }
  950. mouseFlag = SetControlKeyStates (mouseEvent, mouseFlag);
  951. //System.Diagnostics.Debug.WriteLine (
  952. // $"point.X:{(point is { } ? ((Point)point).X : -1)};point.Y:{(point is { } ? ((Point)point).Y : -1)}");
  953. return new MouseEventArgs
  954. {
  955. Position = new (mouseEvent.MousePosition.X, mouseEvent.MousePosition.Y),
  956. Flags = mouseFlag
  957. };
  958. }
  959. }