WindowsDriver.cs 41 KB

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