summaryrefslogtreecommitdiff
path: root/clients/window.c
blob: 1700cf9e23b85ecfee18baccd5b88443f001871c (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
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
/*
 * Copyright © 2008 Kristian Høgsberg
 * Copyright © 2012-2013 Collabora, Ltd.
 *
 * Permission to use, copy, modify, distribute, and sell this software and its
 * documentation for any purpose is hereby granted without fee, provided that
 * the above copyright notice appear in all copies and that both that copyright
 * notice and this permission notice appear in supporting documentation, and
 * that the name of the copyright holders not be used in advertising or
 * publicity pertaining to distribution of the software without specific,
 * written prior permission.  The copyright holders make no representations
 * about the suitability of this software for any purpose.  It is provided "as
 * is" without express or implied warranty.
 *
 * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
 * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, 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 "config.h"

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <math.h>
#include <assert.h>
#include <time.h>
#include <cairo.h>
#include <sys/mman.h>
#include <sys/epoll.h>
#include <sys/timerfd.h>

#ifdef HAVE_CAIRO_EGL
#include <wayland-egl.h>

#ifdef USE_CAIRO_GLESV2
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#else
#include <GL/gl.h>
#endif
#include <EGL/egl.h>
#include <EGL/eglext.h>

#include <cairo-gl.h>
#else /* HAVE_CAIRO_EGL */
typedef void *EGLDisplay;
typedef void *EGLConfig;
typedef void *EGLContext;
#define EGL_NO_DISPLAY ((EGLDisplay)0)
#endif /* no HAVE_CAIRO_EGL */

#include <xkbcommon/xkbcommon.h>
#include <wayland-cursor.h>

#include <linux/input.h>
#include <wayland-client.h>
#include "../shared/cairo-util.h"
#include "xdg-shell-client-protocol.h"
#include "text-cursor-position-client-protocol.h"
#include "workspaces-client-protocol.h"
#include "../shared/os-compatibility.h"

#include "window.h"

struct shm_pool;

struct global {
	uint32_t name;
	char *interface;
	uint32_t version;
	struct wl_list link;
};

struct display {
	struct wl_display *display;
	struct wl_registry *registry;
	struct wl_compositor *compositor;
	struct wl_subcompositor *subcompositor;
	struct wl_shm *shm;
	struct wl_data_device_manager *data_device_manager;
	struct text_cursor_position *text_cursor_position;
	struct workspace_manager *workspace_manager;
	struct xdg_shell *xdg_shell;
	EGLDisplay dpy;
	EGLConfig argb_config;
	EGLContext argb_ctx;
	cairo_device_t *argb_device;
	uint32_t serial;

	int display_fd;
	uint32_t display_fd_events;
	struct task display_task;

	int epoll_fd;
	struct wl_list deferred_list;

	int running;

	struct wl_list global_list;
	struct wl_list window_list;
	struct wl_list input_list;
	struct wl_list output_list;

	struct theme *theme;

	struct wl_cursor_theme *cursor_theme;
	struct wl_cursor **cursors;

	display_output_handler_t output_configure_handler;
	display_global_handler_t global_handler;
	display_global_handler_t global_handler_remove;

	void *user_data;

	struct xkb_context *xkb_context;

	uint32_t workspace;
	uint32_t workspace_count;

	/* A hack to get text extents for tooltips */
	cairo_surface_t *dummy_surface;
	void *dummy_surface_data;

	int has_rgb565;
	int seat_version;
};

struct window_output {
	struct output *output;
	struct wl_list link;
};

struct toysurface {
	/*
	 * Prepare the surface for drawing. Makes sure there is a surface
	 * of the right size available for rendering, and returns it.
	 * dx,dy are the x,y of wl_surface.attach.
	 * width,height are the new buffer size.
	 * If flags has SURFACE_HINT_RESIZE set, the user is
	 * doing continuous resizing.
	 * Returns the Cairo surface to draw to.
	 */
	cairo_surface_t *(*prepare)(struct toysurface *base, int dx, int dy,
				    int32_t width, int32_t height, uint32_t flags,
				    enum wl_output_transform buffer_transform, int32_t buffer_scale);

	/*
	 * Post the surface to the server, returning the server allocation
	 * rectangle. The Cairo surface from prepare() must be destroyed
	 * after calling this.
	 */
	void (*swap)(struct toysurface *base,
		     enum wl_output_transform buffer_transform, int32_t buffer_scale,
		     struct rectangle *server_allocation);

	/*
	 * Make the toysurface current with the given EGL context.
	 * Returns 0 on success, and negative of failure.
	 */
	int (*acquire)(struct toysurface *base, EGLContext ctx);

	/*
	 * Release the toysurface from the EGL context, returning control
	 * to Cairo.
	 */
	void (*release)(struct toysurface *base);

	/*
	 * Destroy the toysurface, including the Cairo surface, any
	 * backing storage, and the Wayland protocol objects.
	 */
	void (*destroy)(struct toysurface *base);
};

struct surface {
	struct window *window;

	struct wl_surface *surface;
	struct wl_subsurface *subsurface;
	int synchronized;
	int synchronized_default;
	struct toysurface *toysurface;
	struct widget *widget;
	int redraw_needed;
	struct wl_callback *frame_cb;
	uint32_t last_time;

	struct rectangle allocation;
	struct rectangle server_allocation;

	struct wl_region *input_region;
	struct wl_region *opaque_region;

	enum window_buffer_type buffer_type;
	enum wl_output_transform buffer_transform;
	int32_t buffer_scale;

	cairo_surface_t *cairo_surface;

	struct wl_list link;
};

struct window {
	struct display *display;
	struct wl_list window_output_list;
	char *title;
	struct rectangle saved_allocation;
	struct rectangle min_allocation;
	struct rectangle pending_allocation;
	int x, y;
	int redraw_needed;
	int redraw_task_scheduled;
	struct task redraw_task;
	int resize_needed;
	int custom;
	int focused;

	int resizing;

	int fullscreen;
	int maximized;

	enum preferred_format preferred_format;

	window_key_handler_t key_handler;
	window_keyboard_focus_handler_t keyboard_focus_handler;
	window_data_handler_t data_handler;
	window_drop_handler_t drop_handler;
	window_close_handler_t close_handler;
	window_fullscreen_handler_t fullscreen_handler;
	window_output_handler_t output_handler;
	window_state_changed_handler_t state_changed_handler;

	struct surface *main_surface;
	struct xdg_surface *xdg_surface;
	struct xdg_popup *xdg_popup;

	struct window *parent;

	struct window_frame *frame;

	/* struct surface::link, contains also main_surface */
	struct wl_list subsurface_list;

	void *user_data;
	struct wl_list link;
};

struct widget {
	struct window *window;
	struct surface *surface;
	struct tooltip *tooltip;
	struct wl_list child_list;
	struct wl_list link;
	struct rectangle allocation;
	widget_resize_handler_t resize_handler;
	widget_redraw_handler_t redraw_handler;
	widget_enter_handler_t enter_handler;
	widget_leave_handler_t leave_handler;
	widget_motion_handler_t motion_handler;
	widget_button_handler_t button_handler;
	widget_touch_down_handler_t touch_down_handler;
	widget_touch_up_handler_t touch_up_handler;
	widget_touch_motion_handler_t touch_motion_handler;
	widget_touch_frame_handler_t touch_frame_handler;
	widget_touch_cancel_handler_t touch_cancel_handler;
	widget_axis_handler_t axis_handler;
	void *user_data;
	int opaque;
	int tooltip_count;
	int default_cursor;
	/* If this is set to false then no cairo surface will be
	 * created before redrawing the surface. This is useful if the
	 * redraw handler is going to do completely custom rendering
	 * such as using EGL directly */
	int use_cairo;
};

struct touch_point {
	int32_t id;
	float x, y;
	struct widget *widget;
	struct wl_list link;
};

struct input {
	struct display *display;
	struct wl_seat *seat;
	struct wl_pointer *pointer;
	struct wl_keyboard *keyboard;
	struct wl_touch *touch;
	struct wl_list touch_point_list;
	struct window *pointer_focus;
	struct window *keyboard_focus;
	struct window *touch_focus;
	int current_cursor;
	uint32_t cursor_anim_start;
	struct wl_callback *cursor_frame_cb;
	struct wl_surface *pointer_surface;
	uint32_t modifiers;
	uint32_t pointer_enter_serial;
	uint32_t cursor_serial;
	float sx, sy;
	struct wl_list link;

	struct widget *focus_widget;
	struct widget *grab;
	uint32_t grab_button;

	struct wl_data_device *data_device;
	struct data_offer *drag_offer;
	struct data_offer *selection_offer;
	uint32_t touch_grab;
	int32_t touch_grab_id;
	float drag_x, drag_y;
	struct window *drag_focus;
	uint32_t drag_enter_serial;

	struct {
		struct xkb_keymap *keymap;
		struct xkb_state *state;
		xkb_mod_mask_t control_mask;
		xkb_mod_mask_t alt_mask;
		xkb_mod_mask_t shift_mask;
	} xkb;

	struct task repeat_task;
	int repeat_timer_fd;
	uint32_t repeat_sym;
	uint32_t repeat_key;
	uint32_t repeat_time;
};

struct output {
	struct display *display;
	struct wl_output *output;
	uint32_t server_output_id;
	struct rectangle allocation;
	struct wl_list link;
	int transform;
	int scale;
	char *make;
	char *model;

	display_output_handler_t destroy_handler;
	void *user_data;
};

struct window_frame {
	struct widget *widget;
	struct widget *child;
	struct frame *frame;
};

struct menu {
	void *user_data;
	struct window *window;
	struct widget *widget;
	struct input *input;
	struct frame *frame;
	const char **entries;
	uint32_t time;
	int current;
	int count;
	int release_count;
	menu_func_t func;
};

struct tooltip {
	struct widget *parent;
	struct widget *widget;
	char *entry;
	struct task tooltip_task;
	int tooltip_fd;
	float x, y;
};

struct shm_pool {
	struct wl_shm_pool *pool;
	size_t size;
	size_t used;
	void *data;
};

enum {
	CURSOR_DEFAULT = 100,
	CURSOR_UNSET
};

static const cairo_user_data_key_t shm_surface_data_key;

/* #define DEBUG */

#ifdef DEBUG

static void
debug_print(void *proxy, int line, const char *func, const char *fmt, ...)
__attribute__ ((format (printf, 4, 5)));

static void
debug_print(void *proxy, int line, const char *func, const char *fmt, ...)
{
	va_list ap;
	struct timeval tv;

	gettimeofday(&tv, NULL);
	fprintf(stderr, "%8ld.%03ld ",
		(long)tv.tv_sec & 0xffff, (long)tv.tv_usec / 1000);

	if (proxy)
		fprintf(stderr, "%s@%d ",
			wl_proxy_get_class(proxy), wl_proxy_get_id(proxy));

	/*fprintf(stderr, __FILE__ ":%d:%s ", line, func);*/
	fprintf(stderr, "%s ", func);

	va_start(ap, fmt);
	vfprintf(stderr, fmt, ap);
	va_end(ap);
}

#define DBG(fmt, ...) \
	debug_print(NULL, __LINE__, __func__, fmt, ##__VA_ARGS__)

#define DBG_OBJ(obj, fmt, ...) \
	debug_print(obj, __LINE__, __func__, fmt, ##__VA_ARGS__)

#else

#define DBG(...) do {} while (0)
#define DBG_OBJ(...) do {} while (0)

#endif

static void
surface_to_buffer_size (enum wl_output_transform buffer_transform, int32_t buffer_scale, int32_t *width, int32_t *height)
{
	int32_t tmp;

	switch (buffer_transform) {
	case WL_OUTPUT_TRANSFORM_90:
	case WL_OUTPUT_TRANSFORM_270:
	case WL_OUTPUT_TRANSFORM_FLIPPED_90:
	case WL_OUTPUT_TRANSFORM_FLIPPED_270:
		tmp = *width;
		*width = *height;
		*height = tmp;
		break;
	default:
		break;
	}

	*width *= buffer_scale;
	*height *= buffer_scale;
}

static void
buffer_to_surface_size (enum wl_output_transform buffer_transform, int32_t buffer_scale, int32_t *width, int32_t *height)
{
	int32_t tmp;

	switch (buffer_transform) {
	case WL_OUTPUT_TRANSFORM_90:
	case WL_OUTPUT_TRANSFORM_270:
	case WL_OUTPUT_TRANSFORM_FLIPPED_90:
	case WL_OUTPUT_TRANSFORM_FLIPPED_270:
		tmp = *width;
		*width = *height;
		*height = tmp;
		break;
	default:
		break;
	}

	*width /= buffer_scale;
	*height /= buffer_scale;
}

#ifdef HAVE_CAIRO_EGL

struct egl_window_surface {
	struct toysurface base;
	cairo_surface_t *cairo_surface;
	struct display *display;
	struct wl_surface *surface;
	struct wl_egl_window *egl_window;
	EGLSurface egl_surface;
};

static struct egl_window_surface *
to_egl_window_surface(struct toysurface *base)
{
	return container_of(base, struct egl_window_surface, base);
}

static cairo_surface_t *
egl_window_surface_prepare(struct toysurface *base, int dx, int dy,
			   int32_t width, int32_t height, uint32_t flags,
			   enum wl_output_transform buffer_transform, int32_t buffer_scale)
{
	struct egl_window_surface *surface = to_egl_window_surface(base);

	surface_to_buffer_size (buffer_transform, buffer_scale, &width, &height);

	wl_egl_window_resize(surface->egl_window, width, height, dx, dy);
	cairo_gl_surface_set_size(surface->cairo_surface, width, height);

	return cairo_surface_reference(surface->cairo_surface);
}

static void
egl_window_surface_swap(struct toysurface *base,
			enum wl_output_transform buffer_transform, int32_t buffer_scale,
			struct rectangle *server_allocation)
{
	struct egl_window_surface *surface = to_egl_window_surface(base);

	cairo_gl_surface_swapbuffers(surface->cairo_surface);
	wl_egl_window_get_attached_size(surface->egl_window,
					&server_allocation->width,
					&server_allocation->height);

	buffer_to_surface_size (buffer_transform, buffer_scale,
				&server_allocation->width,
				&server_allocation->height);
}

static int
egl_window_surface_acquire(struct toysurface *base, EGLContext ctx)
{
	struct egl_window_surface *surface = to_egl_window_surface(base);
	cairo_device_t *device;

	device = cairo_surface_get_device(surface->cairo_surface);
	if (!device)
		return -1;

	if (!ctx) {
		if (device == surface->display->argb_device)
			ctx = surface->display->argb_ctx;
		else
			assert(0);
	}

	cairo_device_flush(device);
	cairo_device_acquire(device);
	if (!eglMakeCurrent(surface->display->dpy, surface->egl_surface,
			    surface->egl_surface, ctx))
		fprintf(stderr, "failed to make surface current\n");

	return 0;
}

static void
egl_window_surface_release(struct toysurface *base)
{
	struct egl_window_surface *surface = to_egl_window_surface(base);
	cairo_device_t *device;

	device = cairo_surface_get_device(surface->cairo_surface);
	if (!device)
		return;

	if (!eglMakeCurrent(surface->display->dpy, NULL, NULL,
			    surface->display->argb_ctx))
		fprintf(stderr, "failed to make context current\n");

	cairo_device_release(device);
}

static void
egl_window_surface_destroy(struct toysurface *base)
{
	struct egl_window_surface *surface = to_egl_window_surface(base);
	struct display *d = surface->display;

	cairo_surface_destroy(surface->cairo_surface);
	eglDestroySurface(d->dpy, surface->egl_surface);
	wl_egl_window_destroy(surface->egl_window);
	surface->surface = NULL;

	free(surface);
}

static struct toysurface *
egl_window_surface_create(struct display *display,
			  struct wl_surface *wl_surface,
			  uint32_t flags,
			  struct rectangle *rectangle)
{
	struct egl_window_surface *surface;

	if (display->dpy == EGL_NO_DISPLAY)
		return NULL;

	surface = calloc(1, sizeof *surface);
	if (!surface)
		return NULL;

	surface->base.prepare = egl_window_surface_prepare;
	surface->base.swap = egl_window_surface_swap;
	surface->base.acquire = egl_window_surface_acquire;
	surface->base.release = egl_window_surface_release;
	surface->base.destroy = egl_window_surface_destroy;

	surface->display = display;
	surface->surface = wl_surface;

	surface->egl_window = wl_egl_window_create(surface->surface,
						   rectangle->width,
						   rectangle->height);

	surface->egl_surface = eglCreateWindowSurface(display->dpy,
						      display->argb_config,
						      surface->egl_window,
						      NULL);

	surface->cairo_surface =
		cairo_gl_surface_create_for_egl(display->argb_device,
						surface->egl_surface,
						rectangle->width,
						rectangle->height);

	return &surface->base;
}

#else

static struct toysurface *
egl_window_surface_create(struct display *display,
			  struct wl_surface *wl_surface,
			  uint32_t flags,
			  struct rectangle *rectangle)
{
	return NULL;
}

#endif

struct shm_surface_data {
	struct wl_buffer *buffer;
	struct shm_pool *pool;
};

struct wl_buffer *
display_get_buffer_for_surface(struct display *display,
			       cairo_surface_t *surface)
{
	struct shm_surface_data *data;

	data = cairo_surface_get_user_data(surface, &shm_surface_data_key);

	return data->buffer;
}

static void
shm_pool_destroy(struct shm_pool *pool);

static void
shm_surface_data_destroy(void *p)
{
	struct shm_surface_data *data = p;

	wl_buffer_destroy(data->buffer);
	if (data->pool)
		shm_pool_destroy(data->pool);

	free(data);
}

static struct wl_shm_pool *
make_shm_pool(struct display *display, int size, void **data)
{
	struct wl_shm_pool *pool;
	int fd;

	fd = os_create_anonymous_file(size);
	if (fd < 0) {
		fprintf(stderr, "creating a buffer file for %d B failed: %m\n",
			size);
		return NULL;
	}

	*data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
	if (*data == MAP_FAILED) {
		fprintf(stderr, "mmap failed: %m\n");
		close(fd);
		return NULL;
	}

	pool = wl_shm_create_pool(display->shm, fd, size);

	close(fd);

	return pool;
}

static struct shm_pool *
shm_pool_create(struct display *display, size_t size)
{
	struct shm_pool *pool = malloc(sizeof *pool);

	if (!pool)
		return NULL;

	pool->pool = make_shm_pool(display, size, &pool->data);
	if (!pool->pool) {
		free(pool);
		return NULL;
	}

	pool->size = size;
	pool->used = 0;

	return pool;
}

static void *
shm_pool_allocate(struct shm_pool *pool, size_t size, int *offset)
{
	if (pool->used + size > pool->size)
		return NULL;

	*offset = pool->used;
	pool->used += size;

	return (char *) pool->data + *offset;
}

/* destroy the pool. this does not unmap the memory though */
static void
shm_pool_destroy(struct shm_pool *pool)
{
	munmap(pool->data, pool->size);
	wl_shm_pool_destroy(pool->pool);
	free(pool);
}

/* Start allocating from the beginning of the pool again */
static void
shm_pool_reset(struct shm_pool *pool)
{
	pool->used = 0;
}

static int
data_length_for_shm_surface(struct rectangle *rect)
{
	int stride;

	stride = cairo_format_stride_for_width (CAIRO_FORMAT_ARGB32,
						rect->width);
	return stride * rect->height;
}

static cairo_surface_t *
display_create_shm_surface_from_pool(struct display *display,
				     struct rectangle *rectangle,
				     uint32_t flags, struct shm_pool *pool)
{
	struct shm_surface_data *data;
	uint32_t format;
	cairo_surface_t *surface;
	cairo_format_t cairo_format;
	int stride, length, offset;
	void *map;

	data = malloc(sizeof *data);
	if (data == NULL)
		return NULL;

	if (flags & SURFACE_HINT_RGB565 && display->has_rgb565)
		cairo_format = CAIRO_FORMAT_RGB16_565;
	else
		cairo_format = CAIRO_FORMAT_ARGB32;

	stride = cairo_format_stride_for_width (cairo_format, rectangle->width);
	length = stride * rectangle->height;
	data->pool = NULL;
	map = shm_pool_allocate(pool, length, &offset);

	if (!map) {
		free(data);
		return NULL;
	}

	surface = cairo_image_surface_create_for_data (map,
						       cairo_format,
						       rectangle->width,
						       rectangle->height,
						       stride);

	cairo_surface_set_user_data(surface, &shm_surface_data_key,
				    data, shm_surface_data_destroy);

	if (flags & SURFACE_HINT_RGB565 && display->has_rgb565)
		format = WL_SHM_FORMAT_RGB565;
	else {
		if (flags & SURFACE_OPAQUE)
			format = WL_SHM_FORMAT_XRGB8888;
		else
			format = WL_SHM_FORMAT_ARGB8888;
	}

	data->buffer = wl_shm_pool_create_buffer(pool->pool, offset,
						 rectangle->width,
						 rectangle->height,
						 stride, format);

	return surface;
}

static cairo_surface_t *
display_create_shm_surface(struct display *display,
			   struct rectangle *rectangle, uint32_t flags,
			   struct shm_pool *alternate_pool,
			   struct shm_surface_data **data_ret)
{
	struct shm_surface_data *data;
	struct shm_pool *pool;
	cairo_surface_t *surface;

	if (alternate_pool) {
		shm_pool_reset(alternate_pool);
		surface = display_create_shm_surface_from_pool(display,
							       rectangle,
							       flags,
							       alternate_pool);
		if (surface) {
			data = cairo_surface_get_user_data(surface,
							   &shm_surface_data_key);
			goto out;
		}
	}

	pool = shm_pool_create(display,
			       data_length_for_shm_surface(rectangle));
	if (!pool)
		return NULL;

	surface =
		display_create_shm_surface_from_pool(display, rectangle,
						     flags, pool);

	if (!surface) {
		shm_pool_destroy(pool);
		return NULL;
	}

	/* make sure we destroy the pool when the surface is destroyed */
	data = cairo_surface_get_user_data(surface, &shm_surface_data_key);
	data->pool = pool;

out:
	if (data_ret)
		*data_ret = data;

	return surface;
}

static int
check_size(struct rectangle *rect)
{
	if (rect->width && rect->height)
		return 0;

	fprintf(stderr, "tried to create surface of "
		"width: %d, height: %d\n", rect->width, rect->height);
	return -1;
}

cairo_surface_t *
display_create_surface(struct display *display,
		       struct wl_surface *surface,
		       struct rectangle *rectangle,
		       uint32_t flags)
{
	if (check_size(rectangle) < 0)
		return NULL;

	assert(flags & SURFACE_SHM);
	return display_create_shm_surface(display, rectangle, flags,
					  NULL, NULL);
}

struct shm_surface_leaf {
	cairo_surface_t *cairo_surface;
	/* 'data' is automatically destroyed, when 'cairo_surface' is */
	struct shm_surface_data *data;

	struct shm_pool *resize_pool;
	int busy;
};

static void
shm_surface_leaf_release(struct shm_surface_leaf *leaf)
{
	if (leaf->cairo_surface)
		cairo_surface_destroy(leaf->cairo_surface);
	/* leaf->data already destroyed via cairo private */

	if (leaf->resize_pool)
		shm_pool_destroy(leaf->resize_pool);

	memset(leaf, 0, sizeof *leaf);
}

#define MAX_LEAVES 3

struct shm_surface {
	struct toysurface base;
	struct display *display;
	struct wl_surface *surface;
	uint32_t flags;
	int dx, dy;

	struct shm_surface_leaf leaf[MAX_LEAVES];
	struct shm_surface_leaf *current;
};

static struct shm_surface *
to_shm_surface(struct toysurface *base)
{
	return container_of(base, struct shm_surface, base);
}

static void
shm_surface_buffer_state_debug(struct shm_surface *surface, const char *msg)
{
#ifdef DEBUG
	struct shm_surface_leaf *leaf;
	char bufs[MAX_LEAVES + 1];
	int i;

	for (i = 0; i < MAX_LEAVES; i++) {
		leaf = &surface->leaf[i];

		if (leaf->busy)
			bufs[i] = 'b';
		else if (leaf->cairo_surface)
			bufs[i] = 'a';
		else
			bufs[i] = ' ';
	}

	bufs[MAX_LEAVES] = '\0';
	DBG_OBJ(surface->surface, "%s, leaves [%s]\n", msg, bufs);
#endif
}

static void
shm_surface_buffer_release(void *data, struct wl_buffer *buffer)
{
	struct shm_surface *surface = data;
	struct shm_surface_leaf *leaf;
	int i;
	int free_found;

	shm_surface_buffer_state_debug(surface, "buffer_release before");

	for (i = 0; i < MAX_LEAVES; i++) {
		leaf = &surface->leaf[i];
		if (leaf->data && leaf->data->buffer == buffer) {
			leaf->busy = 0;
			break;
		}
	}
	assert(i < MAX_LEAVES && "unknown buffer released");

	/* Leave one free leaf with storage, release others */
	free_found = 0;
	for (i = 0; i < MAX_LEAVES; i++) {
		leaf = &surface->leaf[i];

		if (!leaf->cairo_surface || leaf->busy)
			continue;

		if (!free_found)
			free_found = 1;
		else
			shm_surface_leaf_release(leaf);
	}

	shm_surface_buffer_state_debug(surface, "buffer_release  after");
}

static const struct wl_buffer_listener shm_surface_buffer_listener = {
	shm_surface_buffer_release
};

static cairo_surface_t *
shm_surface_prepare(struct toysurface *base, int dx, int dy,
		    int32_t width, int32_t height, uint32_t flags,
		    enum wl_output_transform buffer_transform, int32_t buffer_scale)
{
	int resize_hint = !!(flags & SURFACE_HINT_RESIZE);
	struct shm_surface *surface = to_shm_surface(base);
	struct rectangle rect = { 0};
	struct shm_surface_leaf *leaf = NULL;
	int i;

	surface->dx = dx;
	surface->dy = dy;

	/* pick a free buffer, preferrably one that already has storage */
	for (i = 0; i < MAX_LEAVES; i++) {
		if (surface->leaf[i].busy)
			continue;

		if (!leaf || surface->leaf[i].cairo_surface)
			leaf = &surface->leaf[i];
	}
	DBG_OBJ(surface->surface, "pick leaf %d\n",
		(int)(leaf - &surface->leaf[0]));

	if (!leaf) {
		fprintf(stderr, "%s: all buffers are held by the server.\n",
			__func__);
		exit(1);
		return NULL;
	}

	if (!resize_hint && leaf->resize_pool) {
		cairo_surface_destroy(leaf->cairo_surface);
		leaf->cairo_surface = NULL;
		shm_pool_destroy(leaf->resize_pool);
		leaf->resize_pool = NULL;
	}

	surface_to_buffer_size (buffer_transform, buffer_scale, &width, &height);

	if (leaf->cairo_surface &&
	    cairo_image_surface_get_width(leaf->cairo_surface) == width &&
	    cairo_image_surface_get_height(leaf->cairo_surface) == height)
		goto out;

	if (leaf->cairo_surface)
		cairo_surface_destroy(leaf->cairo_surface);

#ifdef USE_RESIZE_POOL
	if (resize_hint && !leaf->resize_pool) {
		/* Create a big pool to allocate from, while continuously
		 * resizing. Mmapping a new pool in the server
		 * is relatively expensive, so reusing a pool performs
		 * better, but may temporarily reserve unneeded memory.
		 */
		/* We should probably base this number on the output size. */
		leaf->resize_pool = shm_pool_create(surface->display,
						    6 * 1024 * 1024);
	}
#endif

	rect.width = width;
	rect.height = height;

	leaf->cairo_surface =
		display_create_shm_surface(surface->display, &rect,
					   surface->flags,
					   leaf->resize_pool,
					   &leaf->data);
	if (!leaf->cairo_surface)
		return NULL;

	wl_buffer_add_listener(leaf->data->buffer,
			       &shm_surface_buffer_listener, surface);

out:
	surface->current = leaf;

	return cairo_surface_reference(leaf->cairo_surface);
}

static void
shm_surface_swap(struct toysurface *base,
		 enum wl_output_transform buffer_transform, int32_t buffer_scale,
		 struct rectangle *server_allocation)
{
	struct shm_surface *surface = to_shm_surface(base);
	struct shm_surface_leaf *leaf = surface->current;

	server_allocation->width =
		cairo_image_surface_get_width(leaf->cairo_surface);
	server_allocation->height =
		cairo_image_surface_get_height(leaf->cairo_surface);

	buffer_to_surface_size (buffer_transform, buffer_scale,
				&server_allocation->width,
				&server_allocation->height);

	wl_surface_attach(surface->surface, leaf->data->buffer,
			  surface->dx, surface->dy);
	wl_surface_damage(surface->surface, 0, 0,
			  server_allocation->width, server_allocation->height);
	wl_surface_commit(surface->surface);

	DBG_OBJ(surface->surface, "leaf %d busy\n",
		(int)(leaf - &surface->leaf[0]));

	leaf->busy = 1;
	surface->current = NULL;
}

static int
shm_surface_acquire(struct toysurface *base, EGLContext ctx)
{
	return -1;
}

static void
shm_surface_release(struct toysurface *base)
{
}

static void
shm_surface_destroy(struct toysurface *base)
{
	struct shm_surface *surface = to_shm_surface(base);
	int i;

	for (i = 0; i < MAX_LEAVES; i++)
		shm_surface_leaf_release(&surface->leaf[i]);

	free(surface);
}

static struct toysurface *
shm_surface_create(struct display *display, struct wl_surface *wl_surface,
		   uint32_t flags, struct rectangle *rectangle)
{
	struct shm_surface *surface;
	DBG_OBJ(wl_surface, "\n");

	surface = xmalloc(sizeof *surface);
	memset(surface, 0, sizeof *surface);

	if (!surface)
		return NULL;

	surface->base.prepare = shm_surface_prepare;
	surface->base.swap = shm_surface_swap;
	surface->base.acquire = shm_surface_acquire;
	surface->base.release = shm_surface_release;
	surface->base.destroy = shm_surface_destroy;

	surface->display = display;
	surface->surface = wl_surface;
	surface->flags = flags;

	return &surface->base;
}

/*
 * The following correspondences between file names and cursors was copied
 * from: https://bugs.kde.org/attachment.cgi?id=67313
 */

static const char *bottom_left_corners[] = {
	"bottom_left_corner",
	"sw-resize",
	"size_bdiag"
};

static const char *bottom_right_corners[] = {
	"bottom_right_corner",
	"se-resize",
	"size_fdiag"
};

static const char *bottom_sides[] = {
	"bottom_side",
	"s-resize",
	"size_ver"
};

static const char *grabbings[] = {
	"grabbing",
	"closedhand",
	"208530c400c041818281048008011002"
};

static const char *left_ptrs[] = {
	"left_ptr",
	"default",
	"top_left_arrow",
	"left-arrow"
};

static const char *left_sides[] = {
	"left_side",
	"w-resize",
	"size_hor"
};

static const char *right_sides[] = {
	"right_side",
	"e-resize",
	"size_hor"
};

static const char *top_left_corners[] = {
	"top_left_corner",
	"nw-resize",
	"size_fdiag"
};

static const char *top_right_corners[] = {
	"top_right_corner",
	"ne-resize",
	"size_bdiag"
};

static const char *top_sides[] = {
	"top_side",
	"n-resize",
	"size_ver"
};

static const char *xterms[] = {
	"xterm",
	"ibeam",
	"text"
};

static const char *hand1s[] = {
	"hand1",
	"pointer",
	"pointing_hand",
	"e29285e634086352946a0e7090d73106"
};

static const char *watches[] = {
	"watch",
	"wait",
	"0426c94ea35c87780ff01dc239897213"
};

struct cursor_alternatives {
	const char **names;
	size_t count;
};

static const struct cursor_alternatives cursors[] = {
	{bottom_left_corners, ARRAY_LENGTH(bottom_left_corners)},
	{bottom_right_corners, ARRAY_LENGTH(bottom_right_corners)},
	{bottom_sides, ARRAY_LENGTH(bottom_sides)},
	{grabbings, ARRAY_LENGTH(grabbings)},
	{left_ptrs, ARRAY_LENGTH(left_ptrs)},
	{left_sides, ARRAY_LENGTH(left_sides)},
	{right_sides, ARRAY_LENGTH(right_sides)},
	{top_left_corners, ARRAY_LENGTH(top_left_corners)},
	{top_right_corners, ARRAY_LENGTH(top_right_corners)},
	{top_sides, ARRAY_LENGTH(top_sides)},
	{xterms, ARRAY_LENGTH(xterms)},
	{hand1s, ARRAY_LENGTH(hand1s)},
	{watches, ARRAY_LENGTH(watches)},
};

static void
create_cursors(struct display *display)
{
	struct weston_config *config;
	struct weston_config_section *s;
	int size;
	char *theme = NULL;
	unsigned int i, j;
	struct wl_cursor *cursor;

	config = weston_config_parse("weston.ini");
	s = weston_config_get_section(config, "shell", NULL, NULL);
	weston_config_section_get_string(s, "cursor-theme", &theme, NULL);
	weston_config_section_get_int(s, "cursor-size", &size, 32);
	weston_config_destroy(config);

	display->cursor_theme = wl_cursor_theme_load(theme, size, display->shm);
	if (!display->cursor_theme) {
		fprintf(stderr, "could not load theme '%s'\n", theme);
		return;
	}
	free(theme);
	display->cursors =
		xmalloc(ARRAY_LENGTH(cursors) * sizeof display->cursors[0]);

	for (i = 0; i < ARRAY_LENGTH(cursors); i++) {
		cursor = NULL;
		for (j = 0; !cursor && j < cursors[i].count; ++j)
			cursor = wl_cursor_theme_get_cursor(
			    display->cursor_theme, cursors[i].names[j]);

		if (!cursor)
			fprintf(stderr, "could not load cursor '%s'\n",
				cursors[i].names[0]);

		display->cursors[i] = cursor;
	}
}

static void
destroy_cursors(struct display *display)
{
	wl_cursor_theme_destroy(display->cursor_theme);
	free(display->cursors);
}

struct wl_cursor_image *
display_get_pointer_image(struct display *display, int pointer)
{
	struct wl_cursor *cursor = display->cursors[pointer];

	return cursor ? cursor->images[0] : NULL;
}

static void
surface_flush(struct surface *surface)
{
	if (!surface->cairo_surface)
		return;

	if (surface->opaque_region) {
		wl_surface_set_opaque_region(surface->surface,
					     surface->opaque_region);
		wl_region_destroy(surface->opaque_region);
		surface->opaque_region = NULL;
	}

	if (surface->input_region) {
		wl_surface_set_input_region(surface->surface,
					    surface->input_region);
		wl_region_destroy(surface->input_region);
		surface->input_region = NULL;
	}

	surface->toysurface->swap(surface->toysurface,
				  surface->buffer_transform, surface->buffer_scale,
				  &surface->server_allocation);

	cairo_surface_destroy(surface->cairo_surface);
	surface->cairo_surface = NULL;
}

int
window_has_focus(struct window *window)
{
	return window->focused;
}

static void
window_close(struct window *window)
{
	if (window->close_handler)
		window->close_handler(window->user_data);
	else
		display_exit(window->display);
}

struct display *
window_get_display(struct window *window)
{
	return window->display;
}

static void
surface_create_surface(struct surface *surface, uint32_t flags)
{
	struct display *display = surface->window->display;
	struct rectangle allocation = surface->allocation;

	if (!surface->toysurface && display->dpy &&
	    surface->buffer_type == WINDOW_BUFFER_TYPE_EGL_WINDOW) {
		surface->toysurface =
			egl_window_surface_create(display,
						  surface->surface,
						  flags,
						  &allocation);
	}

	if (!surface->toysurface)
		surface->toysurface = shm_surface_create(display,
							 surface->surface,
							 flags, &allocation);

	surface->cairo_surface = surface->toysurface->prepare(
		surface->toysurface, 0, 0,
		allocation.width, allocation.height, flags,
		surface->buffer_transform, surface->buffer_scale);
}

static void
window_create_main_surface(struct window *window)
{
	struct surface *surface = window->main_surface;
	uint32_t flags = 0;

	if (window->resizing)
		flags |= SURFACE_HINT_RESIZE;

	if (window->preferred_format == WINDOW_PREFERRED_FORMAT_RGB565)
		flags |= SURFACE_HINT_RGB565;

	surface_create_surface(surface, flags);
}

int
window_get_buffer_transform(struct window *window)
{
	return window->main_surface->buffer_transform;
}

void
window_set_buffer_transform(struct window *window,
			    enum wl_output_transform transform)
{
	window->main_surface->buffer_transform = transform;
	wl_surface_set_buffer_transform(window->main_surface->surface,
					transform);
}

void
window_set_buffer_scale(struct window *window,
			int32_t scale)
{
	window->main_surface->buffer_scale = scale;
	wl_surface_set_buffer_scale(window->main_surface->surface,
				    scale);
}

uint32_t
window_get_buffer_scale(struct window *window)
{
	return window->main_surface->buffer_scale;
}

uint32_t
window_get_output_scale(struct window *window)
{
	struct window_output *window_output;
	struct window_output *window_output_tmp;
	int scale = 1;

	wl_list_for_each_safe(window_output, window_output_tmp,
			      &window->window_output_list, link) {
		if (window_output->output->scale > scale)
			scale = window_output->output->scale;
	}

	return scale;
}

static void window_frame_destroy(struct window_frame *frame);

static void
surface_destroy(struct surface *surface)
{
	if (surface->frame_cb)
		wl_callback_destroy(surface->frame_cb);

	if (surface->input_region)
		wl_region_destroy(surface->input_region);

	if (surface->opaque_region)
		wl_region_destroy(surface->opaque_region);

	if (surface->subsurface)
		wl_subsurface_destroy(surface->subsurface);

	wl_surface_destroy(surface->surface);

	if (surface->toysurface)
		surface->toysurface->destroy(surface->toysurface);

	wl_list_remove(&surface->link);
	free(surface);
}

void
window_destroy(struct window *window)
{
	struct display *display = window->display;
	struct input *input;
	struct window_output *window_output;
	struct window_output *window_output_tmp;

	wl_list_remove(&window->redraw_task.link);

	wl_list_for_each(input, &display->input_list, link) {	  
		if (input->touch_focus == window)
			input->touch_focus = NULL;
		if (input->pointer_focus == window)
			input->pointer_focus = NULL;
		if (input->keyboard_focus == window)
			input->keyboard_focus = NULL;
		if (input->focus_widget &&
		    input->focus_widget->window == window)
			input->focus_widget = NULL;
	}

	wl_list_for_each_safe(window_output, window_output_tmp,
			      &window->window_output_list, link) {
		free (window_output);
	}

	if (window->frame)
		window_frame_destroy(window->frame);

	if (window->xdg_surface)
		xdg_surface_destroy(window->xdg_surface);
	if (window->xdg_popup)
		xdg_popup_destroy(window->xdg_popup);

	surface_destroy(window->main_surface);

	wl_list_remove(&window->link);

	free(window->title);
	free(window);
}

static struct widget *
widget_find_widget(struct widget *widget, int32_t x, int32_t y)
{
	struct widget *child, *target;

	wl_list_for_each(child, &widget->child_list, link) {
		target = widget_find_widget(child, x, y);
		if (target)
			return target;
	}

	if (widget->allocation.x <= x &&
	    x < widget->allocation.x + widget->allocation.width &&
	    widget->allocation.y <= y &&
	    y < widget->allocation.y + widget->allocation.height) {
		return widget;
	}

	return NULL;
}

static struct widget *
window_find_widget(struct window *window, int32_t x, int32_t y)
{
	struct surface *surface;
	struct widget *widget;

	wl_list_for_each(surface, &window->subsurface_list, link) {
		widget = widget_find_widget(surface->widget, x, y);
		if (widget)
			return widget;
	}

	return NULL;
}

static struct widget *
widget_create(struct window *window, struct surface *surface, void *data)
{
	struct widget *widget;

	widget = xzalloc(sizeof *widget);
	widget->window = window;
	widget->surface = surface;
	widget->user_data = data;
	widget->allocation = surface->allocation;
	wl_list_init(&widget->child_list);
	widget->opaque = 0;
	widget->tooltip = NULL;
	widget->tooltip_count = 0;
	widget->default_cursor = CURSOR_LEFT_PTR;
	widget->use_cairo = 1;

	return widget;
}

struct widget *
window_add_widget(struct window *window, void *data)
{
	struct widget *widget;

	widget = widget_create(window, window->main_surface, data);
	wl_list_init(&widget->link);
	window->main_surface->widget = widget;

	return widget;
}

struct widget *
widget_add_widget(struct widget *parent, void *data)
{
	struct widget *widget;

	widget = widget_create(parent->window, parent->surface, data);
	wl_list_insert(parent->child_list.prev, &widget->link);

	return widget;
}

void
widget_destroy(struct widget *widget)
{
	struct display *display = widget->window->display;
	struct surface *surface = widget->surface;
	struct input *input;

	/* Destroy the sub-surface along with the root widget */
	if (surface->widget == widget && surface->subsurface)
		surface_destroy(widget->surface);

	if (widget->tooltip)
		widget_destroy_tooltip(widget);

	wl_list_for_each(input, &display->input_list, link) {
		if (input->focus_widget == widget)
			input->focus_widget = NULL;
	}

	wl_list_remove(&widget->link);
	free(widget);
}

void
widget_set_default_cursor(struct widget *widget, int cursor)
{
	widget->default_cursor = cursor;
}

void
widget_get_allocation(struct widget *widget, struct rectangle *allocation)
{
	*allocation = widget->allocation;
}

void
widget_set_size(struct widget *widget, int32_t width, int32_t height)
{
	widget->allocation.width = width;
	widget->allocation.height = height;
}

void
widget_set_allocation(struct widget *widget,
		      int32_t x, int32_t y, int32_t width, int32_t height)
{
	widget->allocation.x = x;
	widget->allocation.y = y;
	widget_set_size(widget, width, height);
}

void
widget_set_transparent(struct widget *widget, int transparent)
{
	widget->opaque = !transparent;
}

void *
widget_get_user_data(struct widget *widget)
{
	return widget->user_data;
}

static cairo_surface_t *
widget_get_cairo_surface(struct widget *widget)
{
	struct surface *surface = widget->surface;
	struct window *window = widget->window;

	assert(widget->use_cairo);

	if (!surface->cairo_surface) {
		if (surface == window->main_surface)
			window_create_main_surface(window);
		else
			surface_create_surface(surface, 0);
	}

	return surface->cairo_surface;
}

static void
widget_cairo_update_transform(struct widget *widget, cairo_t *cr)
{
	struct surface *surface = widget->surface;
	double angle;
	cairo_matrix_t m;
	enum wl_output_transform transform;
	int surface_width, surface_height;
	int translate_x, translate_y;
	int32_t scale;

	surface_width = surface->allocation.width;
	surface_height = surface->allocation.height;

	transform = surface->buffer_transform;
	scale = surface->buffer_scale;

	switch (transform) {
	case WL_OUTPUT_TRANSFORM_FLIPPED:
	case WL_OUTPUT_TRANSFORM_FLIPPED_90:
	case WL_OUTPUT_TRANSFORM_FLIPPED_180:
	case WL_OUTPUT_TRANSFORM_FLIPPED_270:
		cairo_matrix_init(&m, -1, 0, 0, 1, 0, 0);
		break;
	default:
		cairo_matrix_init_identity(&m);
		break;
	}

	switch (transform) {
	case WL_OUTPUT_TRANSFORM_NORMAL:
	default:
		angle = 0;
		translate_x = 0;
		translate_y = 0;
		break;
	case WL_OUTPUT_TRANSFORM_FLIPPED:
		angle = 0;
		translate_x = surface_width;
		translate_y = 0;
		break;
	case WL_OUTPUT_TRANSFORM_90:
		angle = M_PI_2;
		translate_x = surface_height;
		translate_y = 0;
		break;
	case WL_OUTPUT_TRANSFORM_FLIPPED_90:
		angle = M_PI_2;
		translate_x = surface_height;
		translate_y = surface_width;
		break;
	case WL_OUTPUT_TRANSFORM_180:
		angle = M_PI;
		translate_x = surface_width;
		translate_y = surface_height;
		break;
	case WL_OUTPUT_TRANSFORM_FLIPPED_180:
		angle = M_PI;
		translate_x = 0;
		translate_y = surface_height;
		break;
	case WL_OUTPUT_TRANSFORM_270:
		angle = M_PI + M_PI_2;
		translate_x = 0;
		translate_y = surface_width;
		break;
	case WL_OUTPUT_TRANSFORM_FLIPPED_270:
		angle = M_PI + M_PI_2;
		translate_x = 0;
		translate_y = 0;
		break;
	}

	cairo_scale(cr, scale, scale);
	cairo_translate(cr, translate_x, translate_y);
	cairo_rotate(cr, angle);
	cairo_transform(cr, &m);
}

cairo_t *
widget_cairo_create(struct widget *widget)
{
	struct surface *surface = widget->surface;
	cairo_surface_t *cairo_surface;
	cairo_t *cr;

	cairo_surface = widget_get_cairo_surface(widget);
	cr = cairo_create(cairo_surface);

	widget_cairo_update_transform(widget, cr);

	cairo_translate(cr, -surface->allocation.x, -surface->allocation.y);

	return cr;
}

struct wl_surface *
widget_get_wl_surface(struct widget *widget)
{
	return widget->surface->surface;
}

struct wl_subsurface *
widget_get_wl_subsurface(struct widget *widget)
{
	return widget->surface->subsurface;
}

uint32_t
widget_get_last_time(struct widget *widget)
{
	return widget->surface->last_time;
}

void
widget_input_region_add(struct widget *widget, const struct rectangle *rect)
{
	struct wl_compositor *comp = widget->window->display->compositor;
	struct surface *surface = widget->surface;

	if (!surface->input_region)
		surface->input_region = wl_compositor_create_region(comp);

	if (rect) {
		wl_region_add(surface->input_region,
			      rect->x, rect->y, rect->width, rect->height);
	}
}

void
widget_set_resize_handler(struct widget *widget,
			  widget_resize_handler_t handler)
{
	widget->resize_handler = handler;
}

void
widget_set_redraw_handler(struct widget *widget,
			  widget_redraw_handler_t handler)
{
	widget->redraw_handler = handler;
}

void
widget_set_enter_handler(struct widget *widget, widget_enter_handler_t handler)
{
	widget->enter_handler = handler;
}

void
widget_set_leave_handler(struct widget *widget, widget_leave_handler_t handler)
{
	widget->leave_handler = handler;
}

void
widget_set_motion_handler(struct widget *widget,
			  widget_motion_handler_t handler)
{
	widget->motion_handler = handler;
}

void
widget_set_button_handler(struct widget *widget,
			  widget_button_handler_t handler)
{
	widget->button_handler = handler;
}

void
widget_set_touch_up_handler(struct widget *widget,
			    widget_touch_up_handler_t handler)
{
	widget->touch_up_handler = handler;
}

void
widget_set_touch_down_handler(struct widget *widget,
			      widget_touch_down_handler_t handler)
{
	widget->touch_down_handler = handler;
}

void
widget_set_touch_motion_handler(struct widget *widget,
				widget_touch_motion_handler_t handler)
{
	widget->touch_motion_handler = handler;
}

void
widget_set_touch_frame_handler(struct widget *widget,
			       widget_touch_frame_handler_t handler)
{
	widget->touch_frame_handler = handler;
}

void
widget_set_touch_cancel_handler(struct widget *widget,
				widget_touch_cancel_handler_t handler)
{
	widget->touch_cancel_handler = handler;
}

void
widget_set_axis_handler(struct widget *widget,
			widget_axis_handler_t handler)
{
	widget->axis_handler = handler;
}

static void
window_schedule_redraw_task(struct window *window);

void
widget_schedule_redraw(struct widget *widget)
{
	DBG_OBJ(widget->surface->surface, "widget %p\n", widget);
	widget->surface->redraw_needed = 1;
	window_schedule_redraw_task(widget->window);
}

void
widget_set_use_cairo(struct widget *widget,
		     int use_cairo)
{
	widget->use_cairo = use_cairo;
}

cairo_surface_t *
window_get_surface(struct window *window)
{
	cairo_surface_t *cairo_surface;

	cairo_surface = widget_get_cairo_surface(window->main_surface->widget);

	return cairo_surface_reference(cairo_surface);
}

struct wl_surface *
window_get_wl_surface(struct window *window)
{
	return window->main_surface->surface;
}

static void
tooltip_redraw_handler(struct widget *widget, void *data)
{
	cairo_t *cr;
	const int32_t r = 3;
	struct tooltip *tooltip = data;
	int32_t width, height;

	cr = widget_cairo_create(widget);
	cairo_translate(cr, widget->allocation.x, widget->allocation.y);
	cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE);
	cairo_set_source_rgba(cr, 0.0, 0.0, 0.0, 0.0);
	cairo_paint(cr);

	width = widget->allocation.width;
	height = widget->allocation.height;
	rounded_rect(cr, 0, 0, width, height, r);

	cairo_set_operator(cr, CAIRO_OPERATOR_OVER);
	cairo_set_source_rgba(cr, 0.0, 0.0, 0.4, 0.8);
	cairo_fill(cr);

	cairo_set_source_rgb(cr, 1.0, 1.0, 1.0);
	cairo_move_to(cr, 10, 16);
	cairo_show_text(cr, tooltip->entry);
	cairo_destroy(cr);
}

static cairo_text_extents_t
get_text_extents(struct display *display, struct tooltip *tooltip)
{
	cairo_t *cr;
	cairo_text_extents_t extents;

	/* Use the dummy_surface because tooltip's surface was not
	 * created yet, and parent does not have a valid surface
	 * outside repaint, either.
	 */
	cr = cairo_create(display->dummy_surface);
	cairo_text_extents(cr, tooltip->entry, &extents);
	cairo_destroy(cr);

	return extents;
}

static int
window_create_tooltip(struct tooltip *tooltip)
{
	struct widget *parent = tooltip->parent;
	struct display *display = parent->window->display;
	const int offset_y = 27;
	const int margin = 3;
	cairo_text_extents_t extents;

	if (tooltip->widget)
		return 0;

	tooltip->widget = window_add_subsurface(parent->window, tooltip, SUBSURFACE_DESYNCHRONIZED);

	extents = get_text_extents(display, tooltip);
	widget_set_redraw_handler(tooltip->widget, tooltip_redraw_handler);
	widget_set_allocation(tooltip->widget,
			      tooltip->x, tooltip->y + offset_y,
			      extents.width + 20, 20 + margin * 2);

	return 0;
}

void
widget_destroy_tooltip(struct widget *parent)
{
	struct tooltip *tooltip = parent->tooltip;

	parent->tooltip_count = 0;
	if (!tooltip)
		return;

	if (tooltip->widget) {
		widget_destroy(tooltip->widget);
		tooltip->widget = NULL;
	}

	close(tooltip->tooltip_fd);
	free(tooltip->entry);
	free(tooltip);
	parent->tooltip = NULL;
}

static void
tooltip_func(struct task *task, uint32_t events)
{
	struct tooltip *tooltip =
		container_of(task, struct tooltip, tooltip_task);
	uint64_t exp;

	if (read(tooltip->tooltip_fd, &exp, sizeof (uint64_t)) != sizeof (uint64_t))
		abort();
	window_create_tooltip(tooltip);
}

#define TOOLTIP_TIMEOUT 500
static int
tooltip_timer_reset(struct tooltip *tooltip)
{
	struct itimerspec its;

	its.it_interval.tv_sec = 0;
	its.it_interval.tv_nsec = 0;
	its.it_value.tv_sec = TOOLTIP_TIMEOUT / 1000;
	its.it_value.tv_nsec = (TOOLTIP_TIMEOUT % 1000) * 1000 * 1000;
	if (timerfd_settime(tooltip->tooltip_fd, 0, &its, NULL) < 0) {
		fprintf(stderr, "could not set timerfd\n: %m");
		return -1;
	}

	return 0;
}

int
widget_set_tooltip(struct widget *parent, char *entry, float x, float y)
{
	struct tooltip *tooltip = parent->tooltip;

	parent->tooltip_count++;
	if (tooltip) {
		tooltip->x = x;
		tooltip->y = y;
		tooltip_timer_reset(tooltip);
		return 0;
	}

	/* the handler might be triggered too fast via input device motion, so
	 * we need this check here to make sure tooltip is fully initialized */
	if (parent->tooltip_count > 1)
		return 0;

        tooltip = malloc(sizeof *tooltip);
        if (!tooltip)
                return -1;

	parent->tooltip = tooltip;
	tooltip->parent = parent;
	tooltip->widget = NULL;
	tooltip->x = x;
	tooltip->y = y;
	tooltip->entry = strdup(entry);
	tooltip->tooltip_fd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC);
	if (tooltip->tooltip_fd < 0) {
		fprintf(stderr, "could not create timerfd\n: %m");
		return -1;
	}

	tooltip->tooltip_task.run = tooltip_func;
	display_watch_fd(parent->window->display, tooltip->tooltip_fd,
			 EPOLLIN, &tooltip->tooltip_task);
	tooltip_timer_reset(tooltip);

	return 0;
}

static void
workspace_manager_state(void *data,
			struct workspace_manager *workspace_manager,
			uint32_t current,
			uint32_t count)
{
	struct display *display = data;

	display->workspace = current;
	display->workspace_count = count;
}

static const struct workspace_manager_listener workspace_manager_listener = {
	workspace_manager_state
};

static void
frame_resize_handler(struct widget *widget,
		     int32_t width, int32_t height, void *data)
{
	struct window_frame *frame = data;
	struct widget *child = frame->child;
	struct rectangle interior;
	struct rectangle input;
	struct rectangle opaque;

	if (widget->window->fullscreen) {
		interior.x = 0;
		interior.y = 0;
		interior.width = width;
		interior.height = height;
	} else {
		frame_resize(frame->frame, width, height);
		frame_interior(frame->frame, &interior.x, &interior.y,
			       &interior.width, &interior.height);
	}

	widget_set_allocation(child, interior.x, interior.y,
			      interior.width, interior.height);

	if (child->resize_handler) {
		child->resize_handler(child, interior.width, interior.height,
				      child->user_data);

		if (widget->window->fullscreen) {
			width = child->allocation.width;
			height = child->allocation.height;
		} else {
			frame_resize_inside(frame->frame,
					    child->allocation.width,
					    child->allocation.height);
			width = frame_width(frame->frame);
			height = frame_height(frame->frame);
		}
	}

	widget_set_allocation(widget, 0, 0, width, height);

	widget->surface->input_region =
		wl_compositor_create_region(widget->window->display->compositor);
	if (!widget->window->fullscreen) {
		frame_input_rect(frame->frame, &input.x, &input.y,
				 &input.width, &input.height);
		wl_region_add(widget->surface->input_region,
			      input.x, input.y, input.width, input.height);
	} else {
		wl_region_add(widget->surface->input_region, 0, 0, width, height);
	}

	widget_set_allocation(widget, 0, 0, width, height);

	if (child->opaque) {
		if (!widget->window->fullscreen) {
			frame_opaque_rect(frame->frame, &opaque.x, &opaque.y,
					  &opaque.width, &opaque.height);

			wl_region_add(widget->surface->opaque_region,
				      opaque.x, opaque.y,
				      opaque.width, opaque.height);
		} else {
			wl_region_add(widget->surface->opaque_region,
				      0, 0, width, height);
		}
	}


	widget_schedule_redraw(widget);
}

static void
frame_redraw_handler(struct widget *widget, void *data)
{
	cairo_t *cr;
	struct window_frame *frame = data;
	struct window *window = widget->window;

	if (window->fullscreen)
		return;

	cr = widget_cairo_create(widget);

	frame_repaint(frame->frame, cr);

	cairo_destroy(cr);
}

static int
frame_get_pointer_image_for_location(struct window_frame *frame,
				     enum theme_location location)
{
	struct window *window = frame->widget->window;

	if (window->custom)
		return CURSOR_LEFT_PTR;

	switch (location) {
	case THEME_LOCATION_RESIZING_TOP:
		return CURSOR_TOP;
	case THEME_LOCATION_RESIZING_BOTTOM:
		return CURSOR_BOTTOM;
	case THEME_LOCATION_RESIZING_LEFT:
		return CURSOR_LEFT;
	case THEME_LOCATION_RESIZING_RIGHT:
		return CURSOR_RIGHT;
	case THEME_LOCATION_RESIZING_TOP_LEFT:
		return CURSOR_TOP_LEFT;
	case THEME_LOCATION_RESIZING_TOP_RIGHT:
		return CURSOR_TOP_RIGHT;
	case THEME_LOCATION_RESIZING_BOTTOM_LEFT:
		return CURSOR_BOTTOM_LEFT;
	case THEME_LOCATION_RESIZING_BOTTOM_RIGHT:
		return CURSOR_BOTTOM_RIGHT;
	case THEME_LOCATION_EXTERIOR:
	case THEME_LOCATION_TITLEBAR:
	default:
		return CURSOR_LEFT_PTR;
	}
}

void
window_show_frame_menu(struct window *window,
		       struct input *input, uint32_t time)
{
	int32_t x, y;

	if (window->xdg_surface) {
		input_get_position(input, &x, &y);
		xdg_surface_show_window_menu(window->xdg_surface,
					     input_get_seat(input),
					     window->display->serial,
					     x - 10, y - 10);
	}
}

static int
frame_enter_handler(struct widget *widget,
		    struct input *input, float x, float y, void *data)
{
	struct window_frame *frame = data;
	enum theme_location location;

	location = frame_pointer_enter(frame->frame, input, x, y);
	if (frame_status(frame->frame) & FRAME_STATUS_REPAINT)
		widget_schedule_redraw(frame->widget);

	return frame_get_pointer_image_for_location(data, location);
}

static int
frame_motion_handler(struct widget *widget,
		     struct input *input, uint32_t time,
		     float x, float y, void *data)
{
	struct window_frame *frame = data;
	enum theme_location location;

	location = frame_pointer_motion(frame->frame, input, x, y);
	if (frame_status(frame->frame) & FRAME_STATUS_REPAINT)
		widget_schedule_redraw(frame->widget);

	return frame_get_pointer_image_for_location(data, location);
}

static void
frame_leave_handler(struct widget *widget,
		    struct input *input, void *data)
{
	struct window_frame *frame = data;

	frame_pointer_leave(frame->frame, input);
	if (frame_status(frame->frame) & FRAME_STATUS_REPAINT)
		widget_schedule_redraw(frame->widget);
}

static void
frame_handle_status(struct window_frame *frame, struct input *input,
		    uint32_t time, enum theme_location location)
{
	struct window *window = frame->widget->window;
	uint32_t status;

	status = frame_status(frame->frame);
	if (status & FRAME_STATUS_REPAINT)
		widget_schedule_redraw(frame->widget);

	if (status & FRAME_STATUS_MINIMIZE) {
		window_set_minimized(window);
		frame_status_clear(frame->frame, FRAME_STATUS_MINIMIZE);
	}

	if (status & FRAME_STATUS_MENU) {
		window_show_frame_menu(window, input, time);
		frame_status_clear(frame->frame, FRAME_STATUS_MENU);
	}

	if (status & FRAME_STATUS_MAXIMIZE) {
		window_set_maximized(window, !window->maximized);
		frame_status_clear(frame->frame, FRAME_STATUS_MAXIMIZE);
	}

	if (status & FRAME_STATUS_CLOSE) {
		window_close(window);
		return;
	}

	if ((status & FRAME_STATUS_MOVE) && window->xdg_surface) {
		input_ungrab(input);
		xdg_surface_move(window->xdg_surface,
				 input_get_seat(input),
				 window->display->serial);

		frame_status_clear(frame->frame, FRAME_STATUS_MOVE);
	}

	if ((status & FRAME_STATUS_RESIZE) && window->xdg_surface) {
		input_ungrab(input);

		xdg_surface_resize(window->xdg_surface,
				   input_get_seat(input),
				   window->display->serial,
				   location);

		frame_status_clear(frame->frame, FRAME_STATUS_RESIZE);
	}
}

static void
frame_button_handler(struct widget *widget,
		     struct input *input, uint32_t time,
		     uint32_t button, enum wl_pointer_button_state state,
		     void *data)

{
	struct window_frame *frame = data;
	enum theme_location location;

	location = frame_pointer_button(frame->frame, input, button, state);
	frame_handle_status(frame, input, time, location);
}

static void
frame_touch_down_handler(struct widget *widget, struct input *input,
			 uint32_t serial, uint32_t time, int32_t id,
			 float x, float y, void *data)
{
	struct window_frame *frame = data;

	frame_touch_down(frame->frame, input, id, x, y);
	frame_handle_status(frame, input, time, THEME_LOCATION_CLIENT_AREA);
}

static void
frame_touch_up_handler(struct widget *widget,
			 struct input *input, uint32_t serial, uint32_t time,
			 int32_t id, void *data)
{
	struct window_frame *frame = data;

	frame_touch_up(frame->frame, input, id);
	frame_handle_status(frame, input, time, THEME_LOCATION_CLIENT_AREA);
}

struct widget *
window_frame_create(struct window *window, void *data)
{
	struct window_frame *frame;
	uint32_t buttons;

	if (window->custom) {
		buttons = FRAME_BUTTON_NONE;
	} else {
		buttons = FRAME_BUTTON_ALL;
	}

	frame = xzalloc(sizeof *frame);
	frame->frame = frame_create(window->display->theme, 0, 0,
				    buttons, window->title);

	frame->widget = window_add_widget(window, frame);
	frame->child = widget_add_widget(frame->widget, data);

	widget_set_redraw_handler(frame->widget, frame_redraw_handler);
	widget_set_resize_handler(frame->widget, frame_resize_handler);
	widget_set_enter_handler(frame->widget, frame_enter_handler);
	widget_set_leave_handler(frame->widget, frame_leave_handler);
	widget_set_motion_handler(frame->widget, frame_motion_handler);
	widget_set_button_handler(frame->widget, frame_button_handler);
	widget_set_touch_down_handler(frame->widget, frame_touch_down_handler);
	widget_set_touch_up_handler(frame->widget, frame_touch_up_handler);

	window->frame = frame;

	return frame->child;
}

void
window_frame_set_child_size(struct widget *widget, int child_width,
			    int child_height)
{
	struct display *display = widget->window->display;
	struct theme *t = display->theme;
	int decoration_width, decoration_height;
	int width, height;
	int margin = widget->window->maximized ? 0 : t->margin;

	if (!widget->window->fullscreen) {
		decoration_width = (t->width + margin) * 2;
		decoration_height = t->width +
			t->titlebar_height + margin * 2;

		width = child_width + decoration_width;
		height = child_height + decoration_height;
	} else {
		width = child_width;
		height = child_height;
	}

	window_schedule_resize(widget->window, width, height);
}

static void
window_frame_destroy(struct window_frame *frame)
{
	frame_destroy(frame->frame);

	/* frame->child must be destroyed by the application */
	widget_destroy(frame->widget);
	free(frame);
}

static void
input_set_focus_widget(struct input *input, struct widget *focus,
		       float x, float y)
{
	struct widget *old, *widget;
	int cursor;

	if (focus == input->focus_widget)
		return;

	old = input->focus_widget;
	if (old) {
		widget = old;
		if (input->grab)
			widget = input->grab;
		if (widget->leave_handler)
			widget->leave_handler(old, input, widget->user_data);
		input->focus_widget = NULL;
	}

	if (focus) {
		widget = focus;
		if (input->grab)
			widget = input->grab;
		input->focus_widget = focus;
		if (widget->enter_handler)
			cursor = widget->enter_handler(focus, input, x, y,
						       widget->user_data);
		else
			cursor = widget->default_cursor;

		input_set_pointer_image(input, cursor);
	}
}

void
touch_grab(struct input  *input, int32_t touch_id)
{
	input->touch_grab = 1;
	input->touch_grab_id = touch_id;
}

void
touch_ungrab(struct input *input)
{
	struct touch_point *tp, *tmp;

	input->touch_grab = 0;

	wl_list_for_each_safe(tp, tmp,
			&input->touch_point_list, link) {
		if (tp->id != input->touch_grab_id)
			continue;
		wl_list_remove(&tp->link);
		free(tp);

		return;
	}
}

void
input_grab(struct input *input, struct widget *widget, uint32_t button)
{
	input->grab = widget;
	input->grab_button = button;

	input_set_focus_widget(input, widget, input->sx, input->sy);
}

void
input_ungrab(struct input *input)
{
	struct widget *widget;

	input->grab = NULL;
	if (input->pointer_focus) {
		widget = window_find_widget(input->pointer_focus,
					    input->sx, input->sy);
		input_set_focus_widget(input, widget, input->sx, input->sy);
	}
}

static void
input_remove_pointer_focus(struct input *input)
{
	struct window *window = input->pointer_focus;

	if (!window)
		return;

	input_set_focus_widget(input, NULL, 0, 0);

	input->pointer_focus = NULL;
	input->current_cursor = CURSOR_UNSET;
}

static void
pointer_handle_enter(void *data, struct wl_pointer *pointer,
		     uint32_t serial, struct wl_surface *surface,
		     wl_fixed_t sx_w, wl_fixed_t sy_w)
{
	struct input *input = data;
	struct window *window;
	struct widget *widget;
	float sx = wl_fixed_to_double(sx_w);
	float sy = wl_fixed_to_double(sy_w);

	if (!surface) {
		/* enter event for a window we've just destroyed */
		return;
	}

	window = wl_surface_get_user_data(surface);
	if (surface != window->main_surface->surface) {
		DBG("Ignoring input event from subsurface %p\n", surface);
		return;
	}

	input->display->serial = serial;
	input->pointer_enter_serial = serial;
	input->pointer_focus = window;

	input->sx = sx;
	input->sy = sy;

	widget = window_find_widget(window, sx, sy);
	input_set_focus_widget(input, widget, sx, sy);
}

static void
pointer_handle_leave(void *data, struct wl_pointer *pointer,
		     uint32_t serial, struct wl_surface *surface)
{
	struct input *input = data;

	input->display->serial = serial;
	input_remove_pointer_focus(input);
}

static void
pointer_handle_motion(void *data, struct wl_pointer *pointer,
		      uint32_t time, wl_fixed_t sx_w, wl_fixed_t sy_w)
{
	struct input *input = data;
	struct window *window = input->pointer_focus;
	struct widget *widget;
	int cursor;
	float sx = wl_fixed_to_double(sx_w);
	float sy = wl_fixed_to_double(sy_w);

	if (!window)
		return;

	input->sx = sx;
	input->sy = sy;

	/* when making the window smaller - e.g. after a unmaximise we might
	 * still have a pending motion event that the compositor has picked
	 * based on the old surface dimensions
	 */
	if (sx > window->main_surface->allocation.width ||
	    sy > window->main_surface->allocation.height)
		return;

	if (!(input->grab && input->grab_button)) {
		widget = window_find_widget(window, sx, sy);
		input_set_focus_widget(input, widget, sx, sy);
	}

	if (input->grab)
		widget = input->grab;
	else
		widget = input->focus_widget;
	if (widget) {
		if (widget->motion_handler)
			cursor = widget->motion_handler(input->focus_widget,
							input, time, sx, sy,
							widget->user_data);
		else
			cursor = widget->default_cursor;
	} else
		cursor = CURSOR_LEFT_PTR;

	input_set_pointer_image(input, cursor);
}

static void
pointer_handle_button(void *data, struct wl_pointer *pointer, uint32_t serial,
		      uint32_t time, uint32_t button, uint32_t state_w)
{
	struct input *input = data;
	struct widget *widget;
	enum wl_pointer_button_state state = state_w;

	input->display->serial = serial;
	if (input->focus_widget && input->grab == NULL &&
	    state == WL_POINTER_BUTTON_STATE_PRESSED)
		input_grab(input, input->focus_widget, button);

	widget = input->grab;
	if (widget && widget->button_handler)
		(*widget->button_handler)(widget,
					  input, time,
					  button, state,
					  input->grab->user_data);

	if (input->grab && input->grab_button == button &&
	    state == WL_POINTER_BUTTON_STATE_RELEASED)
		input_ungrab(input);
}

static void
pointer_handle_axis(void *data, struct wl_pointer *pointer,
		    uint32_t time, uint32_t axis, wl_fixed_t value)
{
	struct input *input = data;
	struct widget *widget;

	widget = input->focus_widget;
	if (input->grab)
		widget = input->grab;
	if (widget && widget->axis_handler)
		(*widget->axis_handler)(widget,
					input, time,
					axis, value,
					widget->user_data);
}

static const struct wl_pointer_listener pointer_listener = {
	pointer_handle_enter,
	pointer_handle_leave,
	pointer_handle_motion,
	pointer_handle_button,
	pointer_handle_axis,
};

static void
input_remove_keyboard_focus(struct input *input)
{
	struct window *window = input->keyboard_focus;
	struct itimerspec its;

	its.it_interval.tv_sec = 0;
	its.it_interval.tv_nsec = 0;
	its.it_value.tv_sec = 0;
	its.it_value.tv_nsec = 0;
	timerfd_settime(input->repeat_timer_fd, 0, &its, NULL);

	if (!window)
		return;

	if (window->keyboard_focus_handler)
		(*window->keyboard_focus_handler)(window, NULL,
						  window->user_data);

	input->keyboard_focus = NULL;
}

static void
keyboard_repeat_func(struct task *task, uint32_t events)
{
	struct input *input =
		container_of(task, struct input, repeat_task);
	struct window *window = input->keyboard_focus;
	uint64_t exp;

	if (read(input->repeat_timer_fd, &exp, sizeof exp) != sizeof exp)
		/* If we change the timer between the fd becoming
		 * readable and getting here, there'll be nothing to
		 * read and we get EAGAIN. */
		return;

	if (window && window->key_handler) {
		(*window->key_handler)(window, input, input->repeat_time,
				       input->repeat_key, input->repeat_sym,
				       WL_KEYBOARD_KEY_STATE_PRESSED,
				       window->user_data);
	}
}

static void
keyboard_handle_keymap(void *data, struct wl_keyboard *keyboard,
		       uint32_t format, int fd, uint32_t size)
{
	struct input *input = data;
	struct xkb_keymap *keymap;
	struct xkb_state *state;
	char *map_str;

	if (!data) {
		close(fd);
		return;
	}

	if (format != WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1) {
		close(fd);
		return;
	}

	map_str = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0);
	if (map_str == MAP_FAILED) {
		close(fd);
		return;
	}

	keymap = xkb_map_new_from_string(input->display->xkb_context,
					 map_str,
					 XKB_KEYMAP_FORMAT_TEXT_V1,
					 0);
	munmap(map_str, size);
	close(fd);

	if (!keymap) {
		fprintf(stderr, "failed to compile keymap\n");
		return;
	}

	state = xkb_state_new(keymap);
	if (!state) {
		fprintf(stderr, "failed to create XKB state\n");
		xkb_map_unref(keymap);
		return;
	}

	xkb_keymap_unref(input->xkb.keymap);
	xkb_state_unref(input->xkb.state);
	input->xkb.keymap = keymap;
	input->xkb.state = state;

	input->xkb.control_mask =
		1 << xkb_map_mod_get_index(input->xkb.keymap, "Control");
	input->xkb.alt_mask =
		1 << xkb_map_mod_get_index(input->xkb.keymap, "Mod1");
	input->xkb.shift_mask =
		1 << xkb_map_mod_get_index(input->xkb.keymap, "Shift");
}

