WindowsKeyHelper.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. #nullable enable
  2. using System.Diagnostics;
  3. namespace Terminal.Gui.Drivers;
  4. /// <summary>
  5. /// Helper class for Windows key conversion utilities.
  6. /// Contains static methods extracted from the legacy WindowsDriver for key processing.
  7. /// </summary>
  8. internal static class WindowsKeyHelper
  9. {
  10. public static WindowsConsole.KeyEventRecord FromVKPacketToKeyEventRecord (WindowsConsole.KeyEventRecord keyEvent)
  11. {
  12. if (keyEvent.wVirtualKeyCode != (ConsoleKeyMapping.VK)ConsoleKey.Packet)
  13. {
  14. return keyEvent;
  15. }
  16. var mod = new ConsoleModifiers ();
  17. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed))
  18. {
  19. mod |= ConsoleModifiers.Shift;
  20. }
  21. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed)
  22. || keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed))
  23. {
  24. mod |= ConsoleModifiers.Alt;
  25. }
  26. if (keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed)
  27. || keyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed))
  28. {
  29. mod |= ConsoleModifiers.Control;
  30. }
  31. var cKeyInfo = new ConsoleKeyInfo (
  32. keyEvent.UnicodeChar,
  33. (ConsoleKey)keyEvent.wVirtualKeyCode,
  34. mod.HasFlag (ConsoleModifiers.Shift),
  35. mod.HasFlag (ConsoleModifiers.Alt),
  36. mod.HasFlag (ConsoleModifiers.Control));
  37. cKeyInfo = ConsoleKeyMapping.DecodeVKPacketToKConsoleKeyInfo (cKeyInfo);
  38. uint scanCode = ConsoleKeyMapping.GetScanCodeFromConsoleKeyInfo (cKeyInfo);
  39. return new WindowsConsole.KeyEventRecord
  40. {
  41. UnicodeChar = cKeyInfo.KeyChar,
  42. bKeyDown = keyEvent.bKeyDown,
  43. dwControlKeyState = keyEvent.dwControlKeyState,
  44. wRepeatCount = keyEvent.wRepeatCount,
  45. wVirtualKeyCode = (ConsoleKeyMapping.VK)cKeyInfo.Key,
  46. wVirtualScanCode = (ushort)scanCode
  47. };
  48. }
  49. public static WindowsConsole.ConsoleKeyInfoEx ToConsoleKeyInfoEx (WindowsConsole.KeyEventRecord keyEvent)
  50. {
  51. WindowsConsole.ControlKeyState state = keyEvent.dwControlKeyState;
  52. bool shift = (state & WindowsConsole.ControlKeyState.ShiftPressed) != 0;
  53. bool alt = (state & (WindowsConsole.ControlKeyState.LeftAltPressed | WindowsConsole.ControlKeyState.RightAltPressed)) != 0;
  54. bool control = (state & (WindowsConsole.ControlKeyState.LeftControlPressed | WindowsConsole.ControlKeyState.RightControlPressed)) != 0;
  55. bool capslock = (state & WindowsConsole.ControlKeyState.CapslockOn) != 0;
  56. bool numlock = (state & WindowsConsole.ControlKeyState.NumlockOn) != 0;
  57. bool scrolllock = (state & WindowsConsole.ControlKeyState.ScrolllockOn) != 0;
  58. var cki = new ConsoleKeyInfo (keyEvent.UnicodeChar, (ConsoleKey)keyEvent.wVirtualKeyCode, shift, alt, control);
  59. return new WindowsConsole.ConsoleKeyInfoEx (cki, capslock, numlock, scrolllock);
  60. }
  61. public static KeyCode MapKey (WindowsConsole.ConsoleKeyInfoEx keyInfoEx)
  62. {
  63. ConsoleKeyInfo keyInfo = keyInfoEx.ConsoleKeyInfo;
  64. switch (keyInfo.Key)
  65. {
  66. case ConsoleKey.D0:
  67. case ConsoleKey.D1:
  68. case ConsoleKey.D2:
  69. case ConsoleKey.D3:
  70. case ConsoleKey.D4:
  71. case ConsoleKey.D5:
  72. case ConsoleKey.D6:
  73. case ConsoleKey.D7:
  74. case ConsoleKey.D8:
  75. case ConsoleKey.D9:
  76. case ConsoleKey.NumPad0:
  77. case ConsoleKey.NumPad1:
  78. case ConsoleKey.NumPad2:
  79. case ConsoleKey.NumPad3:
  80. case ConsoleKey.NumPad4:
  81. case ConsoleKey.NumPad5:
  82. case ConsoleKey.NumPad6:
  83. case ConsoleKey.NumPad7:
  84. case ConsoleKey.NumPad8:
  85. case ConsoleKey.NumPad9:
  86. case ConsoleKey.Oem1:
  87. case ConsoleKey.Oem2:
  88. case ConsoleKey.Oem3:
  89. case ConsoleKey.Oem4:
  90. case ConsoleKey.Oem5:
  91. case ConsoleKey.Oem6:
  92. case ConsoleKey.Oem7:
  93. case ConsoleKey.Oem8:
  94. case ConsoleKey.Oem102:
  95. case ConsoleKey.Multiply:
  96. case ConsoleKey.Add:
  97. case ConsoleKey.Separator:
  98. case ConsoleKey.Subtract:
  99. case ConsoleKey.Decimal:
  100. case ConsoleKey.Divide:
  101. case ConsoleKey.OemPeriod:
  102. case ConsoleKey.OemComma:
  103. case ConsoleKey.OemPlus:
  104. case ConsoleKey.OemMinus:
  105. // These virtual key codes are mapped differently depending on the keyboard layout in use.
  106. // We use the Win32 API to map them to the correct character.
  107. uint mapResult = ConsoleKeyMapping.MapVKtoChar ((ConsoleKeyMapping.VK)keyInfo.Key);
  108. if (mapResult == 0)
  109. {
  110. // There is no mapping - this should not happen
  111. Debug.Assert (true, $@"Unable to map the virtual key code {keyInfo.Key}.");
  112. return KeyCode.Null;
  113. }
  114. // An un-shifted character value is in the low order word of the return value.
  115. var mappedChar = (char)(mapResult & 0x0000FFFF);
  116. if (keyInfo.KeyChar == 0)
  117. {
  118. // If the keyChar is 0, keyInfo.Key value is not a printable character.
  119. // Dead keys (diacritics) are indicated by setting the top bit of the return value.
  120. if ((mapResult & 0x80000000) != 0)
  121. {
  122. // Dead key (e.g. Oem2 '~'/'^' on POR keyboard)
  123. // Option 1: Throw it out.
  124. // - Apps will never see the dead keys
  125. // - If user presses a key that can be combined with the dead key ('a'), the right thing happens (app will see '�').
  126. // - NOTE: With Dead Keys, KeyDown != KeyUp. The KeyUp event will have just the base char ('a').
  127. // - If user presses dead key again, the right thing happens (app will see `~~`)
  128. // - This is what Notepad etc... appear to do
  129. // Option 2: Expand the API to indicate the KeyCode is a dead key
  130. // - Enables apps to do their own dead key processing
  131. // - Adds complexity; no dev has asked for this (yet).
  132. // We choose Option 1 for now.
  133. return KeyCode.Null;
  134. // Note: Ctrl-Deadkey (like Oem3 '`'/'~` on ENG) can't be supported.
  135. // Sadly, the charVal is just the deadkey and subsequent key events do not contain
  136. // any info that the previous event was a deadkey.
  137. // Note WT does not support Ctrl-Deadkey either.
  138. }
  139. if (keyInfo.Modifiers != 0)
  140. {
  141. // These Oem keys have well-defined chars. We ensure the representative char is used.
  142. // If we don't do this, then on some keyboard layouts the wrong char is
  143. // returned (e.g. on ENG OemPlus un-shifted is =, not +). This is important
  144. // for key persistence ("Ctrl++" vs. "Ctrl+=").
  145. mappedChar = keyInfo.Key switch
  146. {
  147. ConsoleKey.OemPeriod => '.',
  148. ConsoleKey.OemComma => ',',
  149. ConsoleKey.OemPlus => '+',
  150. ConsoleKey.OemMinus => '-',
  151. _ => mappedChar
  152. };
  153. }
  154. // Return the mappedChar with modifiers. Because mappedChar is un-shifted, if Shift was down
  155. // we should keep it
  156. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)mappedChar);
  157. }
  158. // KeyChar is printable
  159. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt) && keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control))
  160. {
  161. // AltGr support - AltGr is equivalent to Ctrl+Alt - the correct char is in KeyChar
  162. return (KeyCode)keyInfo.KeyChar;
  163. }
  164. if (keyInfo.Modifiers != ConsoleModifiers.Shift)
  165. {
  166. // If Shift wasn't down we don't need to do anything but return the mappedChar
  167. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)mappedChar);
  168. }
  169. // Strip off Shift - We got here because they KeyChar from Windows is the shifted char (e.g. "�")
  170. // and passing on Shift would be redundant.
  171. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.KeyChar);
  172. }
  173. // A..Z are special cased:
  174. // - Alone, they represent lowercase a...z
  175. // - With ShiftMask they are A..Z
  176. // - If CapsLock is on the above is reversed.
  177. // - If Alt and/or Ctrl are present, treat as upper case
  178. if (keyInfo.Key is >= ConsoleKey.A and <= ConsoleKey.Z)
  179. {
  180. if (keyInfo.KeyChar == 0)
  181. {
  182. // KeyChar is not printable - possibly an AltGr key?
  183. // AltGr support - AltGr is equivalent to Ctrl+Alt
  184. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt) && keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control))
  185. {
  186. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(uint)keyInfo.Key);
  187. }
  188. }
  189. if (keyInfo.Modifiers.HasFlag (ConsoleModifiers.Alt) || keyInfo.Modifiers.HasFlag (ConsoleModifiers.Control))
  190. {
  191. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)(uint)keyInfo.Key);
  192. }
  193. if ((keyInfo.Modifiers == ConsoleModifiers.Shift) ^ keyInfoEx.CapsLock)
  194. {
  195. // If (ShiftMask is on and CapsLock is off) or (ShiftMask is off and CapsLock is on) add the ShiftMask
  196. if (char.IsUpper (keyInfo.KeyChar))
  197. {
  198. if (keyInfo.KeyChar <= 'Z')
  199. {
  200. return (KeyCode)keyInfo.Key | KeyCode.ShiftMask;
  201. }
  202. // Always return the KeyChar because it may be an Á, À with Oem1, etc
  203. return (KeyCode)keyInfo.KeyChar;
  204. }
  205. }
  206. if (keyInfo.KeyChar <= 'z')
  207. {
  208. return (KeyCode)keyInfo.Key;
  209. }
  210. // Always return the KeyChar because it may be an á, à with Oem1, etc
  211. return (KeyCode)keyInfo.KeyChar;
  212. }
  213. // Handle control keys whose VK codes match the related ASCII value (those below ASCII 33) like ESC
  214. // Also handle the key ASCII value 127 (BACK)
  215. if (Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key))
  216. {
  217. // If the key is JUST a modifier, return it as just that key
  218. if (keyInfo.Key == (ConsoleKey)ConsoleKeyMapping.VK.SHIFT)
  219. { // Shift 16
  220. return KeyCode.ShiftMask;
  221. }
  222. if (keyInfo.Key == (ConsoleKey)ConsoleKeyMapping.VK.CONTROL)
  223. { // Ctrl 17
  224. return KeyCode.CtrlMask;
  225. }
  226. if (keyInfo.Key == (ConsoleKey)ConsoleKeyMapping.VK.MENU)
  227. { // Alt 18
  228. return KeyCode.AltMask;
  229. }
  230. if (keyInfo.KeyChar == 0)
  231. {
  232. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar);
  233. }
  234. // Backspace (ASCII 127)
  235. if (keyInfo.KeyChar == '\u007f')
  236. {
  237. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.Key);
  238. }
  239. if (keyInfo.Key != ConsoleKey.None)
  240. {
  241. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar);
  242. }
  243. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers & ~ConsoleModifiers.Shift, (KeyCode)keyInfo.KeyChar);
  244. }
  245. // Handle control keys (e.g. CursorUp)
  246. if (Enum.IsDefined (typeof (KeyCode), (uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint))
  247. {
  248. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)((uint)keyInfo.Key + (uint)KeyCode.MaxCodePoint));
  249. }
  250. return ConsoleKeyMapping.MapToKeyCodeModifiers (keyInfo.Modifiers, (KeyCode)keyInfo.KeyChar);
  251. }
  252. }