summaryrefslogtreecommitdiffstats
path: root/tdeio/tdefile/kpropertiesdialog.cpp
blob: cab15872c578e657a1294f9b8bc63e9d5dfac2e3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
/* This file is part of the KDE project

   Copyright (C) 1998, 1999 Torben Weis <[email protected]>
   Copyright (c) 1999, 2000 Preston Brown <[email protected]>
   Copyright (c) 2000 Simon Hausmann <[email protected]>
   Copyright (c) 2000 David Faure <[email protected]>
   Copyright (c) 2003 Waldo Bastian <[email protected]>

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

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

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/

/*
 * kpropertiesdialog.cpp
 * View/Edit Properties of files, locally or remotely
 *
 * some FilePermissionsPropsPlugin-changes by
 *  Henner Zeller <[email protected]>
 * some layout management by
 *  Bertrand Leconte <[email protected]>
 * the rest of the layout management, bug fixes, adaptation to libtdeio,
 * template feature by
 *  David Faure <[email protected]>
 * More layout, cleanups, and fixes by
 *  Preston Brown <[email protected]>
 * Plugin capability, cleanups and port to KDialogBase by
 *  Simon Hausmann <[email protected]>
 * KDesktopPropsPlugin by
 *  Waldo Bastian <[email protected]>
 */

#include <config.h>
extern "C" {
#include <pwd.h>
#include <grp.h>
#include <time.h>
#include <sys/types.h>
}
#include <unistd.h>
#include <errno.h>
#include <assert.h>
#include <algorithm>
#include <functional>

#include <tqfile.h>
#include <tqdir.h>
#include <tqlabel.h>
#include <tqpushbutton.h>
#include <tqcheckbox.h>
#include <tqstrlist.h>
#include <tqstringlist.h>
#include <tqtextstream.h>
#include <tqpainter.h>
#include <tqlayout.h>
#include <tqcombobox.h>
#include <tqgroupbox.h>
#include <tqwhatsthis.h>
#include <tqtooltip.h>
#include <tqstyle.h>
#include <tqprogressbar.h>
#include <tqvbox.h>
#include <tqvaluevector.h>

#ifdef USE_POSIX_ACL
extern "C" {
#include <sys/param.h>
#ifdef HAVE_SYS_MOUNT_H
#include <sys/mount.h>
#endif
#ifdef HAVE_SYS_XATTR_H
#include <sys/xattr.h>
#endif
}
#endif

#include <tdeapplication.h>
#include <kdialog.h>
#include <kdirsize.h>
#include <kdirwatch.h>
#include <kdirnotify_stub.h>
#include <kdiskfreesp.h>
#include <kdebug.h>
#include <kdesktopfile.h>
#include <kicondialog.h>
#include <kurl.h>
#include <kurlrequester.h>
#include <tdelocale.h>
#include <tdeglobal.h>
#include <tdeglobalsettings.h>
#include <kstandarddirs.h>
#include <tdeio/job.h>
#include <tdeio/chmodjob.h>
#include <tdeio/renamedlg.h>
#include <tdeio/netaccess.h>
#include <tdeio/kservicetypefactory.h>
#include <tdefiledialog.h>
#include <kmimetype.h>
#include <kmountpoint.h>
#include <kiconloader.h>
#include <tdemessagebox.h>
#include <kservice.h>
#include <kcompletion.h>
#include <klineedit.h>
#include <kseparator.h>
#include <ksqueezedtextlabel.h>
#include <klibloader.h>
#include <ktrader.h>
#include <tdeparts/componentfactory.h>
#include <kmetaprops.h>
#include <kpreviewprops.h>
#include <kprocess.h>
#include <krun.h>
#include <tdelistview.h>
#include <kacl.h>
#include "tdefilesharedlg.h"

#include "kpropertiesdesktopbase.h"
#include "kpropertiesdesktopadvbase.h"
#include "kpropertiesmimetypebase.h"
#ifdef USE_POSIX_ACL
#include "kacleditwidget.h"
#endif

#include "kpropertiesdialog.h"

#ifdef Q_WS_WIN
# include <win32_utils.h>
#endif

static TQString nameFromFileName(TQString nameStr)
{
   if ( nameStr.endsWith(".desktop") )
      nameStr.truncate( nameStr.length() - 8 );
   if ( nameStr.endsWith(".kdelnk") )
      nameStr.truncate( nameStr.length() - 7 );
   // Make it human-readable (%2F => '/', ...)
   nameStr = TDEIO::decodeFileName( nameStr );
   return nameStr;
}

mode_t KFilePermissionsPropsPlugin::fperm[3][4] = {
        {S_IRUSR, S_IWUSR, S_IXUSR, S_ISUID},
        {S_IRGRP, S_IWGRP, S_IXGRP, S_ISGID},
        {S_IROTH, S_IWOTH, S_IXOTH, S_ISVTX}
    };

class KPropertiesDialog::KPropertiesDialogPrivate
{
public:
  KPropertiesDialogPrivate()
  {
    m_aborted = false;
    fileSharePage = 0;
  }
  ~KPropertiesDialogPrivate()
  {
  }
  bool m_aborted:1;
  TQWidget* fileSharePage;
};

KPropertiesDialog::KPropertiesDialog (KFileItem* item,
                                      TQWidget* parent, const char* name,
                                      bool modal, bool autoShow)
  : KDialogBase (KDialogBase::Tabbed, i18n( "Properties for %1" ).arg(TDEIO::decodeFileName(item->url().fileName())),
                 KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok,
                 parent, name, modal)
{
  d = new KPropertiesDialogPrivate;
  assert( item );
  m_items.append( new KFileItem(*item) ); // deep copy

  m_singleUrl = item->url();
  assert(!m_singleUrl.isEmpty());

  init (modal, autoShow);
}

KPropertiesDialog::KPropertiesDialog (const TQString& title,
                                      TQWidget* parent, const char* name, bool modal)
  : KDialogBase (KDialogBase::Tabbed, i18n ("Properties for %1").arg(title),
                 KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok,
                 parent, name, modal)
{
  d = new KPropertiesDialogPrivate;

  init (modal, false);
}

KPropertiesDialog::KPropertiesDialog (KFileItemList _items,
                                      TQWidget* parent, const char* name,
                                      bool modal, bool autoShow)
  : KDialogBase (KDialogBase::Tabbed,
                 // TODO: replace <never used> with "Properties for 1 item". It's very confusing how it has to be translated otherwise
                 // (empty translation before the "\n" is not allowed by msgfmt...)
		 _items.count()>1 ? i18n( "<never used>","Properties for %n Selected Items",_items.count()) :
		 i18n( "Properties for %1" ).arg(TDEIO::decodeFileName(_items.first()->url().fileName())),
                 KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok,
                 parent, name, modal)
{
  d = new KPropertiesDialogPrivate;

  assert( !_items.isEmpty() );
  m_singleUrl = _items.first()->url();
  assert(!m_singleUrl.isEmpty());

  KFileItemListIterator it ( _items );
  // Deep copy
  for ( ; it.current(); ++it )
      m_items.append( new KFileItem( **it ) );

  init (modal, autoShow);
}

#ifndef KDE_NO_COMPAT
KPropertiesDialog::KPropertiesDialog (const KURL& _url, mode_t /* _mode is now unused */,
                                      TQWidget* parent, const char* name,
                                      bool modal, bool autoShow)
  : KDialogBase (KDialogBase::Tabbed,
		 i18n( "Properties for %1" ).arg(TDEIO::decodeFileName(_url.fileName())),
                 KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok,
                 parent, name, modal),
  m_singleUrl( _url )
{
  d = new KPropertiesDialogPrivate;

  TDEIO::UDSEntry entry;

  TDEIO::NetAccess::stat(_url, entry, parent);

  m_items.append( new KFileItem( entry, _url ) );
  init (modal, autoShow);
}
#endif

KPropertiesDialog::KPropertiesDialog (const KURL& _url,
                                      TQWidget* parent, const char* name,
                                      bool modal, bool autoShow)
  : KDialogBase (KDialogBase::Tabbed,
		 i18n( "Properties for %1" ).arg(TDEIO::decodeFileName(_url.fileName())),
                 KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok,
                 parent, name, modal),
  m_singleUrl( _url )
{
  d = new KPropertiesDialogPrivate;

  TDEIO::UDSEntry entry;

  TDEIO::NetAccess::stat(_url, entry, parent);

  m_items.append( new KFileItem( entry, _url ) );
  init (modal, autoShow);
}

KPropertiesDialog::KPropertiesDialog (const KURL& _tempUrl, const KURL& _currentDir,
                                      const TQString& _defaultName,
                                      TQWidget* parent, const char* name,
                                      bool modal, bool autoShow)
  : KDialogBase (KDialogBase::Tabbed,
		 i18n( "Properties for %1" ).arg(TDEIO::decodeFileName(_tempUrl.fileName())),
                 KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok,
                 parent, name, modal),

  m_singleUrl( _tempUrl ),
  m_defaultName( _defaultName ),
  m_currentDir( _currentDir )
{
  d = new KPropertiesDialogPrivate;

  assert(!m_singleUrl.isEmpty());

  // Create the KFileItem for the _template_ file, in order to read from it.
  m_items.append( new KFileItem( KFileItem::Unknown, KFileItem::Unknown, m_singleUrl ) );
  init (modal, autoShow);
}

bool KPropertiesDialog::showDialog(KFileItem* item, TQWidget* parent,
                                   const char* name, bool modal)
{
#ifdef Q_WS_WIN
  TQString localPath = item->localPath();
  if (!localPath.isEmpty())
    return showWin32FilePropertyDialog(localPath);
#endif
  new KPropertiesDialog(item, parent, name, modal);
  return true;
}

bool KPropertiesDialog::showDialog(const KURL& _url, TQWidget* parent,
                                   const char* name, bool modal)
{
#ifdef Q_WS_WIN
  if (_url.isLocalFile())
    return showWin32FilePropertyDialog( _url.path() );
#endif
  new KPropertiesDialog(_url, parent, name, modal);
  return true;
}

bool KPropertiesDialog::showDialog(const KFileItemList& _items, TQWidget* parent,
                                   const char* name, bool modal)
{
  if (_items.count()==1)
    return KPropertiesDialog::showDialog(_items.getFirst(), parent, name, modal);
  new KPropertiesDialog(_items, parent, name, modal);
  return true;
}

void KPropertiesDialog::init (bool modal, bool autoShow)
{
  m_pageList.setAutoDelete( true );
  m_items.setAutoDelete( true );

  insertPages();

  if (autoShow)
    {
      if (!modal)
        show();
      else
        exec();
    }
}

void KPropertiesDialog::showFileSharingPage()
{
  if (d->fileSharePage) {
     showPage( pageIndex( d->fileSharePage));
  }
}

void KPropertiesDialog::setFileSharingPage(TQWidget* page) {
  d->fileSharePage = page;
}


void KPropertiesDialog::setFileNameReadOnly( bool ro )
{
    KPropsDlgPlugin *it;

    for ( it=m_pageList.first(); it != 0L; it=m_pageList.next() )
    {
        KFilePropsPlugin* plugin = dynamic_cast<KFilePropsPlugin*>(it);
        if ( plugin ) {
            plugin->setFileNameReadOnly( ro );
            break;
        }
    }
}

void KPropertiesDialog::slotStatResult( TDEIO::Job * )
{
}

KPropertiesDialog::~KPropertiesDialog()
{
  m_pageList.clear();
  delete d;
}

void KPropertiesDialog::insertPlugin (KPropsDlgPlugin* plugin)
{
  connect (plugin, TQT_SIGNAL (changed ()),
           plugin, TQT_SLOT (setDirty ()));

  m_pageList.append (plugin);
}

bool KPropertiesDialog::canDisplay( KFileItemList _items )
{
  // TODO: cache the result of those calls. Currently we parse .desktop files far too many times
  return KFilePropsPlugin::supports( _items ) ||
         KFilePermissionsPropsPlugin::supports( _items ) ||
         KDesktopPropsPlugin::supports( _items ) ||
         KBindingPropsPlugin::supports( _items ) ||
         KURLPropsPlugin::supports( _items ) ||
         KDevicePropsPlugin::supports( _items ) ||
         KFileMetaPropsPlugin::supports( _items ) ||
         KPreviewPropsPlugin::supports( _items );
}

void KPropertiesDialog::slotOk()
{
  KPropsDlgPlugin *page;
  d->m_aborted = false;

  KFilePropsPlugin * filePropsPlugin = 0L;
  if ( m_pageList.first()->isA("KFilePropsPlugin") )
    filePropsPlugin = static_cast<KFilePropsPlugin *>(m_pageList.first());

  // If any page is dirty, then set the main one (KFilePropsPlugin) as
  // dirty too. This is what makes it possible to save changes to a global
  // desktop file into a local one. In other cases, it doesn't hurt.
  for ( page = m_pageList.first(); page != 0L; page = m_pageList.next() )
    if ( page->isDirty() && filePropsPlugin )
    {
        filePropsPlugin->setDirty();
        break;
    }

  // Apply the changes in the _normal_ order of the tabs now
  // This is because in case of renaming a file, KFilePropsPlugin will call
  // KPropertiesDialog::rename, so other tab will be ok with whatever order
  // BUT for file copied from templates, we need to do the renaming first !
  for ( page = m_pageList.first(); page != 0L && !d->m_aborted; page = m_pageList.next() )
    if ( page->isDirty() )
    {
      kdDebug( 250 ) << "applying changes for " << page->className() << endl;
      page->applyChanges();
      // applyChanges may change d->m_aborted.
    }
    else
      kdDebug( 250 ) << "skipping page " << page->className() << endl;

  if ( !d->m_aborted && filePropsPlugin )
    filePropsPlugin->postApplyChanges();

  if ( !d->m_aborted )
  {
    emit applied();
    emit propertiesClosed();
    deleteLater();
    accept();
  } // else, keep dialog open for user to fix the problem.
}

void KPropertiesDialog::slotCancel()
{
  emit canceled();
  emit propertiesClosed();

  deleteLater();
  done( Rejected );
}

void KPropertiesDialog::insertPages()
{
  if (m_items.isEmpty())
    return;

  if ( KFilePropsPlugin::supports( m_items ) )
  {
    KPropsDlgPlugin *p = new KFilePropsPlugin( this );
    insertPlugin (p);
  }

  if ( KFilePermissionsPropsPlugin::supports( m_items ) )
  {
    KPropsDlgPlugin *p = new KFilePermissionsPropsPlugin( this );
    insertPlugin (p);
  }

  if ( KDesktopPropsPlugin::supports( m_items ) )
  {
    KPropsDlgPlugin *p = new KDesktopPropsPlugin( this );
    insertPlugin (p);
  }

  if ( KBindingPropsPlugin::supports( m_items ) )
  {
    KPropsDlgPlugin *p = new KBindingPropsPlugin( this );
    insertPlugin (p);
  }

  if ( KURLPropsPlugin::supports( m_items ) )
  {
    KPropsDlgPlugin *p = new KURLPropsPlugin( this );
    insertPlugin (p);
  }

  if ( KDevicePropsPlugin::supports( m_items ) )
  {
    KPropsDlgPlugin *p = new KDevicePropsPlugin( this );
    insertPlugin (p);
  }

  if ( KFileMetaPropsPlugin::supports( m_items ) )
  {
    KPropsDlgPlugin *p = new KFileMetaPropsPlugin( this );
    insertPlugin (p);
  }

  if ( KPreviewPropsPlugin::supports( m_items ) )
  {
    KPropsDlgPlugin *p = new KPreviewPropsPlugin( this );
    insertPlugin (p);
  }

  if ( kapp->authorizeTDEAction("sharefile") &&
       KFileSharePropsPlugin::supports( m_items ) )
  {
    KPropsDlgPlugin *p = new KFileSharePropsPlugin( this );
    insertPlugin (p);
  }

  //plugins

  if ( m_items.count() != 1 )
    return;

  KFileItem *item = m_items.first();
  TQString mimetype = item->mimetype();

  if ( mimetype.isEmpty() )
    return;

  TQString query = TQString::fromLatin1(
      "('KPropsDlg/Plugin' in ServiceTypes) and "
      "((not exist [X-TDE-Protocol]) or "
      " ([X-TDE-Protocol] == '%1'  )   )"          ).arg(item->url().protocol());

  kdDebug( 250 ) << "trader query: " << query << endl;
  TDETrader::OfferList offers = TDETrader::self()->query( mimetype, query );
  TDETrader::OfferList::ConstIterator it = offers.begin();
  TDETrader::OfferList::ConstIterator end = offers.end();
  for (; it != end; ++it )
  {
    KPropsDlgPlugin *plugin = KParts::ComponentFactory
        ::createInstanceFromLibrary<KPropsDlgPlugin>( (*it)->library().local8Bit().data(),
                                                      TQT_TQOBJECT(this),
                                                      (*it)->name().latin1() );
    if ( !plugin )
        continue;

    insertPlugin( plugin );
  }
}

void KPropertiesDialog::updateUrl( const KURL& _newUrl )
{
  Q_ASSERT( m_items.count() == 1 );
  kdDebug(250) << "KPropertiesDialog::updateUrl (pre)" << _newUrl.url() << endl;
  KURL newUrl = _newUrl;
  emit saveAs(m_singleUrl, newUrl);
  kdDebug(250) << "KPropertiesDialog::updateUrl (post)" << newUrl.url() << endl;

  m_singleUrl = newUrl;
  m_items.first()->setURL( newUrl );
  assert(!m_singleUrl.isEmpty());
  // If we have an Desktop page, set it dirty, so that a full file is saved locally
  // Same for a URL page (because of the Name= hack)
  for ( TQPtrListIterator<KPropsDlgPlugin> it(m_pageList); it.current(); ++it )
   if ( it.current()->isA("KExecPropsPlugin") || // KDE4 remove me
        it.current()->isA("KURLPropsPlugin") ||
        it.current()->isA("KDesktopPropsPlugin"))
   {
     //kdDebug(250) << "Setting page dirty" << endl;
     it.current()->setDirty();
     break;
   }
}

void KPropertiesDialog::rename( const TQString& _name )
{
  Q_ASSERT( m_items.count() == 1 );
  kdDebug(250) << "KPropertiesDialog::rename " << _name << endl;
  KURL newUrl;
  // if we're creating from a template : use currentdir
  if ( !m_currentDir.isEmpty() )
  {
    newUrl = m_currentDir;
    newUrl.addPath( _name );
  }
  else
  {
    TQString tmpurl = m_singleUrl.url();
    if ( tmpurl.at(tmpurl.length() - 1) == '/')
      // It's a directory, so strip the trailing slash first
      tmpurl.truncate( tmpurl.length() - 1);
    newUrl = tmpurl;
    newUrl.setFileName( _name );
  }
  updateUrl( newUrl );
}

void KPropertiesDialog::abortApplying()
{
  d->m_aborted = true;
}

class KPropsDlgPlugin::KPropsDlgPluginPrivate
{
public:
  KPropsDlgPluginPrivate()
  {
  }
  ~KPropsDlgPluginPrivate()
  {
  }

  bool m_bDirty;
};

