-
Notifications
You must be signed in to change notification settings - Fork 0
/
xdpb.c
652 lines (552 loc) · 15.2 KB
/
xdpb.c
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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
/*
* xdpb -- X Display Pointer Barriers.
*
* Copyright (c), Zev Weiss <[email protected]>
*
* Sets up pointer barriers at the edges of each display so that it's easier
* to position the mouse at screen edges (e.g. for scroll bars, etc.).
*
* This file began life as a modified version of
* pointer-barriers-interactive.c by Jasper St. Pierre (not that there's much
* left of it).
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <time.h>
#include <math.h>
#include <stdlib.h>
#include <errno.h>
#include <assert.h>
#include <string.h>
#include <stdio.h>
#include <getopt.h>
#include <unistd.h>
#include <signal.h>
#include <search.h>
#include <sys/time.h>
#include <X11/Xatom.h>
#include <X11/Xlib.h>
#include <X11/extensions/Xfixes.h>
#include <X11/extensions/XInput2.h>
#include <X11/extensions/Xrandr.h>
#ifdef DEBUG
#define dbg(...) (void)fprintf(stderr, __VA_ARGS__)
#else
/* Define as an empty function so arguments get used */
static inline void dbg(const char* fmt, ...) { }
#endif
#define internal_error(msg, ...) do { \
fprintf(stderr, "Internal error: "msg"\n", ##__VA_ARGS__); \
abort(); \
} while (0)
struct pbinfo {
PointerBarrier bar;
int dir;
union {
double distance;
struct {
double last_tap;
int on;
} taphist;
};
};
static const char* progname;
/* What mechanism we use to trigger release */
static enum {
REL__UNSET_,
REL_SPEED,
REL_DISTANCE,
REL_DOUBLETAP,
} releasemode = REL__UNSET_;
/* Pixels or speed needed to release pointer from barrier */
static double threshold;
static Display* dpy;
static Window rootwin;
static int xi2_opcode, xrr_opcode, xrr_event_base;
static int sigpipe[2];
/* Root of a tsearch() tree, so we can look up a struct pbinfo from a PointerBarrier */
static void* pbmap = NULL;
static int pbcmp(const void* va, const void* vb)
{
const struct pbinfo* a = va;
const struct pbinfo* b = vb;
return (a->bar > b->bar) ? 1 : (a->bar < b->bar) ? -1 : 0;
}
/* Add pbi to pbmap */
static inline void add_pbi(const struct pbinfo* pbi)
{
struct pbinfo* old = tsearch(pbi, &pbmap, pbcmp);
if (*(struct pbinfo**)old != pbi)
internal_error("PointerBarrier %lu already in pbmap", pbi->bar);
}
/* Lookup pb in pbmap */
static inline struct pbinfo* find_pbi(PointerBarrier pb)
{
void* v;
struct pbinfo k = { .bar = pb, };
v = tfind(&k, &pbmap, pbcmp);
if (!v)
return NULL;
return *(struct pbinfo**)v;
}
/* Error-checking malloc() wrapper */
static inline void* xmalloc(size_t s)
{
void* p = malloc(s);
if (!p) {
fprintf(stderr, "malloc: %s", strerror(errno));
exit(1);
}
return p;
}
/* Return the current seconds-since-epoch time as a double */
static inline double dnow(void)
{
struct timeval t;
if (gettimeofday(&t, NULL))
internal_error("gettimeofday: %s\n", strerror(errno));
return (double)t.tv_sec + (((double)t.tv_usec) / 1000000);
}
static void handle_barrier_leave(XIBarrierEvent* event)
{
struct pbinfo* pbi = find_pbi(event->barrier);
if (!pbi) {
dbg("BarrierLeave on unknown (stale?) barrier %lu\n", event->barrier);
return;
}
dbg("BarrierLeave [%lu], delta: %.2f/%.2f\n", event->barrier, event->dx, event->dy);
switch (releasemode) {
case REL_DISTANCE:
pbi->distance = 0.0;
break;
case REL_SPEED:
break;
case REL_DOUBLETAP:
pbi->taphist.on = 0;
break;
default:
internal_error("invalid pbi->dir (%u)", pbi->dir);
}
}
static void handle_barrier_hit(XIBarrierEvent* event)
{
int release;
double d, now;
struct pbinfo* pbi = find_pbi(event->barrier);
if (!pbi) {
dbg("BarrierHit on unknown (stale?) barrier %lu\n", event->barrier);
return;
}
dbg("BarrierHit [%lu], delta: %.2f/%.2f\n", event->barrier, event->dx, event->dy);
switch (pbi->dir) {
case BarrierPositiveX:
d = -event->dx;
break;
case BarrierNegativeX:
d = event->dx;
break;
case BarrierPositiveY:
d = -event->dy;
break;
case BarrierNegativeY:
d = event->dy;
break;
default:
internal_error("invalid pbi->dir (%u)", pbi->dir);
}
/*
* Apparent movement *away* from the barrier on a *hit* event seems to
* happen sometimes; ignore it.
*/
if (d < 0.0)
return;
switch (releasemode) {
case REL_SPEED:
release = d > threshold;
break;
case REL_DISTANCE:
pbi->distance += d;
release = pbi->distance > threshold;
if (release)
pbi->distance = 0.0;
break;
case REL_DOUBLETAP:
if (!pbi->taphist.on) {
now = dnow();
release = (now - pbi->taphist.last_tap) < threshold;
if (!release) {
pbi->taphist.last_tap = now;
pbi->taphist.on = 1;
}
} else
release = 0;
break;
default:
internal_error("invalid releasemode (%d)", releasemode);
}
if (release) {
XIBarrierReleasePointer(dpy, event->deviceid, event->barrier, event->eventid);
XFlush(dpy);
}
}
/* Check for necessary extensions, initializing {xi2,xrr}_* globals. */
static void check_extensions(void)
{
int major, minor, opcode, evt, err;
if (!XQueryExtension(dpy, "RANDR", &xrr_opcode, &evt, &err)) {
fprintf(stderr, "XRandr extension not found\n");
exit(1);
}
if (!XRRQueryExtension(dpy, &xrr_event_base, &err)) {
fprintf(stderr, "XRandr present...but also not?\n");
exit(1);
}
if (!XQueryExtension(dpy, "XFIXES", &opcode, &evt, &err)) {
fprintf(stderr, "XFixes extension not found\n");
exit(1);
}
if (!XFixesQueryVersion(dpy, &major, &minor) || (major * 10 + minor) < 50) {
fprintf(stderr, "XFixes too old (have %d.%d, need 5.0+)\n", major, minor);
exit(1);
}
if (!XQueryExtension(dpy, "XInputExtension", &xi2_opcode, &evt, &err)) {
fprintf(stderr, "XInput extension not found\n");
exit(1);
}
major = 2;
minor = 3;
if (XIQueryVersion(dpy, &major, &minor) != Success || ((major * 10) + minor) < 22) {
fprintf(stderr, "XInput too old (have %d.%d, need 2.2+)\n", major, minor);
exit(1);
}
}
static void mkbar(int x1, int y1, int x2, int y2, int directions)
{
struct pbinfo* pbi;
PointerBarrier pb = XFixesCreatePointerBarrier(dpy, rootwin, x1, y1, x2, y2,
directions, 0, NULL);
dbg("mkbar(%d, %d, %d, %d, %d) = %lu\n", x1, y1, x2, y2, directions, pb);
#ifdef DEBUG
XSync(dpy, False);
#endif
pbi = xmalloc(sizeof(*pbi));
memset(pbi, 0, sizeof(*pbi));
pbi->bar = pb;
pbi->dir = directions;
add_pbi(pbi);
}
static int point_within_crtc(XRRCrtcInfo* ci, int x, int y)
{
int xmin = ci->x, xmax = ci->x + ci->width - 1;
int ymin = ci->y, ymax = ci->y + ci->height - 1;
return x >= xmin && x <= xmax && y >= ymin && y <= ymax;
}
static int point_on_any_crtc(int ncrtc, XRRCrtcInfo** crtcinfos, int x, int y)
{
for (int i = 0; i < ncrtc; i++) {
if (point_within_crtc(crtcinfos[i], x, y))
return 1;
}
return 0;
}
/*
* Traverse a line (assumed to be a screen edge) between XSTART,YSTART and
* XEND,YEND creating barriers along it in direction DIR for any segments for
* which the next pixel over in the opposite direction of DIR is within one of
* the NCRTC crtcs in CRTCINFOS.
*/
static void scan_edge(int ncrtc, XRRCrtcInfo** crtcinfos, int xstart, int ystart,
int xend, int yend, int dir)
{
int x, y; /* current point along the line */
int dx, dy; /* x/y delta for moving along the line we're scanning */
int qx, qy; /* x/y delta for the neighbor point whose existence we query */
int within_internal_edge = 0; /* state bit */
int barstart_x, barstart_y; /* where the current barrier started */
int xmin = xstart < xend ? xstart : xend;
int xmax = xstart > xend ? xstart : xend;
int ymin = ystart < yend ? ystart : yend;
int ymax = ystart > yend ? ystart : yend;
switch (dir) {
case BarrierPositiveX:
assert(xstart == xend);
assert(ystart != yend);
dx = 0;
dy = yend > ystart ? 1 : -1;
qx = -1;
qy = 0;
break;
case BarrierPositiveY:
assert(xstart != xend);
assert(ystart == yend);
dx = xend > xstart ? 1 : -1;
dy = 0;
qx = 0;
qy = -1;
break;
case BarrierNegativeX:
assert(xstart == xend);
assert(ystart != yend);
dx = 0;
dy = yend > ystart ? 1 : -1;
qx = 1;
qy = 0;
break;
case BarrierNegativeY:
assert(xstart != xend);
assert(ystart == yend);
dx = xend > xstart ? 1 : -1;
dy = 0;
qx = 0;
qy = 1;
break;
default:
internal_error("bad direction %d in %s\n", dir, __func__);
}
for (x = xstart, y = ystart;
x >= xmin && x <= xmax && y >= ymin && y <= ymax;
x += dx, y += dy) {
int nx = x + qx, ny = y + qy; /* neighbor x/y */
/*
* If the neighbor point exists on a screen, we must be
* somewhere along an internal screen edge.
*/
int internal_edge = point_on_any_crtc(ncrtc, crtcinfos, nx, ny);
if (!within_internal_edge && internal_edge) {
/* record barrier starting point */
barstart_x = x;
barstart_y = y;
} else if (within_internal_edge && !internal_edge) {
/*
* Okay, we've hit the end of an internal-edge
* segment; now pop up a barrier along it.
*/
int barend_x = x - dx, barend_y = y - dy;
mkbar(barstart_x, barstart_y, barend_x, barend_y, dir);
}
within_internal_edge = internal_edge;
}
/*
* If we found the beginning of an internal-edge segment but never ran
* off the end of it, it must run all the way to the edge of the
* screen; handle that here.
*/
if (within_internal_edge) {
int barend_x = x - dx, barend_y = y - dy;
mkbar(barstart_x, barstart_y, barend_x, barend_y, dir);
}
}
static void setup_crtc_barriers(XRRCrtcInfo* ci, int ncrtc, XRRCrtcInfo** crtcinfos)
{
unsigned int xmin = ci->x, xmax = ci->x + ci->width - 1;
unsigned int ymin = ci->y, ymax = ci->y + ci->height - 1;
dbg("%s(%u, %u, %u, %u)\n", __func__, xmin, xmax, ymin, ymax);
scan_edge(ncrtc, crtcinfos, xmin, ymin, xmin, ymax, BarrierPositiveX);
scan_edge(ncrtc, crtcinfos, xmax, ymin, xmax, ymax, BarrierNegativeX);
scan_edge(ncrtc, crtcinfos, xmin, ymin, xmax, ymin, BarrierPositiveY);
scan_edge(ncrtc, crtcinfos, xmin, ymax, xmax, ymax, BarrierNegativeY);
}
static void setup_barriers(void)
{
int i;
XRRCrtcInfo** crtcinfos;
XRRScreenResources* resources = XRRGetScreenResources(dpy, rootwin);
crtcinfos = xmalloc(resources->ncrtc * sizeof(*crtcinfos));
for (i = 0; i < resources->ncrtc; i++)
crtcinfos[i] = XRRGetCrtcInfo(dpy, resources, resources->crtcs[i]);
for (i = 0; i < resources->ncrtc; i++) {
/*
* For some reason there seems to be some magical N+1th
* pseudo-CRTC with width == 0 and height == 0; let's not try
* to set up pointer barriers around that one.
*/
if (crtcinfos[i]->width > 0 && crtcinfos[i]->height > 0)
setup_crtc_barriers(crtcinfos[i], resources->ncrtc, crtcinfos);
else
dbg("skipping %dx%d crtc %d\n", crtcinfos[i]->width, crtcinfos[i]->height, i);
}
for (i = 0; i < resources->ncrtc; i++)
XRRFreeCrtcInfo(crtcinfos[i]);
free(crtcinfos);
XSync(dpy, False);
XRRFreeScreenResources(resources);
}
static void teardown_barriers(void)
{
struct pbinfo* pb;
while (pbmap) {
pb = *(struct pbinfo**)pbmap;
tdelete(pb, &pbmap, pbcmp);
XFixesDestroyPointerBarrier(dpy, pb->bar);
dbg("delbar(%lu)\n", pb->bar);
#ifdef DEBUG
XSync(dpy, False);
#endif
free(pb);
}
}
static void reset_barriers(void)
{
teardown_barriers();
setup_barriers();
}
static void usage(FILE* out, int full)
{
fprintf(out, "Usage: %s [ -h | -d DISTANCE | -s SPEED | -m SECONDS ]\n", progname);
if (!full)
return;
fprintf(out, "Flags:\n");
fprintf(out, "\t-h %-12s print this usage message\n", "");
fprintf(out, "\t-d %-12s release after DISTANCE pixels of (suppressed) pointer travel\n", "DISTANCE");
fprintf(out, "\t-s %-12s release when cursor speed (against barrier) exceeds SPEED\n", "SPEED");
fprintf(out, "\t-m %-12s release on two taps against barrier within SECONDS seconds\n", "SECONDS");
}
static void set_options(int argc, char** argv)
{
int opt;
char* end;
while ((opt = getopt(argc, argv, "d:s:m:h")) != -1) {
switch (opt) {
case 'd':
case 's':
case 'm':
if (releasemode != REL__UNSET_) {
fprintf(stderr, "Error: multiple release modes selected\n");
usage(stderr, 0);
exit(1);
}
releasemode = opt == 'd' ? REL_DISTANCE
: opt == 's' ? REL_SPEED
: REL_DOUBLETAP;
threshold = strtod(optarg, &end);
if (!*optarg || *end || threshold < 0.0) {
fprintf(stderr, "Invalid threshold '%s' (must be numeric and non-negative)\n",
optarg);
exit(1);
}
break;
case 'h':
usage(stdout, 1);
exit(0);
default:
usage(stderr, 0);
exit(1);
}
}
/* Apply defaults if nothing specified */
if (releasemode == REL__UNSET_) {
releasemode = REL_DISTANCE;
threshold = 50.0;
}
}
static void sighdlr(int signo)
{
if (write(sigpipe[1], &signo, sizeof(signo)) != sizeof(signo))
abort();
}
static void setup_sighdlr(void)
{
struct sigaction sa = {
.sa_handler = sighdlr,
.sa_flags = 0,
};
if (sigfillset(&sa.sa_mask))
abort();
if (pipe(sigpipe)) {
perror("pipe");
exit(1);
}
if (sigaction(SIGINT, &sa, NULL)) {
perror("sigaction(SIGINT)");
abort();
}
if (sigaction(SIGTERM, &sa, NULL)) {
perror("sigaction(SIGTERM)");
abort();
}
}
static void handle_xevent(void)
{
XEvent xev;
XGenericEventCookie* cookie;
XNextEvent(dpy, &xev);
if (xev.type == GenericEvent) {
cookie = &xev.xcookie;
if (!XGetEventData(dpy, cookie))
return;
if (cookie->extension == xi2_opcode) {
switch (cookie->evtype) {
case XI_BarrierHit:
handle_barrier_hit(cookie->data);
break;
case XI_BarrierLeave:
handle_barrier_leave(cookie->data);
break;
default:
break;
}
}
XFreeEventData(dpy, cookie);
} else if (xev.type == xrr_event_base + RRScreenChangeNotify)
reset_barriers();
else
dbg("[unexpected event; type=%d]\n", xev.type);
}
int main(int argc, char** argv)
{
int xfd, nfds;
fd_set rfds;
unsigned char mask_bits[XIMaskLen(XI_LASTEVENT)] = { 0, };
XIEventMask mask = {
.deviceid = XIAllMasterDevices,
.mask = mask_bits,
.mask_len = sizeof(mask_bits),
};
progname = strrchr(argv[0], '/');
progname = progname ? progname + 1 : argv[0];
set_options(argc, argv);
dpy = XOpenDisplay(NULL);
if (!dpy) {
fprintf(stderr, "Failed to connect to X server\n");
return 1;
}
check_extensions();
rootwin = XDefaultRootWindow(dpy);
setup_barriers();
XISetMask(mask_bits, XI_BarrierHit);
XISetMask(mask_bits, XI_BarrierLeave);
XISelectEvents(dpy, rootwin, &mask, 1);
XRRSelectInput(dpy, rootwin, RRScreenChangeNotifyMask);
setup_sighdlr();
xfd = XConnectionNumber(dpy);
nfds = (xfd > sigpipe[0]) ? xfd + 1 : sigpipe[0] + 1;
XSync(dpy, False);
for (;;) {
FD_ZERO(&rfds);
FD_SET(xfd, &rfds);
FD_SET(sigpipe[0], &rfds);
if (select(nfds, &rfds, NULL, NULL, NULL) < 0) {
if (errno == EINTR)
continue;
perror("select");
exit(1);
}
if (FD_ISSET(sigpipe[0], &rfds)) {
teardown_barriers();
XCloseDisplay(dpy);
exit(0);
}
if (FD_ISSET(xfd, &rfds))
handle_xevent();
}
}