summaryrefslogtreecommitdiff
path: root/src/spice-gtk-keyboard.c
blob: 5d194d08a4117eeae80be516de280022d20142c0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
/* -*- Mode: C; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
   Copyright (C) 2016 Red Hat, Inc.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, see <http://www.gnu.org/licenses/>.
*/
#include "config.h"

#include <glib.h>

#ifdef HAVE_X11_XKBLIB_H
#include <X11/XKBlib.h>
#include <gdk/gdkx.h>
#endif
#ifdef GDK_WINDOWING_X11
#include <X11/Xlib.h>
#include <gdk/gdkx.h>
#endif
#ifdef G_OS_WIN32
#include <windows.h>
#include <gdk/gdkwin32.h>
#endif

#include <gtk/gtk.h>

#include "channel-inputs.h"
#include "spice-util-priv.h"
#include "spice-gtk-keyboard.h"

guint32 get_keyboard_lock_modifiers(void)
{
    guint32 modifiers = 0;
#if GTK_CHECK_VERSION(3,18,0)
/* Ignore GLib's too-new warnings */
G_GNUC_BEGIN_IGNORE_DEPRECATIONS
    GdkKeymap *keyboard = gdk_keymap_get_default();

    if (gdk_keymap_get_caps_lock_state(keyboard)) {
        modifiers |= SPICE_INPUTS_CAPS_LOCK;
    }

    if (gdk_keymap_get_num_lock_state(keyboard)) {
        modifiers |= SPICE_INPUTS_NUM_LOCK;
    }

    if (gdk_keymap_get_scroll_lock_state(keyboard)) {
        modifiers |= SPICE_INPUTS_SCROLL_LOCK;
    }
G_GNUC_END_IGNORE_DEPRECATIONS
#elif defined(HAVE_X11_XKBLIB_H)
    Display *x_display = NULL;
    XKeyboardState keyboard_state;

    GdkScreen *screen = gdk_screen_get_default();
    if (!GDK_IS_X11_DISPLAY(gdk_screen_get_display(screen))) {
        SPICE_DEBUG("FIXME: gtk backend is not X11");
        return 0;
    }

    x_display = GDK_SCREEN_XDISPLAY(screen);
    XGetKeyboardControl(x_display, &keyboard_state);

    if (keyboard_state.led_mask & 0x01) {
        modifiers |= SPICE_INPUTS_CAPS_LOCK;
    }
    if (keyboard_state.led_mask & 0x02) {
        modifiers |= SPICE_INPUTS_NUM_LOCK;
    }
    if (keyboard_state.led_mask & 0x04) {
        modifiers |= SPICE_INPUTS_SCROLL_LOCK;
    }
#elif defined(G_OS_WIN32)
    if (GetKeyState(VK_CAPITAL) & 1) {
        modifiers |= SPICE_INPUTS_CAPS_LOCK;
    }
    if (GetKeyState(VK_NUMLOCK) & 1) {
        modifiers |= SPICE_INPUTS_NUM_LOCK;
    }
    if (GetKeyState(VK_SCROLL) & 1) {
        modifiers |= SPICE_INPUTS_SCROLL_LOCK;
    }
#else
    g_warning("get_keyboard_lock_modifiers not implemented");
#endif // GTK_CHECK_VERSION(3,18,0)
    return modifiers;
}

#if defined(HAVE_X11_XKBLIB_H)
typedef enum SpiceLed {
    CAPS_LOCK_LED = 1,
    NUM_LOCK_LED,
    SCROLL_LOCK_LED,
} SpiceLed;

static guint get_modifier_mask(Display *x_display, KeySym modifier)
{
    int mask = 0;
    int i;

    XModifierKeymap* map = XGetModifierMapping(x_display);
    KeyCode keycode = XKeysymToKeycode(x_display, modifier);
    if (keycode == NoSymbol) {
        return 0;
    }

    for (i = 0; i < 8; i++) {
        if (map->modifiermap[map->max_keypermod * i] == keycode) {
            mask = 1 << i;
        }
    }
    XFreeModifiermap(map);
    return mask;
}