KPropsDlgPlugin::KPropsDlgPlugin( KPropertiesDialog *_props )
: TQObject( _props, 0L )
{
  d = new KPropsDlgPluginPrivate;
  properties = _props;
  fontHeight = 2*properties->fontMetrics().height();
  d->m_bDirty = false;
}

KPropsDlgPlugin::~KPropsDlgPlugin()
{
  delete d;
}

bool KPropsDlgPlugin::isDesktopFile( KFileItem * _item )
{
  // only local files
  bool isLocal;
  KURL url = _item->mostLocalURL( isLocal );
  if ( !isLocal )
    return false;

  // only regular files
  if ( !S_ISREG( _item->mode() ) )
    return false;

  TQString t( url.path() );

  // only if readable
  FILE *f = fopen( TQFile::encodeName(t), "r" );
  if ( f == 0L )
    return false;
  fclose(f);

  // return true if desktop file
  return ( (_item->mimetype() == "application/x-desktop")
      || (_item->mimetype() == "media/builtin-mydocuments")
      || (_item->mimetype() == "media/builtin-mycomputer")
      || (_item->mimetype() == "media/builtin-mynetworkplaces")
      || (_item->mimetype() == "media/builtin-printers")
      || (_item->mimetype() == "media/builtin-trash")
      || (_item->mimetype() == "media/builtin-webbrowser") );
}

void KPropsDlgPlugin::setDirty( bool b )
{
  d->m_bDirty = b;
}

void KPropsDlgPlugin::setDirty()
{
  d->m_bDirty = true;
}

bool KPropsDlgPlugin::isDirty() const
{
  return d->m_bDirty;
}

void KPropsDlgPlugin::applyChanges()
{
  kdWarning(250) << "applyChanges() not implemented in page !" << endl;
}

///////////////////////////////////////////////////////////////////////////////

class KFilePropsPlugin::KFilePropsPluginPrivate
{
public:
  KFilePropsPluginPrivate()
  {
    dirSizeJob = 0L;
    dirSizeUpdateTimer = 0L;
    m_lined = 0;
    m_freeSpaceLabel = 0;
  }
  ~KFilePropsPluginPrivate()
  {
    if ( dirSizeJob )
      dirSizeJob->kill();
  }

  KDirSize * dirSizeJob;
  TQTimer *dirSizeUpdateTimer;
  TQFrame *m_frame;
  bool bMultiple;
  bool bIconChanged;
  bool bKDesktopMode;
  bool bDesktopFile;
  TQLabel *m_freeSpaceLabel;
  TQString mimeType;
  TQString oldFileName;
  KLineEdit* m_lined;
};

KFilePropsPlugin::KFilePropsPlugin( KPropertiesDialog *_props )
  : KPropsDlgPlugin( _props )
{
  d = new KFilePropsPluginPrivate;
  d->bMultiple = (properties->items().count() > 1);
  d->bIconChanged = false;
  d->bKDesktopMode = (TQCString(tqApp->name()) == "kdesktop"); // nasty heh?
  d->bDesktopFile = KDesktopPropsPlugin::supports(properties->items());
  kdDebug(250) << "KFilePropsPlugin::KFilePropsPlugin bMultiple=" << d->bMultiple << endl;

  // We set this data from the first item, and we'll
  // check that the other items match against it, resetting when not.
  bool isLocal;
  KFileItem * item = properties->item();
  KURL url = item->mostLocalURL( isLocal );
  bool isReallyLocal = item->url().isLocalFile();
  bool bDesktopFile = isDesktopFile(item);
  kdDebug() << "url=" << url << " bDesktopFile=" << bDesktopFile << " isLocal=" << isLocal << " isReallyLocal=" << isReallyLocal << endl;
  mode_t mode = item->mode();
  bool hasDirs = item->isDir() && !item->isLink();
  bool hasRoot = url.path() == TQString::fromLatin1("/");
  TQString iconStr = KMimeType::iconForURL(url, mode);
  TQString directory = properties->kurl().directory();
  TQString protocol = properties->kurl().protocol();
  TQString mimeComment = item->mimeComment();
  d->mimeType = item->mimetype();
  bool hasTotalSize;
  TDEIO::filesize_t totalSize = item->size(hasTotalSize);
  TQString magicMimeComment;
  if ( isLocal ) {
      KMimeType::Ptr magicMimeType = KMimeType::findByFileContent( url.path() );
      if ( magicMimeType->name() != KMimeType::defaultMimeType() ) {
          magicMimeComment = magicMimeType->comment();
      }
  }

  // Those things only apply to 'single file' mode
  TQString filename = TQString::null;
  bool isTrash = false;
  bool isDevice = false;
  bool isMediaNode = false;
  m_bFromTemplate = false;

  // And those only to 'multiple' mode
  uint iDirCount = hasDirs ? 1 : 0;
  uint iFileCount = 1-iDirCount;

  d->m_frame = properties->addPage (i18n("&General"));

  TQVBoxLayout *vbl = new TQVBoxLayout( d->m_frame, 0,
                                      KDialog::spacingHint(), "vbl");
  TQGridLayout *grid = new TQGridLayout(0, 3); // unknown rows
  grid->setColStretch(0, 0);
  grid->setColStretch(1, 0);
  grid->setColStretch(2, 1);
  grid->addColSpacing(1, KDialog::spacingHint());
  vbl->addLayout(TQT_TQLAYOUT(grid));
  int curRow = 0;

  if ( !d->bMultiple )
  {
    TQString path;
    if ( !m_bFromTemplate ) {
      isTrash = ( properties->kurl().protocol().find( "trash", 0, false)==0 );
      if ( properties->kurl().protocol().find("device", 0, false)==0) {
        isDevice = true;
      }
      if (d->mimeType.startsWith("media/")) {
        isMediaNode = true;
      }
      // Extract the full name, but without file: for local files
      if ( isReallyLocal ) {
        path = properties->kurl().path();
      }
      else {
        path = properties->kurl().prettyURL();
      }
    } else {
      path = properties->currentDir().path(1) + properties->defaultName();
      directory = properties->currentDir().prettyURL();
    }

    if (KExecPropsPlugin::supports(properties->items()) || // KDE4 remove me
        d->bDesktopFile ||
        KBindingPropsPlugin::supports(properties->items())) {
      determineRelativePath( path );
    }

    // Extract the file name only
    filename = properties->defaultName();
    if ( filename.isEmpty() ) { // no template
      filename = item->name(); // this gives support for UDS_NAME, e.g. for tdeio_trash or tdeio_system
    } else {
      m_bFromTemplate = true;
      setDirty(); // to enforce that the copy happens
    }
    d->oldFileName = filename;

    // Make it human-readable
    filename = nameFromFileName( filename );

    if ( d->bKDesktopMode && d->bDesktopFile ) {
        KDesktopFile config( url.path(), true /* readonly */ );
        if ( config.hasKey( "Name" ) ) {
            filename = config.readName();
        }
    }

    oldName = filename;
  }
  else
  {
    // Multiple items: see what they have in common
    KFileItemList items = properties->items();
    KFileItemListIterator it( items );
    for ( ++it /*no need to check the first one again*/ ; it.current(); ++it )
    {
      KURL url = (*it)->url();
      kdDebug(250) << "KFilePropsPlugin::KFilePropsPlugin " << url.prettyURL() << endl;
      // The list of things we check here should match the variables defined
      // at the beginning of this method.
      if ( url.isLocalFile() != isLocal )
        isLocal = false; // not all local
      if ( bDesktopFile && isDesktopFile(*it) != bDesktopFile )
        bDesktopFile = false; // not all desktop files
      if ( (*it)->mode() != mode )
        mode = (mode_t)0;
      if ( KMimeType::iconForURL(url, mode) != iconStr )
        iconStr = "application-vnd.tde.tdemultiple";
      if ( url.directory() != directory )
        directory = TQString::null;
      if ( url.protocol() != protocol )
        protocol = TQString::null;
      if ( !mimeComment.isNull() && (*it)->mimeComment() != mimeComment )
        mimeComment = TQString::null;
      if ( isLocal && !magicMimeComment.isNull() ) {
          KMimeType::Ptr magicMimeType = KMimeType::findByFileContent( url.path() );
          if ( magicMimeType->comment() != magicMimeComment )
              magicMimeComment = TQString::null;
      }

      if ( url.path() == TQString::fromLatin1("/") )
        hasRoot = true;
      if ( (*it)->isDir() && !(*it)->isLink() )
      {
        iDirCount++;
        hasDirs = true;
      }
      else
      {
        iFileCount++;
	bool hasSize;
        totalSize += (*it)->size(hasSize);
	hasTotalSize = hasTotalSize || hasSize;
      }
    }
  }

  if (!isReallyLocal && !protocol.isEmpty())
  {
    directory += ' ';
    directory += '(';
    directory += protocol;
    directory += ')';
  }

  if ( !isDevice && !isMediaNode && !isTrash && (bDesktopFile || S_ISDIR(mode)) && !d->bMultiple /*not implemented for multiple*/ )
  {
    TDEIconButton *iconButton = new TDEIconButton( d->m_frame );
    int bsize = 66 + 2 * iconButton->style().pixelMetric(TQStyle::PM_ButtonMargin);
    iconButton->setFixedSize(bsize, bsize);
    iconButton->setIconSize(48);
    iconButton->setStrictIconSize(false);
    // This works for everything except Device icons on unmounted devices
    // So we have to really open .desktop files
    TQString iconStr = KMimeType::findByURL( url, mode )->icon( url, isLocal );
    if ( bDesktopFile && isLocal ) {
      KDesktopFile config( url.path(), true );
      config.setDesktopGroup();
      iconStr = config.readEntry( "Icon" );
      if ( config.hasDeviceType() ) {
	iconButton->setIconType( TDEIcon::Desktop, TDEIcon::Device );
      }
      else {
	iconButton->setIconType( TDEIcon::Desktop, TDEIcon::Application );
      }
    }
    else {
      iconButton->setIconType( TDEIcon::Desktop, TDEIcon::Place );
    }
    iconButton->setIcon(iconStr);
    iconArea = iconButton;
    connect( iconButton, TQT_SIGNAL( iconChanged(TQString) ),
             this, TQT_SLOT( slotIconChanged() ) );
  } else {
    TQLabel *iconLabel = new TQLabel( d->m_frame );
    int bsize = 66 + 2 * iconLabel->style().pixelMetric(TQStyle::PM_ButtonMargin);
    iconLabel->setFixedSize(bsize, bsize);
    if (isMediaNode) {
      // Display the correct device icon
      iconLabel->setPixmap( TDEGlobal::iconLoader()->loadIcon( item->iconName(), TDEIcon::Desktop, 48) );
    }
    else {
      // Display the generic folder icon
      iconLabel->setPixmap( TDEGlobal::iconLoader()->loadIcon( iconStr, TDEIcon::Desktop, 48) );
    }
    iconArea = iconLabel;
  }
  grid->addWidget(iconArea, curRow, 0, Qt::AlignLeft);

  if (d->bMultiple || isTrash || isDevice || isMediaNode || hasRoot)
  {
    TQLabel *lab = new TQLabel(d->m_frame );
    if ( d->bMultiple )
      lab->setText( TDEIO::itemsSummaryString( iFileCount + iDirCount, iFileCount, iDirCount, 0, false ) );
    else
      lab->setText( filename );
    nameArea = lab;
  } else
  {
    d->m_lined = new KLineEdit( d->m_frame );
    d->m_lined->setText(filename);
    nameArea = d->m_lined;
    d->m_lined->setFocus();

    // Enhanced rename: Don't highlight the file extension.
    TQString pattern;
    KServiceTypeFactory::self()->findFromPattern( filename, &pattern );
    if (!pattern.isEmpty() && pattern.at(0)=='*' && pattern.find('*',1)==-1)
      d->m_lined->setSelection(0, filename.length()-pattern.stripWhiteSpace().length()+1);
    else
    {
      int lastDot = filename.findRev('.');
      if (lastDot > 0)
        d->m_lined->setSelection(0, lastDot);
    }

    connect( d->m_lined, TQT_SIGNAL( textChanged( const TQString & ) ),
             this, TQT_SLOT( nameFileChanged(const TQString & ) ) );
  }

  grid->addWidget(nameArea, curRow++, 2);

  KSeparator* sep = new KSeparator( KSeparator::HLine, d->m_frame);
  grid->addMultiCellWidget(sep, curRow, curRow, 0, 2);
  ++curRow;

  TQLabel *l;
  if ( !mimeComment.isEmpty() && !isDevice && !isMediaNode && !isTrash)
  {
    l = new TQLabel(i18n("Type:"), d->m_frame );

    grid->addWidget(l, curRow, 0);

    TQHBox *box = new TQHBox(d->m_frame);
    box->setSpacing(20);
    l = new TQLabel(mimeComment, box );

#ifdef Q_WS_X11
    //TODO: wrap for win32 or mac?
    TQPushButton *button = new TQPushButton(box);

    TQIconSet iconSet = SmallIconSet(TQString::fromLatin1("configure"));
    TQPixmap pixMap = iconSet.pixmap( TQIconSet::Small, TQIconSet::Normal );
    button->setIconSet( iconSet );
    button->setFixedSize( pixMap.width()+8, pixMap.height()+8 );
    if ( d->mimeType == KMimeType::defaultMimeType() )
       TQToolTip::add(button, i18n("Create new file type"));
    else
       TQToolTip::add(button, i18n("Edit file type"));

    connect( button, TQT_SIGNAL( clicked() ), TQT_SLOT( slotEditFileType() ));

    if (!kapp->authorizeTDEAction("editfiletype"))
       button->hide();
#endif

    grid->addWidget(box, curRow++, 2);
  }

  if ( !magicMimeComment.isEmpty() && magicMimeComment != mimeComment )
  {
    l = new TQLabel(i18n("Contents:"), d->m_frame );
    grid->addWidget(l, curRow, 0);

    l = new TQLabel(magicMimeComment, d->m_frame );
    grid->addWidget(l, curRow++, 2);
  }

  if ( !directory.isEmpty() )
  {
    l = new TQLabel( i18n("Location:"), d->m_frame );
    grid->addWidget(l, curRow, 0);

    l = new KSqueezedTextLabel( d->m_frame );
    l->setText( directory );
    grid->addWidget(l, curRow++, 2);
  }

  if( hasDirs || hasTotalSize ) {
    l = new TQLabel(i18n("Size:"), d->m_frame );
    grid->addWidget(l, curRow, 0);

    m_sizeLabel = new TQLabel( d->m_frame );
    grid->addWidget( m_sizeLabel, curRow++, 2 );
  } else {
    m_sizeLabel = 0;
  }

  if ( !hasDirs ) // Only files [and symlinks]
  {
    if(hasTotalSize) {
      m_sizeLabel->setText(TDEIO::convertSizeWithBytes(totalSize));
    }

    m_sizeDetermineButton = 0L;
    m_sizeStopButton = 0L;
  }
  else // Directory
  {
    TQHBoxLayout * sizelay = new TQHBoxLayout(KDialog::spacingHint());
    grid->addLayout( sizelay, curRow++, 2 );

    // buttons
    m_sizeDetermineButton = new TQPushButton( i18n("Calculate"), d->m_frame );
    m_sizeStopButton = new TQPushButton( i18n("Stop"), d->m_frame );
    connect( m_sizeDetermineButton, TQT_SIGNAL( clicked() ), this, TQT_SLOT( slotSizeDetermine() ) );
    connect( m_sizeStopButton, TQT_SIGNAL( clicked() ), this, TQT_SLOT( slotSizeStop() ) );
    sizelay->addWidget(m_sizeDetermineButton, 0);
    sizelay->addWidget(m_sizeStopButton, 0);
    sizelay->addStretch(10); // so that the buttons don't grow horizontally

    // auto-launch for local dirs only, but not for '/' or medias
    if ( isReallyLocal && !hasRoot )
    {
      m_sizeDetermineButton->setText( i18n("Refresh") );
      slotSizeDetermine();
    }
    else
      m_sizeStopButton->setEnabled( false );
  }

  if (!d->bMultiple && item->isLink()) {
    l = new TQLabel(i18n("Points to:"), d->m_frame );
    grid->addWidget(l, curRow, 0);

    l = new KSqueezedTextLabel(item->linkDest(), d->m_frame );
    grid->addWidget(l, curRow++, 2);
  }

  if (!d->bMultiple) // Dates for multiple don't make much sense...
  {
    TQDateTime dt;
    bool hasTime;
    time_t tim = item->time(TDEIO::UDS_CREATION_TIME, hasTime);
    if ( hasTime )
    {
      l = new TQLabel(i18n("Created:"), d->m_frame );
      grid->addWidget(l, curRow, 0);

      dt.setTime_t( tim );
      l = new TQLabel(TDEGlobal::locale()->formatDateTime(dt), d->m_frame );
      grid->addWidget(l, curRow++, 2);
    }

    tim = item->time(TDEIO::UDS_MODIFICATION_TIME, hasTime);
    if ( hasTime )
    {
      l = new TQLabel(i18n("Modified:"), d->m_frame );
      grid->addWidget(l, curRow, 0);

      dt.setTime_t( tim );
      l = new TQLabel(TDEGlobal::locale()->formatDateTime(dt), d->m_frame );
      grid->addWidget(l, curRow++, 2);
    }

    tim = item->time(TDEIO::UDS_ACCESS_TIME, hasTime);
    if ( hasTime )
    {
      l = new TQLabel(i18n("Accessed:"), d->m_frame );
      grid->addWidget(l, curRow, 0);

      dt.setTime_t( tim );
      l = new TQLabel(TDEGlobal::locale()->formatDateTime(dt), d->m_frame );
      grid->addWidget(l, curRow++, 2);
    }
  }

  if ( isLocal && hasDirs )  // only for directories
  {
    sep = new KSeparator( KSeparator::HLine, d->m_frame);
    grid->addMultiCellWidget(sep, curRow, curRow, 0, 2);
    ++curRow;

    TQString mountPoint = TDEIO::findPathMountPoint( url.path() );

    if (mountPoint != "/")
    {
        l = new TQLabel(i18n("Mounted on:"), d->m_frame );
        grid->addWidget(l, curRow, 0);

        l = new KSqueezedTextLabel( mountPoint, d->m_frame );
        grid->addWidget( l, curRow++, 2 );
    }

    l = new TQLabel(i18n("Free disk space:"), d->m_frame );
    grid->addWidget(l, curRow, 0);

    d->m_freeSpaceLabel = new TQLabel( d->m_frame );
    grid->addWidget( d->m_freeSpaceLabel, curRow++, 2 );

    KDiskFreeSp * job = new KDiskFreeSp;
    connect( job, TQT_SIGNAL( foundMountPoint( const unsigned long&, const unsigned long&,
             const unsigned long&, const TQString& ) ),
             this, TQT_SLOT( slotFoundMountPoint( const unsigned long&, const unsigned long&,
          const unsigned long&, const TQString& ) ) );
    job->readDF( mountPoint );
  }

  vbl->addStretch(1);
}

// TQString KFilePropsPlugin::tabName () const
// {
//   return i18n ("&General");
// }

void KFilePropsPlugin::setFileNameReadOnly( bool ro )
{
  if ( d->m_lined )
  {
    d->m_lined->setReadOnly( ro );
    if (ro)
    {
       // Don't put the initial focus on the line edit when it is ro
       TQPushButton *button = properties->actionButton(KDialogBase::Ok);
       if (button)
          button->setFocus();
    }
  }
}

