summaryrefslogtreecommitdiffstats
path: root/client/x11/platform.cpp
blob: 8288f55568f4ac99a1f1446f45cdb074603b3168 (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
/*
   Copyright (C) 2009 Red Hat, Inc.

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2 of
   the License, or (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "common.h"

#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/XKBlib.h>
#include <X11/Xresource.h>
#include <X11/cursorfont.h>
#include <X11/extensions/Xrandr.h>
#include <X11/extensions/render.h>
#include <X11/extensions/XKB.h>
#include <X11/extensions/Xrender.h>
#include <unistd.h>
#include <sys/epoll.h>
#include <sys/resource.h>
#include <sys/types.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <fcntl.h>
#include <set>
#include <values.h>
#include <signal.h>
#include <config.h>

#include "platform.h"
#include "application.h"
#include "utils.h"
#include "x_platform.h"
#include "debug.h"
#include "monitor.h"
#include "rect.h"
#include "record.h"
#include "playback.h"
#include "resource.h"
#include "res.h"
#include "cursor.h"
#include "process_loop.h"

#define DWORD uint32_t
#define BOOL bool
#include "named_pipe.h"

//#define X_DEBUG_SYNC(display) XSync(display, False)
#define X_DEBUG_SYNC(display)
#ifdef HAVE_XRANDR12
#define USE_XRANDR_1_2
#endif

static Display* x_display = NULL;
static XVisualInfo **vinfo = NULL;
static GLXFBConfig **fb_config;

static XContext win_proc_context;
static ProcessLoop* main_loop = NULL;
static int focus_count = 0;

static bool using_xrandr_1_0 = false;
#ifdef USE_XRANDR_1_2
static bool using_xrandr_1_2 = false;
#endif

static int xrandr_event_base;
static int xrandr_error_base;
static int xrandr_major = 0;
static int xrandr_minor = 0;

static bool using_xrender_0_5 = false;

static unsigned int caps_lock_mask = 0;
static unsigned int num_lock_mask = 0;

class DefaultEventListener: public Platform::EventListener {
public:
    virtual void on_app_activated() {}
    virtual void on_app_deactivated() {}
    virtual void on_monitors_change() {}
};

static DefaultEventListener default_event_listener;
static Platform::EventListener* event_listener = &default_event_listener;

class DefaultDisplayModeListner: public Platform::DisplayModeListner {
public:
    void on_display_mode_change() {}
};

static DefaultDisplayModeListner default_display_mode_listener;
static Platform::DisplayModeListner* display_mode_listener = &default_display_mode_listener;


NamedPipe::ListenerRef NamedPipe::create(const char *name, ListenerInterface& listener_interface)
{
    ASSERT(main_loop && main_loop->is_same_thread(pthread_self()));
    return (ListenerRef)(new LinuxListener(name, listener_interface, *main_loop));
}

void NamedPipe::destroy(ListenerRef listener_ref)
{
    ASSERT(main_loop && main_loop->is_same_thread(pthread_self()));
    delete (LinuxListener *)listener_ref;
}

void NamedPipe::destroy_connection(ConnectionRef conn_ref)
{
    ASSERT(main_loop && main_loop->is_same_thread(pthread_self()));
    delete (Session *)conn_ref;
}

int32_t NamedPipe::read(ConnectionRef conn_ref, uint8_t* buf, int32_t size)
{
    if (((Session *)conn_ref) != NULL) {
        return ((Session *)conn_ref)->read(buf, size);
    }
    return -1;
}

int32_t NamedPipe::write(ConnectionRef conn_ref, const uint8_t* buf, int32_t size)
{
    if (((Session *)conn_ref) != NULL) {
        return ((Session *)conn_ref)->write(buf, size);
    }
    return -1;
}

class XEventHandler: public EventSources::File {
public:
    XEventHandler(Display& x_display, XContext& win_proc_context);
    virtual void on_event();
    virtual int get_fd() {return _x_fd;}

private:
    Display& _x_display;
    XContext& _win_proc_context;
    int _x_fd;
};

XEventHandler::XEventHandler(Display& x_display, XContext& win_proc_context)
    : _x_display (x_display)
    , _win_proc_context (win_proc_context)
{
    if ((_x_fd = ConnectionNumber(&x_display)) == -1) {
        THROW("get x fd failed");
    }
}

void XEventHandler::on_event()
{
    while (XPending(&_x_display)) {
        XPointer proc_pointer;
        XEvent event;

        XNextEvent(&_x_display, &event);
        if (event.xany.window == None) {
            LOG_WARN("invalid window");
            continue;
        }

        if (XFindContext(&_x_display, event.xany.window, _win_proc_context, &proc_pointer)) {
            THROW("no window proc");
        }
        ((XPlatform::win_proc_t)proc_pointer)(event);
    }
}

Display* XPlatform::get_display()
{
    return x_display;
}

XVisualInfo** XPlatform::get_vinfo()
{
    return vinfo;
}

GLXFBConfig** XPlatform::get_fbconfig()
{
    return fb_config;
}

void XPlatform::set_win_proc(Window win, win_proc_t proc)
{
    if (XSaveContext(x_display, win, win_proc_context, (XPointer)proc)) {
        THROW("set win proc pailed");
    }
}

void XPlatform::cleare_win_proc(Window win)
{
    XDeleteContext(x_display, win, win_proc_context);
}

void Platform::send_quit_request()
{
    ASSERT(main_loop);
    main_loop->quit(0);
}

uint64_t Platform::get_monolithic_time()
{
    struct timespec time_space;
    clock_gettime(CLOCK_MONOTONIC, &time_space);
    return uint64_t(time_space.tv_sec) * 1000 * 1000 * 1000 + uint64_t(time_space.tv_nsec);
}

void Platform::get_temp_dir(std::string& path)
{
    path = "/tmp/";
}

void Platform::msleep(unsigned int millisec)
{
    usleep(millisec * 1000);
}

void Platform::yield()
{
    pthread_yield();
}

void Platform::set_thread_priority(void* thread, Platform::ThreadPriority in_priority)
{
    ASSERT(thread == NULL);
    int priority;

    switch (in_priority) {
    case PRIORITY_TIME_CRITICAL:
        priority = -20;
        break;
    case PRIORITY_HIGH:
        priority = -2;
        break;
    case PRIORITY_ABOVE_NORMAL:
        priority = -1;
        break;
    case PRIORITY_NORMAL:
        priority = 0;
        break;
    case PRIORITY_BELOW_NORMAL:
        priority = 1;
        break;
    case PRIORITY_LOW:
        priority = 2;
        break;
    case PRIORITY_IDLE:
        priority = 19;
        break;
    default:
        THROW("invalid priority %d", in_priority);
    }

    pid_t tid = syscall(SYS_gettid);
    if (setpriority(PRIO_PROCESS, tid, priority) == -1) {
        DBG(0, "setpriority failed %s", strerror(errno));
    }
}

void Platform::set_event_listener(EventListener* listener)
{
    event_listener = listener ? listener : &default_event_listener;
}

void Platform::set_display_mode_listner(DisplayModeListner* listener)
{
    display_mode_listener = listener ? listener : &default_display_mode_listener;
}

#ifdef USE_XRANDR_1_2
class FreeScreenResources {
public:
    void operator () (XRRScreenResources* res) { XRRFreeScreenResources(res);}
};
typedef _AutoRes<XRRScreenResources, FreeScreenResources> AutoScreenRes;

class FreeOutputInfo {
public:
    void operator () (XRROutputInfo* output_info) { XRRFreeOutputInfo(output_info);}
};

typedef _AutoRes<XRROutputInfo, FreeOutputInfo> AutoOutputInfo;

class FreeCrtcInfo {
public:
    void operator () (XRRCrtcInfo* crtc_info) { XRRFreeCrtcInfo(crtc_info);}
};
typedef _AutoRes<XRRCrtcInfo, FreeCrtcInfo> AutoCrtcInfo;

static XRRModeInfo* find_mod(XRRScreenResources* res, RRMode mode)
{
    for (int i = 0; i < res->nmode; i++) {
        if (res->modes[i].id == mode) {
            return &res->modes[i];
        }
    }
    return NULL;
}

#endif

//#define SHOW_SCREEN_INFO
#ifdef SHOW_SCREEN_INFO

static float mode_refresh(XRRModeInfo *mode_info)
{
    if (!mode_info->hTotal || !mode_info->vTotal) {
        return 0;
    }

    return ((float)mode_info->dotClock / ((float)mode_info->hTotal * (float)mode_info->vTotal));
}

static void show_scren_info()
{
    int screen = DefaultScreen(x_display);
    Window root_window = RootWindow(x_display, screen);

    int minWidth;
    int minHeight;
    int maxWidth;
    int maxHeight;

    AutoScreenRes res(XRRGetScreenResources(x_display, root_window));

    if (!res.valid()) {
        throw Exception(fmt("%s: get screen resources failed") % __FUNCTION__);
    }

    XRRGetScreenSizeRange(x_display, root_window, &minWidth, &minHeight,
                          &maxWidth, &maxHeight);
    printf("screen: min %dx%d max %dx%d\n", minWidth, minHeight,
           maxWidth, maxHeight);

    int i, j;

    for (i = 0; i < res->noutput; i++) {
        AutoOutputInfo output_info(XRRGetOutputInfo(x_display, res.get(), res->outputs[i]));

        printf("output %s", output_info->name);
        if (output_info->crtc == None) {
            printf(" crtc None");
        } else {
            printf(" crtc 0x%lx", output_info->crtc);
        }
        switch (output_info->connection) {
        case RR_Connected:
            printf(" Connected");
            break;
        case RR_Disconnected:
            printf(" Disconnected");
            break;
        case RR_UnknownConnection:
            printf(" UnknownConnection");
            break;
        }
        printf(" ncrtc %u nclone %u nmode %u\n",
               output_info->ncrtc,
               output_info->nclone,
               output_info->nmode);
        for (j = 0; j < output_info->nmode; j++) {
            XRRModeInfo* mode = find_mod(res.get(), output_info->modes[j]);
            printf("\t%lu:", output_info->modes[j]);
            if (!mode) {
                printf(" ???\n");
                continue;
            }
            printf(" %s %ux%u %f\n", mode->name, mode->width, mode->height, mode_refresh(mode));
        }
    }

    for (i = 0; i < res->ncrtc; i++) {
        AutoCrtcInfo crtc_info(XRRGetCrtcInfo(x_display, res.get(), res->crtcs[i]));
        printf("crtc: 0x%lx x %d y %d  width %u height %u  mode %lu\n",
               res->crtcs[i],
               crtc_info->x, crtc_info->y,
               crtc_info->width, crtc_info->height, crtc_info->mode);
    }
}

#endif

enum RedScreenRotation {
    RED_SCREEN_ROTATION_0,
    RED_SCREEN_ROTATION_90,
    RED_SCREEN_ROTATION_180,
    RED_SCREEN_ROTATION_270,
};

enum RedSubpixelOrder {
    RED_SUBPIXEL_ORDER_UNKNOWN,
    RED_SUBPIXEL_ORDER_H_RGB,
    RED_SUBPIXEL_ORDER_H_BGR,
    RED_SUBPIXEL_ORDER_V_RGB,
    RED_SUBPIXEL_ORDER_V_BGR,
    RED_SUBPIXEL_ORDER_NONE,
};

static void root_win_proc(XEvent& event);
static void process_monitor_configure_events(Window root);

class XMonitor;
typedef std::list<XMonitor*> XMonitorsList;

class XScreen {
public:
    XScreen(Display* display, int screen);
    virtual ~XScreen() {}

    virtual void publish_monitors(MonitorsList& monitors) = 0;

    Display* get_display() {return _display;}
    int get_screen() {return _screen;}

    void set_broken() {_broken = true;}
    bool is_broken() const {return _broken;}
    int get_width() const {return _width;}
    void set_width(int width) {_width = width;}
    int get_height() const { return _height;}
    void set_height(int height) {_height = height;}
    Point get_position() const {return _position;}

private:
    Display* _display;
    int _screen;
    Point _position;
    int _width;
    int _height;
    bool _broken;
};

XScreen::XScreen(Display* display, int screen)
    : _display (display)
    , _screen (screen)
    , _broken (false)
{
    int root = RootWindow(display, screen);

    XWindowAttributes attrib;
    XGetWindowAttributes(display, root, &attrib);

    _position.x = attrib.x;
    _position.y = attrib.y;
    _width = attrib.width;
    _height = attrib.height;
}

class StaticScreen: public XScreen, public Monitor {
public:
    StaticScreen(Display* display, int screen, int& next_mon_id)
        : XScreen(display, screen)
        , Monitor(next_mon_id++)
        , _out_of_sync (false)
    {
    }

    virtual void publish_monitors(MonitorsList& monitors)
    {
        monitors.push_back(this);
    }

    virtual void set_mode(int width, int height)
    {
        _out_of_sync = width > get_width() || height > get_height();
    }

    virtual void restore() {}
    virtual int get_depth() { return XPlatform::get_vinfo()[0]->depth;}
    virtual Point get_position() { return XScreen::get_position();}
    virtual Point get_size() const { Point pt = {get_width(), get_height()}; return pt;}
    virtual bool is_out_of_sync() { return _out_of_sync;}
    virtual int get_screen_id() { return get_screen();}

private:
    bool _out_of_sync;
};

class DynamicScreen: public XScreen, public Monitor {
public:
    DynamicScreen(Display* display, int screen, int& next_mon_id);
    virtual ~DynamicScreen();

    void publish_monitors(MonitorsList& monitors);
    virtual void set_mode(int width, int height);
    virtual void restore();
    virtual int get_depth() { return XPlatform::get_vinfo()[0]->depth;}
    virtual Point get_position() { return XScreen::get_position();}
    virtual Point get_size() const { Point pt = {get_width(), get_height()}; return pt;}
    virtual bool is_out_of_sync() { return _out_of_sync;}
    virtual int get_screen_id() { return get_screen();}

private:
    bool set_screen_size(int size_index);

private:
    int _saved_width;
    int _saved_height;
    bool _out_of_sync;
};

DynamicScreen::DynamicScreen(Display* display, int screen, int& next_mon_id)
    : XScreen(display, screen)
    , Monitor(next_mon_id++)
    , _saved_width (get_width())
    , _saved_height (get_height())
    , _out_of_sync (false)
{
    X_DEBUG_SYNC(display);
    Window root_window = RootWindow(display, screen);
    XSelectInput(display, root_window, StructureNotifyMask);
    XRRSelectInput(display, root_window, RRScreenChangeNotifyMask);
    XPlatform::set_win_proc(root_window, root_win_proc);
    X_DEBUG_SYNC(display);
}

DynamicScreen::~DynamicScreen()
{
    restore();
}

void DynamicScreen::publish_monitors(MonitorsList& monitors)
{
    monitors.push_back(this);
}

class SizeInfo {
public:
    SizeInfo(int int_index, XRRScreenSize* in_size) : index (int_index), size (in_size) {}

    int index;
    XRRScreenSize* size;
};

class SizeCompare {
public:
    bool operator () (const SizeInfo& size1, const SizeInfo& size2) const
    {
        int area1 = size1.size->width * size1.size->height;
        int area2 = size2.size->width * size2.size->height;
        return area1 < area2 || (area1 == area2 && size1.index < size2.index);
    }
};

void DynamicScreen::set_mode(int width, int height)
{
    int num_sizes;

    X_DEBUG_SYNC(get_display());
    XRRScreenSize* sizes = XRRSizes(get_display(), get_screen(), &num_sizes);

    typedef std::set<SizeInfo, SizeCompare> SizesSet;
    SizesSet sizes_set;

    for (int i = 0; i < num_sizes; i++) {
        if (sizes[i].width >= width && sizes[i].height >= height) {
            sizes_set.insert(SizeInfo(i, &sizes[i]));
        }
    }
    _out_of_sync = true;
    if (!sizes_set.empty() && set_screen_size((*sizes_set.begin()).index)) {
        _out_of_sync = false;
    }
    X_DEBUG_SYNC(get_display());
}

void DynamicScreen::restore()
{
    X_DEBUG_SYNC(get_display());
    if (is_broken() || (get_width() == _saved_width && get_height() == _saved_height)) {
        return;
    }
    int num_sizes;

    XRRScreenSize* sizes = XRRSizes(get_display(), get_screen(), &num_sizes);
    for (int i = 0; i < num_sizes; i++) {
        if (sizes[i].width == _saved_width && sizes[i].height == _saved_height) {
            set_screen_size(i);
            return;
        }
    }
    X_DEBUG_SYNC(get_display());
    LOG_WARN("can't find startup mode");
}

bool DynamicScreen::set_screen_size(int size_index)
{
    X_DEBUG_SYNC(get_display());
    Window root_window = RootWindow(get_display(), get_screen());
    XRRScreenConfiguration* config;

    if (!(config = XRRGetScreenInfo(get_display(), root_window))) {
        LOG_WARN("get scren info failed");
        return false;
    }
    Rotation rotation;
    XRRConfigCurrentConfiguration(config, &rotation);

    Monitor::self_monitors_change++;
    /*what status*/
    XRRSetScreenConfig(get_display(), config, root_window, size_index, rotation, CurrentTime);
    process_monitor_configure_events(root_window);
    Monitor::self_monitors_change--;
    XRRFreeScreenConfigInfo(config);
    X_DEBUG_SYNC(get_display());

    int num_sizes;
    XRRScreenSize* sizes = XRRSizes(get_display(), get_screen(), &num_sizes);
    if (num_sizes <= size_index) {
        THROW("invalid sizes size");
    }
    set_width(sizes[size_index].width);
    set_height(sizes[size_index].height);
    return true;
}

