File: x11comp.c

package info (click to toggle)
libxkbcommon 1.13.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 8,344 kB
  • sloc: ansic: 57,807; xml: 8,905; python: 7,451; yacc: 913; sh: 253; makefile: 23
file content (573 lines) | stat: -rw-r--r-- 17,608 bytes parent folder | download | duplicates (2)
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
/*
 * Copyright © 2014 Ran Benita <ran234@gmail.com>
 * SPDX-License-Identifier: MIT
 */

#include "config.h"

#include <assert.h>
#include <getopt.h>
#include <signal.h>
#include <spawn.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

#include "xkbcommon/xkbcommon.h"
#include "xkbcommon/xkbcommon-keysyms.h"
#include "xkbcommon/xkbcommon-names.h"
#include "xkbcommon/xkbcommon-x11.h"

#include "evdev-scancodes.h"
#include "test.h"
#include "tools/tools-common.h"
#include "utils.h"
#include "utils-text.h"
#include "xvfb-wrapper.h"

/* Offset between evdev keycodes (where KEY_ESCAPE is 1), and the evdev XKB
 * keycode set (where ESC is 9). */
#define EVDEV_OFFSET 8

enum update_files {
    NO_UPDATE = 0,
    UPDATE_USING_TEST_INPUT,
    UPDATE_USING_TEST_OUTPUT
};

static enum update_files update_test_files = NO_UPDATE;


static char *
prepare_keymap(const char *original, bool strip_all_comments)
{
    if (strip_all_comments) {
        return strip_lines(original, strlen(original), "//");
    } else {
        char *tmp = uncomment(original, strlen(original), "//");
        char *ret = strip_lines(tmp, strlen(tmp), "//");
        free(tmp);
        return ret;
    }
}

/*
 * Reset keymap to `empty` on the server.
 * It seems that xkbcomp does not fully set the keymap on the server and
 * the conflicting leftovers may raise errors.
 */
static int
reset_keymap(const char* display)
{
    char *envp[] = { NULL };
    const char* setxkbmap_argv[] = {
        "setxkbmap", "-display", display,
        "-geometry", "pc",
        "-keycodes", "evdev",
        "-compat", "basic",
        "-types", "basic+numpad", /* Avoid extra types */
        "-symbols", "us",
        // "-v", "10",
        NULL
    };

    /* Launch xkbcomp */
    pid_t setxkbmap_pid;
    int ret = posix_spawnp(&setxkbmap_pid, "setxkbmap", NULL, NULL,
                           (char* const*)setxkbmap_argv, envp);
    if (ret != 0) {
        fprintf(stderr,
                "[ERROR] Cannot run setxkbmap. posix_spawnp error %d: %s\n",
                ret, strerror(ret));
        if (ret == ENOENT) {
            fprintf(stderr,
                    "[ERROR] setxkbmap may be missing. "
                    "Please install the corresponding package, "
                    "e.g. \"setxkbmap\" or \"x11-xkb-utils\".\n");
        }
        return TEST_SETUP_FAILURE;
    }
    int status;
    ret = waitpid(setxkbmap_pid, &status, 0);
    return (ret < 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0)
        ? TEST_SETUP_FAILURE
        : EXIT_SUCCESS;
}

// TODO: unused for now
// /* Use xkbcomp to load a keymap from a file */
// static int
// run_xkbcomp_file(const char* display, xcb_connection_t *conn, int32_t device_id,
//                  const char *xkb_path)
// {
//     /* Prepare xkbcomp parameters */
//     char *envp[] = { NULL };
//     const char* xkbcomp_argv[] = {"xkbcomp", "-I", xkb_path, display, NULL};
//
//     /* Launch xkbcomp */
//     pid_t xkbcomp_pid;
//     int ret = posix_spawnp(&xkbcomp_pid, "xkbcomp", NULL, NULL,
//                            (char* const*)xkbcomp_argv, envp);
//     if (ret != 0) {
//         fprintf(stderr,
//                 "[ERROR] Cannot run xkbcomp. posix_spawnp error %d: %s\n",
//                 ret, strerror(ret));
//         if (ret == ENOENT) {
//             fprintf(stderr,
//                     "[ERROR] xkbcomp may be missing. "
//                     "Please install the corresponding package, "
//                     "e.g. \"xkbcomp\" or \"x11-xkb-utils\".\n");
//         }
//         return TEST_SETUP_FAILURE;
//     }
//
//     /* Wait for xkbcomp to complete */
//     int status;
//     ret = waitpid(xkbcomp_pid, &status, 0);
//     return (ret < 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0)
//         ? TEST_SETUP_FAILURE
//         : EXIT_SUCCESS;
// }