void KFilePropsPlugin::slotEditFileType()
{
#ifdef Q_WS_X11
  TQString mime;
  if ( d->mimeType == KMimeType::defaultMimeType() ) {
    int pos = d->oldFileName.findRev( '.' );
    if ( pos != -1 )
	mime = "*" + d->oldFileName.mid(pos);
    else
	mime = "*";
  }
  else
    mime = d->mimeType;
    //TODO: wrap for win32 or mac?
  TQString keditfiletype = TQString::fromLatin1("keditfiletype");
  KRun::runCommand( keditfiletype
                    + " --parent " + TQString::number( (ulong)properties->topLevelWidget()->winId())
                    + " " + TDEProcess::quote(mime),
                    keditfiletype, keditfiletype /*unused*/);
#endif
}

void KFilePropsPlugin::slotIconChanged()
{
  d->bIconChanged = true;
  emit changed();
}

void KFilePropsPlugin::nameFileChanged(const TQString &text )
{
  properties->enableButtonOK(!text.isEmpty());
  emit changed();
}

void KFilePropsPlugin::determineRelativePath( const TQString & path )
{
    // now let's make it relative
    TQStringList dirs;
    if (KBindingPropsPlugin::supports(properties->items()))
    {
       m_sRelativePath =TDEGlobal::dirs()->relativeLocation("mime", path);
       if (m_sRelativePath.startsWith("/"))
          m_sRelativePath = TQString::null;
    }
    else
    {
       m_sRelativePath =TDEGlobal::dirs()->relativeLocation("apps", path);
       if (m_sRelativePath.startsWith("/"))
       {
          m_sRelativePath =TDEGlobal::dirs()->relativeLocation("xdgdata-apps", path);
          if (m_sRelativePath.startsWith("/"))
             m_sRelativePath = TQString::null;
          else
             m_sRelativePath = path;
       }
    }
    if ( m_sRelativePath.isEmpty() )
    {
      if (KBindingPropsPlugin::supports(properties->items()))
        kdWarning(250) << "Warning : editing a mimetype file out of the mimetype dirs!" << endl;
    }
}

void KFilePropsPlugin::slotFoundMountPoint( const TQString&,
					    unsigned long kBSize,
					    unsigned long /*kBUsed*/,
					    unsigned long kBAvail )
{
    d->m_freeSpaceLabel->setText(
	// xgettext:no-c-format  --  Don't warn about translating the %1 out of %2 part.
	i18n("Available space out of total partition size (percent used)", "%1 out of %2 (%3% used)")
	.arg(TDEIO::convertSizeFromKB(kBAvail))
	.arg(TDEIO::convertSizeFromKB(kBSize))
	.arg( 100 - (int)(100.0 * kBAvail / kBSize) ));
}

// attention: copy&paste below, due to compiler bug
// it doesn't like those unsigned long parameters -- unsigned long& are ok :-/
void KFilePropsPlugin::slotFoundMountPoint( const unsigned long& kBSize,
					    const unsigned long& /*kBUsed*/,
					    const unsigned long& kBAvail,
					    const TQString& )
{
    d->m_freeSpaceLabel->setText(
	// xgettext:no-c-format  --  Don't warn about translating the %1 out of %2 part.
	i18n("Available space out of total partition size (percent used)", "%1 out of %2 (%3% used)")
	.arg(TDEIO::convertSizeFromKB(kBAvail))
	.arg(TDEIO::convertSizeFromKB(kBSize))
	.arg( 100 - (int)(100.0 * kBAvail / kBSize) ));
}

void KFilePropsPlugin::slotDirSizeUpdate()
{
    TDEIO::filesize_t totalSize = d->dirSizeJob->totalSize();
    TDEIO::filesize_t totalFiles = d->dirSizeJob->totalFiles();
         TDEIO::filesize_t totalSubdirs = d->dirSizeJob->totalSubdirs();
    m_sizeLabel->setText( i18n("Calculating... %1 (%2)\n%3, %4")
			  .arg(TDEIO::convertSize(totalSize))
                         .arg(TDEGlobal::locale()->formatNumber(totalSize, 0))
        .arg(i18n("1 file","%n files",totalFiles))
        .arg(i18n("1 sub-folder","%n sub-folders",totalSubdirs)));
}

void KFilePropsPlugin::slotDirSizeFinished( TDEIO::Job * job )
{
  if (job->error())
    m_sizeLabel->setText( job->errorString() );
  else
  {
    TDEIO::filesize_t totalSize = static_cast<KDirSize*>(job)->totalSize();
	TDEIO::filesize_t totalFiles = static_cast<KDirSize*>(job)->totalFiles();
	TDEIO::filesize_t totalSubdirs = static_cast<KDirSize*>(job)->totalSubdirs();
    m_sizeLabel->setText( TQString::fromLatin1("%1 (%2)\n%3, %4")
			  .arg(TDEIO::convertSize(totalSize))
			  .arg(TDEGlobal::locale()->formatNumber(totalSize, 0))
        .arg(i18n("1 file","%n files",totalFiles))
        .arg(i18n("1 sub-folder","%n sub-folders",totalSubdirs)));
  }
  m_sizeStopButton->setEnabled(false);
  // just in case you change something and try again :)
  m_sizeDetermineButton->setText( i18n("Refresh") );
  m_sizeDetermineButton->setEnabled(true);
  d->dirSizeJob = 0L;
  delete d->dirSizeUpdateTimer;
  d->dirSizeUpdateTimer = 0L;
}

void KFilePropsPlugin::slotSizeDetermine()
{
  m_sizeLabel->setText( i18n("Calculating...") );
  kdDebug(250) << " KFilePropsPlugin::slotSizeDetermine() properties->item()=" <<  properties->item() << endl;
  kdDebug(250) << " URL=" << properties->item()->url().url() << endl;
  d->dirSizeJob = KDirSize::dirSizeJob( properties->items() );
  d->dirSizeUpdateTimer = new TQTimer(this);
  connect( d->dirSizeUpdateTimer, TQT_SIGNAL( timeout() ),
           TQT_SLOT( slotDirSizeUpdate() ) );
  d->dirSizeUpdateTimer->start(500);
  connect( d->dirSizeJob, TQT_SIGNAL( result( TDEIO::Job * ) ),
           TQT_SLOT( slotDirSizeFinished( TDEIO::Job * ) ) );
  m_sizeStopButton->setEnabled(true);
  m_sizeDetermineButton->setEnabled(false);

  // also update the "Free disk space" display
  if ( d->m_freeSpaceLabel )
  {
    bool isLocal;
    KFileItem * item = properties->item();
    KURL url = item->mostLocalURL( isLocal );
    TQString mountPoint = TDEIO::findPathMountPoint( url.path() );

    KDiskFreeSp * job = new KDiskFreeSp;
    connect( job, TQT_SIGNAL( foundMountPoint( const unsigned long&, const unsigned long&,
             const unsigned long&, const TQString& ) ),
             this, TQT_SLOT( slotFoundMountPoint( const unsigned long&, const unsigned long&,
          const unsigned long&, const TQString& ) ) );
    job->readDF( mountPoint );
  }
}

void KFilePropsPlugin::slotSizeStop()
{
  if ( d->dirSizeJob )
  {
    m_sizeLabel->setText( i18n("Stopped") );
    d->dirSizeJob->kill();
    d->dirSizeJob = 0;
  }
  if ( d->dirSizeUpdateTimer )
    d->dirSizeUpdateTimer->stop();

  m_sizeStopButton->setEnabled(false);
  m_sizeDetermineButton->setEnabled(true);
}

KFilePropsPlugin::~KFilePropsPlugin()
{
  delete d;
}

bool KFilePropsPlugin::supports( KFileItemList /*_items*/ )
{
  return true;
}

// Don't do this at home
void tqt_enter_modal( TQWidget *widget );
void tqt_leave_modal( TQWidget *widget );

void KFilePropsPlugin::applyChanges()
{
  if ( d->dirSizeJob ) {
    slotSizeStop();
  }

  kdDebug(250) << "KFilePropsPlugin::applyChanges" << endl;

  if (nameArea->inherits("TQLineEdit"))
  {
    TQString n = ((TQLineEdit *) nameArea)->text();
    // Remove trailing spaces (#4345)
    while ( n[n.length()-1].isSpace() )
      n.truncate( n.length() - 1 );
    if ( n.isEmpty() )
    {
      KMessageBox::sorry( properties, i18n("The new file name is empty."));
      properties->abortApplying();
      return;
    }

    // Do we need to rename the file ?
    kdDebug(250) << "oldname = " << oldName << endl;
    kdDebug(250) << "newname = " << n << endl;
    if ( oldName != n || m_bFromTemplate ) { // true for any from-template file
      TDEIO::Job * job = 0L;
      KURL oldurl = properties->kurl();

      TQString newFileName = TDEIO::encodeFileName(n);
      if (d->bDesktopFile && !newFileName.endsWith(".desktop") && !newFileName.endsWith(".kdelnk"))
         newFileName += ".desktop";

      // Tell properties. Warning, this changes the result of properties->kurl() !
      properties->rename( newFileName );

      // Update also relative path (for apps and mimetypes)
      if ( !m_sRelativePath.isEmpty() ) {
        determineRelativePath( properties->kurl().path() );
      }

      kdDebug(250) << "New URL = " << properties->kurl().url() << endl;
      kdDebug(250) << "old = " << oldurl.url() << endl;

      // Don't remove the template !!
      if ( !m_bFromTemplate ) { // (normal renaming)
        job = TDEIO::move( oldurl, properties->kurl() );
      }
      else { // Copying a template
        job = TDEIO::copy( oldurl, properties->kurl() );
      }

      connect( job, TQT_SIGNAL( result( TDEIO::Job * ) ),
               TQT_SLOT( slotCopyFinished( TDEIO::Job * ) ) );
      connect( job, TQT_SIGNAL( renamed( TDEIO::Job *, const KURL &, const KURL & ) ),
               TQT_SLOT( slotFileRenamed( TDEIO::Job *, const KURL &, const KURL & ) ) );
      // wait for job
      TQWidget dummy(0,0,(WFlags)(WType_Dialog|WShowModal));
      tqt_enter_modal(&dummy);
      tqApp->enter_loop();
      tqt_leave_modal(&dummy);
      return;
    }
    properties->updateUrl(properties->kurl());
    // Update also relative path (for apps and mimetypes)
    if ( !m_sRelativePath.isEmpty() ) {
      determineRelativePath( properties->kurl().path() );
    }
  }

  // No job, keep going
  slotCopyFinished( 0L );
}

void KFilePropsPlugin::slotCopyFinished( TDEIO::Job * job )
{
  kdDebug(250) << "KFilePropsPlugin::slotCopyFinished" << endl;
  if (job)
  {
    // allow apply() to return
    tqApp->exit_loop();
    if ( job->error() )
    {
        job->showErrorDialog( d->m_frame );
        // Didn't work. Revert the URL to the old one
        properties->updateUrl( static_cast<TDEIO::CopyJob*>(job)->srcURLs().first() );
        properties->abortApplying(); // Don't apply the changes to the wrong file !
        return;
    }
  }

  assert( properties->item() );
  assert( !properties->item()->url().isEmpty() );

  // Save the file where we can -> usually in ~/.trinity/...
  if (KBindingPropsPlugin::supports(properties->items()) && !m_sRelativePath.isEmpty())
  {
    KURL newURL;
    newURL.setPath( locateLocal("mime", m_sRelativePath) );
    properties->updateUrl( newURL );
  }
  else if (d->bDesktopFile && !m_sRelativePath.isEmpty())
  {
    kdDebug(250) << "KFilePropsPlugin::slotCopyFinished " << m_sRelativePath << endl;
    KURL newURL;
    newURL.setPath( KDesktopFile::locateLocal(m_sRelativePath) );
    kdDebug(250) << "KFilePropsPlugin::slotCopyFinished path=" << newURL.path() << endl;
    properties->updateUrl( newURL );
  }

  if ( d->bKDesktopMode && d->bDesktopFile ) {
      // Renamed? Update Name field
      if ( d->oldFileName != properties->kurl().fileName() || m_bFromTemplate ) {
          KDesktopFile config( properties->kurl().path() );
          TQString nameStr = nameFromFileName(properties->kurl().fileName());
          config.writeEntry( "Name", nameStr );
          config.writeEntry( "Name", nameStr, true, false, true );
      }
  }
}

void KFilePropsPlugin::applyIconChanges()
{
  TDEIconButton *iconButton = ::tqqt_cast<TDEIconButton *>( iconArea );
  if ( !iconButton || !d->bIconChanged )
    return;
  // handle icon changes - only local files (or pseudo-local) for now
  // TODO: Use KTempFile and TDEIO::file_copy with overwrite = true
  KURL url = properties->kurl();
  url = TDEIO::NetAccess::mostLocalURL( url, properties );
  if (url.isLocalFile()) {
    TQString path;

    if (S_ISDIR(properties->item()->mode()))
    {
      path = url.path(1) + TQString::fromLatin1(".directory");
      // don't call updateUrl because the other tabs (i.e. permissions)
      // apply to the directory, not the .directory file.
    }
    else
      path = url.path();

    // Get the default image
    TQString str = KMimeType::findByURL( url,
                                        properties->item()->mode(),
                                        true )->KServiceType::icon();
    // Is it another one than the default ?
    TQString sIcon;
    if ( str != iconButton->icon() )
      sIcon = iconButton->icon();
    // (otherwise write empty value)

    kdDebug(250) << "**" << path << "**" << endl;
    TQFile f( path );

    // If default icon and no .directory file -> don't create one
    if ( !sIcon.isEmpty() || f.exists() )
    {
        if ( !f.open( IO_ReadWrite ) ) {
          KMessageBox::sorry( 0, i18n("<qt>Could not save properties. You do not "
				      "have sufficient access to write to <b>%1</b>.</qt>").arg(path));
          return;
        }
        f.close();

        KDesktopFile cfg(path);
        kdDebug(250) << "sIcon = " << (sIcon) << endl;
        kdDebug(250) << "str = " << (str) << endl;
        cfg.writeEntry( "Icon", sIcon );
        cfg.sync();
    }
  }
}

void KFilePropsPlugin::slotFileRenamed( TDEIO::Job *, const KURL &, const KURL & newUrl )
{
  // This is called in case of an existing local file during the copy/move operation,
  // if the user chooses Rename.
  properties->updateUrl( newUrl );
}

void KFilePropsPlugin::postApplyChanges()
{
  // Save the icon only after applying the permissions changes (#46192)
  applyIconChanges();

  KURL::List lst;
  KFileItemList items = properties->items();
  for ( KFileItemListIterator it( items ); it.current(); ++it )
    lst.append((*it)->url());
  KDirNotify_stub allDirNotify("*", "KDirNotify*");
  allDirNotify.FilesChanged( lst );
}

class KFilePermissionsPropsPlugin::KFilePermissionsPropsPluginPrivate
{
public:
  KFilePermissionsPropsPluginPrivate()
  {
  }
  ~KFilePermissionsPropsPluginPrivate()
  {
  }

  TQFrame *m_frame;
  TQCheckBox *cbRecursive;
  TQLabel *explanationLabel;
  TQComboBox *ownerPermCombo, *groupPermCombo, *othersPermCombo;
  TQCheckBox *extraCheckbox;
  mode_t partialPermissions;
  KFilePermissionsPropsPlugin::PermissionsMode pmode;
  bool canChangePermissions;
  bool isIrregular;
  bool hasExtendedACL;
  KACL extendedACL;
  KACL defaultACL;
  bool fileSystemSupportsACLs;
};

#define UniOwner    (S_IRUSR|S_IWUSR|S_IXUSR)
#define UniGroup    (S_IRGRP|S_IWGRP|S_IXGRP)
#define UniOthers   (S_IROTH|S_IWOTH|S_IXOTH)
#define UniRead     (S_IRUSR|S_IRGRP|S_IROTH)
#define UniWrite    (S_IWUSR|S_IWGRP|S_IWOTH)
#define UniExec     (S_IXUSR|S_IXGRP|S_IXOTH)
#define UniSpecial  (S_ISUID|S_ISGID|S_ISVTX)

// synced with PermissionsTarget
const mode_t KFilePermissionsPropsPlugin::permissionsMasks[3] = {UniOwner, UniGroup, UniOthers};
const mode_t KFilePermissionsPropsPlugin::standardPermissions[4] = { 0, UniRead, UniRead|UniWrite, (mode_t)-1 };

// synced with PermissionsMode and standardPermissions
const char *KFilePermissionsPropsPlugin::permissionsTexts[4][4] = {
  { I18N_NOOP("Forbidden"),
    I18N_NOOP("Can Read"),
    I18N_NOOP("Can Read & Write"),
    0 },
  { I18N_NOOP("Forbidden"),
    I18N_NOOP("Can View Content"),
    I18N_NOOP("Can View & Modify Content"),
    0 },
  { 0, 0, 0, 0}, // no texts for links
  { I18N_NOOP("Forbidden"),
    I18N_NOOP("Can View Content & Read"),
    I18N_NOOP("Can View/Read & Modify/Write"),
    0 }
};


