WindowsDriver.cs 41 KB

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