WindowsDriver.cs 40 KB

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