enum {
    PIPE_READ  = 0,
    PIPE_WRITE = 1
};

/* Use xkbcomp to load a keymap from a string */
static int
run_xkbcomp_str(const char* display, const char *include_path, const char *keymap)
{
    int ret = EXIT_FAILURE;
    assert(keymap);

    /* Prepare xkbcomp parameters */
    char *envp[] = { NULL };
    char include_path_arg[PATH_MAX+2] = "-I";
    const char *xkbcomp_argv[] = {
        "xkbcomp", "-I" /* reset include path*/, include_path_arg,
        "-opt", "g", "-w", "10", "-" /* stdin */, display, NULL
    };
    if (include_path) {
        ret = snprintf(include_path_arg, ARRAY_SIZE(include_path_arg),
                       "-I%s", include_path);
        if (ret < 0 || ret >= (int)ARRAY_SIZE(include_path_arg)) {
            return TEST_SETUP_FAILURE;
        }
    }

    /* Prepare input */
    int stdin_pipe[2];
    posix_spawn_file_actions_t action;
    if (pipe(stdin_pipe) == -1) {
        perror("pipe");
        ret = TEST_SETUP_FAILURE;
        goto pipe_error;
    }
    if (posix_spawn_file_actions_init(&action)) {
        perror("spawn_file_actions_init error");
        goto posix_spawn_file_actions_init_error;
    }

    /* Make spawned process close unused write-end of pipe, else it will not
     * receive EOF when write-end of the pipe is closed below and it will result
     * in a deadlock. */
    if (posix_spawn_file_actions_addclose(&action, stdin_pipe[PIPE_WRITE]))
        goto posix_spawn_file_actions_error;
    /* Make spawned process replace stdin with read end of the pipe */
    if (posix_spawn_file_actions_adddup2(&action, stdin_pipe[PIPE_READ], STDIN_FILENO))
        goto posix_spawn_file_actions_error;

    /* Launch xkbcomp */
    pid_t xkbcomp_pid;
    ret = posix_spawnp(&xkbcomp_pid, "xkbcomp", &action, NULL,
                       (char* const*)xkbcomp_argv, envp);
    if (ret != 0) {
        fprintf(stderr,
                "[ERROR] Cannot run xkbcomp. posix_spawnp error %d: %s\n",
                ret, strerror(ret));
        if (ret == ENOENT) {
            fprintf(stderr,
                    "[ERROR] xkbcomp may be missing. "
                    "Please install the corresponding package, "
                    "e.g. \"xkbcomp\" or \"x11-xkb-utils\".\n");
        }
        goto posix_spawn_file_actions_init_error;
    }
    /* Close unused read-end of pipe */
    close(stdin_pipe[PIPE_READ]);
    const ssize_t count = write(stdin_pipe[PIPE_WRITE], keymap, strlen(keymap));
    /* Close write-end of the pipe, to emit EOF */
    close(stdin_pipe[PIPE_WRITE]);
    if (count == -1) {
        perror("Cannot write keymap to stdin");
        kill(xkbcomp_pid, SIGTERM);
    }

    /* Wait for xkbcomp to complete */
    int status;
    ret = waitpid(xkbcomp_pid, &status, 0);
    ret = (ret < 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0)
        ? TEST_SETUP_FAILURE
        : EXIT_SUCCESS;
    goto cleanup;

posix_spawn_file_actions_error:
    perror("posix_spawn_file_actions_* error");
posix_spawn_file_actions_init_error:
    close(stdin_pipe[PIPE_WRITE]);
    close(stdin_pipe[PIPE_READ]);
    ret = TEST_SETUP_FAILURE;
cleanup:
    posix_spawn_file_actions_destroy(&action);
pipe_error:
    return ret;
}

