aboutsummaryrefslogtreecommitdiff
path: root/xwayland/xwm.c
blob: 2743cc53db8de2a4b5cfefec935e0c209d8805a6 (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
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
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
#ifndef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 200809L
#endif
#include <stdlib.h>
#include <unistd.h>
#include <wlr/config.h>
#include <wlr/types/wlr_surface.h>
#include <wlr/util/edges.h>
#include <wlr/util/log.h>
#include <wlr/xcursor.h>
#include <wlr/xwayland.h>
#include <xcb/composite.h>
#include <xcb/render.h>
#include <xcb/xcb_image.h>
#include <xcb/xfixes.h>
#include "util/signal.h"
#include "xwayland/xwm.h"

const char *atom_map[ATOM_LAST] = {
	"WL_SURFACE_ID",
	"WM_DELETE_WINDOW",
	"WM_PROTOCOLS",
	"WM_HINTS",
	"WM_NORMAL_HINTS",
	"WM_SIZE_HINTS",
	"_MOTIF_WM_HINTS",
	"UTF8_STRING",
	"WM_S0",
	"_NET_SUPPORTED",
	"_NET_WM_S0",
	"_NET_WM_PID",
	"_NET_WM_NAME",
	"_NET_WM_STATE",
	"_NET_WM_WINDOW_TYPE",
	"WM_TAKE_FOCUS",
	"WINDOW",
	"_NET_ACTIVE_WINDOW",
	"_NET_WM_MOVERESIZE",
	"_NET_WM_NAME",
	"_NET_SUPPORTING_WM_CHECK",
	"_NET_WM_STATE_FULLSCREEN",
	"_NET_WM_STATE_MAXIMIZED_VERT",
	"_NET_WM_STATE_MAXIMIZED_HORZ",
	"WM_STATE",
	"CLIPBOARD",
	"PRIMARY",
	"_WL_SELECTION",
	"TARGETS",
	"CLIPBOARD_MANAGER",
	"INCR",
	"TEXT",
	"TIMESTAMP",
	"_NET_WM_WINDOW_TYPE_UTILITY",
	"_NET_WM_WINDOW_TYPE_TOOLTIP",
	"_NET_WM_WINDOW_TYPE_DND",
	"_NET_WM_WINDOW_TYPE_DROPDOWN_MENU",
	"_NET_WM_WINDOW_TYPE_POPUP_MENU",
	"_NET_WM_WINDOW_TYPE_COMBO",
};

/* General helpers */
// TODO: replace this with hash table?
static struct wlr_xwayland_surface *lookup_surface(struct wlr_xwm *xwm,
		xcb_window_t window_id) {
	struct wlr_xwayland_surface *surface;
	wl_list_for_each(surface, &xwm->surfaces, link) {
		if (surface->window_id == window_id) {
			return surface;
		}
	}
	return NULL;
}

static struct wlr_xwayland_surface *wlr_xwayland_surface_create(
		struct wlr_xwm *xwm, xcb_window_t window_id, int16_t x, int16_t y,
		uint16_t width, uint16_t height, bool override_redirect) {
	struct wlr_xwayland_surface *surface =
		calloc(1, sizeof(struct wlr_xwayland_surface));
	if (!surface) {
		wlr_log(L_ERROR, "Could not allocate wlr xwayland surface");
		return NULL;
	}

	xcb_get_geometry_cookie_t geometry_cookie =
		xcb_get_geometry(xwm->xcb_conn, window_id);

	uint32_t values[1];
	values[0] =
		XCB_EVENT_MASK_FOCUS_CHANGE |
		XCB_EVENT_MASK_PROPERTY_CHANGE;
	xcb_change_window_attributes(xwm->xcb_conn, window_id,
		XCB_CW_EVENT_MASK, values);

	surface->xwm = xwm;
	surface->window_id = window_id;
	surface->x = x;
	surface->y = y;
	surface->width = width;
	surface->height = height;
	surface->override_redirect = override_redirect;
	wl_list_insert(&xwm->surfaces, &surface->link);
	wl_list_init(&surface->children);
	wl_list_init(&surface->parent_link);
	wl_signal_init(&surface->events.destroy);
	wl_signal_init(&surface->events.request_configure);
	wl_signal_init(&surface->events.request_move);
	wl_signal_init(&surface->events.request_resize);
	wl_signal_init(&surface->events.request_maximize);
	wl_signal_init(&surface->events.request_fullscreen);
	wl_signal_init(&surface->events.map);
	wl_signal_init(&surface->events.unmap);
	wl_signal_init(&surface->events.set_class);
	wl_signal_init(&surface->events.set_title);
	wl_signal_init(&surface->events.set_parent);
	wl_signal_init(&surface->events.set_pid);
	wl_signal_init(&surface->events.set_window_type);

	xcb_get_geometry_reply_t *geometry_reply =
		xcb_get_geometry_reply(xwm->xcb_conn, geometry_cookie, NULL);

	if (geometry_reply != NULL) {
		surface->has_alpha = geometry_reply->depth == 32;
	}

	free(geometry_reply);

	return surface;
}

static void xwm_set_net_active_window(struct wlr_xwm *xwm,
		xcb_window_t window) {
	xcb_change_property(xwm->xcb_conn, XCB_PROP_MODE_REPLACE,
			xwm->screen->root, xwm->atoms[_NET_ACTIVE_WINDOW],
			xwm->atoms[WINDOW], 32, 1, &window);
}

static void xwm_send_focus_window(struct wlr_xwm *xwm,
		struct wlr_xwayland_surface *xsurface) {
	if (!xsurface) {
		xcb_set_input_focus_checked(xwm->xcb_conn,
			XCB_INPUT_FOCUS_POINTER_ROOT,
			XCB_NONE, XCB_CURRENT_TIME);
		return;
	} else if (xsurface->override_redirect) {
		return;
	}

	xcb_client_message_event_t client_message;
	client_message.response_type = XCB_CLIENT_MESSAGE;
	client_message.format = 32;
	client_message.window = xsurface->window_id;
	client_message.type = xwm->atoms[WM_PROTOCOLS];
	client_message.data.data32[0] = xwm->atoms[WM_TAKE_FOCUS];
	client_message.data.data32[1] = XCB_TIME_CURRENT_TIME;

	xcb_send_event(xwm->xcb_conn, 0, xsurface->window_id,
		XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT, (char*)&client_message);

	xcb_set_input_focus(xwm->xcb_conn, XCB_INPUT_FOCUS_POINTER_ROOT,
		xsurface->window_id, XCB_CURRENT_TIME);

	uint32_t values[1];
	values[0] = XCB_STACK_MODE_ABOVE;
	xcb_configure_window(xwm->xcb_conn, xsurface->window_id,
		XCB_CONFIG_WINDOW_STACK_MODE, values);
}


void xwm_surface_activate(struct wlr_xwm *xwm,
		struct wlr_xwayland_surface *xsurface) {
	if (xwm->focus_surface == xsurface ||
			(xsurface && xsurface->override_redirect)) {
		return;
	}

	if (xsurface) {
		xwm_set_net_active_window(xwm, xsurface->window_id);
	} else {
		xwm_set_net_active_window(xwm, XCB_WINDOW_NONE);
	}

	xwm_send_focus_window(xwm, xsurface);

	xwm->focus_surface = xsurface;

	xcb_flush(xwm->xcb_conn);
}

static void xsurface_set_net_wm_state(struct wlr_xwayland_surface *xsurface) {
	struct wlr_xwm *xwm = xsurface->xwm;
	uint32_t property[3];
	int i;

	i = 0;
	if (xsurface->fullscreen) {
		property[i++] = xwm->atoms[_NET_WM_STATE_FULLSCREEN];
	}
	if (xsurface->maximized_vert) {
		property[i++] = xwm->atoms[_NET_WM_STATE_MAXIMIZED_VERT];
	}
	if (xsurface->maximized_horz) {
		property[i++] = xwm->atoms[_NET_WM_STATE_MAXIMIZED_HORZ];
	}

	xcb_change_property(xwm->xcb_conn,
		XCB_PROP_MODE_REPLACE,
		xsurface->window_id,
		xwm->atoms[NET_WM_STATE],
		XCB_ATOM_ATOM,
		32, // format
		i, property);
}

static void wlr_xwayland_surface_destroy(
		struct wlr_xwayland_surface *xsurface) {
	wlr_signal_emit_safe(&xsurface->events.destroy, xsurface);

	if (xsurface == xsurface->xwm->focus_surface) {
		xwm_surface_activate(xsurface->xwm, NULL);
	}

	wl_list_remove(&xsurface->link);
	wl_list_remove(&xsurface->parent_link);

	if (xsurface->surface_id) {
		wl_list_remove(&xsurface->unpaired_link);
	}

	if (xsurface->surface) {
		wl_list_remove(&xsurface->surface_destroy.link);
		wlr_surface_set_role_committed(xsurface->surface, NULL, NULL);
	}

	free(xsurface->title);
	free(xsurface->class);
	free(xsurface->instance);
	free(xsurface->window_type);
	free(xsurface->protocols);
	free(xsurface->hints);
	free(xsurface->size_hints);
	free(xsurface);
}

static void read_surface_class(struct wlr_xwm *xwm,
		struct wlr_xwayland_surface *surface, xcb_get_property_reply_t *reply) {
	if (reply->type != XCB_ATOM_STRING &&
			reply->type != xwm->atoms[UTF8_STRING]) {
		return;
	}

	size_t len = xcb_get_property_value_length(reply);
	char *class = xcb_get_property_value(reply);

	// Unpack two sequentially stored strings: instance, class
	size_t instance_len = strnlen(class, len);
	free(surface->instance);
	if (len > 0 && instance_len < len) {
		surface->instance = strndup(class, instance_len);
		class += instance_len + 1;
	} else {
		surface->instance = NULL;
	}
	free(surface->class);
	if (len > 0) {
		surface->class = strndup(class, len);
	} else {
		surface->class = NULL;
	}

	wlr_log(L_DEBUG, "XCB_ATOM_WM_CLASS: %s %s", surface->instance,
		surface->class);
	wlr_signal_emit_safe(&surface->events.set_class, surface);
}

static void read_surface_title(struct wlr_xwm *xwm,
		struct wlr_xwayland_surface *xsurface,
		xcb_get_property_reply_t *reply) {
	if (reply->type != XCB_ATOM_STRING &&
			reply->type != xwm->atoms[UTF8_STRING]) {
		return;
	}

	// TODO: if reply->type == XCB_ATOM_STRING, uses latin1 encoding
	// if reply->type == xwm->atoms[UTF8_STRING], uses utf8 encoding

	size_t len = xcb_get_property_value_length(reply);
	char *title = xcb_get_property_value(reply);

	free(xsurface->title);
	if (len > 0) {
		xsurface->title = strndup(title, len);
	} else {
		xsurface->title = NULL;
	}

	wlr_log(L_DEBUG, "XCB_ATOM_WM_NAME: %s", xsurface->title);
	wlr_signal_emit_safe(&xsurface->events.set_title, xsurface);
}

static void read_surface_parent(struct wlr_xwm *xwm,
		struct wlr_xwayland_surface *xsurface,
		xcb_get_property_reply_t *reply) {
	if (reply->type != XCB_ATOM_WINDOW) {
		return;
	}

	xcb_window_t *xid = xcb_get_property_value(reply);
	if (xid != NULL) {
		xsurface->parent = lookup_surface(xwm, *xid);
	} else {
		xsurface->parent = NULL;
	}

	wl_list_remove(&xsurface->parent_link);
	if (xsurface->parent != NULL) {
		wl_list_insert(&xsurface->parent->children, &xsurface->parent_link);
	} else {
		wl_list_init(&xsurface->parent_link);
	}

	wlr_log(L_DEBUG, "XCB_ATOM_WM_TRANSIENT_FOR: %p", xsurface->parent);
	wlr_signal_emit_safe(&xsurface->events.set_parent, xsurface);
}

static void read_surface_pid(struct wlr_xwm *xwm,
		struct wlr_xwayland_surface *xsurface,
		xcb_get_property_reply_t *reply) {
	if (reply->type != XCB_ATOM_CARDINAL) {
		return;
	}

	pid_t *pid = xcb_get_property_value(reply);
	xsurface->pid = *pid;
	wlr_log(L_DEBUG, "NET_WM_PID %d", xsurface->pid);
	wlr_signal_emit_safe(&xsurface->events.set_pid, xsurface);
}

static void read_surface_window_type(struct wlr_xwm *xwm,
		struct wlr_xwayland_surface *xsurface,
		xcb_get_property_reply_t *reply) {
	if (reply->type != XCB_ATOM_ATOM) {
		return;
	}

	xcb_atom_t *atoms = xcb_get_property_value(reply);
	size_t atoms_len = reply->value_len;
	size_t atoms_size = sizeof(xcb_atom_t) * atoms_len;

	free(xsurface->window_type);
	xsurface->window_type = malloc(atoms_size);
	if (xsurface->window_type == NULL) {
		return;
	}
	memcpy(xsurface->window_type, atoms, atoms_size);
	xsurface->window_type_len = atoms_len;

	wlr_log(L_DEBUG, "NET_WM_WINDOW_TYPE (%zu)", atoms_len);
	wlr_signal_emit_safe(&xsurface->events.set_window_type, xsurface);
}

static void read_surface_protocols(struct wlr_xwm *xwm,
		struct wlr_xwayland_surface *xsurface,
		xcb_get_property_reply_t *reply) {
	if (reply->type != XCB_ATOM_ATOM) {
		return;
	}

	xcb_atom_t *atoms = xcb_get_property_value(reply);
	size_t atoms_len = reply->value_len;
	size_t atoms_size = sizeof(xcb_atom_t) * atoms_len;

	free(xsurface->protocols);
	xsurface->protocols = malloc(atoms_size);
	if (xsurface->protocols == NULL) {
		return;
	}
	memcpy(xsurface->protocols, atoms, atoms_size);
	xsurface->protocols_len = atoms_len;

	wlr_log(L_DEBUG, "WM_PROTOCOLS (%zu)", atoms_len);
}

#ifdef WLR_HAS_XCB_ICCCM
static void read_surface_hints(struct wlr_xwm *xwm,
		struct wlr_xwayland_surface *xsurface,
		xcb_get_property_reply_t *reply) {
	// According to the docs, reply->type == xwm->atoms[WM_HINTS]
	// In practice, reply->type == XCB_ATOM_ATOM
	if (reply->value_len == 0) {
		return;
	}

	xcb_icccm_wm_hints_t hints;
	xcb_icccm_get_wm_hints_from_reply(&hints, reply);

	free(xsurface->hints);
	xsurface->hints = calloc(1, sizeof(struct wlr_xwayland_surface_hints));
	if (xsurface->hints == NULL) {
		return;
	}
	memcpy(xsurface->hints, &hints, sizeof(struct wlr_xwayland_surface_hints));
	xsurface->hints_urgency = xcb_icccm_wm_hints_get_urgency(&hints);

	wlr_log(L_DEBUG, "WM_HINTS (%d)", reply->value_len);
}
#else
static void read_surface_hints(struct wlr_xwm *xwm,
		struct wlr_xwayland_surface *xsurface,
		xcb_get_property_reply_t *reply) {
	// Do nothing
}
#endif

#ifdef WLR_HAS_XCB_ICCCM
static void read_surface_normal_hints(struct wlr_xwm *xwm,
		struct wlr_xwayland_surface *xsurface,
		xcb_get_property_reply_t *reply) {
	if (reply->type != xwm->atoms[WM_SIZE_HINTS] || reply->value_len == 0) {
		return;
	}

	xcb_size_hints_t size_hints;
	xcb_icccm_get_wm_size_hints_from_reply(&size_hints, reply);

	free(xsurface->size_hints);
	xsurface->size_hints =
		calloc(1, sizeof(struct wlr_xwayland_surface_size_hints));
	if (xsurface->size_hints == NULL) {
		return;
	}
	memcpy(xsurface->size_hints, &size_hints,
		sizeof(struct wlr_xwayland_surface_size_hints));

	wlr_log(L_DEBUG, "WM_NORMAL_HINTS (%d)", reply->value_len);
}
#else
static void read_surface_normal_hints(struct wlr_xwm *xwm,
		struct wlr_xwayland_surface *xsurface,
		xcb_get_property_reply_t *reply) {
	// Do nothing
}
#endif


#define MWM_HINTS_FLAGS_FIELD 0
#define MWM_HINTS_DECORATIONS_FIELD 2

#define MWM_HINTS_DECORATIONS (1 << 1)

#define MWM_DECOR_ALL (1 << 0)
#define MWM_DECOR_BORDER (1 << 1)
#define MWM_DECOR_TITLE (1 << 3)

static void read_surface_motif_hints(struct wlr_xwm *xwm,
		struct wlr_xwayland_surface *xsurface,
		xcb_get_property_reply_t *reply) {
	if (reply->value_len < 5) {
		return;
	}

	uint32_t *motif_hints = xcb_get_property_value(reply);
	if (motif_hints[MWM_HINTS_FLAGS_FIELD] & MWM_HINTS_DECORATIONS) {
		xsurface->decorations = WLR_XWAYLAND_SURFACE_DECORATIONS_ALL;
		uint32_t decorations = motif_hints[MWM_HINTS_DECORATIONS_FIELD];
		if ((decorations & MWM_DECOR_ALL) == 0) {
			if ((decorations & MWM_DECOR_BORDER) == 0) {
				xsurface->decorations |=
					WLR_XWAYLAND_SURFACE_DECORATIONS_NO_BORDER;
			}
			if ((decorations & MWM_DECOR_TITLE) == 0) {
				xsurface->decorations |=
					WLR_XWAYLAND_SURFACE_DECORATIONS_NO_TITLE;
			}
		}
	}

	wlr_log(L_DEBUG, "MOTIF_WM_HINTS (%d)", reply->value_len);
}

static void read_surface_net_wm_state(struct wlr_xwm *xwm,
		struct wlr_xwayland_surface *xsurface,
		xcb_get_property_reply_t *reply) {
	xsurface->fullscreen = 0;
	xcb_atom_t *atom = xcb_get_property_value(reply);
	for (uint32_t i = 0; i < reply->value_len; i++) {
		if (atom[i] == xwm->atoms[_NET_WM_STATE_FULLSCREEN]) {
			xsurface->fullscreen = true;
		} else if (atom[i] == xwm->atoms[_NET_WM_STATE_MAXIMIZED_VERT]) {
			xsurface->maximized_vert = true;
		} else if (atom[i] == xwm->atoms[_NET_WM_STATE_MAXIMIZED_HORZ]) {
			xsurface->maximized_horz = true;
		}
	}
}

static void read_surface_property(struct wlr_xwm *xwm,
		struct wlr_xwayland_surface *xsurface, xcb_atom_t property) {
	xcb_get_property_cookie_t cookie = xcb_get_property(xwm->xcb_conn, 0,
		xsurface->window_id, property, XCB_ATOM_ANY, 0, 2048);
	xcb_get_property_reply_t *reply = xcb_get_property_reply(xwm->xcb_conn,
		cookie, NULL);
	if (reply == NULL) {
		return;
	}

	if (property == XCB_ATOM_WM_CLASS) {
		read_surface_class(xwm, xsurface, reply);
	} else if (property == XCB_ATOM_WM_NAME ||
			property == xwm->atoms[NET_WM_NAME]) {
		read_surface_title(xwm, xsurface, reply);
	} else if (property == XCB_ATOM_WM_TRANSIENT_FOR) {
		read_surface_parent(xwm, xsurface, reply);
	} else if (property == xwm->atoms[NET_WM_PID]) {
		read_surface_pid(xwm, xsurface, reply);
	} else if (property == xwm->atoms[NET_WM_WINDOW_TYPE]) {
		read_surface_window_type(xwm, xsurface, reply);
	} else if (property == xwm->atoms[WM_PROTOCOLS]) {
		read_surface_protocols(xwm, xsurface, reply);
	} else if (property == xwm->atoms[NET_WM_STATE]) {
		read_surface_net_wm_state(xwm, xsurface, reply);
	} else if (property == xwm->atoms[WM_HINTS]) {
		read_surface_hints(xwm, xsurface, reply);
	} else if (property == xwm->atoms[WM_NORMAL_HINTS]) {
		read_surface_normal_hints(xwm, xsurface, reply);
	} else if (property == xwm->atoms[MOTIF_WM_HINTS]) {
		read_surface_motif_hints(xwm, xsurface, reply);
	} else {
		wlr_log(L_DEBUG, "unhandled x11 property %u", property);
	}

	free(reply);
}

static void handle_surface_commit(struct wlr_surface *wlr_surface,
		void *role_data) {
	struct wlr_xwayland_surface *xsurface = role_data;

	if (!xsurface->added &&
			wlr_surface_has_buffer(xsurface->surface) &&
			xsurface->mapped) {
		wlr_signal_emit_safe(&xsurface->xwm->xwayland->events.new_surface, xsurface);
		xsurface->added = true;
	}
}

static void handle_surface_destroy(struct wl_listener *listener, void *data) {
	struct wlr_xwayland_surface *xsurface =
		wl_container_of(listener, xsurface, surface_destroy);

	xsurface->surface = NULL;
	// TODO destroy xwayland surface?
}

static void xwm_map_shell_surface(struct wlr_xwm *xwm,
		struct wlr_xwayland_surface *xsurface,
		struct wlr_surface *surface) {
	xsurface->surface = surface;

	// read all surface properties
	const xcb_atom_t props[] = {
		XCB_ATOM_WM_CLASS,
		XCB_ATOM_WM_NAME,
		XCB_ATOM_WM_TRANSIENT_FOR,
		xwm->atoms[WM_PROTOCOLS],
		xwm->atoms[WM_HINTS],
		xwm->atoms[WM_NORMAL_HINTS],
		xwm->atoms[MOTIF_WM_HINTS],
		xwm->atoms[NET_WM_STATE],
		xwm->atoms[NET_WM_WINDOW_TYPE],
		xwm->atoms[NET_WM_NAME],
		xwm->atoms[NET_WM_PID],
	};
	for (size_t i = 0; i < sizeof(props)/sizeof(xcb_atom_t); i++) {
		read_surface_property(xwm, xsurface, props[i]);
	}

	wlr_surface_set_role_committed(xsurface->surface, handle_surface_commit,
		xsurface);

	xsurface->surface_destroy.notify = handle_surface_destroy;
	wl_signal_add(&surface->events.destroy, &xsurface->surface_destroy);

	xsurface->mapped = true;
	wlr_signal_emit_safe(&xsurface->events.map, xsurface);
}

static void xwm_handle_create_notify(struct wlr_xwm *xwm,
		xcb_create_notify_event_t *ev) {
	wlr_log(L_DEBUG, "XCB_CREATE_NOTIFY (%u)", ev->window);
	wlr_xwayland_surface_create(xwm, ev->window, ev->x, ev->y,
		ev->width, ev->height, ev->override_redirect);
}

static void xwm_handle_destroy_notify(struct wlr_xwm *xwm,
		xcb_destroy_notify_event_t *ev) {
	wlr_log(L_DEBUG, "XCB_DESTROY_NOTIFY (%u)", ev->window);
	struct wlr_xwayland_surface *xsurface = lookup_surface(xwm, ev->window);
	if (xsurface == NULL) {
		return;
	}
	wlr_xwayland_surface_destroy(xsurface);
}

static void xwm_handle_configure_request(struct wlr_xwm *xwm,
		xcb_configure_request_event_t *ev) {
	wlr_log(L_DEBUG, "XCB_CONFIGURE_REQUEST (%u) [%ux%u+%d,%d]", ev->window,
		ev->width, ev->height, ev->x, ev->y);
	struct wlr_xwayland_surface *xsurface = lookup_surface(xwm, ev->window);
	if (xsurface == NULL) {
		return;
	}

	// TODO: handle ev->{parent,sibling}?

	if (xsurface->surface == NULL) {
		// Surface has not been mapped yet
		wlr_xwayland_surface_configure(xsurface, ev->x, ev->y,
			ev->width, ev->height);
	} else {
		struct wlr_xwayland_surface_configure_event *wlr_event =
			calloc(1, sizeof(struct wlr_xwayland_surface_configure_event));
		if (wlr_event == NULL) {
			return;
		}

		wlr_event->surface = xsurface;
		wlr_event->x = ev->x;
		wlr_event->y = ev->y;
		wlr_event->width = ev->width;
		wlr_event->height = ev->height;

		wlr_signal_emit_safe(&xsurface->events.request_configure, wlr_event);

		free(wlr_event);
	}
}

static void xwm_handle_configure_notify(struct wlr_xwm *xwm,
		xcb_configure_notify_event_t *ev) {
	struct wlr_xwayland_surface *xsurface =
		lookup_surface(xwm, ev->window);

	if (!xsurface) {
		return;
	}

	xsurface->x = ev->x;
	xsurface->y = ev->y;
	xsurface->width = ev->width;
	xsurface->height = ev->height;
}

#define ICCCM_WITHDRAWN_STATE	0
#define ICCCM_NORMAL_STATE	1
#define ICCCM_ICONIC_STATE	3

static void xsurface_set_wm_state(struct wlr_xwayland_surface *xsurface,
		int32_t state) {
	struct wlr_xwm *xwm = xsurface->xwm;
	uint32_t property[2];

	property[0] = state;
	property[1] = XCB_WINDOW_NONE;

	xcb_change_property(xwm->xcb_conn,
		XCB_PROP_MODE_REPLACE,
		xsurface->window_id,
		xwm->atoms[WM_STATE],
		xwm->atoms[WM_STATE],
		32, // format
		2, property);
}

static void xwm_handle_map_request(struct wlr_xwm *xwm,
		xcb_map_request_event_t *ev) {
	wlr_log(L_DEBUG, "XCB_MAP_REQUEST (%u)", ev->window);
	struct wlr_xwayland_surface *xsurface = lookup_surface(xwm, ev->window);
	if (!xsurface) {
		return;
	}

	xsurface_set_wm_state(xsurface, ICCCM_NORMAL_STATE);
	xsurface_set_net_wm_state(xsurface);
	xcb_map_window(xwm->xcb_conn, ev->window);
}

static void xwm_handle_map_notify(struct wlr_xwm *xwm,
		xcb_map_notify_event_t *ev) {
	wlr_log(L_DEBUG, "XCB_MAP_NOTIFY (%u)", ev->window);
}

static void xwm_handle_unmap_notify(struct wlr_xwm *xwm,
		xcb_unmap_notify_event_t *ev) {
	wlr_log(L_DEBUG, "XCB_UNMAP_NOTIFY (%u)", ev->window);
	struct wlr_xwayland_surface *xsurface = lookup_surface(xwm, ev->window);
	if (xsurface == NULL) {
		return;
	}

	if (xsurface->surface_id) {
		// Make sure we're not on the unpaired surface list or we
		// could be assigned a surface during surface creation that
		// was mapped before this unmap request.
		wl_list_remove(&xsurface->unpaired_link);
		xsurface->surface_id = 0;
	}

	if (xsurface->surface) {
		wlr_surface_set_role_committed(xsurface->surface, NULL, NULL);
		wl_list_remove(&xsurface->surface_destroy.link);
	}
	xsurface->surface = NULL;

	if (xsurface->mapped) {
		xsurface->mapped = false;
		wlr_signal_emit_safe(&xsurface->events.unmap, xsurface);
	}

	xsurface_set_wm_state(xsurface, ICCCM_WITHDRAWN_STATE);
}

static void xwm_handle_property_notify(struct wlr_xwm *xwm,
		xcb_property_notify_event_t *ev) {
	wlr_log(L_DEBUG, "XCB_PROPERTY_NOTIFY (%u)", ev->window);
	struct wlr_xwayland_surface *xsurface = lookup_surface(xwm, ev->window);
	if (xsurface == NULL) {
		return;
	}

	read_surface_property(xwm, xsurface, ev->atom);
}

static void xwm_handle_surface_id_message(struct wlr_xwm *xwm,
		xcb_client_message_event_t *ev) {
	struct wlr_xwayland_surface *xsurface = lookup_surface(xwm, ev->window);
	if (xsurface == NULL) {
		wlr_log(L_DEBUG,
			"client message WL_SURFACE_ID but no new window %u ?",
			ev->window);
		return;
	}
	/* Check if we got notified after wayland surface create event */
	uint32_t id = ev->data.data32[0];
	struct wl_resource *resource =
		wl_client_get_object(xwm->xwayland->client, id);
	if (resource) {
		struct wlr_surface *surface = wlr_surface_from_resource(resource);
		xsurface->surface_id = 0;
		xwm_map_shell_surface(xwm, xsurface, surface);
	} else {
		xsurface->surface_id = id;
		wl_list_insert(&xwm->unpaired_surfaces, &xsurface->unpaired_link);
	}
}

#define _NET_WM_MOVERESIZE_SIZE_TOPLEFT      0
#define _NET_WM_MOVERESIZE_SIZE_TOP          1
#define _NET_WM_MOVERESIZE_SIZE_TOPRIGHT     2
#define _NET_WM_MOVERESIZE_SIZE_RIGHT        3
#define _NET_WM_MOVERESIZE_SIZE_BOTTOMRIGHT  4
#define _NET_WM_MOVERESIZE_SIZE_BOTTOM       5
#define _NET_WM_MOVERESIZE_SIZE_BOTTOMLEFT   6
#define _NET_WM_MOVERESIZE_SIZE_LEFT         7
#define _NET_WM_MOVERESIZE_MOVE              8  // movement only
#define _NET_WM_MOVERESIZE_SIZE_KEYBOARD     9  // size via keyboard
#define _NET_WM_MOVERESIZE_MOVE_KEYBOARD    10  // move via keyboard
#define _NET_WM_MOVERESIZE_CANCEL           11  // cancel operation

static enum wlr_edges net_wm_edges_to_wlr(uint32_t net_wm_edges) {
	enum wlr_edges edges = WLR_EDGE_NONE;

	switch(net_wm_edges) {
		case _NET_WM_MOVERESIZE_SIZE_TOPLEFT:
			edges = WLR_EDGE_TOP | WLR_EDGE_LEFT;
			break;
		case _NET_WM_MOVERESIZE_SIZE_TOP:
			edges = WLR_EDGE_TOP;
			break;
		case _NET_WM_MOVERESIZE_SIZE_TOPRIGHT:
			edges = WLR_EDGE_TOP | WLR_EDGE_RIGHT;
			break;
		case _NET_WM_MOVERESIZE_SIZE_RIGHT:
			edges = WLR_EDGE_RIGHT;
			break;
		case _NET_WM_MOVERESIZE_SIZE_BOTTOMRIGHT:
			edges = WLR_EDGE_BOTTOM | WLR_EDGE_RIGHT;
			break;
		case _NET_WM_MOVERESIZE_SIZE_BOTTOM:
			edges = WLR_EDGE_BOTTOM;
			break;
		case _NET_WM_MOVERESIZE_SIZE_BOTTOMLEFT:
			edges = WLR_EDGE_BOTTOM | WLR_EDGE_LEFT;
			break;
		case _NET_WM_MOVERESIZE_SIZE_LEFT:
			edges = WLR_EDGE_LEFT;
			break;
		default:
			break;
	}

	return edges;
}

static void xwm_handle_net_wm_moveresize_message(struct wlr_xwm *xwm,
		xcb_client_message_event_t *ev) {
	struct wlr_xwayland_surface *xsurface = lookup_surface(xwm, ev->window);
	if (!xsurface) {
		return;
	}

	// TODO: we should probably add input or seat info to this but we would just
	// be guessing
	struct wlr_xwayland_resize_event resize_event;
	struct wlr_xwayland_move_event move_event;

	int detail = ev->data.data32[2];
	switch (detail) {
	case _NET_WM_MOVERESIZE_MOVE:
		move_event.surface = xsurface;
		wlr_signal_emit_safe(&xsurface->events.request_move, &move_event);
		break;
	case _NET_WM_MOVERESIZE_SIZE_TOPLEFT:
	case _NET_WM_MOVERESIZE_SIZE_TOP:
	case _NET_WM_MOVERESIZE_SIZE_TOPRIGHT:
	case _NET_WM_MOVERESIZE_SIZE_RIGHT:
	case _NET_WM_MOVERESIZE_SIZE_BOTTOMRIGHT:
	case _NET_WM_MOVERESIZE_SIZE_BOTTOM:
	case _NET_WM_MOVERESIZE_SIZE_BOTTOMLEFT:
	case _NET_WM_MOVERESIZE_SIZE_LEFT:
		resize_event.surface = xsurface;
		resize_event.edges = net_wm_edges_to_wlr(detail);
		wlr_signal_emit_safe(&xsurface->events.request_resize, &resize_event);
		break;
	case _NET_WM_MOVERESIZE_CANCEL:
		// handled by the compositor
		break;
	}
}

#define _NET_WM_STATE_REMOVE	0
#define _NET_WM_STATE_ADD	1
#define _NET_WM_STATE_TOGGLE	2

static bool update_state(int action, bool *state) {
	int new_state, changed;

	switch (action) {
		case _NET_WM_STATE_REMOVE:
			new_state = false;
			break;
		case _NET_WM_STATE_ADD:
			new_state = true;
			break;
		case _NET_WM_STATE_TOGGLE:
			new_state = !*state;
			break;
		default:
			return false;
	}

	changed = (*state != new_state);
	*state = new_state;

	return changed;
}

static inline bool xsurface_is_maximized(
		struct wlr_xwayland_surface *xsurface) {
	return xsurface->maximized_horz && xsurface->maximized_vert;
}

static void xwm_handle_net_wm_state_message(struct wlr_xwm *xwm,
		xcb_client_message_event_t *client_message) {
	struct wlr_xwayland_surface *xsurface =
		lookup_surface(xwm, client_message->window);
	if (!xsurface) {
		return;
	}
	if (client_message->format != 32) {
		return;
	}

	bool fullscreen = xsurface->fullscreen;
	bool maximized = xsurface_is_maximized(xsurface);

	uint32_t action = client_message->data.data32[0];
	for (size_t i = 0; i < 2; ++i) {
		uint32_t property = client_message->data.data32[1 + i];

		if (property == xwm->atoms[_NET_WM_STATE_FULLSCREEN] &&
				update_state(action, &xsurface->fullscreen)) {
			xsurface_set_net_wm_state(xsurface);
		} else if (property == xwm->atoms[_NET_WM_STATE_MAXIMIZED_VERT] &&
				update_state(action, &xsurface->maximized_vert)) {
			xsurface_set_net_wm_state(xsurface);
		} else if (property == xwm->atoms[_NET_WM_STATE_MAXIMIZED_HORZ] &&
				update_state(action, &xsurface->maximized_horz)) {
			xsurface_set_net_wm_state(xsurface);
		}
	}
	// client_message->data.data32[3] is the source indication
	// all other values are set to 0

	if (fullscreen != xsurface->fullscreen) {
		if (xsurface->fullscreen) {
			xsurface->saved_width = xsurface->width;
			xsurface->saved_height = xsurface->height;
		}

		wlr_signal_emit_safe(&xsurface->events.request_fullscreen, xsurface);
	}

	if (maximized != xsurface_is_maximized(xsurface)) {
		if (xsurface_is_maximized(xsurface)) {
			xsurface->saved_width = xsurface->width;
			xsurface->saved_height = xsurface->height;
		}

		wlr_signal_emit_safe(&xsurface->events.request_maximize, xsurface);
	}
}

static void xwm_handle_client_message(struct wlr_xwm *xwm,
		xcb_client_message_event_t *ev) {
	wlr_log(L_DEBUG, "XCB_CLIENT_MESSAGE (%u)", ev->window);

	if (ev->type == xwm->atoms[WL_SURFACE_ID]) {
		xwm_handle_surface_id_message(xwm, ev);
	} else if (ev->type == xwm->atoms[NET_WM_STATE]) {
		xwm_handle_net_wm_state_message(xwm, ev);
	} else if (ev->type == xwm->atoms[_NET_WM_MOVERESIZE]) {
		xwm_handle_net_wm_moveresize_message(xwm, ev);
	} else {
		wlr_log(L_DEBUG, "unhandled x11 client message %u", ev->type);
	}
}

static void xwm_handle_focus_in(struct wlr_xwm *xwm,
		xcb_focus_in_event_t *ev) {
	// Do not interfere with grabs
	if (ev->mode == XCB_NOTIFY_MODE_GRAB ||
			ev->mode == XCB_NOTIFY_MODE_UNGRAB) {
		return;
	}

	// Do not let X clients change the focus behind the compositor's
	// back. Reset the focus to the old one if it changed.
	if (!xwm->focus_surface || ev->event != xwm->focus_surface->window_id) {
		xwm_send_focus_window(xwm, xwm->focus_surface);
	}
}

static void xwm_handle_xcb_error(struct wlr_xwm *xwm, xcb_value_error_t *ev) {
#ifdef WLR_HAS_XCB_ERRORS
	const char *major_name =
		xcb_errors_get_name_for_major_code(xwm->errors_context,
			ev->major_opcode);
	if (!major_name) {
		wlr_log(L_DEBUG, "xcb error happened, but could not get major name");
		goto log_raw;
	}

	const char *minor_name =
		xcb_errors_get_name_for_minor_code(xwm->errors_context,
			ev->major_opcode, ev->minor_opcode);

	const char *extension;
	const char *error_name =
		xcb_errors_get_name_for_error(xwm->errors_context,
			ev->error_code, &extension);
	if (!error_name) {
		wlr_log(L_DEBUG, "xcb error happened, but could not get error name");
		goto log_raw;
	}

	wlr_log(L_ERROR, "xcb error: op %s (%s), code %s (%s), sequence %"PRIu16", value %"PRIu32,
		major_name, minor_name ? minor_name : "no minor",
		error_name, extension ? extension : "no extension",
		ev->sequence, ev->bad_value);

	return;
log_raw:
#endif
	wlr_log(L_ERROR,
		"xcb error: op %"PRIu8":%"PRIu16", code %"PRIu8", sequence %"PRIu16", value %"PRIu32,
		ev->major_opcode, ev->minor_opcode, ev->error_code,
		ev->sequence, ev->bad_value);

}

static void xwm_handle_unhandled_event(struct wlr_xwm *xwm, xcb_generic_event_t *ev) {
#ifdef WLR_HAS_XCB_ERRORS
	const char *extension;
	const char *event_name =
		xcb_errors_get_name_for_xcb_event(xwm->errors_context,
			ev, &extension);
	if (!event_name) {
		wlr_log(L_DEBUG, "no name for unhandled event: %u",
			ev->response_type);
		return;
	}

	wlr_log(L_DEBUG, "unhandled X11 event: %s (%u)", event_name, ev->response_type);
#else
	wlr_log(L_DEBUG, "unhandled X11 event: %u", ev->response_type);
#endif
}

/* This is in xcb/xcb_event.h, but pulling xcb-util just for a constant
 * others redefine anyway is meh
 */
#define XCB_EVENT_RESPONSE_TYPE_MASK (0x7f)
static int x11_event_handler(int fd, uint32_t mask, void *data) {
	int count = 0;
	xcb_generic_event_t *event;
	struct wlr_xwm *xwm = data;

	while ((event = xcb_poll_for_event(xwm->xcb_conn))) {
		count++;

		if (xwm->xwayland->user_event_handler &&
				xwm->xwayland->user_event_handler(xwm, event)) {
			break;
		}

		if (xwm_handle_selection_event(xwm, event)) {
			free(event);
			continue;
		}

		switch (event->response_type & XCB_EVENT_RESPONSE_TYPE_MASK) {
		case XCB_CREATE_NOTIFY:
			xwm_handle_create_notify(xwm, (xcb_create_notify_event_t *)event);
			break;
		case XCB_DESTROY_NOTIFY:
			xwm_handle_destroy_notify(xwm, (xcb_destroy_notify_event_t *)event);
			break;
		case XCB_CONFIGURE_REQUEST:
			xwm_handle_configure_request(xwm,
				(xcb_configure_request_event_t *)event);
			break;
		case XCB_CONFIGURE_NOTIFY:
			xwm_handle_configure_notify(xwm,
				(xcb_configure_notify_event_t *)event);
			break;
		case XCB_MAP_REQUEST:
			xwm_handle_map_request(xwm, (xcb_map_request_event_t *)event);
			break;
		case XCB_MAP_NOTIFY:
			xwm_handle_map_notify(xwm, (xcb_map_notify_event_t *)event);
			break;
		case XCB_UNMAP_NOTIFY:
			xwm_handle_unmap_notify(xwm, (xcb_unmap_notify_event_t *)event);
			break;
		case XCB_PROPERTY_NOTIFY:
			xwm_handle_property_notify(xwm,
				(xcb_property_notify_event_t *)event);
			break;
		case XCB_CLIENT_MESSAGE:
			xwm_handle_client_message(xwm, (xcb_client_message_event_t *)event);
			break;
		case XCB_FOCUS_IN:
			xwm_handle_focus_in(xwm, (xcb_focus_in_event_t *)event);
			break;
		case 0:
			xwm_handle_xcb_error(xwm, (xcb_value_error_t *)event);
			break;
		default:
			xwm_handle_unhandled_event(xwm, event);
			break;
		}
		free(event);
	}

	if (count) {
		xcb_flush(xwm->xcb_conn);
	}

	return count;
}

static void handle_compositor_new_surface(struct wl_listener *listener,
		void *data) {
	struct wlr_xwm *xwm =
		wl_container_of(listener, xwm, compositor_new_surface);
	struct wlr_surface *surface = data;
	if (wl_resource_get_client(surface->resource) != xwm->xwayland->client) {
		return;
	}

	wlr_log(L_DEBUG, "New xwayland surface: %p", surface);

	uint32_t surface_id = wl_resource_get_id(surface->resource);
	struct wlr_xwayland_surface *xsurface;
	wl_list_for_each(xsurface, &xwm->unpaired_surfaces, unpaired_link) {
		if (xsurface->surface_id == surface_id) {
			xwm_map_shell_surface(xwm, xsurface, surface);
			xsurface->surface_id = 0;
			wl_list_remove(&xsurface->unpaired_link);
			xcb_flush(xwm->xcb_conn);
			return;
		}
	}
}

static void handle_compositor_destroy(struct wl_listener *listener,
		void *data) {
	struct wlr_xwm *xwm =
		wl_container_of(listener, xwm, compositor_destroy);
	wl_list_remove(&xwm->compositor_new_surface.link);
	wl_list_remove(&xwm->compositor_destroy.link);
	wl_list_init(&xwm->compositor_new_surface.link);
	wl_list_init(&xwm->compositor_destroy.link);
}

void wlr_xwayland_surface_activate(struct wlr_xwayland_surface *xsurface,
		bool activated) {
	struct wlr_xwayland_surface *focused = xsurface->xwm->focus_surface;
	if (activated) {
		xwm_surface_activate(xsurface->xwm, xsurface);
	} else if (focused == xsurface) {
		xwm_surface_activate(xsurface->xwm, NULL);
	}
}

void wlr_xwayland_surface_configure(struct wlr_xwayland_surface *xsurface,
		int16_t x, int16_t y, uint16_t width, uint16_t height) {
	xsurface->x = x;
	xsurface->y = y;
	xsurface->width = width;
	xsurface->height = height;

	struct wlr_xwm *xwm = xsurface->xwm;
	uint32_t mask = XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y |
		XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT |
		XCB_CONFIG_WINDOW_BORDER_WIDTH;
	uint32_t values[] = {x, y, width, height, 0};
	xcb_configure_window(xwm->xcb_conn, xsurface->window_id, mask, values);
	xcb_flush(xwm->xcb_conn);
}

void wlr_xwayland_surface_close(struct wlr_xwayland_surface *xsurface) {
	struct wlr_xwm *xwm = xsurface->xwm;

	bool supports_delete = false;
	for (size_t i = 0; i < xsurface->protocols_len; i++) {
		if (xsurface->protocols[i] == xwm->atoms[WM_DELETE_WINDOW]) {
			supports_delete = true;
			break;
		}
	}

	if (supports_delete) {
		xcb_client_message_event_t ev = {0};
		ev.response_type = XCB_CLIENT_MESSAGE;
		ev.window = xsurface->window_id;
		ev.format = 32;
		ev.sequence = 0;
		ev.type = xwm->atoms[WM_PROTOCOLS];
		ev.data.data32[0] = xwm->atoms[WM_DELETE_WINDOW];
		ev.data.data32[1] = XCB_CURRENT_TIME;
		xcb_send_event(xwm->xcb_conn, 0,
			xsurface->window_id,
			XCB_EVENT_MASK_NO_EVENT,
			(char *)&ev);
	} else {
		xcb_kill_client(xwm->xcb_conn, xsurface->window_id);
	}

	xcb_flush(xwm->xcb_conn);
}

void xwm_destroy(struct wlr_xwm *xwm) {
	if (!xwm) {
		return;
	}
	xwm_selection_finish(xwm);
	if (xwm->cursor) {
		xcb_free_cursor(xwm->xcb_conn, xwm->cursor);
	}
	if (xwm->colormap) {
		xcb_free_colormap(xwm->xcb_conn, xwm->colormap);
	}
	if (xwm->window) {
		xcb_destroy_window(xwm->xcb_conn, xwm->window);
	}
	if (xwm->event_source) {
		wl_event_source_remove(xwm->event_source);
	}
#ifdef WLR_HAS_XCB_ERRORS
	if (xwm->errors_context) {
		xcb_errors_context_free(xwm->errors_context);
	}
#endif
	struct wlr_xwayland_surface *xsurface, *tmp;
	wl_list_for_each_safe(xsurface, tmp, &xwm->surfaces, link) {
		wlr_xwayland_surface_destroy(xsurface);
	}
	wl_list_for_each_safe(xsurface, tmp, &xwm->unpaired_surfaces, link) {
		wlr_xwayland_surface_destroy(xsurface);
	}
	wl_list_remove(&xwm->compositor_new_surface.link);
	wl_list_remove(&xwm->compositor_destroy.link);
	xcb_disconnect(xwm->xcb_conn);

	free(xwm);
}

static void xwm_get_resources(struct wlr_xwm *xwm) {
	xcb_prefetch_extension_data(xwm->xcb_conn, &xcb_xfixes_id);
	xcb_prefetch_extension_data(xwm->xcb_conn, &xcb_composite_id);

	size_t i;
	xcb_intern_atom_cookie_t cookies[ATOM_LAST];

	for (i = 0; i < ATOM_LAST; i++) {
		cookies[i] =
			xcb_intern_atom(xwm->xcb_conn, 0, strlen(atom_map[i]), atom_map[i]);
	}
	for (i = 0; i < ATOM_LAST; i++) {
		xcb_generic_error_t *error;
		xcb_intern_atom_reply_t *reply =
			xcb_intern_atom_reply(xwm->xcb_conn, cookies[i], &error);
		if (reply && !error) {
			xwm->atoms[i] = reply->atom;
		}
		free(reply);

		if (error) {
			wlr_log(L_ERROR, "could not resolve atom %s, x11 error code %d",
				atom_map[i], error->error_code);
			free(error);
			return;
		}
	}

	xwm->xfixes = xcb_get_extension_data(xwm->xcb_conn, &xcb_xfixes_id);

	if (!xwm->xfixes || !xwm->xfixes->present) {
		wlr_log(L_DEBUG, "xfixes not available");
	}

	xcb_xfixes_query_version_cookie_t xfixes_cookie;
	xcb_xfixes_query_version_reply_t *xfixes_reply;
	xfixes_cookie =
		xcb_xfixes_query_version(xwm->xcb_conn, XCB_XFIXES_MAJOR_VERSION,
			XCB_XFIXES_MINOR_VERSION);
	xfixes_reply =
		xcb_xfixes_query_version_reply(xwm->xcb_conn, xfixes_cookie, NULL);

	wlr_log(L_DEBUG, "xfixes version: %d.%d",
		xfixes_reply->major_version, xfixes_reply->minor_version);

	free(xfixes_reply);
}

static void xwm_create_wm_window(struct wlr_xwm *xwm) {
	static const char name[] = "wlroots wm";

	xwm->window = xcb_generate_id(xwm->xcb_conn);

	xcb_create_window(xwm->xcb_conn,
		XCB_COPY_FROM_PARENT,
		xwm->window,
		xwm->screen->root,
		0, 0,
		10, 10,
		0,
		XCB_WINDOW_CLASS_INPUT_OUTPUT,
		xwm->screen->root_visual,
		0, NULL);

	xcb_change_property(xwm->xcb_conn,
		XCB_PROP_MODE_REPLACE,
		xwm->window,
		xwm->atoms[_NET_WM_NAME],
		xwm->atoms[UTF8_STRING],
		8, // format
		strlen(name), name);

	xcb_change_property(xwm->xcb_conn,
		XCB_PROP_MODE_REPLACE,
		xwm->screen->root,
		xwm->atoms[_NET_SUPPORTING_WM_CHECK],
		XCB_ATOM_WINDOW,
		32, // format
		1, &xwm->window);

	xcb_change_property(xwm->xcb_conn,
		XCB_PROP_MODE_REPLACE,
		xwm->window,
		xwm->atoms[_NET_SUPPORTING_WM_CHECK],
		XCB_ATOM_WINDOW,
		32, // format
		1, &xwm->window);

	xcb_set_selection_owner(xwm->xcb_conn,
		xwm->window,
		xwm->atoms[WM_S0],
		XCB_CURRENT_TIME);

	xcb_set_selection_owner(xwm->xcb_conn,
		xwm->window,
		xwm->atoms[NET_WM_S0],
		XCB_CURRENT_TIME);
}

// TODO use me to support 32 bit color somehow
static void xwm_get_visual_and_colormap(struct wlr_xwm *xwm) {
	xcb_depth_iterator_t d_iter;
	xcb_visualtype_iterator_t vt_iter;
	xcb_visualtype_t *visualtype;

	d_iter = xcb_screen_allowed_depths_iterator(xwm->screen);
	visualtype = NULL;
	while (d_iter.rem > 0) {
		if (d_iter.data->depth == 32) {
			vt_iter = xcb_depth_visuals_iterator(d_iter.data);
			visualtype = vt_iter.data;
			break;
		}

		xcb_depth_next(&d_iter);
	}

	if (visualtype == NULL) {
		wlr_log(L_DEBUG, "No 32 bit visualtype\n");
		return;
	}

	xwm->visual_id = visualtype->visual_id;
	xwm->colormap = xcb_generate_id(xwm->xcb_conn);
	xcb_create_colormap(xwm->xcb_conn,
		XCB_COLORMAP_ALLOC_NONE,
		xwm->colormap,
		xwm->screen->root,
		xwm->visual_id);
}

static void xwm_get_render_format(struct wlr_xwm *xwm) {
	xcb_render_query_pict_formats_cookie_t cookie =
		xcb_render_query_pict_formats(xwm->xcb_conn);
	xcb_render_query_pict_formats_reply_t *reply =
		xcb_render_query_pict_formats_reply(xwm->xcb_conn, cookie, NULL);
	if (!reply) {
		wlr_log(L_ERROR, "Did not get any reply from xcb_render_query_pict_formats");
		return;
	}
	xcb_render_pictforminfo_iterator_t iter =
		xcb_render_query_pict_formats_formats_iterator(reply);
	xcb_render_pictforminfo_t *format = NULL;
	while (iter.rem > 0) {
		if (iter.data->depth == 32) {
			format = iter.data;
			break;
		}

		xcb_render_pictforminfo_next(&iter);
	}

	if (format == NULL) {
		wlr_log(L_DEBUG, "No 32 bit render format");
		free(reply);
		return;
	}

	xwm->render_format_id = format->id;
	free(reply);
}

void xwm_set_cursor(struct wlr_xwm *xwm, const uint8_t *pixels, uint32_t stride,
		uint32_t width, uint32_t height, int32_t hotspot_x, int32_t hotspot_y) {
	if (!xwm->render_format_id) {
		wlr_log(L_ERROR, "Cannot set xwm cursor: no render format available");
		return;
	}
	if (xwm->cursor) {
		xcb_free_cursor(xwm->xcb_conn, xwm->cursor);
	}

	stride *= 4;
	int depth = 32;

	xcb_pixmap_t pix = xcb_generate_id(xwm->xcb_conn);
	xcb_create_pixmap(xwm->xcb_conn, depth, pix, xwm->screen->root, width,
		height);

	xcb_render_picture_t pic = xcb_generate_id(xwm->xcb_conn);
	xcb_render_create_picture(xwm->xcb_conn, pic, pix, xwm->render_format_id,
		0, 0);

	xcb_gcontext_t gc = xcb_generate_id(xwm->xcb_conn);
	xcb_create_gc(xwm->xcb_conn, gc, pix, 0, NULL);

	xcb_put_image(xwm->xcb_conn, XCB_IMAGE_FORMAT_Z_PIXMAP, pix, gc,
		width, height, 0, 0, 0, depth, stride * height * sizeof(uint8_t),
		pixels);
	xcb_free_gc(xwm->xcb_conn, gc);

	xwm->cursor = xcb_generate_id(xwm->xcb_conn);
	xcb_render_create_cursor(xwm->xcb_conn, xwm->cursor, pic, hotspot_x,
		hotspot_y);
	xcb_free_pixmap(xwm->xcb_conn, pix);

	uint32_t values[] = {xwm->cursor};
	xcb_change_window_attributes(xwm->xcb_conn, xwm->screen->root,
		XCB_CW_CURSOR, values);
	xcb_flush(xwm->xcb_conn);
}

struct wlr_xwm *xwm_create(struct wlr_xwayland *wlr_xwayland) {
	struct wlr_xwm *xwm = calloc(1, sizeof(struct wlr_xwm));
	if (xwm == NULL) {
		return NULL;
	}

	xwm->xwayland = wlr_xwayland;
	wl_list_init(&xwm->surfaces);
	wl_list_init(&xwm->unpaired_surfaces);

	xwm->xcb_conn = xcb_connect_to_fd(wlr_xwayland->wm_fd[0], NULL);

	int rc = xcb_connection_has_error(xwm->xcb_conn);
	if (rc) {
		wlr_log(L_ERROR, "xcb connect failed: %d", rc);
		close(wlr_xwayland->wm_fd[0]);
		free(xwm);
		return NULL;
	}

#ifdef WLR_HAS_XCB_ERRORS
	if (xcb_errors_context_new(xwm->xcb_conn, &xwm->errors_context)) {
		wlr_log(L_ERROR, "Could not allocate error context");
		xwm_destroy(xwm);
		return NULL;
	}
#endif
	xcb_screen_iterator_t screen_iterator =
		xcb_setup_roots_iterator(xcb_get_setup(xwm->xcb_conn));
	xwm->screen = screen_iterator.data;

	struct wl_event_loop *event_loop = wl_display_get_event_loop(
		wlr_xwayland->wl_display);
	xwm->event_source =
		wl_event_loop_add_fd(event_loop,
			wlr_xwayland->wm_fd[0],
			WL_EVENT_READABLE,
			x11_event_handler,
			xwm);
	wl_event_source_check(xwm->event_source);

	xwm_get_resources(xwm);
	xwm_get_visual_and_colormap(xwm);
	xwm_get_render_format(xwm);

	uint32_t values[] = {
		XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY |
			XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT |
			XCB_EVENT_MASK_PROPERTY_CHANGE,
	};
	xcb_change_window_attributes(xwm->xcb_conn,
		xwm->screen->root,
		XCB_CW_EVENT_MASK,
		values);

	xcb_composite_redirect_subwindows(xwm->xcb_conn,
		xwm->screen->root,
		XCB_COMPOSITE_REDIRECT_MANUAL);

	xcb_atom_t supported[] = {
		xwm->atoms[NET_WM_STATE],
		xwm->atoms[_NET_ACTIVE_WINDOW],
		xwm->atoms[_NET_WM_MOVERESIZE],
		xwm->atoms[_NET_WM_STATE_FULLSCREEN],
		xwm->atoms[_NET_WM_STATE_MAXIMIZED_VERT],
		xwm->atoms[_NET_WM_STATE_MAXIMIZED_HORZ],
	};
	xcb_change_property(xwm->xcb_conn,
		XCB_PROP_MODE_REPLACE,
		xwm->screen->root,
		xwm->atoms[NET_SUPPORTED],
		XCB_ATOM_ATOM,
		32,
		sizeof(supported)/sizeof(*supported),
		supported);

	xcb_flush(xwm->xcb_conn);

	xwm_set_net_active_window(xwm, XCB_WINDOW_NONE);

	xwm_selection_init(xwm);

	xwm->compositor_new_surface.notify = handle_compositor_new_surface;
	wl_signal_add(&wlr_xwayland->compositor->events.new_surface,
		&xwm->compositor_new_surface);
	xwm->compositor_destroy.notify = handle_compositor_destroy;
	wl_signal_add(&wlr_xwayland->compositor->events.destroy,
		&xwm->compositor_destroy);

	xwm_create_wm_window(xwm);

	xcb_flush(xwm->xcb_conn);

	return xwm;
}

void wlr_xwayland_surface_set_maximized(struct wlr_xwayland_surface *surface,
		bool maximized) {
	surface->maximized_horz = maximized;
	surface->maximized_vert = maximized;
	xsurface_set_net_wm_state(surface);
	xcb_flush(surface->xwm->xcb_conn);
}

void wlr_xwayland_surface_set_fullscreen(struct wlr_xwayland_surface *surface,
		bool fullscreen) {
	surface->fullscreen = fullscreen;
	xsurface_set_net_wm_state(surface);
	xcb_flush(surface->xwm->xcb_conn);
}

bool xwm_atoms_contains(struct wlr_xwm *xwm, xcb_atom_t *atoms,
		size_t num_atoms, enum atom_name needle) {
	xcb_atom_t atom = xwm->atoms[needle];

	for (size_t i = 0; i < num_atoms; ++i) {
		if (atom == atoms[i]) {
			return true;
		}
	}

	return false;
}