Debian Codegraph @

gdk/win32/gdkkeys-win32-impl.c

raw
1 /*
2 * Copyright (c) 2021 Philip Zander
3 * Copyright (c) 2018 Microsoft
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining a copy
6 * of this software and associated documentation files (the "Software"), to deal
7 * in the Software without restriction, including without limitation the rights
8 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 * copies of the Software, and to permit persons to whom the Software is
10 * furnished to do so, subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be included in all
13 * copies or substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 * SOFTWARE.
22 */
23
24 /* NOTE: When compiling the 32-bit version of the library, in addition to being
25 * compiled as a regular source file, this file is also included by
26 * gdkkeys-win32-impl-wow64.c to generate an alternate version of the code
27 * intended for running on a 64-bit kernel. Because of the way keyboard layout
28 * DLLs work on Windows, we have to generate two versions and decide at runtime
29 * which code path to execute. You can read more about the specifics below, in
30 * the section about KBD_LONG_POINTER. */
31
32 #include "gdkkeys-win32.h"
33
34 #ifndef GDK_WIN32_COMPILE_FOR_WOW64
35 #define GDK_WIN32_COMPILE_FOR_WOW64 0
36 #endif
37
38 /* This is our equivalent of the KBD_LONG_POINTER macro in Microsoft's kbd.h.
39 *
40 * A KBD_LONG_POINTER represents a pointer native to the *host*.
41 * I.e. 32 bits on 32-bit Windows and 64 bits on 64-bit Windows.
42 *
43 * This is *not* the same as the the bitness of the application, since it is
44 * possible to execute 32-bit binaries on either a 32-bit *or* a 64-bit host.
45 * On a 64-bit host, KBD_LONG_PTR will be 64-bits, even if the application
46 * itself is 32-bit. (Whereas on a 32-bit host, it will be 32-bit.)
47 *
48 * For clarity, here is an overview of the bit-size of KBD_LONG_POINTER on all
49 * possible host & app combinations:
50 *
51 * Host 32 64
52 * App +-----------
53 * 32 | 32 64
54 * 64 | - 64
55 *
56 * In the official MS headers, KBD_LONG_POINTER is implemented via a macro
57 * which expands to the attribute `__ptr64` if the keyboard driver is
58 * compiled for a 64 bit host. Unfortunately, `__ptr64` is only
59 * supported by MSVC. We use a union here as a workaround.
60 *
61 * For all KBD_LONG_POINTERs, we define an alias starting with "KLP".
62 * Our naming schema (inspired by the Windows headers) is thus the following:
63 * - FOO: The type FOO itself
64 * - PFOO: Regular pointer to the type FOO
65 * - KLPFOO: Keyboard Long Pointer to the type FOO
66 */
67
68 #if GDK_WIN32_COMPILE_FOR_WOW64
69 #define DEFINE_KBD_LONG_POINTER(type) \
70 typedef union { \
71 P##type ptr; \
72 UINT64 _align; \
73 } KLP##type
74 #else
75 #define DEFINE_KBD_LONG_POINTER(type) \
76 typedef union { \
77 P##type ptr; \
78 } KLP##type
79 #endif
80
81 DEFINE_KBD_LONG_POINTER (USHORT);
82 DEFINE_KBD_LONG_POINTER (VOID);
83
84 /* Driver definitions
85 * See
86 * https://github.com/microsoft/windows-rs/blob/0.28.0/crates/deps/sys/src/Windows/Win32/UI/Input/KeyboardAndMouse/mod.rs
87 *
88 * For more information on how these structures work, see also:
89 * https://github.com/microsoft/Windows-driver-samples/tree/f0adcda012820b1cd44a8b3a1953baf478029738/input/layout
90 */
91
92 typedef struct
93 {
94 BYTE Vk;
95 BYTE ModBits;
96 } VK_TO_BIT, *PVK_TO_BIT;
97
98 DEFINE_KBD_LONG_POINTER (VK_TO_BIT);
99
100 typedef struct
101 {
102 KLPVK_TO_BIT pVkToBit;
103 WORD wMaxModBits;
104 BYTE ModNumber[1];
105 } MODIFIERS, *PMODIFIERS;
106
107 DEFINE_KBD_LONG_POINTER (MODIFIERS);
108
109 typedef struct
110 {
111 BYTE Vsc;
112 USHORT Vk;
113 } VSC_VK, *PVSC_VK;
114
115 DEFINE_KBD_LONG_POINTER (VSC_VK);
116
117 typedef struct
118 {
119 BYTE Vk;
120 BYTE Vsc;
121 } VK_VSC, *PVK_VSC;
122
123 DEFINE_KBD_LONG_POINTER (VK_VSC);
124
125 typedef struct
126 {
127 BYTE VirtualKey;
128 BYTE Attributes;
129 WCHAR wch[1];
130 } VK_TO_WCHARS, *PVK_TO_WCHARS;
131
132 DEFINE_KBD_LONG_POINTER (VK_TO_WCHARS);
133
134 typedef struct
135 {
136 KLPVK_TO_WCHARS pVkToWchars;
137 BYTE nModifications;
138 BYTE cbSize;
139 } VK_TO_WCHAR_TABLE, *PVK_TO_WCHAR_TABLE;
140
141 DEFINE_KBD_LONG_POINTER (VK_TO_WCHAR_TABLE);
142
143 typedef struct
144 {
145 DWORD dwBoth;
146 WCHAR wchComposed;
147 USHORT uFlags;
148 } DEADKEY, *PDEADKEY;
149
150 DEFINE_KBD_LONG_POINTER (DEADKEY);
151
152 typedef struct
153 {
154 KLPMODIFIERS pCharModifiers;
155 KLPVK_TO_WCHAR_TABLE pVkToWcharTable;
156 KLPDEADKEY pDeadKey;
157 KLPVOID pKeyNames;
158 KLPVOID pKeyNamesExt;
159 KLPVOID pKeyNamesDead;
160 KLPUSHORT pusVSCtoVK;
161 BYTE bMaxVSCtoVK;
162 KLPVSC_VK pVSCtoVK_E0;
163 KLPVSC_VK pVSCtoVK_E1;
164 DWORD fLocaleFlags;
165 BYTE nLgMaxd;
166 BYTE cbLgEntry;
167 KLPVOID pLigature;
168 } KBDTABLES, *PKBDTABLES;
169
170 DEFINE_KBD_LONG_POINTER (KBDTABLES);
171
172 /* End of declarations */
173
174 static BYTE
175 keystate_to_modbits (GdkWin32KeymapLayoutInfo *info,
176 const BYTE keystate[256])
177 {
178 PKBDTABLES tables = (PKBDTABLES) info->tables;
179 PVK_TO_BIT vk_to_bit;
180 BYTE result = 0;
181 int i;
182
183 if (tables == NULL)
184 return 0;
185
186 vk_to_bit = tables->pCharModifiers.ptr->pVkToBit.ptr;
187
188 for (i = 0; vk_to_bit[i].Vk != 0; ++i)
189 if (keystate[vk_to_bit[i].Vk] & 0x80)
190 result |= vk_to_bit[i].ModBits;
191
192 return result;
193 }
194
195 static BYTE
196 modbits_to_level (GdkWin32KeymapLayoutInfo *info,
197 BYTE modbits)
198 {
199 PKBDTABLES tables = (PKBDTABLES) info->tables;
200 PMODIFIERS modifiers;
201
202 if (tables == NULL)
203 return 0;
204
205 modifiers = tables->pCharModifiers.ptr;
206 if (modbits > modifiers->wMaxModBits)
207 return 0;
208
209 return modifiers->ModNumber[modbits];
210 }
211
212 #define POPCOUNT(b) (!!(b & 0x01) + !!(b & 0x02) + !!(b & 0x04) + !!(b & 0x08) + \
213 !!(b & 0x10) + !!(b & 0x20) + !!(b & 0x40) + !!(b & 0x80))
214
215 /*
216 * vk_to_char_fuzzy:
217 *
218 * For a given key and modifier state, return the best-fit character and the
219 * modifiers used to produce it. Note that not all modifiers need to be used,
220 * because some modifier combination aren't actually mapped in the keyboard
221 * layout (for example the Ctrl key typically has no effect, unless used in
222 * combination with Alt). Such modifiers will not be consumed.
223 *
224 * 'Best-fit' means 'consume as many modifiers as possibe'.
225 *
226 * For example (assuming a neutral lock state):
227 *
228 * - a -> 'a', consumed_mod_bits: []
229 * - Shift + a -> 'A', consumed_mod_bits: [Shift]
230 * - Ctrl + a -> 'a', consumed_mod_bits: []
231 * - Ctrl + Shift + a -> 'A', consumed_mod_bits: [Shift]
232 *
233 * If capslock is active, the result could be:
234 *
235 * - a -> 'A', consumed_mod_bits: [Shift]
236 * - Shift + a -> 'a', consumed_mod_bits: []
237 * - Ctrl + a -> 'a', consumed_mod_bits: []
238 * - Ctrl + Shift + a -> 'A', consumed_mod_bits: [Shift]
239 *
240 * The held down modifiers are supplied in `mod_bits` as a bitmask of KBDSHIFT,
241 * KBDCTRL, KBDALT etc.
242 *
243 * The toggled modifiers are supplied in `lock_state` as a bitmask of CAPLOK and KANALOK.
244 *
245 * If the key combination results in a dead key, `is_dead` will be set to TRUE,
246 * otherwise it will be set to FALSE.
247 */
248 static WCHAR
249 vk_to_char_fuzzy (GdkWin32KeymapLayoutInfo *info,
250 BYTE mod_bits,
251 BYTE lock_bits,
252 BYTE *consumed_mod_bits,
253 gboolean *is_dead,
254 BYTE vk)
255 {
256 PKBDTABLES tables = (PKBDTABLES) info->tables;
257
258 PVK_TO_WCHAR_TABLE wch_tables;
259 PVK_TO_WCHAR_TABLE wch_table;
260 PVK_TO_WCHARS entry;
261
262 int table_index;
263 int entry_index;
264 int n_levels;
265 int entry_size;
266
267 /* Initialize with defaults */
268 if (consumed_mod_bits)
269 *consumed_mod_bits = 0;
270 if (is_dead)
271 *is_dead = FALSE;
272
273 if (tables == NULL)
274 return WCH_NONE;
275
276 wch_tables = tables->pVkToWcharTable.ptr;
277
278 table_index = info->vk_lookup_table[vk].table;
279 entry_index = info->vk_lookup_table[vk].index;
280
281 if (table_index == -1 || entry_index == -1)
282 return WCH_NONE;
283
284 wch_table = &wch_tables[table_index];
285
286 n_levels = wch_table->nModifications;
287 entry_size = wch_table->cbSize;
288
289 entry = (PVK_TO_WCHARS) ((PBYTE) wch_table->pVkToWchars.ptr
290 + entry_size*entry_index);
291
292 if (entry->VirtualKey == vk)
293 {
294 gboolean have_sgcaps = FALSE;
295 WCHAR best_char = WCH_NONE;
296 BYTE best_modifiers = 0;
297 int best_score = -1;
298 gboolean best_is_dead = FALSE;
299 int level;
300
301 /* Take toggled keys into account. For example, capslock normally inverts the
302 * state of KBDSHIFT (with some exceptions). */
303
304 /* Key supporting capslock */
305 if ((entry->Attributes & CAPLOK) &&
306 /* Ignore capslock if any modifiers other than shift are pressed.
307 * E.g. on the German layout, CapsLock + AltGr + q is the same as
308 * AltGr + q ('@'), but NOT the same as Shift + AltGr + q (not mapped). */
309 !(mod_bits & ~KBDSHIFT) &&
310 (lock_bits & CAPLOK))
311 mod_bits ^= KBDSHIFT;
312
313 /* Key supporting combination of capslock + altgr */
314 if ((entry->Attributes & CAPLOKALTGR) &&
315 (mod_bits & KBDALTGR) &&
316 (lock_bits & CAPLOK))
317 mod_bits ^= KBDSHIFT;
318
319 /* In the Swiss German layout, CapsLock + key is different from Shift + key
320 * for some keys. For such keys, the characters for active capslock are
321 * in the next entry. */
322 if ((entry->Attributes & SGCAPS) &&
323 (lock_bits & CAPLOK))
324 have_sgcaps = TRUE;
325
326 /* I'm not totally sure how kanalok behaves, for now I assume that there
327 * aren't any special cases. */
328 if ((entry->Attributes & KANALOK) &&
329 (lock_bits & KANALOK))
330 mod_bits ^= KBDKANA;
331
332 /* We try to find the entry with the most matching modifiers */
333 for (level = 0; level < n_levels; ++level)
334 {
335 BYTE candidate_modbits = info->level_to_modbits[level];
336 gboolean candidate_is_dead = FALSE;
337 WCHAR c;
338 int score;
339
340 if (candidate_modbits & ~mod_bits)
341 continue;
342
343 /* Some keys have bogus mappings for the control key, e.g. Ctrl +
344 * Backspace = Delete, Ctrl + [ = 0x1B or even Ctrl + Shift + 6 =
345 * 0x1E on a US keyboard. So we have to ignore all cases of
346 * Ctrl that aren't part of AltGr.
347 */
348 if ((candidate_modbits & KBDCTRL) && !(candidate_modbits & KBDALT))
349 continue;
350
351 c = entry->wch[level];
352 if (c == WCH_DEAD || have_sgcaps)
353 {
354 /* Next entry contains the undead/capslocked keys */
355 PVK_TO_WCHARS next_entry;
356 next_entry = (PVK_TO_WCHARS) ((PBYTE) wch_table->pVkToWchars.ptr
357 + entry_size * (entry_index + 1));
358 c = next_entry->wch[level];
359 candidate_is_dead = TRUE;
360 }
361
362 if (c == WCH_DEAD || c == WCH_LGTR || c == WCH_NONE)
363 continue;
364
365 score = POPCOUNT (candidate_modbits & mod_bits);
366 if (score > best_score)
367 {
368 best_score = score;
369 best_char = c;
370 best_modifiers = candidate_modbits;
371 best_is_dead = candidate_is_dead;
372 }
373 }
374
375 if (consumed_mod_bits)
376 *consumed_mod_bits = best_modifiers;
377
378 if (is_dead)
379 *is_dead = best_is_dead;
380
381 return best_char;
382 }
383
384 return WCH_NONE;
385 }
386
387 static void
388 init_vk_lookup_table (GdkWin32KeymapLayoutInfo *info)
389 {
390 PKBDTABLES tables = (PKBDTABLES) info->tables;
391 PVK_TO_WCHAR_TABLE wch_tables;
392 PMODIFIERS modifiers;
393 int i, vk, table_idx;
394
395 g_return_if_fail (tables != NULL);
396
397 wch_tables = tables->pVkToWcharTable.ptr;
398
399 /* Initialize empty table */
400 memset (info->vk_lookup_table, -1, sizeof (info->vk_lookup_table));
401
402 /* Initialize level -> modbits lookup table */
403 memset (info->level_to_modbits, 0, sizeof(info->level_to_modbits));
404 info->max_level = 0;
405
406 modifiers = tables->pCharModifiers.ptr;
407 for (i = 0; i <= modifiers->wMaxModBits; ++i)
408 {
409 if (modifiers->ModNumber[i] != SHFT_INVALID &&
410 modifiers->ModNumber[i] != 0 /* Workaround for buggy layouts*/)
411 {
412 if (modifiers->ModNumber[i] > info->max_level)
413 info->max_level = modifiers->ModNumber[i];
414 info->level_to_modbits[modifiers->ModNumber[i]] = i;
415 }
416 }
417
418 info->max_modbit_value = modifiers->wMaxModBits;
419
420 /* For convenience, we add 256 identity-mapped entries corresponding to the VKs.
421 * This allows us to return a pointer to them from the `gdk_keysym_to_key_entry`
422 * function.
423 */
424
425 for (vk = 0; vk < 256; ++vk)
426 {
427 GdkWin32KeymapKeyEntry key_entry = {0};
428 key_entry.vk = vk;
429 key_entry.mod_bits = 0;
430 key_entry.next = -1;
431 g_array_append_val (info->key_entries, key_entry);
432 }
433
434 /* Special entry for ISO_Left_Tab */
435 {
436 GdkWin32KeymapKeyEntry key_entry = {0};
437 key_entry.vk = VK_TAB;
438 key_entry.mod_bits = KBDSHIFT;
439 key_entry.next = -1;
440 g_array_append_val (info->key_entries, key_entry);
441 }
442
443 /* Initialize generic vk <-> char tables */
444
445 for (table_idx = 0; ; ++table_idx)
446 {
447 PVK_TO_WCHAR_TABLE wch_table = &wch_tables[table_idx];
448 int entry_size;
449 int n_levels;
450 int entry_idx;
451
452 if (wch_table->pVkToWchars.ptr == NULL)
453 break;
454
455 entry_size = wch_table->cbSize;
456 n_levels = wch_table->nModifications;
457
458 for (entry_idx = 0; ; ++entry_idx)
459 {
460 PVK_TO_WCHARS entry;
461 int level;
462
463 entry = (PVK_TO_WCHARS) ((PBYTE) wch_table->pVkToWchars.ptr
464 + entry_size * entry_idx);
465
466 if (entry->VirtualKey == 0)
467 break;
468
469 /* Lookup table to find entry for a VK in O(1). */
470
471 /* Only add the first entry, as some layouts (Swiss German) contain
472 * multiple successive entries for the same VK (SGCAPS). */
473 if (info->vk_lookup_table[entry->VirtualKey].table < 0)
474 {
475 info->vk_lookup_table[entry->VirtualKey].table = table_idx;
476 info->vk_lookup_table[entry->VirtualKey].index = entry_idx;
477 }
478
479 /* Create reverse lookup entries to find a VK+modifier combinations
480 * that results in a given character. */
481 for (level = 0; level < n_levels; ++level)
482 {
483 GdkWin32KeymapKeyEntry key_entry = {0};
484 WCHAR c = entry->wch[level];
485 int inserted_idx;
486 gintptr next_idx;
487
488 key_entry.vk = entry->VirtualKey;
489 key_entry.mod_bits = info->level_to_modbits[level];
490
491 /* There can be multiple combinations that produce the same character.
492 * We store all of them in a linked list.
493 * Check if we already have an entry for the character, so we can chain
494 * them together. */
495 if (g_hash_table_lookup_extended (info->reverse_lookup_table,
496 GINT_TO_POINTER (c),
497 NULL, (gpointer*)&next_idx))
498 {
499 key_entry.next = next_idx;
500 }
501 else
502 {
503 key_entry.next = -1;
504 }
505
506 /* We store the KeyEntry in an array. In the hash table we only store
507 * the index. */
508
509 g_array_append_val (info->key_entries, key_entry);
510 inserted_idx = info->key_entries->len - 1;
511
512 g_hash_table_insert (info->reverse_lookup_table,
513 GINT_TO_POINTER (c),
514 GINT_TO_POINTER (inserted_idx));
515 }
516 }
517 }
518 }
519
520 static gboolean
521 load_layout_dll (const char *dll,
522 GdkWin32KeymapLayoutInfo *info)
523 {
524 typedef KLPKBDTABLES (*KbdLayerDescriptor)(VOID);
525
526 HMODULE lib;
527 KbdLayerDescriptor func;
528 KLPKBDTABLES tables;
529
530 g_return_val_if_fail (dll != NULL, FALSE);
531
532 lib = LoadLibraryA (dll);
533 if (lib == NULL)
534 goto fail1;
535
536 func = (KbdLayerDescriptor) GetProcAddress (lib, "KbdLayerDescriptor");
537 if (func == NULL)
538 goto fail2;
539
540 tables = func();
541
542 info->lib = lib;
543 info->tables = (PKBDTABLES) tables.ptr;
544
545 return TRUE;
546
547 fail2:
548 FreeLibrary (lib);
549 fail1:
550 return FALSE;
551 }
552
553 #if GDK_WIN32_COMPILE_FOR_WOW64
554 #define GDK_WIN32_KEYMAP_IMPL_NAME gdkwin32_keymap_impl_wow64
555 #else
556 #define GDK_WIN32_KEYMAP_IMPL_NAME gdkwin32_keymap_impl
557 #endif
558
559 const GdkWin32KeymapImpl GDK_WIN32_KEYMAP_IMPL_NAME =
560 {
561 load_layout_dll,
562 init_vk_lookup_table,
563 keystate_to_modbits,
564 modbits_to_level,
565 vk_to_char_fuzzy
566 };