static void
keyboard_handle_enter(void *data, struct wl_keyboard *keyboard,
		      uint32_t serial, struct wl_surface *surface,
		      struct wl_array *keys)
{
	struct input *input = data;
	struct window *window;

	input->display->serial = serial;
	input->keyboard_focus = wl_surface_get_user_data(surface);

	window = input->keyboard_focus;
	if (window->keyboard_focus_handler)
		(*window->keyboard_focus_handler)(window,
						  input, window->user_data);
}

static void
keyboard_handle_leave(void *data, struct wl_keyboard *keyboard,
		      uint32_t serial, struct wl_surface *surface)
{
	struct input *input = data;

	input->display->serial = serial;
	input_remove_keyboard_focus(input);
}

static void
keyboard_handle_key(void *data, struct wl_keyboard *keyboard,
		    uint32_t serial, uint32_t time, uint32_t key,
		    uint32_t state_w)
{
	struct input *input = data;
	struct window *window = input->keyboard_focus;
	uint32_t code, num_syms;
	enum wl_keyboard_key_state state = state_w;
	const xkb_keysym_t *syms;
	xkb_keysym_t sym;
	struct itimerspec its;

	input->display->serial = serial;
	code = key + 8;
	if (!window || !input->xkb.state)
		return;

	/* We only use input grabs for pointer events for now, so just
	 * ignore key presses if a grab is active.  We expand the key
	 * event delivery mechanism to route events to widgets to
	 * properly handle key grabs.  In the meantime, this prevents
	 * key event devlivery while a grab is active. */
	if (input->grab && input->grab_button == 0)
		return;

	num_syms = xkb_key_get_syms(input->xkb.state, code, &syms);

	sym = XKB_KEY_NoSymbol;
	if (num_syms == 1)
		sym = syms[0];


	if (sym == XKB_KEY_F5 && input->modifiers == MOD_ALT_MASK) {
		if (state == WL_KEYBOARD_KEY_STATE_PRESSED)
			window_set_maximized(window, !window->maximized);
	} else if (sym == XKB_KEY_F11 &&
		   window->fullscreen_handler &&
		   state == WL_KEYBOARD_KEY_STATE_PRESSED) {
		window->fullscreen_handler(window, window->user_data);
	} else if (sym == XKB_KEY_F4 &&
		   input->modifiers == MOD_ALT_MASK &&
		   state == WL_KEYBOARD_KEY_STATE_PRESSED) {
		window_close(window);
	} else if (window->key_handler) {
		(*window->key_handler)(window, input, time, key,
				       sym, state, window->user_data);
	}

	if (state == WL_KEYBOARD_KEY_STATE_RELEASED &&
	    key == input->repeat_key) {
		its.it_interval.tv_sec = 0;
		its.it_interval.tv_nsec = 0;
		its.it_value.tv_sec = 0;
		its.it_value.tv_nsec = 0;
		timerfd_settime(input->repeat_timer_fd, 0, &its, NULL);
	} else if (state == WL_KEYBOARD_KEY_STATE_PRESSED &&
		   xkb_keymap_key_repeats(input->xkb.keymap, code)) {
		input->repeat_sym = sym;
		input->repeat_key = key;
		input->repeat_time = time;
		its.it_interval.tv_sec = 0;
		its.it_interval.tv_nsec = 25 * 1000 * 1000;
		its.it_value.tv_sec = 0;
		its.it_value.tv_nsec = 400 * 1000 * 1000;
		timerfd_settime(input->repeat_timer_fd, 0, &its, NULL);
	}
}