KFilePermissionsPropsPlugin::KFilePermissionsPropsPlugin( KPropertiesDialog *_props )
  : KPropsDlgPlugin( _props )
{
  d = new KFilePermissionsPropsPluginPrivate;
  d->cbRecursive = 0L;
  grpCombo = 0L; grpEdit = 0;
  usrEdit = 0L;
  TQString path = properties->kurl().path(-1);
  TQString fname = properties->kurl().fileName();
  bool isLocal = properties->kurl().isLocalFile();
  bool isTrash = ( properties->kurl().protocol().find("trash", 0, false)==0 );
  bool IamRoot = (geteuid() == 0);

  KFileItem * item = properties->item();
  bool isLink = item->isLink();
  bool isDir = item->isDir(); // all dirs
  bool hasDir = item->isDir(); // at least one dir
  permissions = item->permissions(); // common permissions to all files
  d->partialPermissions = permissions; // permissions that only some files have (at first we take everything)
  d->isIrregular = isIrregular(permissions, isDir, isLink);
  strOwner = item->user();
  strGroup = item->group();
  d->hasExtendedACL = item->ACL().isExtended() || item->defaultACL().isValid();
  d->extendedACL = item->ACL();
  d->defaultACL = item->defaultACL();
  d->fileSystemSupportsACLs = false;

  if ( properties->items().count() > 1 )
  {
    // Multiple items: see what they have in common
    KFileItemList items = properties->items();
    KFileItemListIterator it( items );
    for ( ++it /*no need to check the first one again*/ ; it.current(); ++it )
    {
      if (!d->isIrregular)
        d->isIrregular |= isIrregular((*it)->permissions(),
                                      (*it)->isDir() == isDir,
                                      (*it)->isLink() == isLink);
      d->hasExtendedACL = d->hasExtendedACL || (*it)->hasExtendedACL();
      if ( (*it)->isLink() != isLink )
        isLink = false;
      if ( (*it)->isDir() != isDir )
        isDir = false;
      hasDir |= (*it)->isDir();
      if ( (*it)->permissions() != permissions )
      {
        permissions &= (*it)->permissions();
        d->partialPermissions |= (*it)->permissions();
      }
      if ( (*it)->user() != strOwner )
        strOwner = TQString::null;
      if ( (*it)->group() != strGroup )
        strGroup = TQString::null;
    }
  }

  if (isLink)
    d->pmode = PermissionsOnlyLinks;
  else if (isDir)
    d->pmode = PermissionsOnlyDirs;
  else if (hasDir)
    d->pmode = PermissionsMixed;
  else
    d->pmode = PermissionsOnlyFiles;

  // keep only what's not in the common permissions
  d->partialPermissions = d->partialPermissions & ~permissions;

  bool isMyFile = false;

  if (isLocal && !strOwner.isEmpty()) { // local files, and all owned by the same person
    struct passwd *myself = getpwuid( geteuid() );
    if ( myself != 0L )
    {
      isMyFile = (strOwner == TQString::fromLocal8Bit(myself->pw_name));
    } else
      kdWarning() << "I don't exist ?! geteuid=" << geteuid() << endl;
  } else {
    //We don't know, for remote files, if they are ours or not.
    //So we let the user change permissions, and
    //TDEIO::chmod will tell, if he had no right to do it.
    isMyFile = true;
  }

  d->canChangePermissions = (isMyFile || IamRoot) && (!isLink);


  // create GUI

  d->m_frame = properties->addPage(i18n("&Permissions"));

  TQBoxLayout *box = new TQVBoxLayout( d->m_frame, 0, KDialog::spacingHint() );

  TQWidget *l;
  TQLabel *lbl;
  TQGroupBox *gb;
  TQGridLayout *gl;
  TQPushButton* pbAdvancedPerm = 0;

  /* Group: Access Permissions */
  gb = new TQGroupBox ( 0, Qt::Vertical, i18n("Access Permissions"), d->m_frame );
  gb->layout()->setSpacing(KDialog::spacingHint());
  gb->layout()->setMargin(KDialog::marginHint());
  box->addWidget (gb);

  gl = new TQGridLayout (gb->layout(), 7, 2);
  gl->setColStretch(1, 1);

  l = d->explanationLabel = new TQLabel( "", gb );
  if (isLink)
    d->explanationLabel->setText(i18n("This file is a link and does not have permissions.",
				      "All files are links and do not have permissions.",
				      properties->items().count()));
  else if (!d->canChangePermissions)
    d->explanationLabel->setText(i18n("Only the owner can change permissions."));
  gl->addMultiCellWidget(l, 0, 0, 0, 1);

  lbl = new TQLabel( i18n("O&wner:"), gb);
  gl->addWidget(lbl, 1, 0);
  l = d->ownerPermCombo = new TQComboBox(gb);
  lbl->setBuddy(l);
  gl->addWidget(l, 1, 1);
  connect(l, TQT_SIGNAL( highlighted(int) ), this, TQT_SIGNAL( changed() ));
  TQWhatsThis::add(l, i18n("Specifies the actions that the owner is allowed to do."));

  lbl = new TQLabel( i18n("Gro&up:"), gb);
  gl->addWidget(lbl, 2, 0);
  l = d->groupPermCombo = new TQComboBox(gb);
  lbl->setBuddy(l);
  gl->addWidget(l, 2, 1);
  connect(l, TQT_SIGNAL( highlighted(int) ), this, TQT_SIGNAL( changed() ));
  TQWhatsThis::add(l, i18n("Specifies the actions that the members of the group are allowed to do."));

  lbl = new TQLabel( i18n("O&thers:"), gb);
  gl->addWidget(lbl, 3, 0);
  l = d->othersPermCombo = new TQComboBox(gb);
  lbl->setBuddy(l);
  gl->addWidget(l, 3, 1);
  connect(l, TQT_SIGNAL( highlighted(int) ), this, TQT_SIGNAL( changed() ));
  TQWhatsThis::add(l, i18n("Specifies the actions that all users, who are neither "
			  "owner nor in the group, are allowed to do."));

  if (!isLink) {
    l = d->extraCheckbox = new TQCheckBox(hasDir ?
					 i18n("Only own&er can rename and delete folder content") :
					 i18n("Is &executable"),
					 gb );
    connect( d->extraCheckbox, TQT_SIGNAL( clicked() ), this, TQT_SIGNAL( changed() ) );
    gl->addWidget(l, 4, 1);
    TQWhatsThis::add(l, hasDir ? i18n("Enable this option to allow only the folder's owner to "
				     "delete or rename the contained files and folders. Other "
				     "users can only add new files, which requires the 'Modify "
				     "Content' permission.")
		    : i18n("Enable this option to mark the file as executable. This only makes "
			   "sense for programs and scripts. It is required when you want to "
			   "execute them."));

    TQLayoutItem *spacer = TQT_TQLAYOUTITEM(new TQSpacerItem(0, 20, TQSizePolicy::Minimum, TQSizePolicy::Expanding));
    gl->addMultiCell(spacer, 5, 5, 0, 1);

    pbAdvancedPerm = new TQPushButton(i18n("A&dvanced Permissions"), gb);
    gl->addMultiCellWidget(pbAdvancedPerm, 6, 6, 0, 1, Qt::AlignRight);
    connect(pbAdvancedPerm, TQT_SIGNAL( clicked() ), this, TQT_SLOT( slotShowAdvancedPermissions() ));
  }
  else
    d->extraCheckbox = 0;


  /**** Group: Ownership ****/
  gb = new TQGroupBox ( 0, Qt::Vertical, i18n("Ownership"), d->m_frame );
  gb->layout()->setSpacing(KDialog::spacingHint());
  gb->layout()->setMargin(KDialog::marginHint());
  box->addWidget (gb);

  gl = new TQGridLayout (gb->layout(), 4, 3);
  gl->addRowSpacing(0, 10);

  /*** Set Owner ***/
  l = new TQLabel( i18n("User:"), gb );
  gl->addWidget (l, 1, 0);

  /* GJ: Don't autocomplete more than 1000 users. This is a kind of random
   * value. Huge sites having 10.000+ user have a fair chance of using NIS,
   * (possibly) making this unacceptably slow.
   * OTOH, it is nice to offer this functionality for the standard user.
   */
  int i, maxEntries = 1000;
  struct passwd *user;

  /* File owner: For root, offer a KLineEdit with autocompletion.
   * For a user, who can never chown() a file, offer a TQLabel.
   */
  if (IamRoot && isLocal)
  {
    usrEdit = new KLineEdit( gb );
    TDECompletion *kcom = usrEdit->completionObject();
    kcom->setOrder(TDECompletion::Sorted);
    setpwent();
    for (i=0; ((user = getpwent()) != 0L) && (i < maxEntries); i++)
      kcom->addItem(TQString::fromLatin1(user->pw_name));
    endpwent();
    usrEdit->setCompletionMode((i < maxEntries) ? TDEGlobalSettings::CompletionAuto :
                               TDEGlobalSettings::CompletionNone);
    usrEdit->setText(strOwner);
    gl->addWidget(usrEdit, 1, 1);
    connect( usrEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
             this, TQT_SIGNAL( changed() ) );
  }
  else
  {
    l = new TQLabel(strOwner, gb);
    gl->addWidget(l, 1, 1);
  }

  /*** Set Group ***/

  TQStringList groupList;
  TQCString strUser;
  user = getpwuid(geteuid());
  if (user != 0L)
    strUser = user->pw_name;

#ifdef Q_OS_UNIX
  gid_t *groups = NULL;
  int ng = 1;
  struct group *mygroup;
  gid_t *newgroups = NULL;

  groups = (gid_t *) malloc(ng * sizeof(gid_t));

  if (getgrouplist(strUser, user->pw_gid, groups, &ng) == -1) {
	  newgroups = (gid_t *) malloc(ng * sizeof(gid_t));
	  if (newgroups != NULL) {
	          free(groups);
		  groups = newgroups;
		  getgrouplist(strUser, user->pw_gid, groups, &ng);
	  } else ng = 1;
  }

  for (i = 0; i < ng; i++) {
	  mygroup = getgrgid(groups[i]);
	  if (mygroup != NULL) groupList += TQString::fromLocal8Bit(mygroup->gr_name);
  }

  free(groups);

#else //Q_OS_UNIX
  struct group *ge;

  /* add the effective Group to the list .. */
  ge = getgrgid (getegid());
  if (ge) {
    TQString name = TQString::fromLatin1(ge->gr_name);
    if (name.isEmpty())
      name.setNum(ge->gr_gid);
    if (groupList.find(name) == groupList.end())
      groupList += name;
  }
#endif //Q_OS_UNIX

  bool isMyGroup = groupList.contains(strGroup);

  /* add the group the file currently belongs to ..
   * .. if its not there already
   */
  if (!isMyGroup)
    groupList += strGroup;

  l = new TQLabel( i18n("Group:"), gb );
  gl->addWidget (l, 2, 0);

  /* Set group: if possible to change:
   * - Offer a KLineEdit for root, since he can change to any group.
   * - Offer a TQComboBox for a normal user, since he can change to a fixed
   *   (small) set of groups only.
   * If not changeable: offer a TQLabel.
   */
  if (IamRoot && isLocal)
  {
    grpEdit = new KLineEdit(gb);
    TDECompletion *kcom = new TDECompletion;
    kcom->setItems(groupList);
    grpEdit->setCompletionObject(kcom, true);
    grpEdit->setAutoDeleteCompletionObject( true );
    grpEdit->setCompletionMode(TDEGlobalSettings::CompletionAuto);
    grpEdit->setText(strGroup);
    gl->addWidget(grpEdit, 2, 1);
    connect( grpEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
             this, TQT_SIGNAL( changed() ) );
  }
  else if ((groupList.count() > 1) && isMyFile && isLocal)
  {
    grpCombo = new TQComboBox(gb, "combogrouplist");
    grpCombo->insertStringList(groupList);
    grpCombo->setCurrentItem(groupList.findIndex(strGroup));
    gl->addWidget(grpCombo, 2, 1);
    connect( grpCombo, TQT_SIGNAL( activated( int ) ),
             this, TQT_SIGNAL( changed() ) );
  }
  else
  {
    l = new TQLabel(strGroup, gb);
    gl->addWidget(l, 2, 1);
  }

  gl->setColStretch(2, 10);

  // "Apply recursive" checkbox
  if ( hasDir && !isLink && !isTrash  )
  {
      d->cbRecursive = new TQCheckBox( i18n("Apply changes to all subfolders and their contents"), d->m_frame );
      connect( d->cbRecursive, TQT_SIGNAL( clicked() ), this, TQT_SIGNAL( changed() ) );
      box->addWidget( d->cbRecursive );
  }

  updateAccessControls();


  if ( isTrash || !d->canChangePermissions )
  {
      //don't allow to change properties for file into trash
      enableAccessControls(false);
      if ( pbAdvancedPerm  && !d->hasExtendedACL )
          pbAdvancedPerm->setEnabled(false);
  }

  box->addStretch (10);
}

#ifdef USE_POSIX_ACL
static bool fileSystemSupportsACL( const TQCString& pathCString )
{
    bool fileSystemSupportsACLs = false;
#ifdef Q_OS_FREEBSD
    struct statfs buf;
    fileSystemSupportsACLs = ( statfs( pathCString.data(), &buf ) == 0 ) && ( buf.f_flags & MNT_ACLS );
#else
    fileSystemSupportsACLs =
      getxattr( pathCString.data(), "system.posix_acl_access", NULL, 0 ) >= 0
#ifdef ENODATA
			|| (errno == ENODATA)
#endif
#ifdef ENOATTR
			|| (errno == ENOATTR)
#endif
			;
#endif
    return fileSystemSupportsACLs;
}
#endif


void KFilePermissionsPropsPlugin::slotShowAdvancedPermissions() {

  bool isDir = (d->pmode == PermissionsOnlyDirs) || (d->pmode == PermissionsMixed);
  KDialogBase dlg(properties, 0, true, i18n("Advanced Permissions"),
		  KDialogBase::Ok|KDialogBase::Cancel);

  TQLabel *l, *cl[3];
  TQGroupBox *gb;
  TQGridLayout *gl;

  TQVBox *mainVBox = dlg.makeVBoxMainWidget();

  // Group: Access Permissions
  gb = new TQGroupBox ( 0, Qt::Vertical, i18n("Access Permissions"), mainVBox );
  gb->layout()->setSpacing(KDialog::spacingHint());
  gb->layout()->setMargin(KDialog::marginHint());

  gl = new TQGridLayout (gb->layout(), 6, 6);
  gl->addRowSpacing(0, 10);

  TQValueVector<TQWidget*> theNotSpecials;

  l = new TQLabel(i18n("Class"), gb );
  gl->addWidget(l, 1, 0);
  theNotSpecials.append( l );

  if (isDir)
    l = new TQLabel( i18n("Show\nEntries"), gb );
  else
    l = new TQLabel( i18n("Read"), gb );
  gl->addWidget (l, 1, 1);
  theNotSpecials.append( l );
  TQString readWhatsThis;
  if (isDir)
    readWhatsThis = i18n("This flag allows viewing the content of the folder.");
  else
    readWhatsThis = i18n("The Read flag allows viewing the content of the file.");
  TQWhatsThis::add(l, readWhatsThis);

  if (isDir)
    l = new TQLabel( i18n("Write\nEntries"), gb );
  else
    l = new TQLabel( i18n("Write"), gb );
  gl->addWidget (l, 1, 2);
  theNotSpecials.append( l );
  TQString writeWhatsThis;
  if (isDir)
    writeWhatsThis = i18n("This flag allows adding, renaming and deleting of files. "
			  "Note that deleting and renaming can be limited using the Sticky flag.");
  else
    writeWhatsThis = i18n("The Write flag allows modifying the content of the file.");
  TQWhatsThis::add(l, writeWhatsThis);

  TQString execWhatsThis;
  if (isDir) {
    l = new TQLabel( i18n("Enter folder", "Enter"), gb );
    execWhatsThis = i18n("Enable this flag to allow entering the folder.");
  }
  else {
    l = new TQLabel( i18n("Exec"), gb );
    execWhatsThis = i18n("Enable this flag to allow executing the file as a program.");
  }
  TQWhatsThis::add(l, execWhatsThis);
  theNotSpecials.append( l );
  // GJ: Add space between normal and special modes
  TQSize size = l->sizeHint();
  size.setWidth(size.width() + 15);
  l->setFixedSize(size);
  gl->addWidget (l, 1, 3);

  l = new TQLabel( i18n("Special"), gb );
  gl->addMultiCellWidget(l, 1, 1, 4, 5);
  TQString specialWhatsThis;
  if (isDir)
    specialWhatsThis = i18n("Special flag. Valid for the whole folder, the exact "
			    "meaning of the flag can be seen in the right hand column.");
  else
    specialWhatsThis = i18n("Special flag. The exact meaning of the flag can be seen "
			    "in the right hand column.");
  TQWhatsThis::add(l, specialWhatsThis);

  cl[0] = new TQLabel( i18n("User"), gb );
  gl->addWidget (cl[0], 2, 0);
  theNotSpecials.append( cl[0] );

  cl[1] = new TQLabel( i18n("Group"), gb );
  gl->addWidget (cl[1], 3, 0);
  theNotSpecials.append( cl[1] );

  cl[2] = new TQLabel( i18n("Others"), gb );
  gl->addWidget (cl[2], 4, 0);
  theNotSpecials.append( cl[2] );

  l = new TQLabel(i18n("Set UID"), gb);
  gl->addWidget(l, 2, 5);
  TQString setUidWhatsThis;
  if (isDir)
    setUidWhatsThis = i18n("If this flag is set, the owner of this folder will be "
			   "the owner of all new files.");
  else
    setUidWhatsThis = i18n("If this file is an executable and the flag is set, it will "
			   "be executed with the permissions of the owner.");
  TQWhatsThis::add(l, setUidWhatsThis);

  l = new TQLabel(i18n("Set GID"), gb);
  gl->addWidget(l, 3, 5);
  TQString setGidWhatsThis;
  if (isDir)
    setGidWhatsThis = i18n("If this flag is set, the group of this folder will be "
			   "set for all new files.");
  else
    setGidWhatsThis = i18n("If this file is an executable and the flag is set, it will "
			   "be executed with the permissions of the group.");
  TQWhatsThis::add(l, setGidWhatsThis);

  l = new TQLabel(i18n("File permission", "Sticky"), gb);
  gl->addWidget(l, 4, 5);
  TQString stickyWhatsThis;
  if (isDir)
    stickyWhatsThis = i18n("If the Sticky flag is set on a folder, only the owner "
			   "and root can delete or rename files. Otherwise everybody "
			   "with write permissions can do this.");
  else
    stickyWhatsThis = i18n("The Sticky flag on a file is ignored on Linux, but may "
			   "be used on some systems");
  TQWhatsThis::add(l, stickyWhatsThis);

  mode_t aPermissions, aPartialPermissions;
  mode_t dummy1, dummy2;

  if (!d->isIrregular) {
    switch (d->pmode) {
    case PermissionsOnlyFiles:
      getPermissionMasks(aPartialPermissions,
			 dummy1,
			 aPermissions,
			 dummy2);
      break;
    case PermissionsOnlyDirs:
    case PermissionsMixed:
      getPermissionMasks(dummy1,
			 aPartialPermissions,
			 dummy2,
			 aPermissions);
      break;
    case PermissionsOnlyLinks:
      aPermissions = UniRead | UniWrite | UniExec | UniSpecial;
      aPartialPermissions = 0;
      break;
    }
  }
  else {
    aPermissions = permissions;
    aPartialPermissions = d->partialPermissions;
  }

  // Draw Checkboxes
  bool allDisable = true;
  TQCheckBox *cba[3][4];
  for (int row = 0; row < 3 ; ++row) {
    for (int col = 0; col < 4; ++col) {
      TQCheckBox *cb = new TQCheckBox( gb );
      if ( col != 3 ) theNotSpecials.append( cb );
      cba[row][col] = cb;
      cb->setChecked(aPermissions & fperm[row][col]);
      if ( d->canChangePermissions )
      {
        allDisable = false;
      }
      if ( aPartialPermissions & fperm[row][col] )
      {
        cb->setTristate();
        cb->setNoChange();
      }
      else if (d->cbRecursive && d->cbRecursive->isChecked())
      {
        cb->setTristate();
      }

      cb->setEnabled( d->canChangePermissions );
      gl->addWidget (cb, row+2, col+1);
      switch(col) {
      case 0:
	TQWhatsThis::add(cb, readWhatsThis);
	break;
      case 1:
	TQWhatsThis::add(cb, writeWhatsThis);
	break;
      case 2:
	TQWhatsThis::add(cb, execWhatsThis);
	break;
      case 3:
	switch(row) {
	case 0:
	  TQWhatsThis::add(cb, setUidWhatsThis);
	  break;
	case 1:
	  TQWhatsThis::add(cb, setGidWhatsThis);
	  break;
	case 2:
	  TQWhatsThis::add(cb, stickyWhatsThis);
	  break;
	}
	break;
      }
    }
  }
  gl->setColStretch(6, 10);

#ifdef USE_POSIX_ACL
  KACLEditWidget *extendedACLs = 0;

  // FIXME make it work with partial entries
  if ( properties->items().count() == 1 ) {
      TQCString pathCString = TQFile::encodeName( properties->item()->url().path() );
      d->fileSystemSupportsACLs = fileSystemSupportsACL( pathCString );
  }
  if ( d->fileSystemSupportsACLs  ) {
    std::for_each( theNotSpecials.begin(), theNotSpecials.end(), std::mem_fun( &TQWidget::hide ) );
    extendedACLs = new KACLEditWidget( mainVBox );
    if ( d->extendedACL.isValid() && d->extendedACL.isExtended() )
      extendedACLs->setACL( d->extendedACL );
    else
      extendedACLs->setACL( KACL( aPermissions ) );

    if ( d->defaultACL.isValid() )
      extendedACLs->setDefaultACL( d->defaultACL );

    if ( properties->items().first()->isDir() )
      extendedACLs->setAllowDefaults( true );
    if ( !d->canChangePermissions )
      extendedACLs->setReadOnly( true );

  }
#endif
  if ( allDisable ) {
    dlg.enableButtonOK( false );
  }

  if (dlg.exec() != KDialogBase::Accepted)
    return;

  mode_t andPermissions = mode_t(~0);
  mode_t orPermissions = 0;
  for (int row = 0; row < 3; ++row)
    for (int col = 0; col < 4; ++col) {
      switch (cba[row][col]->state())
      {
      case TQCheckBox::On:
	orPermissions |= fperm[row][col];
	//fall through
      case TQCheckBox::Off:
	andPermissions &= ~fperm[row][col];
	break;
      default: // NoChange
	break;
      }
    }

  d->isIrregular = false;
  KFileItemList items = properties->items();
  for (KFileItemListIterator it(items); it.current(); ++it) {
    if (isIrregular(((*it)->permissions() & andPermissions) | orPermissions,
		    (*it)->isDir(), (*it)->isLink())) {
      d->isIrregular = true;
      break;
    }
  }

  permissions = orPermissions;
  d->partialPermissions = andPermissions;

#ifdef USE_POSIX_ACL
  // override with the acls, if present
  if ( extendedACLs ) {
    d->extendedACL = extendedACLs->getACL();
    d->defaultACL = extendedACLs->getDefaultACL();
    d->hasExtendedACL = d->extendedACL.isExtended() || d->defaultACL.isValid();
    permissions = d->extendedACL.basePermissions();
    permissions |= ( andPermissions | orPermissions ) & ( S_ISUID|S_ISGID|S_ISVTX );
  }
#endif

  updateAccessControls();
  emit changed();
}