#ifdef USE_XRANDR_1_2

class MultyMonScreen: public XScreen {
public:
    MultyMonScreen(Display* display, int screen, int& next_mon_id);
    virtual ~MultyMonScreen();

    virtual void publish_monitors(MonitorsList& monitors);

    void disable();
    void enable();

    bool set_monitor_mode(XMonitor& monitor, const XRRModeInfo& mode_info);

private:
    void set_size(int width, int height);
    void get_trans_size(int& width, int& hight);
    Point get_trans_top_left();
    Point get_trans_bottom_right();
    bool changed();

    XMonitor* crtc_overlap_test(int x, int y, int width, int height);
    void monitors_cleanup();
    void restore();

private:
    int _min_width;
    int _min_height;
    int _max_width;
    int _max_height;
    int _saved_width;
    int _saved_height;
    int _saved_width_mm;
    int _saved_height_mm;
    XMonitorsList _monitors;
};

#define MAX_TRANS_DEPTH 3

class XMonitor: public Monitor {
public:
    XMonitor(MultyMonScreen& container, int id, RRCrtc crtc);
    virtual ~XMonitor();

    virtual void set_mode(int width, int height);
    virtual void restore();
    virtual int get_depth();
    virtual Point get_position();
    virtual Point get_size() const;
    virtual bool is_out_of_sync();
    virtual int get_screen_id() { return _container.get_screen();}

