WindowsKeyHelper.cs 12 KB

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