// TQString KFilePermissionsPropsPlugin::tabName () const
// {
//   return i18n ("&Permissions");
// }

KFilePermissionsPropsPlugin::~KFilePermissionsPropsPlugin()
{
  delete d;
}

bool KFilePermissionsPropsPlugin::supports( KFileItemList _items )
{
  KFileItemList::const_iterator it = _items.constBegin();
  for ( ; it != _items.constEnd(); ++it ) {
    KFileItem *item = *it;
    if( !item->user().isEmpty() || !item->group().isEmpty() )
      return true;
  }
  return false;
}

// sets a combo box in the Access Control frame
void KFilePermissionsPropsPlugin::setComboContent(TQComboBox *combo, PermissionsTarget target,
						  mode_t permissions, mode_t partial) {
  combo->clear();
  if (d->pmode == PermissionsOnlyLinks) {
    combo->insertItem(i18n("Link"));
    combo->setCurrentItem(0);
    return;
  }

  mode_t tMask = permissionsMasks[target];
  int textIndex;
  for (textIndex = 0; standardPermissions[textIndex] != (mode_t)-1; textIndex++)
    if ((standardPermissions[textIndex]&tMask) == (permissions&tMask&(UniRead|UniWrite)))
      break;
  Q_ASSERT(standardPermissions[textIndex] != (mode_t)-1); // must not happen, would be irreglar

  for (int i = 0; permissionsTexts[(int)d->pmode][i]; i++)
    combo->insertItem(i18n(permissionsTexts[(int)d->pmode][i]));

  if (partial & tMask & ~UniExec) {
    combo->insertItem(i18n("Varying (No Change)"));
    combo->setCurrentItem(3);
  }
  else
    combo->setCurrentItem(textIndex);
}

// permissions are irregular if they cant be displayed in a combo box.
bool KFilePermissionsPropsPlugin::isIrregular(mode_t permissions, bool isDir, bool isLink) {
  if (isLink)                             // links are always ok
    return false;

  mode_t p = permissions;
  if (p & (S_ISUID | S_ISGID))  // setuid/setgid -> irregular
    return true;
  if (isDir) {
    p &= ~S_ISVTX;          // ignore sticky on dirs

    // check supported flag combinations
    mode_t p0 = p & UniOwner;
    if ((p0 != 0) && (p0 != (S_IRUSR | S_IXUSR)) && (p0 != UniOwner))
      return true;
    p0 = p & UniGroup;
    if ((p0 != 0) && (p0 != (S_IRGRP | S_IXGRP)) && (p0 != UniGroup))
      return true;
    p0 = p & UniOthers;
    if ((p0 != 0) && (p0 != (S_IROTH | S_IXOTH)) && (p0 != UniOthers))
      return true;
    return false;
  }
  if (p & S_ISVTX) // sticky on file -> irregular
    return true;

  // check supported flag combinations
  mode_t p0 = p & UniOwner;
  bool usrXPossible = !p0; // true if this file could be an executable
  if (p0 & S_IXUSR) {
    if ((p0 == S_IXUSR) || (p0 == (S_IWUSR | S_IXUSR)))
      return true;
    usrXPossible = true;
  }
  else if (p0 == S_IWUSR)
    return true;

  p0 = p & UniGroup;
  bool grpXPossible = !p0; // true if this file could be an executable
  if (p0 & S_IXGRP) {
    if ((p0 == S_IXGRP) || (p0 == (S_IWGRP | S_IXGRP)))
      return true;
    grpXPossible = true;
  }
  else if (p0 == S_IWGRP)
    return true;
  if (p0 == 0)
    grpXPossible = true;

  p0 = p & UniOthers;
  bool othXPossible = !p0; // true if this file could be an executable
  if (p0 & S_IXOTH) {
    if ((p0 == S_IXOTH) || (p0 == (S_IWOTH | S_IXOTH)))
      return true;
    othXPossible = true;
  }
  else if (p0 == S_IWOTH)
    return true;

  // check that there either all targets are executable-compatible, or none
  return (p & UniExec) && !(usrXPossible && grpXPossible && othXPossible);
}

// enables/disabled the widgets in the Access Control frame
void KFilePermissionsPropsPlugin::enableAccessControls(bool enable) {
	d->ownerPermCombo->setEnabled(enable);
	d->groupPermCombo->setEnabled(enable);
	d->othersPermCombo->setEnabled(enable);
	if (d->extraCheckbox)
	  d->extraCheckbox->setEnabled(enable);
        if ( d->cbRecursive )
            d->cbRecursive->setEnabled(enable);
}

// updates all widgets in the Access Control frame
void KFilePermissionsPropsPlugin::updateAccessControls() {
  setComboContent(d->ownerPermCombo, PermissionsOwner,
		  permissions, d->partialPermissions);
  setComboContent(d->groupPermCombo, PermissionsGroup,
		  permissions, d->partialPermissions);
  setComboContent(d->othersPermCombo, PermissionsOthers,
		  permissions, d->partialPermissions);

  switch(d->pmode) {
  case PermissionsOnlyLinks:
    enableAccessControls(false);
    break;
  case PermissionsOnlyFiles:
    enableAccessControls(d->canChangePermissions && !d->isIrregular && !d->hasExtendedACL);
    if (d->canChangePermissions)
      d->explanationLabel->setText(d->isIrregular || d->hasExtendedACL ?
				   i18n("This file uses advanced permissions",
				      "These files use advanced permissions.",
				      properties->items().count()) : "");
    if (d->partialPermissions & UniExec) {
      d->extraCheckbox->setTristate();
      d->extraCheckbox->setNoChange();
    }
    else {
      d->extraCheckbox->setTristate(false);
      d->extraCheckbox->setChecked(permissions & UniExec);
    }
    break;
  case PermissionsOnlyDirs:
    enableAccessControls(d->canChangePermissions && !d->isIrregular && !d->hasExtendedACL);
    // if this is a dir, and we can change permissions, don't dis-allow
    // recursive, we can do that for ACL setting.
    if ( d->cbRecursive )
       d->cbRecursive->setEnabled( d->canChangePermissions && !d->isIrregular );

    if (d->canChangePermissions)
      d->explanationLabel->setText(d->isIrregular || d->hasExtendedACL ?
				   i18n("This folder uses advanced permissions.",
				      "These folders use advanced permissions.",
				      properties->items().count()) : "");
    if (d->partialPermissions & S_ISVTX) {
      d->extraCheckbox->setTristate();
      d->extraCheckbox->setNoChange();
    }
    else {
      d->extraCheckbox->setTristate(false);
      d->extraCheckbox->setChecked(permissions & S_ISVTX);
    }
    break;
  case PermissionsMixed:
    enableAccessControls(d->canChangePermissions && !d->isIrregular && !d->hasExtendedACL);
    if (d->canChangePermissions)
      d->explanationLabel->setText(d->isIrregular || d->hasExtendedACL ?
				   i18n("These files use advanced permissions.") : "");
    break;
    if (d->partialPermissions & S_ISVTX) {
      d->extraCheckbox->setTristate();
      d->extraCheckbox->setNoChange();
    }
    else {
      d->extraCheckbox->setTristate(false);
      d->extraCheckbox->setChecked(permissions & S_ISVTX);
    }
    break;
  }
}

// gets masks for files and dirs from the Access Control frame widgets
void KFilePermissionsPropsPlugin::getPermissionMasks(mode_t &andFilePermissions,
						     mode_t &andDirPermissions,
						     mode_t &orFilePermissions,
						     mode_t &orDirPermissions) {
  andFilePermissions = mode_t(~UniSpecial);
  andDirPermissions = mode_t(~(S_ISUID|S_ISGID));
  orFilePermissions = 0;
  orDirPermissions = 0;
  if (d->isIrregular)
    return;

  mode_t m = standardPermissions[d->ownerPermCombo->currentItem()];
  if (m != (mode_t) -1) {
    orFilePermissions |= m & UniOwner;
    if ((m & UniOwner) &&
	((d->pmode == PermissionsMixed) ||
	 ((d->pmode == PermissionsOnlyFiles) && (d->extraCheckbox->state() == TQButton::NoChange))))
      andFilePermissions &= ~(S_IRUSR | S_IWUSR);
    else {
      andFilePermissions &= ~(S_IRUSR | S_IWUSR | S_IXUSR);
      if ((m & S_IRUSR) && (d->extraCheckbox->state() == TQButton::On))
	orFilePermissions |= S_IXUSR;
    }

    orDirPermissions |= m & UniOwner;
    if (m & S_IRUSR)
	orDirPermissions |= S_IXUSR;
    andDirPermissions &= ~(S_IRUSR | S_IWUSR | S_IXUSR);
  }

  m = standardPermissions[d->groupPermCombo->currentItem()];
  if (m != (mode_t) -1) {
    orFilePermissions |= m & UniGroup;
    if ((m & UniGroup) &&
	((d->pmode == PermissionsMixed) ||
	 ((d->pmode == PermissionsOnlyFiles) && (d->extraCheckbox->state() == TQButton::NoChange))))
      andFilePermissions &= ~(S_IRGRP | S_IWGRP);
    else {
      andFilePermissions &= ~(S_IRGRP | S_IWGRP | S_IXGRP);
      if ((m & S_IRGRP) && (d->extraCheckbox->state() == TQButton::On))
	orFilePermissions |= S_IXGRP;
    }

    orDirPermissions |= m & UniGroup;
    if (m & S_IRGRP)
	orDirPermissions |= S_IXGRP;
    andDirPermissions &= ~(S_IRGRP | S_IWGRP | S_IXGRP);
  }

  m = standardPermissions[d->othersPermCombo->currentItem()];
  if (m != (mode_t) -1) {
    orFilePermissions |= m & UniOthers;
    if ((m & UniOthers) &&
	((d->pmode == PermissionsMixed) ||
	 ((d->pmode == PermissionsOnlyFiles) && (d->extraCheckbox->state() == TQButton::NoChange))))
      andFilePermissions &= ~(S_IROTH | S_IWOTH);
    else {
      andFilePermissions &= ~(S_IROTH | S_IWOTH | S_IXOTH);
      if ((m & S_IROTH) && (d->extraCheckbox->state() == TQButton::On))
	orFilePermissions |= S_IXOTH;
    }

    orDirPermissions |= m & UniOthers;
    if (m & S_IROTH)
	orDirPermissions |= S_IXOTH;
    andDirPermissions &= ~(S_IROTH | S_IWOTH | S_IXOTH);
  }

  if (((d->pmode == PermissionsMixed) || (d->pmode == PermissionsOnlyDirs)) &&
      (d->extraCheckbox->state() != TQButton::NoChange)) {
    andDirPermissions &= ~S_ISVTX;
    if (d->extraCheckbox->state() == TQButton::On)
      orDirPermissions |= S_ISVTX;
  }
}

void KFilePermissionsPropsPlugin::applyChanges()
{
  mode_t orFilePermissions;
  mode_t orDirPermissions;
  mode_t andFilePermissions;
  mode_t andDirPermissions;

  if (!d->canChangePermissions)
    return;

  if (!d->isIrregular)
    getPermissionMasks(andFilePermissions,
		       andDirPermissions,
		       orFilePermissions,
		       orDirPermissions);
  else {
    orFilePermissions = permissions;
    andFilePermissions = d->partialPermissions;
    orDirPermissions = permissions;
    andDirPermissions = d->partialPermissions;
  }

  TQString owner, group;
  if (usrEdit)
    owner = usrEdit->text();
  if (grpEdit)
    group = grpEdit->text();
  else if (grpCombo)
    group = grpCombo->currentText();

  if (owner == strOwner)
      owner = TQString::null; // no change

  if (group == strGroup)
      group = TQString::null;

  bool recursive = d->cbRecursive && d->cbRecursive->isChecked();
  bool permissionChange = false;

  KFileItemList files, dirs;
  KFileItemList items = properties->items();
  for (KFileItemListIterator it(items); it.current(); ++it) {
    if ((*it)->isDir()) {
      dirs.append(*it);
      if ((*it)->permissions() != (((*it)->permissions() & andDirPermissions) | orDirPermissions))
	permissionChange = true;
    }
    else if ((*it)->isFile()) {
      files.append(*it);
      if ((*it)->permissions() != (((*it)->permissions() & andFilePermissions) | orFilePermissions))
	permissionChange = true;
    }
  }

  const bool ACLChange = ( d->extendedACL !=  properties->item()->ACL() );
  const bool defaultACLChange = ( d->defaultACL != properties->item()->defaultACL() );

  if ( owner.isEmpty() && group.isEmpty() && !recursive
      && !permissionChange && !ACLChange && !defaultACLChange )
    return;

  TDEIO::Job * job;
  if (files.count() > 0) {
    job = TDEIO::chmod( files, orFilePermissions, ~andFilePermissions,
        owner, group, false );
    if ( ACLChange && d->fileSystemSupportsACLs )
      job->addMetaData( "ACL_STRING", d->extendedACL.isValid()?d->extendedACL.asString():"ACL_DELETE" );
    if ( defaultACLChange && d->fileSystemSupportsACLs )
      job->addMetaData( "DEFAULT_ACL_STRING", d->defaultACL.isValid()?d->defaultACL.asString():"ACL_DELETE" );

    connect( job, TQT_SIGNAL( result( TDEIO::Job * ) ),
        TQT_SLOT( slotChmodResult( TDEIO::Job * ) ) );
    // Wait for job
    TQWidget dummy(0,0,(WFlags)(WType_Dialog|WShowModal));
    tqt_enter_modal(&dummy);
    tqApp->enter_loop();
    tqt_leave_modal(&dummy);
  }
  if (dirs.count() > 0) {
    job = TDEIO::chmod( dirs, orDirPermissions, ~andDirPermissions,
        owner, group, recursive );
    if ( ACLChange && d->fileSystemSupportsACLs )
      job->addMetaData( "ACL_STRING", d->extendedACL.isValid()?d->extendedACL.asString():"ACL_DELETE" );
    if ( defaultACLChange && d->fileSystemSupportsACLs )
      job->addMetaData( "DEFAULT_ACL_STRING", d->defaultACL.isValid()?d->defaultACL.asString():"ACL_DELETE" );

    connect( job, TQT_SIGNAL( result( TDEIO::Job * ) ),
        TQT_SLOT( slotChmodResult( TDEIO::Job * ) ) );
    // Wait for job
    TQWidget dummy(0,0,(WFlags)(WType_Dialog|WShowModal));
    tqt_enter_modal(&dummy);
    tqApp->enter_loop();
    tqt_leave_modal(&dummy);
  }
}

void KFilePermissionsPropsPlugin::slotChmodResult( TDEIO::Job * job )
{
  kdDebug(250) << "KFilePermissionsPropsPlugin::slotChmodResult" << endl;
  if (job->error())
    job->showErrorDialog( d->m_frame );
  // allow apply() to return
  tqApp->exit_loop();
}




class KURLPropsPlugin::KURLPropsPluginPrivate
{
public:
  KURLPropsPluginPrivate()
  {
  }
  ~KURLPropsPluginPrivate()
  {
  }

  TQFrame *m_frame;
};

KURLPropsPlugin::KURLPropsPlugin( KPropertiesDialog *_props )
  : KPropsDlgPlugin( _props )
{
  d = new KURLPropsPluginPrivate;
  d->m_frame = properties->addPage(i18n("U&RL"));
  TQVBoxLayout *layout = new TQVBoxLayout(d->m_frame, 0, KDialog::spacingHint());

  TQLabel *l;
  l = new TQLabel( d->m_frame, "Label_1" );
  l->setText( i18n("URL:") );
  layout->addWidget(l);

  URLEdit = new KURLRequester( d->m_frame, "URL Requester" );
  layout->addWidget(URLEdit);

  TQString path = properties->kurl().path();

  TQFile f( path );
  if ( !f.open( IO_ReadOnly ) ) {
    return;
  }
  f.close();

  KSimpleConfig config( path );
  config.setDesktopGroup();
  URLStr = config.readPathEntry( "URL" );

  KFileItem * item = properties->item();

  if (item && item->mimetype().startsWith("media/builtin-")) {
    URLEdit->setEnabled(false);
  }

  if ( !URLStr.isNull() ) {
    URLEdit->setURL( URLStr );
  }

  connect( URLEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
           this, TQT_SIGNAL( changed() ) );

  layout->addStretch (1);
}

KURLPropsPlugin::~KURLPropsPlugin()
{
  delete d;
}

// TQString KURLPropsPlugin::tabName () const
// {
//   return i18n ("U&RL");
// }

bool KURLPropsPlugin::supports( KFileItemList _items )
{
  if ( _items.count() != 1 )
    return false;
  KFileItem * item = _items.first();
  // check if desktop file
  if ( !KPropsDlgPlugin::isDesktopFile( item ) )
    return false;

  // open file and check type
  KDesktopFile config( item->url().path(), true /* readonly */ );
  return config.hasLinkType();
}