    void add_clone(XMonitor *clone);
    void revert();
    void disable();
    void enable();

    void set_mode(const XRRModeInfo& mode);
    const Rect& get_prev_area();
    Rect& get_trans_area();
    void pin() { _pin_count++;}
    void unpin() { ASSERT(_pin_count > 0); _pin_count--;}
    bool is_pinned() {return !!_pin_count;}
    void commit_trans_position();
    void set_pusher(XMonitor& pusher) { _pusher = &pusher;}
    XMonitor* get_pusher() { return _pusher;}
    void push_trans();
    void begin_trans();
    bool mode_changed();
    bool position_changed();

    static void inc_change_ref() { Monitor::self_monitors_change++;}
    static void dec_change_ref() { Monitor::self_monitors_change--;}

private:
    void update_position();
    bool finde_mode_in_outputs(RRMode mode, int start_index, XRRScreenResources* res);
    bool finde_mode_in_clones(RRMode mode, XRRScreenResources* res);
    XRRModeInfo* find_mode(int width, int height, XRRScreenResources* res);

private:
    MultyMonScreen& _container;
    RRCrtc _crtc;
    XMonitorsList _clones;
    Point _position;
    Point _size;
    RRMode _mode;
    Rotation _rotation;
    int _noutput;
    RROutput* _outputs;

    Point _saved_position;
    Point _saved_size;
    RRMode _saved_mode;
    Rotation _saved_rotation;

    bool _out_of_sync;
    RedScreenRotation _red_rotation;
    RedSubpixelOrder _subpixel_order;

    int _trans_depth;
    Rect _trans_area[MAX_TRANS_DEPTH];
    int _pin_count;
    XMonitor* _pusher;
};

MultyMonScreen::MultyMonScreen(Display* display, int screen, int& next_mon_id)
    : XScreen(display, screen)
    , _saved_width (get_width())
    , _saved_height (get_height())
    , _saved_width_mm (DisplayWidthMM(display, screen))
    , _saved_height_mm (DisplayHeightMM(display, screen))
{
    X_DEBUG_SYNC(get_display());
    Window root_window = RootWindow(display, screen);
    XRRGetScreenSizeRange(display, root_window, &_min_width, &_min_height,
                          &_max_width, &_max_height);

    AutoScreenRes res(XRRGetScreenResources(display, root_window));
    if (!res.valid()) {
        THROW("get screen resources failed");
    }

#ifdef SHOW_SCREEN_INFO
    show_scren_info();
#endif
    try {
        for (int i = 0; i < res->ncrtc; i++) {
            AutoCrtcInfo crtc_info(XRRGetCrtcInfo(display, res.get(), res->crtcs[i]));

            if (!crtc_info.valid()) {
                THROW("get crtc info failed");
            }

            if (crtc_info->mode == None) {
                continue;
            }

            ASSERT(crtc_info->noutput);

            XMonitor* clone_mon = crtc_overlap_test(crtc_info->x, crtc_info->y,
                                                    crtc_info->width, crtc_info->height);

            if (clone_mon) {
                clone_mon->add_clone(new XMonitor(*this, next_mon_id++, res->crtcs[i]));
                continue;
            }

            _monitors.push_back(new XMonitor(*this, next_mon_id++, res->crtcs[i]));
        }
    } catch (...) {
        monitors_cleanup();
        throw;
    }

    XSelectInput(display, root_window, StructureNotifyMask);
    XRRSelectInput(display, root_window, RRScreenChangeNotifyMask);
    XPlatform::set_win_proc(root_window, root_win_proc);
    X_DEBUG_SYNC(get_display());
}

MultyMonScreen::~MultyMonScreen()
{
    restore();
    monitors_cleanup();
}

XMonitor* MultyMonScreen::crtc_overlap_test(int x, int y, int width, int height)
{
    XMonitorsList::iterator iter = _monitors.begin();
    for (; iter != _monitors.end(); iter++) {
        XMonitor* mon = *iter;

        Point pos = mon->get_position();
        Point size = mon->get_size();

        if (x == pos.x && y == pos.y && width == size.x && height == size.y) {
            return mon;
        }

        if (x < pos.x + size.x && x + width > pos.x && y < pos.y + size.y && y + height > pos.y) {
            THROW("unsupported partial overlap");
        }
    }
    return NULL;
}

void MultyMonScreen::publish_monitors(MonitorsList& monitors)
{
    XMonitorsList::iterator iter = _monitors.begin();
    for (; iter != _monitors.end(); iter++) {
        monitors.push_back(*iter);
    }
}

void MultyMonScreen::monitors_cleanup()
{
    while (!_monitors.empty()) {
        XMonitor* monitor = _monitors.front();
        _monitors.pop_front();
        delete monitor;
    }
}

void MultyMonScreen::disable()
{
    XMonitorsList::iterator iter = _monitors.begin();
    for (; iter != _monitors.end(); iter++) {
        (*iter)->disable();
    }
}

void MultyMonScreen::enable()
{
    XMonitorsList::iterator iter = _monitors.begin();
    for (; iter != _monitors.end(); iter++) {
        (*iter)->enable();
    }
}

void MultyMonScreen::set_size(int width, int height)
{
    X_DEBUG_SYNC(get_display());
    Window root_window = RootWindow(get_display(), get_screen());
    set_width(width);
    int width_mm = (int)((double)_saved_width_mm / _saved_width * width);
    set_height(height);
    int height_mm = (int)((double)_saved_height_mm / _saved_height * height);
    XRRSetScreenSize(get_display(), root_window, width, height, width_mm, height_mm);
    X_DEBUG_SYNC(get_display());
}

bool MultyMonScreen::changed()
{
    if (get_width() != _saved_width || get_height() != _saved_height) {
        return true;
    }

    XMonitorsList::iterator iter = _monitors.begin();
    for (; iter != _monitors.end(); iter++) {
        if ((*iter)->mode_changed() || (*iter)->position_changed()) {
            return true;
        }
    }
    return false;
}

void MultyMonScreen::restore()
{
    if (is_broken() || !changed()) {
        return;
    }
    X_DEBUG_SYNC(get_display());
    XMonitor::inc_change_ref();
    disable();
    Window root_window = RootWindow(get_display(), get_screen());

    XRRSetScreenSize(get_display(), root_window, _saved_width,
                     _saved_height,
                     _saved_width_mm, _saved_height_mm);
    XMonitorsList::iterator iter = _monitors.begin();
    for (; iter != _monitors.end(); iter++) {
        (*iter)->revert();
    }
    enable();
    process_monitor_configure_events(root_window);
    XMonitor::dec_change_ref();
    X_DEBUG_SYNC(get_display());
}

Point MultyMonScreen::get_trans_top_left()
{
    Point position;
    position.y = position.x = MAXINT;

    XMonitorsList::iterator iter = _monitors.begin();
    for (; iter != _monitors.end(); iter++) {
        Rect& area = (*iter)->get_trans_area();
        position.x = MIN(position.x, area.left);
        position.y = MIN(position.y, area.top);
    }
    return position;
}

Point MultyMonScreen::get_trans_bottom_right()
{
    Point position;
    position.y = position.x = MININT;

    XMonitorsList::iterator iter = _monitors.begin();
    for (; iter != _monitors.end(); iter++) {
        Rect& area = (*iter)->get_trans_area();
        position.x = MAX(position.x, area.right);
        position.y = MAX(position.y, area.bottom);
    }
    return position;
}

void MultyMonScreen::get_trans_size(int& width, int& height)
{
    ASSERT(get_trans_top_left().x == 0 && get_trans_top_left().y == 0);
    Point bottom_right = get_trans_bottom_right();
    ASSERT(bottom_right.x > 0 && bottom_right.y > 0);
    width = bottom_right.x;
    height = bottom_right.y;
}

#endif

