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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
|
#define _POSIX_C_SOURCE 200809L
#include "common/backend.h"
#include "common/input.h"
#include "common/timing.h"
#include <X11/Xatom.h>
#include <X11/XKBlib.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/cursorfont.h>
#include <X11/keysym.h>
#include <X11/extensions/XInput2.h>
#include <xkbcommon/xkbcommon.h>
#include <assert.h>
#include <errno.h>
#include <limits.h>
#include <math.h>
#include <poll.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#define TEXT_LIMIT (16 * 1024 * 1024)
#ifndef likely
#define likely(x) __builtin_expect(!!(x), 1)
#endif
#ifndef unlikely
#define unlikely(x) __builtin_expect(!!(x), 0)
#endif
struct x11_surface {
struct yasl_surface base;
struct x11_surface *next;
struct x11_surface *dead_next;
Window window;
GC gc;
XIC ic;
XImage *image;
uint32_t *pixels;
struct yasl_vector2i size;
const struct yasl_surface_cbs *cbs;
void *ud;
struct input_queue input;
struct yasl_frame frame;
struct yasl_damage_list damage;
struct yasl_frame_clock clock;
uint32_t state;
bool want_draw, drawing, presented, destroyed;
};
struct paste_request {
struct paste_request *next;
struct x11_surface *target;
Window window;
};
struct tablet_axis {
int number;
double min, max, value;
};
struct x11_pointer {
struct x11_pointer *next;
int id;
enum yasl_pointer_device device;
struct tablet_axis pressure, tilt_x, tilt_y;
};
struct x11_display {
struct yasl_display base;
Display *native;
int screen;
struct yasl_loop *loop;
int watch;
struct x11_surface *surfaces, *dead;
int depth;
XIM im;
Window selection_window;
Atom protocols, delete_window, utf8, clipboard, targets, paste_property;
Atom net_name, net_state, fullscreen, maximized_h, maximized_v;
char *selection[2];
struct paste_request *pastes;
uint32_t mods;
char *app_id;
bool owns_loop;
int xi_opcode;
bool xi2;
Atom abs_pressure, abs_tilt_x, abs_tilt_y, tool_type, eraser;
struct x11_pointer *pointers;
};
static struct x11_display *display_of(const struct yasl_surface *s)
{
return (struct x11_display *)s->display;
}
static void leave(struct x11_display *d)
{
if (--d->depth) return;
while (d->dead) {
struct x11_surface *s = d->dead;
d->dead = s->dead_next;
free(s);
}
}
static void push(struct x11_surface *s, struct yasl_input_event event,
const char *text, size_t len)
{
if (s->destroyed) return;
if (text) {
if (event.kind == YASL_INPUT_TEXT) {
event.text.text = text;
event.text.len = len;
} else {
event.paste.text = text;
event.paste.len = len;
}
}
event.surface = &s->base;
input_queue_push(&s->input, &event);
}
static uint32_t modifiers(unsigned state)
{
return ((state & ShiftMask) ? YASL_MOD_SHIFT : 0) |
((state & ControlMask) ? YASL_MOD_CTRL : 0) |
((state & Mod1Mask) ? YASL_MOD_ALT : 0) |
((state & Mod4Mask) ? YASL_MOD_SUPER : 0) |
((state & LockMask) ? YASL_MOD_CAPS : 0);
}
static void pointer_info(struct x11_display *d, struct x11_pointer *p,
const XIDeviceInfo *info)
{
p->id = info->deviceid;
p->device = YASL_PTR_DEV_MOUSE;
p->pressure.number = p->tilt_x.number = p->tilt_y.number = -1;
bool touch = false;
for (int i = 0; i < info->num_classes; i++) {
XIAnyClassInfo *c = info->classes[i];
if (c->type == XITouchClass) touch = true;
if (c->type != XIValuatorClass) continue;
XIValuatorClassInfo *v = (XIValuatorClassInfo *)c;
if (v->mode != XIModeAbsolute) continue;
struct tablet_axis *axis = v->label == d->abs_pressure ? &p->pressure :
v->label == d->abs_tilt_x ? &p->tilt_x :
v->label == d->abs_tilt_y ? &p->tilt_y : NULL;
if (axis) *axis = (struct tablet_axis){v->number, v->min, v->max, v->value};
}
if (!touch && p->pressure.number >= 0) {
p->device = YASL_PTR_DEV_PEN;
/* Xorg's Wacom and libinput drivers expose separate eraser devices.
* Use the tool property when available, with the device name as a
* fallback for servers (including Xwayland) without that property. */
if (info->name) {
for (const char *s = info->name; *s; s++)
if (!strncasecmp(s, "eraser", 6)) { p->device = YASL_PTR_DEV_ERASER; break; }
}
}
}
static struct x11_pointer *pointer_for(struct x11_display *d, int id)
{
for (struct x11_pointer *p = d->pointers; p; p = p->next)
if (p->id == id) return p;
int count = 0;
XIDeviceInfo *info = XIQueryDevice(d->native, id, &count);
if (!info) return NULL;
struct x11_pointer *p = count ? calloc(1, sizeof(*p)) : NULL;
if (p) {
pointer_info(d, p, info);
if (p->device == YASL_PTR_DEV_PEN || p->device == YASL_PTR_DEV_ERASER) {
Atom type;
int format;
unsigned long n, after;
unsigned char *value = NULL;
if (XIGetProperty(d->native, id, d->tool_type, 0, 1, False,
XA_ATOM, &type, &format, &n, &after, &value) == Success &&
type == XA_ATOM && format == 32 && n == 1 && value)
/* XIGetProperty packs format-32 values as uint32_t, unlike
* XGetWindowProperty's array of native-sized longs. */
p->device = *(uint32_t *)value == d->eraser ? YASL_PTR_DEV_ERASER : p->device;
if (value) XFree(value);
}
p->next = d->pointers;
d->pointers = p;
}
XIFreeDeviceInfo(info);
return p;
}
static void clear_pointers(struct x11_display *d)
{
while (d->pointers) {
struct x11_pointer *p = d->pointers;
d->pointers = p->next;
free(p);
}
}
static void update_axes(struct x11_pointer *p, const XIValuatorState *state)
{
const double *value = state->values;
for (int i = 0; i < state->mask_len * 8; i++) {
if (!XIMaskIsSet(state->mask, i)) continue;
struct tablet_axis *axes[] = {&p->pressure, &p->tilt_x, &p->tilt_y};
for (unsigned a = 0; a < sizeof(axes) / sizeof(axes[0]); a++)
if (axes[a]->number == i && isfinite(*value)) axes[a]->value = *value;
value++;
}
}
static uint16_t pressure_value(const struct tablet_axis *a)
{
if (a->number < 0 || !(a->max > a->min) || !isfinite(a->value)) return 0;
double v = (a->value - a->min) / (a->max - a->min);
return (uint16_t)lround(fmax(0, fmin(1, v)) * 65535);
}
static int8_t tilt_value(const struct tablet_axis *a)
{
/* Xorg tablet tilt valuators are already in degrees. */
return a->number < 0 || !isfinite(a->value) ? 0 :
(int8_t)lround(fmax(-90, fmin(90, a->value)));
}
static int pointer_button(unsigned button)
{
return button == 1 ? 0 : button == 2 ? 1 : button == 3 ? 2 :
button >= 8 && button <= INT16_MAX ? (int)button - 5 : 3;
}
static void xi_pointer_event(struct x11_surface *s, const XIDeviceEvent *ev)
{
struct x11_display *d = display_of(&s->base);
struct x11_pointer *p = pointer_for(d, ev->sourceid);
struct yasl_mouse_event mouse = {
.pos = {yasl_scale_to_device(ev->event_x, YASL_SCALE_UNIT),
yasl_scale_to_device(ev->event_y, YASL_SCALE_UNIT)},
.device = p ? p->device : YASL_PTR_DEV_MOUSE,
.mods = modifiers(ev->mods.effective),
.button = 3,
};
if (p && (p->device == YASL_PTR_DEV_PEN || p->device == YASL_PTR_DEV_ERASER)) {
update_axes(p, &ev->valuators);
if (ev->evtype == XI_ButtonRelease && ev->detail == 1)
p->pressure.value = p->pressure.min;
mouse.pen = (struct yasl_pointer_pen){
pressure_value(&p->pressure), tilt_value(&p->tilt_x), tilt_value(&p->tilt_y)};
}
if (ev->evtype == XI_Motion) mouse.kind = YASL_PTR_MOTION;
else if (ev->detail >= 4 && ev->detail <= 7) {
if (ev->evtype == XI_ButtonRelease) return;
mouse.kind = YASL_PTR_SCROLL;
mouse.scroll_lines = (ev->detail == 4 || ev->detail == 6) ? -1 : 1;
} else {
mouse.kind = ev->evtype == XI_ButtonPress ? YASL_PTR_PRESS : YASL_PTR_RELEASE;
mouse.button = pointer_button(ev->detail);
}
d->mods = mouse.mods;
push(s, (struct yasl_input_event){.kind = YASL_INPUT_MOUSE, .mouse = mouse}, NULL, 0);
}
static void xi_event(struct x11_display *d, XGenericEventCookie *cookie)
{
if (cookie->evtype == XI_HierarchyChanged || cookie->evtype == XI_DeviceChanged) {
if (cookie->evtype == XI_DeviceChanged &&
((XIDeviceChangedEvent *)cookie->data)->reason == XISlaveSwitch) return;
clear_pointers(d);
if (cookie->evtype == XI_HierarchyChanged &&
(((XIHierarchyEvent *)cookie->data)->flags &
(XISlaveRemoved | XIDeviceDisabled | XISlaveDetached | XIMasterRemoved))) {
/* Removal/disable may interrupt a drag before a release arrives. */
for (struct x11_surface *s = d->surfaces; s; s = s->next)
push(s, (struct yasl_input_event){.kind = YASL_INPUT_RESET}, NULL, 0);
}
return;
}
bool crossing = cookie->evtype == XI_Enter || cookie->evtype == XI_Leave;
if (!crossing && cookie->evtype != XI_Motion && cookie->evtype != XI_ButtonPress &&
cookie->evtype != XI_ButtonRelease) return;
Window window = crossing ? ((XIEnterEvent *)cookie->data)->event :
((XIDeviceEvent *)cookie->data)->event;
struct x11_surface *s = d->surfaces;
while (s && s->window != window) s = s->next;
if (!s) return;
if (!crossing) xi_pointer_event(s, cookie->data);
else {
const XIEnterEvent *ev = cookie->data;
struct x11_pointer *p = pointer_for(d, ev->sourceid);
if (p) p->pressure.value = p->pressure.min;
push(s, (struct yasl_input_event){.kind = YASL_INPUT_MOUSE, .mouse = {
.pos = {yasl_scale_to_device(ev->event_x, YASL_SCALE_UNIT),
yasl_scale_to_device(ev->event_y, YASL_SCALE_UNIT)},
.device = p ? p->device : YASL_PTR_DEV_MOUSE,
.button = 3, .mods = modifiers(ev->mods.effective),
.kind = cookie->evtype == XI_Leave ? YASL_PTR_LEAVE : YASL_PTR_MOTION,
}}, NULL, 0);
}
}
static bool resize(struct x11_surface *s, struct yasl_vector2i size)
{
if (size.x <= 0 || size.y <= 0 || size.x > 32767 || size.y > 32767 ||
(size_t)size.x > SIZE_MAX / sizeof(uint32_t) / (size_t)size.y)
return false;
if (s->image && size.x == s->size.x && size.y == s->size.y) return true;
struct x11_display *d = display_of(&s->base);
uint64_t start = yasl_loop_now_ns();
XImage *image = XCreateImage(d->native, DefaultVisual(d->native, d->screen),
(unsigned)DefaultDepth(d->native, d->screen), ZPixmap, 0, NULL,
(unsigned)size.x, (unsigned)size.y, 32, 0);
uint32_t *pixels = calloc((size_t)size.x * (size_t)size.y, sizeof(*pixels));
if (!image || !pixels) {
if (image) XDestroyImage(image);
free(pixels);
return false;
}
image->data = calloc((size_t)image->bytes_per_line, (size_t)size.y);
if (!image->data) {
XDestroyImage(image);
free(pixels);
return false;
}
if (s->image) XDestroyImage(s->image);
free(s->pixels);
s->image = image;
s->pixels = pixels;
s->size = size;
s->want_draw = true;
yasl_clock_note_resize(&s->clock, yasl_loop_now_ns() - start);
return true;
}
static void cancel_pastes(struct x11_display *d, struct x11_surface *target)
{
for (struct paste_request **p = &d->pastes; *p;) {
struct paste_request *r = *p;
if (!target) {
*p = r->next;
XDestroyWindow(d->native, r->window);
free(r);
} else {
/* Keep the requestor alive until SelectionNotify: the owner may
* still be writing to its property. Never retain a dead target. */
if (r->target == target) r->target = NULL;
p = &r->next;
}
}
}
static void surface_destroy(struct yasl_surface *base)
{
struct x11_surface *s = (struct x11_surface *)base;
if (s->destroyed) return;
struct x11_display *d = display_of(base);
s->destroyed = true;
for (struct x11_surface **p = &d->surfaces; *p; p = &(*p)->next) {
if (*p == s) { *p = s->next; break; }
}
cancel_pastes(d, s);
if (s->ic) XDestroyIC(s->ic);
if (s->image) XDestroyImage(s->image);
free(s->pixels);
if (s->gc) XFreeGC(d->native, s->gc);
if (s->window) XDestroyWindow(d->native, s->window);
input_queue_clear(&s->input);
if (d->depth) {
s->dead_next = d->dead;
d->dead = s;
} else free(s);
}
static void set_callbacks(struct yasl_surface *base,
const struct yasl_surface_cbs *cbs, void *ud)
{
struct x11_surface *s = (struct x11_surface *)base;
if (s->destroyed) return;
s->base.callbacks = cbs ? *cbs : (struct yasl_surface_cbs){0};
s->cbs = &s->base.callbacks;
s->ud = ud;
}
static void set_title(struct yasl_surface *base, const char *title)
{
struct x11_surface *s = (struct x11_surface *)base;
if (s->destroyed || !title) return;
struct x11_display *d = display_of(base);
XStoreName(d->native, s->window, title);
XChangeProperty(d->native, s->window, d->net_name, d->utf8, 8,
PropModeReplace, (const unsigned char *)title, (int)strlen(title));
}
static void net_message(struct x11_surface *s, Atom type,
long a, long b, long c, long e, long f)
{
struct x11_display *d = display_of(&s->base);
XEvent event = {0};
event.xclient = (XClientMessageEvent){
.type = ClientMessage, .display = d->native, .window = s->window,
.message_type = type, .format = 32, .data.l = {a, b, c, e, f},
};
XSendEvent(d->native, RootWindow(d->native, d->screen), False,
SubstructureRedirectMask | SubstructureNotifyMask, &event);
}
static struct yasl_surface *create_toplevel(struct yasl_display *base,
const struct yasl_surface_spec *spec, void *graphics_device)
{
(void)graphics_device;
if (!spec) return NULL;
struct x11_display *d = (struct x11_display *)base;
struct x11_surface *s = calloc(1, sizeof(*s));
if (!s) return NULL;
s->base.display = base;
s->clock.refresh_ns = YASL_REFRESH_DEFAULT_NS;
if (!resize(s, spec->size)) { free(s); return NULL; }
s->window = XCreateSimpleWindow(d->native, RootWindow(d->native, d->screen),
0, 0, (unsigned)spec->size.x, (unsigned)spec->size.y, 0, 0, 0);
s->gc = XCreateGC(d->native, s->window, 0, NULL);
XSelectInput(d->native, s->window, ExposureMask | StructureNotifyMask |
FocusChangeMask | KeyPressMask | KeyReleaseMask | PropertyChangeMask |
(d->xi2 ? 0 : ButtonPressMask | ButtonReleaseMask |
PointerMotionMask | LeaveWindowMask));
if (d->xi2) {
unsigned char bits[XIMaskLen(XI_LASTEVENT)] = {0};
XISetMask(bits, XI_Motion);
XISetMask(bits, XI_ButtonPress);
XISetMask(bits, XI_ButtonRelease);
XISetMask(bits, XI_Enter);
XISetMask(bits, XI_Leave);
XIEventMask mask = {XIAllMasterDevices, sizeof(bits), bits};
XISelectEvents(d->native, s->window, &mask, 1);
}
XSetWMProtocols(d->native, s->window, &d->delete_window, 1);
XClassHint hint = { .res_name = d->app_id, .res_class = d->app_id };
XSetClassHint(d->native, s->window, &hint);
if (d->im) {
s->ic = XCreateIC(d->im, XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
XNClientWindow, s->window, XNFocusWindow, s->window, NULL);
}
s->next = d->surfaces;
d->surfaces = s;
set_title(&s->base, spec->title ? spec->title : "YASL");
if (spec->fullscreen) {
XChangeProperty(d->native, s->window, d->net_state, XA_ATOM, 32,
PropModeReplace, (unsigned char *)&d->fullscreen, 1);
s->state |= YASL_STATE_FULLSCREEN;
}
XMapWindow(d->native, s->window);
XFlush(d->native);
return &s->base;
}
static void update_state(struct x11_surface *s)
{
struct x11_display *d = display_of(&s->base);
Atom actual;
int format;
unsigned long count, left;
unsigned char *data = NULL;
uint32_t state = s->state & YASL_STATE_ACTIVATED;
if (XGetWindowProperty(d->native, s->window, d->net_state, 0, 64, False,
XA_ATOM, &actual, &format, &count, &left, &data) == Success && format == 32) {
Atom *atoms = (Atom *)data;
bool h = false, v = false;
for (unsigned long i = 0; i < count; i++) {
if (atoms[i] == d->fullscreen) state |= YASL_STATE_FULLSCREEN;
if (atoms[i] == d->maximized_h) h = true;
if (atoms[i] == d->maximized_v) v = true;
}
if (h && v) state |= YASL_STATE_MAXIMIZED;
}
if (data) XFree(data);
if (state == s->state) return;
s->state = state;
if (s->cbs && s->cbs->state) s->cbs->state(&s->base, state, s->ud);
}
static void selection_request(struct x11_display *d, XSelectionRequestEvent *request)
{
XEvent reply = {0};
reply.xselection = (XSelectionEvent){
.type = SelectionNotify, .display = d->native,
.requestor = request->requestor, .selection = request->selection,
.target = request->target, .time = request->time,
};
Atom property = request->property ? request->property : request->target;
int slot = request->selection == XA_PRIMARY ? YASL_PRIMARY : YASL_CLIPBOARD;
const char *text = d->selection[slot];
if (text && request->target == d->targets) {
Atom targets[] = {d->targets, d->utf8, XA_STRING};
XChangeProperty(d->native, request->requestor, property, XA_ATOM, 32,
PropModeReplace, (unsigned char *)targets, 3);
reply.xselection.property = property;
} else if (text && (request->target == d->utf8 || request->target == XA_STRING)) {
size_t len = strlen(text);
long max = XMaxRequestSize(d->native) * 4 - 128;
if (len <= (size_t)max) {
XChangeProperty(d->native, request->requestor, property, request->target,
8, PropModeReplace, (const unsigned char *)text, (int)len);
reply.xselection.property = property;
}
}
XSendEvent(d->native, request->requestor, False, 0, &reply);
}
static void selection_notify(struct x11_display *d, XSelectionEvent *event)
{
struct paste_request **p = &d->pastes;
while (*p && (*p)->window != event->requestor) p = &(*p)->next;
if (!*p) return;
struct paste_request *r = *p;
*p = r->next;
struct x11_surface *s = r->target;
if (!s || event->property == None) {
XDestroyWindow(d->native, r->window);
free(r);
return;
}
Atom actual;
int format;
unsigned long count, left;
unsigned char *data = NULL;
if (XGetWindowProperty(d->native, r->window, event->property,
0, TEXT_LIMIT / 4, True, AnyPropertyType,
&actual, &format, &count, &left, &data) == Success &&
(actual == d->utf8 || actual == XA_STRING) && format == 8 && !left) {
push(s, (struct yasl_input_event){.kind = YASL_INPUT_PASTE},
(const char *)data, count);
}
if (data) XFree(data);
XDestroyWindow(d->native, r->window);
free(r);
}
static void key_event(struct x11_surface *s, XKeyEvent *key, bool repeat)
{
struct x11_display *d = display_of(&s->base);
d->mods = modifiers(key->state);
KeySym sym = XLookupKeysym(key, (key->state & ShiftMask) ? 1 : 0);
KeySym base = XLookupKeysym(key, 0), shifted = XLookupKeysym(key, 1);
char local[128];
char *text = local;
int len = 0;
if (key->type == KeyPress) {
if (s->ic) {
Status status;
len = Xutf8LookupString(s->ic, key, local, sizeof(local), &sym, &status);
if (status == XBufferOverflow && len > 0 && len < TEXT_LIMIT) {
text = malloc((size_t)len + 1);
if (text) len = Xutf8LookupString(s->ic, key, text, len + 1, &sym, &status);
else len = 0;
}
if (status != XLookupChars && status != XLookupBoth) len = 0;
} else len = XLookupString(key, local, sizeof(local), &sym, NULL);
}
uint32_t cp = xkb_keysym_to_utf32((xkb_keysym_t)base);
if (!cp) cp = xkb_keysym_to_utf32((xkb_keysym_t)sym);
push(s, (struct yasl_input_event){
.kind = YASL_INPUT_KEY,
.key = {.key = (uint32_t)sym, .codepoint = cp,
.base = key->keycode >= 8 ? key->keycode - 8 : 0,
.keypad = sym >= XK_KP_Space && sym <= XK_KP_Equal,
.shifted = xkb_keysym_to_utf32((xkb_keysym_t)shifted),
.text = xkb_keysym_to_utf32((xkb_keysym_t)sym), .mods = d->mods,
.action = key->type == KeyRelease ? YASL_KEY_RELEASE :
repeat ? YASL_KEY_REPEAT : YASL_KEY_PRESS},
}, NULL, 0);
if (len > 0 && text)
push(s, (struct yasl_input_event){.kind = YASL_INPUT_TEXT}, text, (size_t)len);
if (text != local) free(text);
}
static void dispatch(struct yasl_display *base)
{
struct x11_display *d = (struct x11_display *)base;
d->depth++;
while (XPending(d->native)) {
XEvent event;
XNextEvent(d->native, &event);
if (event.type == GenericEvent && d->xi2 &&
event.xcookie.extension == d->xi_opcode && XGetEventData(d->native, &event.xcookie)) {
xi_event(d, &event.xcookie);
XFreeEventData(d->native, &event.xcookie);
continue;
}
if (XFilterEvent(&event, None)) continue;
if (event.type == SelectionRequest) {
selection_request(d, &event.xselectionrequest);
continue;
}
if (event.type == SelectionNotify) {
selection_notify(d, &event.xselection);
continue;
}
struct x11_surface *s = d->surfaces;
while (s && s->window != event.xany.window) s = s->next;
if (!s) continue;
switch (event.type) {
case Expose: s->want_draw = true; break;
case ConfigureNotify: {
struct yasl_vector2i size = {event.xconfigure.width, event.xconfigure.height};
if (size.x == s->size.x && size.y == s->size.y) break;
if (resize(s, size) && s->cbs && s->cbs->configure)
s->cbs->configure(&s->base, (struct yasl_geometry){size, YASL_SCALE_UNIT}, s->ud);
break;
}
case ClientMessage:
if (event.xclient.message_type == d->protocols &&
(Atom)event.xclient.data.l[0] == d->delete_window && s->cbs && s->cbs->close)
s->cbs->close(&s->base, s->ud);
break;
case FocusIn: case FocusOut: {
bool focused = event.type == FocusIn;
if (s->ic) { if (focused) XSetICFocus(s->ic); else XUnsetICFocus(s->ic); }
if (focused) s->state |= YASL_STATE_ACTIVATED;
else s->state &= ~YASL_STATE_ACTIVATED;
push(s, (struct yasl_input_event){
.kind = YASL_INPUT_FOCUS, .focus.focused = focused}, NULL, 0);
if (s->cbs && s->cbs->state) s->cbs->state(&s->base, s->state, s->ud);
break;
}
case PropertyNotify:
if (event.xproperty.atom == d->net_state) update_state(s);
break;
case KeyPress: case KeyRelease: {
bool repeat = false;
if (event.type == KeyRelease && XPending(d->native)) {
XEvent next;
XPeekEvent(d->native, &next);
if (next.type == KeyPress && next.xkey.window == event.xkey.window &&
next.xkey.keycode == event.xkey.keycode && next.xkey.time == event.xkey.time) {
XNextEvent(d->native, &event);
repeat = true;
}
}
key_event(s, &event.xkey, repeat);
break;
}
case MotionNotify: case LeaveNotify: case ButtonPress: case ButtonRelease: {
struct yasl_mouse_event mouse = {.device = YASL_PTR_DEV_MOUSE};
unsigned state;
if (event.type == MotionNotify) {
mouse.pos = (struct yasl_vector2i){event.xmotion.x, event.xmotion.y};
mouse.kind = YASL_PTR_MOTION;
state = event.xmotion.state;
} else if (event.type == LeaveNotify) {
mouse.pos = (struct yasl_vector2i){event.xcrossing.x, event.xcrossing.y};
mouse.kind = YASL_PTR_LEAVE;
state = event.xcrossing.state;
} else {
mouse.pos = (struct yasl_vector2i){event.xbutton.x, event.xbutton.y};
state = event.xbutton.state;
unsigned button = event.xbutton.button;
if (button >= 4 && button <= 7) {
if (event.type == ButtonRelease) break;
mouse.kind = YASL_PTR_SCROLL;
mouse.scroll_lines = (button == 4 || button == 6) ? -1 : 1;
} else {
mouse.kind = event.type == ButtonPress ? YASL_PTR_PRESS : YASL_PTR_RELEASE;
mouse.button = pointer_button(button);
}
}
d->mods = mouse.mods = modifiers(state);
push(s, (struct yasl_input_event){.kind = YASL_INPUT_MOUSE, .mouse = mouse}, NULL, 0);
break;
}
}
}
leave(d);
}
static unsigned long component(uint32_t color, unsigned long mask)
{
if (unlikely(!mask)) return 0;
unsigned shift = (unsigned)__builtin_ctzl(mask);
unsigned long m = mask >> shift;
return (((unsigned long)color * m + 127) / 255) << shift;
}
static bool present(struct yasl_surface *base, const struct yasl_framebuffer *fb,
const struct yasl_damage_list *damage)
{
struct x11_surface *s = (struct x11_surface *)base;
if (s->destroyed || !s->drawing || s->presented || !fb || !damage ||
fb->pixels != s->pixels || fb->size.x != s->size.x || fb->size.y != s->size.y ||
damage->n < -1 || damage->n > YASL_DAMAGE_MAX) return false;
struct x11_display *d = display_of(base);
XImage *im = s->image;
bool direct = im->bits_per_pixel == 32 && im->red_mask == 0xff0000 &&
im->green_mask == 0xff00 && im->blue_mask == 0xff;
for (int y = 0; y < s->size.y; y++) {
const uint32_t *row = s->pixels + (size_t)y * s->size.x;
if (direct) memcpy(im->data + (size_t)y * im->bytes_per_line, row, (size_t)s->size.x * 4);
else for (int x = 0; x < s->size.x; x++) {
uint32_t p = row[x];
XPutPixel(im, x, y, component((p >> 16) & 255, im->red_mask) |
component((p >> 8) & 255, im->green_mask) | component(p & 255, im->blue_mask));
}
}
if (damage->n == -1)
XPutImage(d->native, s->window, s->gc, im, 0, 0, 0, 0,
(unsigned)s->size.x, (unsigned)s->size.y);
else for (int i = 0; i < damage->n; i++) {
struct yasl_rect2i r = damage->rects[i];
int64_t right = (int64_t)r.x + r.width, bottom = (int64_t)r.y + r.height;
int x = r.x > 0 ? r.x : 0, y = r.y > 0 ? r.y : 0;
int w = (int)(right < s->size.x ? right : s->size.x) - x;
int h = (int)(bottom < s->size.y ? bottom : s->size.y) - y;
if (w > 0 && h > 0)
XPutImage(d->native, s->window, s->gc, im, x, y, x, y, (unsigned)w, (unsigned)h);
}
s->presented = true;
yasl_clock_presented(&s->clock, yasl_loop_now_ns(), false);
return true;
}
static void flush(struct yasl_display *base)
{
struct x11_display *d = (struct x11_display *)base;
d->depth++;
for (struct x11_surface *s = d->surfaces, *next; s; s = next) {
next = s->next;
if (s->destroyed || !s->want_draw || !s->cbs || !s->cbs->draw || s->drawing) continue;
s->want_draw = false;
s->drawing = true;
s->presented = false;
s->damage = (struct yasl_damage_list){0};
s->frame = (struct yasl_frame){
.surface = &s->base,
.target = {.generation = yasl_frame_begin(&s->base),
.pixels = s->pixels, .size = s->size},
};
s->cbs->draw(&s->base, &s->frame, s->ud);
s->drawing = false;
}
XFlush(d->native);
leave(d);
}
static int ready(int fd, short events, void *ud)
{
(void)fd;
struct yasl_display *base = ud;
if (events & POLLIN) { dispatch(base); flush(base); }
return 0;
}
static int dispatch_timeout(struct yasl_display *base, int timeout_ms)
{
struct x11_display *d = (struct x11_display *)base;
if (unlikely(!d || !d->native)) return -1;
dispatch(base);
for (struct x11_surface *s = d->surfaces; s; s = s->next) {
if (s->want_draw || s->input.count || s->input.reset_pending) {
timeout_ms = 0;
break;
}
}
if (d->loop) {
if (!XPending(d->native) && timeout_ms != 0) {
yasl_loop_step(d->loop, timeout_ms);
dispatch(base);
} else {
yasl_loop_step(d->loop, 0);
}
}
return 0;
}
static struct yasl_display *display_open(struct yasl_loop *loop,
const struct yasl_display_spec *spec)
{
struct x11_display *d = calloc(1, sizeof(*d));
if (!d) return NULL;
d->base.ops = &yasl_x11_backend;
d->base.callbacks = spec && spec->cbs ? *spec->cbs : (struct yasl_display_cbs){0};
d->native = XOpenDisplay(NULL);
if (!d->native) { free(d); errno = ENODEV; return NULL; }
d->screen = DefaultScreen(d->native);
int xi_event_base, xi_error_base;
int major = 2, minor = 0;
d->xi2 = XQueryExtension(d->native, "XInputExtension", &d->xi_opcode,
&xi_event_base, &xi_error_base) &&
XIQueryVersion(d->native, &major, &minor) == Success && major >= 2;
if (d->xi2) {
d->abs_pressure = XInternAtom(d->native, "Abs Pressure", False);
d->abs_tilt_x = XInternAtom(d->native, "Abs Tilt X", False);
d->abs_tilt_y = XInternAtom(d->native, "Abs Tilt Y", False);
d->tool_type = XInternAtom(d->native, "Wacom Tool Type", False);
d->eraser = XInternAtom(d->native, "ERASER", False);
unsigned char bits[XIMaskLen(XI_LASTEVENT)] = {0};
XISetMask(bits, XI_HierarchyChanged);
XISetMask(bits, XI_DeviceChanged);
XIEventMask mask = {XIAllDevices, sizeof(bits), bits};
XISelectEvents(d->native, RootWindow(d->native, d->screen), &mask, 1);
}
if (!loop) {
d->loop = yasl_loop_create();
d->owns_loop = true;
} else {
d->loop = loop;
}
d->base.loop = d->loop;
d->app_id = strdup(spec && spec->app_id ? spec->app_id : "YASL");
if (!d->loop || !d->app_id) {
if (d->owns_loop) yasl_loop_destroy(d->loop);
free(d->app_id);
XCloseDisplay(d->native);
free(d);
return NULL;
}
d->im = XOpenIM(d->native, NULL, NULL, NULL);
d->selection_window = XCreateSimpleWindow(d->native,
RootWindow(d->native, d->screen), 0, 0, 1, 1, 0, 0, 0);
#define ATOM(field, name) d->field = XInternAtom(d->native, name, False)
ATOM(protocols, "WM_PROTOCOLS");
ATOM(delete_window, "WM_DELETE_WINDOW");
ATOM(utf8, "UTF8_STRING");
ATOM(clipboard, "CLIPBOARD");
ATOM(targets, "TARGETS");
ATOM(paste_property, "YASL_SELECTION");
ATOM(net_name, "_NET_WM_NAME");
ATOM(net_state, "_NET_WM_STATE");
ATOM(fullscreen, "_NET_WM_STATE_FULLSCREEN");
ATOM(maximized_h, "_NET_WM_STATE_MAXIMIZED_HORZ");
ATOM(maximized_v, "_NET_WM_STATE_MAXIMIZED_VERT");
#undef ATOM
if (d->loop) {
d->watch = yasl_loop_add_fd(d->loop, ConnectionNumber(d->native), POLLIN, ready, &d->base);
if (d->watch < 0) {
if (d->im) XCloseIM(d->im);
XDestroyWindow(d->native, d->selection_window);
XCloseDisplay(d->native);
free(d->app_id);
if (d->owns_loop) yasl_loop_destroy(d->loop);
free(d);
return NULL;
}
}
return &d->base;
}
static void display_close(struct yasl_display *base)
{
struct x11_display *d = (struct x11_display *)base;
assert(!d->surfaces && "destroy every surface before its display");
cancel_pastes(d, NULL);
if (d->loop && d->watch > 0) yasl_loop_del_fd(d->loop, d->watch);
if (d->owns_loop && d->loop) {
yasl_loop_destroy(d->loop);
d->loop = NULL;
d->base.loop = NULL;
}
if (d->im) XCloseIM(d->im);
clear_pointers(d);
XDestroyWindow(d->native, d->selection_window);
XCloseDisplay(d->native);
free(d->selection[0]);
free(d->selection[1]);
free(d->app_id);
free(d);
}
static uint32_t caps(const struct yasl_display *d)
{
return YASL_CAP_PLACE_WINDOW | YASL_CAP_PRIMARY_SELECTION |
(((const struct x11_display *)d)->xi2 ? YASL_CAP_TABLET : 0);
}
static void copy(struct yasl_display *base, enum yasl_selection sel, const char *text)
{
if (!text || (sel != YASL_CLIPBOARD && sel != YASL_PRIMARY)) return;
struct x11_display *d = (struct x11_display *)base;
char *value = strdup(text);
if (!value) return;
free(d->selection[sel]);
d->selection[sel] = value;
XSetSelectionOwner(d->native, sel == YASL_PRIMARY ? XA_PRIMARY : d->clipboard,
d->selection_window, CurrentTime);
XFlush(d->native);
}
static void paste(struct yasl_display *base, enum yasl_selection sel, struct yasl_surface *target)
{
if (sel != YASL_CLIPBOARD && sel != YASL_PRIMARY) return;
struct x11_display *d = (struct x11_display *)base;
struct x11_surface *s = (struct x11_surface *)target;
Atom selection = sel == YASL_PRIMARY ? XA_PRIMARY : d->clipboard;
if (XGetSelectionOwner(d->native, selection) == d->selection_window) {
const char *text = d->selection[sel];
if (text) push(s, (struct yasl_input_event){.kind = YASL_INPUT_PASTE}, text, strlen(text));
} else {
struct paste_request *r = calloc(1, sizeof(*r));
if (!r) return;
r->window = XCreateSimpleWindow(d->native, RootWindow(d->native, d->screen),
0, 0, 1, 1, 0, 0, 0);
r->target = s;
r->next = d->pastes;
d->pastes = r;
XConvertSelection(d->native, selection, d->utf8, d->paste_property,
r->window, CurrentTime);
XFlush(d->native);
}
}
static bool input_poll(struct yasl_surface *base, struct yasl_input_event *event)
{
struct x11_surface *s = (struct x11_surface *)base;
return !s->destroyed && input_queue_pop(&s->input, event);
}
static void schedule_redraw(struct yasl_surface *base)
{
struct x11_surface *s = (struct x11_surface *)base;
if (!s->destroyed) {
s->want_draw = true;
struct x11_display *d = display_of(base);
if (d && d->loop)
yasl_loop_kick(d->loop);
}
}
static struct yasl_display *surface_display(const struct yasl_surface *s) { return s->display; }
static struct yasl_geometry geometry(const struct yasl_surface *s)
{
return (struct yasl_geometry){((const struct x11_surface *)s)->size, YASL_SCALE_UNIT};
}
static uint32_t state(const struct yasl_surface *s) { return ((const struct x11_surface *)s)->state; }
static int mods(const struct yasl_display *d) { return (int)((const struct x11_display *)d)->mods; }
static void *native_display(struct yasl_display *d) { return ((struct x11_display *)d)->native; }
static void *native_surface(struct yasl_surface *s) { return (void *)(uintptr_t)((struct x11_surface *)s)->window; }
static struct yasl_timing timing(const struct yasl_surface *base)
{
const struct x11_surface *s = (const struct x11_surface *)base;
struct yasl_timing t = {.refresh_ns = s->clock.refresh_ns,
.last_present_ns = s->clock.last_present_ns,
.next_present_ns = yasl_clock_next_present_ns(&s->clock),
.source = s->clock.source};
yasl_clock_resize_stats(&s->clock, &t.resize);
return t;
}
static uint64_t frame_time(struct yasl_surface *s, uint64_t now)
{
return yasl_clock_frame_timestamp_ns(&((struct x11_surface *)s)->clock, now);
}
static void cursor(struct yasl_surface *base, enum yasl_cursor cursor)
{
static const unsigned shapes[] = {XC_left_ptr, XC_xterm, XC_hand2, XC_crosshair,
XC_fleur, XC_bottom_right_corner, XC_bottom_left_corner,
XC_sb_h_double_arrow, XC_sb_v_double_arrow};
struct x11_surface *s = (struct x11_surface *)base;
if (s->destroyed || (unsigned)cursor > YASL_CURSOR_HIDDEN) return;
struct x11_display *d = display_of(base);
Cursor native;
if (cursor == YASL_CURSOR_HIDDEN) {
char bits[] = {0};
Pixmap pixmap = XCreateBitmapFromData(d->native, s->window, bits, 1, 1);
XColor color = {0};
native = XCreatePixmapCursor(d->native, pixmap, pixmap, &color, &color, 0, 0);
XFreePixmap(d->native, pixmap);
} else native = XCreateFontCursor(d->native, shapes[cursor]);
XDefineCursor(d->native, s->window, native);
XFreeCursor(d->native, native);
}
static bool place(struct yasl_surface *base, struct yasl_vector2i at)
{
struct x11_surface *s = (struct x11_surface *)base;
struct x11_display *d = display_of(base);
Window root, child;
int root_x, root_y, x, y;
unsigned mask;
if (s->destroyed || !XQueryPointer(d->native, s->window,
&root, &child, &root_x, &root_y, &x, &y, &mask)) return false;
XMoveWindow(d->native, s->window, root_x - at.x, root_y - at.y);
return true;
}
static bool interactive_move(struct yasl_surface *base)
{
struct x11_surface *s = (struct x11_surface *)base;
struct x11_display *d = display_of(base);
Window root, child;
int rx, ry, x, y;
unsigned mask;
if (s->destroyed || !XQueryPointer(d->native, s->window,
&root, &child, &rx, &ry, &x, &y, &mask)) return false;
XUngrabPointer(d->native, CurrentTime);
net_message(s, XInternAtom(d->native, "_NET_WM_MOVERESIZE", False), rx, ry, 8, 1, 1);
return true;
}
const struct yasl_backend_ops yasl_x11_backend = {
.type = YASL_BACKEND_X11,
.display_open = display_open,
.display_close = display_close,
.display_caps = caps,
.display_dispatch_timeout = dispatch_timeout,
.display_flush = flush,
.display_modifiers = mods,
.display_copy = copy,
.display_paste = paste,
.surface_create_toplevel = create_toplevel,
.surface_destroy = surface_destroy,
.surface_display = surface_display,
.surface_set_callbacks = set_callbacks,
.surface_set_title = set_title,
.surface_schedule_redraw = schedule_redraw,
.surface_present = present,
.surface_input_poll = input_poll,
.surface_geometry = geometry,
.surface_state = state,
.surface_timing = timing,
.surface_frame_time_ns = frame_time,
.surface_set_cursor = cursor,
.surface_place_under_pointer = place,
.surface_start_interactive_move = interactive_move,
.display_get_native_handle = native_display,
.surface_get_native_handle = native_surface,
};
|