void KURLPropsPlugin::applyChanges()
{
  TQString path = properties->kurl().path();
  KFileItem * item = properties->item();

  if (item && item->mimetype().startsWith("media/builtin-")) {
    return;
  }

  TQFile f( path );
  if ( !f.open( IO_ReadWrite ) ) {
    KMessageBox::sorry( 0, i18n("<qt>Could not save properties. You do not have "
				"sufficient access to write to <b>%1</b>.</qt>").arg(path));
    return;
  }
  f.close();

  KSimpleConfig config( path );
  config.setDesktopGroup();
  config.writeEntry( "Type", TQString::fromLatin1("Link"));
  config.writePathEntry( "URL", URLEdit->url() );
  // Users can't create a Link .desktop file with a Name field,
  // but distributions can. Update the Name field in that case.
  if ( config.hasKey("Name") )
  {
    TQString nameStr = nameFromFileName(properties->kurl().fileName());
    config.writeEntry( "Name", nameStr );
    config.writeEntry( "Name", nameStr, true, false, true );

  }
}


/* ----------------------------------------------------
 *
 * KBindingPropsPlugin
 *
 * -------------------------------------------------- */

class KBindingPropsPlugin::KBindingPropsPluginPrivate
{
public:
  KBindingPropsPluginPrivate()
  {
  }
  ~KBindingPropsPluginPrivate()
  {
  }

  TQFrame *m_frame;
};

KBindingPropsPlugin::KBindingPropsPlugin( KPropertiesDialog *_props ) : KPropsDlgPlugin( _props )
{
  d = new KBindingPropsPluginPrivate;
  d->m_frame = properties->addPage(i18n("A&ssociation"));
  patternEdit = new KLineEdit( d->m_frame, "LineEdit_1" );
  commentEdit = new KLineEdit( d->m_frame, "LineEdit_2" );
  mimeEdit = new KLineEdit( d->m_frame, "LineEdit_3" );

  TQBoxLayout *mainlayout = new TQVBoxLayout(d->m_frame, 0, KDialog::spacingHint());
  TQLabel* tmpQLabel;

  tmpQLabel = new TQLabel( d->m_frame, "Label_1" );
  tmpQLabel->setText(  i18n("Pattern ( example: *.html;*.htm )") );
  tmpQLabel->setMinimumSize(tmpQLabel->sizeHint());
  mainlayout->addWidget(tmpQLabel, 1);

  //patternEdit->setGeometry( 10, 40, 210, 30 );
  //patternEdit->setText( "" );
  patternEdit->setMaxLength( 512 );
  patternEdit->setMinimumSize( patternEdit->sizeHint() );
  patternEdit->setFixedHeight( fontHeight );
  mainlayout->addWidget(patternEdit, 1);

  tmpQLabel = new TQLabel( d->m_frame, "Label_2" );
  tmpQLabel->setText(  i18n("Mime Type") );
  tmpQLabel->setMinimumSize(tmpQLabel->sizeHint());
  mainlayout->addWidget(tmpQLabel, 1);

  //mimeEdit->setGeometry( 10, 160, 210, 30 );
  mimeEdit->setMaxLength( 256 );
  mimeEdit->setMinimumSize( mimeEdit->sizeHint() );
  mimeEdit->setFixedHeight( fontHeight );
  mainlayout->addWidget(mimeEdit, 1);

  tmpQLabel = new TQLabel( d->m_frame, "Label_3" );
  tmpQLabel->setText(  i18n("Comment") );
  tmpQLabel->setMinimumSize(tmpQLabel->sizeHint());
  mainlayout->addWidget(tmpQLabel, 1);

  //commentEdit->setGeometry( 10, 100, 210, 30 );
  commentEdit->setMaxLength( 256 );
  commentEdit->setMinimumSize( commentEdit->sizeHint() );
  commentEdit->setFixedHeight( fontHeight );
  mainlayout->addWidget(commentEdit, 1);

  cbAutoEmbed = new TQCheckBox( i18n("Left click previews"), d->m_frame, "cbAutoEmbed" );
  mainlayout->addWidget(cbAutoEmbed, 1);

  mainlayout->addStretch (10);
  mainlayout->activate();

  TQFile f( _props->kurl().path() );
  if ( !f.open( IO_ReadOnly ) )
    return;
  f.close();

  KSimpleConfig config( _props->kurl().path() );
  config.setDesktopGroup();
  TQString patternStr = config.readEntry( "Patterns" );
  TQString iconStr = config.readEntry( "Icon" );
  TQString commentStr = config.readEntry( "Comment" );
  m_sMimeStr = config.readEntry( "MimeType" );

  if ( !patternStr.isEmpty() )
    patternEdit->setText( patternStr );
  if ( !commentStr.isEmpty() )
    commentEdit->setText( commentStr );
  if ( !m_sMimeStr.isEmpty() )
    mimeEdit->setText( m_sMimeStr );
  cbAutoEmbed->setTristate();
  if ( config.hasKey( "X-TDE-AutoEmbed" ) )
      cbAutoEmbed->setChecked( config.readBoolEntry( "X-TDE-AutoEmbed" ) );
  else
      cbAutoEmbed->setNoChange();

  connect( patternEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
           this, TQT_SIGNAL( changed() ) );
  connect( commentEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
           this, TQT_SIGNAL( changed() ) );
  connect( mimeEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
           this, TQT_SIGNAL( changed() ) );
  connect( cbAutoEmbed, TQT_SIGNAL( toggled( bool ) ),
           this, TQT_SIGNAL( changed() ) );
}

KBindingPropsPlugin::~KBindingPropsPlugin()
{
  delete d;
}

// TQString KBindingPropsPlugin::tabName () const
// {
//   return i18n ("A&ssociation");
// }

bool KBindingPropsPlugin::supports( KFileItemList _items )
{
  if ( _items.count() != 1 )
    return false;
  KFileItem * item = _items.first();
  // check if desktop file
  if ( !KPropsDlgPlugin::isDesktopFile( item ) )
    return false;

  // open file and check type
  KDesktopFile config( item->url().path(), true /* readonly */ );
  return config.hasMimeTypeType();
}

void KBindingPropsPlugin::applyChanges()
{
  TQString path = properties->kurl().path();
  TQFile f( path );

  if ( !f.open( IO_ReadWrite ) )
  {
    KMessageBox::sorry( 0, i18n("<qt>Could not save properties. You do not have "
				"sufficient access to write to <b>%1</b>.</qt>").arg(path));
    return;
  }
  f.close();

  KSimpleConfig config( path );
  config.setDesktopGroup();
  config.writeEntry( "Type", TQString::fromLatin1("MimeType") );

  config.writeEntry( "Patterns",  patternEdit->text() );
  config.writeEntry( "Comment", commentEdit->text() );
  config.writeEntry( "Comment",
		     commentEdit->text(), true, false, true ); // for compat
  config.writeEntry( "MimeType", mimeEdit->text() );
  if ( cbAutoEmbed->state() == TQButton::NoChange )
      config.deleteEntry( "X-TDE-AutoEmbed", false );
  else
      config.writeEntry( "X-TDE-AutoEmbed", cbAutoEmbed->isChecked() );
  config.sync();
}

/* ----------------------------------------------------
 *
 * KDevicePropsPlugin
 *
 * -------------------------------------------------- */

class KDevicePropsPlugin::KDevicePropsPluginPrivate
{
public:
  KDevicePropsPluginPrivate()
  {
  }
  ~KDevicePropsPluginPrivate()
  {
  }

  TQFrame *m_frame;
  TQStringList mountpointlist;
  TQLabel *m_freeSpaceText;
  TQLabel *m_freeSpaceLabel;
  TQProgressBar *m_freeSpaceBar;
};

KDevicePropsPlugin::KDevicePropsPlugin( KPropertiesDialog *_props ) : KPropsDlgPlugin( _props )
{
  d = new KDevicePropsPluginPrivate;
  d->m_frame = properties->addPage(i18n("De&vice"));

  TQStringList devices;
  KMountPoint::List mountPoints = KMountPoint::possibleMountPoints();

  for(KMountPoint::List::ConstIterator it = mountPoints.begin();
      it != mountPoints.end(); ++it)
  {
     KMountPoint *mp = *it;
     TQString mountPoint = mp->mountPoint();
     TQString device = mp->mountedFrom();
     kdDebug()<<"mountPoint :"<<mountPoint<<" device :"<<device<<" mp->mountType() :"<<mp->mountType()<<endl;

     if ((mountPoint != "-") && (mountPoint != "none") && !mountPoint.isEmpty()
          && device != "none")
     {
        devices.append( device + TQString::fromLatin1(" (")
                        + mountPoint + TQString::fromLatin1(")") );
        m_devicelist.append(device);
        d->mountpointlist.append(mountPoint);
     }
  }

  TQGridLayout *layout = new TQGridLayout( d->m_frame, 0, 2, 0,
                                        KDialog::spacingHint());
  layout->setColStretch(1, 1);

  TQLabel* label;
  label = new TQLabel( d->m_frame );
  label->setText( devices.count() == 0 ?
                      i18n("Device (/dev/fd0):") : // old style
                      i18n("Device:") ); // new style (combobox)
  layout->addWidget(label, 0, 0);

  device = new TQComboBox( true, d->m_frame, "ComboBox_device" );
  device->insertStringList( devices );
  layout->addWidget(device, 0, 1);
  connect( device, TQT_SIGNAL( activated( int ) ),
           this, TQT_SLOT( slotActivated( int ) ) );

  readonly = new TQCheckBox( d->m_frame, "CheckBox_readonly" );
  readonly->setText(  i18n("Read only") );
  layout->addWidget(readonly, 1, 1);

  label = new TQLabel( d->m_frame );
  label->setText( i18n("File system:") );
  layout->addWidget(label, 2, 0);

  TQLabel *fileSystem = new TQLabel( d->m_frame );
  layout->addWidget(fileSystem, 2, 1);

  label = new TQLabel( d->m_frame );
  label->setText( devices.count()==0 ?
                      i18n("Mount point (/mnt/floppy):") : // old style
                      i18n("Mount point:")); // new style (combobox)
  layout->addWidget(label, 3, 0);

  mountpoint = new TQLabel( d->m_frame, "LineEdit_mountpoint" );

  layout->addWidget(mountpoint, 3, 1);

  // show disk free
  d->m_freeSpaceText = new TQLabel(i18n("Free disk space:"), d->m_frame );
  layout->addWidget(d->m_freeSpaceText, 4, 0);

  d->m_freeSpaceLabel = new TQLabel( d->m_frame );
  layout->addWidget( d->m_freeSpaceLabel, 4, 1 );

  d->m_freeSpaceBar = new TQProgressBar( d->m_frame, "freeSpaceBar" );
  layout->addMultiCellWidget(d->m_freeSpaceBar, 5, 5, 0, 1);

  // we show it in the slot when we know the values
  d->m_freeSpaceText->hide();
  d->m_freeSpaceLabel->hide();
  d->m_freeSpaceBar->hide();

  KSeparator* sep = new KSeparator( KSeparator::HLine, d->m_frame);
  layout->addMultiCellWidget(sep, 6, 6, 0, 1);

  unmounted = new TDEIconButton( d->m_frame );
  int bsize = 66 + 2 * unmounted->style().pixelMetric(TQStyle::PM_ButtonMargin);
  unmounted->setFixedSize(bsize, bsize);
  unmounted->setIconType(TDEIcon::Desktop, TDEIcon::Device);
  layout->addWidget(unmounted, 7, 0);

  label = new TQLabel( i18n("Unmounted Icon"),  d->m_frame );
  layout->addWidget(label, 7, 1);

  layout->setRowStretch(8, 1);

  TQString path( _props->kurl().path() );

  TQFile f( path );
  if ( !f.open( IO_ReadOnly ) )
    return;
  f.close();

  KSimpleConfig config( path );
  config.setDesktopGroup();
  TQString deviceStr = config.readEntry( "Dev" );
  TQString mountPointStr = config.readEntry( "MountPoint" );
  bool ro = config.readBoolEntry( "ReadOnly", false );
  TQString unmountedStr = config.readEntry( "UnmountIcon" );

  TQString fsType = config.readEntry("FSType");
  fileSystem->setText( (fsType.stripWhiteSpace() != "") ? i18n(fsType.local8Bit()) : "" );

  device->setEditText( deviceStr );
  if ( !deviceStr.isEmpty() ) {
    // Set default options for this device (first matching entry)
    int index = m_devicelist.findIndex(deviceStr);
    if (index != -1)
    {
      //kdDebug(250) << "found it " << index << endl;
      slotActivated( index );
    }
  }

  if ( !mountPointStr.isEmpty() )
  {
    mountpoint->setText( mountPointStr );
    updateInfo();
  }

  readonly->setChecked( ro );

  if ( unmountedStr.isEmpty() )
    unmountedStr = KMimeType::defaultMimeTypePtr()->KServiceType::icon(); // default icon

  unmounted->setIcon( unmountedStr );

  connect( device, TQT_SIGNAL( activated( int ) ),
           this, TQT_SIGNAL( changed() ) );
  connect( device, TQT_SIGNAL( textChanged( const TQString & ) ),
           this, TQT_SIGNAL( changed() ) );
  connect( readonly, TQT_SIGNAL( toggled( bool ) ),
           this, TQT_SIGNAL( changed() ) );
  connect( unmounted, TQT_SIGNAL( iconChanged( TQString ) ),
           this, TQT_SIGNAL( changed() ) );

  connect( device, TQT_SIGNAL( textChanged( const TQString & ) ),
           this, TQT_SLOT( slotDeviceChanged() ) );

  processLockouts();
}

KDevicePropsPlugin::~KDevicePropsPlugin()
{
  delete d;
}

// TQString KDevicePropsPlugin::tabName () const
// {
//   return i18n ("De&vice");
// }

void KDevicePropsPlugin::processLockouts()
{
  if (device->currentText().stripWhiteSpace() != "")
  {
    properties->enableButtonOK(true);
  }
  else
  {
    properties->enableButtonOK(false);
  }
}

void KDevicePropsPlugin::updateInfo()
{
  // we show it in the slot when we know the values
  d->m_freeSpaceText->hide();
  d->m_freeSpaceLabel->hide();
  d->m_freeSpaceBar->hide();

  if ( !mountpoint->text().isEmpty() )
  {
    KDiskFreeSp * job = new KDiskFreeSp;
    connect( job, TQT_SIGNAL( foundMountPoint( const unsigned long&, const unsigned long&,
                                           const unsigned long&, const TQString& ) ),
             this, TQT_SLOT( slotFoundMountPoint( const unsigned long&, const unsigned long&,
                                              const unsigned long&, const TQString& ) ) );

    job->readDF( mountpoint->text() );
  }

  processLockouts();
}

void KDevicePropsPlugin::slotActivated( int index )
{
  // Update mountpoint so that it matches the device that was selected in the combo
  device->setEditText( m_devicelist[index] );
  mountpoint->setText( d->mountpointlist[index] );

  updateInfo();
}

void KDevicePropsPlugin::slotDeviceChanged()
{
  // Update mountpoint so that it matches the typed device
  int index = m_devicelist.findIndex( device->currentText() );
  if ( index != -1 )
    mountpoint->setText( d->mountpointlist[index] );
  else
    mountpoint->setText( TQString::null );

  updateInfo();
}

void KDevicePropsPlugin::slotFoundMountPoint( const unsigned long& kBSize,
                                              const unsigned long& /*kBUsed*/,
                                              const unsigned long& kBAvail,
                                              const TQString& )
{
  d->m_freeSpaceText->show();
  d->m_freeSpaceLabel->show();

  int percUsed = 100 - (int)(100.0 * kBAvail / kBSize);

  d->m_freeSpaceLabel->setText(
      // xgettext:no-c-format  --  Don't warn about translating the %1 out of %2 part.
      i18n("Available space out of total partition size (percent used)", "%1 out of %2 (%3% used)")
      .arg(TDEIO::convertSizeFromKB(kBAvail))
      .arg(TDEIO::convertSizeFromKB(kBSize))
      .arg( 100 - (int)(100.0 * kBAvail / kBSize) ));

  d->m_freeSpaceBar->setProgress(percUsed, 100);
  d->m_freeSpaceBar->show();
}

bool KDevicePropsPlugin::supports( KFileItemList _items )
{
  if ( _items.count() != 1 )
    return false;
  KFileItem * item = _items.first();
  // check if desktop file
  if ( !KPropsDlgPlugin::isDesktopFile( item ) )
    return false;
  // open file and check type
  KDesktopFile config( item->url().path(), true /* readonly */ );
  return config.hasDeviceType();
}

void KDevicePropsPlugin::applyChanges()
{
  TQString path = properties->kurl().path();
  TQFile f( path );
  if ( !f.open( IO_ReadWrite ) )
  {
    KMessageBox::sorry( 0, i18n("<qt>Could not save properties. You do not have sufficient "
				"access to write to <b>%1</b>.</qt>").arg(path));
    return;
  }
  f.close();

  KSimpleConfig config( path );
  config.setDesktopGroup();
  config.writeEntry( "Type", TQString::fromLatin1("FSDevice") );

  config.writeEntry( "Dev", device->currentText() );
  config.writeEntry( "MountPoint", mountpoint->text() );

  config.writeEntry( "UnmountIcon", unmounted->icon() );
  kdDebug(250) << "unmounted->icon() = " << unmounted->icon() << endl;

  config.writeEntry( "ReadOnly", readonly->isChecked() );

  config.sync();
}


/* ----------------------------------------------------
 *
 * KDesktopPropsPlugin
 *
 * -------------------------------------------------- */


