WindowsDriver.cs 42 KB

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