// TODO: implement tests to ensure compatibility with xkbcomp
// struct compile_buffer_private {
//     const char* display;
//     xcb_connection_t *conn;
//     int32_t device_id;
// };
//
// static struct xkb_keymap *
// compile_buffer(struct xkb_context *ctx, const char *buf, size_t len,
//                void *private)
// {
//     const struct compile_buffer_private *config = private;
//     assert(buf[len - 1] == '\0');
//
//     char *include_path = test_get_path("");
//     int ret = run_xkbcomp_str(config->display, config->conn,
//                               config->device_id, include_path, buf);
//     free(include_path);
//
//     if (ret != EXIT_SUCCESS)
//         return NULL;
//
//     return xkb_x11_keymap_new_from_device(ctx, config->conn, config->device_id,
//                                           XKB_KEYMAP_COMPILE_NO_FLAGS);
// }

static int
test_keymap_roundtrip(struct xkb_context *ctx,
                      const char* display, xcb_connection_t *conn,
                      int32_t device_id, bool print_keymap, bool tweak,
                      enum xkb_keymap_serialize_flags serialize_flags,
                      const char *keymap_path)
{
    /* Get raw keymap */
    FILE *file = NULL;
    if (isempty(keymap_path) || strcmp(keymap_path, "-") == 0) {
        /* Read stdin */
        file = tools_read_stdin();
        if (!file)
            return TEST_SETUP_FAILURE;
    } else {
        /* Read file from path */
        file = fopen(keymap_path, "rb");
        if (!file) {
            perror("Unable to read file");
            return TEST_SETUP_FAILURE;
        }
    }
    char *original = read_file(keymap_path, file);
    fclose(file);
    if (!original)
        return TEST_SETUP_FAILURE;

    /* Pre-process keymap string */
    char* expected = prepare_keymap(original, tweak);
    free(original);
    if (!expected) {
        return TEST_SETUP_FAILURE;
    }

    /* Prepare X server */
    int ret = reset_keymap(display);
    if (ret != EXIT_SUCCESS) {
#ifdef __APPLE__
        /* Brew may not provide setxkbmap */
#else
        goto xkbcomp_error;
#endif
    }

    /* Load keymap into X server */
    ret = run_xkbcomp_str(display, NULL, expected);
    if (ret != EXIT_SUCCESS)
        goto xkbcomp_error;

    /* Get keymap from X server */
    struct xkb_keymap *keymap =
        xkb_x11_keymap_new_from_device(ctx, conn, device_id,
                                       XKB_KEYMAP_COMPILE_NO_FLAGS);
    assert(keymap);
    if (!keymap) {
        ret = EXIT_FAILURE;
        fprintf(stderr, "ERROR: Failed to get keymap from X server.\n");
        goto xkbcomp_error;
    }

    /* Dump keymap and compare to expected */
    char *got = xkb_keymap_get_as_string2(keymap, XKB_KEYMAP_USE_ORIGINAL_FORMAT,
                                          serialize_flags);
    if (!got) {
        ret = EXIT_FAILURE;
        fprintf(stderr, "ERROR: Failed to dump keymap.\n");
    } else {
        if (print_keymap)
            fprintf(stdout, "%s\n", got);
        if (!streq(got, expected)) {
            ret = EXIT_FAILURE;
            fprintf(stderr,
                    "ERROR: roundtrip failed. "
                    "Lengths difference: got %zu, expected %zu.\n",
                    strlen(got), strlen(expected));
        } else {
            ret = EXIT_SUCCESS;
            fprintf(stderr, "Roundtrip succeed.\n");
        }
        free(got);
    }

    xkb_keymap_unref(keymap);
xkbcomp_error:
    free(expected);
    return ret;
}