KDesktopPropsPlugin::KDesktopPropsPlugin( KPropertiesDialog *_props )
  : KPropsDlgPlugin( _props )
{
  TQFrame *frame = properties->addPage(i18n("&Application"));
  TQVBoxLayout *mainlayout = new TQVBoxLayout( frame, 0, KDialog::spacingHint() );

  w = new KPropertiesDesktopBase(frame);
  mainlayout->addWidget(w);

  bool bKDesktopMode = (TQCString(tqApp->name()) == "kdesktop"); // nasty heh?

  if (bKDesktopMode)
  {
    // Hide Name entry
    w->nameEdit->hide();
    w->nameLabel->hide();
  }

  w->pathEdit->setMode(KFile::Directory | KFile::LocalOnly);
  w->pathEdit->lineEdit()->setAcceptDrops(false);

  connect( w->nameEdit, TQT_SIGNAL( textChanged( const TQString & ) ), this, TQT_SIGNAL( changed() ) );
  connect( w->genNameEdit, TQT_SIGNAL( textChanged( const TQString & ) ), this, TQT_SIGNAL( changed() ) );
  connect( w->commentEdit, TQT_SIGNAL( textChanged( const TQString & ) ), this, TQT_SIGNAL( changed() ) );
  connect( w->commandEdit, TQT_SIGNAL( textChanged( const TQString & ) ), this, TQT_SIGNAL( changed() ) );
  connect( w->pathEdit, TQT_SIGNAL( textChanged( const TQString & ) ), this, TQT_SIGNAL( changed() ) );

  connect( w->browseButton, TQT_SIGNAL( clicked() ), this, TQT_SLOT( slotBrowseExec() ) );
  connect( w->addFiletypeButton, TQT_SIGNAL( clicked() ), this, TQT_SLOT( slotAddFiletype() ) );
  connect( w->delFiletypeButton, TQT_SIGNAL( clicked() ), this, TQT_SLOT( slotDelFiletype() ) );
  connect( w->advancedButton, TQT_SIGNAL( clicked() ), this, TQT_SLOT( slotAdvanced() ) );

  // now populate the page
  TQString path = _props->kurl().path();
  TQFile f( path );
  if ( !f.open( IO_ReadOnly ) )
    return;
  f.close();

  KDesktopFile  config( path );
  TQString nameStr = config.readName();
  TQString genNameStr = config.readGenericName();
  TQString commentStr = config.readComment();
  TQString commandStr = config.readPathEntry( "Exec" );
  if (commandStr.left(12) == "ksystraycmd ")
  {
    commandStr.remove(0, 12);
    m_systrayBool = true;
  }
  else
    m_systrayBool = false;

  m_origCommandStr = commandStr;
  TQString pathStr = config.readPathEntry( "Path" );
  m_terminalBool = config.readBoolEntry( "Terminal" );
  m_terminalOptionStr = config.readEntry( "TerminalOptions" );
  m_suidBool = config.readBoolEntry( "X-TDE-SubstituteUID" ) || config.readBoolEntry( "X-KDE-SubstituteUID" );
  if( config.hasKey( "X-TDE-Username" ))
    m_suidUserStr = config.readEntry( "X-TDE-Username" );
  else
    m_suidUserStr = config.readEntry( "X-KDE-Username" );
  if( config.hasKey( "StartupNotify" ))
    m_startupBool = config.readBoolEntry( "StartupNotify", true );
  else
    m_startupBool = config.readBoolEntry( "X-TDE-StartupNotify", true );
  m_dcopServiceType = config.readEntry("X-DCOP-ServiceType").lower();

  TQStringList mimeTypes = config.readListEntry( "MimeType", ';' );

  if ( nameStr.isEmpty() || bKDesktopMode ) {
    // We'll use the file name if no name is specified
    // because we _need_ a Name for a valid file.
    // But let's do it in apply, not here, so that we pick up the right name.
    setDirty();
  }
  if ( !bKDesktopMode )
    w->nameEdit->setText(nameStr);

  w->genNameEdit->setText( genNameStr );
  w->commentEdit->setText( commentStr );
  w->commandEdit->setText( commandStr );
  w->pathEdit->lineEdit()->setText( pathStr );
  w->filetypeList->setAllColumnsShowFocus(true);

  KMimeType::Ptr defaultMimetype = KMimeType::defaultMimeTypePtr();
  for(TQStringList::ConstIterator it = mimeTypes.begin();
      it != mimeTypes.end(); )
  {
    KMimeType::Ptr p = KMimeType::mimeType(*it);
    ++it;
    TQString preference;
    if (it != mimeTypes.end())
    {
       bool numeric;
       (*it).toInt(&numeric);
       if (numeric)
       {
         preference = *it;
         ++it;
       }
    }
    if (p && (p != defaultMimetype))
    {
       new TQListViewItem(w->filetypeList, p->name(), p->comment(), preference);
    }
  }

}

KDesktopPropsPlugin::~KDesktopPropsPlugin()
{
}

void KDesktopPropsPlugin::slotSelectMimetype()
{
  TQListView *w = (TQListView*)sender();
  TQListViewItem *item = w->firstChild();
  while(item)
  {
     if (item->isSelected())
        w->setSelected(item, false);
     item = item->nextSibling();
  }
}

void KDesktopPropsPlugin::slotAddFiletype()
{
  KDialogBase dlg(w, "KPropertiesMimetypes", true,
                  i18n("Add File Type for %1").arg(properties->kurl().fileName()),
                  KDialogBase::Ok|KDialogBase::Cancel, KDialogBase::Ok);

  KGuiItem okItem(i18n("&Add"), TQString::null /* no icon */,
                  i18n("Add the selected file types to\nthe list of supported file types."),
                  i18n("Add the selected file types to\nthe list of supported file types."));
  dlg.setButtonOK(okItem);

  KPropertiesMimetypeBase *mw = new KPropertiesMimetypeBase(&dlg);

  dlg.setMainWidget(mw);

  {
     mw->listView->setRootIsDecorated(true);
     mw->listView->setSelectionMode(TQListView::Extended);
     mw->listView->setAllColumnsShowFocus(true);
     mw->listView->setFullWidth(true);
     mw->listView->setMinimumSize(500,400);

     connect(mw->listView, TQT_SIGNAL(selectionChanged()),
             this, TQT_SLOT(slotSelectMimetype()));
     connect(mw->listView, TQT_SIGNAL(doubleClicked( TQListViewItem *, const TQPoint &, int )),
             &dlg, TQT_SLOT( slotOk()));

     TQMap<TQString,TQListViewItem*> majorMap;
     TQListViewItem *majorGroup;
     KMimeType::List mimetypes = KMimeType::allMimeTypes();
     TQValueListIterator<KMimeType::Ptr> it(mimetypes.begin());
     for (; it != mimetypes.end(); ++it) {
        TQString mimetype = (*it)->name();
        if (mimetype == KMimeType::defaultMimeType())
           continue;
        int index = mimetype.find("/");
        TQString maj = mimetype.left(index);
        TQString min = mimetype.mid(index+1);

        TQMapIterator<TQString,TQListViewItem*> mit = majorMap.find( maj );
        if ( mit == majorMap.end() ) {
           majorGroup = new TQListViewItem( mw->listView, maj );
           majorGroup->setExpandable(true);
           mw->listView->setOpen(majorGroup, true);
           majorMap.insert( maj, majorGroup );
        }
        else
        {
           majorGroup = mit.data();
        }

        TQListViewItem *item = new TQListViewItem(majorGroup, min, (*it)->comment());
        item->setPixmap(0, (*it)->pixmap(TDEIcon::Small, IconSize(TDEIcon::Small)));
     }
     TQMapIterator<TQString,TQListViewItem*> mit = majorMap.find( "all" );
     if ( mit != majorMap.end())
     {
        mw->listView->setCurrentItem(mit.data());
        mw->listView->ensureItemVisible(mit.data());
     }
  }

  if (dlg.exec() == KDialogBase::Accepted)
  {
     KMimeType::Ptr defaultMimetype = KMimeType::defaultMimeTypePtr();
     TQListViewItem *majorItem = mw->listView->firstChild();
     while(majorItem)
     {
        TQString major = majorItem->text(0);

        TQListViewItem *minorItem = majorItem->firstChild();
        while(minorItem)
        {
           if (minorItem->isSelected())
           {
              TQString mimetype = major + "/" + minorItem->text(0);
              KMimeType::Ptr p = KMimeType::mimeType(mimetype);
              if (p && (p != defaultMimetype))
              {
                 mimetype = p->name();
                 bool found = false;
                 TQListViewItem *item = w->filetypeList->firstChild();
                 while (item)
                 {
                    if (mimetype == item->text(0))
                    {
                       found = true;
                       break;
                    }
                    item = item->nextSibling();
                 }
                 if (!found) {
                    new TQListViewItem(w->filetypeList, p->name(), p->comment());
                    emit changed();
                 }
              }
           }
           minorItem = minorItem->nextSibling();
        }

        majorItem = majorItem->nextSibling();
     }

  }
}

void KDesktopPropsPlugin::slotDelFiletype()
{
  delete w->filetypeList->currentItem();
  emit changed();
}

void KDesktopPropsPlugin::checkCommandChanged()
{
  if (KRun::binaryName(w->commandEdit->text(), true) !=
      KRun::binaryName(m_origCommandStr, true))
  {
    TQString m_origCommandStr = w->commandEdit->text();
    m_dcopServiceType= TQString::null; // Reset
  }
}

void KDesktopPropsPlugin::applyChanges()
{
  kdDebug(250) << "KDesktopPropsPlugin::applyChanges" << endl;
  TQString path = properties->kurl().path();

  TQFile f( path );

  if ( !f.open( IO_ReadWrite ) ) {
    KMessageBox::sorry( 0, i18n("<qt>Could not save properties. You do not have "
				"sufficient access to write to <b>%1</b>.</qt>").arg(path));
    return;
  }
  f.close();

  // If the command is changed we reset certain settings that are strongly
  // coupled to the command.
  checkCommandChanged();

  KSimpleConfig config( path );
  config.setDesktopGroup();
  config.writeEntry( "Type", TQString::fromLatin1("Application"));
  config.writeEntry( "Comment", w->commentEdit->text() );
  config.writeEntry( "Comment", w->commentEdit->text(), true, false, true ); // for compat
  config.writeEntry( "GenericName", w->genNameEdit->text() );
  config.writeEntry( "GenericName", w->genNameEdit->text(), true, false, true ); // for compat

  if (m_systrayBool)
    config.writePathEntry( "Exec", w->commandEdit->text().prepend("ksystraycmd ") );
  else
    config.writePathEntry( "Exec", w->commandEdit->text() );
  config.writePathEntry( "Path", w->pathEdit->lineEdit()->text() );

  // Write mimeTypes
  TQStringList mimeTypes;
  for( TQListViewItem *item = w->filetypeList->firstChild();
       item; item = item->nextSibling() )
  {
    TQString preference = item->text(2);
    mimeTypes.append(item->text(0));
    if (!preference.isEmpty())
       mimeTypes.append(preference);
  }

  config.writeEntry( "MimeType", mimeTypes, ';' );

  if ( !w->nameEdit->isHidden() ) {
      TQString nameStr = w->nameEdit->text();
      config.writeEntry( "Name", nameStr );
      config.writeEntry( "Name", nameStr, true, false, true );
  }

  config.writeEntry("Terminal", m_terminalBool);
  config.writeEntry("TerminalOptions", m_terminalOptionStr);
  config.writeEntry("X-TDE-SubstituteUID", m_suidBool);
  config.writeEntry("X-TDE-Username", m_suidUserStr);
  config.writeEntry("StartupNotify", m_startupBool);
  config.writeEntry("X-DCOP-ServiceType", m_dcopServiceType);
  config.sync();

  // KSycoca update needed?
  TQString sycocaPath = TDEGlobal::dirs()->relativeLocation("apps", path);
  bool updateNeeded = !sycocaPath.startsWith("/");
  if (!updateNeeded)
  {
     sycocaPath = TDEGlobal::dirs()->relativeLocation("xdgdata-apps", path);
     updateNeeded = !sycocaPath.startsWith("/");
  }
  if (updateNeeded)
     KService::rebuildKSycoca(w);
}


void KDesktopPropsPlugin::slotBrowseExec()
{
  KURL f = KFileDialog::getOpenURL( TQString::null,
                                      TQString::null, w );
  if ( f.isEmpty() )
    return;

  if ( !f.isLocalFile()) {
    KMessageBox::sorry(w, i18n("Only executables on local file systems are supported."));
    return;
  }

  TQString path = f.path();
  KRun::shellQuote( path );
  w->commandEdit->setText( path );
}

void KDesktopPropsPlugin::slotAdvanced()
{
  KDialogBase dlg(w, "KPropertiesDesktopAdv", true,
      i18n("Advanced Options for %1").arg(properties->kurl().fileName()),
      KDialogBase::Ok|KDialogBase::Cancel, KDialogBase::Ok);
  KPropertiesDesktopAdvBase *w = new KPropertiesDesktopAdvBase(&dlg);

  dlg.setMainWidget(w);

  // If the command is changed we reset certain settings that are strongly
  // coupled to the command.
  checkCommandChanged();

  // check to see if we use konsole if not do not add the nocloseonexit
  // because we don't know how to do this on other terminal applications
  TDEConfigGroup confGroup( TDEGlobal::config(), TQString::fromLatin1("General") );
  TQString preferredTerminal = confGroup.readPathEntry("TerminalApplication",
						  TQString::fromLatin1("konsole"));

  bool terminalCloseBool = false;

  if (preferredTerminal == "konsole")
  {
     terminalCloseBool = (m_terminalOptionStr.contains( "--noclose" ) > 0);
     w->terminalCloseCheck->setChecked(terminalCloseBool);
     m_terminalOptionStr.replace( "--noclose", "");
  }
  else
  {
     w->terminalCloseCheck->hide();
  }

  w->terminalCheck->setChecked(m_terminalBool);
  w->terminalEdit->setText(m_terminalOptionStr);
  w->terminalCloseCheck->setEnabled(m_terminalBool);
  w->terminalEdit->setEnabled(m_terminalBool);
  w->terminalEditLabel->setEnabled(m_terminalBool);

  w->suidCheck->setChecked(m_suidBool);
  w->suidEdit->setText(m_suidUserStr);
  w->suidEdit->setEnabled(m_suidBool);
  w->suidEditLabel->setEnabled(m_suidBool);

  w->startupInfoCheck->setChecked(m_startupBool);
  w->systrayCheck->setChecked(m_systrayBool);

  if (m_dcopServiceType == "unique")
    w->dcopCombo->setCurrentItem(2);
  else if (m_dcopServiceType == "multi")
    w->dcopCombo->setCurrentItem(1);
  else if (m_dcopServiceType == "wait")
    w->dcopCombo->setCurrentItem(3);
  else
    w->dcopCombo->setCurrentItem(0);

  // Provide username completion up to 1000 users.
  TDECompletion *kcom = new TDECompletion;
  kcom->setOrder(TDECompletion::Sorted);
  struct passwd *pw;
  int i, maxEntries = 1000;
  setpwent();
  for (i=0; ((pw = getpwent()) != 0L) && (i < maxEntries); i++)
    kcom->addItem(TQString::fromLatin1(pw->pw_name));
  endpwent();
  if (i < maxEntries)
  {
    w->suidEdit->setCompletionObject(kcom, true);
    w->suidEdit->setAutoDeleteCompletionObject( true );
    w->suidEdit->setCompletionMode(TDEGlobalSettings::CompletionAuto);
  }
  else
  {
    delete kcom;
  }

  connect( w->terminalEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
           this, TQT_SIGNAL( changed() ) );
  connect( w->terminalCloseCheck, TQT_SIGNAL( toggled( bool ) ),
           this, TQT_SIGNAL( changed() ) );
  connect( w->terminalCheck, TQT_SIGNAL( toggled( bool ) ),
           this, TQT_SIGNAL( changed() ) );
  connect( w->suidCheck, TQT_SIGNAL( toggled( bool ) ),
           this, TQT_SIGNAL( changed() ) );
  connect( w->suidEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
           this, TQT_SIGNAL( changed() ) );
  connect( w->startupInfoCheck, TQT_SIGNAL( toggled( bool ) ),
           this, TQT_SIGNAL( changed() ) );
  connect( w->systrayCheck, TQT_SIGNAL( toggled( bool ) ),
           this, TQT_SIGNAL( changed() ) );
  connect( w->dcopCombo, TQT_SIGNAL( highlighted( int ) ),
           this, TQT_SIGNAL( changed() ) );

  if ( dlg.exec() == TQDialog::Accepted )
  {
    m_terminalOptionStr = w->terminalEdit->text().stripWhiteSpace();
    m_terminalBool = w->terminalCheck->isChecked();
    m_suidBool = w->suidCheck->isChecked();
    m_suidUserStr = w->suidEdit->text().stripWhiteSpace();
    m_startupBool = w->startupInfoCheck->isChecked();
    m_systrayBool = w->systrayCheck->isChecked();

    if (w->terminalCloseCheck->isChecked())
    {
      m_terminalOptionStr.append(" --noclose");
    }

    switch(w->dcopCombo->currentItem())
    {
      case 1:  m_dcopServiceType = "multi"; break;
      case 2:  m_dcopServiceType = "unique"; break;
      case 3:  m_dcopServiceType = "wait"; break;
      default: m_dcopServiceType = "none"; break;
    }
  }
}

bool KDesktopPropsPlugin::supports( KFileItemList _items )
{
  if ( _items.count() != 1 )
    return false;
  KFileItem * item = _items.first();
  // check if desktop file
  if ( !KPropsDlgPlugin::isDesktopFile( item ) )
    return false;
  // open file and check type
  KDesktopFile config( item->url().path(), true /* readonly */ );
  return config.hasApplicationType() && kapp->authorize("run_desktop_files") && kapp->authorize("shell_access");
}

void KPropertiesDialog::virtual_hook( int id, void* data )
{ KDialogBase::virtual_hook( id, data ); }

void KPropsDlgPlugin::virtual_hook( int, void* )
{ /*BASE::virtual_hook( id, data );*/ }





/**
 * The following code is obsolete and only kept for binary compatibility
 * To be removed in KDE 4
 */

class KExecPropsPlugin::KExecPropsPluginPrivate
{
public:
  KExecPropsPluginPrivate()
  {
  }
  ~KExecPropsPluginPrivate()
  {
  }

  TQFrame *m_frame;
  TQCheckBox *nocloseonexitCheck;
};