static void set_keyboard_led(Display *x_display, SpiceLed led, int set)
{
    guint mask;
    XKeyboardControl keyboard_control;

    switch (led) {
    case CAPS_LOCK_LED:
        if ((mask = get_modifier_mask(x_display, XK_Caps_Lock)) != 0) {
            XkbLockModifiers(x_display, XkbUseCoreKbd, mask, set ? mask : 0);
        }
        return;
    case NUM_LOCK_LED:
        if ((mask = get_modifier_mask(x_display, XK_Num_Lock)) != 0) {
            XkbLockModifiers(x_display, XkbUseCoreKbd, mask, set ? mask : 0);
        }
        return;
    case SCROLL_LOCK_LED:
        keyboard_control.led_mode = set ? LedModeOn : LedModeOff;
        keyboard_control.led = led;
        XChangeKeyboardControl(x_display, KBLed | KBLedMode, &keyboard_control);
        return;
    }
}

void set_keyboard_lock_modifiers(guint32 modifiers)
{
    Display *x_display;

    GdkScreen *screen = gdk_screen_get_default();
    if (!GDK_IS_X11_DISPLAY(gdk_screen_get_display(screen))) {
        SPICE_DEBUG("FIXME: gtk backend is not X11");
        return;
    }

    x_display = GDK_SCREEN_XDISPLAY(screen);

    set_keyboard_led(x_display, CAPS_LOCK_LED, !!(modifiers & SPICE_INPUTS_CAPS_LOCK));
    set_keyboard_led(x_display, NUM_LOCK_LED, !!(modifiers & SPICE_INPUTS_NUM_LOCK));
    set_keyboard_led(x_display, SCROLL_LOCK_LED, !!(modifiers & SPICE_INPUTS_SCROLL_LOCK));
}

gboolean can_set_keyboard_lock_modifiers(void)
{
    return TRUE;
}
#elif defined(G_OS_WIN32)

/* Some definitions from kbd.h to define internal layout file structures */
/* Note that pointer in Wow64 are 64 bit despite program bits */
#define KBDSPECIAL (USHORT)0x0400

/* type of NLS function key */
#define KBDNLS_TYPE_NULL      0
#define KBDNLS_TYPE_NORMAL    1
#define KBDNLS_TYPE_TOGGLE    2

/* action to perform on a specific combination (only needed) */
#define KBDNLS_NULL             0 /* Invalid function */
#define KBDNLS_SEND_BASE_VK     2 /* Send Base VK_xxx */
#define KBDNLS_SEND_PARAM_VK    3 /* Send Parameter VK_xxx */

typedef struct {
    BYTE  NLSFEProcIndex;
    ULONG NLSFEProcParam;
} VK_FPARAM;

typedef struct {
    BYTE Vk;
    BYTE NLSFEProcType;
    BYTE NLSFEProcCurrent;
    BYTE NLSFEProcSwitch;   /* 8 bits */
    VK_FPARAM NLSFEProc[8];
    VK_FPARAM NLSFEProcAlt[8];
} VK_F;

typedef struct {
    USHORT OEMIdentifier;
    USHORT LayoutInformation;
    UINT  NumOfVkToF;
    VK_F *pVkToF;
    void *dummy; /* used to check size */
} KBDNLSTABLES;

typedef void *WINAPI KbdLayerDescriptor_t(void);
typedef BOOL WINAPI KbdLayerRealDllFile_t(HKL hkl, WCHAR *realDllName, LPVOID pClientKbdType, LPVOID reserve1 , LPVOID reserve2);
typedef KBDNLSTABLES *WINAPI KbdNlsLayerDescriptor_t(void);

/* where all keyboard layouts information are in the registry */
#define LAYOUT_REGKEY "SYSTEM\\CurrentControlSet\\Control\\Keyboard Layouts"

static LONG reg_read_str(HKEY key, LPCWSTR name, WCHAR *value, size_t len);
static HMODULE load_keyboard_layout(const WCHAR *dll_name);

/*
 * Read a string from registry
 * @key registry key to read from
 * @name name of the value to read
 * @value buffer where to store results
 * @size size of value buffer in bytes (not value elements!)
 * @returns system error code or ERROR_SUCCESS
 */
static LONG reg_read_str(HKEY key, LPCWSTR name, WCHAR *value, size_t len)
{
    DWORD size = len-sizeof(*value), type;
    LONG err = RegQueryValueExW(key, name, 0, &type, (void *) value, &size);
    if (err != ERROR_SUCCESS)
        return err;

    if (type != REG_SZ)
        return ERROR_INVALID_DATA;

    /* assure terminated */
    value[size/sizeof(*value)] = 0;
    return ERROR_SUCCESS;
}