static void
keyboard_handle_modifiers(void *data, struct wl_keyboard *keyboard,
			  uint32_t serial, uint32_t mods_depressed,
			  uint32_t mods_latched, uint32_t mods_locked,
			  uint32_t group)
{
	struct input *input = data;
	xkb_mod_mask_t mask;

	/* If we're not using a keymap, then we don't handle PC-style modifiers */
	if (!input->xkb.keymap)
		return;

	xkb_state_update_mask(input->xkb.state, mods_depressed, mods_latched,
			      mods_locked, 0, 0, group);
	mask = xkb_state_serialize_mods(input->xkb.state,
					XKB_STATE_DEPRESSED |
					XKB_STATE_LATCHED);
	input->modifiers = 0;
	if (mask & input->xkb.control_mask)
		input->modifiers |= MOD_CONTROL_MASK;
	if (mask & input->xkb.alt_mask)
		input->modifiers |= MOD_ALT_MASK;
	if (mask & input->xkb.shift_mask)
		input->modifiers |= MOD_SHIFT_MASK;
}

static const struct wl_keyboard_listener keyboard_listener = {
	keyboard_handle_keymap,
	keyboard_handle_enter,
	keyboard_handle_leave,
	keyboard_handle_key,
	keyboard_handle_modifiers,
};