/*class Variant {
    static void get_area_in_front(const Rect& base, int size, Rect& area)
    static int get_push_distance(const Rect& fix_area, const Rect& other)
    static int get_head(const Rect& area)
    static int get_tail(const Rect& area)
    static void move_head(Rect& area, int delta)
    static int get_pull_distance(const Rect& fix_area, const Rect& other)
    static void offset(Rect& area, int delta)
    static void shrink(Rect& area, int delta)
    static int get_distance(const Rect& area, const Rect& other_area)
    static bool is_on_tail(const Rect& area, const Rect& other_area)
    static bool is_on_perpendiculars(const Rect& area, const Rect& other_area)
}*/

#ifdef USE_XRANDR_1_2

class SortRightToLeft {
public:
    bool operator () (XMonitor* mon1, XMonitor* mon2) const
    {
        return mon1->get_trans_area().right > mon2->get_trans_area().right;
    }
};

typedef std::multiset<XMonitor*, SortRightToLeft> PushLeftSet;

class LeftVariant {
public:

    static void get_area_in_front(const Rect& base, int size, Rect& area)
    {
        area.right = base.left;
        area.left = area.right - size;
        area.bottom = base.bottom;
        area.top = base.top;
    }

    static int get_push_distance(const Rect& fix_area, const Rect& other)
    {
        return other.right - fix_area.left;
    }

    static int get_head(const Rect& area)
    {
        return area.left;
    }

    static int get_tail(const Rect& area)
    {
        return area.right;
    }

    static void move_head(Rect& area, int delta)
    {
        area.left -= delta;
        ASSERT(area.right >= area.left);
    }

    static int get_pull_distance(const Rect& fix_area, const Rect& other)
    {
        return other.left - fix_area.right;
    }

    static void offset(Rect& area, int delta)
    {
        rect_offset(area, -delta, 0);
    }

    static void shrink(Rect& area, int delta)
    {
        area.right -= delta;
        ASSERT(area.right > area.left);
    }

    static int get_distance(const Rect& area, const Rect& other_area)
    {
        return other_area.left - area.left;
    }

    static bool is_on_tail(const Rect& area, const Rect& other_area)
    {
        return area.right == other_area.left && other_area.top < area.bottom &&
               other_area.bottom > area.top;
    }

    static bool is_on_perpendiculars(const Rect& area, const Rect& other_area)
    {
        return (other_area.bottom == area.top || other_area.top == area.bottom) &&
               other_area.left < area.right && other_area.right > area.left;
    }
};

class SortLeftToRight {
public:
    bool operator () (XMonitor* mon1, XMonitor* mon2) const
    {
        return mon1->get_trans_area().left < mon2->get_trans_area().left;
    }
};

typedef std::multiset<XMonitor*, SortLeftToRight> PushRightSet;

class RightVariant {
public:

    static void get_area_in_front(const Rect& base, int size, Rect& area)
    {
        area.left = base.right;
        area.right = area.left + size;
        area.top = base.top;
        area.bottom = base.bottom;
    }

    static int get_push_distance(const Rect& fix_area, const Rect& other)
    {
        return fix_area.right - other.left;
    }

    static int get_head(const Rect& area)
    {
        return area.right;
    }

    static int get_tail(const Rect& area)
    {
        return area.left;
    }

    static void move_head(Rect& area, int delta)
    {
        area.right += delta;
        ASSERT(area.right >= area.left);
    }

    static int get_pull_distance(const Rect& fix_area, const Rect& other)
    {
        return fix_area.left - other.right;
    }

    static void offset(Rect& area, int delta)
    {
        rect_offset(area, delta, 0);
    }

    static bool is_on_tail(const Rect& area, const Rect& other_area)
    {
        return other_area.right == area.left && other_area.top < area.bottom &&
               other_area.bottom > area.top;
    }

    static bool is_on_perpendiculars(const Rect& area, const Rect& other_area)
    {
        return (other_area.bottom == area.top || other_area.top == area.bottom) &&
               other_area.left < area.right && other_area.right > area.left;
    }
};

class SortBottomToTop {
public:
    bool operator () (XMonitor* mon1, XMonitor* mon2) const
    {
        return mon1->get_trans_area().bottom > mon2->get_trans_area().bottom;
    }
};

typedef std::multiset<XMonitor*, SortBottomToTop> PushTopSet;

class TopVariant {
public:
    static void get_area_in_front(const Rect& base, int size, Rect& area)
    {
        area.left = base.left;
        area.right = base.right;
        area.bottom = base.top;
        area.top = area.bottom - size;
    }

    static int get_push_distance(const Rect& fix_area, const Rect& other)
    {
        return other.bottom - fix_area.top;
    }

    static int get_head(const Rect& area)
    {
        return area.top;
    }

    static int get_tail(const Rect& area)
    {
        return area.bottom;
    }

    static void move_head(Rect& area, int delta)
    {
        area.top -= delta;
        ASSERT(area.bottom >= area.top);
    }

    static int get_pull_distance(const Rect& fix_area, const Rect& other)
    {
        return other.top - fix_area.bottom;
    }

    static void offset(Rect& area, int delta)
    {
        rect_offset(area, 0, -delta);
    }

    static void shrink(Rect& area, int delta)
    {
        area.bottom -= delta;
        ASSERT(area.bottom > area.top);
    }

    static int get_distance(const Rect& area, const Rect& other_area)
    {
        return other_area.top - area.top;
    }

    static bool is_on_tail(const Rect& area, const Rect& other_area)
    {
        return area.bottom == other_area.top && other_area.left < area.right &&
               other_area.right > area.left;
    }

    static bool is_on_perpendiculars(const Rect& area, const Rect& other_area)
    {
        return (other_area.right == area.left || other_area.left == area.right) &&
               other_area.top < area.bottom && other_area.bottom > area.top;
    }
};

class SortTopToBottom {
public:
    bool operator () (XMonitor* mon1, XMonitor* mon2) const
    {
        return mon1->get_trans_area().top < mon2->get_trans_area().top;
    }
};

typedef std::multiset<XMonitor*, SortTopToBottom> PushBottomSet;

class BottomVariant {
public:

    static void get_area_in_front(const Rect& base, int size, Rect& area)
    {
        area.left = base.left;
        area.right = base.right;
        area.top = base.bottom;
        area.bottom = area.top + size;
    }

    static int get_push_distance(const Rect& fix_area, const Rect& other)
    {
        return fix_area.bottom - other.top;
    }

    static int get_head(const Rect& area)
    {
        return area.bottom;
    }

    static int get_tail(const Rect& area)
    {
        return area.top;
    }

    static void move_head(Rect& area, int delta)
    {
        area.bottom += delta;
        ASSERT(area.bottom >= area.top);
    }

    static int get_pull_distance(const Rect& fix_area, const Rect& other)
    {
        return fix_area.top - other.bottom;
    }

    static void offset(Rect& area, int delta)
    {
        rect_offset(area, 0, delta);
    }

    static bool is_on_tail(const Rect& area, const Rect& other_area)
    {
        return other_area.bottom == area.top && other_area.left < area.right &&
               other_area.right > area.left;
    }

    static bool is_on_perpendiculars(const Rect& area, const Rect& other_area)
    {
        return (other_area.right == area.left || other_area.left == area.right) &&
               other_area.top < area.bottom && other_area.bottom > area.top;
    }
};

volatile int wait_for_me = false;

template <class Variant>
static void bounce_back(XMonitor& monitor, const XMonitorsList& monitors, int head, int distance)
{
    ASSERT(distance > 0);
    while (wait_for_me);

    for (XMonitorsList::const_iterator iter = monitors.begin(); iter != monitors.end(); iter++) {
        Rect& area = (*iter)->get_trans_area();
        if (Variant::get_tail(area) == head && (*iter)->get_pusher() == &monitor) {
            Variant::offset(area, -distance);
            bounce_back<Variant>(**iter, monitors, Variant::get_head(area) + distance, distance);
            //todo: pull_back monitors on perpendiculars
        }
    }
}

template <class Variant, class SortList, class SortListIter>
static int push(XMonitor& pusher, XMonitor& monitor, const XMonitorsList& monitors, int delta)
{
    monitor.pin();
    monitor.set_pusher(pusher);

    SortList sort;
    XMonitorsList::const_iterator iter = monitors.begin();
    for (; iter != monitors.end(); iter++) {
        if (*iter == &monitor) {
            continue;
        }
        sort.insert(*iter);
    }

    Rect area_to_clear;
    Variant::get_area_in_front(monitor.get_trans_area(), delta, area_to_clear);

    SortListIter sort_iter = sort.begin();

    for (; sort_iter != sort.end(); sort_iter++) {
        const Rect& other_area = (*sort_iter)->get_trans_area();

        if (rect_intersects(area_to_clear, other_area)) {
            int distance = Variant::get_push_distance(area_to_clear, other_area);
            ASSERT(distance > 0);
            if (!(*sort_iter)->is_pinned()) {
                distance = distance - push<Variant, SortList, SortListIter>(monitor, **sort_iter,
                                                                            monitors, distance);
            }

            if (distance) {
                delta -= distance;
                bounce_back<Variant>(monitor, monitors, Variant::get_head(area_to_clear), distance);
                Variant::move_head(area_to_clear, -distance);
            }
        }
    }
    Variant::offset(monitor.get_trans_area(), delta);

    const Rect& area = monitor.get_prev_area();
    for (iter = monitors.begin(); iter != monitors.end(); iter++) {
        if ((*iter)->is_pinned()) {
            continue;
        }

        const Rect& other_area = (*iter)->get_prev_area();
        if (Variant::is_on_perpendiculars(area, other_area)) {
            int current_distance = Variant::get_pull_distance(monitor.get_trans_area(),
                                                              (*iter)->get_trans_area());
            int base_distance = Variant::get_pull_distance(area, other_area);
            int distance = current_distance - base_distance;
            if (distance > 0) {
                push<Variant, SortList, SortListIter>(monitor, **iter, monitors, distance);
            }
        } else if (Variant::is_on_tail(area, other_area)) {
            int distance = Variant::get_pull_distance(monitor.get_trans_area(),
                                                      (*iter)->get_trans_area());
            ASSERT(distance >= 0);
            push<Variant, SortList, SortListIter>(monitor, **iter, monitors, distance);
        }
    }
    return delta;
}