/*
 * Load a keyboard layout file given the file name
 * @dll_name dll name (should be just file name without paths)
 */
static HMODULE load_keyboard_layout(const WCHAR *dll_name)
{
    WCHAR fn[MAX_PATH+256];

#ifdef _WIN64
    GetSystemDirectoryW(fn, MAX_PATH);
#else
    typedef UINT WINAPI GetSystemWow64DirectoryW_t(LPWSTR str, UINT size);
    GetSystemWow64DirectoryW_t *pGetSystemWow64DirectoryW =
        (GetSystemWow64DirectoryW_t*)GetProcAddress(GetModuleHandle("kernel32"), "GetSystemWow64DirectoryW");
    if (!pGetSystemWow64DirectoryW || pGetSystemWow64DirectoryW(fn, MAX_PATH) == 0)
        GetSystemDirectoryW(fn, MAX_PATH);
#endif
    wcscat(fn, L"\\");
    wcscat(fn, dll_name);

    SPICE_DEBUG("loading file %S", fn);
    return LoadLibraryW(fn);
}

/* keyboard status
 * caps lock VK/SC
 * combination (ctrl+alt+shift / none)
 * ctrl/alt/shift keys VK/SC (2 for each) ?
 */
static WORD vsc_capital = 58;
static int specific_modifiers = -1;

/*
 * Extract information from keyboard.
 * Currently scancode of Caps Lock is searched and
 * possible modifiers needed to have that Caps Lock.
 * @layout layout to get information
 */
