summaryrefslogtreecommitdiffstats
path: root/kwin/workspace.cpp
blob: 6829b3ccb553a3f93b827fc1b7d5ce49b772d12f (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
/*****************************************************************
 KWin - the KDE window manager
 This file is part of the KDE project.

Copyright (C) 1999, 2000 Matthias Ettrich <ettrich@kde.org>
Copyright (C) 2003 Lubos Lunak <l.lunak@kde.org>

You can Freely distribute this program under the GNU General Public
License. See the file "COPYING" for the exact licensing terms.
******************************************************************/

//#define QT_CLEAN_NAMESPACE

#include "workspace.h"

#include <kapplication.h>
#include <kstartupinfo.h>
#include <fixx11h.h>
#include <kconfig.h>
#include <kglobal.h>
#include <tqpopupmenu.h>
#include <klocale.h>
#include <tqregexp.h>
#include <tqpainter.h>
#include <tqbitmap.h>
#include <tqclipboard.h>
#include <kmenubar.h>
#include <kprocess.h>
#include <kglobalaccel.h>
#include <dcopclient.h>
#include <kipc.h>

#include "plugins.h"
#include "client.h"
#include "popupinfo.h"
#include "tabbox.h"
#include "atoms.h"
#include "placement.h"
#include "notifications.h"
#include "group.h"
#include "rules.h"

#include <X11/extensions/shape.h>
#include <X11/keysym.h>
#include <X11/keysymdef.h>
#include <X11/cursorfont.h>

namespace KWinInternal
{

extern int screen_number;

Workspace *Workspace::_self = 0;

KProcess* kompmgr = 0;
KSelectionOwner* kompmgr_selection;

bool allowKompmgrRestart = TRUE;

bool supportsCompMgr()
{
    int i;

    bool damageExt = XQueryExtension(qt_xdisplay(), "DAMAGE", &i, &i, &i);
    bool compositeExt = XQueryExtension(qt_xdisplay(), "Composite", &i, &i, &i);
    bool xfixesExt = XQueryExtension(qt_xdisplay(), "XFIXES", &i, &i, &i);

    return damageExt && compositeExt && xfixesExt;
}

// Rikkus: This class is too complex. It needs splitting further.
// It's a nightmare to understand, especially with so few comments :(

// Matthias: Feel free to ask me questions about it. Feel free to add
// comments. I disagree that further splittings makes it easier. 2500
// lines are not too much. It's the task that is complex, not the
// code.
Workspace::Workspace( bool restore )
  : DCOPObject        ("KWinInterface"),
    TQObject           (0, "workspace"),
    current_desktop   (0),
    number_of_desktops(0),
    active_screen     (0),
    active_popup( NULL ),
    active_popup_client( NULL ),
    desktop_widget    (0),
    temporaryRulesMessages( "_KDE_NET_WM_TEMPORARY_RULES", NULL, false ),
    rules_updates_disabled( false ),
    active_client     (0),
    last_active_client     (0),
    next_active_client     (0),
    most_recently_raised (0),
    movingClient(0),
    pending_take_activity ( NULL ),
    delayfocus_client (0),
    showing_desktop( false ),
    block_showing_desktop( 0 ),
    was_user_interaction (false),
    session_saving    (false),
    control_grab      (false),
    tab_grab          (false),
    mouse_emulation   (false),
    block_focus       (0),
    tab_box           (0),
    popupinfo         (0),
    popup             (0),
    advanced_popup    (0),
    desk_popup        (0),
    desk_popup_index  (0),
    keys              (0),
    client_keys       ( NULL ),
    client_keys_dialog ( NULL ),
    client_keys_client ( NULL ),
    disable_shortcuts_keys ( NULL ),
    global_shortcuts_disabled( false ),
    global_shortcuts_disabled_for_client( false ),
    root              (0),
    workspaceInit     (true),
    startup(0), electric_have_borders(false),
    electric_current_border(0),
    electric_top_border(None),
    electric_bottom_border(None),
    electric_left_border(None),
    electric_right_border(None),
    layoutOrientation(Qt::Vertical),
    layoutX(-1),
    layoutY(2),
    workarea(NULL),
    screenarea(NULL),
    managing_topmenus( false ),
    topmenu_selection( NULL ),
    topmenu_watcher( NULL ),
    topmenu_height( 0 ),
    topmenu_space( NULL ),
    set_active_client_recursion( 0 ),
    block_stacking_updates( 0 ),
    forced_global_mouse_grab( false )
    {
    _self = this;
    mgr = new PluginMgr;
    root = qt_xrootwin();
    default_colormap = DefaultColormap(qt_xdisplay(), qt_xscreen() );
    installed_colormap = default_colormap;
    session.setAutoDelete( TRUE );

    connect( &temporaryRulesMessages, TQT_SIGNAL( gotMessage( const TQString& )),
        this, TQT_SLOT( gotTemporaryRulesMessage( const TQString& )));
    connect( &rulesUpdatedTimer, TQT_SIGNAL( timeout()), this, TQT_SLOT( writeWindowRules()));

    updateXTime(); // needed for proper initialization of user_time in Client ctor

    delayFocusTimer = 0; 
    
    electric_time_first = GET_QT_X_TIME();
    electric_time_last = GET_QT_X_TIME();

    if ( restore )
      loadSessionInfo();

    loadWindowRules();

    (void) TQApplication::desktop(); // trigger creation of desktop widget

    desktop_widget =
      new TQWidget(
        0,
        "desktop_widget",
        (WFlags)(TQt::WType_Desktop | TQt::WPaintUnclipped)
    );

    kapp->setGlobalMouseTracking( true ); // so that this doesn't mess eventmask on root window later
    // call this before XSelectInput() on the root window
    startup = new KStartupInfo(
        KStartupInfo::DisableKWinModule | KStartupInfo::AnnounceSilenceChanges, this );

    // select windowmanager privileges
    XSelectInput(qt_xdisplay(), root,
                 KeyPressMask |
                 PropertyChangeMask |
                 ColormapChangeMask |
                 SubstructureRedirectMask |
                 SubstructureNotifyMask |
                 FocusChangeMask // for NotifyDetailNone
                 );

    Shape::init();

    // compatibility
    long data = 1;

    XChangeProperty(
      qt_xdisplay(),
      qt_xrootwin(),
      atoms->kwin_running,
      atoms->kwin_running,
      32,
      PropModeAppend,
      (unsigned char*) &data,
      1
    );

    client_keys = new KGlobalAccel( this );
    initShortcuts();
    tab_box = new TabBox( this );
    popupinfo = new PopupInfo( this );

    init();

#if (QT_VERSION-0 >= 0x030200) // XRANDR support
    connect( kapp->desktop(), TQT_SIGNAL( resized( int )), TQT_SLOT( desktopResized()));
#endif

    if (!supportsCompMgr())
        options->useTranslucency = false;

    // start kompmgr - i wanted to put this into main.cpp, but that would prevent dcop support, as long as Application was no dcop_object
    if (options->useTranslucency)
        {
        kompmgr = new KProcess;
        connect(kompmgr, TQT_SIGNAL(receivedStderr(KProcess*, char*, int)), TQT_SLOT(handleKompmgrOutput(KProcess*, char*, int)));
        *kompmgr << "kompmgr";
        startKompmgr();
        }
    }


void Workspace::init()
    {
    checkElectricBorders();

// not used yet
//     topDock = 0L;
//     maximizedWindowCounter = 0;
    
    supportWindow = new TQWidget;
    XLowerWindow( qt_xdisplay(), supportWindow->winId()); // see usage in layers.cpp

    XSetWindowAttributes attr;
    attr.override_redirect = 1;
    null_focus_window = XCreateWindow( qt_xdisplay(), qt_xrootwin(), -1,-1, 1, 1, 0, CopyFromParent,
        InputOnly, CopyFromParent, CWOverrideRedirect, &attr );
    XMapWindow(qt_xdisplay(), null_focus_window);

    unsigned long protocols[ 5 ] =
        {
        NET::Supported |
        NET::SupportingWMCheck |
        NET::ClientList |
        NET::ClientListStacking |
        NET::DesktopGeometry |
        NET::NumberOfDesktops |
        NET::CurrentDesktop |
        NET::ActiveWindow |
        NET::WorkArea |
        NET::CloseWindow |
        NET::DesktopNames |
        NET::KDESystemTrayWindows |
        NET::WMName |
        NET::WMVisibleName |
        NET::WMDesktop |
        NET::WMWindowType |
        NET::WMState |
        NET::WMStrut |
        NET::WMIconGeometry |
        NET::WMIcon |
        NET::WMPid |
        NET::WMMoveResize |
        NET::WMKDESystemTrayWinFor |
        NET::WMFrameExtents |
        NET::WMPing
        ,
        NET::NormalMask |
        NET::DesktopMask |
        NET::DockMask |
        NET::ToolbarMask |
        NET::MenuMask |
        NET::DialogMask |
        NET::OverrideMask |
        NET::TopMenuMask |
        NET::UtilityMask |
        NET::SplashMask |
        0
        ,
        NET::Modal |
//        NET::Sticky |  // large desktops not supported (and probably never will be)
        NET::MaxVert |
        NET::MaxHoriz |
        NET::Shaded |
        NET::SkipTaskbar |
        NET::KeepAbove |
//        NET::StaysOnTop |  the same like KeepAbove
        NET::SkipPager |
        NET::Hidden |
        NET::FullScreen |
        NET::KeepBelow |
        NET::DemandsAttention |
        0
        ,
        NET::WM2UserTime |
        NET::WM2StartupId |
        NET::WM2AllowedActions |
        NET::WM2RestackWindow |
        NET::WM2MoveResizeWindow |
        NET::WM2ExtendedStrut |
        NET::WM2KDETemporaryRules |
        NET::WM2ShowingDesktop |
        NET::WM2FullPlacement |
        NET::WM2DesktopLayout |
        0
        ,
        NET::ActionMove |
        NET::ActionResize |
        NET::ActionMinimize |
        NET::ActionShade |
//        NET::ActionStick | // Sticky state is not supported
        NET::ActionMaxVert |
        NET::ActionMaxHoriz |
        NET::ActionFullScreen |
        NET::ActionChangeDesktop |
        NET::ActionClose |
        0
        ,
        };

    rootInfo = new RootInfo( this, qt_xdisplay(), supportWindow->winId(), "KWin",
        protocols, 5, qt_xscreen() );

    loadDesktopSettings();
    updateDesktopLayout();
    // extra NETRootInfo instance in Client mode is needed to get the values of the properties
    NETRootInfo client_info( qt_xdisplay(), NET::ActiveWindow | NET::CurrentDesktop );
    int initial_desktop;
    if( !kapp->isSessionRestored())
        initial_desktop = client_info.currentDesktop();
    else
        {
        KConfigGroupSaver saver( kapp->sessionConfig(), "Session" );
        initial_desktop = kapp->sessionConfig()->readNumEntry( "desktop", 1 );
        }
    if( !setCurrentDesktop( initial_desktop ))
        setCurrentDesktop( 1 );

    // now we know how many desktops we'll, thus, we initialise the positioning object
    initPositioning = new Placement(this);

    connect(&reconfigureTimer, TQT_SIGNAL(timeout()), this,
            TQT_SLOT(slotReconfigure()));
    connect( &updateToolWindowsTimer, TQT_SIGNAL( timeout()), this, TQT_SLOT( slotUpdateToolWindows()));

    connect(kapp, TQT_SIGNAL(appearanceChanged()), this,
            TQT_SLOT(slotReconfigure()));
    connect(kapp, TQT_SIGNAL(settingsChanged(int)), this,
            TQT_SLOT(slotSettingsChanged(int)));
    connect(kapp, TQT_SIGNAL( kipcMessage( int, int )), this, TQT_SLOT( kipcMessage( int, int )));

    active_client = NULL;
    rootInfo->setActiveWindow( None );
    focusToNull();
    if( !kapp->isSessionRestored())
        ++block_focus; // because it will be set below

    char nm[ 100 ];
    sprintf( nm, "_KDE_TOPMENU_OWNER_S%d", DefaultScreen( qt_xdisplay()));
    Atom topmenu_atom = XInternAtom( qt_xdisplay(), nm, False );
    topmenu_selection = new KSelectionOwner( topmenu_atom );
    topmenu_watcher = new KSelectionWatcher( topmenu_atom );
// TODO grabXServer(); - where exactly put this? topmenu selection claiming down belong must be before

        { // begin updates blocker block
        StackingUpdatesBlocker blocker( this );

        if( options->topMenuEnabled() && topmenu_selection->claim( false ))
            setupTopMenuHandling(); // this can call updateStackingOrder()
        else
            lostTopMenuSelection();

        unsigned int i, nwins;
        Window root_return, parent_return, *wins;
        XQueryTree(qt_xdisplay(), root, &root_return, &parent_return, &wins, &nwins);
        for (i = 0; i < nwins; i++) 
            {
            XWindowAttributes attr;
            XGetWindowAttributes(qt_xdisplay(), wins[i], &attr);
            if (attr.override_redirect )
                continue;
            if( topmenu_space && topmenu_space->winId() == wins[ i ] )
                continue;
            if (attr.map_state != IsUnmapped) 
                {
                if ( addSystemTrayWin( wins[i] ) )
                    continue;
                Client* c = createClient( wins[i], true );
                if ( c != NULL && root != qt_xrootwin() ) 
                    { // TODO what is this?
                // TODO may use TQWidget:.create
                    XReparentWindow( qt_xdisplay(), c->frameId(), root, 0, 0 );
                    c->move(0,0);
                    }
                }
            }
        if ( wins )
            XFree((void *) wins);
    // propagate clients, will really happen at the end of the updates blocker block
        updateStackingOrder( true );

        updateClientArea();
        raiseElectricBorders();

    // NETWM spec says we have to set it to (0,0) if we don't support it
        NETPoint* viewports = new NETPoint[ number_of_desktops ];
        rootInfo->setDesktopViewport( number_of_desktops, *viewports );
        delete[] viewports;
        TQRect geom = TQApplication::desktop()->geometry();
        NETSize desktop_geometry;
        desktop_geometry.width = geom.width();
        desktop_geometry.height = geom.height();
        rootInfo->setDesktopGeometry( -1, desktop_geometry );
        setShowingDesktop( false );

        } // end updates blocker block

    Client* new_active_client = NULL;
    if( !kapp->isSessionRestored())
        {
        --block_focus;
        new_active_client = findClient( WindowMatchPredicate( client_info.activeWindow()));
        }
    if( new_active_client == NULL
        && activeClient() == NULL && should_get_focus.count() == 0 ) // no client activated in manage()
        {
        if( new_active_client == NULL )
            new_active_client = topClientOnDesktop( currentDesktop());
        if( new_active_client == NULL && !desktops.isEmpty() )
            new_active_client = findDesktop( true, currentDesktop());
        }
    if( new_active_client != NULL )
        activateClient( new_active_client );
    // SELI TODO this won't work with unreasonable focus policies,
    // and maybe in rare cases also if the selected client doesn't
    // want focus
    workspaceInit = false;
// TODO ungrabXServer()
    }

Workspace::~Workspace()
    {
    if (kompmgr)
        delete kompmgr;
    blockStackingUpdates( true );
// TODO    grabXServer();
    // use stacking_order, so that kwin --replace keeps stacking order
    for( ClientList::ConstIterator it = stacking_order.begin();
         it != stacking_order.end();
         ++it )
        {
	// only release the window
        (*it)->releaseWindow( true );
        // No removeClient() is called, it does more than just removing.
        // However, remove from some lists to e.g. prevent performTransiencyCheck()
        // from crashing.
        clients.remove( *it );
        desktops.remove( *it );
        }
    delete desktop_widget;
    delete tab_box;
    delete popupinfo;
    delete popup;
    if ( root == qt_xrootwin() )
        XDeleteProperty(qt_xdisplay(), qt_xrootwin(), atoms->kwin_running);

    writeWindowRules();
    KGlobal::config()->sync();

    delete rootInfo;
    delete supportWindow;
    delete mgr;
    delete[] workarea;
    delete[] screenarea;
    delete startup;
    delete initPositioning;
    delete topmenu_watcher;
    delete topmenu_selection;
    delete topmenu_space;
    delete client_keys_dialog;
    while( !rules.isEmpty())
        {
        delete rules.front();
        rules.pop_front();
        }
    XDestroyWindow( qt_xdisplay(), null_focus_window );
// TODO    ungrabXServer();
    _self = 0;
    }

Client* Workspace::createClient( Window w, bool is_mapped )
    {
    StackingUpdatesBlocker blocker( this );
    Client* c = new Client( this );
    if( !c->manage( w, is_mapped ))
        {
        Client::deleteClient( c, Allowed );
        return NULL;
        }
    addClient( c, Allowed );
    return c;
    }

void Workspace::addClient( Client* c, allowed_t )
    {
    // waited with trans settings until window figured out if active or not ;)
//     qWarning("%s", (const char*)(c->resourceClass()));
    c->setBMP(c->resourceName() == "beep-media-player" || c->decorationId() == None);
    // first check if the window has it's own opinion of it's translucency ;)
    c->getWindowOpacity();
    if (c->isDock())
        {
//         if (c->x() == 0 && c->y() == 0 && c->width() > c->height()) topDock = c;
        if (!c->hasCustomOpacity()) // this xould be done slightly more efficient, but we want to support the topDock in future
            {
            c->setShadowSize(options->dockShadowSize);
            c->setOpacity(options->translucentDocks, options->dockOpacity);
            }
        }
//------------------------------------------------        
    Group* grp = findGroup( c->window());
    if( grp != NULL )
        grp->gotLeader( c );

    if ( c->isDesktop() )
        {
        desktops.append( c );
        if( active_client == NULL && should_get_focus.isEmpty() && c->isOnCurrentDesktop())
            requestFocus( c ); // CHECKME? make sure desktop is active after startup if there's no other window active
        }
    else
        {
        updateFocusChains( c, FocusChainUpdate ); // add to focus chain if not already there
        clients.append( c );
        }
    if( !unconstrained_stacking_order.contains( c ))
        unconstrained_stacking_order.append( c );
    if( !stacking_order.contains( c )) // it'll be updated later, and updateToolWindows() requires
        stacking_order.append( c );    // c to be in stacking_order
    if( c->isTopMenu())
        addTopMenu( c );
    updateClientArea(); // this cannot be in manage(), because the client got added only now
    updateClientLayer( c );
    if( c->isDesktop())
        {
        raiseClient( c );
	// if there's no active client, make this desktop the active one
        if( activeClient() == NULL && should_get_focus.count() == 0 )
            activateClient( findDesktop( true, currentDesktop()));
        }
    c->checkActiveModal();
    checkTransients( c->window()); // SELI does this really belong here?
    updateStackingOrder( true ); // propagate new client
    if( c->isUtility() || c->isMenu() || c->isToolbar())
        updateToolWindows( true );
    checkNonExistentClients();
    }

/*
  Destroys the client \a c
 */
void Workspace::removeClient( Client* c, allowed_t )
    {
    if (c == active_popup_client)
        closeActivePopup();

    if( client_keys_client == c )
        setupWindowShortcutDone( false );
    if( !c->shortcut().isNull())
        c->setShortcut( TQString::null ); // remove from client_keys

    if( c->isDialog())
        Notify::raise( Notify::TransDelete );
    if( c->isNormalWindow())
        Notify::raise( Notify::Delete );

    Q_ASSERT( clients.contains( c ) || desktops.contains( c ));
    clients.remove( c );
    desktops.remove( c );
    unconstrained_stacking_order.remove( c );
    stacking_order.remove( c );
    for( int i = 1;
         i <= numberOfDesktops();
         ++i )
        focus_chain[ i ].remove( c );
    global_focus_chain.remove( c );
    attention_chain.remove( c );
    showing_desktop_clients.remove( c );
    if( c->isTopMenu())
        removeTopMenu( c );
    Group* group = findGroup( c->window());
    if( group != NULL )
        group->lostLeader();

    if ( c == most_recently_raised )
        most_recently_raised = 0;
    should_get_focus.remove( c );
    Q_ASSERT( c != active_client );
    if ( c == last_active_client )
        last_active_client = 0;
    if( c == pending_take_activity )
        pending_take_activity = NULL;
    if( c == delayfocus_client )
        cancelDelayFocus();

    updateStackingOrder( true );

    if (tab_grab)
       tab_box->repaint();

    updateClientArea();
    }

void Workspace::updateFocusChains( Client* c, FocusChainChange change )
    {
    if( !c->wantsTabFocus()) // doesn't want tab focus, remove
        {
        for( int i=1;
             i<= numberOfDesktops();
             ++i )
            focus_chain[i].remove(c);
        global_focus_chain.remove( c );
        return;
        }
    if(c->desktop() == NET::OnAllDesktops)
        { //now on all desktops, add it to focus_chains it is not already in
        for( int i=1; i<= numberOfDesktops(); i++)
            { // making first/last works only on current desktop, don't affect all desktops
            if( i == currentDesktop()
                && ( change == FocusChainMakeFirst || change == FocusChainMakeLast ))
                {
                focus_chain[ i ].remove( c );
                if( change == FocusChainMakeFirst )
                    focus_chain[ i ].append( c );
                else
                    focus_chain[ i ].prepend( c );
                }
            else if( !focus_chain[ i ].contains( c ))
                { // add it after the active one
                if( active_client != NULL && active_client != c
                    && !focus_chain[ i ].isEmpty() && focus_chain[ i ].last() == active_client )
                    focus_chain[ i ].insert( focus_chain[ i ].fromLast(), c );
                else
                    focus_chain[ i ].append( c ); // otherwise add as the first one
                }
            }
        }
    else    //now only on desktop, remove it anywhere else
        {
        for( int i=1; i<= numberOfDesktops(); i++)
            {
            if( i == c->desktop())
                {
                if( change == FocusChainMakeFirst )
                    {
                    focus_chain[ i ].remove( c );
                    focus_chain[ i ].append( c );
                    }
                else if( change == FocusChainMakeLast )
                    {
                    focus_chain[ i ].remove( c );
                    focus_chain[ i ].prepend( c );
                    }
                else if( !focus_chain[ i ].contains( c ))
                    {
                    if( active_client != NULL && active_client != c
                        && !focus_chain[ i ].isEmpty() && focus_chain[ i ].last() == active_client )
                        focus_chain[ i ].insert( focus_chain[ i ].fromLast(), c );
                    else
                        focus_chain[ i ].append( c ); // otherwise add as the first one
                    }
                }
            else
                focus_chain[ i ].remove( c );
            }
        }
    if( change == FocusChainMakeFirst )
        {
        global_focus_chain.remove( c );
        global_focus_chain.append( c );
        }
    else if( change == FocusChainMakeLast )
        {
        global_focus_chain.remove( c );
        global_focus_chain.prepend( c );
        }
    else if( !global_focus_chain.contains( c ))
        {
        if( active_client != NULL && active_client != c
            && !global_focus_chain.isEmpty() && global_focus_chain.last() == active_client )
            global_focus_chain.insert( global_focus_chain.fromLast(), c );
        else
            global_focus_chain.append( c ); // otherwise add as the first one
        }
    }

void Workspace::updateOverlappingShadows(unsigned long window)
    {
    Client *client;
    
    if ((client = findClient(WindowMatchPredicate((WId)window))))
        // Redraw overlapping shadows without waiting for the specified window
        // to redraw its own shadow
        client->drawOverlappingShadows(false);
    }

void Workspace::setShadowed(unsigned long window, bool shadowed)
    {
    Client *client;
    
    if ((client = findClient(WindowMatchPredicate((WId)window))))
        client->setShadowed(shadowed);
    }

void Workspace::updateCurrentTopMenu()
    {
    if( !managingTopMenus())
        return;
    // toplevel menubar handling
    Client* menubar = 0;
    bool block_desktop_menubar = false;
    if( active_client )
        {
        // show the new menu bar first...
        Client* menu_client = active_client;
        for(;;)
            {
            if( menu_client->isFullScreen())
                block_desktop_menubar = true;
            for( ClientList::ConstIterator it = menu_client->transients().begin();
                 it != menu_client->transients().end();
                 ++it )
                if( (*it)->isTopMenu())
                    {
                    menubar = *it;
                    break;
                    }
            if( menubar != NULL || !menu_client->isTransient())
                break;
            if( menu_client->isModal() || menu_client->transientFor() == NULL )
                break; // don't use mainwindow's menu if this is modal or group transient
            menu_client = menu_client->transientFor();
            }
        if( !menubar )
            { // try to find any topmenu from the application (#72113)
            for( ClientList::ConstIterator it = active_client->group()->members().begin();
                 it != active_client->group()->members().end();
                 ++it )
                if( (*it)->isTopMenu())
                    {
                    menubar = *it;
                    break;
                    }
            }
        }
    if( !menubar && !block_desktop_menubar && options->desktopTopMenu())
        {
        // Find the menubar of the desktop
        Client* desktop = findDesktop( true, currentDesktop());
        if( desktop != NULL )
            {
            for( ClientList::ConstIterator it = desktop->transients().begin();
                 it != desktop->transients().end();
                 ++it )
                if( (*it)->isTopMenu())
                    {
                    menubar = *it;
                    break;
                    }
            }
        // TODO to be cleaned app with window grouping
        // Without qt-copy patch #0009, the topmenu and desktop are not in the same group,
        // thus the topmenu is not transient for it :-/.
        if( menubar == NULL )
            {
            for( ClientList::ConstIterator it = topmenus.begin();
                 it != topmenus.end();
                 ++it )
                if( (*it)->wasOriginallyGroupTransient()) // kdesktop's topmenu has WM_TRANSIENT_FOR
                    {                                     // set pointing to the root window
                    menubar = *it;                        // to recognize it here
                    break;                                // Also, with the xroot hack in kdesktop,
                    }                                     // there's no NET::Desktop window to be transient for
            }
        }

//    kdDebug() << "CURRENT TOPMENU:" << menubar << ":" << active_client << endl;
    if ( menubar )
        {
        if( active_client && !menubar->isOnDesktop( active_client->desktop()))
            menubar->setDesktop( active_client->desktop());
        menubar->hideClient( false );
        topmenu_space->hide();
        // make it appear like it's been raised manually - it's in the Dock layer anyway,
        // and not raising it could mess up stacking order of topmenus within one application,
        // and thus break raising of mainclients in raiseClient()
        unconstrained_stacking_order.remove( menubar );
        unconstrained_stacking_order.append( menubar );
        }
    else if( !block_desktop_menubar )
        { // no topmenu active - show the space window, so that there's not empty space
        topmenu_space->show();
        }

    // ... then hide the other ones. Avoids flickers.
    for ( ClientList::ConstIterator it = clients.begin(); it != clients.end(); ++it) 
        {
        if( (*it)->isTopMenu() && (*it) != menubar )
            (*it)->hideClient( true );
        }
    }


void Workspace::updateToolWindows( bool also_hide )
    {
    // TODO what if Client's transiency/group changes? should this be called too? (I'm paranoid, am I not?)
    if( !options->hideUtilityWindowsForInactive )
        {
        for( ClientList::ConstIterator it = clients.begin();
             it != clients.end();
             ++it )
            (*it)->hideClient( false );
        return;
        }
    const Group* group = NULL;
    const Client* client = active_client;
// Go up in transiency hiearchy, if the top is found, only tool transients for the top mainwindow
// will be shown; if a group transient is group, all tools in the group will be shown
    while( client != NULL )
        {
        if( !client->isTransient())
            break;
        if( client->groupTransient())
            {
            group = client->group();
            break;
            }
        client = client->transientFor();
        }
    // use stacking order only to reduce flicker, it doesn't matter if block_stacking_updates == 0,
    // i.e. if it's not up to date

    // SELI but maybe it should - what if a new client has been added that's not in stacking order yet?
    ClientList to_show, to_hide;
    for( ClientList::ConstIterator it = stacking_order.begin();
         it != stacking_order.end();
         ++it )
        {
        if( (*it)->isUtility() || (*it)->isMenu() || (*it)->isToolbar())
            {
            bool show = true;
            if( !(*it)->isTransient())
                {
                if( (*it)->group()->members().count() == 1 ) // has its own group, keep always visible
                    show = true;
                else if( client != NULL && (*it)->group() == client->group())
                    show = true;
                else
                    show = false;
                }
            else
                {
                if( group != NULL && (*it)->group() == group )
                    show = true;
                else if( client != NULL && client->hasTransient( (*it), true ))
                    show = true;
                else
                    show = false;
                }
            if( !show && also_hide )
                {
                const ClientList mainclients = (*it)->mainClients();
                // don't hide utility windows which are standalone(?) or
                // have e.g. kicker as mainwindow
                if( mainclients.isEmpty())
                    show = true;
                for( ClientList::ConstIterator it2 = mainclients.begin();
                     it2 != mainclients.end();
                     ++it2 )
                    {
                    if( (*it2)->isSpecialWindow())
                        show = true;
                    }
                if( !show )
                    to_hide.append( *it );
                }
            if( show )
                to_show.append( *it );
            }
        } // first show new ones, then hide
    for( ClientList::ConstIterator it = to_show.fromLast();
         it != to_show.end();
         --it ) // from topmost
        // TODO since this is in stacking order, the order of taskbar entries changes :(
        (*it)->hideClient( false );
    if( also_hide )
        {
        for( ClientList::ConstIterator it = to_hide.begin();
             it != to_hide.end();
             ++it ) // from bottommost
            (*it)->hideClient( true );
        updateToolWindowsTimer.stop();
        }
    else // setActiveClient() is after called with NULL client, quickly followed
        {    // by setting a new client, which would result in flickering
        updateToolWindowsTimer.start( 50, true );
        }
    }

void Workspace::slotUpdateToolWindows()
    {
    updateToolWindows( true );
    }

/*!
  Updates the current colormap according to the currently active client
 */
void Workspace::updateColormap()
    {
    Colormap cmap = default_colormap;
    if ( activeClient() && activeClient()->colormap() != None )
        cmap = activeClient()->colormap();
    if ( cmap != installed_colormap ) 
        {
        XInstallColormap(qt_xdisplay(), cmap );
        installed_colormap = cmap;
        }
    }

void Workspace::reconfigure()
    {
    reconfigureTimer.start(200, true);
    }


void Workspace::slotSettingsChanged(int category)
    {
    kdDebug(1212) << "Workspace::slotSettingsChanged()" << endl;
    if( category == (int) KApplication::SETTINGS_SHORTCUTS )
        readShortcuts();
    }

/*!
  Reread settings
 */
KWIN_PROCEDURE( CheckBorderSizesProcedure, cl->checkBorderSizes() );

void Workspace::slotReconfigure()
    {
    kdDebug(1212) << "Workspace::slotReconfigure()" << endl;
    reconfigureTimer.stop();

    KGlobal::config()->reparseConfiguration();
    unsigned long changed = options->updateSettings();
    tab_box->reconfigure();
    popupinfo->reconfigure();
    initPositioning->reinitCascading( 0 );
    readShortcuts();
    forEachClient( CheckIgnoreFocusStealingProcedure());
    updateToolWindows( true );

    if( mgr->reset( changed ))
        { // decorations need to be recreated
#if 0 // This actually seems to make things worse now
        TQWidget curtain;
        curtain.setBackgroundMode( NoBackground );
        curtain.setGeometry( TQApplication::desktop()->geometry() );
        curtain.show();
#endif
        for( ClientList::ConstIterator it = clients.begin();
                it != clients.end();
                ++it )
            {
            (*it)->updateDecoration( true, true );
            }
        mgr->destroyPreviousPlugin();
        }
    else
        {
        forEachClient( CheckBorderSizesProcedure());
        }

    checkElectricBorders();

    if( options->topMenuEnabled() && !managingTopMenus())
        {
        if( topmenu_selection->claim( false ))
            setupTopMenuHandling();
        else
            lostTopMenuSelection();
        }
    else if( !options->topMenuEnabled() && managingTopMenus())
        {
        topmenu_selection->release();
        lostTopMenuSelection();
        }
    topmenu_height = 0; // tqinvalidate used menu height
    if( managingTopMenus())
        {
        updateTopMenuGeometry();
        updateCurrentTopMenu();
        }

    loadWindowRules();
    for( ClientList::Iterator it = clients.begin();
         it != clients.end();
         ++it )
        {
        (*it)->setupWindowRules( true );
        (*it)->applyWindowRules();
        discardUsedWindowRules( *it, false );
        }

    if (options->resetKompmgr) // need restart
        {
        bool tmp = options->useTranslucency;
        stopKompmgr();
        if (tmp)
            TQTimer::singleShot( 200, this, TQT_SLOT(startKompmgr()) ); // wait some time to ensure system's ready for restart
        }
    }

void Workspace::loadDesktopSettings()
    {
    KConfig* c = KGlobal::config();
    TQCString groupname;
    if (screen_number == 0)
        groupname = "Desktops";
    else
        groupname.sprintf("Desktops-screen-%d", screen_number);
    KConfigGroupSaver saver(c,groupname);

    int n = c->readNumEntry("Number", 4);
    number_of_desktops = n;
    delete workarea;
    workarea = new TQRect[ n + 1 ];
    delete screenarea;
    screenarea = NULL;
    rootInfo->setNumberOfDesktops( number_of_desktops );
    desktop_focus_chain.resize( n );
    // make it +1, so that it can be accessed as [1..numberofdesktops]
    focus_chain.resize( n + 1 );
    for(int i = 1; i <= n; i++) 
        {
        TQString s = c->readEntry(TQString("Name_%1").arg(i),
                                i18n("Desktop %1").arg(i));
        rootInfo->setDesktopName( i, s.utf8().data() );
        desktop_focus_chain[i-1] = i;
        }
    }

void Workspace::saveDesktopSettings()
    {
    KConfig* c = KGlobal::config();
    TQCString groupname;
    if (screen_number == 0)
        groupname = "Desktops";
    else
        groupname.sprintf("Desktops-screen-%d", screen_number);
    KConfigGroupSaver saver(c,groupname);

    c->writeEntry("Number", number_of_desktops );
    for(int i = 1; i <= number_of_desktops; i++) 
        {
        TQString s = desktopName( i );
        TQString defaultvalue = i18n("Desktop %1").arg(i);
        if ( s.isEmpty() ) 
            {
            s = defaultvalue;
            rootInfo->setDesktopName( i, s.utf8().data() );
            }

        if (s != defaultvalue) 
            {
            c->writeEntry( TQString("Name_%1").arg(i), s );
            }
        else 
            {
            TQString currentvalue = c->readEntry(TQString("Name_%1").arg(i));
            if (currentvalue != defaultvalue)
                c->writeEntry( TQString("Name_%1").arg(i), "" );
            }
        }
    }

TQStringList Workspace::configModules(bool controlCenter)
    {
    TQStringList args;
    args <<  "kde-kwindecoration.desktop";
    if (controlCenter)
        args << "kde-kwinoptions.desktop";
    else if (kapp->authorizeControlModule("kde-kwinoptions.desktop"))
        args  << "kwinactions" << "kwinfocus" <<  "kwinmoving" << "kwinadvanced" << "kwinrules" << "kwintranslucency";
    return args;
    }

void Workspace::configureWM()
    {
    KApplication::kdeinitExec( "kcmshell", configModules(false) );
    }

/*!
  avoids managing a window with title \a title
 */
void Workspace::doNotManage( TQString title )
    {
    doNotManageList.append( title );
    }

/*!
  Hack for java applets
 */
bool Workspace::isNotManaged( const TQString& title )
    {
    for ( TQStringList::Iterator it = doNotManageList.begin(); it != doNotManageList.end(); ++it ) 
        {
        TQRegExp r( (*it) );
        if (r.search(title) != -1) 
            {
            doNotManageList.remove( it );
            return TRUE;
            }
        }
    return FALSE;
    }

/*!
  Refreshes all the client windows
 */
void Workspace::refresh() 
    {
    TQWidget w;
    w.setGeometry( TQApplication::desktop()->geometry() );
    w.show();
    w.hide();
    TQApplication::flushX();
    }

/*!
  During virt. desktop switching, desktop areas covered by windows that are
  going to be hidden are first obscured by new windows with no background
  ( i.e. transparent ) placed right below the windows. These invisible windows
  are removed after the switch is complete.
  Reduces desktop ( wallpaper ) repaints during desktop switching
*/
class ObscuringWindows
    {
    public:
        ~ObscuringWindows();
        void create( Client* c );
    private:
        TQValueList<Window> obscuring_windows;
        static TQValueList<Window>* cached;
        static unsigned int max_cache_size;
    };

TQValueList<Window>* ObscuringWindows::cached = 0;
unsigned int ObscuringWindows::max_cache_size = 0;

void ObscuringWindows::create( Client* c )
    {
    if( cached == 0 )
        cached = new TQValueList<Window>;
    Window obs_win;
    XWindowChanges chngs;
    int mask = CWSibling | CWStackMode;
    if( cached->count() > 0 ) 
        {
        cached->remove( obs_win = cached->first());
        chngs.x = c->x();
        chngs.y = c->y();
        chngs.width = c->width();
        chngs.height = c->height();
        mask |= CWX | CWY | CWWidth | CWHeight;
        }
    else 
        {
        XSetWindowAttributes a;
        a.background_pixmap = None;
        a.override_redirect = True;
        obs_win = XCreateWindow( qt_xdisplay(), qt_xrootwin(), c->x(), c->y(),
            c->width(), c->height(), 0, CopyFromParent, InputOutput,
            CopyFromParent, CWBackPixmap | CWOverrideRedirect, &a );
        }
    chngs.sibling = c->frameId();
    chngs.stack_mode = Below;
    XConfigureWindow( qt_xdisplay(), obs_win, mask, &chngs );
    XMapWindow( qt_xdisplay(), obs_win );
    obscuring_windows.append( obs_win );
    }

ObscuringWindows::~ObscuringWindows()
    {
    max_cache_size = TQMAX( max_cache_size, obscuring_windows.count() + 4 ) - 1;
    for( TQValueList<Window>::ConstIterator it = obscuring_windows.begin();
         it != obscuring_windows.end();
         ++it ) 
        {
        XUnmapWindow( qt_xdisplay(), *it );
        if( cached->count() < max_cache_size )
            cached->prepend( *it );
        else
            XDestroyWindow( qt_xdisplay(), *it );
        }
    }


/*!
  Sets the current desktop to \a new_desktop

  Shows/Hides windows according to the stacking order and finally
  propages the new desktop to the world
 */
bool Workspace::setCurrentDesktop( int new_desktop )
    {
    if (new_desktop < 1 || new_desktop > number_of_desktops )
        return false;

    closeActivePopup();
    ++block_focus;
// TODO    Q_ASSERT( block_stacking_updates == 0 ); // make sure stacking_order is up to date
    StackingUpdatesBlocker blocker( this );

    int old_desktop = current_desktop;
    if (new_desktop != current_desktop) 
        {
        ++block_showing_desktop;
        /*
          optimized Desktop switching: unmapping done from back to front
          mapping done from front to back => less exposure events
        */
        Notify::raise((Notify::Event) (Notify::DesktopChange+new_desktop));

        ObscuringWindows obs_wins;

        current_desktop = new_desktop; // change the desktop (so that Client::updateVisibility() works)

        bool desktopHasCompositing = kapp->isCompositionManagerAvailable();	// Technically I should call isX11CompositionAvailable(), but it isn't initialized via my kapp constructir, and in this case it doesn't really matter anyway....
        if (!desktopHasCompositing) {
            // If composition is not in use then we can hide the old windows before showing the new ones
            for ( ClientList::ConstIterator it = stacking_order.begin(); it != stacking_order.end(); ++it) {
                if ( !(*it)->isOnDesktop( new_desktop ) && (*it) != movingClient )
                {
                    if( (*it)->isShown( true ) && (*it)->isOnDesktop( old_desktop )) {
                        obs_wins.create( *it );
                    }
                    (*it)->updateVisibility();
                }
            }
        }

        rootInfo->setCurrentDesktop( current_desktop ); // now propagate the change, after hiding, before showing

        if( movingClient && !movingClient->isOnDesktop( new_desktop ))
            movingClient->setDesktop( new_desktop );

        for ( ClientList::ConstIterator it = stacking_order.fromLast(); it != stacking_order.end(); --it) {
            if ( (*it)->isOnDesktop( new_desktop ) ) {
                (*it)->updateVisibility();
            }
        }

        if (desktopHasCompositing) {
            // If composition is in use then we cannot hide the old windows before showing the new ones, 
            // unless you happen to like the "flicker annoyingly to desktop" effect... :-P
            XSync( qt_xdisplay(), false);	// Make absolutely certain all new windows are shown before hiding the old ones
            for ( ClientList::ConstIterator it = stacking_order.begin(); it != stacking_order.end(); ++it) {
                if ( !(*it)->isOnDesktop( new_desktop ) && (*it) != movingClient )
                {
                    if( (*it)->isShown( true ) && (*it)->isOnDesktop( old_desktop )) {
                        obs_wins.create( *it );
                    }
                    (*it)->updateVisibility();
                }
            }
        }

        --block_showing_desktop;
        if( showingDesktop()) // do this only after desktop change to avoid flicker
            resetShowingDesktop( false );
        }

    // restore the focus on this desktop
    --block_focus;
    Client* c = 0;

    if ( options->focusPolicyIsReasonable()) 
        {
        // Search in focus chain
        if ( movingClient != NULL && active_client == movingClient
            && focus_chain[currentDesktop()].contains( active_client )
            && active_client->isShown( true ) && active_client->isOnCurrentDesktop())
            {
            c = active_client; // the requestFocus below will fail, as the client is already active
            }
        if ( !c ) 
            {
            for( ClientList::ConstIterator it = focus_chain[currentDesktop()].fromLast();
                 it != focus_chain[currentDesktop()].end();
                 --it )
                {
                if ( (*it)->isShown( false ) && (*it)->isOnCurrentDesktop())
                    {
                    c = *it;
                    break;
                    }
                }
            }
        }

    //if "unreasonable focus policy"
    // and active_client is on_all_desktops and under mouse (hence == old_active_client),
    // conserve focus (thanks to Volker Schatz <V.Schatz at thphys.uni-heidelberg.de>)
    else if( active_client && active_client->isShown( true ) && active_client->isOnCurrentDesktop())
      c = active_client;

    if( c == NULL && !desktops.isEmpty())
        c = findDesktop( true, currentDesktop());

    if( c != active_client )
        setActiveClient( NULL, Allowed );

    if ( c ) 
        requestFocus( c );
    else 
        focusToNull();

    updateCurrentTopMenu();

    // Update focus chain:
    //  If input: chain = { 1, 2, 3, 4 } and current_desktop = 3,
    //   Output: chain = { 3, 1, 2, 4 }.
//    kdDebug(1212) << TQString("Switching to desktop #%1, at focus_chain[currentDesktop()] index %2\n")
//      .arg(currentDesktop()).arg(desktop_focus_chain.find( currentDesktop() ));
    for( int i = desktop_focus_chain.find( currentDesktop() ); i > 0; i-- )
        desktop_focus_chain[i] = desktop_focus_chain[i-1];
    desktop_focus_chain[0] = currentDesktop();

//    TQString s = "desktop_focus_chain[] = { ";
//    for( uint i = 0; i < desktop_focus_chain.size(); i++ )
//        s += TQString::number(desktop_focus_chain[i]) + ", ";
//    kdDebug(1212) << s << "}\n";

    if( old_desktop != 0 )  // not for the very first time
        popupinfo->showInfo( desktopName(currentDesktop()) );
    return true;
    }

// called only from DCOP
void Workspace::nextDesktop()
    {
    int desktop = currentDesktop() + 1;
    setCurrentDesktop(desktop > numberOfDesktops() ? 1 : desktop);
    }

// called only from DCOP
void Workspace::previousDesktop()
    {
    int desktop = currentDesktop() - 1;
    setCurrentDesktop(desktop > 0 ? desktop : numberOfDesktops());
    }

int Workspace::desktopToRight( int desktop ) const
    {
    int x,y;
    calcDesktopLayout(x,y);
    int dt = desktop-1;
    if (layoutOrientation == Qt::Vertical)
        {
        dt += y;
        if ( dt >= numberOfDesktops() ) 
            {
            if ( options->rollOverDesktops )
              dt -= numberOfDesktops();
            else
              return desktop;
            }
        }
    else
        {
        int d = (dt % x) + 1;
        if ( d >= x ) 
            {
            if ( options->rollOverDesktops )
              d -= x;
            else
              return desktop;
            }
        dt = dt - (dt % x) + d;
        }
    return dt+1;
    }

int Workspace::desktopToLeft( int desktop ) const
    {
    int x,y;
    calcDesktopLayout(x,y);
    int dt = desktop-1;
    if (layoutOrientation == Qt::Vertical)
        {
        dt -= y;
        if ( dt < 0 ) 
            {
            if ( options->rollOverDesktops )
              dt += numberOfDesktops();
            else
              return desktop;
            }
        }
    else
        {
        int d = (dt % x) - 1;
        if ( d < 0 ) 
            {
            if ( options->rollOverDesktops )
              d += x;
            else
              return desktop;
            }
        dt = dt - (dt % x) + d;
        }
    return dt+1;
    }

int Workspace::desktopUp( int desktop ) const
    {
    int x,y;
    calcDesktopLayout(x,y);
    int dt = desktop-1;
    if (layoutOrientation == Qt::Horizontal)
        {
        dt -= x;
        if ( dt < 0 ) 
            {
            if ( options->rollOverDesktops )
              dt += numberOfDesktops();
            else
              return desktop;
            }
        }
    else
        {
        int d = (dt % y) - 1;
        if ( d < 0 ) 
            {
            if ( options->rollOverDesktops )
              d += y;
            else
              return desktop;
            }
        dt = dt - (dt % y) + d;
        }
    return dt+1;
    }

int Workspace::desktopDown( int desktop ) const
    {
    int x,y;
    calcDesktopLayout(x,y);
    int dt = desktop-1;
    if (layoutOrientation == Qt::Horizontal)
        {
        dt += x;
        if ( dt >= numberOfDesktops() ) 
            {
            if ( options->rollOverDesktops )
              dt -= numberOfDesktops();
            else
              return desktop;
            }
        }
    else
        {
        int d = (dt % y) + 1;
        if ( d >= y ) 
            {
            if ( options->rollOverDesktops )
              d -= y;
            else
              return desktop;
            }
        dt = dt - (dt % y) + d;
        }
    return dt+1;
    }


/*!
  Sets the number of virtual desktops to \a n
 */
void Workspace::setNumberOfDesktops( int n )
    {
    if ( n == number_of_desktops )
        return;
    int old_number_of_desktops = number_of_desktops;
    number_of_desktops = n;

    if( currentDesktop() > numberOfDesktops())
        setCurrentDesktop( numberOfDesktops());

    // if increasing the number, do the resizing now,
    // otherwise after the moving of windows to still existing desktops
    if( old_number_of_desktops < number_of_desktops ) 
        {
        rootInfo->setNumberOfDesktops( number_of_desktops );
        NETPoint* viewports = new NETPoint[ number_of_desktops ];
        rootInfo->setDesktopViewport( number_of_desktops, *viewports );
        delete[] viewports;
        updateClientArea( true );
        focus_chain.resize( number_of_desktops + 1 );
        }

    // if the number of desktops decreased, move all
    // windows that would be hidden to the last visible desktop
    if( old_number_of_desktops > number_of_desktops ) 
        {
        for( ClientList::ConstIterator it = clients.begin();
              it != clients.end();
              ++it) 
            {
            if( !(*it)->isOnAllDesktops() && (*it)->desktop() > numberOfDesktops())
                sendClientToDesktop( *it, numberOfDesktops(), true );
            }
        }
    if( old_number_of_desktops > number_of_desktops ) 
        {
        rootInfo->setNumberOfDesktops( number_of_desktops );
        NETPoint* viewports = new NETPoint[ number_of_desktops ];
        rootInfo->setDesktopViewport( number_of_desktops, *viewports );
        delete[] viewports;
        updateClientArea( true );
        focus_chain.resize( number_of_desktops + 1 );
        }

    saveDesktopSettings();

    // Resize and reset the desktop focus chain.
    desktop_focus_chain.resize( n );
    for( int i = 0; i < (int)desktop_focus_chain.size(); i++ )
        desktop_focus_chain[i] = i+1;
    }

/*!
  Sends client \a c to desktop \a desk.

  Takes care of transients as well.
 */
void Workspace::sendClientToDesktop( Client* c, int desk, bool dont_activate )
    {
    bool was_on_desktop = c->isOnDesktop( desk ) || c->isOnAllDesktops();
    c->setDesktop( desk );
    if ( c->desktop() != desk ) // no change or desktop forced
        return;
    desk = c->desktop(); // Client did range checking

    if ( c->isOnDesktop( currentDesktop() ) )
        {
        if ( c->wantsTabFocus() && options->focusPolicyIsReasonable()
            && !was_on_desktop // for stickyness changes
            && !dont_activate )
            requestFocus( c );
        else
            restackClientUnderActive( c );
        }
    else 
        {
        raiseClient( c );
        }

    ClientList transients_stacking_order = ensureStackingOrder( c->transients());
    for( ClientList::ConstIterator it = transients_stacking_order.begin();
         it != transients_stacking_order.end();
         ++it )
        sendClientToDesktop( *it, desk, dont_activate );
    updateClientArea();
    }

int Workspace::numScreens() const
    {
    if( !options->xineramaEnabled )
        return 0;
    return tqApp->desktop()->numScreens();
    }

int Workspace::activeScreen() const
    {
    if( !options->xineramaEnabled )
        return 0;
    if( !options->activeMouseScreen )
        {
        if( activeClient() != NULL && !activeClient()->isOnScreen( active_screen ))
            return tqApp->desktop()->screenNumber( activeClient()->geometry().center());
        return active_screen;
        }
    return tqApp->desktop()->screenNumber( TQCursor::pos());
    }

// check whether a client moved completely out of what's considered the active screen,
// if yes, set a new active screen
void Workspace::checkActiveScreen( const Client* c )
    {
    if( !options->xineramaEnabled )
        return;
    if( !c->isActive())
        return;
    if( !c->isOnScreen( active_screen ))
        active_screen = c->screen();
    }

// called e.g. when a user clicks on a window, set active screen to be the screen
// where the click occured
void Workspace::setActiveScreenMouse( TQPoint mousepos )
    {
    if( !options->xineramaEnabled )
        return;
    active_screen = tqApp->desktop()->screenNumber( mousepos );
    }

TQRect Workspace::screenGeometry( int screen ) const
    {
    if (( !options->xineramaEnabled ) || (kapp->desktop()->numScreens() < 2))
        return tqApp->desktop()->geometry();
    return tqApp->desktop()->screenGeometry( screen );
    }

int Workspace::screenNumber( TQPoint pos ) const
    {
    if( !options->xineramaEnabled )
        return 0;
    return tqApp->desktop()->screenNumber( pos );
    }

void Workspace::sendClientToScreen( Client* c, int screen )
    {
    if( c->screen() == screen ) // don't use isOnScreen(), that's true even when only partially
        return;
    GeometryUpdatesPostponer blocker( c );
    TQRect old_sarea = clientArea( MaximizeArea, c );
    TQRect sarea = clientArea( MaximizeArea, screen, c->desktop());
    c->setGeometry( sarea.x() - old_sarea.x() + c->x(), sarea.y() - old_sarea.y() + c->y(),
        c->size().width(), c->size().height());
    c->checkWorkspacePosition();
    ClientList transients_stacking_order = ensureStackingOrder( c->transients());
    for( ClientList::ConstIterator it = transients_stacking_order.begin();
         it != transients_stacking_order.end();
         ++it )
        sendClientToScreen( *it, screen );
    if( c->isActive())
        active_screen = screen;
    }


void Workspace::setDesktopLayout( int, int, int )
    { // DCOP-only, unused
    }

void Workspace::updateDesktopLayout()
    {
    // rootInfo->desktopLayoutCorner(); // I don't find this worth bothering, feel free to
    layoutOrientation = ( rootInfo->desktopLayoutOrientation() == NET::OrientationHorizontal
        ? Qt::Horizontal : Qt::Vertical );
    layoutX = rootInfo->desktopLayoutColumnsRows().width();
    layoutY = rootInfo->desktopLayoutColumnsRows().height();
    if( layoutX == 0 && layoutY == 0 ) // not given, set default layout
        layoutY = 2;
    }

void Workspace::calcDesktopLayout(int &x, int &y) const
    {
    x = layoutX; // <= 0 means compute it from the other and total number of desktops
    y = layoutY;
    if((x <= 0) && (y > 0))
       x = (numberOfDesktops()+y-1) / y;
    else if((y <=0) && (x > 0))
       y = (numberOfDesktops()+x-1) / x;

    if(x <=0)
       x = 1;
    if (y <= 0)
       y = 1;
    }

/*!
  Check whether \a w is a system tray window. If so, add it to the respective
  datastructures and propagate it to the world.
 */
bool Workspace::addSystemTrayWin( WId w )
    {
    if ( systemTrayWins.contains( w ) )
        return TRUE;

    NETWinInfo ni( qt_xdisplay(), w, root, NET::WMKDESystemTrayWinFor );
    WId trayWinFor = ni.kdeSystemTrayWinFor();
    if ( !trayWinFor )
        return FALSE;
    systemTrayWins.append( SystemTrayWindow( w, trayWinFor ) );
    XSelectInput( qt_xdisplay(), w,
                  StructureNotifyMask
                  );
    XAddToSaveSet( qt_xdisplay(), w );
    propagateSystemTrayWins();
    return TRUE;
    }

/*!
  Check whether \a w is a system tray window. If so, remove it from
  the respective datastructures and propagate this to the world.
 */
bool Workspace::removeSystemTrayWin( WId w, bool check )
    {
    if ( !systemTrayWins.contains( w ) )
        return FALSE;
    if( check )
        {
    // When getting UnmapNotify, it's not clear if it's the systray
    // reparenting the window into itself, or if it's the window
    // going away. This is obviously a flaw in the design, and we were
    // just lucky it worked for so long. Kicker's systray temporarily
    // sets _KDE_SYSTEM_TRAY_EMBEDDING property on the window while
    // embedding it, allowing KWin to figure out. Kicker just mustn't
    // crash before removing it again ... *shrug* .
        int num_props;
        Atom* props = XListProperties( qt_xdisplay(), w, &num_props );
        if( props != NULL )
            {
            for( int i = 0;
                 i < num_props;
                 ++i )
                if( props[ i ] == atoms->kde_system_tray_embedding )
                    {
                    XFree( props );
                    return false;
                    }
            XFree( props );
            }
        }
    systemTrayWins.remove( w );
    XRemoveFromSaveSet (qt_xdisplay (), w);
    propagateSystemTrayWins();
    return TRUE;
    }


/*!
  Propagates the systemTrayWins to the world
 */
void Workspace::propagateSystemTrayWins()
    {
    Window *cl = new Window[ systemTrayWins.count()];

    int i = 0;
    for ( SystemTrayWindowList::ConstIterator it = systemTrayWins.begin(); it != systemTrayWins.end(); ++it ) 
        {
        cl[i++] =  (*it).win;
        }

    rootInfo->setKDESystemTrayWindows( cl, i );
    delete [] cl;
    }


void Workspace::killWindowId( Window window_to_kill )
    {
    if( window_to_kill == None )
        return;
    Window window = window_to_kill;
    Client* client = NULL;
    for(;;) 
        {
        client = findClient( FrameIdMatchPredicate( window ));
        if( client != NULL ) // found the client
            break;
        Window parent, root;
        Window* children;
        unsigned int children_count;
        XQueryTree( qt_xdisplay(), window, &root, &parent, &children, &children_count );
        if( children != NULL )
            XFree( children );
        if( window == root ) // we didn't find the client, probably an override-redirect window
            break;
        window = parent; // go up
        }
    if( client != NULL )
        client->killWindow();
    else
        XKillClient( qt_xdisplay(), window_to_kill );
    }


void Workspace::sendPingToWindow( Window window, Time timestamp )
    {
    rootInfo->sendPing( window, timestamp );
    }

void Workspace::sendTakeActivity( Client* c, Time timestamp, long flags )
    {
    rootInfo->takeActivity( c->window(), timestamp, flags );
    pending_take_activity = c;
    }


/*!
  Takes a screenshot of the current window and puts it in the clipboard.
*/
void Workspace::slotGrabWindow()
    {
    if ( active_client ) 
        {
        TQPixmap snapshot = TQPixmap::grabWindow( active_client->frameId() );

	//No XShape - no work.
        if( Shape::available()) 
            {
	    //As the first step, get the mask from XShape.
            int count, order;
            XRectangle* rects = XShapeGetRectangles( qt_xdisplay(), active_client->frameId(),
                                                     ShapeBounding, &count, &order);
	    //The ShapeBounding region is the outermost tqshape of the window;
	    //ShapeBounding - ShapeClipping is defined to be the border.
	    //Since the border area is part of the window, we use bounding
	    // to limit our work region
            if (rects) 
                {
		//Create a TQRegion from the rectangles describing the bounding mask.
                TQRegion contents;
                for (int pos = 0; pos < count; pos++)
                    contents += TQRegion(rects[pos].x, rects[pos].y,
                                        rects[pos].width, rects[pos].height);
                XFree(rects);

		//Create the bounding box.
                TQRegion bbox(0, 0, snapshot.width(), snapshot.height());

		//Get the masked away area.
                TQRegion maskedAway = bbox - contents;
                TQMemArray<TQRect> maskedAwayRects = maskedAway.tqrects();

		//Construct a bitmap mask from the rectangles
                TQBitmap mask( snapshot.width(), snapshot.height());
                TQPainter p(&mask);
                p.fillRect(0, 0, mask.width(), mask.height(), Qt::color1);
                for (uint pos = 0; pos < maskedAwayRects.count(); pos++)
                    p.fillRect(maskedAwayRects[pos], Qt::color0);
                p.end();
                snapshot.setMask(mask);
                }
            }

        TQClipboard *cb = TQApplication::tqclipboard();
        cb->setPixmap( snapshot );
        }
    else
        slotGrabDesktop();
    }

/*!
  Takes a screenshot of the whole desktop and puts it in the clipboard.
*/
void Workspace::slotGrabDesktop()
    {
    TQPixmap p = TQPixmap::grabWindow( qt_xrootwin() );
    TQClipboard *cb = TQApplication::tqclipboard();
    cb->setPixmap( p );
    }


/*!
  Invokes keyboard mouse emulation
 */
void Workspace::slotMouseEmulation()
    {

    if ( mouse_emulation ) 
        {
        XUngrabKeyboard(qt_xdisplay(), GET_QT_X_TIME());
        mouse_emulation = FALSE;
        return;
        }

    if ( XGrabKeyboard(qt_xdisplay(),
                       root, FALSE,
                       GrabModeAsync, GrabModeAsync,
                       GET_QT_X_TIME()) == GrabSuccess ) 
        {
        mouse_emulation = TRUE;
        mouse_emulation_state = 0;
        mouse_emulation_window = 0;
        }
    }

/*!
  Returns the child window under the mouse and activates the
  respective client if necessary.

  Auxiliary function for the mouse emulation system.
 */
WId Workspace::getMouseEmulationWindow()
    {
    Window root;
    Window child = qt_xrootwin();
    int root_x, root_y, lx, ly;
    uint state;
    Window w;
    Client * c = 0;
    do 
        {
        w = child;
        if (!c)
            c = findClient( FrameIdMatchPredicate( w ));
        XQueryPointer( qt_xdisplay(), w, &root, &child,
                       &root_x, &root_y, &lx, &ly, &state );
        } while  ( child != None && child != w );

    if ( c && !c->isActive() )
        activateClient( c );
    return (WId) w;
    }

/*!
  Sends a faked mouse event to the specified window. Returns the new button state.
 */
unsigned int Workspace::sendFakedMouseEvent( TQPoint pos, WId w, MouseEmulation type, int button, unsigned int state )
    {
    if ( !w )
        return state;
    TQWidget* widget = TQWidget::find( w );
    if ( (!widget ||  widget->inherits(TQTOOLBUTTON_OBJECT_NAME_STRING) ) && !findClient( WindowMatchPredicate( w )) ) 
        {
        int x, y;
        Window xw;
        XTranslateCoordinates( qt_xdisplay(), qt_xrootwin(), w, pos.x(), pos.y(), &x, &y, &xw );
        if ( type == EmuMove ) 
            { // motion notify events
            XEvent e;
            e.type = MotionNotify;
            e.xmotion.window = w;
            e.xmotion.root = qt_xrootwin();
            e.xmotion.subwindow = w;
            e.xmotion.time = GET_QT_X_TIME();
            e.xmotion.x = x;
            e.xmotion.y = y;
            e.xmotion.x_root = pos.x();
            e.xmotion.y_root = pos.y();
            e.xmotion.state = state;
            e.xmotion.is_hint = NotifyNormal;
            XSendEvent( qt_xdisplay(), w, TRUE, ButtonMotionMask, &e );
            }
        else 
            {
            XEvent e;
            e.type = type == EmuRelease ? ButtonRelease : ButtonPress;
            e.xbutton.window = w;
            e.xbutton.root = qt_xrootwin();
            e.xbutton.subwindow = w;
            e.xbutton.time = GET_QT_X_TIME();
            e.xbutton.x = x;
            e.xbutton.y = y;
            e.xbutton.x_root = pos.x();
            e.xbutton.y_root = pos.y();
            e.xbutton.state = state;
            e.xbutton.button = button;
            XSendEvent( qt_xdisplay(), w, TRUE, ButtonPressMask, &e );

            if ( type == EmuPress ) 
                {
                switch ( button ) 
                    {
                    case 2:
                        state |= Button2Mask;
                        break;
                    case 3:
                        state |= Button3Mask;
                        break;
                    default: // 1
                        state |= Button1Mask;
                        break;
                    }
                }
            else 
                {
                switch ( button ) 
                    {
                    case 2:
                        state &= ~Button2Mask;
                        break;
                    case 3:
                        state &= ~Button3Mask;
                        break;
                    default: // 1
                        state &= ~Button1Mask;
                        break;
                    }
                }
            }
        }
    return state;
    }

/*!
  Handles keypress event during mouse emulation
 */
bool Workspace::keyPressMouseEmulation( XKeyEvent& ev )
    {
    if ( root != qt_xrootwin() )
        return FALSE;
    int kc = XKeycodeToKeysym(qt_xdisplay(), ev.keycode, 0);
    int km = ev.state & (ControlMask | Mod1Mask | ShiftMask);

    bool is_control = km & ControlMask;
    bool is_alt = km & Mod1Mask;
    bool is_shift = km & ShiftMask;
    int delta = is_control?1:is_alt?32:8;
    TQPoint pos = TQCursor::pos();

    switch ( kc ) 
        {
        case XK_Left:
        case XK_KP_Left:
            pos.rx() -= delta;
            break;
        case XK_Right:
        case XK_KP_Right:
            pos.rx() += delta;
            break;
        case XK_Up:
        case XK_KP_Up:
            pos.ry() -= delta;
            break;
        case XK_Down:
        case XK_KP_Down:
            pos.ry() += delta;
            break;
        case XK_F1:
            if ( !mouse_emulation_state )
                mouse_emulation_window = getMouseEmulationWindow();
            if ( (mouse_emulation_state & Button1Mask) == 0 )
                mouse_emulation_state = sendFakedMouseEvent( pos, mouse_emulation_window, EmuPress, Button1, mouse_emulation_state );
            if ( !is_shift )
                mouse_emulation_state = sendFakedMouseEvent( pos, mouse_emulation_window, EmuRelease, Button1, mouse_emulation_state );
            break;
        case XK_F2:
            if ( !mouse_emulation_state )
                mouse_emulation_window = getMouseEmulationWindow();
            if ( (mouse_emulation_state & Button2Mask) == 0 )
                mouse_emulation_state = sendFakedMouseEvent( pos, mouse_emulation_window, EmuPress, Button2, mouse_emulation_state );
            if ( !is_shift )
                mouse_emulation_state = sendFakedMouseEvent( pos, mouse_emulation_window, EmuRelease, Button2, mouse_emulation_state );
            break;
        case XK_F3:
            if ( !mouse_emulation_state )
                mouse_emulation_window = getMouseEmulationWindow();
            if ( (mouse_emulation_state & Button3Mask) == 0 )
                mouse_emulation_state = sendFakedMouseEvent( pos, mouse_emulation_window, EmuPress, Button3, mouse_emulation_state );
            if ( !is_shift )
                mouse_emulation_state = sendFakedMouseEvent( pos, mouse_emulation_window, EmuRelease, Button3, mouse_emulation_state );
            break;
        case XK_Return:
        case XK_space:
        case XK_KP_Enter:
        case XK_KP_Space: 
            {
            if ( !mouse_emulation_state ) 
                {
            // nothing was pressed, fake a LMB click
                mouse_emulation_window = getMouseEmulationWindow();
                mouse_emulation_state = sendFakedMouseEvent( pos, mouse_emulation_window, EmuPress, Button1, mouse_emulation_state );
                mouse_emulation_state = sendFakedMouseEvent( pos, mouse_emulation_window, EmuRelease, Button1, mouse_emulation_state );
                }
            else 
                { // release all
                if ( mouse_emulation_state & Button1Mask )
                    mouse_emulation_state = sendFakedMouseEvent( pos, mouse_emulation_window, EmuRelease, Button1, mouse_emulation_state );
                if ( mouse_emulation_state & Button2Mask )
                    mouse_emulation_state = sendFakedMouseEvent( pos, mouse_emulation_window, EmuRelease, Button2, mouse_emulation_state );
                if ( mouse_emulation_state & Button3Mask )
                    mouse_emulation_state = sendFakedMouseEvent( pos, mouse_emulation_window, EmuRelease, Button3, mouse_emulation_state );
                }
            }
    // fall through
        case XK_Escape:
            XUngrabKeyboard(qt_xdisplay(), GET_QT_X_TIME());
            mouse_emulation = FALSE;
            return TRUE;
        default:
            return FALSE;
        }

    TQCursor::setPos( pos );
    if ( mouse_emulation_state )
        mouse_emulation_state = sendFakedMouseEvent( pos, mouse_emulation_window, EmuMove, 0,  mouse_emulation_state );
    return TRUE;

    }

/*!
  Returns the workspace's desktop widget. The desktop widget is
  sometimes required by clients to draw on it, for example outlines on
  moving or resizing.
 */
TQWidget* Workspace::desktopWidget()
    {
    return desktop_widget;
    }

//Delayed focus functions
void Workspace::delayFocus()
    {
    requestFocus( delayfocus_client );
    cancelDelayFocus();
    }
    
void Workspace::requestDelayFocus( Client* c )
    {
    delayfocus_client = c;
    delete delayFocusTimer;
    delayFocusTimer = new TQTimer( this );
    connect( delayFocusTimer, TQT_SIGNAL( timeout() ), this, TQT_SLOT( delayFocus() ) );
    delayFocusTimer->start( options->delayFocusInterval, TRUE  );
    }
    
void Workspace::cancelDelayFocus()
    {
    delete delayFocusTimer;
    delayFocusTimer = 0;
    }

// Electric Borders
//========================================================================//
// Electric Border Window management. Electric borders allow a user
// to change the virtual desktop by moving the mouse pointer to the
// borders. Technically this is done with input only windows. Since
// electric borders can be switched on and off, we have these two
// functions to create and destroy them.
void Workspace::checkElectricBorders( bool force )
    {
    if( force )
        destroyBorderWindows();
    
    electric_current_border = 0;

    TQRect r = TQApplication::desktop()->geometry();
    electricTop = r.top();
    electricBottom = r.bottom();
    electricLeft = r.left();
    electricRight = r.right();

    if (options->electricBorders() == Options::ElectricAlways)
       createBorderWindows();
    else
       destroyBorderWindows();
    }

void Workspace::createBorderWindows()
    {
    if ( electric_have_borders )
        return;

    electric_have_borders = true;

    TQRect r = TQApplication::desktop()->geometry();
    XSetWindowAttributes attributes;
    unsigned long valuemask;
    attributes.override_redirect = True;
    attributes.event_mask =  ( EnterWindowMask | LeaveWindowMask );
    valuemask=  (CWOverrideRedirect | CWEventMask | CWCursor );
    attributes.cursor = XCreateFontCursor(qt_xdisplay(),
                                          XC_sb_up_arrow);
    electric_top_border = XCreateWindow (qt_xdisplay(), qt_xrootwin(),
                                0,0,
                                r.width(),1,
                                0,
                                CopyFromParent, InputOnly,
                                CopyFromParent,
                                valuemask, &attributes);
    XMapWindow(qt_xdisplay(), electric_top_border);

    attributes.cursor = XCreateFontCursor(qt_xdisplay(),
                                          XC_sb_down_arrow);
    electric_bottom_border = XCreateWindow (qt_xdisplay(), qt_xrootwin(),
                                   0,r.height()-1,
                                   r.width(),1,
                                   0,
                                   CopyFromParent, InputOnly,
                                   CopyFromParent,
                                   valuemask, &attributes);
    XMapWindow(qt_xdisplay(), electric_bottom_border);

    attributes.cursor = XCreateFontCursor(qt_xdisplay(),
                                          XC_sb_left_arrow);
    electric_left_border = XCreateWindow (qt_xdisplay(), qt_xrootwin(),
                                 0,0,
                                 1,r.height(),
                                 0,
                                 CopyFromParent, InputOnly,
                                 CopyFromParent,
                                 valuemask, &attributes);
    XMapWindow(qt_xdisplay(), electric_left_border);

    attributes.cursor = XCreateFontCursor(qt_xdisplay(),
                                          XC_sb_right_arrow);
    electric_right_border = XCreateWindow (qt_xdisplay(), qt_xrootwin(),
                                  r.width()-1,0,
                                  1,r.height(),
                                  0,
                                  CopyFromParent, InputOnly,
                                  CopyFromParent,
                                  valuemask, &attributes);
    XMapWindow(qt_xdisplay(),  electric_right_border);
    // Set XdndAware on the windows, so that DND enter events are received (#86998)
    Atom version = 4; // XDND version
    XChangeProperty( qt_xdisplay(), electric_top_border, atoms->xdnd_aware, XA_ATOM,
        32, PropModeReplace, ( unsigned char* )&version, 1 );
    XChangeProperty( qt_xdisplay(), electric_bottom_border, atoms->xdnd_aware, XA_ATOM,
        32, PropModeReplace, ( unsigned char* )&version, 1 );
    XChangeProperty( qt_xdisplay(), electric_left_border, atoms->xdnd_aware, XA_ATOM,
        32, PropModeReplace, ( unsigned char* )&version, 1 );
    XChangeProperty( qt_xdisplay(), electric_right_border, atoms->xdnd_aware, XA_ATOM,
        32, PropModeReplace, ( unsigned char* )&version, 1 );
    }


// Electric Border Window management. Electric borders allow a user
// to change the virtual desktop by moving the mouse pointer to the
// borders. Technically this is done with input only windows. Since
// electric borders can be switched on and off, we have these two
// functions to create and destroy them.
void Workspace::destroyBorderWindows()
    {
    if( !electric_have_borders)
      return;

    electric_have_borders = false;

    if(electric_top_border)
      XDestroyWindow(qt_xdisplay(),electric_top_border);
    if(electric_bottom_border)
      XDestroyWindow(qt_xdisplay(),electric_bottom_border);
    if(electric_left_border)
      XDestroyWindow(qt_xdisplay(),electric_left_border);
    if(electric_right_border)
      XDestroyWindow(qt_xdisplay(),electric_right_border);

    electric_top_border    = None;
    electric_bottom_border = None;
    electric_left_border   = None;
    electric_right_border  = None;
    }

void Workspace::clientMoved(const TQPoint &pos, Time now)
    {
    if (options->electricBorders() == Options::ElectricDisabled)
       return;

    if ((pos.x() != electricLeft) &&
        (pos.x() != electricRight) &&
        (pos.y() != electricTop) &&
        (pos.y() != electricBottom))
       return;

    Time treshold_set = options->electricBorderDelay(); // set timeout
    Time treshold_reset = 250; // reset timeout
    int distance_reset = 30; // Mouse should not move more than this many pixels

    int border = 0;
    if (pos.x() == electricLeft)
       border = 1;
    else if (pos.x() == electricRight)
       border = 2;
    else if (pos.y() == electricTop)
       border = 3;
    else if (pos.y() == electricBottom)
       border = 4;

    if ((electric_current_border == border) &&
        (timestampDiff(electric_time_last, now) < treshold_reset) &&
        ((pos-electric_push_point).manhattanLength() < distance_reset))
        {
        electric_time_last = now;

        if (timestampDiff(electric_time_first, now) > treshold_set)
            {
            electric_current_border = 0;

            TQRect r = TQApplication::desktop()->geometry();
            int offset;

            int desk_before = currentDesktop();
            switch(border)
                {
                case 1:
                 slotSwitchDesktopLeft();
                 if (currentDesktop() != desk_before) 
                    {
                    offset = r.width() / 5;
                    TQCursor::setPos(r.width() - offset, pos.y());
                    }
                break;

               case 2:
                slotSwitchDesktopRight();
                if (currentDesktop() != desk_before) 
                    {
                    offset = r.width() / 5;
                    TQCursor::setPos(offset, pos.y());
                    }
                break;

               case 3:
                slotSwitchDesktopUp();
                if (currentDesktop() != desk_before) 
                    {
                    offset = r.height() / 5;
                    TQCursor::setPos(pos.x(), r.height() - offset);
                    }
                break;

               case 4:
                slotSwitchDesktopDown();
                if (currentDesktop() != desk_before) 
                    {
                    offset = r.height() / 5;
                    TQCursor::setPos(pos.x(), offset);
                    }
                break;
                }
            return;
            }
        }
    else 
        {
        electric_current_border = border;
        electric_time_first = now;
        electric_time_last = now;
        electric_push_point = pos;
        }

    int mouse_warp = 1;

  // reset the pointer to find out wether the user is really pushing
    switch( border)
        {
        case 1: TQCursor::setPos(pos.x()+mouse_warp, pos.y()); break;
        case 2: TQCursor::setPos(pos.x()-mouse_warp, pos.y()); break;
        case 3: TQCursor::setPos(pos.x(), pos.y()+mouse_warp); break;
        case 4: TQCursor::setPos(pos.x(), pos.y()-mouse_warp); break;
        }
    }

// this function is called when the user entered an electric border
// with the mouse. It may switch to another virtual desktop
bool Workspace::electricBorder(XEvent *e)
    {
    if( !electric_have_borders )
        return false;
    if( e->type == EnterNotify )
        {
        if( e->xcrossing.window == electric_top_border ||
            e->xcrossing.window == electric_left_border ||
            e->xcrossing.window == electric_bottom_border ||
            e->xcrossing.window == electric_right_border)
            // the user entered an electric border
            {
            clientMoved( TQPoint( e->xcrossing.x_root, e->xcrossing.y_root ), e->xcrossing.time );
            return true;
            }
        }
    if( e->type == ClientMessage )
        {
        if( e->xclient.message_type == atoms->xdnd_position
            && ( e->xclient.window == electric_top_border
                 || e->xclient.window == electric_bottom_border
                 || e->xclient.window == electric_left_border
                 || e->xclient.window == electric_right_border ))
            {
            updateXTime();
            clientMoved( TQPoint( e->xclient.data.l[2]>>16, e->xclient.data.l[2]&0xffff), GET_QT_X_TIME() );
            return true;
            }
        }
    return false;
    }

// electric borders (input only windows) have to be always on the
// top. For that reason kwm calls this function always after some
// windows have been raised.
void Workspace::raiseElectricBorders()
    {

    if(electric_have_borders)
        {
        XRaiseWindow(qt_xdisplay(), electric_top_border);
        XRaiseWindow(qt_xdisplay(), electric_left_border);
        XRaiseWindow(qt_xdisplay(), electric_bottom_border);
        XRaiseWindow(qt_xdisplay(), electric_right_border);
        }
    }

void Workspace::addTopMenu( Client* c )
    {
    assert( c->isTopMenu());
    assert( !topmenus.contains( c ));
    topmenus.append( c );
    if( managingTopMenus())
        {
        int minsize = c->minSize().height();
        if( minsize > topMenuHeight())
            {
            topmenu_height = minsize;
            updateTopMenuGeometry();
            }
        updateTopMenuGeometry( c );
        updateCurrentTopMenu();
        }
//        kdDebug() << "NEW TOPMENU:" << c << endl;
    }

void Workspace::removeTopMenu( Client* c )
    {
//    if( c->isTopMenu())
//        kdDebug() << "REMOVE TOPMENU:" << c << endl;
    assert( c->isTopMenu());
    assert( topmenus.contains( c ));
    topmenus.remove( c );
    updateCurrentTopMenu();
    // TODO reduce topMenuHeight() if possible?
    }

void Workspace::lostTopMenuSelection()
    {
//    kdDebug() << "lost TopMenu selection" << endl;
    // make sure this signal is always set when not owning the selection
    disconnect( topmenu_watcher, TQT_SIGNAL( lostOwner()), this, TQT_SLOT( lostTopMenuOwner()));
    connect( topmenu_watcher, TQT_SIGNAL( lostOwner()), this, TQT_SLOT( lostTopMenuOwner()));
    if( !managing_topmenus )
        return;
    connect( topmenu_watcher, TQT_SIGNAL( lostOwner()), this, TQT_SLOT( lostTopMenuOwner()));
    disconnect( topmenu_selection, TQT_SIGNAL( lostOwnership()), this, TQT_SLOT( lostTopMenuSelection()));
    managing_topmenus = false;
    delete topmenu_space;
    topmenu_space = NULL;
    updateClientArea();
    for( ClientList::ConstIterator it = topmenus.begin();
         it != topmenus.end();
         ++it )
        (*it)->checkWorkspacePosition();
    }

void Workspace::lostTopMenuOwner()
    {
    if( !options->topMenuEnabled())
        return;
//    kdDebug() << "TopMenu selection lost owner" << endl;
    if( !topmenu_selection->claim( false ))
        {
//        kdDebug() << "Failed to claim TopMenu selection" << endl;
        return;
        }
//    kdDebug() << "claimed TopMenu selection" << endl;
    setupTopMenuHandling();
    }

void Workspace::setupTopMenuHandling()
    {
    if( managing_topmenus )
        return;
    connect( topmenu_selection, TQT_SIGNAL( lostOwnership()), this, TQT_SLOT( lostTopMenuSelection()));
    disconnect( topmenu_watcher, TQT_SIGNAL( lostOwner()), this, TQT_SLOT( lostTopMenuOwner()));
    managing_topmenus = true;
    topmenu_space = new TQWidget;
    Window stack[ 2 ];
    stack[ 0 ] = supportWindow->winId();
    stack[ 1 ] = topmenu_space->winId();
    XRestackWindows(qt_xdisplay(), stack, 2);
    updateTopMenuGeometry();
    topmenu_space->show();
    updateClientArea();
    updateCurrentTopMenu();
    }

int Workspace::topMenuHeight() const
    {
    if( topmenu_height == 0 )
        { // simply create a dummy menubar and use its preffered height as the menu height
        KMenuBar tmpmenu;
        tmpmenu.insertItem( "dummy" );
        topmenu_height = tmpmenu.tqsizeHint().height();
        }
    return topmenu_height;
    }

KDecoration* Workspace::createDecoration( KDecorationBridge* bridge )
    {
    return mgr->createDecoration( bridge );
    }

TQString Workspace::desktopName( int desk ) const
    {
    return TQString::fromUtf8( rootInfo->desktopName( desk ) );
    }

bool Workspace::checkStartupNotification( Window w, KStartupInfoId& id, KStartupInfoData& data )
    {
    return startup->checkStartup( w, id, data ) == KStartupInfo::Match;
    }

/*!
  Puts the focus on a dummy window
  Just using XSetInputFocus() with None would block keyboard input
 */
void Workspace::focusToNull()
    {
    XSetInputFocus(qt_xdisplay(), null_focus_window, RevertToPointerRoot, GET_QT_X_TIME() );
    }

void Workspace::helperDialog( const TQString& message, const Client* c )
    {
    TQStringList args;
    TQString type;
    if( message == "noborderaltf3" )
        {
        TQString shortcut = TQString( "%1 (%2)" ).arg( keys->label( "Window Operations Menu" ))
            .arg( keys->shortcut( "Window Operations Menu" ).seq( 0 ).toString());
        args << "--msgbox" <<
              i18n( "You have selected to show a window without its border.\n"
                    "Without the border, you will not be able to enable the border "
                    "again using the mouse: use the window operations menu instead, "
                    "activated using the %1 keyboard shortcut." )
                .arg( shortcut );
        type = "altf3warning";
        }
    else if( message == "fullscreenaltf3" )
        {
        TQString shortcut = TQString( "%1 (%2)" ).arg( keys->label( "Window Operations Menu" ))
            .arg( keys->shortcut( "Window Operations Menu" ).seq( 0 ).toString());
        args << "--msgbox" <<
              i18n( "You have selected to show a window in fullscreen mode.\n"
                    "If the application itself does not have an option to turn the fullscreen "
                    "mode off you will not be able to disable it "
                    "again using the mouse: use the window operations menu instead, "
                    "activated using the %1 keyboard shortcut." )
                .arg( shortcut );
        type = "altf3warning";
        }
    else
        assert( false );
    KProcess proc;
    proc << "kdialog" << args;
    if( !type.isEmpty())
        {
        KConfig cfg( "kwin_dialogsrc" );
        cfg.setGroup( "Notification Messages" ); // this depends on KMessageBox
        if( !cfg.readBoolEntry( type, true )) // has don't show again checked
            return;                           // save launching kdialog
        proc << "--dontagain" << "kwin_dialogsrc:" + type;
        }
    if( c != NULL )
        proc << "--embed" << TQString::number( c->window());
    proc.start( KProcess::DontCare );
    }


// kompmgr stuff

void Workspace::startKompmgr()
{
    // See if the desktop is loaded yet
    Atom type;
    int format;
    unsigned long length, after;
    unsigned char* data_root;
    Atom prop_root;
    prop_root = XInternAtom(qt_xdisplay(), "_XROOTPMAP_ID", False);
    if( XGetWindowProperty( qt_xdisplay(), qt_xrootwin(), prop_root, 0L, 1L, False, AnyPropertyType, &type, &format, &length, &after, &data_root) == Success && data_root != NULL ) {
        // Root pixmap is available; OK to load...
    }
    else {
        // Try again a bit later!
        TQTimer::singleShot( 200, this, TQT_SLOT(startKompmgr()) );
        return;
    }
    if (!kompmgr || kompmgr->isRunning())
        return;
    if (!kompmgr->start(KProcess::OwnGroup, KProcess::Stderr))
    {
        options->useTranslucency = FALSE;
        KProcess proc;
        proc << "kdialog" << "--error"
            << i18n("The Composite Manager could not be started.\\nMake sure you have \"kompmgr\" in a $PATH directory.")
            << "--title" << "Composite Manager Failure";
        proc.start(KProcess::DontCare);
    }
    else
    {
        delete kompmgr_selection;
        char selection_name[ 100 ];
        sprintf( selection_name, "_NET_WM_CM_S%d", DefaultScreen( qt_xdisplay()));
        kompmgr_selection = new KSelectionOwner( selection_name );
        connect( kompmgr_selection, TQT_SIGNAL( lostOwnership()), TQT_SLOT( stopKompmgr()));
        kompmgr_selection->claim( true );
        connect(kompmgr, TQT_SIGNAL(processExited(KProcess*)), TQT_SLOT(restartKompmgr(KProcess*)));
        options->useTranslucency = TRUE;
        //allowKompmgrRestart = FALSE;
        //TQTimer::singleShot( 60000, this, TQT_SLOT(unblockKompmgrRestart()) );
        TQByteArray ba;
        TQDataStream arg(ba, IO_WriteOnly);
        arg << "";
        kapp->dcopClient()->emitDCOPSignal("default", "kompmgrStarted()", ba);
    }
    if (popup){ delete popup; popup = 0L; } // to add/remove opacity slider
}

void Workspace::stopKompmgr()
{
    if (!kompmgr  || !kompmgr->isRunning())
        return;
    delete kompmgr_selection;
    kompmgr_selection = NULL;
    kompmgr->disconnect(this, TQT_SLOT(restartKompmgr()));
    options->useTranslucency = FALSE;
    if (popup){ delete popup; popup = 0L; } // to add/remove opacity slider
    kompmgr->kill();
    TQByteArray ba;
    TQDataStream arg(ba, IO_WriteOnly);
    arg << "";
    kapp->dcopClient()->emitDCOPSignal("default", "kompmgrStopped()", ba);
}

bool Workspace::kompmgrIsRunning()
{
   return kompmgr && kompmgr->isRunning();
}

void Workspace::unblockKompmgrRestart()
{
    allowKompmgrRestart = TRUE;
}

void Workspace::restartKompmgr( KProcess *proc )
// this is for inernal purpose (crashhandling) only, usually you want to use workspace->stopKompmgr(); TQTimer::singleShot(200, workspace, TQT_SLOT(startKompmgr()));
{
    if (proc->signalled()) {	// looks like kompmgr may have crashed
      int exit_signal_number = proc->exitSignal();
      if ( (exit_signal_number == SIGILL) || (exit_signal_number == SIGTRAP) || (exit_signal_number == SIGABRT) || (exit_signal_number == SIGSYS) || (exit_signal_number == SIGFPE) || (exit_signal_number == SIGBUS) || (exit_signal_number == SIGSEGV) ) {
        if (!allowKompmgrRestart)   // uh oh, it crashed recently already
        {
            delete kompmgr_selection;
            kompmgr_selection = NULL;
            options->useTranslucency = FALSE;
            KProcess proc;
            proc << "kdialog" << "--error"
                << i18n( "The Composite Manager crashed twice within a minute and is therefore disabled for this session.")
                << "--title" << i18n("Composite Manager Failure");
            proc.start(KProcess::DontCare);
            return;
        }
      }
      if (!kompmgr)
            return;
// this should be useless, i keep it for maybe future need
//         if (!kcompmgr)
//             {
//             kompmgr = new KProcess;
//             kompmgr->clearArguments();
//             *kompmgr << "kompmgr";
//             }
// -------------------
        if (!kompmgr->start(KProcess::NotifyOnExit, KProcess::Stderr))
        {
            delete kompmgr_selection;
            kompmgr_selection = NULL;
            options->useTranslucency = FALSE;
            KProcess proc;
            proc << "kdialog" << "--error"
                << i18n("The Composite Manager could not be started.\\nMake sure you have \"kompmgr\" in a $PATH directory.")
                << "--title" << i18n("Composite Manager Failure");
            proc.start(KProcess::DontCare);
        }
        else
        {
            allowKompmgrRestart = FALSE;
            TQTimer::singleShot( 60000, this, TQT_SLOT(unblockKompmgrRestart()) );
        }
    }
}

void Workspace::handleKompmgrOutput( KProcess* , char *buffer, int buflen)
{
    TQString message;
    TQString output = TQString::fromLocal8Bit( buffer, buflen );
    if (output.contains("Started",false))
        ; // don't do anything, just pass to the connection release
    else if (output.contains("Can't open display",false))
        message = i18n("<qt><b>kompmgr failed to open the display</b><br>There is probably an invalid display entry in your ~/.xcompmgrrc.</qt>");
    else if (output.contains("No render extension",false))
        message = i18n("<qt><b>kompmgr cannot find the Xrender extension</b><br>You are using either an outdated or a crippled version of XOrg.<br>Get XOrg &ge; 6.8 from www.freedesktop.org.<br></qt>");
    else if (output.contains("No composite extension",false))
        message = i18n("<qt><b>Composite extension not found</b><br>You <i>must</i> use XOrg &ge; 6.8 for translucency and shadows to work.<br>Additionally, you need to add a new section to your X config file:<br>"
        "<i>Section \"Extensions\"<br>"
        "Option \"Composite\" \"Enable\"<br>"
        "EndSection</i></qt>");
    else if (output.contains("No damage extension",false))
        message = i18n("<qt><b>Damage extension not found</b><br>You <i>must</i> use XOrg &ge; 6.8 for translucency and shadows to work.</qt>");
    else if (output.contains("No XFixes extension",false))
        message = i18n("<qt><b>XFixes extension not found</b><br>You <i>must</i> use XOrg &ge; 6.8 for translucency and shadows to work.</qt>");
    else return; //skip others
    // kompmgr startup failed or succeeded, release connection
    kompmgr->closeStderr();
    disconnect(kompmgr, TQT_SIGNAL(receivedStderr(KProcess*, char*, int)), this, TQT_SLOT(handleKompmgrOutput(KProcess*, char*, int)));
    if( !message.isEmpty())
        {
        KProcess proc;
        proc << "kdialog" << "--error"
            << message
            << "--title" << i18n("Composite Manager Failure");
        proc.start(KProcess::DontCare);
        }
}
    
        
void Workspace::setOpacity(unsigned long winId, unsigned int opacityPercent)
{
    if (opacityPercent > 100) opacityPercent = 100;
    for( ClientList::ConstIterator it = stackingOrder().begin(); it != stackingOrder().end(); it++ )
        if (winId == (*it)->window())
            {
            (*it)->setOpacity(opacityPercent < 100, (unsigned int)((opacityPercent/100.0)*0xFFFFFFFF));
            return;
            }
}

void Workspace::setShadowSize(unsigned long winId, unsigned int shadowSizePercent)
{
    //this is open to the user by dcop - to avoid stupid trials, we limit the max shadow size to 400%
    if (shadowSizePercent > 400) shadowSizePercent = 400;
    for( ClientList::ConstIterator it = stackingOrder().begin(); it != stackingOrder().end(); it++ )
        if (winId == (*it)->window())
            {
            (*it)->setShadowSize(shadowSizePercent);
            return;
            }
}

void Workspace::setUnshadowed(unsigned long winId)
{
    for( ClientList::ConstIterator it = stackingOrder().begin(); it != stackingOrder().end(); it++ )
        if (winId == (*it)->window())
            {
            (*it)->setShadowSize(0);
            return;
            }
}

void Workspace::setShowingDesktop( bool showing )
    {
    rootInfo->setShowingDesktop( showing );
    showing_desktop = showing;
    ++block_showing_desktop;
    if( showing_desktop )
        {
        showing_desktop_clients.clear();
        ++block_focus;
        ClientList cls = stackingOrder();
        // find them first, then minimize, otherwise transients may get minimized with the window
        // they're transient for
        for( ClientList::ConstIterator it = cls.begin();
             it != cls.end();
             ++it )
            {
            if( (*it)->isOnCurrentDesktop() && (*it)->isShown( true ) && !(*it)->isSpecialWindow())
                showing_desktop_clients.prepend( *it ); // topmost first to reduce flicker
            }
        for( ClientList::ConstIterator it = showing_desktop_clients.begin();
             it != showing_desktop_clients.end();
             ++it )
            (*it)->minimize(true);
        --block_focus;
        if( Client* desk = findDesktop( true, currentDesktop()))
            requestFocus( desk );
        }
    else
        {
        for( ClientList::ConstIterator it = showing_desktop_clients.begin();
             it != showing_desktop_clients.end();
             ++it )
            (*it)->unminimize(true);
        if( showing_desktop_clients.count() > 0 )
            requestFocus( showing_desktop_clients.first());
        showing_desktop_clients.clear();
        }
    --block_showing_desktop;
    }

// Following Kicker's behavior:
// Changing a virtual desktop resets the state and shows the windows again.
// Unminimizing a window resets the state but keeps the windows hidden (except
// the one that was unminimized).
// A new window resets the state and shows the windows again, with the new window
// being active. Due to popular demand (#67406) by people who apparently
// don't see a difference between "show desktop" and "minimize all", this is not
// true if "showDesktopIsMinimizeAll" is set in kwinrc. In such case showing
// a new window resets the state but doesn't show windows.
void Workspace::resetShowingDesktop( bool keep_hidden )
    {
    if( block_showing_desktop > 0 )
        return;
    rootInfo->setShowingDesktop( false );
    showing_desktop = false;
    ++block_showing_desktop;
    if( !keep_hidden )
        {
        for( ClientList::ConstIterator it = showing_desktop_clients.begin();
             it != showing_desktop_clients.end();
             ++it )
            (*it)->unminimize(true);
        }
    showing_desktop_clients.clear();
    --block_showing_desktop;
    }

// Activating/deactivating this feature works like this:
// When nothing is active, and the shortcut is pressed, global shortcuts are disabled
//   (using global_shortcuts_disabled)
// When a window that has disabling forced is activated, global shortcuts are disabled.
//   (using global_shortcuts_disabled_for_client)
// When a shortcut is pressed and global shortcuts are disabled (either by a shortcut
// or for a client), they are enabled again.
void Workspace::slotDisableGlobalShortcuts()
    {
    if( global_shortcuts_disabled || global_shortcuts_disabled_for_client )
        disableGlobalShortcuts( false );
    else
        disableGlobalShortcuts( true );
    }

static bool pending_dfc = false;

void Workspace::disableGlobalShortcutsForClient( bool disable )
    {
    if( global_shortcuts_disabled_for_client == disable )
        return;
    if( !global_shortcuts_disabled )
        {
        if( disable )
            pending_dfc = true;
        KIPC::sendMessageAll( KIPC::BlockShortcuts, disable );
        // kwin will get the kipc message too
        }
    }

void Workspace::disableGlobalShortcuts( bool disable )
    {
    KIPC::sendMessageAll( KIPC::BlockShortcuts, disable );
    // kwin will get the kipc message too
    }

void Workspace::kipcMessage( int id, int data )
    {
    if( id != KIPC::BlockShortcuts )
        return;
    if( pending_dfc && data )
        {
        global_shortcuts_disabled_for_client = true;
        pending_dfc = false;
        }
    else
        {
        global_shortcuts_disabled = data;
        global_shortcuts_disabled_for_client = false;
        }
    // update also Alt+LMB actions etc.
    for( ClientList::ConstIterator it = clients.begin();
         it != clients.end();
         ++it )
        (*it)->updateMouseGrab();
    }

} // namespace

#include "workspace.moc"