summaryrefslogtreecommitdiff
path: root/multitouch.c
blob: 4a3d8e006c0bfbb12533ee30bb1d23e5ff26d7e7 (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
#if HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#include <signal.h>
#include <poll.h>
#include <stdint.h>
#include <math.h>

#include <cairo.h>
#include <cairo-xlib.h>

#include <X11/Xlib.h>
#include <X11/extensions/XInput.h>
#include <X11/extensions/XInput2.h>

#define MAX_TOUCHES 10

static void usage(void)
{
    printf("Usage:\n");
    printf("	Grey window: normal touch surface\n");
    printf("	Black bar left: grabs the touchpoint, no ownership\n");
    printf("	White bar left: grabs the touchpoint, with ownership\n");
}

enum TouchState {
    TSTATE_END = 0,
    TSTATE_BEGIN,
    TSTATE_UPDATE,
};

struct touchpoint {
    enum TouchState state;
    uint32_t touchid; /* 0 == unused */
    double x, y;   /* last recorded x/y position */
};

struct grabpoint {
    enum TouchState state;
    uint32_t touchid;
    double startx, starty; /* x/y of TouchBegin */
    double x, y;           /* last recorded x/y position */
};

struct multitouch {
    Display *dpy;
    int screen_no;
    Screen* screen;
    Window root;
    Window win;
    Window blackbar;
    Window whitebar;
    GC gc;
    Visual *visual;
    int xi_opcode;

    Pixmap pixmap;

    int width;
    int height;

    cairo_t *cr;
    cairo_t *cr_win;
    cairo_t *cr_grabs;
    cairo_surface_t *surface;
    cairo_surface_t *surface_win;
    cairo_surface_t *surface_grabs;

    struct touchpoint touches[MAX_TOUCHES];
    int ntouches;

    struct grabpoint grabs[MAX_TOUCHES];
    size_t ngrabs;
};

static void expose(struct multitouch *mt, int x1, int y1, int x2, int y2);

static int error(const char *fmt, ...)
{
    va_list args;
    fprintf(stderr, "E: ");

    va_start(args, fmt);
    vfprintf(stderr, fmt, args);
    va_end(args);

    return EXIT_FAILURE;
}

static void msg(const char *fmt, ...)
{
    va_list args;
    printf("M: ");

    va_start(args, fmt);
    vprintf(fmt, args);
    va_end(args);
}

static int running = 1;
static void sighandler(int signal)
{
    running = 0;
    error("signal received, shutting down\n");
}

static void init_windows(struct multitouch *mt)
{
    Window win, subwin;
    XEvent event;
    XIEventMask evmask;
    unsigned char mask[XIMaskLen(XI_LASTEVENT)];
    XIGrabModifiers modifiers;

    win = XCreateSimpleWindow(mt->dpy, mt->root, 0, 0, mt->width, mt->height,
                              0, 0, WhitePixel(mt->dpy, mt->screen_no));
    mt->win = win;

    subwin = XCreateSimpleWindow(mt->dpy, win, 0, 0, 50, mt->height/2, 0, 0,
                                 BlackPixel(mt->dpy, mt->screen_no));
    mt->blackbar = subwin;

    subwin = XCreateSimpleWindow(mt->dpy, win, 0, mt->height/2, 50, mt->height/2, 0, 0,
                                 WhitePixel(mt->dpy, mt->screen_no));
    mt->whitebar = subwin;

    /* select for touch events on main window */
    XSelectInput(mt->dpy, win, ExposureMask);
    XMapSubwindows(mt->dpy, win);
    XMapWindow(mt->dpy, win);
    XMaskEvent(mt->dpy, ExposureMask, &event);

    evmask.mask = mask;
    evmask.mask_len = sizeof(mask);
    memset(mask, 0, sizeof(mask));
    evmask.deviceid = XIAllMasterDevices;

    XISetMask(mask, XI_TouchBegin);
    XISetMask(mask, XI_TouchUpdate);
    XISetMask(mask, XI_TouchEnd);

    XISelectEvents(mt->dpy, win, &evmask, 1);


    /* grab touch events on blackbar */
    modifiers.modifiers = XIAnyModifier;
    if (XIGrabTouchBegin(mt->dpy, XIAllMasterDevices, mt->blackbar,
                         XINoOwnerEvents, &evmask, 1, &modifiers) != 0)
        error("Failed to establish passive grab on blackbar\n");

    /* grab touch events with ownership on whitebar */
    XISetMask(mask, XI_TouchOwnership);
    if (XIGrabTouchBegin(mt->dpy, XIAllMasterDevices, mt->whitebar,
                         XINoOwnerEvents, &evmask, 1, &modifiers) != 0)
        error("Failed to establish passive grab on blackbar\n");

    XSync(mt->dpy, False);
}

static Pixmap init_pixmap(struct multitouch *mt)
{
    Pixmap p;
    p = XCreatePixmap(mt->dpy, mt->win, mt->width, mt->height,
                      DefaultDepth(mt->dpy, mt->screen_no));
    return p;
}

static GC init_gc(struct multitouch *mt)
{
    GC gc;

    gc = XCreateGC(mt->dpy, mt->win, 0, NULL);

    return gc;
}

static int init_x11(struct multitouch *mt, int width, int height)
{
    Display *dpy;
    int major = 2, minor = 2;
    int xi_opcode, xi_error, xi_event;

    dpy = XOpenDisplay(NULL);
    if (!dpy)
        return error("Invalid DISPLAY.\n");

    if (!XQueryExtension(dpy, INAME, &xi_opcode, &xi_event, &xi_error))
        return error("No X Input extension\n");

    if (XIQueryVersion(dpy, &major, &minor) != Success ||
        major * 10 + minor < 22)
        return error("Need XI 2.2\n");

    mt->dpy       = dpy;
    mt->screen_no = DefaultScreen(dpy);
    mt->screen    = DefaultScreenOfDisplay(dpy);
    mt->root      = DefaultRootWindow(dpy);
    mt->visual    = DefaultVisual(dpy, mt->screen_no);
    mt->xi_opcode = xi_opcode;
    mt->width     = width;
    mt->height    = height;

    init_windows(mt);

    mt->pixmap = init_pixmap(mt);
    mt->gc = init_gc(mt);
    if (!mt->win)
        return error("Failed to create window.\n");

    XFlush(mt->dpy);
    return EXIT_SUCCESS;
}

static void teardown(struct multitouch *mt)
{
    if (mt->win)
        XUnmapWindow(mt->dpy, mt->win);
    XCloseDisplay(mt->dpy);
}

static void print_event(struct multitouch *mt, XIDeviceEvent* event)
{
    const char *type;
    switch(event->evtype)
    {
        case XI_TouchBegin:  type = "TouchBegin";  break;
        case XI_TouchUpdate: type = "TouchUpdate"; break;
        case XI_TouchEnd:    type = "TouchEnd";    break;
    }
    msg("Event: %s (%d)\n", type, event->deviceid);
    msg("\t%.2f/%.2f (%.2f/%.2f)\n", event->event_x, event->event_y, event->root_x, event->root_y);
    msg("\ttouchid: %d\n", event->detail);
    msg("\ton %s\n", event->event == mt->win ? "window" : "blackbar");
}

static void paint_touch_begin(struct multitouch *mt, XIDeviceEvent *event)
{
    int i;
    int radius = 30;
    struct touchpoint *t = NULL;

    for (i = 0; i < mt->ntouches; i++)
    {
        if (mt->touches[i].state == TSTATE_END)
        {
            t = &mt->touches[i];
            break;
        }
    }
    if (!t)
    {
        error("Too many touchpoints, skipping\n");
        return;
    }

    t->touchid = event->detail;
    t->x = event->event_x;
    t->y = event->event_y;
    t->state = TSTATE_BEGIN;

    cairo_save(mt->cr);
    cairo_set_source_rgb(mt->cr, 0, 0, 0);
    cairo_arc(mt->cr, t->x, t->y, radius, 0, 2 * M_PI);
    cairo_stroke(mt->cr);
    cairo_restore(mt->cr);
    expose(mt, t->x - radius, t->y - radius, t->x + radius, t->y + radius);
}

static struct touchpoint* find_touch(struct multitouch *mt, uint32_t touchid)
{
    int i;

    for (i = 0; i < mt->ntouches; i++)
        if (mt->touches[i].state != TSTATE_END &&
            mt->touches[i].touchid == touchid)
            return &mt->touches[i];

    return NULL;
}

static void paint_touch_update(struct multitouch *mt, XIDeviceEvent *event)
{
    struct touchpoint *t = find_touch(mt, event->detail);

    cairo_save(mt->cr);
    cairo_set_source_rgb(mt->cr, 0, 0, 0);
    cairo_move_to(mt->cr, t->x, t->y);
    cairo_line_to(mt->cr, event->event_x, event->event_y);
    cairo_stroke(mt->cr);
    cairo_restore(mt->cr);
    expose(mt, t->x, t->y, event->event_x, event->event_y);

    t->x = event->event_x;
    t->y = event->event_y;
    t->state = TSTATE_UPDATE;
}

static void paint_touch_end(struct multitouch *mt, XIDeviceEvent *event)
{
    int rsize = 30;
    struct touchpoint *t = find_touch(mt, event->detail);

    t->x = event->event_x;
    t->y = event->event_y;
    t->state = TSTATE_END;

    cairo_save(mt->cr);
    cairo_set_source_rgb(mt->cr, 0, 0, 0);
    cairo_rectangle(mt->cr, t->x - rsize/2, t->y - rsize/2, rsize, rsize);
    cairo_stroke(mt->cr);
    cairo_restore(mt->cr);
    expose(mt, t->x - rsize/2, t->y - rsize/2, t->x + rsize/2, t->y + rsize/2);

}

static void paint_grabs(struct multitouch *mt)
{
    const int radius = 50;
    struct grabpoint *grab;
    int i;

    /* clear the whole area */
    cairo_save(mt->cr_grabs);
    cairo_save(mt->cr_grabs);
    cairo_set_operator(mt->cr_grabs, CAIRO_OPERATOR_CLEAR);
    cairo_paint(mt->cr_grabs);
    cairo_restore(mt->cr_grabs);


    for (i = 0; i < mt->ngrabs; i++)
    {
        grab = &mt->grabs[i];

        if (grab->state == TSTATE_END)
            continue;

        /* draw starting circle */
        cairo_set_source_rgba(mt->cr_grabs, 0, 0, 1, 1);
        cairo_move_to(mt->cr_grabs, grab->startx + radius, grab->starty);
        cairo_arc(mt->cr_grabs, grab->startx, grab->starty, radius, 0, 2 * M_PI);
        cairo_stroke(mt->cr_grabs);

        /* draw line to current point */
        cairo_set_source_rgba(mt->cr_grabs, 0, 0, 1, 1);
        cairo_move_to(mt->cr_grabs, grab->startx, grab->starty);
        cairo_line_to(mt->cr_grabs, grab->x, grab->y);

        msg("%d: %.2f/%.2f %.2f/%.2f\n", i, grab->startx, grab->starty, grab->x,
                grab->y);
    }

    cairo_stroke(mt->cr_grabs);
    cairo_restore(mt->cr_grabs);
}

static void handle_grabbed_event(struct multitouch *mt, XIDeviceEvent *event)
{
    struct grabpoint *grab = NULL;

    int i;
    for (i = 0; i < mt->ngrabs; i++)
    {
        grab = &mt->grabs[i];
        if (event->evtype == XI_TouchBegin && grab->state == TSTATE_END)
        {
                grab->state = TSTATE_BEGIN;
                grab->touchid = event->detail;
                grab->startx = event->event_x;
                grab->starty = event->event_y;
                break;
        } else if (event->evtype != XI_TouchBegin) {
            if (grab->state != TSTATE_END && grab->touchid == event->detail)
                break;
        }
    }
    if (!grab) {
        error("oops, touchpoint for %d (touchid %d) not found\n",
                event->evtype, event->detail);
        return;
    }

    grab->x = event->event_x;
    grab->y = event->event_y;

    paint_grabs(mt);
    expose(mt, 0, 0, mt->width, mt->height);

    switch (event->evtype)
    {
        case XI_TouchEnd: grab->state = TSTATE_END; break;
        case XI_TouchUpdate: grab->state = TSTATE_UPDATE; break;
    }
}

static void paint_event(struct multitouch *mt, XIDeviceEvent *event)
{
    if (event->event == mt->blackbar)
    {
        handle_grabbed_event(mt, event);
        return;
    }

    switch(event->evtype)
    {
        case XI_TouchBegin: paint_touch_begin(mt, event); break;
        case XI_TouchUpdate: paint_touch_update(mt, event); break;
        case XI_TouchEnd: paint_touch_end(mt, event); break;
    }
}


static int init_cairo(struct multitouch *mt)
{
    cairo_surface_t *surface;
    cairo_t *cr;

    /* frontbuffer */
    surface = cairo_xlib_surface_create(mt->dpy, mt->win,
                                        mt->visual, mt->width, mt->height);
    if (!surface)
        return error("Failed to create cairo surface\n");

    mt->surface_win = surface;

    cr = cairo_create(surface);
    if (!cr)
        return error("Failed to create cairo context\n");

    mt->cr_win = cr;

    /* grab drawing backbuffer */
    surface = cairo_surface_create_similar(surface,
                                           CAIRO_CONTENT_COLOR_ALPHA,
                                           mt->width, mt->height);
    if (!surface)
        return error("Failed to create cairo surface\n");

    mt->surface_grabs = surface;

    cr = cairo_create(surface);
    if (!cr)
        return error("Failed to create cairo context\n");

    mt->cr_grabs = cr;

    /* backbuffer */
    surface = cairo_surface_create_similar(surface,
                                           CAIRO_CONTENT_COLOR_ALPHA,
                                           mt->width, mt->height);
    if (!surface)
        return error("Failed to create cairo surface\n");

    mt->surface = surface;

    cr = cairo_create(surface);
    if (!cr)
        return error("Failed to create cairo context\n");

    cairo_set_line_width(cr, 1);
    cairo_set_source_rgb(cr, .85, .85, .85);
    cairo_rectangle(cr, 0, 0, mt->width, mt->height);
    cairo_fill(cr);

    mt->cr = cr;

    expose(mt, 0, 0, mt->width, mt->height);

    return EXIT_SUCCESS;
}

static void expose(struct multitouch *mt, int x1, int y1, int x2, int y2)
{
    cairo_set_source_surface(mt->cr_win, mt->surface, 0, 0);
    cairo_paint(mt->cr_win);

    cairo_save(mt->cr_win);
    cairo_set_source_surface(mt->cr_win, mt->surface_grabs, 0, 0);
    cairo_mask_surface(mt->cr_win, mt->surface_grabs, 0, 0);
    cairo_restore(mt->cr_win);

}

static int main_loop(struct multitouch *mt)
{
    struct pollfd fd;

    fd.fd = ConnectionNumber(mt->dpy);
    fd.events = POLLIN;

    while (running)
    {

        if (poll(&fd, 1, 500) <= 0)
            continue;

        while (XPending(mt->dpy)) {
            XEvent ev;
            XGenericEventCookie *cookie = &ev.xcookie;

            XNextEvent(mt->dpy, &ev);
            if (ev.type == Expose) {
                expose(mt, ev.xexpose.x, ev.xexpose.y,
                           ev.xexpose.x + ev.xexpose.width,
                           ev.xexpose.y + ev.xexpose.height);
            } else if (ev.type == GenericEvent &&
                XGetEventData(mt->dpy, cookie) &&
                cookie->type == GenericEvent &&
                cookie->extension == mt->xi_opcode)
            {
                paint_event(mt, cookie->data);
                print_event(mt, cookie->data);
            }

            XFreeEventData(mt->dpy, cookie);
        }
    }

    return EXIT_SUCCESS;
}

static void init(struct multitouch *mt)
{
    memset(mt, 0, sizeof(*mt));

    mt->ntouches = MAX_TOUCHES;
    mt->ngrabs = MAX_TOUCHES;
}

int main(int argc, char **argv)
{
    int rc;
    struct multitouch mt;

    usage();

    init(&mt);

    rc = init_x11(&mt, 800, 600);
    if (rc != EXIT_SUCCESS)
        return rc;

    rc = init_cairo(&mt);
    if (rc != EXIT_SUCCESS)
        return rc;

    signal(SIGINT, sighandler);

    main_loop(&mt);

    teardown(&mt);

    return EXIT_SUCCESS;
}