template <class Variant>
static void pin(XMonitor& monitor, const XMonitorsList& monitors)
{
    const Rect& area = monitor.get_trans_area();

    for (XMonitorsList::const_iterator iter = monitors.begin(); iter != monitors.end(); iter++) {
        const Rect& other_area = (*iter)->get_trans_area();
        if ((*iter)->is_pinned()) {
            continue;
        }
        if (Variant::is_on_tail(other_area, area) ||
                                                  Variant::is_on_perpendiculars(area, other_area)) {
            (*iter)->pin();
            pin<Variant>(**iter, monitors);
        }
    }
}

template <class Variant, class SortList, class SortListIter>
static void shrink(XMonitor& monitor, const XMonitorsList& monitors, int delta)
{
    monitor.pin();
    pin<Variant>(monitor, monitors);
    ASSERT(delta > 0);

    SortList sort;
    XMonitorsList::const_iterator iter = monitors.begin();
    for (; iter != monitors.end(); iter++) {
        if (*iter == &monitor) {
            continue;
        }
        sort.insert(*iter);
    }

    const Rect area = monitor.get_trans_area();
    Variant::shrink(monitor.get_trans_area(), delta);
    for (SortListIter sort_iter = sort.begin(); sort_iter != sort.end(); sort_iter++) {
        const Rect& other_area = (*sort_iter)->get_trans_area();
        if (Variant::is_on_perpendiculars(area, other_area)) {
            int distance = Variant::get_distance(area, other_area);
            if (distance > 0) {
                distance = MIN(distance, delta);
                push<Variant, SortList, SortListIter>(monitor, **sort_iter, monitors, distance);
            }
        } else if (Variant::is_on_tail(area, other_area)) {
            push<Variant, SortList, SortListIter>(monitor, **sort_iter, monitors, delta);
        }
    }
}

template <class Variant, class SortList, class SortListIter>
static void expand(XMonitor& monitor, const XMonitorsList& monitors, int delta)
{
    monitor.pin();
    ASSERT(delta > 0);

    SortList sort;
    XMonitorsList::const_iterator iter = monitors.begin();
    for (; iter != monitors.end(); iter++) {
        if (*iter == &monitor) {
            continue;
        }
        sort.insert(*iter);
    }

    Rect area_to_clear;
    Variant::get_area_in_front(monitor.get_trans_area(), delta, area_to_clear);

    for (SortListIter sort_iter = sort.begin(); sort_iter != sort.end(); sort_iter++) {
        const Rect& other_area = (*sort_iter)->get_trans_area();

        if (rect_intersects(area_to_clear, other_area)) {
            int distance = Variant::get_push_distance(area_to_clear, other_area);
            ASSERT(distance > 0);
            ASSERT(!(*sort_iter)->is_pinned());
#ifdef RED_DEBUG
            int actual =
#endif
            push<Variant, SortList, SortListIter>(monitor, **sort_iter, monitors, distance);
            ASSERT(actual == distance);
        }
    }
    Variant::move_head(monitor.get_trans_area(), delta);
}

bool MultyMonScreen::set_monitor_mode(XMonitor& monitor, const XRRModeInfo& mode_info)
{
    if (is_broken()) {
        return false;
    }

    Point size = monitor.get_size();
    int dx = mode_info.width - size.x;
    int dy = mode_info.height - size.y;

    XMonitorsList::iterator iter = _monitors.begin();

    for (; iter != _monitors.end(); iter++) {
        (*iter)->begin_trans();
    }

    if (dx > 0) {
        expand<RightVariant, PushRightSet, PushRightSet::iterator>(monitor, _monitors, dx);
    } else if (dx < 0) {
        shrink<LeftVariant, PushLeftSet, PushLeftSet::iterator>(monitor, _monitors, -dx);
    }

    for (iter = _monitors.begin(); iter != _monitors.end(); iter++) {
        (*iter)->push_trans();
    }

    if (dy > 0) {
        expand<BottomVariant, PushBottomSet, PushBottomSet::iterator>(monitor, _monitors, dy);
    } else if (dy < 0) {
        shrink<TopVariant, PushTopSet, PushTopSet::iterator>(monitor, _monitors, -dy);
    }

    int screen_width;
    int screen_height;

    get_trans_size(screen_width, screen_height);

    if (screen_width > _max_width || screen_height > _max_height) {
        return false;
    }

    screen_width = MAX(screen_width, _min_width);
    screen_height = MAX(screen_height, _min_height);

    XMonitor::inc_change_ref();
    disable();
    for (iter = _monitors.begin(); iter != _monitors.end(); iter++) {
        (*iter)->commit_trans_position();
    }
    X_DEBUG_SYNC(get_display());
    monitor.set_mode(mode_info);
    set_size(screen_width, screen_height);
    enable();
    Window root_window = RootWindow(get_display(), get_screen());
    process_monitor_configure_events(root_window);
    XMonitor::dec_change_ref();
    X_DEBUG_SYNC(get_display());
    return true;
}

XMonitor::XMonitor(MultyMonScreen& container, int id, RRCrtc crtc)
    : Monitor(id)
    , _container (container)
    , _crtc (crtc)
    , _out_of_sync (false)
{
    update_position();
    _saved_position = _position;
    _saved_size = _size;
    _saved_mode = _mode;
    _saved_rotation = _rotation;
}

XMonitor::~XMonitor()
{
    while (!_clones.empty()) {
        XMonitor* clone = _clones.front();
        _clones.pop_front();
        delete clone;
    }
    delete[] _outputs;
}

void XMonitor::update_position()
{
    Display* display = _container.get_display();
    X_DEBUG_SYNC(display);
    Window root_window = RootWindow(display, _container.get_screen());
    AutoScreenRes res(XRRGetScreenResources(display, root_window));

    if (!res.valid()) {
        THROW("get screen resources failed");
    }

    AutoCrtcInfo crtc_info(XRRGetCrtcInfo(display, res.get(), _crtc));

    ASSERT(crtc_info->noutput);

    _position.x = crtc_info->x;
    _position.y = crtc_info->y;
    _size.x = crtc_info->width;
    _size.y = crtc_info->height;

    switch (crtc_info->rotation & 0xf) {
    case RR_Rotate_0:
        _red_rotation = RED_SCREEN_ROTATION_0;
        break;
    case RR_Rotate_90:
        _red_rotation = RED_SCREEN_ROTATION_90;
        break;
    case RR_Rotate_180:
        _red_rotation = RED_SCREEN_ROTATION_180;
        break;
    case RR_Rotate_270:
        _red_rotation = RED_SCREEN_ROTATION_270;
        break;
    default:
        THROW("invalid rotation");
    }

    if (crtc_info->noutput > 1) {
        //todo: set valid subpixel order in case all outputs share the same type
        _subpixel_order = RED_SUBPIXEL_ORDER_UNKNOWN;
    } else {
        AutoOutputInfo output_info(XRRGetOutputInfo(display, res.get(), crtc_info->outputs[0]));

        switch (output_info->subpixel_order) {
        case SubPixelUnknown:
            _subpixel_order = RED_SUBPIXEL_ORDER_UNKNOWN;
        break;
        case SubPixelHorizontalRGB:
            _subpixel_order = RED_SUBPIXEL_ORDER_H_RGB;
            break;
        case SubPixelHorizontalBGR:
            _subpixel_order = RED_SUBPIXEL_ORDER_H_BGR;
            break;
        case SubPixelVerticalRGB:
            _subpixel_order = RED_SUBPIXEL_ORDER_V_RGB;
            break;
        case SubPixelVerticalBGR:
            _subpixel_order = RED_SUBPIXEL_ORDER_V_BGR;
            break;
        case SubPixelNone:
            _subpixel_order = RED_SUBPIXEL_ORDER_NONE;
            break;
        default:
            THROW("invalid subpixel order");
        }
    }

    _mode = crtc_info->mode;
    _rotation = crtc_info->rotation;
    _noutput = crtc_info->noutput;
    _outputs = new RROutput[_noutput];
    memcpy(_outputs, crtc_info->outputs, _noutput * sizeof(RROutput));
    X_DEBUG_SYNC(display);
}

