WindowsDriver.cs 41 KB

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