void keyboard_cache(HKL layout, const char *layout_name)
{
    WCHAR buf[256];
    char reg_path[256];
    HKEY key;
    LONG err;

    KbdLayerDescriptor_t *get_desc;

    const BYTE *kbd_table;
    int num_keys, i;
    const USHORT *keys;
    const KBDNLSTABLES *nls_table;
    const VK_F *vkf, *vkf_end;

    /* set default output, usually work with lot of keyboard layout
       these values will be used in case of errors */
    vsc_capital = MapVirtualKey(VK_CAPITAL, MAPVK_VK_TO_VSC);
    specific_modifiers = -1;

    /* get keyboard dll name from registry */
    snprintf(reg_path, SPICE_N_ELEMENTS(reg_path), LAYOUT_REGKEY "\\%s", layout_name);
    err = RegOpenKeyEx(HKEY_LOCAL_MACHINE, reg_path, 0, KEY_READ, &key);
    if (err != ERROR_SUCCESS) {
        g_critical("failed getting keyboard layout registry key %s %ld", reg_path, err);
        return;
    }
    err = reg_read_str(key, L"Layout File", buf, sizeof(buf));
    RegCloseKey(key);
    if (err != ERROR_SUCCESS) {
        g_critical("failed getting keyboard layout file name");
        return;
    }

    /* load keyboard layout file */
    HMODULE dll = load_keyboard_layout(buf);
    if (!dll) {
        g_critical("error loading keyboard layout for %08x", (unsigned)(DWORD_PTR)layout);
        return;
    }

    /* see if we need to get another dll */
    KbdLayerRealDllFile_t *dll_file = (KbdLayerRealDllFile_t *) GetProcAddress(dll, "KbdLayerRealDllFile");
    if (dll_file) {
        /* load the other file */
        if (dll_file(layout, buf, NULL, NULL, NULL)) {
            SPICE_DEBUG("dll redirected to %S %u", buf, (unsigned) wcslen(buf));
            HMODULE new_dll = load_keyboard_layout(buf);
            if (new_dll) {
                SPICE_DEBUG("unloading stub");
                FreeLibrary(dll);
                dll = new_dll;
            }
        }
    }

    /* check if there are NLS function (in this case we must parse tables) */
    KbdNlsLayerDescriptor_t *get_nls_desc = (KbdNlsLayerDescriptor_t *) GetProcAddress(dll, "KbdNlsLayerDescriptor");
    if (!get_nls_desc)
        goto cleanup;

    /* get main keyboard table */
    get_desc = (KbdLayerDescriptor_t *) GetProcAddress(dll, "KbdLayerDescriptor");
    if (!get_desc) {
        g_critical("keyboard dll layout has no descriptor");
        goto cleanup;
    }
    kbd_table = (BYTE *) get_desc();

    /* check table (for Win32 see format 32 or 64) */
    if (os_is_64bit()) {
        SPICE_DEBUG("64 bit");
        if (IsBadReadPtr(kbd_table, 12*8)) {
            g_critical("wrong table address");
            goto cleanup;
        }
        keys = *((USHORT **) &kbd_table[6*8]);
        num_keys = kbd_table[7*8];
    } else {
        SPICE_DEBUG("32 bit");
        if (IsBadReadPtr(kbd_table, 13*4)) {
            g_critical("wrong table address");
            goto cleanup;
        }
        keys = *((USHORT **) &kbd_table[6*4]);
        num_keys = kbd_table[7*4];
    }

    /* scan VKs for a VK_CAPITAL not special */
    if (IsBadReadPtr(keys, num_keys*sizeof(*keys))) {
        g_critical("wrong VKs table");
        goto cleanup;
    }
    for (i = 0; i < num_keys; ++i) {
        /* ... return if found */
        if ((keys[i] & KBDSPECIAL) == 0 && (keys[i] & 0xFF) == VK_CAPITAL) {
            vsc_capital = i;
            specific_modifiers = -1;
            goto cleanup;
        }
    }

    /* scan NLS table for VK_CAPITALs */
    nls_table = get_nls_desc();
    if (IsBadReadPtr(keys, sizeof(*nls_table))) {
        g_critical("wrong NLS table");
        goto cleanup;
    }
    vkf = nls_table->pVkToF;
    if (IsBadReadPtr(vkf, sizeof(*vkf) * nls_table->NumOfVkToF)) {
        g_critical("wrong function table");
        goto cleanup;
    }
    SPICE_DEBUG("layout has %u NLS key", (unsigned) nls_table->NumOfVkToF);
    vkf_end = vkf + nls_table->NumOfVkToF;
    for (; vkf < vkf_end; ++vkf) {
        unsigned mask = 0;
        const VK_FPARAM *params = vkf->NLSFEProc;

        /* scan all functions searching for VK_CAPITAL
           check both part, normal and with alternate (if present) */
        for (i = 0; i < 16; ++i) {
            if ((vkf->Vk == VK_CAPITAL && params[i].NLSFEProcIndex == KBDNLS_SEND_BASE_VK)
                || (params[i].NLSFEProcIndex == KBDNLS_SEND_PARAM_VK && params[i].NLSFEProcParam == VK_CAPITAL))
                mask |= 1<<i;
        }
        /* no VK_CAPITAL found */
        if (!mask)
            continue;
        SPICE_DEBUG("found mask %x at vk %x", mask, vkf->Vk);
        /* see if there are a common key between the two tables for
           each special key */
        unsigned common = (mask >> 8) & mask;
        if (common)
            mask = common;
        for (i = 0; i < 16; ++i)
            if (mask & (1<<i)) {
                specific_modifiers = i & 7;
                break;
            }
        /* get back base VK */
        for (i = 0; i < num_keys; ++i) {
            /* ... return if found */
            SPICE_DEBUG("keys %d = %x vk %x", i, keys[i], vkf->Vk);
            if ((keys[i] & KBDSPECIAL) != 0 && (keys[i] & 0xFF) == vkf->Vk) {
                vsc_capital = i;
                goto cleanup;
            }
        }
        /* this is unexpected, there should be a key matching the NLS table */
        g_critical("NLS key not found in normal table");
    }
    specific_modifiers = -1;

cleanup:
    SPICE_DEBUG("unloading dll");
    FreeLibrary(dll);
}

/*
 * Add input keys in order to make the special key (shift/control/alt)
 * state the same as wanted one.
 * @vk virtual key of the key
 * @curr_state current state (!=0 is key down)
 * @wanted_state wanted state (!=0 is key down)
 * @begin_inputs beginning of already present input keys
 * @end_inputs end of already present input keys
 */
static void adjust_special(WORD vk, int curr_state, int wanted_state,
                           INPUT **begin_inputs, INPUT **end_inputs)
{
    KEYBDINPUT *ki;

    curr_state &= 0x80;
    if (!!wanted_state == !!curr_state)
        return;

    /* if there are not the specific key no need to handle */
    UINT vsc = MapVirtualKey(vk, MAPVK_VK_TO_VSC);
    if (!vsc)
        return;

    /* make sure modifier key is in the right state before pressing
       main key */
    --(*begin_inputs);
    ki = &(*begin_inputs)->ki;
    ki->wVk = vk;
    ki->wScan = vsc;
    ki->dwFlags = wanted_state ? 0 : KEYEVENTF_KEYUP;

    /* make sure key state is restored at the end */
    ki = &(*end_inputs)->ki;
    ki->wVk = vk;
    ki->wScan = vsc;
    ki->dwFlags = wanted_state ? KEYEVENTF_KEYUP : 0;
    ++(*end_inputs);
}

