summaryrefslogtreecommitdiff
path: root/app/xrandr/xrandr.c
blob: 24b483edfb8bad6300938fc67a550927d28f379d (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
/* 
 * Copyright © 2001 Keith Packard, member of The XFree86 Project, Inc.
 * Copyright © 2002 Hewlett Packard Company, Inc.
 * Copyright © 2006 Intel Corporation
 * Copyright © 2013 NVIDIA Corporation
 *
 * 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.
 *
 * Thanks to Jim Gettys who wrote most of the client side code,
 * and part of the server code for randr.
 */

#include <stdio.h>
#include <X11/Xlib.h>
#include <X11/Xlibint.h>
#include <X11/Xproto.h>
#include <X11/Xatom.h>
#include <X11/extensions/Xrandr.h>
#include <X11/extensions/Xrender.h>	/* we share subpixel information */
#include <strings.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
#include <stdarg.h>
#include <math.h>

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

static char	*program_name;
static Display	*dpy;
static Window	root;
static int	screen = -1;
static Bool	verbose = False;
static Bool	automatic = False;
static Bool	properties = False;
static Bool	grab_server = True;
static Bool	no_primary = False;
static int	filter_type = -1;

static const char *filter_names[2] = {
    "bilinear",
    "nearest"};

static const char *direction[5] = {
    "normal", 
    "left", 
    "inverted", 
    "right",
    "\n"};

static const char *reflections[5] = {
    "normal", 
    "x", 
    "y", 
    "xy",
    "\n"};

/* subpixel order */
static const char *order[6] = {
    "unknown",
    "horizontal rgb",
    "horizontal bgr",
    "vertical rgb",
    "vertical bgr",
    "no subpixels"};

static const struct {
    const char	    *string;
    unsigned long   flag;
} mode_flags[] = {
    { "+HSync", RR_HSyncPositive },
    { "-HSync", RR_HSyncNegative },
    { "+VSync", RR_VSyncPositive },
    { "-VSync", RR_VSyncNegative },
    { "Interlace", RR_Interlace },
    { "DoubleScan", RR_DoubleScan },
    { "CSync",	    RR_CSync },
    { "+CSync",	    RR_CSyncPositive },
    { "-CSync",	    RR_CSyncNegative },
    { NULL,	    0 }
};

static void
usage(void)
{
    printf("usage: %s [options]\n%s", program_name,
           "  where options are:\n"
           "  --display <display> or -d <display>\n"
           "  --help\n"
           "  -o <normal,inverted,left,right,0,1,2,3>\n"
           "            or --orientation <normal,inverted,left,right,0,1,2,3>\n"
           "  -q        or --query\n"
           "  -s <size>/<width>x<height> or --size <size>/<width>x<height>\n"
           "  -r <rate> or --rate <rate> or --refresh <rate>\n"
           "  -v        or --version\n"
           "  -x        (reflect in x)\n"
           "  -y        (reflect in y)\n"
           "  --screen <screen>\n"
           "  --verbose\n"
           "  --current\n"
           "  --dryrun\n"
           "  --nograb\n"
           "  --prop or --properties\n"
           "  --fb <width>x<height>\n"
           "  --fbmm <width>x<height>\n"
           "  --dpi <dpi>/<output>\n"
           "  --output <output>\n"
           "      --auto\n"
           "      --mode <mode>\n"
           "      --preferred\n"
           "      --pos <x>x<y>\n"
           "      --rate <rate> or --refresh <rate>\n"
           "      --reflect normal,x,y,xy\n"
           "      --rotate normal,inverted,left,right\n"
           "      --left-of <output>\n"
           "      --right-of <output>\n"
           "      --above <output>\n"
           "      --below <output>\n"
           "      --same-as <output>\n"
           "      --set <property> <value>\n"
           "      --scale <x>[x<y>]\n"
           "      --scale-from <w>x<h>\n"
           "      --transform <a>,<b>,<c>,<d>,<e>,<f>,<g>,<h>,<i>\n"
           "      --filter nearest,bilinear\n"
           "      --off\n"
           "      --crtc <crtc>\n"
           "      --panning <w>x<h>[+<x>+<y>[/<track:w>x<h>+<x>+<y>[/<border:l>/<t>/<r>/<b>]]]\n"
           "      --gamma <r>[:<g>:<b>]\n"
           "      --brightness <value>\n"
           "      --primary\n"
           "  --noprimary\n"
           "  --newmode <name> <clock MHz>\n"
           "            <hdisp> <hsync-start> <hsync-end> <htotal>\n"
           "            <vdisp> <vsync-start> <vsync-end> <vtotal>\n"
           "            [flags...]\n"
           "            Valid flags: +HSync -HSync +VSync -VSync\n"
           "                         +CSync -CSync CSync Interlace DoubleScan\n"
           "  --rmmode <name>\n"
           "  --addmode <output> <name>\n"
           "  --delmode <output> <name>\n"
           "  --listproviders\n"
           "  --setprovideroutputsource <prov-xid> <source-xid>\n"
           "  --setprovideroffloadsink <prov-xid> <sink-xid>\n"
	   "  --listmonitors\n"
	   "  --listactivemonitors\n"
	   "  --setmonitor <name> {auto|<w>/<mmw>x<h>/<mmh>+<x>+<y>} {none|<output>,<output>,...}\n"
	   "  --delmonitor <name>\n");
}

static void _X_NORETURN _X_ATTRIBUTE_PRINTF(1,2)
fatal (const char *format, ...)
{
    va_list ap;
    
    va_start (ap, format);
    fprintf (stderr, "%s: ", program_name);
    vfprintf (stderr, format, ap);
    va_end (ap);
    exit (1);
    /*NOTREACHED*/
}

static void _X_ATTRIBUTE_PRINTF(1,2)
warning (const char *format, ...)
{
    va_list ap;
    
    va_start (ap, format);
    fprintf (stderr, "%s: ", program_name);
    vfprintf (stderr, format, ap);
    va_end (ap);
}

static void _X_NORETURN _X_ATTRIBUTE_PRINTF(1,2)
argerr (const char *format, ...)
{
    va_list ap;

    va_start (ap, format);
    fprintf (stderr, "%s: ", program_name);
    vfprintf (stderr, format, ap);
    fprintf (stderr, "Try '%s --help' for more information.\n", program_name);
    va_end (ap);
    exit (1);
    /*NOTREACHED*/
}

/* Because fmin requires C99 support */
static inline double dmin (double x, double y)
{
    return x < y ? x : y;
}

static const char *
rotation_name (Rotation rotation)
{
    if ((rotation & 0xf) == 0)
	return "normal";
    for (int i = 0; i < 4; i++)
	if (rotation & (1 << i))
	    return direction[i];
    return "invalid rotation";
}

static const char *
reflection_name (Rotation rotation)
{
    rotation &= (RR_Reflect_X|RR_Reflect_Y);
    switch (rotation) {
    case 0:
	return "none";
    case RR_Reflect_X:
	return "X axis";
    case RR_Reflect_Y:
	return "Y axis";
    case RR_Reflect_X|RR_Reflect_Y:
	return "X and Y axis";
    }
    return "invalid reflection";
}

static const char *
capability_name (int cap_bit)
{
    switch (cap_bit) {
    case RR_Capability_SourceOutput:
	return "Source Output";
    case RR_Capability_SinkOutput:
	return "Sink Output";
    case RR_Capability_SourceOffload:
	return "Source Offload";
    case RR_Capability_SinkOffload:
	return "Sink Offload";
    }
    return "invalid capability";
}

typedef enum _relation {
    relation_left_of,
    relation_right_of,
    relation_above,
    relation_below,
    relation_same_as,
} relation_t;

typedef struct {
    int	    x1, y1, x2, y2;
} box_t;

typedef struct {
    int	    x, y;
} point_t;

typedef enum _changes {
    changes_none = 0,
    changes_crtc = (1 << 0),
    changes_mode = (1 << 1),
    changes_relation = (1 << 2),
    changes_position = (1 << 3),
    changes_rotation = (1 << 4),
    changes_reflection = (1 << 5),
    changes_automatic = (1 << 6),
    changes_refresh = (1 << 7),
    changes_property = (1 << 8),
    changes_transform = (1 << 9),
    changes_panning = (1 << 10),
    changes_gamma = (1 << 11),
    changes_primary = (1 << 12),
    changes_filter = (1 << 13),
} changes_t;

typedef enum _name_kind {
    name_none = 0,
    name_string = (1 << 0),
    name_xid = (1 << 1),
    name_index = (1 << 2),
    name_preferred = (1 << 3),
} name_kind_t;

typedef struct {
    name_kind_t	    kind;
    char    	    *string;
    XID	    	    xid;
    int		    index;
} name_t;

typedef struct _crtc crtc_t;
typedef struct _output	output_t;
typedef struct _transform transform_t;
typedef struct _umode	umode_t;
typedef struct _output_prop output_prop_t;
typedef struct _provider provider_t;
typedef struct _monitors monitors_t;
typedef struct _umonitor umonitor_t;

struct _transform {
    XTransform	    transform;
    const char	    *filter;
    int		    nparams;
    XFixed	    *params;
};

struct _crtc {
    name_t	    crtc;
    Bool	    changing;
    XRRCrtcInfo	    *crtc_info;

    XRRModeInfo	    *mode_info;
    XRRPanning      *panning_info;
    int		    x;
    int		    y;
    Rotation	    rotation;
    output_t	    **outputs;
    int		    noutput;
    transform_t	    current_transform, pending_transform;
};

struct _output_prop {
    struct _output_prop	*next;
    char		*name;
    char		*value;
};

struct _output {
    struct _output   *next;
    
    changes_t	    changes;
    
    output_prop_t   *props;

    name_t	    output;
    XRROutputInfo   *output_info;
    
    name_t	    crtc;
    crtc_t	    *crtc_info;
    crtc_t	    *current_crtc_info;
    
    name_t	    mode;
    double	    refresh;
    XRRModeInfo	    *mode_info;
    
    name_t	    addmode;

    relation_t	    relation;
    char	    *relative_to;

    int		    x, y;
    Rotation	    rotation;

    XRRPanning      panning;

    Bool    	    automatic;
    int     	    scale_from_w, scale_from_h;
    transform_t	    transform;

    struct {
	float red;
	float green;
	float blue;
    } gamma;

    float	    brightness;

    Bool	    primary;

    Bool	    found;
};

typedef enum _umode_action {
    umode_create, umode_destroy, umode_add, umode_delete
} umode_action_t;


struct _umode {
    struct _umode   *next;
    
    umode_action_t  action;
    XRRModeInfo	    mode;
    name_t	    output;
    name_t	    name;
};

struct _provider {
    name_t		provider;
    XRRProviderInfo	*info;
};

struct _monitors {
    int			n;
    XRRMonitorInfo	*monitors;
};

struct _umonitor {
    struct _umonitor	*next;
    char		*name;
    Bool		set;
    Bool		primary;
    int			x, y, width, height;
    int			mmwidth, mmheight;
    int			noutput;
    name_t		*outputs;
};

static const char *connection[3] = {
    "connected",
    "disconnected",
    "unknown connection"};

static output_t	*all_outputs = NULL;
static output_t	**all_outputs_tail = &all_outputs;
static crtc_t	*crtcs;
static provider_t	*providers;
static umode_t	*umodes;
static int	num_crtcs, num_providers;
static XRRScreenResources  *res;
static int	fb_width = 0, fb_height = 0;
static int	fb_width_mm = 0, fb_height_mm = 0;
static double	dpi = 0;
static char	*dpi_output_name = NULL;
static Bool	dryrun = False;
static int	minWidth, maxWidth, minHeight, maxHeight;
static Bool    	has_1_2 = False;
static Bool    	has_1_3 = False;
static Bool    	has_1_4 = False;
static Bool	has_1_5 = False;
static name_t   provider_name, output_source_provider_name, offload_sink_provider_name;
static monitors_t	*monitors;
static umonitor_t	*umonitors;

static int
mode_height (XRRModeInfo *mode_info, Rotation rotation)
{
    switch (rotation & 0xf) {
    case RR_Rotate_0:
    case RR_Rotate_180:
	return mode_info->height;
    case RR_Rotate_90:
    case RR_Rotate_270:
	return mode_info->width;
    default:
	return 0;
    }
}

static int
mode_width (XRRModeInfo *mode_info, Rotation rotation)
{
    switch (rotation & 0xf) {
    case RR_Rotate_0:
    case RR_Rotate_180:
	return mode_info->width;
    case RR_Rotate_90:
    case RR_Rotate_270:
	return mode_info->height;
    default:
	return 0;
    }
}

static Bool
transform_point (XTransform *transform, double *xp, double *yp)
{
    double  vector[3];
    double  result[3];


    vector[0] = *xp;
    vector[1] = *yp;
    vector[2] = 1;
    for (int j = 0; j < 3; j++)
    {
	double  v = 0;
	for (int i = 0; i < 3; i++)
	    v += (XFixedToDouble (transform->matrix[j][i]) * vector[i]);
	result[j] = v;
    }
    if (!result[2])
	return False;
    for (int j = 0; j < 2; j++) {
	vector[j] = result[j] / result[2];
	if (vector[j] > 32767 || vector[j] < -32767)
	    return False;
    }
    *xp = vector[0];
    *yp = vector[1];
    return True;
}

static void
path_bounds (XTransform *transform, point_t *points, int npoints, box_t *box)
{
    for (int i = 0; i < npoints; i++) {
	double	x, y;
	box_t	point;

	x = points[i].x;
	y = points[i].y;
	transform_point (transform, &x, &y);
	point.x1 = floor (x);
	point.y1 = floor (y);
	point.x2 = ceil (x);
	point.y2 = ceil (y);
	if (i == 0)
	    *box = point;
	else {
	    if (point.x1 < box->x1) box->x1 = point.x1;
	    if (point.y1 < box->y1) box->y1 = point.y1;
	    if (point.x2 > box->x2) box->x2 = point.x2;
	    if (point.y2 > box->y2) box->y2 = point.y2;
	}
    }
}

static void
mode_geometry (XRRModeInfo *mode_info, Rotation rotation,
	       XTransform *transform,
	       box_t *bounds)
{
    point_t rect[4];
    int	width = mode_width (mode_info, rotation);
    int height = mode_height (mode_info, rotation);

    rect[0].x = 0;
    rect[0].y = 0;
    rect[1].x = width;
    rect[1].y = 0;
    rect[2].x = width;
    rect[2].y = height;
    rect[3].x = 0;
    rect[3].y = height;
    path_bounds (transform, rect, 4, bounds);
}

/* v refresh frequency in Hz */
static double
mode_refresh (const XRRModeInfo *mode_info)
{
    double rate;
    double vTotal = mode_info->vTotal;

    if (mode_info->modeFlags & RR_DoubleScan) {
	/* doublescan doubles the number of lines */
	vTotal *= 2;
    }

    if (mode_info->modeFlags & RR_Interlace) {
	/* interlace splits the frame into two fields */
	/* the field rate is what is typically reported by monitors */
	vTotal /= 2;
    }
    
    if (mode_info->hTotal && vTotal)
	rate = ((double) mode_info->dotClock /
		((double) mode_info->hTotal * (double) vTotal));
    else
    	rate = 0;
    return rate;
}

/* h sync frequency in Hz */
static double
mode_hsync (const XRRModeInfo *mode_info)
{
    double rate;
    
    if (mode_info->hTotal)
	rate = (double) mode_info->dotClock / (double) mode_info->hTotal;
    else
    	rate = 0;
    return rate;
}

static void
print_verbose_mode (const XRRModeInfo *mode, Bool current, Bool preferred)
{
    printf ("  %s (0x%x) %6.3fMHz",
	    mode->name, (int)mode->id,
	    (double)mode->dotClock / 1000000.0);
    for (int f = 0; mode_flags[f].flag; f++)
	if (mode->modeFlags & mode_flags[f].flag)
	    printf (" %s", mode_flags[f].string);
    if (current)
	printf (" *current");
    if (preferred)
	printf (" +preferred");
    printf ("\n");
    printf ("        h: width  %4d start %4d end %4d total %4d skew %4d clock %6.2fKHz\n",
	    mode->width, mode->hSyncStart, mode->hSyncEnd,
	    mode->hTotal, mode->hSkew, mode_hsync (mode) / 1000);
    printf ("        v: height %4d start %4d end %4d total %4d           clock %6.2fHz\n",
	    mode->height, mode->vSyncStart, mode->vSyncEnd, mode->vTotal,
	    mode_refresh (mode));
}

static void
init_name (name_t *name)
{
    memset(name, 0, sizeof(*name));
    name->kind = name_none;
}

static void
set_name_string (name_t *name, char *string)
{
    name->kind |= name_string;
    name->string = string;
}

static void
set_name_xid (name_t *name, XID xid)
{
    name->kind |= name_xid;
    name->xid = xid;
}

static void
set_name_index (name_t *name, int idx)
{
    name->kind |= name_index;
    name->index = idx;
}

static void
set_name_preferred (name_t *name)
{
    name->kind |= name_preferred;
}

static void
set_name_all (name_t *name, name_t *old)
{
    if (old->kind & name_xid)
	name->xid = old->xid;
    if (old->kind & name_string)
	name->string = old->string;
    if (old->kind & name_index)
	name->index = old->index;
    name->kind |= old->kind;
}

static void
set_name (name_t *name, char *string, name_kind_t valid)
{
    unsigned int xid; /* don't make it XID (which is unsigned long):
			 scanf() takes unsigned int */
    int idx;

    if ((valid & name_xid) && sscanf (string, "0x%x", &xid) == 1)
	set_name_xid (name, xid);
    else if ((valid & name_index) && sscanf (string, "%d", &idx) == 1)
	set_name_index (name, idx);
    else if (valid & name_string)
	set_name_string (name, string);
    else
	argerr ("invalid name '%s'\n", string);
}

static int
print_name (const name_t *name)
{
    name_kind_t kind = name->kind;

    if ((kind & name_xid))         return printf("XID 0x%x", (unsigned int)name->xid);
    else if ((kind & name_string)) return printf("name %s", name->string);
    else if ((kind & name_index))  return printf("index %d", name->index);
    else                           return printf("unknown name");
}

static void
init_transform (transform_t *transform)
{
    memset (&transform->transform, '\0', sizeof (transform->transform));
    for (int x = 0; x < 3; x++)
	transform->transform.matrix[x][x] = XDoubleToFixed (1.0);
    transform->filter = "";
    transform->nparams = 0;
    transform->params = NULL;
}

static void
set_transform (transform_t  *dest,
	       XTransform   *transform,
	       const char   *filter,
	       XFixed	    *params,
	       int	    nparams)
{
    dest->transform = *transform;
    /* note: this string is leaked */
    dest->filter = strdup (filter);
    dest->nparams = nparams;
    dest->params = malloc (nparams * sizeof (XFixed));
    memcpy (dest->params, params, nparams * sizeof (XFixed));
}

static void
copy_transform (transform_t *dest, transform_t *src)
{
    set_transform (dest, &src->transform,
		   src->filter, src->params, src->nparams);
}

static Bool
equal_transform (transform_t *a, transform_t *b)
{
    if (memcmp (&a->transform, &b->transform, sizeof (XTransform)) != 0)
	return False;
    if (strcmp (a->filter, b->filter) != 0)
	return False;
    if (a->nparams != b->nparams)
	return False;
    if (memcmp (a->params, b->params, a->nparams * sizeof (XFixed)) != 0)
	return False;
    return True;
}

static output_t *
add_output (void)
{
    output_t *output = calloc (1, sizeof (output_t));

    if (!output)
	fatal ("out of memory\n");
    output->next = NULL;
    output->found = False;
    output->brightness = 1.0;
    *all_outputs_tail = output;
    all_outputs_tail = &output->next;
    return output;
}

static output_t *
find_output (name_t *name)
{
    output_t *output;

    for (output = all_outputs; output; output = output->next)
    {
	name_kind_t common = name->kind & output->output.kind;
	
	if ((common & name_xid) && name->xid == output->output.xid)
	    break;
	if ((common & name_string) && !strcmp (name->string, output->output.string))
	    break;
	if ((common & name_index) && name->index == output->output.index)
	    break;
    }
    return output;
}

static output_t *
find_output_by_xid (RROutput output)
{
    name_t  output_name;

    init_name (&output_name);
    set_name_xid (&output_name, output);
    return find_output (&output_name);
}

static output_t *
find_output_by_name (char *name)
{
    name_t  output_name;

    init_name (&output_name);
    set_name_string (&output_name, name);
    return find_output (&output_name);
}

static crtc_t *
find_crtc (name_t *name)
{
    crtc_t  *crtc = NULL;

    for (int c = 0; c < num_crtcs; c++)
    {
	name_kind_t common;
	
	crtc = &crtcs[c];
	common = name->kind & crtc->crtc.kind;
	
	if ((common & name_xid) && name->xid == crtc->crtc.xid)
	    break;
	if ((common & name_string) && !strcmp (name->string, crtc->crtc.string))
	    break;
	if ((common & name_index) && name->index == crtc->crtc.index)
	    break;
	crtc = NULL;
    }
    return crtc;
}

static crtc_t *
find_crtc_by_xid (RRCrtc crtc)
{
    name_t  crtc_name;

    init_name (&crtc_name);
    set_name_xid (&crtc_name, crtc);
    return find_crtc (&crtc_name);
}

static XRRModeInfo *
find_mode (name_t *name, double refresh)
{
    XRRModeInfo	*best = NULL;
    double	bestDist = 0;

    for (int m = 0; m < res->nmode; m++)
    {
	XRRModeInfo *mode = &res->modes[m];
	if ((name->kind & name_xid) && name->xid == mode->id)
	{
	    best = mode;
	    break;
	}
	if ((name->kind & name_string) && !strcmp (name->string, mode->name))
	{
	    double   dist;
	    
	    if (refresh)
		dist = fabs (mode_refresh (mode) - refresh);
	    else
		dist = 0;
	    if (!best || dist < bestDist)
	    {
		bestDist = dist;
		best = mode;
	    }
	}
    }
    return best;
}

static XRRModeInfo *
find_mode_by_xid (RRMode mode)
{
    name_t  mode_name;

    init_name (&mode_name);
    set_name_xid (&mode_name, mode);
    return find_mode (&mode_name, 0);
}

#if 0
static XRRModeInfo *
find_mode_by_name (char *name)
{
    name_t  mode_name;
    init_name (&mode_name);
    set_name_string (&mode_name, name);
    return find_mode (&mode_name, 0);
}
#endif

static
XRRModeInfo *
find_mode_for_output (output_t *output, name_t *name)
{
    XRROutputInfo   *output_info = output->output_info;
    XRRModeInfo	    *best = NULL;
    double	    bestDist = 0;

    for (int m = 0; m < output_info->nmode; m++)
    {
	XRRModeInfo	    *mode;

	mode = find_mode_by_xid (output_info->modes[m]);
	if (!mode) continue;
	if ((name->kind & name_xid) && name->xid == mode->id)
	{
	    best = mode;
	    break;
	}
	if ((name->kind & name_string) && !strcmp (name->string, mode->name))
	{
	    double   dist;

	    /* Stay away from doublescan modes unless refresh rate is specified. */
	    if (!output->refresh && (mode->modeFlags & RR_DoubleScan))
		continue;

	    if (output->refresh)
		dist = fabs (mode_refresh (mode) - output->refresh);
	    else
		dist = 0;
	    if (!best || dist < bestDist)
	    {
		bestDist = dist;
		best = mode;
	    }
	}
    }
    return best;
}

static XRRModeInfo *
preferred_mode (output_t *output)
{
    XRROutputInfo   *output_info = output->output_info;
    XRRModeInfo	    *best = NULL;
    int		    bestDist = 0;
    
    for (int m = 0; m < output_info->nmode; m++)
    {
	XRRModeInfo *mode_info = find_mode_by_xid (output_info->modes[m]);
	int	    dist;
	
	if (m < output_info->npreferred)
	    dist = 0;
	else if (output_info->mm_height)
	    dist = (1000 * DisplayHeight(dpy, screen) / DisplayHeightMM(dpy, screen) -
		    1000 * mode_info->height / output_info->mm_height);
	else
	    dist = DisplayHeight(dpy, screen) - mode_info->height;

        if (dist < 0) dist = -dist;
	if (!best || dist < bestDist)
	{
	    best = mode_info;
	    bestDist = dist;
	}
    }
    return best;
}

static Bool
output_can_use_crtc (output_t *output, crtc_t *crtc)
{
    XRROutputInfo   *output_info = output->output_info;

    for (int c = 0; c < output_info->ncrtc; c++)
	if (output_info->crtcs[c] == crtc->crtc.xid)
	    return True;
    return False;
}

static Bool
output_can_use_mode (output_t *output, XRRModeInfo *mode)
{
    XRROutputInfo   *output_info = output->output_info;

    for (int m = 0; m < output_info->nmode; m++)
	if (output_info->modes[m] == mode->id)
	    return True;
    return False;
}

static Bool
crtc_can_use_rotation (crtc_t *crtc, Rotation rotation)
{
    Rotation	rotations = crtc->crtc_info->rotations;
    Rotation	dir = rotation & (RR_Rotate_0|RR_Rotate_90|RR_Rotate_180|RR_Rotate_270);
    Rotation	reflect = rotation & (RR_Reflect_X|RR_Reflect_Y);
    if (((rotations & dir) != 0) && ((rotations & reflect) == reflect))
	return True;
    return False;
}

#if 0
static Bool
crtc_can_use_transform (crtc_t *crtc, XTransform *transform)
{
    int	major, minor;

    XRRQueryVersion (dpy, &major, &minor);
    if (major > 1 || (major == 1 && minor >= 3))
	return True;
    return False;
}
#endif

/*
 * Report only rotations that are supported by all crtcs
 */
static Rotation
output_rotations (output_t *output)
{
    Bool	    found = False;
    Rotation	    rotation = RR_Rotate_0;
    XRROutputInfo   *output_info = output->output_info;
    
    for (int c = 0; c < output_info->ncrtc; c++)
    {
	crtc_t	*crtc = find_crtc_by_xid (output_info->crtcs[c]);
	if (crtc)
	{
	    if (!found) {
		rotation = crtc->crtc_info->rotations;
		found = True;
	    } else
		rotation &= crtc->crtc_info->rotations;
	}
    }
    return rotation;
}

static Bool
output_can_use_rotation (output_t *output, Rotation rotation)
{
    XRROutputInfo   *output_info = output->output_info;

    /* make sure all of the crtcs can use this rotation.
     * yes, this is not strictly necessary, but it is 
     * simpler,and we expect most drivers to either
     * support rotation everywhere or nowhere
     */
    for (int c = 0; c < output_info->ncrtc; c++)
    {
	crtc_t	*crtc = find_crtc_by_xid (output_info->crtcs[c]);
	if (crtc && !crtc_can_use_rotation (crtc, rotation))
	    return False;
    }
    return True;
}

static Bool
output_is_primary(output_t *output)
{
    if (has_1_3)
	    return XRRGetOutputPrimary(dpy, root) == output->output.xid;
    return False;
}

/* Returns the index of the last value in an array < 0xffff */
static int
find_last_non_clamped(const CARD16 array[], int size)
{
    for (int i = size - 1; i > 0; i--) {
        if (array[i] < 0xffff)
	    return i;
    }
    return 0;
}

static void
set_gamma_info(output_t *output)
{
    XRRCrtcGamma *crtc_gamma;
    double i1, v1, i2, v2;
    int size, middle, last_best, last_red, last_green, last_blue;
    CARD16 *best_array;

    if (!output->crtc_info)
	return;

    crtc_gamma = XRRGetCrtcGamma(dpy, output->crtc_info->crtc.xid);
    if (!crtc_gamma) {
	warning("Failed to get gamma for output %s\n", output->output.string);
	return;
    }
    size = crtc_gamma->size;

    /*
     * Here is a bit tricky because gamma is a whole curve for each
     * color.  So, typically, we need to represent 3 * 256 values as 3 + 1
     * values.  Therefore, we approximate the gamma curve (v) by supposing
     * it always follows the way we set it: a power function (i^g)
     * multiplied by a brightness (b).
     * v = i^g * b
     * so g = (ln(v) - ln(b))/ln(i)
     * and b can be found using two points (v1,i1) and (v2, i2):
     * b = e^((ln(v2)*ln(i1) - ln(v1)*ln(i2))/ln(i1/i2))
     * For the best resolution, we select i2 at the highest place not
     * clamped and i1 at i2/2. Note that if i2 = 1 (as in most normal
     * cases), then b = v2.
     */
    last_red = find_last_non_clamped(crtc_gamma->red, size);
    last_green = find_last_non_clamped(crtc_gamma->green, size);
    last_blue = find_last_non_clamped(crtc_gamma->blue, size);
    best_array = crtc_gamma->red;
    last_best = last_red;
    if (last_green > last_best) {
	last_best = last_green;
	best_array = crtc_gamma->green;
    }
    if (last_blue > last_best) {
	last_best = last_blue;
	best_array = crtc_gamma->blue;
    }
    if (last_best == 0)
	last_best = 1;

    middle = last_best / 2;
    i1 = (double)(middle + 1) / size;
    v1 = (double)(best_array[middle]) / 65535;
    i2 = (double)(last_best + 1) / size;
    v2 = (double)(best_array[last_best]) / 65535;
    if (v2 < 0.0001) { /* The screen is black */
	output->brightness = 0;
	output->gamma.red = 1;
	output->gamma.green = 1;
	output->gamma.blue = 1;
    } else {
	if ((last_best + 1) == size)
	    output->brightness = v2;
	else
	    output->brightness = exp((log(v2)*log(i1) - log(v1)*log(i2))/log(i1/i2));
	output->gamma.red = log((double)(crtc_gamma->red[last_red / 2]) / output->brightness
				/ 65535) / log((double)((last_red / 2) + 1) / size);
	output->gamma.green = log((double)(crtc_gamma->green[last_green / 2]) / output->brightness
				  / 65535) / log((double)((last_green / 2) + 1) / size);
	output->gamma.blue = log((double)(crtc_gamma->blue[last_blue / 2]) / output->brightness
				 / 65535) / log((double)((last_blue / 2) + 1) / size);
    }

    XRRFreeGamma(crtc_gamma);
}

static void
set_output_info (output_t *output, RROutput xid, XRROutputInfo *output_info)
{
    /* sanity check output info */
    if (output_info->connection != RR_Disconnected && !output_info->nmode)
	warning ("Output %s is not disconnected but has no modes\n",
		 output_info->name);
    
    /* set output name and info */
    if (!(output->output.kind & name_xid))
	set_name_xid (&output->output, xid);
    if (!(output->output.kind & name_string))
	set_name_string (&output->output, output_info->name);
    output->output_info = output_info;
    
    /* set crtc name and info */
    if (!(output->changes & changes_crtc))
	set_name_xid (&output->crtc, output_info->crtc);
    
    if (output->crtc.kind == name_xid && output->crtc.xid == None)
	output->crtc_info = NULL;
    else
    {
	output->crtc_info = find_crtc (&output->crtc);
	if (!output->crtc_info)
	{
	    if (output->crtc.kind & name_xid)
		fatal ("cannot find crtc 0x%lx\n", output->crtc.xid);
	    if (output->crtc.kind & name_index)
		fatal ("cannot find crtc %d\n", output->crtc.index);
	}
	if (!output_can_use_crtc (output, output->crtc_info))
	    fatal ("output %s cannot use crtc 0x%lx\n", output->output.string,
		   output->crtc_info->crtc.xid);
    }

    /* set mode name and info */
    if (!(output->changes & changes_mode))
    {
	crtc_t	*crtc = NULL;
	
	if (output_info->crtc)
	    crtc = find_crtc_by_xid(output_info->crtc);
	if (crtc && crtc->crtc_info)
	    set_name_xid (&output->mode, crtc->crtc_info->mode);
	else if (output->crtc_info)
	    set_name_xid (&output->mode, output->crtc_info->crtc_info->mode);
	else
	    set_name_xid (&output->mode, None);
	if (output->mode.xid)
	{
	    output->mode_info = find_mode_by_xid (output->mode.xid);
	    if (!output->mode_info)
		fatal ("server did not report mode 0x%lx for output %s\n",
		       output->mode.xid, output->output.string);
	}
	else
	    output->mode_info = NULL;
    }
    else if (output->mode.kind == name_xid && output->mode.xid == None)
	output->mode_info = NULL;
    else
    {
	if (output->mode.kind == name_preferred)
	    output->mode_info = preferred_mode (output);
	else
	    output->mode_info = find_mode_for_output (output, &output->mode);
	if (!output->mode_info)
	{
	    if (output->mode.kind & name_preferred)
		fatal ("cannot find preferred mode\n");
	    if (output->mode.kind & name_string)
		fatal ("cannot find mode %s\n", output->mode.string);
	    if (output->mode.kind & name_xid)
		fatal ("cannot find mode 0x%lx\n", output->mode.xid);
	}
	if (!output_can_use_mode (output, output->mode_info))
	    fatal ("output %s cannot use mode %s\n", output->output.string,
		   output->mode_info->name);
    }

    /* set position */
    if (!(output->changes & changes_position))
    {
	if (output->crtc_info)
	{
	    output->x = output->crtc_info->crtc_info->x;
	    output->y = output->crtc_info->crtc_info->y;
	}
	else
	{
	    output->x = 0;
	    output->y = 0;
	}
    }

    /* set rotation */
    if (!(output->changes & changes_rotation))
    {
	output->rotation &= ~0xf;
	if (output->crtc_info)
	    output->rotation |= (output->crtc_info->crtc_info->rotation & 0xf);
	else
	    output->rotation = RR_Rotate_0;
    }
    if (!(output->changes & changes_reflection))
    {
	output->rotation &= ~(RR_Reflect_X|RR_Reflect_Y);
	if (output->crtc_info)
	    output->rotation |= (output->crtc_info->crtc_info->rotation &
				 (RR_Reflect_X|RR_Reflect_Y));
    }
    if (!output_can_use_rotation (output, output->rotation))
	fatal ("output %s cannot use rotation \"%s\" reflection \"%s\"\n",
	       output->output.string,
	       rotation_name (output->rotation),
	       reflection_name (output->rotation));

    /* set gamma */
    if (!(output->changes & changes_gamma))
	    set_gamma_info(output);

    /* set transformation */
    if (!(output->changes & changes_transform))
    {
	if (output->crtc_info)
	    copy_transform (&output->transform, &output->crtc_info->current_transform);
	else
	    init_transform (&output->transform);
    } else {
	/* transform was already set for --scale or --transform */

	/* for --scale-from, figure out the mode size and compute the transform
	 * for the target framebuffer area */
	if (output->scale_from_w > 0 && output->mode_info) {
	    double sx = (double)output->scale_from_w /
				output->mode_info->width;
	    double sy = (double)output->scale_from_h /
				output->mode_info->height;
	    if (verbose)
		printf("scaling %s by %lfx%lf\n", output->output.string, sx,
		       sy);
	    init_transform (&output->transform);
	    output->transform.transform.matrix[0][0] = XDoubleToFixed (sx);
	    output->transform.transform.matrix[1][1] = XDoubleToFixed (sy);
	    output->transform.transform.matrix[2][2] = XDoubleToFixed (1.0);
	    if (sx != 1 || sy != 1)
		output->transform.filter = "bilinear";
	    else
		output->transform.filter = "nearest";
	    output->transform.nparams = 0;
	    output->transform.params = NULL;
	}
    }
    if (output->changes & changes_filter)
    {
	output->transform.filter = filter_names[filter_type];
    }

    /* set primary */
    if (!(output->changes & changes_primary))
	output->primary = output_is_primary(output);
}
    
static void
get_screen (Bool current)
{
    if (!has_1_2)
        fatal ("Server RandR version before 1.2\n");

    if (res)
	return;

    XRRGetScreenSizeRange (dpy, root, &minWidth, &minHeight,
			   &maxWidth, &maxHeight);
    
    if (current)
	res = XRRGetScreenResourcesCurrent (dpy, root);
    else
	res = XRRGetScreenResources (dpy, root);
    if (!res) fatal ("could not get screen resources");
}

static void
get_crtcs (void)
{
    num_crtcs = res->ncrtc;
    crtcs = calloc (num_crtcs, sizeof (crtc_t));
    if (!crtcs) fatal ("out of memory\n");
    
    for (int c = 0; c < res->ncrtc; c++)
    {
	XRRCrtcInfo *crtc_info = XRRGetCrtcInfo (dpy, res, res->crtcs[c]);
	XRRCrtcTransformAttributes  *attr;
	XRRPanning  *panning_info = NULL;

	if (has_1_3) {
	    XRRPanning zero;
	    memset(&zero, 0, sizeof(zero));
	    panning_info = XRRGetPanning  (dpy, res, res->crtcs[c]);
	    zero.timestamp = panning_info->timestamp;
	    if (!memcmp(panning_info, &zero, sizeof(zero))) {
		Xfree(panning_info);
		panning_info = NULL;
	    }
	}

	set_name_xid (&crtcs[c].crtc, res->crtcs[c]);
	set_name_index (&crtcs[c].crtc, c);
	if (!crtc_info) fatal ("could not get crtc 0x%lx information\n", res->crtcs[c]);
	crtcs[c].crtc_info = crtc_info;
	crtcs[c].panning_info = panning_info;
	if (crtc_info->mode == None)
	{
	    crtcs[c].mode_info = NULL;
	    crtcs[c].x = 0;
	    crtcs[c].y = 0;
	    crtcs[c].rotation = RR_Rotate_0;
	}
	if (XRRGetCrtcTransform (dpy, res->crtcs[c], &attr) && attr) {
	    set_transform (&crtcs[c].current_transform,
			   &attr->currentTransform,
			   attr->currentFilter,
			   attr->currentParams,
			   attr->currentNparams);
	    XFree (attr);
	}
	else
	{
	    init_transform (&crtcs[c].current_transform);
	}
	copy_transform (&crtcs[c].pending_transform, &crtcs[c].current_transform);
   }
}

static void
crtc_add_output (crtc_t *crtc, output_t *output)
{
    if (crtc->outputs)
	crtc->outputs = realloc (crtc->outputs, (crtc->noutput + 1) * sizeof (output_t *));
    else
    {
	crtc->outputs = malloc (sizeof (output_t *));
	crtc->x = output->x;
	crtc->y = output->y;
	crtc->rotation = output->rotation;
	crtc->mode_info = output->mode_info;
	copy_transform (&crtc->pending_transform, &output->transform);
   }
    if (!crtc->outputs) fatal ("out of memory\n");
    crtc->outputs[crtc->noutput++] = output;
}

static void
set_crtcs (void)
{
    output_t	*output;

    for (output = all_outputs; output; output = output->next)
    {
	if (!output->mode_info) continue;
	crtc_add_output (output->crtc_info, output);
    }
}

static void
set_panning (void)
{
    output_t	*output;

    for (output = all_outputs; output; output = output->next)
    {
	if (! output->crtc_info)
	    continue;
	if (! (output->changes & changes_panning))
	    continue;
	if (! output->crtc_info->panning_info)
	    output->crtc_info->panning_info = malloc (sizeof(XRRPanning));
	memcpy (output->crtc_info->panning_info, &output->panning, sizeof(XRRPanning));
	output->crtc_info->changing = 1;
    }
}

static void
set_gamma(void)
{
    for (output_t *output = all_outputs; output; output = output->next) {
	int i, size;
	crtc_t *crtc;
	XRRCrtcGamma *crtc_gamma;
	float gammaRed;
	float gammaGreen;
	float gammaBlue;

	if (!(output->changes & changes_gamma))
	    continue;

	if (!output->crtc_info) {
	    fatal("Need crtc to set gamma on.\n");
	    continue;
	}

	crtc = output->crtc_info;

	size = XRRGetCrtcGammaSize(dpy, crtc->crtc.xid);

	if (!size) {
	    fatal("Gamma size is 0.\n");
	    continue;
	}

	/*
	 * The gamma-correction lookup table managed through XRR[GS]etCrtcGamma
	 * is 2^n in size, where 'n' is the number of significant bits in
	 * the X Color.  Because an X Color is 16 bits, size cannot be larger
	 * than 2^16.
	 */
	if (size > 65536) {
	    fatal("Gamma correction table is impossibly large.\n");
	    continue;
	}

	crtc_gamma = XRRAllocGamma(size);
	if (!crtc_gamma) {
	    fatal("Gamma allocation failed.\n");
	    continue;
	}

	if (output->gamma.red == 0.0)
	    output->gamma.red = 1.0;
	if (output->gamma.green == 0.0)
	    output->gamma.green = 1.0;
	if (output->gamma.blue == 0.0)
	    output->gamma.blue = 1.0;

	gammaRed = 1.0 / output->gamma.red;
	gammaGreen = 1.0 / output->gamma.green;
	gammaBlue = 1.0 / output->gamma.blue;

	for (i = 0; i < size; i++) {
	    if (gammaRed == 1.0 && output->brightness == 1.0)
		crtc_gamma->red[i] = (double)i / (double)(size - 1) * 65535.0;
	    else
		crtc_gamma->red[i] = dmin(pow((double)i/(double)(size - 1),
					      gammaRed) * output->brightness,
					  1.0) * 65535.0;

	    if (gammaGreen == 1.0 && output->brightness == 1.0)
		crtc_gamma->green[i] = (double)i / (double)(size - 1) * 65535.0;
	    else
		crtc_gamma->green[i] = dmin(pow((double)i/(double)(size - 1),
						gammaGreen) * output->brightness,
					    1.0) * 65535.0;

	    if (gammaBlue == 1.0 && output->brightness == 1.0)
		crtc_gamma->blue[i] = (double)i / (double)(size - 1) * 65535.0;
	    else
		crtc_gamma->blue[i] = dmin(pow((double)i/(double)(size - 1),
					       gammaBlue) * output->brightness,
					   1.0) * 65535.0;
	}

	XRRSetCrtcGamma(dpy, crtc->crtc.xid, crtc_gamma);

	free(crtc_gamma);
    }
}

static void
set_primary(void)
{
    if (no_primary) {
	XRRSetOutputPrimary(dpy, root, None);
    } else {
	for (output_t *output = all_outputs; output; output = output->next) {
	    if (!(output->changes & changes_primary))
		continue;
	    if (output->primary)
		XRRSetOutputPrimary(dpy, root, output->output.xid);
	}
    }
}

static Status
crtc_disable (crtc_t *crtc)
{
    if (verbose)
    	printf ("crtc %d: disable\n", crtc->crtc.index);
	
    if (dryrun)
	return RRSetConfigSuccess;
    return XRRSetCrtcConfig (dpy, res, crtc->crtc.xid, CurrentTime,
			     0, 0, None, RR_Rotate_0, NULL, 0);
}

static void
crtc_set_transform (crtc_t *crtc, transform_t *transform)
{
    int	major, minor;

    XRRQueryVersion (dpy, &major, &minor);
    if (major > 1 || (major == 1 && minor >= 3))
	XRRSetCrtcTransform (dpy, crtc->crtc.xid,
			     &transform->transform,
			     transform->filter,
			     transform->params,
			     transform->nparams);
}

static Status
crtc_revert (crtc_t *crtc)
{
    XRRCrtcInfo	*crtc_info = crtc->crtc_info;
    
    if (verbose)
    	printf ("crtc %d: revert\n", crtc->crtc.index);
	
    if (dryrun)
	return RRSetConfigSuccess;

    if (!equal_transform (&crtc->current_transform, &crtc->pending_transform))
	crtc_set_transform (crtc, &crtc->current_transform);
    return XRRSetCrtcConfig (dpy, res, crtc->crtc.xid, CurrentTime,
			    crtc_info->x, crtc_info->y,
			    crtc_info->mode, crtc_info->rotation,
			    crtc_info->outputs, crtc_info->noutput);
}

static Status
crtc_apply (crtc_t *crtc)
{
    RROutput	*rr_outputs;
    Status	s;
    RRMode	mode = None;

    if (!crtc->changing || !crtc->mode_info)
	return RRSetConfigSuccess;

    rr_outputs = calloc (crtc->noutput, sizeof (RROutput));
    if (!rr_outputs)
	return BadAlloc;
    for (int o = 0; o < crtc->noutput; o++)
	rr_outputs[o] = crtc->outputs[o]->output.xid;
    mode = crtc->mode_info->id;
    if (verbose) {
	printf ("crtc %d: %12s %6.2f +%d+%d", crtc->crtc.index,
		crtc->mode_info->name, mode_refresh (crtc->mode_info),
		crtc->x, crtc->y);
	for (int o = 0; o < crtc->noutput; o++)
	    printf (" \"%s\"", crtc->outputs[o]->output.string);
	printf ("\n");
    }
    
    if (dryrun)
	s = RRSetConfigSuccess;
    else
    {
	if (!equal_transform (&crtc->current_transform, &crtc->pending_transform))
	    crtc_set_transform (crtc, &crtc->pending_transform);
	s = XRRSetCrtcConfig (dpy, res, crtc->crtc.xid, CurrentTime,
			      crtc->x, crtc->y, mode, crtc->rotation,
			      rr_outputs, crtc->noutput);
	if (s == RRSetConfigSuccess && crtc->panning_info) {
	    if (has_1_3)
		s = XRRSetPanning (dpy, res, crtc->crtc.xid, crtc->panning_info);
	    else
		fatal ("panning needs RandR 1.3\n");
	}
    }
    free (rr_outputs);
    return s;
}

static void
screen_revert (void)
{
    if (verbose)
	printf ("screen %d: revert\n", screen);

    if (dryrun)
	return;
    XRRSetScreenSize (dpy, root,
		      DisplayWidth (dpy, screen),
		      DisplayHeight (dpy, screen),
		      DisplayWidthMM (dpy, screen),
		      DisplayHeightMM (dpy, screen));
}

static void
screen_apply (void)
{
    if (fb_width == DisplayWidth (dpy, screen) &&
	fb_height == DisplayHeight (dpy, screen) &&
	fb_width_mm == DisplayWidthMM (dpy, screen) &&
	fb_height_mm == DisplayHeightMM (dpy, screen))
    {
	return;
    }
    if (verbose)
	printf ("screen %d: %dx%d %dx%d mm %6.2fdpi\n", screen,
		fb_width, fb_height, fb_width_mm, fb_height_mm, dpi);
    if (dryrun)
	return;
    XRRSetScreenSize (dpy, root, fb_width, fb_height,
		      fb_width_mm, fb_height_mm);
}

static void
revert (void)
{
    /* first disable all crtcs */
    for (int c = 0; c < res->ncrtc; c++)
	crtc_disable (&crtcs[c]);
    /* next reset screen size */
    screen_revert ();
    /* now restore all crtcs */
    for (int c = 0; c < res->ncrtc; c++)
	crtc_revert (&crtcs[c]);
}

/*
 * uh-oh, something bad happened in the middle of changing
 * the configuration. Revert to the previous configuration
 * and bail
 */
static void _X_NORETURN
panic (Status s, crtc_t *crtc)
{
    int	    c = crtc->crtc.index;
    const char *message;
    
    switch (s) {
    case RRSetConfigSuccess:		message = "succeeded";		    break;
    case BadAlloc:			message = "out of memory";	    break;
    case RRSetConfigFailed:		message = "failed";		    break;
    case RRSetConfigInvalidConfigTime:	message = "invalid config time";    break;
    case RRSetConfigInvalidTime:	message = "invalid time";	    break;
    default:				message = "unknown failure";	    break;
    }
    
    fprintf (stderr, "%s: Configure crtc %d %s\n", program_name, c, message);
    revert ();
    exit (1);
}

static void
apply (void)
{
    Status  s;
    
    /*
     * Hold the server grabbed while messing with
     * the screen so that apps which notice the resize
     * event and ask for xinerama information from the server
     * receive up-to-date information
     */
    if (grab_server)
	XGrabServer (dpy);
    
    /*
     * Turn off any crtcs which are to be disabled or which
     * need to be updated
     */
    for (int c = 0; c < res->ncrtc; c++)
    {
	crtc_t	    *crtc = &crtcs[c];
	XRRCrtcInfo *crtc_info = crtc->crtc_info;

	/* if this crtc is already disabled, skip it */
	if (crtc_info->mode == None) 
	    continue;
	
	/* 
	 * If this crtc is to be left enabled, make
	 * sure the new geometry is unchanged and fits
	 */
	if (crtc->mode_info) 
	{
	    XRRModeInfo	*old_mode = find_mode_by_xid (crtc_info->mode);
	    box_t cur, pending;

	    if (!old_mode) 
		panic (RRSetConfigFailed, crtc);

	    mode_geometry (old_mode, crtc_info->rotation,
			   &crtc->current_transform.transform, &cur);
	    mode_geometry (crtc->mode_info, crtc_info->rotation,
			   &crtc->pending_transform.transform, &pending);

	    if (cur.x1 == pending.x1 && cur.x2 == pending.x2 &&
	        cur.y1 == pending.y1 && cur.y2 == pending.y2) {
		int x = crtc_info->x + cur.x1;
		int y = crtc_info->y + cur.y1;
		int w = cur.x2 - cur.x1;
		int h = cur.y2 - cur.y1;

		/* if it fits, skip it */
		if (x + w <= fb_width && y + h <= fb_height)
		    continue;
	    }
	    crtc->changing = True;
	}
	s = crtc_disable (crtc);
	if (s != RRSetConfigSuccess)
	    panic (s, crtc);
    }

    /*
     * Set the screen size
     */
    screen_apply ();
    
    /*
     * Set crtcs
     */

    for (int c = 0; c < res->ncrtc; c++)
    {
	crtc_t	*crtc = &crtcs[c];
	
	s = crtc_apply (crtc);
	if (s != RRSetConfigSuccess)
	    panic (s, crtc);
    }

    set_primary ();

    /*
     * Release the server grab and let all clients
     * respond to the updated state
     */
    if (grab_server)
	XUngrabServer (dpy);
}

/*
 * Use current output state to complete the output list
 */
static void
get_outputs (void)
{
    for (int o = 0; o < res->noutput; o++)
    {
	XRROutputInfo	*output_info = XRRGetOutputInfo (dpy, res, res->outputs[o]);
	output_t	*output;
	name_t		output_name;
	if (!output_info) fatal ("could not get output 0x%lx information\n", res->outputs[o]);
	init_name(&output_name);
	set_name_xid (&output_name, res->outputs[o]);
	set_name_index (&output_name, o);
	set_name_string (&output_name, output_info->name);
	output = find_output (&output_name);
	if (!output)
	{
	    output = add_output ();
	    set_name_all (&output->output, &output_name);
	    /*
	     * When global --automatic mode is set, turn on connected but off
	     * outputs, turn off disconnected but on outputs
	     */
	    if (automatic)
	    {
		switch (output_info->connection) {
		case RR_Connected:
		    if (!output_info->crtc) {
			output->changes |= changes_automatic;
			output->automatic = True;
		    }
		    break;
		case RR_Disconnected:
		    if (output_info->crtc)
		    {
			output->changes |= changes_automatic;
			output->automatic = True;
		    }
		    break;
		}
	    }
	}
	output->found = True;

	/*
	 * Automatic mode -- track connection state and enable/disable outputs
	 * as necessary
	 */
	if (output->automatic)
	{
	    switch (output_info->connection) {
	    case RR_Connected:
	    case RR_UnknownConnection:
		if ((!(output->changes & changes_mode)))
		{
		    set_name_preferred (&output->mode);
		    output->changes |= changes_mode;
		}
		break;
	    case RR_Disconnected:
		if ((!(output->changes & changes_mode)))
		{
		    set_name_xid (&output->mode, None);
		    set_name_xid (&output->crtc, None);
		    output->changes |= changes_mode;
		    output->changes |= changes_crtc;
		}
		break;
	    }
	}

	set_output_info (output, res->outputs[o], output_info);
    }
    for (output_t *q = all_outputs; q; q = q->next)
    {
	if (!q->found)
	{
	    fprintf(stderr, "warning: output %s not found; ignoring\n",
		    q->output.string);
	}
    }
}

static void
mark_changing_crtcs (void)
{
    for (int c = 0; c < num_crtcs; c++)
    {
	crtc_t	    *crtc = &crtcs[c];
	output_t    *output;

	/* walk old output list (to catch disables) */
	for (int o = 0; o < crtc->crtc_info->noutput; o++)
	{
	    output = find_output_by_xid (crtc->crtc_info->outputs[o]);
	    if (!output) fatal ("cannot find output 0x%lx\n",
				crtc->crtc_info->outputs[o]);
	    if (output->changes)
		crtc->changing = True;
	}
	/* walk new output list */
	for (int o = 0; o < crtc->noutput; o++)
	{
	    output = crtc->outputs[o];
	    if (output->changes)
		crtc->changing = True;
	}
    }
}

/*
 * Test whether 'crtc' can be used for 'output'
 */
static Bool
check_crtc_for_output (crtc_t *crtc, output_t *output)
{
    int		c;
    int		l;
    output_t    *other;
    
    for (c = 0; c < output->output_info->ncrtc; c++)
	if (output->output_info->crtcs[c] == crtc->crtc.xid)
	    break;
    if (c == output->output_info->ncrtc)
	return False;
    for (other = all_outputs; other; other = other->next)
    {
	if (other == output)
	    continue;

	if (other->mode_info == NULL)
	    continue;

	if (other->crtc_info != crtc)
	    continue;

	/* see if the output connected to the crtc can clone to this output */
	for (l = 0; l < output->output_info->nclone; l++)
	    if (output->output_info->clones[l] == other->output.xid)
		break;
	/* not on the list, can't clone */
	if (l == output->output_info->nclone) 
	    return False;
    }

    if (crtc->noutput)
    {
	/* make sure the state matches */
	if (crtc->mode_info != output->mode_info)
	    return False;
	if (crtc->x != output->x)
	    return False;
	if (crtc->y != output->y)
	    return False;
	if (crtc->rotation != output->rotation)
	    return False;
	if (!equal_transform (&crtc->current_transform, &output->transform))
	    return False;
    }
    else if (crtc->crtc_info->noutput)
    {
	/* make sure the state matches the already used state */
	XRRModeInfo *mode = find_mode_by_xid (crtc->crtc_info->mode);

	if (mode != output->mode_info)
	    return False;
	if (crtc->crtc_info->x != output->x)
	    return False;
	if (crtc->crtc_info->y != output->y)
	    return False;
	if (crtc->crtc_info->rotation != output->rotation)
	    return False;
    }
    return True;
}

static crtc_t *
find_crtc_for_output (output_t *output)
{
    for (int c = 0; c < output->output_info->ncrtc; c++)
    {
	crtc_t	    *crtc;

	crtc = find_crtc_by_xid (output->output_info->crtcs[c]);
	if (!crtc) fatal ("cannot find crtc 0x%lx\n", output->output_info->crtcs[c]);

	if (check_crtc_for_output (crtc, output))
	    return crtc;
    }
    return NULL;
}

static void
set_positions (void)
{
    output_t	*output;
    int		min_x, min_y;

    for (;;)
    {
	Bool	any_set = False;
	Bool	keep_going = False;

	for (output = all_outputs; output; output = output->next)
	{
	    output_t    *relation;
	    name_t	relation_name;

	    if (!(output->changes & changes_relation)) continue;
	    
	    if (output->mode_info == NULL) continue;

	    init_name (&relation_name);
	    set_name_string (&relation_name, output->relative_to);
	    relation = find_output (&relation_name);
	    if (!relation) fatal ("cannot find output \"%s\"\n", output->relative_to);
	    
	    if (relation->mode_info == NULL) 
	    {
		output->x = 0;
		output->y = 0;
		output->changes |= changes_position;
		any_set = True;
		continue;
	    }
	    /*
	     * Make sure the dependent object has been set in place
	     */
	    if ((relation->changes & changes_relation) && 
		!(relation->changes & changes_position))
	    {
		keep_going = True;
		continue;
	    }
	    
	    switch (output->relation) {
	    case relation_left_of:
		output->y = relation->y;
		output->x = relation->x - mode_width (output->mode_info, output->rotation);
		break;
	    case relation_right_of:
		output->y = relation->y;
		output->x = relation->x + mode_width (relation->mode_info, relation->rotation);
		break;
	    case relation_above:
		output->x = relation->x;
		output->y = relation->y - mode_height (output->mode_info, output->rotation);
		break;
	    case relation_below:
		output->x = relation->x;
		output->y = relation->y + mode_height (relation->mode_info, relation->rotation);
		break;
	    case relation_same_as:
		output->x = relation->x;
		output->y = relation->y;
	    }
	    output->changes |= changes_position;
	    any_set = True;
	}
	if (!keep_going)
	    break;
	if (!any_set)
	    fatal ("loop in relative position specifications\n");
    }

    /*
     * Now normalize positions so the upper left corner of all outputs is at 0,0
     */
    min_x = 32768;
    min_y = 32768;
    for (output = all_outputs; output; output = output->next)
    {
	if (output->mode_info == NULL) continue;
	
	if (output->x < min_x) min_x = output->x;
	if (output->y < min_y) min_y = output->y;
    }
    if (min_x || min_y)
    {
	/* move all outputs */
	for (output = all_outputs; output; output = output->next)
	{
	    if (output->mode_info == NULL) continue;

	    output->x -= min_x;
	    output->y -= min_y;
	    output->changes |= changes_position;
	}
    }
}

static void
set_screen_size (void)
{
    Bool	fb_specified = fb_width != 0 && fb_height != 0;
    
    for (output_t *output = all_outputs; output; output = output->next)
    {
	XRRModeInfo *mode_info = output->mode_info;
	int	    x, y, w, h;
	box_t	    bounds;
	
	if (!mode_info) continue;
	
	mode_geometry (mode_info, output->rotation,
		       &output->transform.transform,
		       &bounds);
	x = output->x + bounds.x1;
	y = output->y + bounds.y1;
	w = bounds.x2 - bounds.x1;
	h = bounds.y2 - bounds.y1;
	/* make sure output fits in specified size */
	if (fb_specified)
	{
	    if (x + w > fb_width || y + h > fb_height)
		warning ("specified screen %dx%d not large enough for output %s (%dx%d+%d+%d)\n",
			 fb_width, fb_height, output->output.string, w, h, x, y);
	}
	/* fit fb to output */
	else
	{
	    XRRPanning *pan;
	    if (x + w > fb_width)
		fb_width = x + w;
	    if (y + h > fb_height)
		fb_height = y + h;
	    if (output->changes & changes_panning)
		pan = &output->panning;
	    else
		pan = output->crtc_info ? output->crtc_info->panning_info : NULL;
	    if (pan && pan->left + pan->width > fb_width)
		fb_width = pan->left + pan->width;
	    if (pan && pan->top + pan->height > fb_height)
		fb_height = pan->top + pan->height;
	}
    }	

    if (fb_width > maxWidth || fb_height > maxHeight)
        fatal ("screen cannot be larger than %dx%d (desired size %dx%d)\n",
	       maxWidth, maxHeight, fb_width, fb_height);
    if (fb_specified)
    {
	if (fb_width < minWidth || fb_height < minHeight)
	    fatal ("screen must be at least %dx%d\n", minWidth, minHeight);
    }
    else
    {
	if (fb_width < minWidth) fb_width = minWidth;
	if (fb_height < minHeight) fb_height = minHeight;
    }
}
    

static void
disable_outputs (output_t *outputs)
{
    while (outputs)
    {
	outputs->crtc_info = NULL;
	outputs = outputs->next;
    }
}

/*
 * find the best mapping from output to crtc available
 */
static int
pick_crtcs_score (output_t *outputs)
{
    output_t	*output;
    int		best_score;
    int		my_score;
    int		score;
    crtc_t	*best_crtc;
    
    if (!outputs)
	return 0;
    
    output = outputs;
    outputs = outputs->next;
    /*
     * Score with this output disabled
     */
    output->crtc_info = NULL;
    best_score = pick_crtcs_score (outputs);
    if (output->mode_info == NULL)
	return best_score;

    best_crtc = NULL;
    /* 
     * Now score with this output any valid crtc
     */
    for (int c = 0; c < output->output_info->ncrtc; c++)
    {
	crtc_t	    *crtc;

	crtc = find_crtc_by_xid (output->output_info->crtcs[c]);
	if (!crtc)
	    fatal ("cannot find crtc 0x%lx\n", output->output_info->crtcs[c]);
	
	/* reset crtc allocation for following outputs */
	disable_outputs (outputs);
	if (!check_crtc_for_output (crtc, output))
	    continue;
	
	my_score = 1000;
	/* slight preference for existing connections */
	if (crtc == output->current_crtc_info)
	    my_score++;

	output->crtc_info = crtc;
	score = my_score + pick_crtcs_score (outputs);
	if (score > best_score)
	{
	    best_crtc = crtc;
	    best_score = score;
	}
    }
    if (output->crtc_info != best_crtc)
	output->crtc_info = best_crtc;
    /*
     * Reset other outputs based on this one using the best crtc
     */
    (void) pick_crtcs_score (outputs);

    return best_score;
}

/*
 * Pick crtcs for any changing outputs that don't have one
 */
static void
pick_crtcs (void)
{
    output_t	*output;
    int saved_crtc_noutput[num_crtcs];

    /*
     * First try to match up newly enabled outputs with spare crtcs
     */
    for (output = all_outputs; output; output = output->next)
    {
	if (output->changes && output->mode_info)
	{
	    if (output->crtc_info) {
		if (output->crtc_info->crtc_info->noutput > 0 &&
		    (output->crtc_info->crtc_info->noutput > 1 ||
		     output != find_output_by_xid (output->crtc_info->crtc_info->outputs[0])))
		    break;
	    } else {
		output->crtc_info = find_crtc_for_output (output);
		if (!output->crtc_info)
		    break;
	    }
	}
    }
    /*
     * Everyone is happy
     */
    if (!output)
	return;
    /*
     * When the simple way fails, see if there is a way
     * to swap crtcs around and make things work
     */
    for (output = all_outputs; output; output = output->next)
	output->current_crtc_info = output->crtc_info;

    /* Mark all CRTC as currently unused */
    for (int n = 0; n < num_crtcs; n++) {
	    saved_crtc_noutput[n] = crtcs[n].crtc_info->noutput;
	    crtcs[n].crtc_info->noutput = 0;
    }

    pick_crtcs_score (all_outputs);

    for (int n = 0; n < num_crtcs; n++)
	    crtcs[n].crtc_info->noutput = saved_crtc_noutput[n];

    for (output = all_outputs; output; output = output->next)
    {
	if (output->mode_info && !output->crtc_info)
	    fatal ("cannot find crtc for output %s\n", output->output.string);
	if (!output->changes && output->crtc_info != output->current_crtc_info)
	    output->changes |= changes_crtc;
    }
}

static int
check_strtol(char *s)
{
    char *endptr;
    int result = strtol(s, &endptr, 10);
    if (s == endptr)
	argerr ("failed to parse '%s' as a number\n", s);
    return result;
}

static double
check_strtod(char *s)
{
    char *endptr;
    double result = strtod(s, &endptr);
    if (s == endptr)
	argerr ("failed to parse '%s' as a number\n", s);
    return result;
}

static void *
ctm_from_string(const char *str, int *returned_nitems)
{
    double ctm[9];
    long *prop;
    int i;

    if (sscanf (str, "%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf",
		&ctm[0],&ctm[1],&ctm[2],
		&ctm[3],&ctm[4],&ctm[5],
		&ctm[6],&ctm[7],&ctm[8]) != 9)
	return NULL;

    prop = malloc (2*9*sizeof(prop[0]));
    if (!prop)
	return NULL;

    for (i = 0; i < 9; i++) {
	unsigned long long tmp;

	tmp = fabs (ctm[i]) * (1ULL << 32);
	if (ctm[i] < 0.0)
	    tmp |= 1ULL << 63;

	prop[i*2+0] = tmp & 0xffffffff;
	prop[i*2+1] = tmp >> 32;
    }

    *returned_nitems = 2*9;

    return prop;
}

static void *
property_values_from_string(const char *str, const Atom type, const int format,
                            int *returned_nitems)
{
    char *tmp;
    void *returned_bytes = NULL;
    int nitems = 0, bytes_per_item;

    if (type != XA_INTEGER && type != XA_CARDINAL)
	return NULL;

    /* compute memory needed for Xlib datatype (sigh) */
    switch (format) {
    case 8:
       bytes_per_item = sizeof(char);
       break;
    case 16:
       bytes_per_item = sizeof(short);
       break;
    case 32:
       bytes_per_item = sizeof(long);
       break;
    default:
       return NULL;
    }

    tmp = strdup (str);

    for (char *token = strtok (tmp, ","); token; token = strtok (NULL, ","))
    {
	char *endptr;
	long int val = strtol (token, &endptr, 0);

	if (token == endptr || *endptr != '\0')
	{
	    argerr ("failed to parse '%s' as a number\n", token);
	}

	returned_bytes = realloc (returned_bytes, (nitems + 1) * bytes_per_item);

	if (type == XA_INTEGER && format == 8)
	{
	    signed char *ptr = returned_bytes;
	    ptr[nitems] = (char) val;
	}
	else if (type == XA_INTEGER && format == 16)
	{
	    short *ptr = returned_bytes;
	    ptr[nitems] = (short) val;
	}
	else if (type == XA_INTEGER && format == 32)
	{
	    long *ptr = returned_bytes;
	    ptr[nitems] = (long) val;
	}
	else if (type == XA_CARDINAL && format == 8)
	{
	    unsigned char *ptr = returned_bytes;
	    ptr[nitems] = (unsigned char) val;
	}
	else if (type == XA_CARDINAL && format == 16)
	{
	    unsigned short *ptr = returned_bytes;
	    ptr[nitems] = (unsigned short) val;
	}
	else if (type == XA_CARDINAL && format == 32)
	{
	    unsigned long *ptr = returned_bytes;
	    ptr[nitems] = (unsigned long) val;
	}
	else
	{
	    free (tmp);
	    free (returned_bytes);
	    return NULL;
	}

	nitems++;
    }

    free (tmp);

    *returned_nitems = nitems;
    return returned_bytes;
}


static void
print_output_property_value(int value_format, /* 8, 16, 32 */
                            Atom value_type,  /* XA_{ATOM,INTEGER,CARDINAL} */
                            const void *value_bytes)
{
    if (value_type == XA_ATOM && value_format == 32)
    {
	const Atom *val = value_bytes;
	char *str = XGetAtomName (dpy, *val);
	if (str != NULL)
	{
	    printf ("%s", str);
	    XFree (str);
	    return;
	}
    }

    if (value_type == XA_INTEGER)
    {
	if (value_format == 8)
	{
	    const signed char *val = value_bytes;
	    printf ("%d", *val);
	    return;
	}
	if (value_format == 16)
	{
	    const short *val = value_bytes;
	    printf ("%d", *val);
	    return;
	}
	if (value_format == 32)
	{
	    const long *val = value_bytes;
	    printf ("%ld", *val);
	    return;
	}
    }

    if (value_type == XA_CARDINAL)
    {
	if (value_format == 8)
	{
	    const unsigned char *val = value_bytes;
	    printf ("%u", *val);
	    return;
	}
	if (value_format == 16)
	{
	    const unsigned short *val = value_bytes;
	    printf ("%u", *val);
	    return;
	}
	if (value_format == 32)
	{
	    const unsigned long *val = value_bytes;
	    printf ("%lu", *val);
	    return;
	}
    }

    printf ("?");
}

static void
print_edid(int nitems, const unsigned char *prop)
{
    printf ("\n\t\t");

    for (int k = 0; k < nitems; k++)
    {
	if (k != 0 && (k % 16) == 0)
	{
	    printf ("\n\t\t");
	}

	printf("%02" PRIx8, prop[k]);
    }

    printf("\n");
}

static void
print_guid(const unsigned char *prop)
{
    printf("{");

    for (int k = 0; k < 16; k++)
    {
	printf("%02" PRIX8, prop[k]);
	if (k == 3 || k == 5 || k == 7 || k == 9)
	{
	    printf("-");
	}
    }

    printf("}\n");
}

static void
print_ctm(const unsigned long *prop)
{
    printf("\t");
    for (int i = 0; i < 9; i++)
    {
	unsigned long long tmp;
	double c;

	tmp = prop[2*i+1];
	tmp <<= 32;
	tmp |= prop[2*i+0];

	c = (double)(tmp & ~(1ULL << 63)) / (1ULL << 32);
	if (tmp & (1ULL << 63))
	    c = -c;

	printf("%f", c);
	if (i == 2 || i == 5)
	    printf("\n\t\t");
	else if (i != 8)
	    printf(" ");
    }
    printf("\n");
}

static void
print_output_property(const char *atom_name,
                      int value_format,
                      Atom value_type,
                      int nitems,
                      const unsigned char *prop)
{
    int bytes_per_item;

    switch (value_format) {
    case 8:
       bytes_per_item = sizeof(char);
       break;
    case 16:
       bytes_per_item = sizeof(short);
       break;
    case 32:
       bytes_per_item = sizeof(long);
       break;
    default:
       return;
    }
    /*
     * Check for properties that need special formatting.
     */
    if (strcmp (atom_name, "EDID") == 0 && value_format == 8 &&
	value_type == XA_INTEGER)
    {
	print_edid (nitems, prop);
	return;
    }
    else if (strcmp (atom_name, "GUID") == 0 && value_format == 8 &&
	     value_type == XA_INTEGER && nitems == 16)
    {
	print_guid (prop);
	return;
    }
    else if (strcmp (atom_name, "CTM") == 0 && value_format == 32 &&
	     value_type == XA_INTEGER && nitems == 9*2)
    {
	print_ctm ((unsigned long *)prop);
	return;
    }

    for (int k = 0; k < nitems; k++)
    {
	if (k != 0)
	{
	    if ((k % 16) == 0)
	    {
		printf ("\n\t\t");
	    }
	}
	print_output_property_value (value_format, value_type,
				     prop + (k * bytes_per_item));
	printf (" ");
    }

    printf ("\n");
}

static void
get_providers (void)
{
    XRRProviderResources *pr;

    if (!has_1_4 || providers)
	return;

    pr = XRRGetProviderResources(dpy, root);
    num_providers = pr->nproviders;
    providers = calloc (num_providers, sizeof (provider_t));
    if (!providers)
	fatal ("out of memory\n");

    for (int i = 0; i < num_providers; i++) {
	provider_t *provider = &providers[i];
	name_t *name = &provider->provider;
	XRRProviderInfo *info = XRRGetProviderInfo(dpy, res, pr->providers[i]);

	provider->info = info;
	set_name_xid (name, pr->providers[i]);
	set_name_index (name, i);
	set_name_string (name, info->name);
   }

   XRRFreeProviderResources(pr);
}

static provider_t *
find_provider (name_t *name)
{
    if ((name->kind & name_xid) && name->xid == 0)
	return NULL;
    for (int i = 0; i < num_providers; i++) {
	provider_t *p = &providers[i];
	name_kind_t common = name->kind & p->provider.kind;

	if ((common & name_xid) && name->xid == p->provider.xid)
	    return p;
	if ((common & name_string) && !strcmp (name->string, p->provider.string))
	    return p;
	if ((common & name_index) && name->index == p->provider.index)
	    return p;
    }

    printf ("Could not find provider with ");
    print_name (name);
    printf ("\n");
    exit (1);
}

static void
get_monitors(Bool get_active)
{
    XRRMonitorInfo	*m;
    int			n;

    if (!has_1_5 || monitors)
	return;

    m = XRRGetMonitors(dpy, root, get_active, &n);
    if (n == -1)
	fatal("get monitors failed\n");
    monitors = calloc(1, sizeof (monitors_t));
    monitors->n = n;
    monitors->monitors = m;
}

int
main (int argc, char **argv)
{
    XRRScreenSize *sizes;
    XRRScreenConfiguration *sc;
    int		nsize;
    int		nrate;
    Status	status = RRSetConfigFailed;
    int		rot = -1;
    int		query = False;
    int		action_requested = False;
    Rotation	current_rotation;
    XEvent	event;
    XRRScreenChangeNotifyEvent *sce;    
    char       *display_name = NULL;
    SizeID	current_size;
    short	current_rate;
    double    	rate = -1;
    int		size = -1;
    int		dirind = 0;
    Bool	setit = False;
    Bool    	version = False;
    int		event_base, error_base;
    int		reflection = 0;
    int		width = 0, height = 0;
    Bool    	have_pixel_size = False;
    int		ret = 0;
    output_t	*config_output = NULL;
    Bool    	setit_1_2 = False;
    Bool    	query_1_2 = False;
    Bool	modeit = False;
    Bool	propit = False;
    Bool	query_1 = False;
    Bool	list_providers = False;
    Bool        provsetoutsource = False;
    Bool        provsetoffsink = False;
    Bool	monitorit = False;
    Bool	list_monitors = False;
    Bool	list_active_monitors = False;
    int		major, minor;
    Bool	current = False;
    Bool	toggle_x = False;
    Bool	toggle_y = False;

    program_name = argv[0];
    for (int i = 1; i < argc; i++) {
	if (!strcmp ("-display", argv[i]) || !strcmp ("--display", argv[i]) ||
	    !strcmp ("-d", argv[i])) {
	    if (++i >= argc) argerr ("%s requires an argument\n", argv[i-1]);
	    display_name = argv[i];
	    continue;
	}
	if (!strcmp("-help", argv[i]) || !strcmp("--help", argv[i])) {
	    usage();
	    exit(0);
	}
	if (!strcmp ("--verbose", argv[i])) {
	    verbose = True;
	    continue;
	}
	if (!strcmp ("--dryrun", argv[i])) {
	    dryrun = True;
	    verbose = True;
	    continue;
	}
	if (!strcmp ("--nograb", argv[i])) {
	    grab_server = False;
	    continue;
	}
	if (!strcmp("--current", argv[i])) {
	    current = True;
	    continue;
	}

	if (!strcmp ("-s", argv[i]) || !strcmp ("--size", argv[i])) {
	    if (++i >= argc) argerr ("%s requires an argument\n", argv[i-1]);
	    if (sscanf (argv[i], "%dx%d", &width, &height) == 2) {
		have_pixel_size = True;
	    } else {
		size = check_strtol(argv[i]);
                if (size < 0) argerr ("--size argument must be nonnegative\n");
            }
	    setit = True;
	    action_requested = True;
	    continue;
	}

	if (!strcmp ("-r", argv[i]) ||
	    !strcmp ("--rate", argv[i]) ||
	    !strcmp ("--refresh", argv[i]))
	{
	    if (++i >= argc) argerr ("%s requires an argument\n", argv[i-1]);
	    rate = check_strtod(argv[i]);
	    setit = True;
	    if (config_output)
	    {
		config_output->refresh = rate;
		config_output->changes |= changes_refresh;
		setit_1_2 = True;
	    }
	    action_requested = True;
	    continue;
	}

	if (!strcmp ("-v", argv[i]) || !strcmp ("--version", argv[i])) {
	    version = True;
	    action_requested = True;
	    continue;
	}

	if (!strcmp ("-x", argv[i])) {
	    toggle_x = True;
	    setit = True;
	    action_requested = True;
	    continue;
	}
	if (!strcmp ("-y", argv[i])) {
	    toggle_y = True;
	    setit = True;
	    action_requested = True;
	    continue;
	}
	if (!strcmp ("--screen", argv[i])) {
	    if (++i >= argc) argerr ("%s requires an argument\n", argv[i-1]);
	    screen = check_strtol(argv[i]);
	    if (screen < 0) argerr ("--screen argument must be nonnegative\n");
	    continue;
	}
	if (!strcmp ("-q", argv[i]) || !strcmp ("--query", argv[i])) {
	    query = True;
	    continue;
	}
	if (!strcmp ("-o", argv[i]) || !strcmp ("--orientation", argv[i])) {
	    char *endptr;
	    if (++i >= argc) argerr ("%s requires an argument\n", argv[i-1]);
	    dirind = strtol(argv[i], &endptr, 10);
	    if (argv[i] == endptr) {
		for (dirind = 0; dirind < 4; dirind++) {
		    if (strcmp (direction[dirind], argv[i]) == 0) break;
		}
	    }
	    if ((dirind < 0) || (dirind > 3))
		argerr ("%s: invalid argument '%s'\n", argv[i-1], argv[i]);
	    rot = dirind;
	    setit = True;
	    action_requested = True;
	    continue;
	}
	if (!strcmp ("--prop", argv[i]) ||
	    !strcmp ("--props", argv[i]) ||
	    !strcmp ("--madprops", argv[i]) ||
	    !strcmp ("--properties", argv[i]))
	{
	    query_1_2 = True;
	    properties = True;
	    action_requested = True;
	    continue;
	}
	if (!strcmp ("--output", argv[i])) {
	    if (++i >= argc) argerr ("%s requires an argument\n", argv[i-1]);

	    config_output = find_output_by_name (argv[i]);
	    if (!config_output) {
		config_output = add_output ();
		set_name (&config_output->output, argv[i], name_string|name_xid);
	    }
	    
	    setit_1_2 = True;
	    action_requested = True;
	    continue;
	}
	if (!strcmp("--filter", argv[i])) {
	    if (!config_output) argerr ("%s must be used after --output\n", argv[i]);
	    if (++i >= argc) argerr("%s requires an argument\n", argv[i-1]);

	    filter_type = -1;
	    for (size_t t = 0; t < sizeof(filter_names) / sizeof(filter_names[0]); t++)
	    {
		if (!strcmp(filter_names[t], argv[i]))
		{
		    filter_type = t;
		    break;
		}
	    }

	    if (filter_type == -1) argerr("Bad argument: %s, for a filter\n", argv[i]);

	    config_output->changes |= changes_filter;
	    action_requested = True;
	    continue;
	}
	if (!strcmp ("--crtc", argv[i])) {
	    if (!config_output) argerr ("%s must be used after --output\n", argv[i]);
	    if (++i >= argc) argerr ("%s requires an argument\n", argv[i-1]);
	    set_name (&config_output->crtc, argv[i], name_xid|name_index);
	    config_output->changes |= changes_crtc;
	    continue;
	}
	if (!strcmp ("--mode", argv[i])) {
	    if (!config_output) argerr ("%s must be used after --output\n", argv[i]);
	    if (++i >= argc) argerr ("%s requires an argument\n", argv[i-1]);
	    set_name (&config_output->mode, argv[i], name_string|name_xid);
	    config_output->changes |= changes_mode;
	    continue;
	}
	if (!strcmp ("--preferred", argv[i])) {
	    if (!config_output) argerr ("%s must be used after --output\n", argv[i]);
	    set_name_preferred (&config_output->mode);
	    config_output->changes |= changes_mode;
	    continue;
	}
	if (!strcmp ("--pos", argv[i])) {
	    if (!config_output) argerr ("%s must be used after --output\n", argv[i]);
	    if (++i >= argc) argerr ("%s requires an argument\n", argv[i-1]);
	    if (sscanf (argv[i], "%dx%d",
			&config_output->x, &config_output->y) != 2)
		argerr ("failed to parse '%s' as a position\n", argv[i]);
	    config_output->changes |= changes_position;
	    continue;
	}
	if (!strcmp ("--rotation", argv[i]) || !strcmp ("--rotate", argv[i])) {
	    if (!config_output) argerr ("%s must be used after --output\n", argv[i]);
	    if (++i >= argc) argerr ("%s requires an argument\n", argv[i-1]);
	    for (dirind = 0; dirind < 4; dirind++) {
		if (strcmp (direction[dirind], argv[i]) == 0) break;
	    }
	    if (dirind == 4)
		argerr ("%s: invalid argument '%s'\n", argv[i-1], argv[i]);
	    config_output->rotation &= ~0xf;
	    config_output->rotation |= 1 << dirind;
	    config_output->changes |= changes_rotation;
	    continue;
	}
	if (!strcmp ("--reflect", argv[i]) || !strcmp ("--reflection", argv[i])) {
	    if (!config_output) argerr ("%s must be used after --output\n", argv[i]);
	    if (++i >= argc) argerr ("%s requires an argument\n", argv[i-1]);
	    for (dirind = 0; dirind < 4; dirind++) {
		if (strcmp (reflections[dirind], argv[i]) == 0) break;
	    }
	    if (dirind == 4)
		argerr ("%s: invalid argument '%s'\n", argv[i-1], argv[i]);
	    config_output->rotation &= ~(RR_Reflect_X|RR_Reflect_Y);
	    config_output->rotation |= dirind * RR_Reflect_X;
	    config_output->changes |= changes_reflection;
	    continue;
	}
	if (!strcmp ("--left-of", argv[i])) {
	    if (!config_output) argerr ("%s must be used after --output\n", argv[i]);
	    if (++i >= argc) argerr ("%s requires an argument\n", argv[i-1]);
	    config_output->relation = relation_left_of;
	    config_output->relative_to = argv[i];
	    config_output->changes |= changes_relation;
	    continue;
	}
	if (!strcmp ("--right-of", argv[i])) {
	    if (!config_output) argerr ("%s must be used after --output\n", argv[i]);
	    if (++i >= argc) argerr ("%s requires an argument\n", argv[i-1]);
	    config_output->relation = relation_right_of;
	    config_output->relative_to = argv[i];
	    config_output->changes |= changes_relation;
	    continue;
	}
	if (!strcmp ("--above", argv[i])) {
	    if (!config_output) argerr ("%s must be used after --output\n", argv[i]);
	    if (++i >= argc) argerr ("%s requires an argument\n", argv[i-1]);
	    config_output->relation = relation_above;
	    config_output->relative_to = argv[i];
	    config_output->changes |= changes_relation;
	    continue;
	}
	if (!strcmp ("--below", argv[i])) {
	    if (!config_output) argerr ("%s must be used after --output\n", argv[i]);
	    if (++i >= argc) argerr ("%s requires an argument\n", argv[i-1]);
	    config_output->relation = relation_below;
	    config_output->relative_to = argv[i];
	    config_output->changes |= changes_relation;
	    continue;
	}
	if (!strcmp ("--same-as", argv[i])) {
	    if (!config_output) argerr ("%s must be used after --output\n", argv[i]);
	    if (++i >= argc) argerr ("%s requires an argument\n", argv[i-1]);
	    config_output->relation = relation_same_as;
	    config_output->relative_to = argv[i];
	    config_output->changes |= changes_relation;
	    continue;
	}
	if (!strcmp ("--panning", argv[i])) {
	    XRRPanning *pan;
	    if (!config_output) argerr ("%s must be used after --output\n", argv[i]);
	    if (++i >= argc) argerr ("%s requires an argument\n", argv[i-1]);
	    pan = &config_output->panning;
	    switch (sscanf (argv[i], "%dx%d+%d+%d/%dx%d+%d+%d/%d/%d/%d/%d",
			    &pan->width, &pan->height, &pan->left, &pan->top,
			    &pan->track_width, &pan->track_height,
			    &pan->track_left, &pan->track_top,
			    &pan->border_left, &pan->border_top,
			    &pan->border_right, &pan->border_bottom)) {
	    case 2:
		pan->left = pan->top = 0;
		/* fall through */
	    case 4:
		pan->track_left = pan->track_top =
		    pan->track_width = pan->track_height = 0;
		/* fall through */
	    case 8:
		pan->border_left = pan->border_top =
		    pan->border_right = pan->border_bottom = 0;
		/* fall through */
	    case 12:
		break;
	    default:
		argerr ("%s: invalid argument '%s'\n", argv[i-1], argv[i]);
	    }
	    config_output->changes |= changes_panning;
	    continue;
	}
	if (!strcmp ("--gamma", argv[i])) {
	    char junk;
	    if (!config_output) argerr ("%s must be used after --output\n", argv[i]);
	    if (++i >= argc) argerr ("%s requires an argument\n", argv[i-1]);
	    if (sscanf(argv[i], "%f:%f:%f%c", &config_output->gamma.red,
		    &config_output->gamma.green, &config_output->gamma.blue, &junk) != 3)
	    {
		/* check if it's a single floating-point value,
		 * to be applied to all components */
		if (sscanf(argv[i], "%f%c", &config_output->gamma.red, &junk) != 1)
		    argerr ("%s: invalid argument '%s'\n", argv[i-1], argv[i]);
		config_output->gamma.green = config_output->gamma.blue = config_output->gamma.red;
	    }
	    if (config_output->gamma.red <= 0.0 || config_output->gamma.green <= 0.0 ||
		    config_output->gamma.blue <= 0.0)
		    argerr ("gamma correction factors must be positive\n");
	    config_output->changes |= changes_gamma;
	    setit_1_2 = True;
	    continue;
	}
	if (!strcmp ("--brightness", argv[i])) {
	    if (!config_output) argerr ("%s must be used after --output\n", argv[i]);
	    if (++i >= argc) argerr ("%s requires an argument\n", argv[i-1]);
	    if (sscanf(argv[i], "%f", &config_output->brightness) != 1)
		argerr ("%s: invalid argument '%s'\n", argv[i-1], argv[i]);
	    config_output->changes |= changes_gamma;
	    setit_1_2 = True;
	    continue;
	}
	if (!strcmp ("--primary", argv[i])) {
	    if (!config_output) argerr ("%s must be used after --output\n", argv[i]);
	    config_output->changes |= changes_primary;
	    config_output->primary = True;
	    setit_1_2 = True;
	    continue;
	}
	if (!strcmp ("--noprimary", argv[i])) {
	    no_primary = True;
	    setit_1_2 = True;
	    continue;
	}
	if (!strcmp ("--set", argv[i])) {
	    output_prop_t   *prop;
	    if (!config_output) argerr ("%s must be used after --output\n", argv[i]);
	    if (i+2 >= argc) argerr ("%s requires two arguments\n", argv[i]);
	    prop = malloc (sizeof (output_prop_t));
	    prop->next = config_output->props;
	    config_output->props = prop;
	    prop->name = argv[++i];
	    prop->value = argv[++i];
	    propit = True;
	    config_output->changes |= changes_property;
	    setit_1_2 = True;
	    continue;
	}
	if (!strcmp ("--scale", argv[i]))
	{
	    double  sx, sy;
	    char junk;
	    if (!config_output) argerr ("%s must be used after --output\n", argv[i]);
	    if (++i >= argc) argerr ("%s requires an argument\n", argv[i-1]);
	    if (sscanf (argv[i], "%lfx%lf%c", &sx, &sy, &junk) != 2)
	    {
		if (sscanf (argv[i], "%lf%c", &sx, &junk) != 1)
		    argerr ("failed to parse '%s' as a scaling factor\n", argv[i]);
		sy = sx;
	    }
	    if (sx <= 0.0 || sy <= 0.0)
		    argerr ("scaling factors must be positive\n");
	    init_transform (&config_output->transform);
	    config_output->transform.transform.matrix[0][0] = XDoubleToFixed (sx);
	    config_output->transform.transform.matrix[1][1] = XDoubleToFixed (sy);
	    config_output->transform.transform.matrix[2][2] = XDoubleToFixed (1.0);
	    if (sx != 1 || sy != 1)
		config_output->transform.filter = "bilinear";
	    else
		config_output->transform.filter = "nearest";
	    config_output->transform.nparams = 0;
	    config_output->transform.params = NULL;
	    config_output->changes |= changes_transform;
	    continue;
	}
	if (!strcmp ("--scale-from", argv[i]))
	{
	    int w, h;
	    if (!config_output) argerr ("%s must be used after --output\n", argv[i]);
	    if (++i >= argc) argerr ("%s requires an argument\n", argv[i-1]);
	    if (sscanf (argv[i], "%dx%d", &w, &h) != 2)
		argerr ("failed to parse '%s' as a scale-from size\n", argv[i]);
	    if (w <=0 || h <= 0)
		argerr ("--scale-from dimensions must be nonnegative\n");
	    config_output->scale_from_w = w;
	    config_output->scale_from_h = h;
	    config_output->changes |= changes_transform;
	    continue;
	}
	if (!strcmp ("--transform", argv[i])) {
	    double  transform[3][3];

	    if (!config_output) argerr ("%s must be used after --output\n", argv[i]);
	    if (++i >= argc) argerr ("%s requires an argument\n", argv[i-1]);
	    init_transform (&config_output->transform);
	    if (strcmp (argv[i], "none") != 0)
	    {
		if (sscanf(argv[i], "%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf",
			   &transform[0][0],&transform[0][1],&transform[0][2],
			   &transform[1][0],&transform[1][1],&transform[1][2],
			   &transform[2][0],&transform[2][1],&transform[2][2])
		    != 9)
		    argerr ("failed to parse '%s' as a transformation\n", argv[i]);
		init_transform (&config_output->transform);
		for (int k = 0; k < 3; k++)
		    for (int l = 0; l < 3; l++) {
			config_output->transform.transform.matrix[k][l] = XDoubleToFixed (transform[k][l]);
		    }
		config_output->transform.filter = "bilinear";
		config_output->transform.nparams = 0;
		config_output->transform.params = NULL;
	    }
	    config_output->changes |= changes_transform;
	    continue;
	}
	if (!strcmp ("--off", argv[i])) {
	    if (!config_output) argerr ("%s must be used after --output\n", argv[i]);
	    set_name_xid (&config_output->mode, None);
	    set_name_xid (&config_output->crtc, None);
	    config_output->changes |= changes_mode | changes_crtc;
	    continue;
	}
	if (!strcmp ("--fb", argv[i])) {
	    if (++i >= argc) argerr ("%s requires an argument\n", argv[i-1]);
	    if (sscanf (argv[i], "%dx%d",
			&fb_width, &fb_height) != 2)
		argerr ("failed to parse '%s' as a framebuffer size\n", argv[i]);
	    setit_1_2 = True;
	    action_requested = True;
	    continue;
	}
	if (!strcmp ("--fbmm", argv[i])) {
	    if (++i >= argc) argerr ("%s requires an argument\n", argv[i-1]);
	    if (sscanf (argv[i], "%dx%d",
			&fb_width_mm, &fb_height_mm) != 2)
		argerr ("failed to parse '%s' as a physical size\n", argv[i]);
	    setit_1_2 = True;
	    action_requested = True;
	    continue;
	}
	if (!strcmp ("--dpi", argv[i])) {
	    char *strtod_error;
	    if (++i >= argc) argerr ("%s requires an argument\n", argv[i-1]);
	    dpi = strtod(argv[i], &strtod_error);
	    if (argv[i] == strtod_error)
	    {
		dpi = 0.0;
		dpi_output_name = argv[i];
	    }
	    setit_1_2 = True;
	    action_requested = True;
	    continue;
	}
	if (!strcmp ("--auto", argv[i])) {
	    if (config_output)
	    {
		config_output->automatic = True;
		config_output->changes |= changes_automatic;
	    }
	    else
		automatic = True;
	    setit_1_2 = True;
	    action_requested = True;
	    continue;
	}
	if (!strcmp ("--q12", argv[i]))
	{
	    query_1_2 = True;
	    continue;
	}
	if (!strcmp ("--q1", argv[i]))
	{
	    query_1 = True;
	    continue;
	}
	if (!strcmp ("--newmode", argv[i]))
	{
	    umode_t  *m = calloc (1, sizeof (umode_t));
	    double    clock;
	    
	    ++i;
	    if (i + 9 >= argc)
		argerr ("failed to parse '%s' as a mode specification\n", argv[i]);
	    m->mode.name = argv[i];
	    m->mode.nameLength = strlen (argv[i]);
	    i++;
	    clock = check_strtod(argv[i++]);
	    m->mode.dotClock = clock * 1e6;

	    m->mode.width = check_strtol(argv[i++]);
	    m->mode.hSyncStart = check_strtol(argv[i++]);
	    m->mode.hSyncEnd = check_strtol(argv[i++]);
	    m->mode.hTotal = check_strtol(argv[i++]);
	    m->mode.height = check_strtol(argv[i++]);
	    m->mode.vSyncStart = check_strtol(argv[i++]);
	    m->mode.vSyncEnd = check_strtol(argv[i++]);
	    m->mode.vTotal = check_strtol(argv[i++]);
	    m->mode.modeFlags = 0;
	    while (i < argc) {
		int f;
		
		for (f = 0; mode_flags[f].string; f++)
		    if (!strcasecmp (mode_flags[f].string, argv[i]))
			break;
		
		if (!mode_flags[f].string)
		    break;
    		m->mode.modeFlags |= mode_flags[f].flag;
    		i++;
	    }
	    m->next = umodes;
	    m->action = umode_create;
	    umodes = m;
	    modeit = True;
	    action_requested = True;
	    continue;
	}
	if (!strcmp ("--rmmode", argv[i]))
	{
	    umode_t  *m = calloc (1, sizeof (umode_t));

	    if (++i >= argc) argerr ("%s requires an argument\n", argv[i-1]);
	    set_name (&m->name, argv[i], name_string|name_xid);
	    m->action = umode_destroy;
	    m->next = umodes;
	    umodes = m;
	    modeit = True;
	    action_requested = True;
	    continue;
	}
	if (!strcmp ("--addmode", argv[i]))
	{
	    umode_t  *m = calloc (1, sizeof (umode_t));

	    if (i+2 >= argc) argerr ("%s requires two arguments\n", argv[i]);
	    set_name (&m->output, argv[++i], name_string|name_xid);
	    set_name (&m->name, argv[++i], name_string|name_xid);
	    m->action = umode_add;
	    m->next = umodes;
	    umodes = m;
	    modeit = True;
	    action_requested = True;
	    continue;
	}
	if (!strcmp ("--delmode", argv[i]))
	{
	    umode_t  *m = calloc (1, sizeof (umode_t));

	    if (i+2 >= argc) argerr ("%s requires two arguments\n", argv[i]);
	    set_name (&m->output, argv[++i], name_string|name_xid);
	    set_name (&m->name, argv[++i], name_string|name_xid);
	    m->action = umode_delete;
	    m->next = umodes;
	    umodes = m;
	    modeit = True;
	    action_requested = True;
	    continue;
	}
	if (!strcmp ("--listproviders", argv[i]))
	{
	    list_providers = True;
	    action_requested = True;
	    continue;
	}
	if (!strcmp("--setprovideroutputsource", argv[i]))
	{ 
	    if (++i >= argc) argerr ("%s requires an argument\n", argv[i-1]);
	    set_name (&provider_name, argv[i], name_string|name_xid|name_index);
	    if (++i>=argc) 
		set_name_xid (&output_source_provider_name, 0);
	    else
		set_name (&output_source_provider_name, argv[i], name_string|name_xid|name_index);
	    action_requested = True;
	    provsetoutsource = True;
	    continue;
	}
	if (!strcmp("--setprovideroffloadsink", argv[i]))
	{ 
	    if (++i >= argc) argerr ("%s requires an argument\n", argv[i-1]);
	    set_name (&provider_name, argv[i], name_string|name_xid|name_index);
	    if (++i>=argc) 
		set_name_xid (&offload_sink_provider_name, 0);
	    else
		set_name (&offload_sink_provider_name, argv[i], name_string|name_xid|name_index);
	    action_requested = True;
	    provsetoffsink = True;
	    continue;
	}
	if (!strcmp("--listmonitors", argv[i]))
	{
	    list_monitors = True;
	    action_requested = True;
	    continue;
	}
	if (!strcmp("--listactivemonitors", argv[i]))
	{
	    list_active_monitors = True;
	    action_requested = True;
	    continue;
	}
	if (!strcmp("--setmonitor", argv[i]))
	{
	    umonitor_t	*m = calloc(1, sizeof (umonitor_t)), **l;
	    char	*o;
	    char	*n;
	    char	*geom;

	    if (i+3 >= argc) argerr("%s requires three argument\n", argv[i]);
	    n = argv[++i];
	    if (*n == '*') {
		m->primary = True;
		n++;
	    }
	    m->name = n;
	    m->set = True;
	    geom = argv[++i];

	    if (strncmp (geom, "auto", 4) != 0) {
		if (sscanf(geom, "%d/%dx%d/%d+%d+%d",
			   &m->width, &m->mmwidth, &m->height, &m->mmheight, &m->x, &m->y) != 6)
		    argerr ("failed to parse '%s' as monitor geometry\n", argv[i]);
	    }

	    o = argv[++i];
	    if (strcmp(o, "none") != 0) {
		char	*t;

		printf ("output list %s\n", o);
		for (; (t = strtok(o, ",")) != NULL; o = NULL) {
		    m->outputs = realloc(m->outputs, (m->noutput + 1) * sizeof (name_t));
		    printf ("add monitor %s\n", t);
		    set_name(&m->outputs[m->noutput++], t, name_string|name_xid|name_index);
		    printf ("output name %s\n", m->outputs[m->noutput-1].string);
		}
	    }
	    for (l = &umonitors; *l; l = &((*l)->next));
	    *l = m;
	    action_requested = True;
	    monitorit = True;
	    continue;
	}
	if (!strcmp("--delmonitor", argv[i]))
	{
	    umonitor_t	*m = calloc(1, sizeof (umonitor_t)), **l;

	    if (++i >= argc) argerr("%s requires an argument\n", argv[i-1]);

	    m->name = argv[i];
	    m->set = False;
	    for (l = &umonitors; *l; l = &((*l)->next));
	    *l = m;
	    action_requested = True;
	    monitorit = True;
	    continue;
	}

	argerr ("unrecognized option '%s'\n", argv[i]);
    }
    if (!action_requested)
	    query = True;
    if (verbose) 
    {
	query = True;
	if (setit && !setit_1_2)
	    query_1 = True;
    }
    if (version)
	printf("xrandr program version       " VERSION "\n");

    dpy = XOpenDisplay (display_name);

    if (dpy == NULL) {
	fprintf (stderr, "Can't open display %s\n", XDisplayName(display_name));
	exit (1);
    }
    if (screen < 0)
	screen = DefaultScreen (dpy);
    if (screen >= ScreenCount (dpy)) {
	fprintf (stderr, "Invalid screen number %d (display has %d)\n",
		 screen, ScreenCount (dpy));
	exit (1);
    }

    root = RootWindow (dpy, screen);

    if (!XRRQueryExtension (dpy, &event_base, &error_base) ||
        !XRRQueryVersion (dpy, &major, &minor))
    {
	fprintf (stderr, "RandR extension missing\n");
	exit (1);
    }
    if (major > 1 || (major == 1 && minor >= 2))
	has_1_2 = True;
    if (major > 1 || (major == 1 && minor >= 3))
	has_1_3 = True;
    if (major > 1 || (major == 1 && minor >= 4))
	has_1_4 = True;
    if (major > 1 || (major == 1 && minor >= 5))
	has_1_5 = True;
    if (has_1_2 && modeit)
    {
        get_screen (True);
	get_crtcs();
	get_outputs();
	
	for (umode_t *m = umodes; m; m = m->next)
	{
	    XRRModeInfo *e;
	    output_t	*o;
	    
	    switch (m->action) {
	    case umode_create:
		XRRCreateMode (dpy, root, &m->mode);
		break;
	    case umode_destroy:
		e = find_mode (&m->name, 0);
		if (!e)
		    fatal ("cannot find mode \"%s\"\n", m->name.string);
		XRRDestroyMode (dpy, e->id);
		break;
	    case umode_add:
		o = find_output (&m->output);
		if (!o)
		    fatal ("cannot find output \"%s\"\n", m->output.string);
		e = find_mode (&m->name, 0);
		if (!e)
		    fatal ("cannot find mode \"%s\"\n", m->name.string);
		XRRAddOutputMode (dpy, o->output.xid, e->id);
		break;
	    case umode_delete:
		o = find_output (&m->output);
		if (!o)
		    fatal ("cannot find output \"%s\"\n", m->output.string);
		e = find_mode (&m->name, 0);
		if (!e)
		    fatal ("cannot find mode \"%s\"\n", m->name.string);
		XRRDeleteOutputMode (dpy, o->output.xid, e->id);
		break;
	    }
	}
	if (!propit && !setit_1_2 && !monitorit)
	{
	    XSync (dpy, False);
	    exit (0);
	}
    }
    if (has_1_2 && propit)
    {
        get_screen (True);
	get_crtcs();
	get_outputs();
	
	for (output_t *output = all_outputs; output; output = output->next)
	{
	    for (output_prop_t *prop = output->props; prop; prop = prop->next)
	    {
		Atom		name = XInternAtom (dpy, prop->name, False);
		char            *atom_name = XGetAtomName (dpy, name);
		Atom		type;
		int		format = 0;
		unsigned char	*data, *malloced_data = NULL;
		int		nelements;
		int		int_value;
		unsigned long	ulong_value;
		unsigned char	*prop_data;
		int		actual_format;
		unsigned long	nitems, bytes_after;
		Atom		actual_type;
		XRRPropertyInfo *propinfo;

		type = AnyPropertyType;
		
		if (XRRGetOutputProperty (dpy, output->output.xid, name,
					  0, 100, False, False,
					  AnyPropertyType,
					  &actual_type, &actual_format,
					  &nitems, &bytes_after, &prop_data) == Success &&

		    (propinfo = XRRQueryOutputProperty(dpy, output->output.xid,
						      name)))
		{
		    type = actual_type;
		    format = actual_format;
		}

		if (strcmp (atom_name, "CTM") == 0 && type == XA_INTEGER && actual_format == 32)
		    malloced_data = ctm_from_string (prop->value, &nelements);

		if (!malloced_data)
		    malloced_data = property_values_from_string (prop->value, type,
								 actual_format, &nelements);

		if (malloced_data)
		{
		    data = malloced_data;
		    type = actual_type;
		    format = actual_format;
		}
		else if (type == AnyPropertyType &&
		    (sscanf (prop->value, "%d", &int_value) == 1 ||
		     sscanf (prop->value, "0x%x", &int_value) == 1))
		{
		    type = XA_INTEGER;
		    ulong_value = int_value;
		    data = (unsigned char *) &ulong_value;
		    nelements = 1;
		    format = 32;
		}
		else if (type == XA_ATOM)
		{
		    ulong_value = XInternAtom (dpy, prop->value, False);
		    data = (unsigned char *) &ulong_value;
		    nelements = 1;
		}
		else if (type == XA_STRING || type == AnyPropertyType)
		{
		    type = XA_STRING;
		    data = (unsigned char *) prop->value;
		    nelements = strlen (prop->value);
		    format = 8;
		}
		else
		    continue;
		XRRChangeOutputProperty (dpy, output->output.xid,
					 name, type, format, PropModeReplace,
					 data, nelements);
		free (malloced_data);
	    }
	}
	if (!setit_1_2)
	{
	    XSync (dpy, False);
	    exit (0);
	}
    }
    if (provsetoutsource)
    {
	provider_t *provider, *source;

	if (!has_1_4)
	    fatal ("--setprovideroutputsource requires RandR 1.4\n");

	get_screen (True);
	get_providers ();

	provider = find_provider (&provider_name);
	source = find_provider(&output_source_provider_name);

	XRRSetProviderOutputSource(dpy, provider->provider.xid, source ? source->provider.xid : 0);
    }
    if (provsetoffsink)
    {
	provider_t *provider, *sink;

	if (!has_1_4)
	    fatal ("--setprovideroffloadsink requires RandR 1.4\n");

	get_screen (True);
	get_providers ();

	provider = find_provider (&provider_name);
	sink = find_provider(&offload_sink_provider_name);

	XRRSetProviderOffloadSink(dpy, provider->provider.xid, sink ? sink->provider.xid : 0);
    }
    if (setit_1_2)
    {
	get_screen (True);
	get_crtcs ();
	get_outputs ();
	set_positions ();
	set_screen_size ();

	pick_crtcs ();

	/*
	 * Assign outputs to crtcs
	 */
	set_crtcs ();
	
	/*
	 * Mark changing crtcs
	 */
	mark_changing_crtcs ();

	/*
	 * If an output was specified to track dpi, use it
	 */
	if (dpi_output_name)
	{
	    output_t	*dpi_output = find_output_by_name (dpi_output_name);
	    XRROutputInfo	*output_info;
	    XRRModeInfo	*mode_info;
	    if (!dpi_output)
		fatal ("Cannot find output %s\n", dpi_output_name);
	    output_info = dpi_output->output_info;
	    mode_info = dpi_output->mode_info;
	    if (output_info && mode_info && output_info->mm_height)
	    {
		/*
		 * When this output covers the whole screen, just use
		 * the known physical size
		 */
		if (fb_width == mode_info->width &&
		    fb_height == mode_info->height)
		{
		    fb_width_mm = output_info->mm_width;
		    fb_height_mm = output_info->mm_height;
		}
		else
		{
		    dpi = (25.4 * mode_info->height) / output_info->mm_height;
		}
	    }
	}

	/*
	 * Compute physical screen size
	 */
	if (fb_width_mm == 0 || fb_height_mm == 0)
	{
	    if (fb_width != DisplayWidth (dpy, screen) ||
		fb_height != DisplayHeight (dpy, screen) || dpi != 0.0)
	    {
		if (dpi <= 0)
		    dpi = (25.4 * DisplayHeight (dpy, screen)) / DisplayHeightMM(dpy, screen);

		fb_width_mm = (25.4 * fb_width) / dpi;
		fb_height_mm = (25.4 * fb_height) / dpi;
	    }
	    else
	    {
		fb_width_mm = DisplayWidthMM (dpy, screen);
		fb_height_mm = DisplayHeightMM (dpy, screen);
	    }
	}
	
	/*
	 * Set panning
	 */
	set_panning ();

	/* 
	 * Set gamma on crtc's that belong to the outputs.
	 */
	set_gamma ();

	/*
	 * Now apply all of the changes
	 */
	apply ();
	
	if (!monitorit) {
	    XSync (dpy, False);
	    exit (0);
	}
    }
    if (monitorit) {
	if (!has_1_5) {
	    printf("RandR 1.5 not supported\n");
	    exit(0);
	}

	get_screen(True);
	get_monitors(False);
	get_crtcs();
	get_outputs();

	for (umonitor_t *u = umonitors; u; u = u->next) {
	    if (u->set) {
		Atom		name = XInternAtom(dpy, u->name, False);
		XRRMonitorInfo	*m = XRRAllocateMonitor(dpy, u->noutput);

		m->name = name;
		m->primary = u->primary;
		m->x = u->x;
		m->y = u->y;
		m->width = u->width;
		m->height = u->height;
		m->mwidth = u->mmwidth;
		m->mheight = u->mmheight;
		for (int o = 0; o < u->noutput; o++) {
		    output_t	*output = find_output(&u->outputs[o]);
		    if (!output)
			fatal("cannot find output\n");
		    m->outputs[o] = output->output.xid;
		}

		XRRSetMonitor(dpy, root, m);

		XRRFreeMonitors(m);
	    } else {
		Atom		name = XInternAtom(dpy, u->name, True);

		if (!name) {
		    printf("No monitor named '%s'\n", u->name);
		} else {
		    if (!monitors)
			printf ("No monitors\n");
		    else {
			int	m;

			for (m = 0; m < monitors->n; m++) {
			    if (monitors->monitors[m].name == name)
				break;
			}
			if (m == monitors->n)
			    printf("No monitor named '%s'\n", u->name);
			else
			    XRRDeleteMonitor(dpy, root, name);
		    }
		}
	    }
	}
	XSync (dpy, False);
	exit (0);
    }
    if (query_1_2 || (query && has_1_2 && !query_1))
    {

#define ModeShown   0x80000000
	
	get_screen (current);
	get_crtcs ();
	get_outputs ();

        printf ("Screen %d: minimum %d x %d, current %d x %d, maximum %d x %d\n",
		screen, minWidth, minHeight,
		DisplayWidth (dpy, screen), DisplayHeight(dpy, screen),
		maxWidth, maxHeight);

	for (output_t *output = all_outputs; output; output = output->next)
	{
	    XRROutputInfo   *output_info = output->output_info;
	    crtc_t	    *cur_crtc = output->crtc_info;
	    XRRCrtcInfo	    *crtc_info = cur_crtc ? cur_crtc->crtc_info : NULL;
	    XRRModeInfo	    *cur_mode = output->mode_info;
	    int		    nprop;
	    Rotation	    rotations = output_rotations (output);

	    printf ("%s %s", output_info->name, connection[output_info->connection]);
	    if (output->primary) {
		printf(" primary");
	    }
	    if (cur_mode)
	    {
		if (crtc_info) {
		    printf (" %dx%d+%d+%d",
			    crtc_info->width, crtc_info->height,
			    crtc_info->x, crtc_info->y);
		} else {
		    printf (" %dx%d+%d+%d",
			    cur_mode->width, cur_mode->height, output->x,
			    output->y);
		}
		if (verbose)
		    printf (" (0x%x)", (int)cur_mode->id);
		if (output->rotation != RR_Rotate_0 || verbose)
		{
		    printf (" %s", 
			    rotation_name (output->rotation));
		    if (output->rotation & (RR_Reflect_X|RR_Reflect_Y))
			printf (" %s", reflection_name (output->rotation));
		}
	    }
	    if (rotations != RR_Rotate_0 || verbose)
	    {
		Bool    first = True;
		printf (" (");
		for (int i = 0; i < 4; i ++) {
		    if ((rotations >> i) & 1) {
			if (!first) printf (" ");
			printf("%s", direction[i]);
			first = False;
		    }
		}
		if (rotations & RR_Reflect_X)
		{
		    if (!first) printf (" ");
		    printf ("x axis");
		    first = False;
		}
		if (rotations & RR_Reflect_Y)
		{
		    if (!first) printf (" ");
		    printf ("y axis");
		}
		printf (")");
	    }

	    if (cur_mode)
	    {
		printf (" %dmm x %dmm",
			(int)output_info->mm_width, (int)output_info->mm_height);
	    }

	    if (cur_crtc && cur_crtc->panning_info &&
		cur_crtc->panning_info->width > 0)
	    {
		XRRPanning *pan = cur_crtc->panning_info;
		printf (" panning %dx%d+%d+%d",
			pan->width, pan->height, pan->left, pan->top);
		if ((pan->track_width    != 0 &&
		     (pan->track_left    != pan->left		||
		      pan->track_width   != pan->width		||
		      pan->border_left   != 0			||
		      pan->border_right  != 0))			||
		    (pan->track_height   != 0 &&
		     (pan->track_top     != pan->top		||
		      pan->track_height  != pan->height		||
		      pan->border_top    != 0			||
		      pan->border_bottom != 0)))
		    printf (" tracking %dx%d+%d+%d border %d/%d/%d/%d",
			    pan->track_width,  pan->track_height,
			    pan->track_left,   pan->track_top,
			    pan->border_left,  pan->border_top,
			    pan->border_right, pan->border_bottom);
	    }
	    printf ("\n");

	    if (verbose)
	    {
		printf ("\tIdentifier: 0x%x\n", (int)output->output.xid);
		printf ("\tTimestamp:  %d\n", (int)output_info->timestamp);
		printf ("\tSubpixel:   %s\n", order[output_info->subpixel_order]);
	        if (output->gamma.red != 0.0 && output->gamma.green != 0.0 && output->gamma.blue != 0.0) {
		    printf ("\tGamma:      %#.2g:%#.2g:%#.2g\n",
			    output->gamma.red, output->gamma.green, output->gamma.blue);
		    printf ("\tBrightness: %#.2g\n", output->brightness);
		}
		printf ("\tClones:    ");
		for (int j = 0; j < output_info->nclone; j++)
		{
		    output_t	*clone = find_output_by_xid (output_info->clones[j]);

		    if (clone) printf (" %s", clone->output.string);
		}
		printf ("\n");
		if (output->crtc_info)
		    printf ("\tCRTC:       %d\n", output->crtc_info->crtc.index);
		printf ("\tCRTCs:     ");
		for (int j = 0; j < output_info->ncrtc; j++)
		{
		    crtc_t	*crtc = find_crtc_by_xid (output_info->crtcs[j]);
		    if (crtc)
			printf (" %d", crtc->crtc.index);
		}
		printf ("\n");
		if (output->crtc_info && output->crtc_info->panning_info) {
		    XRRPanning *pan = output->crtc_info->panning_info;
		    printf ("\tPanning:    %dx%d+%d+%d\n",
			    pan->width, pan->height, pan->left, pan->top);
		    printf ("\tTracking:   %dx%d+%d+%d\n",
			    pan->track_width,  pan->track_height,
			    pan->track_left,   pan->track_top);
		    printf ("\tBorder:     %d/%d/%d/%d\n",
			    pan->border_left,  pan->border_top,
			    pan->border_right, pan->border_bottom);
		}
	    }
	    if (verbose)
	    {
		printf ("\tTransform: ");
		for (int y = 0; y < 3; y++)
		{
		    for (int x = 0; x < 3; x++)
			printf (" %f", XFixedToDouble (output->transform.transform.matrix[y][x]));
		    if (y < 2)
			printf ("\n\t           ");
		}
		if (output->transform.filter)
		    printf ("\n\t           filter: %s", output->transform.filter);
		printf ("\n");
	    }
	    if (verbose || properties)
	    {
		Atom *props = XRRListOutputProperties (dpy, output->output.xid,
						       &nprop);

		for (int j = 0; j < nprop; j++) {
		    unsigned char *prop;
		    int actual_format;
		    unsigned long nitems, bytes_after;
		    Atom actual_type;
		    XRRPropertyInfo *propinfo;
		    char *atom_name = XGetAtomName (dpy, props[j]);

		    XRRGetOutputProperty (dpy, output->output.xid, props[j],
					  0, 100, False, False,
					  AnyPropertyType,
					  &actual_type, &actual_format,
					  &nitems, &bytes_after, &prop);

		    propinfo = XRRQueryOutputProperty(dpy, output->output.xid,
						      props[j]);

		    printf ("\t%s: ", atom_name);

		    print_output_property(atom_name, actual_format,
					  actual_type, nitems, prop);

		    if (propinfo->range && propinfo->num_values > 0)
		    {
			printf ("\t\trange%s: ",
			        (propinfo->num_values == 2) ? "" : "s");
			for (int k = 0; k < propinfo->num_values / 2; k++)
			{
			    printf ("(");
			    print_output_property_value (32, actual_type,
							 (unsigned char *) &(propinfo->values[k * 2]));
			    printf (", ");
			    print_output_property_value (32, actual_type,
							 (unsigned char *) &(propinfo->values[k * 2 + 1]));
			    printf (")");
			    if (k < propinfo->num_values / 2 - 1)
				printf (", ");
			}
			printf ("\n");
		    }
		    if (!propinfo->range && propinfo->num_values > 0)
		    {
			printf ("\t\tsupported: ");
			for (int k = 0; k < propinfo->num_values; k++)
			{
			    print_output_property_value (32, actual_type,
							 (unsigned char *) &(propinfo->values[k]));
			    if (k < propinfo->num_values - 1)
				printf (", ");
			}
			printf ("\n");
		    }

		    free(propinfo);
		}
	    }

	    if (verbose)
	    {
		for (int j = 0; j < output_info->nmode; j++)
		{
		    XRRModeInfo	*mode = find_mode_by_xid (output_info->modes[j]);
		    if (!mode)
		    {
			printf ("  [Unknown mode ID 0x%x]\n",
				(int)output_info->modes[j]);
			continue;
		    }

		    print_verbose_mode (mode, mode == output->mode_info,
					j < output_info->npreferred);
		    mode->modeFlags |= ModeShown;
		}
	    }
	    else
	    {
		Bool *mode_shown = calloc (output_info->nmode, sizeof (Bool));
		if (!mode_shown) fatal ("out of memory\n");
		for (int j = 0; j < output_info->nmode; j++)
		{
		    XRRModeInfo *jmode, *kmode;

		    if (mode_shown[j]) continue;

		    jmode = find_mode_by_xid (output_info->modes[j]);
		    if (!jmode)
		    {
			printf ("   [Unknown mode ID 0x%x]\n",
				(int)output_info->modes[j]);
			continue;
		    }
		    printf (" ");
		    printf ("  %-12s", jmode->name);
		    for (int k = j; k < output_info->nmode; k++)
		    {
			if (mode_shown[k]) continue;
			kmode = find_mode_by_xid (output_info->modes[k]);
			if (!kmode) continue;
			if (strcmp (jmode->name, kmode->name) != 0) continue;
			mode_shown[k] = True;
			kmode->modeFlags |= ModeShown;
			printf (" %6.2f", mode_refresh (kmode));
			if (kmode == output->mode_info)
			    printf ("*");
			else
			    printf (" ");
			if (k < output_info->npreferred)
			    printf ("+");
			else
			    printf (" ");
		    }
		    printf ("\n");
		}
		free (mode_shown);
	    }
	}
	for (int m = 0; m < res->nmode; m++)
	{
	    XRRModeInfo	*mode = &res->modes[m];

	    if (!(mode->modeFlags & ModeShown))
		print_verbose_mode(mode, False, False);
	}
	exit (0);
    }
    if (list_providers) {
	if (!has_1_4) {
	    printf ("RandR 1.4 not supported\n");
	    exit (0);
	}

	get_screen (current);
	get_providers ();

	if (providers) {
	    printf("Providers: number : %d\n", num_providers);

	    for (int j = 0; j < num_providers; j++) {
		provider_t *provider = &providers[j];
		XRRProviderInfo *info = provider->info;

		printf("Provider %d: id: 0x%x cap: 0x%x", j, (int)provider->provider.xid, info->capabilities);
		for (int k = 0; k < 4; k++)
			if (info->capabilities & (1 << k))
				printf(", %s", capability_name(1<<k));

		printf(" crtcs: %d outputs: %d associated providers: %d name:%s\n", info->ncrtcs, info->noutputs, info->nassociatedproviders, info->name);
	    }
	}
    }
    if (list_monitors || list_active_monitors) {

	if (!has_1_5) {
	    printf("RandR 1.5 not supported\n");
	    exit(0);
	}

	get_screen(current);
	get_monitors(list_active_monitors ? True : False);
	get_crtcs();
	get_outputs();

	if (monitors) {
	    printf("Monitors: %d\n", monitors->n);

	    for (int m = 0; m < monitors->n; m++) {
		printf (" %d: %s%s%s %d/%dx%d/%d+%d+%d ",
			m,
			monitors->monitors[m].automatic ? "+" : "",
			monitors->monitors[m].primary ? "*" : "",
			XGetAtomName(dpy, monitors->monitors[m].name),
			monitors->monitors[m].width,
			monitors->monitors[m].mwidth,
			monitors->monitors[m].height,
			monitors->monitors[m].mheight,
			monitors->monitors[m].x,
			monitors->monitors[m].y);
		for (int o = 0; o < monitors->monitors[m].noutput; o++) {
		    output_t	*output = find_output_by_xid(monitors->monitors[m].outputs[o]);
		    if (output)
			printf (" %s", output->output.string);
		    else
			printf (" unknown output 0x%x\n", (CARD32) monitors->monitors[m].outputs[o]);
		}
		printf ("\n");
	    }
	}
    }

    sc = XRRGetScreenInfo (dpy, root);

    if (sc == NULL) 
	exit (1);

    current_size = XRRConfigCurrentConfiguration (sc, &current_rotation);

    sizes = XRRConfigSizes(sc, &nsize);

    if (have_pixel_size) {
	for (size = 0; size < nsize; size++)
	{
	    if (sizes[size].width == width && sizes[size].height == height)
		break;
	}
	if (size >= nsize) {
	    fprintf (stderr,
		     "Size %dx%d not found in available modes\n", width, height);
	    exit (1);
	}
    }
    else if (size < 0)
	size = current_size;
    else if (size >= nsize) {
	fprintf (stderr,
		 "Size index %d is too large, there are only %d sizes\n",
		 size, nsize);
	exit (1);
    }

    if (rot < 0)
    {
	for (rot = 0; rot < 4; rot++)
	    if (1 << rot == (current_rotation & 0xf))
		break;
    }

    current_rate = XRRConfigCurrentRate (sc);

    if (rate < 0)
    {
	if (size == current_size)
	    rate = current_rate;
	else
	    rate = 0;
    }
    else
    {
	int	i;
	short	*rates = XRRConfigRates (sc, size, &nrate);

	for (i = 0; i < nrate; i++)
	    if (rate == rates[i])
		break;
	if (i == nrate) {
	    fprintf (stderr, "Rate %.2f Hz not available for this size\n", rate);
	    exit (1);
	}
    }

    if (version) {
	int major_version, minor_version;
	XRRQueryVersion (dpy, &major_version, &minor_version);
	printf("Server reports RandR version %d.%d\n", 
	       major_version, minor_version);
    }

    if (query || query_1) {
	printf(" SZ:    Pixels          Physical       Refresh\n");
	for (int i = 0; i < nsize; i++) {
	    short	*rates;

	    printf ("%c%-2d %5d x %-5d  (%4dmm x%4dmm )",
		    i == current_size ? '*' : ' ',
		    i, sizes[i].width, sizes[i].height,
		    sizes[i].mwidth, sizes[i].mheight);
	    rates = XRRConfigRates (sc, i, &nrate);
	    if (nrate) printf ("  ");
	    for (int j = 0; j < nrate; j++)
		printf ("%c%-4d",
			i == current_size && rates[j] == current_rate ? '*' : ' ',
			rates[j]);
	    printf ("\n");
	}
    }

    {
	Rotation rotations = XRRConfigRotations(sc, &current_rotation);

	if (toggle_x && !(current_rotation & RR_Reflect_X)) reflection |= RR_Reflect_X;
	if (toggle_y && !(current_rotation & RR_Reflect_Y)) reflection |= RR_Reflect_Y;

	if (query) {
	    printf("Current rotation - %s\n",
		   rotation_name (current_rotation));

	    printf("Current reflection - %s\n",
		   reflection_name (current_rotation));

	    printf ("Rotations possible - ");
	    for (int i = 0; i < 4; i ++) {
		if ((rotations >> i) & 1)  printf("%s ", direction[i]);
	    }
	    printf ("\n");

	    printf ("Reflections possible - ");
	    if (rotations & (RR_Reflect_X|RR_Reflect_Y))
	    {
		if (rotations & RR_Reflect_X) printf ("X Axis ");
		if (rotations & RR_Reflect_Y) printf ("Y Axis");
	    }
	    else
		printf ("none");
	    printf ("\n");
	}
    }

    if (verbose) { 
	printf("Setting size to %d, rotation to %s\n",  size, direction[rot]);

	printf ("Setting reflection on ");
	if (reflection)
	{
	    if (reflection & RR_Reflect_X) printf ("X Axis ");
	    if (reflection & RR_Reflect_Y) printf ("Y Axis");
	}
	else
	    printf ("neither axis");
	printf ("\n");
    }

    /* we should test configureNotify on the root window */
    XSelectInput (dpy, root, StructureNotifyMask);

    if (setit && !dryrun) XRRSelectInput (dpy, root,
			       RRScreenChangeNotifyMask);
    if (setit && !dryrun) {
	Rotation rotation = 1 << rot;
	status = XRRSetScreenConfigAndRate (dpy, sc, root, (SizeID) size,
					    (Rotation) (rotation | reflection),
					    rate, CurrentTime);
    }

    if (setit && !dryrun && status == RRSetConfigFailed) {
	printf ("Failed to change the screen configuration!\n");
	ret = 1;
    }

    if (verbose && setit && !dryrun && size != current_size) {
	if (status == RRSetConfigSuccess)
	{
	    Bool    seen_screen = False;
	    while (!seen_screen) {
		int spo;
		XNextEvent(dpy, (XEvent *) &event);

		printf ("Event received, type = %d\n", event.type);
		/* update Xlib's knowledge of the event */
		XRRUpdateConfiguration (&event);
		if (event.type == ConfigureNotify)
		    printf("Received ConfigureNotify Event!\n");

		switch (event.type - event_base) {
		case RRScreenChangeNotify:
		    sce = (XRRScreenChangeNotifyEvent *) &event;

		    printf("Got a screen change notify event!\n");
		    printf(" window = %d\n root = %d\n size_index = %d\n rotation %d\n", 
			   (int) sce->window, (int) sce->root, 
			   sce->size_index,  sce->rotation);
		    printf(" timestamp = %ld, config_timestamp = %ld\n",
			   sce->timestamp, sce->config_timestamp);
		    printf(" Rotation = %x\n", sce->rotation);
		    printf(" %d X %d pixels, %d X %d mm\n",
			   sce->width, sce->height, sce->mwidth, sce->mheight);
		    printf("Display width   %d, height   %d\n",
			   DisplayWidth(dpy, screen), DisplayHeight(dpy, screen));
		    printf("Display widthmm %d, heightmm %d\n", 
			   DisplayWidthMM(dpy, screen), DisplayHeightMM(dpy, screen));
		    spo = sce->subpixel_order;
		    if ((spo < 0) || (spo > 5))
			printf ("Unknown subpixel order, value = %d\n", spo);
		    else printf ("new Subpixel rendering model is %s\n", order[spo]);
		    seen_screen = True;
		    break;
		default:
		    if (event.type != ConfigureNotify) 
			printf("unknown event received, type = %d!\n", event.type);
		}
	    }
	}
    }
    XRRFreeScreenConfigInfo(sc);
    return(ret);
}