static void
touch_handle_down(void *data, struct wl_touch *wl_touch,
		  uint32_t serial, uint32_t time, struct wl_surface *surface,
		  int32_t id, wl_fixed_t x_w, wl_fixed_t y_w)
{
	struct input *input = data;
	struct widget *widget;
	float sx = wl_fixed_to_double(x_w);
	float sy = wl_fixed_to_double(y_w);

	input->display->serial = serial;
	input->touch_focus = wl_surface_get_user_data(surface);
	if (!input->touch_focus) {
		DBG("Failed to find to touch focus for surface %p\n", surface);
		return;
	}

	if (surface != input->touch_focus->main_surface->surface) {
		DBG("Ignoring input event from subsurface %p\n", surface);
		input->touch_focus = NULL;
		return;
	}

	if (input->grab)
		widget = input->grab;
	else
		widget = window_find_widget(input->touch_focus,
					    wl_fixed_to_double(x_w),
					    wl_fixed_to_double(y_w));
	if (widget) {
		struct touch_point *tp = xmalloc(sizeof *tp);
		if (tp) {
			tp->id = id;
			tp->widget = widget;
			tp->x = sx;
			tp->y = sy;
			wl_list_insert(&input->touch_point_list, &tp->link);

			if (widget->touch_down_handler)
				(*widget->touch_down_handler)(widget, input, 
							      serial, time, id,
							      sx, sy,
							      widget->user_data);
		}
	}
}

