WindowsDriver.cs 42 KB

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