WindowsDriver.cs 42 KB

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