static void
touch_handle_up(void *data, struct wl_touch *wl_touch,
		uint32_t serial, uint32_t time, int32_t id)
{
	struct input *input = data;
	struct touch_point *tp, *tmp;

	if (!input->touch_focus) {
		DBG("No touch focus found for touch up event!\n");
		return;
	}

	wl_list_for_each_safe(tp, tmp, &input->touch_point_list, link) {
		if (tp->id != id)
			continue;

		if (tp->widget->touch_up_handler)
			(*tp->widget->touch_up_handler)(tp->widget, input, serial,
							time, id,
							tp->widget->user_data);

		wl_list_remove(&tp->link);
		free(tp);

		return;
	}
}

static void
touch_handle_motion(void *data, struct wl_touch *wl_touch,
		    uint32_t time, int32_t id, wl_fixed_t x_w, wl_fixed_t y_w)
{
	struct input *input = data;
	struct touch_point *tp;
	float sx = wl_fixed_to_double(x_w);
	float sy = wl_fixed_to_double(y_w);

	DBG("touch_handle_motion: %i %i\n", id, wl_list_length(&input->touch_point_list));

	if (!input->touch_focus) {
		DBG("No touch focus found for touch motion event!\n");
		return;
	}

	wl_list_for_each(tp, &input->touch_point_list, link) {
		if (tp->id != id)
			continue;

		tp->x = sx;
		tp->y = sy;
		if (tp->widget->touch_motion_handler)
			(*tp->widget->touch_motion_handler)(tp->widget, input, time,
							    id, sx, sy,
							    tp->widget->user_data);
		return;
	}
}

static void
touch_handle_frame(void *data, struct wl_touch *wl_touch)
{
	struct input *input = data;
	struct touch_point *tp, *tmp;

	DBG("touch_handle_frame\n");

	if (!input->touch_focus) {
		DBG("No touch focus found for touch frame event!\n");
		return;
	}

	wl_list_for_each_safe(tp, tmp, &input->touch_point_list, link) {
		if (tp->widget->touch_frame_handler)
			(*tp->widget->touch_frame_handler)(tp->widget, input, 
							   tp->widget->user_data);
	}
}

static void
touch_handle_cancel(void *data, struct wl_touch *wl_touch)
{
	struct input *input = data;
	struct touch_point *tp, *tmp;

	DBG("touch_handle_cancel\n");

	if (!input->touch_focus) {
		DBG("No touch focus found for touch cancel event!\n");
		return;
	}

	wl_list_for_each_safe(tp, tmp, &input->touch_point_list, link) {
		if (tp->widget->touch_cancel_handler)
			(*tp->widget->touch_cancel_handler)(tp->widget, input,
							    tp->widget->user_data);

		wl_list_remove(&tp->link);
		free(tp);
	}
}

static const struct wl_touch_listener touch_listener = {
	touch_handle_down,
	touch_handle_up,
	touch_handle_motion,
	touch_handle_frame,
	touch_handle_cancel,
};

static void
seat_handle_capabilities(void *data, struct wl_seat *seat,
			 enum wl_seat_capability caps)
{
	struct input *input = data;

	if ((caps & WL_SEAT_CAPABILITY_POINTER) && !input->pointer) {
		input->pointer = wl_seat_get_pointer(seat);
		wl_pointer_set_user_data(input->pointer, input);
		wl_pointer_add_listener(input->pointer, &pointer_listener,
					input);
	} else if (!(caps & WL_SEAT_CAPABILITY_POINTER) && input->pointer) {
		wl_pointer_destroy(input->pointer);
		input->pointer = NULL;
	}

	if ((caps & WL_SEAT_CAPABILITY_KEYBOARD) && !input->keyboard) {
		input->keyboard = wl_seat_get_keyboard(seat);
		wl_keyboard_set_user_data(input->keyboard, input);
		wl_keyboard_add_listener(input->keyboard, &keyboard_listener,
					 input);
	} else if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD) && input->keyboard) {
		wl_keyboard_destroy(input->keyboard);
		input->keyboard = NULL;
	}

	if ((caps & WL_SEAT_CAPABILITY_TOUCH) && !input->touch) {
		input->touch = wl_seat_get_touch(seat);
		wl_touch_set_user_data(input->touch, input);
		wl_touch_add_listener(input->touch, &touch_listener, input);
	} else if (!(caps & WL_SEAT_CAPABILITY_TOUCH) && input->touch) {
		wl_touch_destroy(input->touch);
		input->touch = NULL;
	}
}

static void
seat_handle_name(void *data, struct wl_seat *seat,
		 const char *name)
{

}

static const struct wl_seat_listener seat_listener = {
	seat_handle_capabilities,
	seat_handle_name
};

void
input_get_position(struct input *input, int32_t *x, int32_t *y)
{
	*x = input->sx;
	*y = input->sy;
}

int
input_get_touch(struct input *input, int32_t id, float *x, float *y)
{
	struct touch_point *tp;

	wl_list_for_each(tp, &input->touch_point_list, link) {
		if (tp->id != id)
			continue;

		*x = tp->x;
		*y = tp->y;
		return 0;
	}

	return -1;
}

struct display *
input_get_display(struct input *input)
{
	return input->display;
}

struct wl_seat *
input_get_seat(struct input *input)
{
	return input->seat;
}

uint32_t
input_get_modifiers(struct input *input)
{
	return input->modifiers;
}

struct widget *
input_get_focus_widget(struct input *input)
{
	return input->focus_widget;
}

struct data_offer {
	struct wl_data_offer *offer;
	struct input *input;
	struct wl_array types;
	int refcount;

	struct task io_task;
	int fd;
	data_func_t func;
	int32_t x, y;
	void *user_data;
};

static void
data_offer_offer(void *data, struct wl_data_offer *wl_data_offer, const char *type)
{
	struct data_offer *offer = data;
	char **p;

	p = wl_array_add(&offer->types, sizeof *p);
	*p = strdup(type);
}

static const struct wl_data_offer_listener data_offer_listener = {
	data_offer_offer,
};

static void
data_offer_destroy(struct data_offer *offer)
{
	char **p;

	offer->refcount--;
	if (offer->refcount == 0) {
		wl_data_offer_destroy(offer->offer);
		for (p = offer->types.data; *p; p++)
			free(*p);
		wl_array_release(&offer->types);
		free(offer);
	}
}

static void
data_device_data_offer(void *data,
		       struct wl_data_device *data_device,
		       struct wl_data_offer *_offer)
{
	struct data_offer *offer;

	offer = xmalloc(sizeof *offer);

	wl_array_init(&offer->types);
	offer->refcount = 1;
	offer->input = data;
	offer->offer = _offer;
	wl_data_offer_add_listener(offer->offer,
				   &data_offer_listener, offer);
}

static void
data_device_enter(void *data, struct wl_data_device *data_device,
		  uint32_t serial, struct wl_surface *surface,
		  wl_fixed_t x_w, wl_fixed_t y_w,
		  struct wl_data_offer *offer)
{
	struct input *input = data;
	struct window *window;
	void *types_data;
	float x = wl_fixed_to_double(x_w);
	float y = wl_fixed_to_double(y_w);
	char **p;

	window = wl_surface_get_user_data(surface);
	input->drag_enter_serial = serial;
	input->drag_focus = window,
	input->drag_x = x;
	input->drag_y = y;

	if (!input->touch_grab)
		input->pointer_enter_serial = serial;

	if (offer) {
		input->drag_offer = wl_data_offer_get_user_data(offer);

		p = wl_array_add(&input->drag_offer->types, sizeof *p);
		*p = NULL;

		types_data = input->drag_offer->types.data;
	} else {
		input->drag_offer = NULL;
		types_data = NULL;
	}

	if (window->data_handler)
		window->data_handler(window, input, x, y, types_data,
				     window->user_data);
}

static void
data_device_leave(void *data, struct wl_data_device *data_device)
{
	struct input *input = data;

	if (input->drag_offer) {
		data_offer_destroy(input->drag_offer);
		input->drag_offer = NULL;
	}
}

static void
data_device_motion(void *data, struct wl_data_device *data_device,
		   uint32_t time, wl_fixed_t x_w, wl_fixed_t y_w)
{
	struct input *input = data;
	struct window *window = input->drag_focus;
	float x = wl_fixed_to_double(x_w);
	float y = wl_fixed_to_double(y_w);
	void *types_data;

	input->drag_x = x;
	input->drag_y = y;

	if (input->drag_offer)
		types_data = input->drag_offer->types.data;
	else
		types_data = NULL;

	if (window->data_handler)
		window->data_handler(window, input, x, y, types_data,
				     window->user_data);
}

static void
data_device_drop(void *data, struct wl_data_device *data_device)
{
	struct input *input = data;
	struct window *window = input->drag_focus;
	float x, y;

	x = input->drag_x;
	y = input->drag_y;

	if (window->drop_handler)
		window->drop_handler(window, input,
				     x, y, window->user_data);

	if (input->touch_grab)
		touch_ungrab(input);
}

static void
data_device_selection(void *data,
		      struct wl_data_device *wl_data_device,
		      struct wl_data_offer *offer)
{
	struct input *input = data;
	char **p;

	if (input->selection_offer)
		data_offer_destroy(input->selection_offer);

	if (offer) {
		input->selection_offer = wl_data_offer_get_user_data(offer);
		p = wl_array_add(&input->selection_offer->types, sizeof *p);
		*p = NULL;
	} else {
		input->selection_offer = NULL;
	}
}

static const struct wl_data_device_listener data_device_listener = {
	data_device_data_offer,
	data_device_enter,
	data_device_leave,
	data_device_motion,
	data_device_drop,
	data_device_selection
};

static void
input_set_pointer_image_index(struct input *input, int index)
{
	struct wl_buffer *buffer;
	struct wl_cursor *cursor;
	struct wl_cursor_image *image;

	if (!input->pointer)
		return;

	cursor = input->display->cursors[input->current_cursor];
	if (!cursor)
		return;

	if (index >= (int) cursor->image_count) {
		fprintf(stderr, "cursor index out of range\n");
		return;
	}

	image = cursor->images[index];
	buffer = wl_cursor_image_get_buffer(image);
	if (!buffer)
		return;

	wl_surface_attach(input->pointer_surface, buffer, 0, 0);
	wl_surface_damage(input->pointer_surface, 0, 0,
			  image->width, image->height);
	wl_surface_commit(input->pointer_surface);
	wl_pointer_set_cursor(input->pointer, input->pointer_enter_serial,
			      input->pointer_surface,
			      image->hotspot_x, image->hotspot_y);
}

static const struct wl_callback_listener pointer_surface_listener;

static void
pointer_surface_frame_callback(void *data, struct wl_callback *callback,
			       uint32_t time)
{
	struct input *input = data;
	struct wl_cursor *cursor;
	int i;

	if (callback) {
		assert(callback == input->cursor_frame_cb);
		wl_callback_destroy(callback);
		input->cursor_frame_cb = NULL;
	}

	if (!input->pointer)
		return;

	if (input->current_cursor == CURSOR_BLANK) {
		wl_pointer_set_cursor(input->pointer,
				      input->pointer_enter_serial,
				      NULL, 0, 0);
		return;
	}

	if (input->current_cursor == CURSOR_UNSET)
		return;
	cursor = input->display->cursors[input->current_cursor];
	if (!cursor)
		return;

	/* FIXME We don't have the current time on the first call so we set
	 * the animation start to the time of the first frame callback. */
	if (time == 0)
		input->cursor_anim_start = 0;
	else if (input->cursor_anim_start == 0)
		input->cursor_anim_start = time;

	if (time == 0 || input->cursor_anim_start == 0)
		i = 0;
	else
		i = wl_cursor_frame(cursor, time - input->cursor_anim_start);

	if (cursor->image_count > 1) {
		input->cursor_frame_cb =
			wl_surface_frame(input->pointer_surface);
		wl_callback_add_listener(input->cursor_frame_cb,
					 &pointer_surface_listener, input);
	}

	input_set_pointer_image_index(input, i);
}

static const struct wl_callback_listener pointer_surface_listener = {
	pointer_surface_frame_callback
};

void
input_set_pointer_image(struct input *input, int pointer)
{
	int force = 0;

	if (!input->pointer)
		return;

	if (input->pointer_enter_serial > input->cursor_serial)
		force = 1;

	if (!force && pointer == input->current_cursor)
		return;

	input->current_cursor = pointer;
	input->cursor_serial = input->pointer_enter_serial;
	if (!input->cursor_frame_cb)
		pointer_surface_frame_callback(input, NULL, 0);
	else if (force) {
		/* The current frame callback may be stuck if, for instance,
		 * the set cursor request was processed by the server after
		 * this client lost the focus. In this case the cursor surface
		 * might not be mapped and the frame callback wouldn't ever
		 * complete. Send a set_cursor and attach to try to map the
		 * cursor surface again so that the callback will finish */
		input_set_pointer_image_index(input, 0);
	}
}

