WindowsKeyHelper.cs 12 KB

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