KExecPropsPlugin::KExecPropsPlugin( KPropertiesDialog *_props )
  : KPropsDlgPlugin( _props )
{
  d = new KExecPropsPluginPrivate;
  d->m_frame = properties->addPage(i18n("E&xecute"));
  TQVBoxLayout * mainlayout = new TQVBoxLayout( d->m_frame, 0,
      KDialog::spacingHint());

  // Now the widgets in the top layout

  TQLabel* l;
  l = new TQLabel( i18n( "Comman&d:" ), d->m_frame );
  mainlayout->addWidget(l);

  TQHBoxLayout * hlayout;
  hlayout = new TQHBoxLayout(KDialog::spacingHint());
  mainlayout->addLayout(hlayout);

  execEdit = new KLineEdit( d->m_frame );
  TQWhatsThis::add(execEdit,i18n(
    "Following the command, you can have several place holders which will be replaced "
    "with the actual values when the actual program is run:\n"
    "%f - a single file name\n"
    "%F - a list of files; use for applications that can open several local files at once\n"
    "%u - a single URL\n"
    "%U - a list of URLs\n"
    "%d - the folder of the file to open\n"
    "%D - a list of folders\n"
    "%i - the icon\n"
    "%m - the mini-icon\n"
    "%c - the caption"));
  hlayout->addWidget(execEdit, 1);

  l->setBuddy( execEdit );

  execBrowse = new TQPushButton( d->m_frame );
  execBrowse->setText( i18n("&Browse...") );
  hlayout->addWidget(execBrowse);

  // The groupbox about swallowing
  TQGroupBox* tmpQGroupBox;
  tmpQGroupBox = new TQGroupBox( i18n("Panel Embedding"), d->m_frame );
  tmpQGroupBox->setColumnLayout( 0, Qt::Horizontal );

  mainlayout->addWidget(tmpQGroupBox);

  TQGridLayout *grid = new TQGridLayout(tmpQGroupBox->layout(), 2, 2);
  grid->setSpacing( KDialog::spacingHint() );
  grid->setColStretch(1, 1);

  l = new TQLabel( i18n( "&Execute on click:" ), tmpQGroupBox );
  grid->addWidget(l, 0, 0);

  swallowExecEdit = new KLineEdit( tmpQGroupBox );
  grid->addWidget(swallowExecEdit, 0, 1);

  l->setBuddy( swallowExecEdit );

  l = new TQLabel( i18n( "&Window title:" ), tmpQGroupBox );
  grid->addWidget(l, 1, 0);

  swallowTitleEdit = new KLineEdit( tmpQGroupBox );
  grid->addWidget(swallowTitleEdit, 1, 1);

  l->setBuddy( swallowTitleEdit );

  // The groupbox about run in terminal

  tmpQGroupBox = new TQGroupBox( d->m_frame );
  tmpQGroupBox->setColumnLayout( 0, Qt::Horizontal );

  mainlayout->addWidget(tmpQGroupBox);

  grid = new TQGridLayout(tmpQGroupBox->layout(), 3, 2);
  grid->setSpacing( KDialog::spacingHint() );
  grid->setColStretch(1, 1);

  terminalCheck = new TQCheckBox( tmpQGroupBox );
  terminalCheck->setText( i18n("&Run in terminal") );
  grid->addMultiCellWidget(terminalCheck, 0, 0, 0, 1);

  // check to see if we use konsole if not do not add the nocloseonexit
  // because we don't know how to do this on other terminal applications
  TDEConfigGroup confGroup( TDEGlobal::config(), TQString::fromLatin1("General") );
  TQString preferredTerminal = confGroup.readPathEntry("TerminalApplication",
						  TQString::fromLatin1("konsole"));

  int posOptions = 1;
  d->nocloseonexitCheck = 0L;
  if (preferredTerminal == "konsole")
  {
    posOptions = 2;
    d->nocloseonexitCheck = new TQCheckBox( tmpQGroupBox );
    d->nocloseonexitCheck->setText( i18n("Do not &close when command exits") );
    grid->addMultiCellWidget(d->nocloseonexitCheck, 1, 1, 0, 1);
  }

  terminalLabel = new TQLabel( i18n( "&Terminal options:" ), tmpQGroupBox );
  grid->addWidget(terminalLabel, posOptions, 0);

  terminalEdit = new KLineEdit( tmpQGroupBox );
  grid->addWidget(terminalEdit, posOptions, 1);

  terminalLabel->setBuddy( terminalEdit );

  // The groupbox about run with substituted uid.

  tmpQGroupBox = new TQGroupBox( d->m_frame );
  tmpQGroupBox->setColumnLayout( 0, Qt::Horizontal );

  mainlayout->addWidget(tmpQGroupBox);

  grid = new TQGridLayout(tmpQGroupBox->layout(), 2, 2);
  grid->setSpacing(KDialog::spacingHint());
  grid->setColStretch(1, 1);

  suidCheck = new TQCheckBox(tmpQGroupBox);
  suidCheck->setText(i18n("Ru&n as a different user"));
  grid->addMultiCellWidget(suidCheck, 0, 0, 0, 1);

  suidLabel = new TQLabel(i18n( "&Username:" ), tmpQGroupBox);
  grid->addWidget(suidLabel, 1, 0);

  suidEdit = new KLineEdit(tmpQGroupBox);
  grid->addWidget(suidEdit, 1, 1);

  suidLabel->setBuddy( suidEdit );

  mainlayout->addStretch(1);

  // now populate the page
  TQString path = _props->kurl().path();
  TQFile f( path );
  if ( !f.open( IO_ReadOnly ) )
    return;
  f.close();

  KSimpleConfig config( path );
  config.setDollarExpansion( false );
  config.setDesktopGroup();
  execStr = config.readPathEntry( "Exec" );
  swallowExecStr = config.readPathEntry( "SwallowExec" );
  swallowTitleStr = config.readEntry( "SwallowTitle" );
  termBool = config.readBoolEntry( "Terminal" );
  termOptionsStr = config.readEntry( "TerminalOptions" );
  suidBool = config.readBoolEntry( "X-TDE-SubstituteUID" );
  suidUserStr = config.readEntry( "X-TDE-Username" );

  if ( !swallowExecStr.isNull() )
    swallowExecEdit->setText( swallowExecStr );
  if ( !swallowTitleStr.isNull() )
    swallowTitleEdit->setText( swallowTitleStr );

  if ( !execStr.isNull() )
    execEdit->setText( execStr );

  if ( d->nocloseonexitCheck )
  {
    d->nocloseonexitCheck->setChecked( (termOptionsStr.contains( "--noclose" ) > 0) );
    termOptionsStr.replace( "--noclose", "");
  }
  if ( !termOptionsStr.isNull() )
    terminalEdit->setText( termOptionsStr );

  terminalCheck->setChecked( termBool );
  enableCheckedEdit();

  suidCheck->setChecked( suidBool );
  suidEdit->setText( suidUserStr );
  enableSuidEdit();

  // Provide username completion up to 1000 users.
  TDECompletion *kcom = new TDECompletion;
  kcom->setOrder(TDECompletion::Sorted);
  struct passwd *pw;
  int i, maxEntries = 1000;
  setpwent();
  for (i=0; ((pw = getpwent()) != 0L) && (i < maxEntries); i++)
    kcom->addItem(TQString::fromLatin1(pw->pw_name));
  endpwent();
  if (i < maxEntries)
  {
    suidEdit->setCompletionObject(kcom, true);
    suidEdit->setAutoDeleteCompletionObject( true );
    suidEdit->setCompletionMode(TDEGlobalSettings::CompletionAuto);
  }
  else
  {
    delete kcom;
  }

  connect( swallowExecEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
           this, TQT_SIGNAL( changed() ) );
  connect( swallowTitleEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
           this, TQT_SIGNAL( changed() ) );
  connect( execEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
           this, TQT_SIGNAL( changed() ) );
  connect( terminalEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
           this, TQT_SIGNAL( changed() ) );
  if (d->nocloseonexitCheck)
    connect( d->nocloseonexitCheck, TQT_SIGNAL( toggled( bool ) ),
           this, TQT_SIGNAL( changed() ) );
  connect( terminalCheck, TQT_SIGNAL( toggled( bool ) ),
           this, TQT_SIGNAL( changed() ) );
  connect( suidCheck, TQT_SIGNAL( toggled( bool ) ),
           this, TQT_SIGNAL( changed() ) );
  connect( suidEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
           this, TQT_SIGNAL( changed() ) );

  connect( execBrowse, TQT_SIGNAL( clicked() ), this, TQT_SLOT( slotBrowseExec() ) );
  connect( terminalCheck, TQT_SIGNAL( clicked() ), this,  TQT_SLOT( enableCheckedEdit() ) );
  connect( suidCheck, TQT_SIGNAL( clicked() ), this,  TQT_SLOT( enableSuidEdit() ) );

}

KExecPropsPlugin::~KExecPropsPlugin()
{
  delete d;
}

void KExecPropsPlugin::enableCheckedEdit()
{
  bool checked = terminalCheck->isChecked();
  terminalLabel->setEnabled( checked );
  if (d->nocloseonexitCheck)
    d->nocloseonexitCheck->setEnabled( checked );
  terminalEdit->setEnabled( checked );
}

void KExecPropsPlugin::enableSuidEdit()
{
  bool checked = suidCheck->isChecked();
  suidLabel->setEnabled( checked );
  suidEdit->setEnabled( checked );
}

bool KExecPropsPlugin::supports( KFileItemList _items )
{
  if ( _items.count() != 1 )
    return false;
  KFileItem * item = _items.first();
  // check if desktop file
  if ( !KPropsDlgPlugin::isDesktopFile( item ) )
    return false;
  // open file and check type
  KDesktopFile config( item->url().path(), true /* readonly */ );
  return config.hasApplicationType() && kapp->authorize("run_desktop_files") && kapp->authorize("shell_access");
}

void KExecPropsPlugin::applyChanges()
{
  kdDebug(250) << "KExecPropsPlugin::applyChanges" << endl;
  TQString path = properties->kurl().path();

  TQFile f( path );

  if ( !f.open( IO_ReadWrite ) ) {
    KMessageBox::sorry( 0, i18n("<qt>Could not save properties. You do not have "
				"sufficient access to write to <b>%1</b>.</qt>").arg(path));
    return;
  }
  f.close();

  KSimpleConfig config( path );
  config.setDesktopGroup();
  config.writeEntry( "Type", TQString::fromLatin1("Application"));
  config.writePathEntry( "Exec", execEdit->text() );
  config.writePathEntry( "SwallowExec", swallowExecEdit->text() );
  config.writeEntry( "SwallowTitle", swallowTitleEdit->text() );
  config.writeEntry( "Terminal", terminalCheck->isChecked() );
  TQString temp = terminalEdit->text();
  if (d->nocloseonexitCheck )
    if ( d->nocloseonexitCheck->isChecked() )
      temp += TQString::fromLatin1("--noclose ");
  temp = temp.stripWhiteSpace();
  config.writeEntry( "TerminalOptions", temp );
  config.writeEntry( "X-TDE-SubstituteUID", suidCheck->isChecked() );
  config.writeEntry( "X-TDE-Username", suidEdit->text() );
}


void KExecPropsPlugin::slotBrowseExec()
{
    KURL f = KFileDialog::getOpenURL( TQString::null,
                                      TQString::null, d->m_frame );
    if ( f.isEmpty() )
        return;

    if ( !f.isLocalFile()) {
        KMessageBox::sorry(d->m_frame, i18n("Only executables on local file systems are supported."));
        return;
    }

    TQString path = f.path();
    KRun::shellQuote( path );
    execEdit->setText( path );
}

class TDEApplicationPropsPlugin::TDEApplicationPropsPluginPrivate
{
public:
  TDEApplicationPropsPluginPrivate()
  {
      m_kdesktopMode = TQCString(tqApp->name()) == "kdesktop"; // nasty heh?
  }
  ~TDEApplicationPropsPluginPrivate()
  {
  }

  TQFrame *m_frame;
  bool m_kdesktopMode;
};

TDEApplicationPropsPlugin::TDEApplicationPropsPlugin( KPropertiesDialog *_props )
  : KPropsDlgPlugin( _props )
{
  d = new TDEApplicationPropsPluginPrivate;
  d->m_frame = properties->addPage(i18n("&Application"));
  TQVBoxLayout *toplayout = new TQVBoxLayout( d->m_frame, 0, KDialog::spacingHint());

  TQIconSet iconSet;
  TQPixmap pixMap;

  addExtensionButton = new TQPushButton( TQString::null, d->m_frame );
  iconSet = SmallIconSet( "back" );
  addExtensionButton->setIconSet( iconSet );
  pixMap = iconSet.pixmap( TQIconSet::Small, TQIconSet::Normal );
  addExtensionButton->setFixedSize( pixMap.width()+8, pixMap.height()+8 );
  connect( addExtensionButton, TQT_SIGNAL( clicked() ),
            TQT_SLOT( slotAddExtension() ) );

  delExtensionButton = new TQPushButton( TQString::null, d->m_frame );
  iconSet = SmallIconSet( "forward" );
  delExtensionButton->setIconSet( iconSet );
  delExtensionButton->setFixedSize( pixMap.width()+8, pixMap.height()+8 );
  connect( delExtensionButton, TQT_SIGNAL( clicked() ),
            TQT_SLOT( slotDelExtension() ) );

  TQLabel *l;

  TQGridLayout *grid = new TQGridLayout(2, 2);
  grid->setColStretch(1, 1);
  toplayout->addLayout(TQT_TQLAYOUT(grid));

  if ( d->m_kdesktopMode )
  {
      // in kdesktop the name field comes from the first tab
      nameEdit = 0L;
  }
  else
  {
      l = new TQLabel(i18n("Name:"), d->m_frame, "Label_4" );
      grid->addWidget(l, 0, 0);

      nameEdit = new KLineEdit( d->m_frame, "LineEdit_3" );
      grid->addWidget(nameEdit, 0, 1);
  }

  l = new TQLabel(i18n("Description:"),  d->m_frame, "Label_5" );
  grid->addWidget(l, 1, 0);

  genNameEdit = new KLineEdit( d->m_frame, "LineEdit_4" );
  grid->addWidget(genNameEdit, 1, 1);

  l = new TQLabel(i18n("Comment:"),  d->m_frame, "Label_3" );
  grid->addWidget(l, 2, 0);

  commentEdit = new KLineEdit( d->m_frame, "LineEdit_2" );
  grid->addWidget(commentEdit, 2, 1);

  l = new TQLabel(i18n("File types:"), d->m_frame);
  toplayout->addWidget(l, 0, AlignLeft);

  grid = new TQGridLayout(4, 3);
  grid->setColStretch(0, 1);
  grid->setColStretch(2, 1);
  grid->setRowStretch( 0, 1 );
  grid->setRowStretch( 3, 1 );
  toplayout->addLayout(TQT_TQLAYOUT(grid), 2);

  extensionsList = new TQListBox( d->m_frame );
  extensionsList->setSelectionMode( TQListBox::Extended );
  grid->addMultiCellWidget(extensionsList, 0, 3, 0, 0);

  grid->addWidget(addExtensionButton, 1, 1);
  grid->addWidget(delExtensionButton, 2, 1);

  availableExtensionsList = new TQListBox( d->m_frame );
  availableExtensionsList->setSelectionMode( TQListBox::Extended );
  grid->addMultiCellWidget(availableExtensionsList, 0, 3, 2, 2);

  TQString path = properties->kurl().path() ;
  TQFile f( path );
  if ( !f.open( IO_ReadOnly ) )
    return;
  f.close();

  KDesktopFile config( path );
  TQString commentStr = config.readComment();
  TQString genNameStr = config.readGenericName();

  TQStringList selectedTypes = config.readListEntry( "X-TDE-ServiceTypes" );
  // For compatibility with KDE 1.x
  selectedTypes += config.readListEntry( "MimeType", ';' );

  TQString nameStr = config.readName();
  if ( nameStr.isEmpty() || d->m_kdesktopMode ) {
    // We'll use the file name if no name is specified
    // because we _need_ a Name for a valid file.
    // But let's do it in apply, not here, so that we pick up the right name.
    setDirty();
  }

  commentEdit->setText( commentStr );
  genNameEdit->setText( genNameStr );
  if ( nameEdit )
      nameEdit->setText( nameStr );

  selectedTypes.sort();
  TQStringList::Iterator sit = selectedTypes.begin();
  for( ; sit != selectedTypes.end(); ++sit ) {
    if ( !((*sit).isEmpty()) )
      extensionsList->insertItem( *sit );
  }

  KMimeType::List mimeTypes = KMimeType::allMimeTypes();
  TQValueListIterator<KMimeType::Ptr> it2 = mimeTypes.begin();
  for ( ; it2 != mimeTypes.end(); ++it2 )
    addMimeType ( (*it2)->name() );

  updateButton();

  connect( extensionsList, TQT_SIGNAL( highlighted( int ) ),
           this, TQT_SLOT( updateButton() ) );
  connect( availableExtensionsList, TQT_SIGNAL( highlighted( int ) ),
           this, TQT_SLOT( updateButton() ) );

  connect( addExtensionButton, TQT_SIGNAL( clicked() ),
           this, TQT_SIGNAL( changed() ) );
  connect( delExtensionButton, TQT_SIGNAL( clicked() ),
           this, TQT_SIGNAL( changed() ) );
  if ( nameEdit )
      connect( nameEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
               this, TQT_SIGNAL( changed() ) );
  connect( commentEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
           this, TQT_SIGNAL( changed() ) );
  connect( genNameEdit, TQT_SIGNAL( textChanged( const TQString & ) ),
           this, TQT_SIGNAL( changed() ) );
  connect( availableExtensionsList, TQT_SIGNAL( selected( int ) ),
           this, TQT_SIGNAL( changed() ) );
  connect( extensionsList, TQT_SIGNAL( selected( int ) ),
           this, TQT_SIGNAL( changed() ) );
}

TDEApplicationPropsPlugin::~TDEApplicationPropsPlugin()
{
  delete d;
}

// TQString TDEApplicationPropsPlugin::tabName () const
// {
//   return i18n ("&Application");
// }

void TDEApplicationPropsPlugin::updateButton()
{
    addExtensionButton->setEnabled(availableExtensionsList->currentItem()>-1);
    delExtensionButton->setEnabled(extensionsList->currentItem()>-1);
}

void TDEApplicationPropsPlugin::addMimeType( const TQString & name )
{
  // Add a mimetype to the list of available mime types if not in the extensionsList

  bool insert = true;

  for ( uint i = 0; i < extensionsList->count(); i++ )
    if ( extensionsList->text( i ) == name )
      insert = false;

  if ( insert )
  {
    availableExtensionsList->insertItem( name );
    availableExtensionsList->sort();
  }
}

bool TDEApplicationPropsPlugin::supports( KFileItemList _items )
{
  // same constraints as KExecPropsPlugin : desktop file with Type = Application
  return KExecPropsPlugin::supports( _items );
}

void TDEApplicationPropsPlugin::applyChanges()
{
  TQString path = properties->kurl().path();

  TQFile f( path );

  if ( !f.open( IO_ReadWrite ) ) {
    KMessageBox::sorry( 0, i18n("<qt>Could not save properties. You do not "
				"have sufficient access to write to <b>%1</b>.</qt>").arg(path));
    return;
  }
  f.close();

  KSimpleConfig config( path );
  config.setDesktopGroup();
  config.writeEntry( "Type", TQString::fromLatin1("Application"));
  config.writeEntry( "Comment", commentEdit->text() );
  config.writeEntry( "Comment", commentEdit->text(), true, false, true ); // for compat
  config.writeEntry( "GenericName", genNameEdit->text() );
  config.writeEntry( "GenericName", genNameEdit->text(), true, false, true ); // for compat

  TQStringList selectedTypes;
  for ( uint i = 0; i < extensionsList->count(); i++ )
    selectedTypes.append( extensionsList->text( i ) );

  config.writeEntry( "MimeType", selectedTypes, ';' );
  config.writeEntry( "X-TDE-ServiceTypes", "" );
  // hmm, actually it should probably be the contrary (but see also typeslistitem.cpp)

  TQString nameStr = nameEdit ? nameEdit->text() : TQString::null;
  if ( nameStr.isEmpty() ) // nothing entered, or widget not existing at all (kdesktop mode)
    nameStr = nameFromFileName(properties->kurl().fileName());

  config.writeEntry( "Name", nameStr );
  config.writeEntry( "Name", nameStr, true, false, true );

  config.sync();
}

void TDEApplicationPropsPlugin::slotAddExtension()
{
  TQListBoxItem *item = availableExtensionsList->firstItem();
  TQListBoxItem *nextItem;

  while ( item )
  {
    nextItem = item->next();

    if ( item->isSelected() )
    {
      extensionsList->insertItem( item->text() );
      availableExtensionsList->removeItem( availableExtensionsList->index( item ) );
    }

    item = nextItem;
  }

  extensionsList->sort();
  updateButton();
}

void TDEApplicationPropsPlugin::slotDelExtension()
{
  TQListBoxItem *item = extensionsList->firstItem();
  TQListBoxItem *nextItem;

  while ( item )
  {
    nextItem = item->next();

    if ( item->isSelected() )
    {
      availableExtensionsList->insertItem( item->text() );
      extensionsList->removeItem( extensionsList->index( item ) );
    }

    item = nextItem;
  }

  availableExtensionsList->sort();
  updateButton();
}



#include "kpropertiesdialog.moc"