struct wl_data_device *
input_get_data_device(struct input *input)
{
	return input->data_device;
}

void
input_set_selection(struct input *input,
		    struct wl_data_source *source, uint32_t time)
{
	if (input->data_device)
		wl_data_device_set_selection(input->data_device, source, time);
}

void
input_accept(struct input *input, const char *type)
{
	wl_data_offer_accept(input->drag_offer->offer,
			     input->drag_enter_serial, type);
}

static void
offer_io_func(struct task *task, uint32_t events)
{
	struct data_offer *offer =
		container_of(task, struct data_offer, io_task);
	unsigned int len;
	char buffer[4096];

	len = read(offer->fd, buffer, sizeof buffer);
	offer->func(buffer, len,
		    offer->x, offer->y, offer->user_data);

	if (len == 0) {
		close(offer->fd);
		data_offer_destroy(offer);
	}
}

static void
data_offer_receive_data(struct data_offer *offer, const char *mime_type,
			data_func_t func, void *user_data)
{
	int p[2];

	if (pipe2(p, O_CLOEXEC) == -1)
		return;

	wl_data_offer_receive(offer->offer, mime_type, p[1]);
	close(p[1]);

	offer->io_task.run = offer_io_func;
	offer->fd = p[0];
	offer->func = func;
	offer->refcount++;
	offer->user_data = user_data;

	display_watch_fd(offer->input->display,
			 offer->fd, EPOLLIN, &offer->io_task);
}

void
input_receive_drag_data(struct input *input, const char *mime_type,
			data_func_t func, void *data)
{
	data_offer_receive_data(input->drag_offer, mime_type, func, data);
	input->drag_offer->x = input->drag_x;
	input->drag_offer->y = input->drag_y;
}

int
input_receive_drag_data_to_fd(struct input *input,
			      const char *mime_type, int fd)
{
	if (input->drag_offer)
		wl_data_offer_receive(input->drag_offer->offer, mime_type, fd);

	return 0;
}

int
input_receive_selection_data(struct input *input, const char *mime_type,
			     data_func_t func, void *data)
{
	char **p;

	if (input->selection_offer == NULL)
		return -1;

	for (p = input->selection_offer->types.data; *p; p++)
		if (strcmp(mime_type, *p) == 0)
			break;

	if (*p == NULL)
		return -1;

	data_offer_receive_data(input->selection_offer,
				mime_type, func, data);
	return 0;
}

int
input_receive_selection_data_to_fd(struct input *input,
				   const char *mime_type, int fd)
{
	if (input->selection_offer)
		wl_data_offer_receive(input->selection_offer->offer,
				      mime_type, fd);

	return 0;
}

void
window_move(struct window *window, struct input *input, uint32_t serial)
{
	if (!window->xdg_surface)
		return;

	xdg_surface_move(window->xdg_surface, input->seat, serial);
}

static void
surface_set_synchronized(struct surface *surface)
{
	if (!surface->subsurface)
		return;

	if (surface->synchronized)
		return;

	wl_subsurface_set_sync(surface->subsurface);
	surface->synchronized = 1;
}

static void
surface_set_synchronized_default(struct surface *surface)
{
	if (!surface->subsurface)
		return;

	if (surface->synchronized == surface->synchronized_default)
		return;

	if (surface->synchronized_default)
		wl_subsurface_set_sync(surface->subsurface);
	else
		wl_subsurface_set_desync(surface->subsurface);

	surface->synchronized = surface->synchronized_default;
}

static void
surface_resize(struct surface *surface)
{
	struct widget *widget = surface->widget;
	struct wl_compositor *compositor = widget->window->display->compositor;

	if (surface->input_region) {
		wl_region_destroy(surface->input_region);
		surface->input_region = NULL;
	}

	if (surface->opaque_region)
		wl_region_destroy(surface->opaque_region);

	surface->opaque_region = wl_compositor_create_region(compositor);

	if (widget->resize_handler)
		widget->resize_handler(widget,
				       widget->allocation.width,
				       widget->allocation.height,
				       widget->user_data);

	if (surface->subsurface &&
	    (surface->allocation.x != widget->allocation.x ||
	     surface->allocation.y != widget->allocation.y)) {
		wl_subsurface_set_position(surface->subsurface,
					   widget->allocation.x,
					   widget->allocation.y);
	}
	if (surface->allocation.width != widget->allocation.width ||
	    surface->allocation.height != widget->allocation.height) {
		window_schedule_redraw(widget->window);
	}
	surface->allocation = widget->allocation;

	if (widget->opaque)
		wl_region_add(surface->opaque_region, 0, 0,
			      widget->allocation.width,
			      widget->allocation.height);
}

static void
hack_prevent_EGL_sub_surface_deadlock(struct window *window)
{
	/*
	 * This hack should be removed, when EGL respects
	 * eglSwapInterval(0).
	 *
	 * If this window has sub-surfaces, especially a free-running
	 * EGL-widget, we need to post the parent surface once with
	 * all the old state to guarantee, that the EGL-widget will
	 * receive its frame callback soon. Otherwise, a forced call
	 * to eglSwapBuffers may end up blocking, waiting for a frame
	 * event that will never come, because we will commit the parent
	 * surface with all new state only after eglSwapBuffers returns.
	 *
	 * This assumes, that:
	 * 1. When the EGL widget's resize hook is called, it pauses.
	 * 2. When the EGL widget's redraw hook is called, it forces a
	 *    repaint and a call to eglSwapBuffers(), and maybe resumes.
	 * In a single threaded application condition 1 is a no-op.
	 *
	 * XXX: This should actually be after the surface_resize() calls,
	 * but cannot, because then it would commit the incomplete state
	 * accumulated from the widget resize hooks.
	 */
	if (window->subsurface_list.next != &window->main_surface->link ||
	    window->subsurface_list.prev != &window->main_surface->link)
		wl_surface_commit(window->main_surface->surface);
}

static void
window_do_resize(struct window *window)
{
	struct surface *surface;

	widget_set_allocation(window->main_surface->widget,
			      window->pending_allocation.x,
			      window->pending_allocation.y,
			      window->pending_allocation.width,
			      window->pending_allocation.height);

	surface_resize(window->main_surface);

	/* The main surface is in the list, too. Main surface's
	 * resize_handler is responsible for calling widget_set_allocation()
	 * on all sub-surface root widgets, so they will be resized
	 * properly.
	 */
	wl_list_for_each(surface, &window->subsurface_list, link) {
		if (surface == window->main_surface)
			continue;

		surface_set_synchronized(surface);
		surface_resize(surface);
	}

	if (!window->fullscreen && !window->maximized)
		window->saved_allocation = window->pending_allocation;
}

static void
idle_resize(struct window *window)
{
	window->resize_needed = 0;
	window->redraw_needed = 1;

	DBG("from %dx%d to %dx%d\n",
	    window->main_surface->server_allocation.width,
	    window->main_surface->server_allocation.height,
	    window->pending_allocation.width,
	    window->pending_allocation.height);

	hack_prevent_EGL_sub_surface_deadlock(window);

	window_do_resize(window);
}

static void
undo_resize(struct window *window)
{
	window->pending_allocation.width =
		window->main_surface->server_allocation.width;
	window->pending_allocation.height =
		window->main_surface->server_allocation.height;

	DBG("back to %dx%d\n",
	    window->main_surface->server_allocation.width,
	    window->main_surface->server_allocation.height);

	window_do_resize(window);

	if (window->pending_allocation.width == 0 &&
	    window->pending_allocation.height == 0) {
		fprintf(stderr, "Error: Could not draw a surface, "
			"most likely due to insufficient disk space in "
			"%s (XDG_RUNTIME_DIR).\n", getenv("XDG_RUNTIME_DIR"));
		exit(EXIT_FAILURE);
	}
}

void
window_schedule_resize(struct window *window, int width, int height)
{
	/* We should probably get these numbers from the theme. */
	const int min_width = 200, min_height = 200;

	window->pending_allocation.x = 0;
	window->pending_allocation.y = 0;
	window->pending_allocation.width = width;
	window->pending_allocation.height = height;

	if (window->min_allocation.width == 0) {
		if (width < min_width && window->frame)
			window->min_allocation.width = min_width;
		else
			window->min_allocation.width = width;
		if (height < min_height && window->frame)
			window->min_allocation.height = min_height;
		else
			window->min_allocation.height = height;
	}

	if (window->pending_allocation.width < window->min_allocation.width)
		window->pending_allocation.width = window->min_allocation.width;
	if (window->pending_allocation.height < window->min_allocation.height)
		window->pending_allocation.height = window->min_allocation.height;

	window->resize_needed = 1;
	window_schedule_redraw(window);
}

void
widget_schedule_resize(struct widget *widget, int32_t width, int32_t height)
{
	window_schedule_resize(widget->window, width, height);
}

static int
window_get_shadow_margin(struct window *window)
{
	if (window->frame)
		return frame_get_shadow_margin(window->frame->frame);
	else
		return 0;
}

static void
handle_surface_configure(void *data, struct xdg_surface *xdg_surface,
			 int32_t width, int32_t height,
			 struct wl_array *states, uint32_t serial)
{
	struct window *window = data;
	uint32_t *p;

	window->maximized = 0;
	window->fullscreen = 0;
	window->resizing = 0;
	window->focused = 0;

	wl_array_for_each(p, states) {
		uint32_t state = *p;
		switch (state) {
		case XDG_SURFACE_STATE_MAXIMIZED:
			window->maximized = 1;
			break;
		case XDG_SURFACE_STATE_FULLSCREEN:
			window->fullscreen = 1;
			break;
		case XDG_SURFACE_STATE_RESIZING:
			window->resizing = 1;
			break;
		case XDG_SURFACE_STATE_ACTIVATED:
			window->focused = 1;
			break;
		default:
			/* Unknown state */
			break;
		}
	}

	if (window->frame) {
		if (window->maximized) {
			frame_set_flag(window->frame->frame, FRAME_FLAG_MAXIMIZED);
		} else {
			frame_unset_flag(window->frame->frame, FRAME_FLAG_MAXIMIZED);
		}

		if (window->focused) {
			frame_set_flag(window->frame->frame, FRAME_FLAG_ACTIVE);
		} else {
			frame_unset_flag(window->frame->frame, FRAME_FLAG_ACTIVE);
		}
	}

	if (width > 0 && height > 0) {
		/* The width / height params are for window geometry,
		 * but window_schedule_resize takes allocation. Add
		 * on the shadow margin to get the difference. */
		int margin = window_get_shadow_margin(window);

		window_schedule_resize(window,
				       width + margin * 2,
				       height + margin * 2);
	} else {
		window_schedule_resize(window,
				       window->saved_allocation.width,
				       window->saved_allocation.height);
	}

	xdg_surface_ack_configure(window->xdg_surface, serial);

	if (window->state_changed_handler)
		window->state_changed_handler(window, window->user_data);
}

static void
handle_surface_delete(void *data, struct xdg_surface *xdg_surface)
{
	struct window *window = data;
	window_close(window);
}

static const struct xdg_surface_listener xdg_surface_listener = {
	handle_surface_configure,
	handle_surface_delete,
};

static void
window_sync_parent(struct window *window)
{
	struct wl_surface *parent_surface;

	if (!window->xdg_surface)
		return;

	if (window->parent)
		parent_surface = window->parent->main_surface->surface;
	else
		parent_surface = NULL;

	xdg_surface_set_parent(window->xdg_surface, parent_surface);
}

static void
window_get_geometry(struct window *window, struct rectangle *geometry)
{
	if (window->frame)
		frame_input_rect(window->frame->frame,
				 &geometry->x,
				 &geometry->y,
				 &geometry->width,
				 &geometry->height);
	else
		window_get_allocation(window, geometry);
}

static void
window_sync_geometry(struct window *window)
{
	struct rectangle geometry;

	if (!window->xdg_surface)
		return;

	window_get_geometry(window, &geometry);

	xdg_surface_set_window_geometry(window->xdg_surface,
					geometry.x,
					geometry.y,
					geometry.width,
					geometry.height);
}

static void
window_flush(struct window *window)
{
	struct surface *surface;

	if (!window->custom) {
		if (window->xdg_surface) {
			window_sync_parent(window);
			window_sync_geometry(window);
		}
	}

	wl_list_for_each(surface, &window->subsurface_list, link) {
		if (surface == window->main_surface)
			continue;

		surface_flush(surface);
	}

	surface_flush(window->main_surface);
}

static void
menu_destroy(struct menu *menu)
{
	widget_destroy(menu->widget);
	window_destroy(menu->window);
	frame_destroy(menu->frame);
	free(menu);
}

void
window_get_allocation(struct window *window,
		      struct rectangle *allocation)
{
	*allocation = window->main_surface->allocation;
}

static void
widget_redraw(struct widget *widget)
{
	struct widget *child;

	if (widget->redraw_handler)
		widget->redraw_handler(widget, widget->user_data);
	wl_list_for_each(child, &widget->child_list, link)
		widget_redraw(child);
}

static void
frame_callback(void *data, struct wl_callback *callback, uint32_t time)
{
	struct surface *surface = data;

	assert(callback == surface->frame_cb);
	DBG_OBJ(callback, "done\n");
	wl_callback_destroy(callback);
	surface->frame_cb = NULL;

	surface->last_time = time;

	if (surface->redraw_needed || surface->window->redraw_needed) {
		DBG_OBJ(surface->surface, "window_schedule_redraw_task\n");
		window_schedule_redraw_task(surface->window);
	}
}

static const struct wl_callback_listener listener = {
	frame_callback
};

static int
surface_redraw(struct surface *surface)
{
	DBG_OBJ(surface->surface, "begin\n");

	if (!surface->window->redraw_needed && !surface->redraw_needed)
		return 0;

	/* Whole-window redraw forces a redraw even if the previous has
	 * not yet hit the screen.
	 */
	if (surface->frame_cb) {
		if (!surface->window->redraw_needed)
			return 0;

		DBG_OBJ(surface->frame_cb, "cancelled\n");
		wl_callback_destroy(surface->frame_cb);
	}

	if (surface->widget->use_cairo &&
	    !widget_get_cairo_surface(surface->widget)) {
		DBG_OBJ(surface->surface, "cancelled due buffer failure\n");
		return -1;
	}

	surface->frame_cb = wl_surface_frame(surface->surface);
	wl_callback_add_listener(surface->frame_cb, &listener, surface);
	DBG_OBJ(surface->frame_cb, "new\n");

	surface->redraw_needed = 0;
	DBG_OBJ(surface->surface, "-> widget_redraw\n");
	widget_redraw(surface->widget);
	DBG_OBJ(surface->surface, "done\n");
	return 0;
}

static void
idle_redraw(struct task *task, uint32_t events)
{
	struct window *window = container_of(task, struct window, redraw_task);
	struct surface *surface;
	int failed = 0;
	int resized = 0;

	DBG(" --------- \n");

	wl_list_init(&window->redraw_task.link);
	window->redraw_task_scheduled = 0;

	if (window->resize_needed) {
		/* throttle resizing to the main surface display */
		if (window->main_surface->frame_cb) {
			DBG_OBJ(window->main_surface->frame_cb, "pending\n");
			return;
		}

		idle_resize(window);
		resized = 1;
	}

	if (surface_redraw(window->main_surface) < 0) {
		/*
		 * Only main_surface failure will cause us to undo the resize.
		 * If sub-surfaces fail, they will just be broken with old
		 * content.
		 */
		failed = 1;
	} else {
		wl_list_for_each(surface, &window->subsurface_list, link) {
			if (surface == window->main_surface)
				continue;

			surface_redraw(surface);
		}
	}

	window->redraw_needed = 0;
	window_flush(window);

	wl_list_for_each(surface, &window->subsurface_list, link)
		surface_set_synchronized_default(surface);

	if (resized && failed) {
		/* Restore widget tree to correspond to what is on screen. */
		undo_resize(window);
	}
}

static void
window_schedule_redraw_task(struct window *window)
{
	if (!window->redraw_task_scheduled) {
		window->redraw_task.run = idle_redraw;
		display_defer(window->display, &window->redraw_task);
		window->redraw_task_scheduled = 1;
	}
}

void
window_schedule_redraw(struct window *window)
{
	struct surface *surface;

	DBG_OBJ(window->main_surface->surface, "window %p\n", window);

	wl_list_for_each(surface, &window->subsurface_list, link)
		surface->redraw_needed = 1;

	window_schedule_redraw_task(window);
}

int
window_is_fullscreen(struct window *window)
{
	return window->fullscreen;
}

void
window_set_fullscreen(struct window *window, int fullscreen)
{
	if (!window->xdg_surface)
		return;

	if (window->fullscreen == fullscreen)
		return;

	if (fullscreen)
		xdg_surface_set_fullscreen(window->xdg_surface, NULL);
	else
		xdg_surface_unset_fullscreen(window->xdg_surface);
}

int
window_is_maximized(struct window *window)
{
	return window->maximized;
}

void
window_set_maximized(struct window *window, int maximized)
{
	if (!window->xdg_surface)
		return;

	if (window->maximized == maximized)
		return;

	if (maximized)
		xdg_surface_set_maximized(window->xdg_surface);
	else
		xdg_surface_unset_maximized(window->xdg_surface);
}

int
window_is_resizing(struct window *window)
{
	return window->resizing;
}

void
window_set_minimized(struct window *window)
{
	if (!window->xdg_surface)
		return;

	xdg_surface_set_minimized(window->xdg_surface);
}

void
window_set_user_data(struct window *window, void *data)
{
	window->user_data = data;
}

void *
window_get_user_data(struct window *window)
{
	return window->user_data;
}

void
window_set_key_handler(struct window *window,
		       window_key_handler_t handler)
{
	window->key_handler = handler;
}

void
window_set_keyboard_focus_handler(struct window *window,
				  window_keyboard_focus_handler_t handler)
{
	window->keyboard_focus_handler = handler;
}