bool XMonitor::finde_mode_in_outputs(RRMode mode, int start_index, XRRScreenResources* res)
{
    int i, j;

    X_DEBUG_SYNC(_container.get_display());
    for (i = start_index; i < _noutput; i++) {
        AutoOutputInfo output_info(XRRGetOutputInfo(_container.get_display(), res, _outputs[i]));
        for (j = 0; j < output_info->nmode; j++) {
            if (output_info->modes[j] == mode) {
                break;
            }
        }
        if (j == output_info->nmode) {
            return false;
        }
    }
    X_DEBUG_SYNC(_container.get_display());
    return true;
}

bool XMonitor::finde_mode_in_clones(RRMode mode, XRRScreenResources* res)
{
    XMonitorsList::iterator iter = _clones.begin();
    for (; iter != _clones.end(); iter++) {
        if (!(*iter)->finde_mode_in_outputs(mode, 0, res)) {
            return false;
        }
    }
    return true;
}

class ModeInfo {
public:
    ModeInfo(int int_index, XRRModeInfo* in_info) : index (int_index), info (in_info) {}

    int index;
    XRRModeInfo* info;
};

class ModeCompare {
public:
    bool operator () (const ModeInfo& mode1, const ModeInfo& mode2) const
    {
        int area1 = mode1.info->width * mode1.info->height;
        int area2 = mode2.info->width * mode2.info->height;
        return area1 < area2 || (area1 == area2 && mode1.index < mode2.index);
    }
};

XRRModeInfo* XMonitor::find_mode(int width, int height, XRRScreenResources* res)
{
    typedef std::set<ModeInfo, ModeCompare> ModesSet;
    ModesSet modes_set;
    X_DEBUG_SYNC(_container.get_display());
    AutoOutputInfo output_info(XRRGetOutputInfo(_container.get_display(), res, _outputs[0]));
    for (int i = 0; i < output_info->nmode; i++) {
        XRRModeInfo* mode_inf = find_mod(res, output_info->modes[i]);
        if (mode_inf->width >= width && mode_inf->height >= height) {
            modes_set.insert(ModeInfo(i, mode_inf));
        }
    }

    while (!modes_set.empty()) {
        ModesSet::iterator iter = modes_set.begin();

        if (!finde_mode_in_outputs((*iter).info->id, 1, res)) {
            modes_set.erase(iter);
            continue;
        }

        if (!finde_mode_in_clones((*iter).info->id, res)) {
            modes_set.erase(iter);
            continue;
        }
        return (*iter).info;
    }
    X_DEBUG_SYNC(_container.get_display());
    return NULL;
}

void XMonitor::set_mode(int width, int height)
{
    if (width == _size.x && height == _size.y) {
        _out_of_sync = false;
        return;
    }
    Display* display = _container.get_display();
    X_DEBUG_SYNC(display);
    Window root_window = RootWindow(display, _container.get_screen());
    AutoScreenRes res(XRRGetScreenResources(display, root_window));
    if (!res.valid()) {
        THROW("get screen resource failed");
    }
    XRRModeInfo* mode_info = find_mode(width, height, res.get());

    if (!mode_info || !_container.set_monitor_mode(*this, *mode_info)) {
        _out_of_sync = true;
        X_DEBUG_SYNC(display);
        return;
    }
    _out_of_sync = false;
}

void XMonitor::revert()
{
    _position = _saved_position;
    _size = _saved_size;
    _mode = _saved_mode;
    _rotation = _saved_rotation;
    XMonitorsList::iterator iter = _clones.begin();
    for (; iter != _clones.end(); iter++) {
        (*iter)->revert();
    }
}

void XMonitor::disable()
{
    Display* display = _container.get_display();
    X_DEBUG_SYNC(display);
    Window root_window = RootWindow(display, _container.get_screen());
    AutoScreenRes res(XRRGetScreenResources(display, root_window));
    if (!res.valid()) {
        THROW("get screen resources failed");
    }
    XRRSetCrtcConfig(display, res.get(), _crtc, CurrentTime,
                     0, 0, None, RR_Rotate_0, NULL, 0);

    XMonitorsList::iterator iter = _clones.begin();
    for (; iter != _clones.end(); iter++) {
        (*iter)->disable();
    }
    X_DEBUG_SYNC(display);
}

void XMonitor::enable()
{
    Display* display = _container.get_display();
    X_DEBUG_SYNC(display);
    Window root_window = RootWindow(display, _container.get_screen());
    AutoScreenRes res(XRRGetScreenResources(display, root_window));
    if (!res.valid()) {
        THROW("get screen resources failed");
    }
    XRRSetCrtcConfig(display, res.get(), _crtc, CurrentTime,
                     _position.x, _position.y,
                     _mode, _rotation,
                     _outputs, _noutput);

    XMonitorsList::iterator iter = _clones.begin();
    for (; iter != _clones.end(); iter++) {
        (*iter)->enable();
    }
    X_DEBUG_SYNC(display);
}

bool XMonitor::mode_changed()
{
    return _size.x != _saved_size.x || _size.y != _saved_size.y ||
           _mode != _saved_mode || _rotation != _saved_rotation;
}

bool XMonitor::position_changed()
{
    return _position.x != _saved_position.x || _position.y != _saved_position.y;
}

void XMonitor::restore()
{
    if (!mode_changed()) {
        return;
    }
    set_mode(_saved_size.x, _saved_size.y);
}

int XMonitor::get_depth()
{
    return XPlatform::get_vinfo()[0]->depth;
}

Point XMonitor::get_position()
{
    return _position;
}

Point XMonitor::get_size() const
{
    return _size;
}

bool XMonitor::is_out_of_sync()
{
    return _out_of_sync;
}

void XMonitor::add_clone(XMonitor *clone)
{
    _clones.push_back(clone);
}

const Rect& XMonitor::get_prev_area()
{
    return _trans_area[_trans_depth - 1];
}

Rect& XMonitor::get_trans_area()
{
    return _trans_area[_trans_depth];
}

void XMonitor::push_trans()
{
    _trans_depth++;
    ASSERT(_trans_depth < MAX_TRANS_DEPTH);
    _trans_area[_trans_depth] = _trans_area[_trans_depth - 1];
    _pin_count = 0;
    _pusher = NULL;
}

void XMonitor::begin_trans()
{
    _trans_area[0].left = _position.x;
    _trans_area[0].right = _trans_area[0].left + _size.x;
    _trans_area[0].top = _position.y;
    _trans_area[0].bottom = _trans_area[0].top + _size.y;
    _trans_area[1] = _trans_area[0];
    _trans_depth = 1;
    _pin_count = 0;
    _pusher = NULL;
}

void XMonitor::commit_trans_position()
{
    _position.x = _trans_area[_trans_depth].left;
    _position.y = _trans_area[_trans_depth].top;
    XMonitorsList::iterator iter = _clones.begin();
    for (; iter != _clones.end(); iter++) {
        (*iter)->_position = _position;
    }
}

void XMonitor::set_mode(const XRRModeInfo& mode)
{
    _mode = mode.id;
    _size.x = mode.width;
    _size.y = mode.height;
    XMonitorsList::iterator iter = _clones.begin();
    for (; iter != _clones.end(); iter++) {
        (*iter)->set_mode(mode);
    }
}

#endif

static MonitorsList monitors;

typedef std::list<XScreen*> ScreenList;
static ScreenList screens;

const MonitorsList& Platform::init_monitors()
{
    int next_mon_id = 0;
    ASSERT(screens.empty());
#ifdef USE_XRANDR_1_2
    if (using_xrandr_1_2) {
        for (int i = 0; i < ScreenCount(x_display); i++) {
            screens.push_back(new MultyMonScreen(x_display, i, next_mon_id));
        }
    } else
#endif
    if (using_xrandr_1_0) {
        for (int i = 0; i < ScreenCount(x_display); i++) {
            screens.push_back(new DynamicScreen(x_display, i, next_mon_id));
        }
    } else {
        for (int i = 0; i < ScreenCount(x_display); i++) {
            screens.push_back(new StaticScreen(x_display, i, next_mon_id));
        }
    }

    ASSERT(monitors.empty());
    ScreenList::iterator iter = screens.begin();
    for (; iter != screens.end(); iter++) {
        (*iter)->publish_monitors(monitors);
    }
    return monitors;
}

void Platform::destroy_monitors()
{
    monitors.clear();
    while (!screens.empty()) {
        XScreen* screen = screens.front();
        screens.pop_front();
        delete screen;
    }
}

bool Platform::is_monitors_pos_valid()
{
    return (ScreenCount(x_display) == 1);
}