static int
init_x11_connection(const char *display, xcb_connection_t **conn_rtrn,
                    int32_t *device_id_rtrn)
{
    xcb_connection_t *conn = xcb_connect(display, NULL);
    if (xcb_connection_has_error(conn)) {
        return TEST_SETUP_FAILURE;
    }

    int ret = xkb_x11_setup_xkb_extension(conn,
                                          XKB_X11_MIN_MAJOR_XKB_VERSION,
                                          XKB_X11_MIN_MINOR_XKB_VERSION,
                                          XKB_X11_SETUP_XKB_EXTENSION_NO_FLAGS,
                                          NULL, NULL, NULL, NULL);
    if (!ret)
        goto err_xcb;

    int32_t device_id = xkb_x11_get_core_keyboard_device_id(conn);
    if (device_id == -1)
        goto err_xcb;

    *conn_rtrn = conn;
    *device_id_rtrn = device_id;
    return EXIT_SUCCESS;

err_xcb:
    xcb_disconnect(conn);
    return TEST_SETUP_FAILURE;
}

X11_TEST(test_basic)
{
    if (update_test_files != NO_UPDATE)
        return EXIT_SUCCESS;

    xcb_connection_t *conn = NULL;
    int32_t device_id = 0;
    int ret = init_x11_connection(display, &conn, &device_id);
    if (ret != EXIT_SUCCESS) {
        ret = TEST_SETUP_FAILURE;
        goto err_xcb;
    }

    struct xkb_context *ctx = test_get_context(CONTEXT_NO_FLAG);
    assert(ctx);

    static const struct {
        const char *path;
        enum xkb_keymap_serialize_flags serialize_flags;
    } keymaps[] = {
        {
            .path = "keymaps/host-no-pretty.xkb",
            .serialize_flags = TEST_KEYMAP_SERIALIZE_FLAGS
                             & ~XKB_KEYMAP_SERIALIZE_PRETTY
        },
        /* This last keymap will be used for the next tests */
        {
            .path = "keymaps/host.xkb",
            .serialize_flags = TEST_KEYMAP_SERIALIZE_FLAGS
        },
    };
    for (size_t k = 0; k < ARRAY_SIZE(keymaps); k++) {
        fprintf(stderr, "------\n*** %s: #%zu ***\n", __func__, k);
        char *keymap_path = test_get_path(keymaps[k].path);
        assert(keymap_path);

        ret = test_keymap_roundtrip(ctx, display, conn, device_id,
                                    false, false, keymaps[k].serialize_flags,
                                    keymap_path);
        assert(ret == EXIT_SUCCESS);

        free(keymap_path);
    }

    struct xkb_keymap *keymap =
        xkb_x11_keymap_new_from_device(ctx, conn, device_id,
                                       XKB_KEYMAP_COMPILE_NO_FLAGS);

    /* Check capitalization transformation */
    struct xkb_state *state =
        xkb_x11_state_new_from_device(keymap, conn, device_id);
    assert(state);
    xkb_keysym_t sym;
    sym = xkb_state_key_get_one_sym(state, KEY_A + EVDEV_OFFSET);
    assert(sym == XKB_KEY_a);
    sym = xkb_state_key_get_one_sym(state, KEY_LEFT + EVDEV_OFFSET);
    assert(sym == XKB_KEY_Left);
    const xkb_mod_index_t caps_idx =
        xkb_keymap_mod_get_index(keymap, XKB_MOD_NAME_CAPS);
    assert(caps_idx != XKB_MOD_INVALID);
    const xkb_mod_mask_t caps = UINT32_C(1) << caps_idx;
    xkb_state_update_mask(state, 0, 0, caps, 0, 0, 0);
    sym = xkb_state_key_get_one_sym(state, KEY_A + EVDEV_OFFSET);
    assert(sym == XKB_KEY_A);
    sym = xkb_state_key_get_one_sym(state, KEY_LEFT + EVDEV_OFFSET);
    assert(sym == XKB_KEY_Left);
    xkb_state_unref(state);

    xkb_keymap_unref(keymap);
    xkb_context_unref(ctx);

    ret = EXIT_SUCCESS;

err_xcb:
    if (conn != NULL)
        xcb_disconnect(conn);
    return ret;
}