void
window_set_data_handler(struct window *window, window_data_handler_t handler)
{
	window->data_handler = handler;
}

void
window_set_drop_handler(struct window *window, window_drop_handler_t handler)
{
	window->drop_handler = handler;
}

void
window_set_close_handler(struct window *window,
			 window_close_handler_t handler)
{
	window->close_handler = handler;
}

void
window_set_fullscreen_handler(struct window *window,
			      window_fullscreen_handler_t handler)
{
	window->fullscreen_handler = handler;
}

void
window_set_output_handler(struct window *window,
			  window_output_handler_t handler)
{
	window->output_handler = handler;
}

void
window_set_state_changed_handler(struct window *window,
				 window_state_changed_handler_t handler)
{
	window->state_changed_handler = handler;
}

void
window_set_title(struct window *window, const char *title)
{
	free(window->title);
	window->title = strdup(title);
	if (window->frame) {
		frame_set_title(window->frame->frame, title);
		widget_schedule_redraw(window->frame->widget);
	}
	if (window->xdg_surface)
		xdg_surface_set_title(window->xdg_surface, title);
}

const char *
window_get_title(struct window *window)
{
	return window->title;
}

void
window_set_text_cursor_position(struct window *window, int32_t x, int32_t y)
{
	struct text_cursor_position *text_cursor_position =
					window->display->text_cursor_position;

	if (!text_cursor_position)
		return;

	text_cursor_position_notify(text_cursor_position,
				    window->main_surface->surface,
				    wl_fixed_from_int(x),
				    wl_fixed_from_int(y));
}

void
window_damage(struct window *window, int32_t x, int32_t y,
	      int32_t width, int32_t height)
{
	wl_surface_damage(window->main_surface->surface, x, y, width, height);
}

static void
surface_enter(void *data,
	      struct wl_surface *wl_surface, struct wl_output *wl_output)
{
	struct window *window = data;
	struct output *output;
	struct output *output_found = NULL;
	struct window_output *window_output;

	wl_list_for_each(output, &window->display->output_list, link) {
		if (output->output == wl_output) {
			output_found = output;
			break;
		}
	}

	if (!output_found)
		return;

	window_output = xmalloc(sizeof *window_output);
	window_output->output = output_found;

	wl_list_insert (&window->window_output_list, &window_output->link);

	if (window->output_handler)
		window->output_handler(window, output_found, 1,
				       window->user_data);
}

static void
surface_leave(void *data,
	      struct wl_surface *wl_surface, struct wl_output *output)
{
	struct window *window = data;
	struct window_output *window_output;
	struct window_output *window_output_found = NULL;

	wl_list_for_each(window_output, &window->window_output_list, link) {
		if (window_output->output->output == output) {
			window_output_found = window_output;
			break;
		}
	}

	if (window_output_found) {
		wl_list_remove(&window_output_found->link);

		if (window->output_handler)
			window->output_handler(window, window_output->output,
					       0, window->user_data);

		free(window_output_found);
	}
}

static const struct wl_surface_listener surface_listener = {
	surface_enter,
	surface_leave
};

static struct surface *
surface_create(struct window *window)
{
	struct display *display = window->display;
	struct surface *surface;

	surface = xmalloc(sizeof *surface);
	memset(surface, 0, sizeof *surface);
	if (!surface)
		return NULL;

	surface->window = window;
	surface->surface = wl_compositor_create_surface(display->compositor);
	surface->buffer_scale = 1;
	wl_surface_add_listener(surface->surface, &surface_listener, window);

	wl_list_insert(&window->subsurface_list, &surface->link);

	return surface;
}

static enum window_buffer_type
get_preferred_buffer_type(struct display *display)
{
#ifdef HAVE_CAIRO_EGL
	if (display->argb_device && !getenv("TOYTOOLKIT_NO_EGL"))
		return WINDOW_BUFFER_TYPE_EGL_WINDOW;
#endif

	return WINDOW_BUFFER_TYPE_SHM;
}

static struct window *
window_create_internal(struct display *display, int custom)
{
	struct window *window;
	struct surface *surface;

	window = xzalloc(sizeof *window);
	wl_list_init(&window->subsurface_list);
	window->display = display;

	surface = surface_create(window);
	window->main_surface = surface;

	assert(custom || display->xdg_shell);

	window->custom = custom;
	window->preferred_format = WINDOW_PREFERRED_FORMAT_NONE;

	surface->buffer_type = get_preferred_buffer_type(display);

	wl_surface_set_user_data(surface->surface, window);
	wl_list_insert(display->window_list.prev, &window->link);
	wl_list_init(&window->redraw_task.link);

	wl_list_init (&window->window_output_list);

	return window;
}

struct window *
window_create(struct display *display)
{
	struct window *window;

	window = window_create_internal(display, 0);

	window->xdg_surface =
		xdg_shell_get_xdg_surface(window->display->xdg_shell,
					  window->main_surface->surface);
	fail_on_null(window->xdg_surface);

	xdg_surface_set_user_data(window->xdg_surface, window);
	xdg_surface_add_listener(window->xdg_surface,
				 &xdg_surface_listener, window);

	return window;
}

struct window *
window_create_custom(struct display *display)
{
	return window_create_internal(display, 1);
}

void
window_set_parent(struct window *window,
		  struct window *parent_window)
{
	window->parent = parent_window;
	window_sync_parent(window);
}

struct window *
window_get_parent(struct window *window)
{
	return window->parent;
}

static void
menu_set_item(struct menu *menu, int sy)
{
	int32_t x, y, width, height;
	int next;

	frame_interior(menu->frame, &x, &y, &width, &height);
	next = (sy - y) / 20;
	if (menu->current != next) {
		menu->current = next;
		widget_schedule_redraw(menu->widget);
	}
}

static int
menu_motion_handler(struct widget *widget,
		    struct input *input, uint32_t time,
		    float x, float y, void *data)
{
	struct menu *menu = data;

	if (widget == menu->widget)
		menu_set_item(data, y);

	return CURSOR_LEFT_PTR;
}

static int
menu_enter_handler(struct widget *widget,
		   struct input *input, float x, float y, void *data)
{
	struct menu *menu = data;

	if (widget == menu->widget)
		menu_set_item(data, y);

	return CURSOR_LEFT_PTR;
}

static void
menu_leave_handler(struct widget *widget, struct input *input, void *data)
{
	struct menu *menu = data;

	if (widget == menu->widget)
		menu_set_item(data, -200);
}

static void
menu_button_handler(struct widget *widget,
		    struct input *input, uint32_t time,
		    uint32_t button, enum wl_pointer_button_state state,
		    void *data)

{
	struct menu *menu = data;

	if (state == WL_POINTER_BUTTON_STATE_RELEASED &&
	    (menu->release_count > 0 || time - menu->time > 500)) {
		/* Either relase after press-drag-release or
		 * click-motion-click. */
		menu->func(menu->user_data, input, menu->current);
		input_ungrab(input);
		menu_destroy(menu);
	} else if (state == WL_POINTER_BUTTON_STATE_RELEASED) {
		menu->release_count++;
	}
}

static void
menu_touch_up_handler(struct widget *widget,
					  struct input *input,
					  uint32_t serial,
					  uint32_t time,
					  int32_t id,
					  void *data)
{
	struct menu *menu = data;

	input_ungrab(input);
	menu_destroy(menu);
}

static void
menu_redraw_handler(struct widget *widget, void *data)
{
	cairo_t *cr;
	struct menu *menu = data;
	int32_t x, y, width, height, i;

	cr = widget_cairo_create(widget);

	frame_repaint(menu->frame, cr);
	frame_interior(menu->frame, &x, &y, &width, &height);

	theme_set_background_source(menu->window->display->theme,
				    cr, THEME_FRAME_ACTIVE);
	cairo_rectangle(cr, x, y, width, height);
	cairo_fill(cr);

	cairo_select_font_face(cr, "sans",
			       CAIRO_FONT_SLANT_NORMAL,
			       CAIRO_FONT_WEIGHT_NORMAL);
	cairo_set_font_size(cr, 12);

	for (i = 0; i < menu->count; i++) {
		if (i == menu->current) {
			cairo_set_source_rgb(cr, 1.0, 1.0, 1.0);
			cairo_rectangle(cr, x, y + i * 20, width, 20);
			cairo_fill(cr);
			cairo_set_source_rgb(cr, 0.0, 0.0, 0.0);
			cairo_move_to(cr, x + 10, y + i * 20 + 16);
			cairo_show_text(cr, menu->entries[i]);
		} else {
			cairo_set_source_rgb(cr, 0.0, 0.0, 0.0);
			cairo_move_to(cr, x + 10, y + i * 20 + 16);
			cairo_show_text(cr, menu->entries[i]);
		}
	}

	cairo_destroy(cr);
}

static void
handle_popup_popup_done(void *data, struct xdg_popup *xdg_popup, uint32_t serial)
{
	struct window *window = data;
	struct menu *menu = window->main_surface->widget->user_data;

	input_ungrab(menu->input);
	menu_destroy(menu);
}

static const struct xdg_popup_listener xdg_popup_listener = {
	handle_popup_popup_done,
};

static struct menu *
create_menu(struct display *display,
	    struct input *input, uint32_t time,
	    menu_func_t func, const char **entries, int count,
	    void *user_data)
{
	struct window *window;
	struct menu *menu;

	menu = malloc(sizeof *menu);
	if (!menu)
		return NULL;

	window = window_create_internal(display, 0);
	if (!window) {
		free(menu);
		return NULL;
	}

	menu->window = window;
	menu->user_data = user_data;
	menu->widget = window_add_widget(menu->window, menu);
	menu->frame = frame_create(window->display->theme, 0, 0,
				   FRAME_BUTTON_NONE, NULL);
	fail_on_null(menu->frame);
	menu->entries = entries;
	menu->count = count;
	menu->release_count = 0;
	menu->current = -1;
	menu->time = time;
	menu->func = func;
	menu->input = input;

	input_ungrab(input);

	widget_set_redraw_handler(menu->widget, menu_redraw_handler);
	widget_set_enter_handler(menu->widget, menu_enter_handler);
	widget_set_leave_handler(menu->widget, menu_leave_handler);
	widget_set_motion_handler(menu->widget, menu_motion_handler);
	widget_set_button_handler(menu->widget, menu_button_handler);
	widget_set_touch_up_handler(menu->widget, menu_touch_up_handler);

	input_grab(input, menu->widget, 0);
	frame_resize_inside(menu->frame, 200, count * 20);
	frame_set_flag(menu->frame, FRAME_FLAG_ACTIVE);
	window_schedule_resize(window, frame_width(menu->frame),
			       frame_height(menu->frame));

	return menu;
}

struct window *
window_create_menu(struct display *display,
		   struct input *input, uint32_t time,
		   menu_func_t func, const char **entries, int count,
		   void *user_data)
{
	struct menu *menu;
	menu = create_menu(display, input, time, func, entries, count, user_data);

	if (menu == NULL)
		return NULL;

	return menu->window;
}

void
window_show_menu(struct display *display,
		 struct input *input, uint32_t time, struct window *parent,
		 int32_t x, int32_t y,
		 menu_func_t func, const char **entries, int count)
{
	struct menu *menu;
	struct window *window;
	int32_t ix, iy;

	menu = create_menu(display, input, time, func, entries, count, parent);

	if (menu == NULL)
		return;

	window = menu->window;

	window_set_buffer_scale (menu->window, window_get_buffer_scale (parent));
	window_set_buffer_transform (menu->window, window_get_buffer_transform (parent));

	window->x = x;
	window->y = y;

	frame_interior(menu->frame, &ix, &iy, NULL, NULL);

	window->xdg_popup = xdg_shell_get_xdg_popup(display->xdg_shell,
						    window->main_surface->surface,
						    parent->main_surface->surface,
						    input->seat,
						    display_get_serial(window->display),
						    window->x - ix,
						    window->y - iy,
						    0);
	fail_on_null(window->xdg_popup);

	xdg_popup_set_user_data(window->xdg_popup, window);
	xdg_popup_add_listener(window->xdg_popup,
			       &xdg_popup_listener, window);
}

void
window_set_buffer_type(struct window *window, enum window_buffer_type type)
{
	window->main_surface->buffer_type = type;
}

enum window_buffer_type
window_get_buffer_type(struct window *window)
{
	return window->main_surface->buffer_type;
}

void
window_set_preferred_format(struct window *window,
			    enum preferred_format format)
{
	window->preferred_format = format;
}

struct widget *
window_add_subsurface(struct window *window, void *data,
		      enum subsurface_mode default_mode)
{
	struct widget *widget;
	struct surface *surface;
	struct wl_surface *parent;
	struct wl_subcompositor *subcompo = window->display->subcompositor;

	surface = surface_create(window);
	surface->buffer_type = window_get_buffer_type(window);
	widget = widget_create(window, surface, data);
	wl_list_init(&widget->link);
	surface->widget = widget;

	parent = window->main_surface->surface;
	surface->subsurface = wl_subcompositor_get_subsurface(subcompo,
							      surface->surface,
							      parent);
	surface->synchronized = 1;

	switch (default_mode) {
	case SUBSURFACE_SYNCHRONIZED:
		surface->synchronized_default = 1;
		break;
	case SUBSURFACE_DESYNCHRONIZED:
		surface->synchronized_default = 0;
		break;
	default:
		assert(!"bad enum subsurface_mode");
	}

	window->resize_needed = 1;
	window_schedule_redraw(window);

	return widget;
}

static void
display_handle_geometry(void *data,
			struct wl_output *wl_output,
			int x, int y,
			int physical_width,
			int physical_height,
			int subpixel,
			const char *make,
			const char *model,
			int transform)
{
	struct output *output = data;

	output->allocation.x = x;
	output->allocation.y = y;
	output->transform = transform;

	if (output->make)
		free(output->make);
	output->make = strdup(make);

	if (output->model)
		free(output->model);
	output->model = strdup(model);
}

static void
display_handle_done(void *data,
		     struct wl_output *wl_output)
{
}

static void
display_handle_scale(void *data,
		     struct wl_output *wl_output,
		     int32_t scale)
{
	struct output *output = data;

	output->scale = scale;
}

static void
display_handle_mode(void *data,
		    struct wl_output *wl_output,
		    uint32_t flags,
		    int width,
		    int height,
		    int refresh)
{
	struct output *output = data;
	struct display *display = output->display;

	if (flags & WL_OUTPUT_MODE_CURRENT) {
		output->allocation.width = width;
		output->allocation.height = height;
		if (display->output_configure_handler)
			(*display->output_configure_handler)(
						output, display->user_data);
	}
}

static const struct wl_output_listener output_listener = {
	display_handle_geometry,
	display_handle_mode,
	display_handle_done,
	display_handle_scale
};

static void
display_add_output(struct display *d, uint32_t id)
{
	struct output *output;

	output = xzalloc(sizeof *output);
	output->display = d;
	output->scale = 1;
	output->output =
		wl_registry_bind(d->registry, id, &wl_output_interface, 2);
	output->server_output_id = id;
	wl_list_insert(d->output_list.prev, &output->link);

	wl_output_add_listener(output->output, &output_listener, output);
}

static void
output_destroy(struct output *output)
{
	if (output->destroy_handler)
		(*output->destroy_handler)(output, output->user_data);

	wl_output_destroy(output->output);
	wl_list_remove(&output->link);
	free(output);
}

static void
display_destroy_output(struct display *d, uint32_t id)
{
	struct output *output;

	wl_list_for_each(output, &d->output_list, link) {
		if (output->server_output_id == id) {
			output_destroy(output);
			break;
		}
	}
}

void
display_set_global_handler(struct display *display,
			   display_global_handler_t handler)
{
	struct global *global;

	display->global_handler = handler;
	if (!handler)
		return;

	wl_list_for_each(global, &display->global_list, link)
		display->global_handler(display,
					global->name, global->interface,
					global->version, display->user_data);
}

void
display_set_global_handler_remove(struct display *display,
			   display_global_handler_t remove_handler)
{
	display->global_handler_remove = remove_handler;
	if (!remove_handler)
		return;
}

void
display_set_output_configure_handler(struct display *display,
				     display_output_handler_t handler)
{
	struct output *output;

	display->output_configure_handler = handler;
	if (!handler)
		return;

	wl_list_for_each(output, &display->output_list, link) {
		if (output->allocation.width == 0 &&
		    output->allocation.height == 0)
			continue;

		(*display->output_configure_handler)(output,
						     display->user_data);
	}
}

void
output_set_user_data(struct output *output, void *data)
{
	output->user_data = data;
}

void *
output_get_user_data(struct output *output)
{
	return output->user_data;
}

void
output_set_destroy_handler(struct output *output,
			   display_output_handler_t handler)
{
	output->destroy_handler = handler;
	/* FIXME: implement this, once we have way to remove outputs */
}

void
output_get_allocation(struct output *output, struct rectangle *base)
{
	struct rectangle allocation = output->allocation;

	switch (output->transform) {
	case WL_OUTPUT_TRANSFORM_90:
	case WL_OUTPUT_TRANSFORM_270:
	case WL_OUTPUT_TRANSFORM_FLIPPED_90:
	case WL_OUTPUT_TRANSFORM_FLIPPED_270:
	        /* Swap width and height */
	        allocation.width = output->allocation.height;
	        allocation.height = output->allocation.width;
	        break;
	}

	*base = allocation;
}

struct wl_output *
output_get_wl_output(struct output *output)
{
	return output->output;
}

enum wl_output_transform
output_get_transform(struct output *output)
{
	return output->transform;
}

uint32_t
output_get_scale(struct output *output)
{
	return output->scale;
}

const char *
output_get_make(struct output *output)
{
	return output->make;
}

const char *
output_get_model(struct output *output)
{
	return output->model;
}

static void
fini_xkb(struct input *input)
{
	xkb_state_unref(input->xkb.state);
	xkb_map_unref(input->xkb.keymap);
}

#define MIN(a,b) ((a) < (b) ? a : b)