static void root_win_proc(XEvent& event)
{
#ifdef USE_XRANDR_1_2
    ASSERT(using_xrandr_1_0 || using_xrandr_1_2);
#else
    ASSERT(using_xrandr_1_0);
#endif
    if (event.type == ConfigureNotify || event.type - xrandr_event_base == RRScreenChangeNotify) {
        XRRUpdateConfiguration(&event);
        if (event.type - xrandr_event_base == RRScreenChangeNotify) {
            display_mode_listener->on_display_mode_change();
        }

        if (Monitor::is_self_change()) {
            return;
        }

        ScreenList::iterator iter = screens.begin();
        for (; iter != screens.end(); iter++) {
            (*iter)->set_broken();
        }
        event_listener->on_monitors_change();
    }

    /*switch (event.type - xrandr_event_base) {
    case RRScreenChangeNotify:
        //XRRScreenChangeNotifyEvent * = (XRRScreenChangeNotifyEvent *) &event;
        XRRUpdateConfiguration(&event);
        break;
    }*/
}

static void process_monitor_configure_events(Window root)
{
    XSync(x_display, False);
    XEvent event;

    while (XCheckTypedWindowEvent(x_display, root, ConfigureNotify, &event)) {
        root_win_proc(event);
    }

    while (XCheckTypedWindowEvent(x_display, root, xrandr_event_base + RRScreenChangeNotify,
                                  &event)) {
        root_win_proc(event);
    }
}

static void cleanup(void)
{
    int i;

    DBG(0, "");
    if (!Monitor::is_self_change()) {
        Platform::destroy_monitors();
    }
    if (vinfo) {
        for (i = 0; i < ScreenCount(x_display); ++i) {
            XFree(vinfo[i]);
        }
        delete vinfo;
        vinfo = NULL;
    }
    if (fb_config) {
        for (i = 0; i < ScreenCount(x_display); ++i) {
            XFree(fb_config[i]);
        }
        delete fb_config;
        fb_config = NULL;
    }
}

static void quit_handler(int sig)
{
    LOG_INFO("signal %d", sig);
    Platform::send_quit_request();
}

static void abort_handler(int sig)
{
    LOG_INFO("signal %d", sig);
    Platform::destroy_monitors();
}

static void init_xrandr()
{
    Bool xrandr_ext = XRRQueryExtension(x_display, &xrandr_event_base, &xrandr_error_base);
    if (xrandr_ext) {
        XRRQueryVersion(x_display, &xrandr_major, &xrandr_minor);
        if (xrandr_major < 1) {
            return;
        }
#ifdef USE_XRANDR_1_2
        if (xrandr_major == 1 && xrandr_minor < 2) {
            using_xrandr_1_0 = true;
            return;
        }
        using_xrandr_1_2 = true;
#else
        using_xrandr_1_0 = true;
#endif
    }
}

static void init_xrender()
{
    int event_base;
    int error_base;
    int major;
    int minor;

    using_xrender_0_5 = XRenderQueryExtension(x_display, &event_base, &error_base) &&
        XRenderQueryVersion(x_display, &major, &minor) && (major > 0 || minor >= 5);
}

unsigned int get_modifier_mask(KeySym modifier)
{
    int mask = 0;
    int i;

    XModifierKeymap* map = XGetModifierMapping(x_display);
    KeyCode keycode = XKeysymToKeycode(x_display, modifier);
    if (keycode == NoSymbol) {
        return 0;
    }

    for (i = 0; i < 8; i++) {
        if (map->modifiermap[map->max_keypermod * i] == keycode) {
            mask = 1 << i;
        }
    }
    XFreeModifiermap(map);
    return mask;
}

static void init_kbd()
{
    int xkb_major = XkbMajorVersion;
    int xkb_minor = XkbMinorVersion;
    int opcode;
    int event;
    int error;

    if (!XkbLibraryVersion(&xkb_major, &xkb_minor) ||
        !XkbQueryExtension(x_display, &opcode, &event, &error, &xkb_major, &xkb_minor)) {
        return;
    }
    caps_lock_mask = get_modifier_mask(XK_Caps_Lock);
    num_lock_mask = get_modifier_mask(XK_Num_Lock);
}

static int x_error_handler(Display* display, XErrorEvent* error_event)
{
    char error_str[256];
    char request_str[256];
    char number_str[32];

    char* display_name = XDisplayString(display);
    XGetErrorText(display, error_event->error_code, error_str, sizeof(error_str));

    if (error_event->request_code < 128) {
        snprintf(number_str, sizeof(number_str), "%d", error_event->request_code);
        XGetErrorDatabaseText(display, "XRequest", number_str, "",
                              request_str, sizeof(request_str));
    } else {
        snprintf(request_str, sizeof(request_str), "%d", error_event->request_code);
    }

    LOG_ERROR("x error on display %s error %s minor %u request %s",
              display_name,
              error_str,
              (uint32_t)error_event->minor_code,
              request_str);
    exit(-1);
    return 0;
}

static int x_io_error_handler(Display* display)
{
    LOG_ERROR("x io error on %s", XDisplayString(display));
    exit(-1);
    return 0;
}

static XVisualInfo* get_x_vis_info(int screen)
{
    XVisualInfo vtemplate;
    int count;

    Visual* visual = DefaultVisualOfScreen(ScreenOfDisplay(x_display, screen));
    vtemplate.screen = screen;
    vtemplate.visualid = XVisualIDFromVisual(visual);
    return XGetVisualInfo(x_display, VisualIDMask | VisualScreenMask, &vtemplate, &count);
}

void Platform::init()
{
    int err, ev;
    int threads_enable;

    DBG(0, "");

    threads_enable = XInitThreads();


    if (!(x_display = XOpenDisplay(NULL))) {
        THROW("open X display failed");
    }

    vinfo = new XVisualInfo *[ScreenCount(x_display)];
    memset(vinfo, 0, sizeof(XVisualInfo *) * ScreenCount(x_display));
    fb_config = new GLXFBConfig *[ScreenCount(x_display)];
    memset(fb_config, 0, sizeof(GLXFBConfig *) * ScreenCount(x_display));

    if (threads_enable && glXQueryExtension(x_display, &err, &ev)) {
        int num_configs;
        int attrlist[] = {
            GLX_RENDER_TYPE, GLX_RGBA_BIT,
            GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT | GLX_WINDOW_BIT,
            GLX_X_VISUAL_TYPE, GLX_TRUE_COLOR,
            GLX_RED_SIZE, 8,
            GLX_GREEN_SIZE, 8,
            GLX_BLUE_SIZE, 8,
            GLX_ALPHA_SIZE, 8,
            GLX_STENCIL_SIZE, 4,
            GLX_DEPTH_SIZE, 0,
            None
        };

        for (int i = 0; i < ScreenCount(x_display); ++i) {
            if (!(fb_config[i] = glXChooseFBConfig(x_display, i, attrlist, &num_configs))) {
                vinfo[i] = get_x_vis_info(i);
            } else {
                ASSERT(num_configs > 0);
                vinfo[i] = glXGetVisualFromFBConfig(x_display, fb_config[i][0]);
            }

            if (!vinfo[i]) {
                THROW("XGetVisualInfo failed");
            }
        }
    } else {
        for (int i = 0; i < ScreenCount(x_display); ++i) {
            if (!(vinfo[i] = get_x_vis_info(i))) {
                THROW("XGetVisualInfo failed");
            }
        }
    }

    XSetErrorHandler(x_error_handler);
    XSetIOErrorHandler(x_io_error_handler);

    win_proc_context = XUniqueContext();

    init_kbd();
    init_xrandr();
    init_xrender();

    struct sigaction act;
    memset(&act, 0, sizeof(act));
    sigfillset(&act.sa_mask);

    act.sa_handler = quit_handler;
    sigaction(SIGINT, &act, NULL);
    sigaction(SIGHUP, &act, NULL);
    sigaction(SIGTERM, &act, NULL);
    sigaction(SIGQUIT, &act, NULL);

    act.sa_handler = SIG_IGN;
    sigaction(SIGPIPE, &act, NULL);

    act.sa_flags = SA_RESETHAND;
    act.sa_handler = abort_handler;
    sigaction(SIGABRT, &act, NULL);
    sigaction(SIGILL, &act, NULL);
    sigaction(SIGSEGV, &act, NULL);
    sigaction(SIGFPE, &act, NULL);

    atexit(cleanup);
}

void Platform::set_process_loop(ProcessLoop& main_process_loop)
{
    main_loop = &main_process_loop;
    XEventHandler *x_event_handler;
    x_event_handler = new XEventHandler(*x_display, win_proc_context);
    main_loop->add_file(*x_event_handler);
}

uint32_t Platform::get_keyboard_modifiers()
{
    XKeyboardState keyboard_state;
    uint32_t modifiers = 0;

    XGetKeyboardControl(x_display, &keyboard_state);

    if (keyboard_state.led_mask & 0x01) {
        modifiers |= CAPS_LOCK_MODIFIER;
    }
    if (keyboard_state.led_mask & 0x02) {
        modifiers |= NUM_LOCK_MODIFIER;
    }
    if (keyboard_state.led_mask & 0x04) {
        modifiers |= SCROLL_LOCK_MODIFIER;
    }
    return modifiers;
}

enum XLed {
    X11_CAPS_LOCK_LED = 1,
    X11_NUM_LOCK_LED,
    X11_SCROLL_LOCK_LED,
};