struct xkbcomp_roundtrip_data {
    const char *path;
    bool tweak_comments;
    enum xkb_keymap_serialize_flags serialize_flags;
};

static int
xkbcomp_roundtrip(const char *display, void *private) {
    const struct xkbcomp_roundtrip_data *priv = private;

    xcb_connection_t *conn = NULL;
    int32_t device_id = 0;
    int ret = init_x11_connection(display, &conn, &device_id);
    if (ret != EXIT_SUCCESS) {
        ret = TEST_SETUP_FAILURE;
        goto error_xcb;
    }

    struct xkb_context *ctx = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
    if (!ctx) {
        ret = EXIT_FAILURE;
        goto error_context;
    }

    ret = test_keymap_roundtrip(ctx, display, conn, device_id, true,
                                priv->tweak_comments, priv->serialize_flags,
                                priv->path);

    xkb_context_unref(ctx);
error_context:
error_xcb:
    xcb_disconnect(conn);
    return ret;
}

static void
usage(FILE *fp, char *progname)
{
    fprintf(fp,
            "Usage: %s [--update] [--update-obtained] "
            "[--keymap KEYMAP_FILE] [--tweak] [--no-pretty] [--help]\n",
            progname);
}

int
main(int argc, char **argv) {
    test_init();

    enum options {
        OPT_UPDATE_GOLDEN_TEST_WITH_OUTPUT,
        OPT_UPDATE_GOLDEN_TEST_WITH_INPUT,
        OPT_FILE,
        OPT_TWEAK_COMMENTS,
        OPT_NO_PRETTY,
    };
    static struct option opts[] = {
        {"help",            no_argument,       0, 'h'},
        {"update-obtained", no_argument,       0, OPT_UPDATE_GOLDEN_TEST_WITH_OUTPUT},
        {"update",          no_argument,       0, OPT_UPDATE_GOLDEN_TEST_WITH_INPUT},
        {"keymap",          required_argument, 0, OPT_FILE},
        {"tweak",           no_argument,       0, OPT_TWEAK_COMMENTS},
        {"no-pretty",       no_argument,       0, OPT_NO_PRETTY},
        {0, 0, 0, 0},
    };

    bool tweak_comments = false;
    const char *path = NULL;
    enum xkb_keymap_serialize_flags serialize_flags =
        (enum xkb_keymap_serialize_flags) TEST_KEYMAP_SERIALIZE_FLAGS;

    while (1) {
        int opt;
        int option_index = 0;

        opt = getopt_long(argc, argv, "h", opts, &option_index);
        if (opt == -1)
            break;

        switch (opt) {
        case OPT_UPDATE_GOLDEN_TEST_WITH_OUTPUT:
            update_test_files = UPDATE_USING_TEST_OUTPUT;
            break;
        case OPT_UPDATE_GOLDEN_TEST_WITH_INPUT:
            update_test_files = UPDATE_USING_TEST_INPUT;
            break;
        case OPT_FILE:
            path = optarg;
            break;
        case OPT_TWEAK_COMMENTS:
            tweak_comments = optarg;
            break;
        case OPT_NO_PRETTY:
            serialize_flags &= ~XKB_KEYMAP_SERIALIZE_PRETTY;
            break;
        case 'h':
            usage(stdout, argv[0]);
            return EXIT_SUCCESS;
        default:
            usage(stderr, argv[0]);
            return EXIT_INVALID_USAGE;
        }
    }

    if (update_test_files != NO_UPDATE && path != NULL) {
        fprintf(stderr,
                "ERROR: --update* and --keymap are mutually exclusive.\n");
        usage(stderr, argv[0]);
        return EXIT_INVALID_USAGE;
    }

    if (path == NULL) {
        return x11_tests_run();
    } else {
        struct xkbcomp_roundtrip_data priv = {
            .path = path,
            .tweak_comments = tweak_comments,
            .serialize_flags = serialize_flags
        };
        return xvfb_wrapper(xkbcomp_roundtrip, &priv);
    }
}