WindowsDriver.cs 41 KB

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