static void
display_add_input(struct display *d, uint32_t id)
{
	struct input *input;

	input = xzalloc(sizeof *input);
	input->display = d;
	input->seat = wl_registry_bind(d->registry, id, &wl_seat_interface,
				       MIN(d->seat_version, 3));
	input->touch_focus = NULL;
	input->pointer_focus = NULL;
	input->keyboard_focus = NULL;
	wl_list_init(&input->touch_point_list);
	wl_list_insert(d->input_list.prev, &input->link);

	wl_seat_add_listener(input->seat, &seat_listener, input);
	wl_seat_set_user_data(input->seat, input);

	if (d->data_device_manager) {
		input->data_device =
			wl_data_device_manager_get_data_device(d->data_device_manager,
							       input->seat);
		wl_data_device_add_listener(input->data_device,
					    &data_device_listener,
					    input);
	}

	input->pointer_surface = wl_compositor_create_surface(d->compositor);

	input->repeat_timer_fd = timerfd_create(CLOCK_MONOTONIC,
						TFD_CLOEXEC | TFD_NONBLOCK);
	input->repeat_task.run = keyboard_repeat_func;
	display_watch_fd(d, input->repeat_timer_fd,
			 EPOLLIN, &input->repeat_task);
}

static void
input_destroy(struct input *input)
{
	input_remove_keyboard_focus(input);
	input_remove_pointer_focus(input);

	if (input->drag_offer)
		data_offer_destroy(input->drag_offer);

	if (input->selection_offer)
		data_offer_destroy(input->selection_offer);

	if (input->data_device)
		wl_data_device_destroy(input->data_device);

	if (input->display->seat_version >= 3) {
		if (input->pointer)
			wl_pointer_release(input->pointer);
		if (input->keyboard)
			wl_keyboard_release(input->keyboard);
	}

	fini_xkb(input);

	wl_surface_destroy(input->pointer_surface);

	wl_list_remove(&input->link);
	wl_seat_destroy(input->seat);
	close(input->repeat_timer_fd);
	free(input);
}

static void
init_workspace_manager(struct display *d, uint32_t id)
{
	d->workspace_manager =
		wl_registry_bind(d->registry, id,
				 &workspace_manager_interface, 1);
	if (d->workspace_manager != NULL)
		workspace_manager_add_listener(d->workspace_manager,
					       &workspace_manager_listener,
					       d);
}

static void
shm_format(void *data, struct wl_shm *wl_shm, uint32_t format)
{
	struct display *d = data;

	if (format == WL_SHM_FORMAT_RGB565)
		d->has_rgb565 = 1;
}

struct wl_shm_listener shm_listener = {
	shm_format
};

static void
xdg_shell_ping(void *data, struct xdg_shell *shell, uint32_t serial)
{
	xdg_shell_pong(shell, serial);
}

static const struct xdg_shell_listener xdg_shell_listener = {
	xdg_shell_ping,
};

#define XDG_VERSION 3 /* The version of xdg-shell that we implement */
#ifdef static_assert
static_assert(XDG_VERSION == XDG_SHELL_VERSION_CURRENT,
	      "Interface version doesn't match implementation version");
#endif

static void
registry_handle_global(void *data, struct wl_registry *registry, uint32_t id,
		       const char *interface, uint32_t version)
{
	struct display *d = data;
	struct global *global;

	global = xmalloc(sizeof *global);
	global->name = id;
	global->interface = strdup(interface);
	global->version = version;
	wl_list_insert(d->global_list.prev, &global->link);

	if (strcmp(interface, "wl_compositor") == 0) {
		d->compositor = wl_registry_bind(registry, id,
						 &wl_compositor_interface, 3);
	} else if (strcmp(interface, "wl_output") == 0) {
		display_add_output(d, id);
	} else if (strcmp(interface, "wl_seat") == 0) {
		d->seat_version = version;
		display_add_input(d, id);
	} else if (strcmp(interface, "wl_shm") == 0) {
		d->shm = wl_registry_bind(registry, id, &wl_shm_interface, 1);
		wl_shm_add_listener(d->shm, &shm_listener, d);
	} else if (strcmp(interface, "wl_data_device_manager") == 0) {
		d->data_device_manager =
			wl_registry_bind(registry, id,
					 &wl_data_device_manager_interface, 1);
	} else if (strcmp(interface, "xdg_shell") == 0) {
		d->xdg_shell = wl_registry_bind(registry, id,
						&xdg_shell_interface, 1);
		xdg_shell_use_unstable_version(d->xdg_shell, XDG_VERSION);
		xdg_shell_add_listener(d->xdg_shell, &xdg_shell_listener, d);
	} else if (strcmp(interface, "text_cursor_position") == 0) {
		d->text_cursor_position =
			wl_registry_bind(registry, id,
					 &text_cursor_position_interface, 1);
	} else if (strcmp(interface, "workspace_manager") == 0) {
		init_workspace_manager(d, id);
	} else if (strcmp(interface, "wl_subcompositor") == 0) {
		d->subcompositor =
			wl_registry_bind(registry, id,
					 &wl_subcompositor_interface, 1);
	}

	if (d->global_handler)
		d->global_handler(d, id, interface, version, d->user_data);
}

static void
registry_handle_global_remove(void *data, struct wl_registry *registry,
			      uint32_t name)
{
	struct display *d = data;
	struct global *global;
	struct global *tmp;

	wl_list_for_each_safe(global, tmp, &d->global_list, link) {
		if (global->name != name)
			continue;

		if (strcmp(global->interface, "wl_output") == 0)
			display_destroy_output(d, name);

		/* XXX: Should destroy remaining bound globals */

		if (d->global_handler_remove)
			d->global_handler_remove(d, name, global->interface,
					global->version, d->user_data);

		wl_list_remove(&global->link);
		free(global->interface);
		free(global);
	}
}

void *
display_bind(struct display *display, uint32_t name,
	     const struct wl_interface *interface, uint32_t version)
{
	return wl_registry_bind(display->registry, name, interface, version);
}

static const struct wl_registry_listener registry_listener = {
	registry_handle_global,
	registry_handle_global_remove
};

#ifdef HAVE_CAIRO_EGL
static int
init_egl(struct display *d)
{
	EGLint major, minor;
	EGLint n;

#ifdef USE_CAIRO_GLESV2
#  define GL_BIT EGL_OPENGL_ES2_BIT
#else
#  define GL_BIT EGL_OPENGL_BIT
#endif

	static const EGLint argb_cfg_attribs[] = {
		EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
		EGL_RED_SIZE, 1,
		EGL_GREEN_SIZE, 1,
		EGL_BLUE_SIZE, 1,
		EGL_ALPHA_SIZE, 1,
		EGL_DEPTH_SIZE, 1,
		EGL_RENDERABLE_TYPE, GL_BIT,
		EGL_NONE
	};

#ifdef USE_CAIRO_GLESV2
	static const EGLint context_attribs[] = {
		EGL_CONTEXT_CLIENT_VERSION, 2,
		EGL_NONE
	};
	EGLint api = EGL_OPENGL_ES_API;
#else
	EGLint *context_attribs = NULL;
	EGLint api = EGL_OPENGL_API;
#endif

	d->dpy = eglGetDisplay(d->display);
	if (!eglInitialize(d->dpy, &major, &minor)) {
		fprintf(stderr, "failed to initialize EGL\n");
		return -1;
	}

	if (!eglBindAPI(api)) {
		fprintf(stderr, "failed to bind EGL client API\n");
		return -1;
	}

	if (!eglChooseConfig(d->dpy, argb_cfg_attribs,
			     &d->argb_config, 1, &n) || n != 1) {
		fprintf(stderr, "failed to choose argb EGL config\n");
		return -1;
	}

	d->argb_ctx = eglCreateContext(d->dpy, d->argb_config,
				       EGL_NO_CONTEXT, context_attribs);
	if (d->argb_ctx == NULL) {
		fprintf(stderr, "failed to create EGL context\n");
		return -1;
	}

	d->argb_device = cairo_egl_device_create(d->dpy, d->argb_ctx);
	if (cairo_device_status(d->argb_device) != CAIRO_STATUS_SUCCESS) {
		fprintf(stderr, "failed to get cairo EGL argb device\n");
		return -1;
	}

	return 0;
}

static void
fini_egl(struct display *display)
{
	cairo_device_destroy(display->argb_device);

	eglMakeCurrent(display->dpy, EGL_NO_SURFACE, EGL_NO_SURFACE,
		       EGL_NO_CONTEXT);

	eglTerminate(display->dpy);
	eglReleaseThread();
}
#endif

static void
init_dummy_surface(struct display *display)
{
	int len;
	void *data;

	len = cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, 1);
	data = malloc(len);
	display->dummy_surface =
		cairo_image_surface_create_for_data(data, CAIRO_FORMAT_ARGB32,
						    1, 1, len);
	display->dummy_surface_data = data;
}

static void
handle_display_data(struct task *task, uint32_t events)
{
	struct display *display =
		container_of(task, struct display, display_task);
	struct epoll_event ep;
	int ret;

	display->display_fd_events = events;

	if (events & EPOLLERR || events & EPOLLHUP) {
		display_exit(display);
		return;
	}

	if (events & EPOLLIN) {
		ret = wl_display_dispatch(display->display);
		if (ret == -1) {
			display_exit(display);
			return;
		}
	}

	if (events & EPOLLOUT) {
		ret = wl_display_flush(display->display);
		if (ret == 0) {
			ep.events = EPOLLIN | EPOLLERR | EPOLLHUP;
			ep.data.ptr = &display->display_task;
			epoll_ctl(display->epoll_fd, EPOLL_CTL_MOD,
				  display->display_fd, &ep);
		} else if (ret == -1 && errno != EAGAIN) {
			display_exit(display);
			return;
		}
	}
}

static void
log_handler(const char *format, va_list args)
{
	vfprintf(stderr, format, args);
}

struct display *
display_create(int *argc, char *argv[])
{
	struct display *d;

	wl_log_set_handler_client(log_handler);

	d = zalloc(sizeof *d);
	if (d == NULL)
		return NULL;

	d->display = wl_display_connect(NULL);
	if (d->display == NULL) {
		fprintf(stderr, "failed to connect to Wayland display: %m\n");
		free(d);
		return NULL;
	}

	d->xkb_context = xkb_context_new(0);
	if (d->xkb_context == NULL) {
		fprintf(stderr, "Failed to create XKB context\n");
		free(d);
		return NULL;
	}

	d->epoll_fd = os_epoll_create_cloexec();
	d->display_fd = wl_display_get_fd(d->display);
	d->display_task.run = handle_display_data;
	display_watch_fd(d, d->display_fd, EPOLLIN | EPOLLERR | EPOLLHUP,
			 &d->display_task);

	wl_list_init(&d->deferred_list);
	wl_list_init(&d->input_list);
	wl_list_init(&d->output_list);
	wl_list_init(&d->global_list);

	d->workspace = 0;
	d->workspace_count = 1;

	d->registry = wl_display_get_registry(d->display);
	wl_registry_add_listener(d->registry, &registry_listener, d);

	if (wl_display_dispatch(d->display) < 0) {
		fprintf(stderr, "Failed to process Wayland connection: %m\n");
		return NULL;
	}

#ifdef HAVE_CAIRO_EGL
	if (init_egl(d) < 0)
		fprintf(stderr, "EGL does not seem to work, "
			"falling back to software rendering and wl_shm.\n");
#endif

	create_cursors(d);

	d->theme = theme_create();

	wl_list_init(&d->window_list);

	init_dummy_surface(d);

	return d;
}

static void
display_destroy_outputs(struct display *display)
{
	struct output *tmp;
	struct output *output;

	wl_list_for_each_safe(output, tmp, &display->output_list, link)
		output_destroy(output);
}

static void
display_destroy_inputs(struct display *display)
{
	struct input *tmp;
	struct input *input;

	wl_list_for_each_safe(input, tmp, &display->input_list, link)
		input_destroy(input);
}

void
display_destroy(struct display *display)
{
	if (!wl_list_empty(&display->window_list))
		fprintf(stderr, "toytoolkit warning: %d windows exist.\n",
			wl_list_length(&display->window_list));

	if (!wl_list_empty(&display->deferred_list))
		fprintf(stderr, "toytoolkit warning: deferred tasks exist.\n");

	cairo_surface_destroy(display->dummy_surface);
	free(display->dummy_surface_data);

	display_destroy_outputs(display);
	display_destroy_inputs(display);

	xkb_context_unref(display->xkb_context);

	theme_destroy(display->theme);
	destroy_cursors(display);

#ifdef HAVE_CAIRO_EGL
	if (display->argb_device)
		fini_egl(display);
#endif

	if (display->subcompositor)
		wl_subcompositor_destroy(display->subcompositor);

	if (display->xdg_shell)
		xdg_shell_destroy(display->xdg_shell);

	if (display->shm)
		wl_shm_destroy(display->shm);

	if (display->data_device_manager)
		wl_data_device_manager_destroy(display->data_device_manager);

	wl_compositor_destroy(display->compositor);
	wl_registry_destroy(display->registry);

	close(display->epoll_fd);

	if (!(display->display_fd_events & EPOLLERR) &&
	    !(display->display_fd_events & EPOLLHUP))
		wl_display_flush(display->display);

	wl_display_disconnect(display->display);
	free(display);
}

void
display_set_user_data(struct display *display, void *data)
{
	display->user_data = data;
}

void *
display_get_user_data(struct display *display)
{
	return display->user_data;
}

struct wl_display *
display_get_display(struct display *display)
{
	return display->display;
}

int
display_has_subcompositor(struct display *display)
{
	if (display->subcompositor)
		return 1;

	wl_display_roundtrip(display->display);

	return display->subcompositor != NULL;
}

cairo_device_t *
display_get_cairo_device(struct display *display)
{
	return display->argb_device;
}

struct output *
display_get_output(struct display *display)
{
	return container_of(display->output_list.next, struct output, link);
}

struct wl_compositor *
display_get_compositor(struct display *display)
{
	return display->compositor;
}

uint32_t
display_get_serial(struct display *display)
{
	return display->serial;
}

EGLDisplay
display_get_egl_display(struct display *d)
{
	return d->dpy;
}

struct wl_data_source *
display_create_data_source(struct display *display)
{
	if (display->data_device_manager)
		return wl_data_device_manager_create_data_source(display->data_device_manager);
	else
		return NULL;
}

EGLConfig
display_get_argb_egl_config(struct display *d)
{
	return d->argb_config;
}

int
display_acquire_window_surface(struct display *display,
			       struct window *window,
			       EGLContext ctx)
{
	struct surface *surface = window->main_surface;

	if (surface->buffer_type != WINDOW_BUFFER_TYPE_EGL_WINDOW)
		return -1;

	widget_get_cairo_surface(window->main_surface->widget);
	return surface->toysurface->acquire(surface->toysurface, ctx);
}

void
display_release_window_surface(struct display *display,
			       struct window *window)
{
	struct surface *surface = window->main_surface;

	if (surface->buffer_type != WINDOW_BUFFER_TYPE_EGL_WINDOW)
		return;

	surface->toysurface->release(surface->toysurface);
}

void
display_defer(struct display *display, struct task *task)
{
	wl_list_insert(&display->deferred_list, &task->link);
}

void
display_watch_fd(struct display *display,
		 int fd, uint32_t events, struct task *task)
{
	struct epoll_event ep;

	ep.events = events;
	ep.data.ptr = task;
	epoll_ctl(display->epoll_fd, EPOLL_CTL_ADD, fd, &ep);
}

void
display_unwatch_fd(struct display *display, int fd)
{
	epoll_ctl(display->epoll_fd, EPOLL_CTL_DEL, fd, NULL);
}

void
display_run(struct display *display)
{
	struct task *task;
	struct epoll_event ep[16];
	int i, count, ret;

	display->running = 1;
	while (1) {
		while (!wl_list_empty(&display->deferred_list)) {
			task = container_of(display->deferred_list.prev,
					    struct task, link);
			wl_list_remove(&task->link);
			task->run(task, 0);
		}

		wl_display_dispatch_pending(display->display);

		if (!display->running)
			break;

		ret = wl_display_flush(display->display);
		if (ret < 0 && errno == EAGAIN) {
			ep[0].events =
				EPOLLIN | EPOLLOUT | EPOLLERR | EPOLLHUP;
			ep[0].data.ptr = &display->display_task;

			epoll_ctl(display->epoll_fd, EPOLL_CTL_MOD,
				  display->display_fd, &ep[0]);
		} else if (ret < 0) {
			break;
		}

		count = epoll_wait(display->epoll_fd,
				   ep, ARRAY_LENGTH(ep), -1);
		for (i = 0; i < count; i++) {
			task = ep[i].data.ptr;
			task->run(task, ep[i].events);
		}
	}
}

void
display_exit(struct display *display)
{
	display->running = 0;
}

void
keysym_modifiers_add(struct wl_array *modifiers_map,
		     const char *name)
{
	size_t len = strlen(name) + 1;
	char *p;

	p = wl_array_add(modifiers_map, len);

	if (p == NULL)
		return;

	strncpy(p, name, len);
}

static xkb_mod_index_t
keysym_modifiers_get_index(struct wl_array *modifiers_map,
			   const char *name)
{
	xkb_mod_index_t index = 0;
	char *p = modifiers_map->data;

	while ((const char *)p < (const char *)(modifiers_map->data + modifiers_map->size)) {
		if (strcmp(p, name) == 0)
			return index;

		index++;
		p += strlen(p) + 1;
	}

	return XKB_MOD_INVALID;
}

xkb_mod_mask_t
keysym_modifiers_get_mask(struct wl_array *modifiers_map,
			  const char *name)
{
	xkb_mod_index_t index = keysym_modifiers_get_index(modifiers_map, name);

	if (index == XKB_MOD_INVALID)
		return XKB_MOD_INVALID;

	return 1 << index;
}

void *
fail_on_null(void *p)
{
	if (p == NULL) {
		fprintf(stderr, "%s: out of memory\n", program_invocation_short_name);
		exit(EXIT_FAILURE);
	}

	return p;
}

void *
xmalloc(size_t s)
{
	return fail_on_null(malloc(s));
}

void *
xzalloc(size_t s)
{
	return fail_on_null(zalloc(s));
}

char *
xstrdup(const char *s)
{
	return fail_on_null(strdup(s));
}

void *
xrealloc(char *p, size_t s)
{
	return fail_on_null(realloc(p, s));
}