/*
 * Add a key pression and a release to inputs events
 */
static gboolean add_press_release(INPUT *inputs, WORD vk, WORD vsc)
{
    KEYBDINPUT *ki;

    if (!vsc)
        return FALSE;

    ki = &inputs[0].ki;
    ki->wVk = vk;
    ki->wScan = vsc;
    ki = &inputs[1].ki;
    ki->wVk = vk;
    ki->wScan = vsc;
    ki->dwFlags = KEYEVENTF_KEYUP;

    return TRUE;
}

void set_keyboard_lock_modifiers(guint32 modifiers)
{
    static HKL cached_layout = 0;

    /* get keyboard layout */
    HKL curr_layout = GetKeyboardLayout(0);

    /* same as before, use old informations.. */
    if (curr_layout != cached_layout) {
        /* .. otherwise cache new keyboard layout */
        char curr_layout_name[KL_NAMELENGTH + 1];
        if (GetKeyboardLayoutName(curr_layout_name)) {
            keyboard_cache(curr_layout, curr_layout_name);
            cached_layout = curr_layout;
        }
    }

    BYTE key_states[256];
    GetKeyboardState(key_states);

    /* compute sequence to press
     * as documented in SetKeyboardState we must press
     * the sequence that cause the state to change
     * to modify the global state */
    int i;
    INPUT inputs[6*2+2+4], *begin_inputs, *end_inputs;
    memset(inputs, 0, sizeof(inputs));
    for (i = 0; i < G_N_ELEMENTS(inputs); ++i) {
        inputs[i].type = INPUT_KEYBOARD;
        inputs[i].ki.dwExtraInfo = 0x12345678;
    }

    /* start pointers, make sure we have enough space
       before and after to insert shift/control/alt keys */
    begin_inputs = end_inputs = inputs + 6;

    /* we surely must press the caps lock key */
    if ((!!(modifiers & SPICE_INPUTS_CAPS_LOCK) != !!(key_states[VK_CAPITAL] & 1))
        && add_press_release(end_inputs, VK_CAPITAL, vsc_capital)) {
        end_inputs += 2;

        /* unfortunately the key expect a specific combination
           of shift/control/alt, make sure we have that state */
        if (specific_modifiers >= 0) {

#define adjust_special(vk, mask)  \
    adjust_special((vk), key_states[vk], specific_modifiers & (mask), &begin_inputs, &end_inputs)

            adjust_special(VK_LSHIFT, 1);
            adjust_special(VK_RSHIFT, 1);
            adjust_special(VK_LCONTROL, 2);
            adjust_special(VK_RCONTROL, 2);
            adjust_special(VK_LMENU, 4);
            adjust_special(VK_RMENU, 4);
        }
    }

    /* sync NUMLOCK */
    if ((!!(modifiers & SPICE_INPUTS_NUM_LOCK) != !!(key_states[VK_NUMLOCK] & 1))
        && add_press_release(end_inputs, VK_NUMLOCK, MapVirtualKey(VK_NUMLOCK, MAPVK_VK_TO_VSC))) {
        end_inputs += 2;
    }

    /* sync SCROLLLOCK */
    if ((!!(modifiers & SPICE_INPUTS_SCROLL_LOCK) != !!(key_states[VK_SCROLL] & 1))
        && add_press_release(end_inputs, VK_SCROLL, MapVirtualKey(VK_SCROLL, MAPVK_VK_TO_VSC))) {
        end_inputs += 2;
    }

    /* press the sequence */
    if (end_inputs > begin_inputs) {
        BlockInput(TRUE);
        SendInput(end_inputs - begin_inputs, begin_inputs, sizeof(inputs[0]));
        BlockInput(FALSE);
    }
}

gboolean can_set_keyboard_lock_modifiers(void)
{
    return TRUE;
}
#else

void set_keyboard_lock_modifiers(guint32 modifiers)
{
    g_warning("set_keyboard_lock_modifiers not implemented");
}

gboolean can_set_keyboard_lock_modifiers(void)
{
    return FALSE;
}
#endif