static void  set_keyboard_led(XLed led, int set)
{
    switch (led) {
    case X11_CAPS_LOCK_LED:
        if (caps_lock_mask) {
            XkbLockModifiers(x_display, XkbUseCoreKbd, caps_lock_mask, set ? caps_lock_mask : 0);
        }
        return;
    case X11_NUM_LOCK_LED:
        if (num_lock_mask) {
            XkbLockModifiers(x_display, XkbUseCoreKbd, num_lock_mask, set ? num_lock_mask : 0);
        }
        return;
    case X11_SCROLL_LOCK_LED:
        XKeyboardControl keyboard_control;
        keyboard_control.led_mode = set ? LedModeOn : LedModeOff;
        keyboard_control.led = led;
        XChangeKeyboardControl(x_display, KBLed | KBLedMode, &keyboard_control);
        return;
    }
}

void Platform::set_keyboard_modifiers(uint32_t modifiers)
{
    uint32_t now = get_keyboard_modifiers();

    if ((now & CAPS_LOCK_MODIFIER) != (modifiers & CAPS_LOCK_MODIFIER)) {
        set_keyboard_led(X11_CAPS_LOCK_LED, !!(modifiers & CAPS_LOCK_MODIFIER));
    }
    if ((now & NUM_LOCK_MODIFIER) != (modifiers & NUM_LOCK_MODIFIER)) {
        set_keyboard_led(X11_NUM_LOCK_LED, !!(modifiers & NUM_LOCK_MODIFIER));
    }
    if ((now & SCROLL_LOCK_MODIFIER) != (modifiers & SCROLL_LOCK_MODIFIER)) {
        set_keyboard_led(X11_SCROLL_LOCK_LED, !!(modifiers & SCROLL_LOCK_MODIFIER));
    }
}

WaveRecordAbstract* Platform::create_recorder(RecordClient& client,
                                              uint32_t sampels_per_sec,
                                              uint32_t bits_per_sample,
                                              uint32_t channels)
{
    return new WaveRecorder(client, sampels_per_sec, bits_per_sample, channels);
}

WavePlaybackAbstract* Platform::create_player(uint32_t sampels_per_sec,
                                              uint32_t bits_per_sample,
                                              uint32_t channels)
{
    return new WavePlayer(sampels_per_sec, bits_per_sample, channels);
}

void XPlatform::on_focus_in()
{
    if (focus_count++ == 0) {
        event_listener->on_app_activated();
    }
}

void XPlatform::on_focus_out()
{
    ASSERT(focus_count > 0);
    if (--focus_count == 0) {
        event_listener->on_app_deactivated();
    }
}

class XBaseLocalCursor: public LocalCursor {
public:
    XBaseLocalCursor() : _handle (0) {}
    ~XBaseLocalCursor();
    void set(Window window);

protected:
    Cursor _handle;
};

void XBaseLocalCursor::set(Window window)
{
    if (_handle) {
        XDefineCursor(x_display, window, _handle);
    }
}

XBaseLocalCursor::~XBaseLocalCursor()
{
    if (_handle) {
        XFreeCursor(x_display, _handle);
    }
}

class XLocalCursor: public XBaseLocalCursor {
public:
    XLocalCursor(CursorData* cursor_data);
};

static inline uint8_t get_pix_mask(const uint8_t* data, int offset, int pix_index)
{
    return data[offset + (pix_index >> 3)] & (0x80 >> (pix_index % 8));
}

static inline uint32_t get_pix_hack(int pix_index, int width)
{
    return (((pix_index % width) ^ (pix_index / width)) & 1) ? 0xc0303030 : 0x30505050;
}

XLocalCursor::XLocalCursor(CursorData* cursor_data)
{
    const CursorHeader& header = cursor_data->header();
    const uint8_t* data = cursor_data->data();
    int cur_size = header.width * header.height;
    uint8_t pix_mask;
    uint32_t pix;
    uint16_t i;
    int size;

    if (!get_size_bits(header, size)) {
        THROW("invalid curosr type");
    }

    uint32_t* cur_data = new uint32_t[cur_size];

    switch (header.type) {
    case CURSOR_TYPE_ALPHA:
        break;
    case CURSOR_TYPE_COLOR32:
        memcpy(cur_data, data, cur_size * sizeof(uint32_t));
        for (i = 0; i < cur_size; i++) {
            pix_mask = get_pix_mask(data, size, i);
            if (pix_mask && *((uint32_t*)data + i) == 0xffffff) {
                cur_data[i] = get_pix_hack(i, header.width);
            } else {
                cur_data[i] |= (pix_mask ? 0 : 0xff000000);
            }
        }
        break;
    case CURSOR_TYPE_COLOR16:
        for (i = 0; i < cur_size; i++) {
            pix_mask = get_pix_mask(data, size, i);
            pix = *((uint16_t*)data + i);
            if (pix_mask && pix == 0x7fff) {
                cur_data[i] = get_pix_hack(i, header.width);
            } else {
                cur_data[i] = ((pix & 0x1f) << 3) | ((pix & 0x3e0) << 6) | ((pix & 0x7c00) << 9) |
                    (pix_mask ? 0 : 0xff000000);
            }
        }
        break;
    case CURSOR_TYPE_MONO:
        for (i = 0; i < cur_size; i++) {
            pix_mask = get_pix_mask(data, 0, i);
            pix = get_pix_mask(data, size, i);
            if (pix_mask && pix) {
                cur_data[i] = get_pix_hack(i, header.width);
            } else {
                cur_data[i] = (pix ? 0xffffff : 0) | (pix_mask ? 0 : 0xff000000);
            }
        }
        break;
    case CURSOR_TYPE_COLOR4:
        for (i = 0; i < cur_size; i++) {
            pix_mask = get_pix_mask(data, size + (sizeof(uint32_t) << 4), i);
            int idx = (i & 1) ? (data[i >> 1] & 0x0f) : ((data[i >> 1] & 0xf0) >> 4);
            pix = *((uint32_t*)(data + size) + idx);
            if (pix_mask && pix == 0xffffff) {
                cur_data[i] = get_pix_hack(i, header.width);
            } else {
                cur_data[i] = pix | (pix_mask ? 0 : 0xff000000);
            }
        }
        break;
    case CURSOR_TYPE_COLOR24:
    case CURSOR_TYPE_COLOR8:
    default:
        LOG_WARN("unsupported cursor type %d", header.type);
        _handle = XCreateFontCursor(x_display, XC_arrow);
        delete[] cur_data;
        return;
    }

    XImage image;
    memset(&image, 0, sizeof(image));
    image.width = header.width;
    image.height = header.height;
    image.data = (header.type == CURSOR_TYPE_ALPHA ? (char*)data : (char*)cur_data);
    image.byte_order = LSBFirst;
    image.bitmap_unit = 32;
    image.bitmap_bit_order = LSBFirst;
    image.bitmap_pad = 8;
    image.bytes_per_line = header.width << 2;
    image.depth = 32;
    image.format = ZPixmap;
    image.bits_per_pixel = 32;
    image.red_mask = 0x00ff0000;
    image.green_mask = 0x0000ff00;
    image.blue_mask = 0x000000ff;
    if (!XInitImage(&image)) {
        THROW("init image failed");
    }

    Window root_window = RootWindow(x_display, DefaultScreen(x_display));
    Pixmap pixmap = XCreatePixmap(x_display, root_window, header.width, header.height, 32);

    XGCValues gc_vals;
    gc_vals.function = GXcopy;
    gc_vals.foreground = ~0;
    gc_vals.background = 0;
    gc_vals.plane_mask = AllPlanes;

    GC gc = XCreateGC(x_display, pixmap, GCFunction | GCForeground | GCBackground | GCPlaneMask,
                      &gc_vals);
    XPutImage(x_display, pixmap, gc, &image, 0, 0, 0, 0, header.width, header.height);
    XFreeGC(x_display, gc);

    XRenderPictFormat *xformat = XRenderFindStandardFormat(x_display, PictStandardARGB32);
    Picture picture = XRenderCreatePicture(x_display, pixmap, xformat, 0, NULL);
    _handle = XRenderCreateCursor(x_display, picture, header.hot_spot_x, header.hot_spot_y);
    XRenderFreePicture(x_display, picture);
    XFreePixmap(x_display, pixmap);
    delete[] cur_data;
}

LocalCursor* Platform::create_local_cursor(CursorData* cursor_data)
{
    ASSERT(using_xrender_0_5);
    return new XLocalCursor(cursor_data);
}

class XInactiveCursor: public XBaseLocalCursor {
public:
    XInactiveCursor() { _handle = XCreateFontCursor(x_display, XC_X_cursor);}
};

LocalCursor* Platform::create_inactive_cursor()
{
    return new XInactiveCursor();
}

class XDefaultCursor: public XBaseLocalCursor {
public:
    XDefaultCursor() { _handle = XCreateFontCursor(x_display, XC_top_left_arrow);}
};

LocalCursor* Platform::create_default_cursor()
{
    return new XDefaultCursor();
}