File: kdiroperator.cpp

package info (click to toggle)
kde4libs 4%3A4.14.2-5
  • links: PTS, VCS
  • area: main
  • in suites: jessie-kfreebsd
  • size: 82,316 kB
  • sloc: cpp: 761,810; xml: 12,344; ansic: 6,295; java: 4,060; perl: 2,938; yacc: 2,507; python: 1,207; sh: 1,179; ruby: 337; lex: 278; makefile: 29
file content (2650 lines) | stat: -rw-r--r-- 83,184 bytes parent folder | download | duplicates (4)
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
/* This file is part of the KDE libraries
    Copyright (C) 1999,2000 Stephan Kulow <coolo@kde.org>
                  1999,2000,2001,2002,2003 Carsten Pfeiffer <pfeiffer@kde.org>

    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.
*/

#include "kdiroperator.h"
#include <kprotocolmanager.h>
#include "kdirmodel.h"
#include "kdiroperatordetailview_p.h"
#include "kdirsortfilterproxymodel.h"
#include "kfileitem.h"
#include "kfilemetapreview.h"
#include "kpreviewwidgetbase.h"
#include "knewfilemenu.h"

#include <config-kfile.h>

#include <unistd.h>

#include <QtCore/QDir>
#include <QtCore/QRegExp>
#include <QtCore/QTimer>
#include <QtCore/QAbstractItemModel>
#include <QtGui/QApplication>
#include <QtGui/QDialog>
#include <QtGui/QHeaderView>
#include <QtGui/QLabel>
#include <QtGui/QLayout>
#include <QtGui/QListView>
#include <QtGui/QMouseEvent>
#include <QtGui/QTreeView>
#include <QtGui/QPushButton>
#include <QtGui/QProgressBar>
#include <QtGui/QScrollBar>
#include <QtGui/QSplitter>
#include <QtGui/QWheelEvent>

#include <kaction.h>
#include <kapplication.h>
#include <kdebug.h>
#include <kdialog.h>
#include <kdirlister.h>
#include <kfileitemdelegate.h>
#include <kicon.h>
#include <kinputdialog.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kmenu.h>
#include <kstandardaction.h>
#include <kio/job.h>
#include <kio/deletejob.h>
#include <kio/copyjob.h>
#include <kio/jobuidelegate.h>
#include <kio/jobclasses.h>
#include <kio/netaccess.h>
#include <kio/previewjob.h>
#include <kio/renamedialog.h>
#include <kfilepreviewgenerator.h>
#include <krun.h>
#include <kpropertiesdialog.h>
#include <kstandardshortcut.h>
#include <kde_file.h>
#include <kactioncollection.h>
#include <ktoggleaction.h>
#include <kactionmenu.h>
#include <kconfiggroup.h>
#include <kdeversion.h>


template class QHash<QString, KFileItem>;

// QDir::SortByMask is not only undocumented, it also omits QDir::Type which  is another
// sorting mode.
static const int QDirSortMask = QDir::SortByMask | QDir::Type;

/**
 * Default icon view for KDirOperator using
 * custom view options.
 */
class KDirOperatorIconView : public QListView
{
public:
    KDirOperatorIconView(KDirOperator *dirOperator, QWidget *parent = 0);
    virtual ~KDirOperatorIconView();

protected:
    virtual QStyleOptionViewItem viewOptions() const;
    virtual void dragEnterEvent(QDragEnterEvent* event);
    virtual void mousePressEvent(QMouseEvent *event);
    virtual void wheelEvent(QWheelEvent *event);

private:
    KDirOperator *ops;
};

KDirOperatorIconView::KDirOperatorIconView(KDirOperator *dirOperator, QWidget *parent) :
    QListView(parent),
    ops(dirOperator)
{
    setViewMode(QListView::IconMode);
    setFlow(QListView::TopToBottom);
    setResizeMode(QListView::Adjust);
    setSpacing(0);
    setMovement(QListView::Static);
    setDragDropMode(QListView::DragOnly);
    setVerticalScrollMode(QListView::ScrollPerPixel);
    setHorizontalScrollMode(QListView::ScrollPerPixel);
    setEditTriggers(QAbstractItemView::NoEditTriggers);
    setWordWrap(true);
    setIconSize(QSize(KIconLoader::SizeSmall, KIconLoader::SizeSmall));
}

KDirOperatorIconView::~KDirOperatorIconView()
{
}

QStyleOptionViewItem KDirOperatorIconView::viewOptions() const
{
    QStyleOptionViewItem viewOptions = QListView::viewOptions();
    viewOptions.showDecorationSelected = true;
    viewOptions.decorationPosition = ops->decorationPosition();
    if (viewOptions.decorationPosition == QStyleOptionViewItem::Left) {
        viewOptions.displayAlignment = Qt::AlignLeft | Qt::AlignVCenter;
    } else {
        viewOptions.displayAlignment = Qt::AlignCenter;
    }

    return viewOptions;
}

void KDirOperatorIconView::dragEnterEvent(QDragEnterEvent* event)
{
    if (event->mimeData()->hasUrls()) {
        event->acceptProposedAction();
    }
}

void KDirOperatorIconView::mousePressEvent(QMouseEvent *event)
{
    if (!indexAt(event->pos()).isValid()) {
        const Qt::KeyboardModifiers modifiers = QApplication::keyboardModifiers();
        if (!(modifiers & Qt::ShiftModifier) && !(modifiers & Qt::ControlModifier)) {
            clearSelection();
        }
    }

    QListView::mousePressEvent(event);
}

void KDirOperatorIconView::wheelEvent(QWheelEvent *event)
{
    QListView::wheelEvent(event);

    // apply the vertical wheel event to the horizontal scrollbar, as
    // the items are aligned from left to right
    if (event->orientation() == Qt::Vertical) {
        QWheelEvent horizEvent(event->pos(),
                               event->delta(),
                               event->buttons(),
                               event->modifiers(),
                               Qt::Horizontal);
        QApplication::sendEvent(horizontalScrollBar(), &horizEvent);
    }
}

void KDirOperator::keyPressEvent(QKeyEvent *e)
{
    if (!(e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter )) {
        QWidget::keyPressEvent(e);
    }
}

class KDirOperator::Private
{
public:
    Private( KDirOperator *parent );
    ~Private();

    enum InlinePreviewState {
        ForcedToFalse = 0,
        ForcedToTrue,
        NotForced
    };

    // private methods
    bool checkPreviewInternal() const;
    void checkPath(const QString &txt, bool takeFiles = false);
    bool openUrl(const KUrl &url, KDirLister::OpenUrlFlags flags = KDirLister::NoFlags);
    int sortColumn() const;
    Qt::SortOrder sortOrder() const;
    void updateSorting(QDir::SortFlags sort);

    static bool isReadable(const KUrl &url);

    KFile::FileView allViews();

    // private slots
    void _k_slotDetailedView();
    void _k_slotSimpleView();
    void _k_slotTreeView();
    void _k_slotDetailedTreeView();
    void _k_slotToggleHidden(bool);
    void _k_togglePreview(bool);
    void _k_toggleInlinePreviews(bool);
    void _k_slotOpenFileManager();
    void _k_slotSortByName();
    void _k_slotSortBySize();
    void _k_slotSortByDate();
    void _k_slotSortByType();
    void _k_slotSortReversed(bool doReverse);
    void _k_slotToggleDirsFirst();
    void _k_slotToggleIgnoreCase();
    void _k_slotStarted();
    void _k_slotProgress(int);
    void _k_slotShowProgress();
    void _k_slotIOFinished();
    void _k_slotCanceled();
    void _k_slotRedirected(const KUrl&);
    void _k_slotProperties();
    void _k_slotActivated(const QModelIndex&);
    void _k_slotSelectionChanged();
    void _k_openContextMenu(const QPoint&);
    void _k_triggerPreview(const QModelIndex&);
    void _k_showPreview();
    void _k_slotSplitterMoved(int, int);
    void _k_assureVisibleSelection();
    void _k_synchronizeSortingState(int, Qt::SortOrder);
    void _k_slotChangeDecorationPosition();
    void _k_slotExpandToUrl(const QModelIndex&);
    void _k_slotItemsChanged();
    void _k_slotDirectoryCreated(const KUrl&);

    void updateListViewGrid();
    int iconSizeForViewType(QAbstractItemView *itemView) const;

    // private members
    KDirOperator *parent;
    QStack<KUrl*> backStack;    ///< Contains all URLs you can reach with the back button.
    QStack<KUrl*> forwardStack; ///< Contains all URLs you can reach with the forward button.

    QModelIndex lastHoveredIndex;

    KDirLister *dirLister;
    KUrl currUrl;

    KCompletion completion;
    KCompletion dirCompletion;
    bool completeListDirty;
    QDir::SortFlags sorting;
    QStyleOptionViewItem::Position decorationPosition;

    QSplitter *splitter;

    QAbstractItemView *itemView;
    KDirModel *dirModel;
    KDirSortFilterProxyModel *proxyModel;

    KFileItemList pendingMimeTypes;

    // the enum KFile::FileView as an int
    int viewKind;
    int defaultView;

    KFile::Modes mode;
    QProgressBar *progressBar;

    KPreviewWidgetBase *preview;
    KUrl previewUrl;
    int previewWidth;

    bool dirHighlighting;
    bool onlyDoubleClickSelectsFiles;
    QString lastURL; // used for highlighting a directory on cdUp
    QTimer *progressDelayTimer;
    int dropOptions;

    KActionMenu *actionMenu;
    KActionCollection *actionCollection;

    KNewFileMenu *newFileMenu;

    KConfigGroup *configGroup;

    KFilePreviewGenerator *previewGenerator;

    bool showPreviews;
    int iconsZoom;

    bool isSaving;

    KActionMenu *decorationMenu;
    KToggleAction *leftAction;
    KUrl::List itemsToBeSetAsCurrent;
    bool shouldFetchForItems;
    InlinePreviewState inlinePreviewState;
};

KDirOperator::Private::Private(KDirOperator *_parent) :
    parent(_parent),
    dirLister(0),
    decorationPosition(QStyleOptionViewItem::Left),
    splitter(0),
    itemView(0),
    dirModel(0),
    proxyModel(0),
    progressBar(0),
    preview(0),
    previewUrl(),
    previewWidth(0),
    dirHighlighting(false),
    onlyDoubleClickSelectsFiles(!KGlobalSettings::singleClick()),
    progressDelayTimer(0),
    dropOptions(0),
    actionMenu(0),
    actionCollection(0),
    newFileMenu(0),
    configGroup(0),
    previewGenerator(0),
    showPreviews(false),
    iconsZoom(0),
    isSaving(false),
    decorationMenu(0),
    leftAction(0),
    shouldFetchForItems(false),
    inlinePreviewState(NotForced)
{
}

KDirOperator::Private::~Private()
{
    delete itemView;
    itemView = 0;

    // TODO:
    // if (configGroup) {
    //     itemView->writeConfig(configGroup);
    // }

    qDeleteAll(backStack);
    qDeleteAll(forwardStack);
    delete preview;
    preview = 0;

    delete proxyModel;
    proxyModel = 0;
    delete dirModel;
    dirModel = 0;
    dirLister = 0; // deleted by KDirModel
    delete configGroup;
    configGroup = 0;

    delete progressDelayTimer;
    progressDelayTimer = 0;
}

KDirOperator::KDirOperator(const KUrl& _url, QWidget *parent) :
    QWidget(parent),
    d(new Private(this))
{
    d->splitter = new QSplitter(this);
    d->splitter->setChildrenCollapsible(false);
    connect(d->splitter, SIGNAL(splitterMoved(int,int)),
            this, SLOT(_k_slotSplitterMoved(int,int)));

    d->preview = 0;

    d->mode = KFile::File;
    d->viewKind = KFile::Simple;

    if (_url.isEmpty()) { // no dir specified -> current dir
        QString strPath = QDir::currentPath();
        strPath.append(QChar('/'));
        d->currUrl = QUrl::fromLocalFile(strPath);
    } else {
        d->currUrl = _url;
        if (d->currUrl.protocol().isEmpty())
            d->currUrl.setProtocol(QLatin1String("file"));

        d->currUrl.addPath("/"); // make sure we have a trailing slash!
    }

    // We set the direction of this widget to LTR, since even on RTL desktops
    // viewing directory listings in RTL mode makes people's head explode.
    // Is this the correct place? Maybe it should be in some lower level widgets...?
    setLayoutDirection(Qt::LeftToRight);
    setDirLister(new KDirLister());

    connect(&d->completion, SIGNAL(match(QString)),
            SLOT(slotCompletionMatch(QString)));

    d->progressBar = new QProgressBar(this);
    d->progressBar->setObjectName("d->progressBar");
    d->progressBar->adjustSize();
    d->progressBar->move(2, height() - d->progressBar->height() - 2);

    d->progressDelayTimer = new QTimer(this);
    d->progressDelayTimer->setObjectName(QLatin1String("d->progressBar delay timer"));
    connect(d->progressDelayTimer, SIGNAL(timeout()),
            SLOT(_k_slotShowProgress()));

    d->completeListDirty = false;

    // action stuff
    setupActions();
    setupMenu();

    d->sorting = QDir::NoSort;  //so updateSorting() doesn't think nothing has changed
    d->updateSorting(QDir::Name | QDir::DirsFirst);

    setFocusPolicy(Qt::WheelFocus);
}

KDirOperator::~KDirOperator()
{
    resetCursor();
    disconnect(d->dirLister, 0, this, 0);
    delete d;
}


void KDirOperator::setSorting(QDir::SortFlags spec)
{
    d->updateSorting(spec);
}

QDir::SortFlags KDirOperator::sorting() const
{
    return d->sorting;
}

bool KDirOperator::isRoot() const
{
#ifdef Q_WS_WIN
    if (url().isLocalFile()) {
        const QString path = url().toLocalFile();
        if (path.length() == 3)
            return (path[0].isLetter() && path[1] == ':' && path[2] == '/');
        return false;
    } else
#endif
    return url().path() == QString(QLatin1Char('/'));
}

KDirLister *KDirOperator::dirLister() const
{
    return d->dirLister;
}

void KDirOperator::resetCursor()
{
    if (qApp)
        QApplication::restoreOverrideCursor();
    d->progressBar->hide();
}

void KDirOperator::sortByName()
{
    d->updateSorting((d->sorting & ~QDirSortMask) | QDir::Name);
}

void KDirOperator::sortBySize()
{
    d->updateSorting((d->sorting & ~QDirSortMask) | QDir::Size);
}

void KDirOperator::sortByDate()
{
    d->updateSorting((d->sorting & ~QDirSortMask) | QDir::Time);
}

void KDirOperator::sortByType()
{
    d->updateSorting((d->sorting & ~QDirSortMask) | QDir::Type);
}

void KDirOperator::sortReversed()
{
    // toggle it, hence the inversion of current state
    d->_k_slotSortReversed(!(d->sorting & QDir::Reversed));
}

void KDirOperator::toggleDirsFirst()
{
    d->_k_slotToggleDirsFirst();
}

void KDirOperator::toggleIgnoreCase()
{
    if (d->proxyModel != 0) {
        Qt::CaseSensitivity cs = d->proxyModel->sortCaseSensitivity();
        cs = (cs == Qt::CaseSensitive) ? Qt::CaseInsensitive : Qt::CaseSensitive;
        d->proxyModel->setSortCaseSensitivity(cs);
    }
}

void KDirOperator::updateSelectionDependentActions()
{
    const bool hasSelection = (d->itemView != 0) &&
                              d->itemView->selectionModel()->hasSelection();
    d->actionCollection->action("trash")->setEnabled(hasSelection);
    d->actionCollection->action("delete")->setEnabled(hasSelection);
    d->actionCollection->action("properties")->setEnabled(hasSelection);
}

void KDirOperator::setPreviewWidget(KPreviewWidgetBase *w)
{
    const bool showPreview = (w != 0);
    if (showPreview) {
        d->viewKind = (d->viewKind | KFile::PreviewContents);
    } else {
        d->viewKind = (d->viewKind & ~KFile::PreviewContents);
    }

    delete d->preview;
    d->preview = w;

    if (w) {
        d->splitter->addWidget(w);
    }

    KToggleAction *previewAction = static_cast<KToggleAction*>(d->actionCollection->action("preview"));
    previewAction->setEnabled(showPreview);
    previewAction->setChecked(showPreview);
    setView(static_cast<KFile::FileView>(d->viewKind));
}

KFileItemList KDirOperator::selectedItems() const
{
    KFileItemList itemList;
    if (d->itemView == 0) {
        return itemList;
    }

    const QItemSelection selection = d->proxyModel->mapSelectionToSource(d->itemView->selectionModel()->selection());

    const QModelIndexList indexList = selection.indexes();
    foreach(const QModelIndex &index, indexList) {
        KFileItem item = d->dirModel->itemForIndex(index);
        if (!item.isNull()) {
            itemList.append(item);
        }
    }

    return itemList;
}

bool KDirOperator::isSelected(const KFileItem &item) const
{
    if ((item.isNull()) || (d->itemView == 0)) {
        return false;
    }

    const QModelIndex dirIndex = d->dirModel->indexForItem(item);
    const QModelIndex proxyIndex = d->proxyModel->mapFromSource(dirIndex);
    return d->itemView->selectionModel()->isSelected(proxyIndex);
}

int KDirOperator::numDirs() const
{
    return (d->dirLister == 0) ? 0 : d->dirLister->directories().count();
}

int KDirOperator::numFiles() const
{
    return (d->dirLister == 0) ? 0 : d->dirLister->items().count() - numDirs();
}

KCompletion * KDirOperator::completionObject() const
{
    return const_cast<KCompletion *>(&d->completion);
}

KCompletion *KDirOperator::dirCompletionObject() const
{
    return const_cast<KCompletion *>(&d->dirCompletion);
}

KActionCollection * KDirOperator::actionCollection() const
{
    return d->actionCollection;
}

KFile::FileView KDirOperator::Private::allViews() {
    return static_cast<KFile::FileView>(KFile::Simple | KFile::Detail | KFile::Tree | KFile::DetailTree);
}

void KDirOperator::Private::_k_slotDetailedView()
{
    KFile::FileView view = static_cast<KFile::FileView>((viewKind & ~allViews()) | KFile::Detail);
    parent->setView(view);
}

void KDirOperator::Private::_k_slotSimpleView()
{
    KFile::FileView view = static_cast<KFile::FileView>((viewKind & ~allViews()) | KFile::Simple);
    parent->setView(view);
}

void KDirOperator::Private::_k_slotTreeView()
{
    KFile::FileView view = static_cast<KFile::FileView>((viewKind & ~allViews()) | KFile::Tree);
    parent->setView(view);
}

void KDirOperator::Private::_k_slotDetailedTreeView()
{
    KFile::FileView view = static_cast<KFile::FileView>((viewKind & ~allViews()) | KFile::DetailTree);
    parent->setView(view);
}

void KDirOperator::Private::_k_slotToggleHidden(bool show)
{
    dirLister->setShowingDotFiles(show);
    parent->updateDir();
    _k_assureVisibleSelection();
}

void KDirOperator::Private::_k_togglePreview(bool on)
{
    if (on) {
        viewKind = viewKind | KFile::PreviewContents;
        if (preview == 0) {
            preview = new KFileMetaPreview(parent);
            actionCollection->action("preview")->setChecked(true);
            splitter->addWidget(preview);
        }

        preview->show();

        QMetaObject::invokeMethod(parent, "_k_assureVisibleSelection", Qt::QueuedConnection);
        if (itemView != 0) {
            const QModelIndex index = itemView->selectionModel()->currentIndex();
            if (index.isValid()) {
                _k_triggerPreview(index);
            }
        }
    } else if (preview != 0) {
        viewKind = viewKind & ~KFile::PreviewContents;
        preview->hide();
    }
}

void KDirOperator::Private::_k_toggleInlinePreviews(bool show)
{
    if (showPreviews == show) {
        return;
    }

    showPreviews = show;

    if (!previewGenerator) {
        return;
    }

    previewGenerator->setPreviewShown(show);

    if (!show) {
        // remove all generated previews
        QAbstractItemModel *model = dirModel;
        for (int i = 0; i < model->rowCount(); ++i) {
            QModelIndex index = model->index(i, 0);
            const KFileItem item = dirModel->itemForIndex(index);
            const_cast<QAbstractItemModel*>(index.model())->setData(index, KIcon(item.iconName()), Qt::DecorationRole);
        }
    }
}

void KDirOperator::Private::_k_slotOpenFileManager()
{
    new KRun(currUrl, parent);
}

void KDirOperator::Private::_k_slotSortByName()
{
    parent->sortByName();
}

void KDirOperator::Private::_k_slotSortBySize()
{
    parent->sortBySize();
}

void KDirOperator::Private::_k_slotSortByDate()
{
    parent->sortByDate();
}

void KDirOperator::Private::_k_slotSortByType()
{
    parent->sortByType();
}

void KDirOperator::Private::_k_slotSortReversed(bool doReverse)
{
    QDir::SortFlags s = sorting & ~QDir::Reversed;
    if (doReverse) {
        s |= QDir::Reversed;
    }
    updateSorting(s);
}

void KDirOperator::Private::_k_slotToggleDirsFirst()
{
    QDir::SortFlags s = (sorting ^ QDir::DirsFirst);
    updateSorting(s);
}

void KDirOperator::Private::_k_slotToggleIgnoreCase()
{
    // TODO: port to Qt4's QAbstractItemView
    /*if ( !d->fileView )
      return;

    QDir::SortFlags sorting = d->fileView->sorting();
    if ( !KFile::isSortCaseInsensitive( sorting ) )
        d->fileView->setSorting( sorting | QDir::IgnoreCase );
    else
        d->fileView->setSorting( sorting & ~QDir::IgnoreCase );
    d->sorting = d->fileView->sorting();*/
}

void KDirOperator::mkdir()
{
    d->newFileMenu->setPopupFiles(url());
    d->newFileMenu->setViewShowsHiddenFiles(showHiddenFiles());
    d->newFileMenu->createDirectory();
}

bool KDirOperator::mkdir(const QString& directory, bool enterDirectory)
{
    // Creates "directory", relative to the current directory (d->currUrl).
    // The given path may contain any number directories, existent or not.
    // They will all be created, if possible.

    bool writeOk = false;
    bool exists = false;
    KUrl url(d->currUrl);

    const QStringList dirs = directory.split('/', QString::SkipEmptyParts);
    QStringList::ConstIterator it = dirs.begin();

    for (; it != dirs.end(); ++it) {
        url.addPath(*it);
        exists = KIO::NetAccess::exists(url, KIO::NetAccess::DestinationSide, this);
        writeOk = !exists && KIO::NetAccess::mkdir(url, this);
    }

    if (exists) { // url was already existent
        KMessageBox::sorry(d->itemView, i18n("A file or folder named %1 already exists.", url.pathOrUrl()));
    } else if (!writeOk) {
        KMessageBox::sorry(d->itemView, i18n("You do not have permission to "
                                              "create that folder."));
    } else if (enterDirectory) {
        setUrl(url, true);
    }

    return writeOk;
}

KIO::DeleteJob * KDirOperator::del(const KFileItemList& items,
                                   QWidget *parent,
                                   bool ask, bool showProgress)
{
    if (items.isEmpty()) {
        KMessageBox::information(parent,
                                 i18n("You did not select a file to delete."),
                                 i18n("Nothing to Delete"));
        return 0L;
    }

    if (parent == 0) {
        parent = this;
    }

    KUrl::List urls;
    QStringList files;
    foreach (const KFileItem &item, items) {
        const KUrl url = item.url();
        urls.append(url);
        files.append(url.pathOrUrl());
    }

    bool doIt = !ask;
    if (ask) {
        int ret;
        if (items.count() == 1) {
            ret = KMessageBox::warningContinueCancel(parent,
                    i18n("<qt>Do you really want to delete\n <b>'%1'</b>?</qt>" ,
                         files.first()),
                    i18n("Delete File"),
                    KStandardGuiItem::del(),
                    KStandardGuiItem::cancel(), "AskForDelete");
        } else
            ret = KMessageBox::warningContinueCancelList(parent,
                    i18np("Do you really want to delete this item?", "Do you really want to delete these %1 items?", items.count()),
                    files,
                    i18n("Delete Files"),
                    KStandardGuiItem::del(),
                    KStandardGuiItem::cancel(), "AskForDelete");
        doIt = (ret == KMessageBox::Continue);
    }

    if (doIt) {
        KIO::JobFlags flags = showProgress ? KIO::DefaultFlags : KIO::HideProgressInfo;
        KIO::DeleteJob *job = KIO::del(urls, flags);
        job->ui()->setWindow(this);
        job->ui()->setAutoErrorHandlingEnabled(true);
        return job;
    }

    return 0L;
}

void KDirOperator::deleteSelected()
{
    const KFileItemList list = selectedItems();
    if (!list.isEmpty()) {
        del(list, this);
    }
}

KIO::CopyJob * KDirOperator::trash(const KFileItemList& items,
                                   QWidget *parent,
                                   bool ask, bool showProgress)
{
    if (items.isEmpty()) {
        KMessageBox::information(parent,
                                 i18n("You did not select a file to trash."),
                                 i18n("Nothing to Trash"));
        return 0L;
    }

    KUrl::List urls;
    QStringList files;
    foreach (const KFileItem &item, items) {
        const KUrl url = item.url();
        urls.append(url);
        files.append(url.pathOrUrl());
    }

    bool doIt = !ask;
    if (ask) {
        int ret;
        if (items.count() == 1) {
            ret = KMessageBox::warningContinueCancel(parent,
                    i18n("<qt>Do you really want to trash\n <b>'%1'</b>?</qt>" ,
                         files.first()),
                    i18n("Trash File"),
                    KGuiItem(i18nc("to trash", "&Trash"), "user-trash"),
                    KStandardGuiItem::cancel(), "AskForTrash");
        } else
            ret = KMessageBox::warningContinueCancelList(parent,
                    i18np("translators: not called for n == 1", "Do you really want to trash these %1 items?", items.count()),
                    files,
                    i18n("Trash Files"),
                    KGuiItem(i18nc("to trash", "&Trash"), "user-trash"),
                    KStandardGuiItem::cancel(), "AskForTrash");
        doIt = (ret == KMessageBox::Continue);
    }

    if (doIt) {
        KIO::JobFlags flags = showProgress ? KIO::DefaultFlags : KIO::HideProgressInfo;
        KIO::CopyJob *job = KIO::trash(urls, flags);
        job->ui()->setWindow(this);
        job->ui()->setAutoErrorHandlingEnabled(true);
        return job;
    }

    return 0L;
}

KFilePreviewGenerator *KDirOperator::previewGenerator() const
{
    return d->previewGenerator;
}

void KDirOperator::setInlinePreviewShown(bool show)
{
    d->inlinePreviewState = show ? Private::ForcedToTrue : Private::ForcedToFalse;
}

bool KDirOperator::isInlinePreviewShown() const
{
    return d->showPreviews;
}

int KDirOperator::iconsZoom() const
{
    return d->iconsZoom;
}

void KDirOperator::setIsSaving(bool isSaving)
{
    d->isSaving = isSaving;
}

bool KDirOperator::isSaving() const
{
    return d->isSaving;
}

void KDirOperator::trashSelected()
{
    if (d->itemView == 0) {
        return;
    }

    if (QApplication::keyboardModifiers() & Qt::ShiftModifier) {
        deleteSelected();
        return;
    }

    const KFileItemList list = selectedItems();
    if (!list.isEmpty()) {
        trash(list, this);
    }
}

void KDirOperator::setIconsZoom(int _value)
{
    if (d->iconsZoom == _value) {
        return;
    }

    int value = _value;
    value = qMin(100, value);
    value = qMax(0, value);

    d->iconsZoom = value;

    if (!d->previewGenerator) {
        return;
    }

    const int maxSize = KIconLoader::SizeEnormous - KIconLoader::SizeSmall;
    const int val = (maxSize * value / 100) + KIconLoader::SizeSmall;
    d->itemView->setIconSize(QSize(val, val));
    d->updateListViewGrid();
    d->previewGenerator->updatePreviews();

    emit currentIconSizeChanged(value);
}

void KDirOperator::close()
{
    resetCursor();
    d->pendingMimeTypes.clear();
    d->completion.clear();
    d->dirCompletion.clear();
    d->completeListDirty = true;
    d->dirLister->stop();
}

void KDirOperator::Private::checkPath(const QString &, bool /*takeFiles*/) // SLOT
{
#if 0
    // copy the argument in a temporary string
    QString text = _txt;
    // it's unlikely to happen, that at the beginning are spaces, but
    // for the end, it happens quite often, I guess.
    text = text.trimmed();
    // if the argument is no URL (the check is quite fragil) and it's
    // no absolute path, we add the current directory to get a correct url
    if (text.find(':') < 0 && text[0] != '/')
        text.insert(0, d->currUrl);

    // in case we have a selection defined and someone patched the file-
    // name, we check, if the end of the new name is changed.
    if (!selection.isNull()) {
        int position = text.lastIndexOf('/');
        ASSERT(position >= 0); // we already inserted the current d->dirLister in case
        QString filename = text.mid(position + 1, text.length());
        if (filename != selection)
            selection.clear();
    }

    KUrl u(text); // I have to take care of entered URLs
    bool filenameEntered = false;

    if (u.isLocalFile()) {
        // the empty path is kind of a hack
        KFileItem i("", u.toLocalFile());
        if (i.isDir())
            setUrl(text, true);
        else {
            if (takeFiles)
                if (acceptOnlyExisting && !i.isFile())
                    warning("you entered an invalid URL");
                else
                    filenameEntered = true;
        }
    } else
        setUrl(text, true);

    if (filenameEntered) {
        filename_ = u.url();
        emit fileSelected(filename_);

        QApplication::restoreOverrideCursor();

        accept();
    }
#endif
    kDebug(kfile_area) << "TODO KDirOperator::checkPath()";
}

void KDirOperator::setUrl(const KUrl& _newurl, bool clearforward)
{
    KUrl newurl;

    if (!_newurl.isValid())
        newurl = QUrl::fromLocalFile(QDir::homePath());
    else
        newurl = _newurl;

    newurl.adjustPath( KUrl::AddTrailingSlash );

    // already set
    if (newurl.equals(d->currUrl, KUrl::CompareWithoutTrailingSlash))
        return;

    if (!Private::isReadable(newurl)) {
        // maybe newurl is a file? check its parent directory
        newurl.setPath(newurl.directory(KUrl::ObeyTrailingSlash));
        if (newurl.equals(d->currUrl, KUrl::CompareWithoutTrailingSlash))
            return; // parent is current dir, nothing to do (fixes #173454, too)
        KIO::UDSEntry entry;
        bool res = KIO::NetAccess::stat(newurl, entry, this);
        KFileItem i(entry, newurl);
        if ((!res || !Private::isReadable(newurl)) && i.isDir()) {
            resetCursor();
            KMessageBox::error(d->itemView,
                               i18n("The specified folder does not exist "
                                    "or was not readable."));
            return;
        } else if (!i.isDir()) {
            return;
        }
    }

    if (clearforward) {
        // autodelete should remove this one
        d->backStack.push(new KUrl(d->currUrl));
        qDeleteAll(d->forwardStack);
        d->forwardStack.clear();
    }

    d->lastURL = d->currUrl.url(KUrl::RemoveTrailingSlash);
    d->currUrl = newurl;

    pathChanged();
    emit urlEntered(newurl);

    // enable/disable actions
    QAction* forwardAction = d->actionCollection->action("forward");
    forwardAction->setEnabled(!d->forwardStack.isEmpty());

    QAction* backAction = d->actionCollection->action("back");
    backAction->setEnabled(!d->backStack.isEmpty());

    QAction* upAction = d->actionCollection->action("up");
    upAction->setEnabled(!isRoot());

    d->openUrl(newurl);
}

void KDirOperator::updateDir()
{
    QApplication::setOverrideCursor(Qt::WaitCursor);
    d->dirLister->emitChanges();
    QApplication::restoreOverrideCursor();
}

void KDirOperator::rereadDir()
{
    pathChanged();
    d->openUrl(d->currUrl, KDirLister::Reload);
}


bool KDirOperator::Private::openUrl(const KUrl& url, KDirLister::OpenUrlFlags flags)
{
    const bool result = KProtocolManager::supportsListing(url) && dirLister->openUrl(url, flags);
    if (!result)   // in that case, neither completed() nor canceled() will be emitted by KDL
        _k_slotCanceled();

    return result;
}

int KDirOperator::Private::sortColumn() const
{
    int column = KDirModel::Name;
    if (KFile::isSortByDate(sorting)) {
        column = KDirModel::ModifiedTime;
    } else if (KFile::isSortBySize(sorting)) {
        column = KDirModel::Size;
    } else if (KFile::isSortByType(sorting)) {
        column = KDirModel::Type;
    } else {
        Q_ASSERT(KFile::isSortByName(sorting));
    }

    return column;
}

Qt::SortOrder KDirOperator::Private::sortOrder() const
{
    return (sorting & QDir::Reversed) ? Qt::DescendingOrder :
                                        Qt::AscendingOrder;
}

void KDirOperator::Private::updateSorting(QDir::SortFlags sort)
{
    kDebug(kfile_area) << "changing sort flags from"  << sorting << "to" << sort;
    if (sort == sorting) {
        return;
    }

    if ((sorting ^ sort) & QDir::DirsFirst) {
        // The "Folders First" setting has been changed.
        // We need to make sure that the files and folders are really re-sorted.
        // Without the following intermediate "fake resorting",
        // QSortFilterProxyModel::sort(int column, Qt::SortOrder order)
        // would do nothing because neither the column nor the sort order have been changed.
        Qt::SortOrder tmpSortOrder = (sortOrder() == Qt::AscendingOrder ? Qt::DescendingOrder : Qt::AscendingOrder);
        proxyModel->sort(sortOrder(), tmpSortOrder);
        proxyModel->setSortFoldersFirst(sort & QDir::DirsFirst);
    }

    sorting = sort;
    parent->updateSortActions();
    proxyModel->sort(sortColumn(), sortOrder());

    // TODO: The headers from QTreeView don't take care about a sorting
    // change of the proxy model hence they must be updated the manually.
    // This is done here by a qobject_cast, but it would be nicer to:
    // - provide a signal 'sortingChanged()'
    // - connect KDirOperatorDetailView() with this signal and update the
    //   header internally
    QTreeView* treeView = qobject_cast<QTreeView*>(itemView);
    if (treeView != 0) {
        QHeaderView* headerView = treeView->header();
        headerView->blockSignals(true);
        headerView->setSortIndicator(sortColumn(), sortOrder());
        headerView->blockSignals(false);
    }

    _k_assureVisibleSelection();
}

// Protected
void KDirOperator::pathChanged()
{
    if (d->itemView == 0)
        return;

    d->pendingMimeTypes.clear();
    //d->fileView->clear(); TODO
    d->completion.clear();
    d->dirCompletion.clear();

    // it may be, that we weren't ready at this time
    QApplication::restoreOverrideCursor();

    // when KIO::Job emits finished, the slot will restore the cursor
    QApplication::setOverrideCursor(Qt::WaitCursor);

    if (!Private::isReadable(d->currUrl)) {
        KMessageBox::error(d->itemView,
                           i18n("The specified folder does not exist "
                                "or was not readable."));
        if (d->backStack.isEmpty())
            home();
        else
            back();
    }
}

void KDirOperator::Private::_k_slotRedirected(const KUrl& newURL)
{
    currUrl = newURL;
    pendingMimeTypes.clear();
    completion.clear();
    dirCompletion.clear();
    completeListDirty = true;
    emit parent->urlEntered(newURL);
}

// Code pinched from kfm then hacked
void KDirOperator::back()
{
    if (d->backStack.isEmpty())
        return;

    d->forwardStack.push(new KUrl(d->currUrl));

    KUrl *s = d->backStack.pop();

    setUrl(*s, false);
    delete s;
}

// Code pinched from kfm then hacked
void KDirOperator::forward()
{
    if (d->forwardStack.isEmpty())
        return;

    d->backStack.push(new KUrl(d->currUrl));

    KUrl *s = d->forwardStack.pop();
    setUrl(*s, false);
    delete s;
}

KUrl KDirOperator::url() const
{
    return d->currUrl;
}

void KDirOperator::cdUp()
{
    KUrl tmp(d->currUrl);
    tmp.cd(QLatin1String(".."));
    setUrl(tmp, true);
}

void KDirOperator::home()
{
    KUrl u = QUrl::fromLocalFile(QDir::homePath());
    setUrl(u, true);
}

void KDirOperator::clearFilter()
{
    d->dirLister->setNameFilter(QString());
    d->dirLister->clearMimeFilter();
    checkPreviewSupport();
}

void KDirOperator::setNameFilter(const QString& filter)
{
    d->dirLister->setNameFilter(filter);
    checkPreviewSupport();
}

QString KDirOperator::nameFilter() const
{
    return d->dirLister->nameFilter();
}

void KDirOperator::setMimeFilter(const QStringList& mimetypes)
{
    d->dirLister->setMimeFilter(mimetypes);
    checkPreviewSupport();
}

QStringList KDirOperator::mimeFilter() const
{
    return d->dirLister->mimeFilters();
}

void KDirOperator::setNewFileMenuSupportedMimeTypes(const QStringList& mimeTypes)
{
    d->newFileMenu->setSupportedMimeTypes(mimeTypes);
}

QStringList KDirOperator::newFileMenuSupportedMimeTypes() const
{
    return d->newFileMenu->supportedMimeTypes();
}

bool KDirOperator::checkPreviewSupport()
{
    KToggleAction *previewAction = static_cast<KToggleAction*>(d->actionCollection->action("preview"));

    bool hasPreviewSupport = false;
    KConfigGroup cg(KGlobal::config(), ConfigGroup);
    if (cg.readEntry("Show Default Preview", true))
        hasPreviewSupport = d->checkPreviewInternal();

    previewAction->setEnabled(hasPreviewSupport);
    return hasPreviewSupport;
}

void KDirOperator::activatedMenu(const KFileItem &item, const QPoint &pos)
{
    Q_UNUSED(item);
    updateSelectionDependentActions();

    d->newFileMenu->setPopupFiles(url());
    d->newFileMenu->setViewShowsHiddenFiles(showHiddenFiles());
    d->newFileMenu->checkUpToDate();

    emit contextMenuAboutToShow( item, d->actionMenu->menu() );

    d->actionMenu->menu()->exec(pos);
}

void KDirOperator::changeEvent(QEvent *event)
{
    QWidget::changeEvent(event);
}

bool KDirOperator::eventFilter(QObject *watched, QEvent *event)
{
    Q_UNUSED(watched);

    // If we are not hovering any items, check if there is a current index
    // set. In that case, we show the preview of that item.
    switch(event->type()) {
        case QEvent::MouseMove: {
                if (d->preview && !d->preview->isHidden()) {
                    const QModelIndex hoveredIndex = d->itemView->indexAt(d->itemView->viewport()->mapFromGlobal(QCursor::pos()));

                    if (d->lastHoveredIndex == hoveredIndex)
                        return QWidget::eventFilter(watched, event);

                    d->lastHoveredIndex = hoveredIndex;

                    const QModelIndex focusedIndex = d->itemView->selectionModel() ? d->itemView->selectionModel()->currentIndex()
                                                                                : QModelIndex();

                    if (!hoveredIndex.isValid() && focusedIndex.isValid() &&
                        d->itemView->selectionModel()->isSelected(focusedIndex) &&
                        (d->lastHoveredIndex != focusedIndex)) {
                        const QModelIndex sourceFocusedIndex = d->proxyModel->mapToSource(focusedIndex);
                        const KFileItem item = d->dirModel->itemForIndex(sourceFocusedIndex);
                        if (!item.isNull()) {
                            d->preview->showPreview(item.url());
                        }
                    }
                }
            }
            break;
        case QEvent::MouseButtonRelease: {
                if (d->preview != 0 && !d->preview->isHidden()) {
                    const QModelIndex hoveredIndex = d->itemView->indexAt(d->itemView->viewport()->mapFromGlobal(QCursor::pos()));
                    const QModelIndex focusedIndex = d->itemView->selectionModel() ? d->itemView->selectionModel()->currentIndex()
                                                                                : QModelIndex();

                    if (((!focusedIndex.isValid()) ||
                        !d->itemView->selectionModel()->isSelected(focusedIndex)) &&
                        (!hoveredIndex.isValid())) {
                        d->preview->clearPreview();
                    }
                }
            }
            break;
        case QEvent::Wheel: {
                QWheelEvent *evt = static_cast<QWheelEvent*>(event);
                if (evt->modifiers() & Qt::ControlModifier) {
                    if (evt->delta() > 0) {
                        setIconsZoom(d->iconsZoom + 10);
                    } else {
                        setIconsZoom(d->iconsZoom - 10);
                    }
                    return true;
                }
            }
            break;
        default:
            break;
    }

    return QWidget::eventFilter(watched, event);
}

bool KDirOperator::Private::checkPreviewInternal() const
{
    const QStringList supported = KIO::PreviewJob::supportedMimeTypes();
    // no preview support for directories?
    if (parent->dirOnlyMode() && supported.indexOf("inode/directory") == -1)
        return false;

    QStringList mimeTypes = dirLister->mimeFilters();
    const QStringList nameFilter = dirLister->nameFilter().split(' ', QString::SkipEmptyParts);

    if (mimeTypes.isEmpty() && nameFilter.isEmpty() && !supported.isEmpty())
        return true;
    else {
        QRegExp r;
        r.setPatternSyntax(QRegExp::Wildcard);   // the "mimetype" can be "image/*"

        if (!mimeTypes.isEmpty()) {
            QStringList::ConstIterator it = supported.begin();

            for (; it != supported.end(); ++it) {
                r.setPattern(*it);

                QStringList result = mimeTypes.filter(r);
                if (!result.isEmpty()) {   // matches! -> we want previews
                    return true;
                }
            }
        }

        if (!nameFilter.isEmpty()) {
            // find the mimetypes of all the filter-patterns
            QStringList::const_iterator it1 = nameFilter.begin();
            for (; it1 != nameFilter.end(); ++it1) {
                if ((*it1) == "*") {
                    return true;
                }

                KMimeType::Ptr mt = KMimeType::findByPath(*it1, 0, true /*fast mode, no file contents exist*/);
                if (!mt)
                    continue;
                QString mime = mt->name();

                // the "mimetypes" we get from the PreviewJob can be "image/*"
                // so we need to check in wildcard mode
                QStringList::ConstIterator it2 = supported.begin();
                for (; it2 != supported.end(); ++it2) {
                    r.setPattern(*it2);
                    if (r.indexIn(mime) != -1) {
                        return true;
                    }
                }
            }
        }
    }

    return false;
}

QAbstractItemView* KDirOperator::createView(QWidget* parent, KFile::FileView viewKind)
{
    QAbstractItemView *itemView = 0;
    if (KFile::isDetailView(viewKind) || KFile::isTreeView(viewKind) || KFile::isDetailTreeView(viewKind)) {
        KDirOperatorDetailView *detailView = new KDirOperatorDetailView(parent);
        detailView->setViewMode(viewKind);
        itemView = detailView;
    } else {
        itemView = new KDirOperatorIconView(this, parent);
    }

    return itemView;
}

void KDirOperator::setAcceptDrops(bool b)
{
    // TODO:
    //if (d->fileView)
    //   d->fileView->widget()->setAcceptDrops(b);
    QWidget::setAcceptDrops(b);
}

void KDirOperator::setDropOptions(int options)
{
    d->dropOptions = options;
    // TODO:
    //if (d->fileView)
    //   d->fileView->setDropOptions(options);
}

void KDirOperator::setView(KFile::FileView viewKind)
{
    bool preview = (KFile::isPreviewInfo(viewKind) || KFile::isPreviewContents(viewKind));

    if (viewKind == KFile::Default) {
        if (KFile::isDetailView((KFile::FileView)d->defaultView)) {
            viewKind = KFile::Detail;
        } else if (KFile::isTreeView((KFile::FileView)d->defaultView)) {
            viewKind = KFile::Tree;
        } else if (KFile::isDetailTreeView((KFile::FileView)d->defaultView)) {
            viewKind = KFile::DetailTree;
        } else {
            viewKind = KFile::Simple;
        }

        const KFile::FileView defaultViewKind = static_cast<KFile::FileView>(d->defaultView);
        preview = (KFile::isPreviewInfo(defaultViewKind) || KFile::isPreviewContents(defaultViewKind))
                  && d->actionCollection->action("preview")->isEnabled();
    }

    d->viewKind = static_cast<int>(viewKind);
    viewKind = static_cast<KFile::FileView>(d->viewKind);

    QAbstractItemView *newView = createView(this, viewKind);
    setView(newView);

    d->_k_togglePreview(preview);
}

QAbstractItemView * KDirOperator::view() const
{
    return d->itemView;
}

KFile::Modes KDirOperator::mode() const
{
    return d->mode;
}

void KDirOperator::setMode(KFile::Modes mode)
{
    if (d->mode == mode)
        return;

    d->mode = mode;

    d->dirLister->setDirOnlyMode(dirOnlyMode());

    // reset the view with the different mode
    if (d->itemView != 0)
    setView(static_cast<KFile::FileView>(d->viewKind));
}

void KDirOperator::setView(QAbstractItemView *view)
{
    if (view == d->itemView) {
        return;
    }

    // TODO: do a real timer and restart it after that
    d->pendingMimeTypes.clear();
    const bool listDir = (d->itemView == 0);

    if (d->mode & KFile::Files) {
        view->setSelectionMode(QAbstractItemView::ExtendedSelection);
    } else {
        view->setSelectionMode(QAbstractItemView::SingleSelection);
    }

    QItemSelectionModel *selectionModel = 0;
    if ((d->itemView != 0) && d->itemView->selectionModel()->hasSelection()) {
        // remember the selection of the current item view and apply this selection
        // to the new view later
        const QItemSelection selection = d->itemView->selectionModel()->selection();
        selectionModel = new QItemSelectionModel(d->proxyModel, this);
        selectionModel->select(selection, QItemSelectionModel::Select);
    }

    setFocusProxy(0);
    delete d->itemView;
    d->itemView = view;
    d->itemView->setModel(d->proxyModel);
    setFocusProxy(d->itemView);

    view->viewport()->installEventFilter(this);

    KFileItemDelegate *delegate = new KFileItemDelegate(d->itemView);
    d->itemView->setItemDelegate(delegate);
    d->itemView->viewport()->setAttribute(Qt::WA_Hover);
    d->itemView->setContextMenuPolicy(Qt::CustomContextMenu);
    d->itemView->setMouseTracking(true);
    //d->itemView->setDropOptions(d->dropOptions);

    // first push our settings to the view, then listen for changes from the view
    QTreeView* treeView = qobject_cast<QTreeView*>(d->itemView);
    if (treeView) {
        QHeaderView* headerView = treeView->header();
        headerView->setSortIndicator(d->sortColumn(), d->sortOrder());
        connect(headerView, SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)),
                this, SLOT(_k_synchronizeSortingState(int,Qt::SortOrder)));
    }

    connect(d->itemView, SIGNAL(activated(QModelIndex)),
            this, SLOT(_k_slotActivated(QModelIndex)));
    connect(d->itemView, SIGNAL(customContextMenuRequested(QPoint)),
            this, SLOT(_k_openContextMenu(QPoint)));
    connect(d->itemView, SIGNAL(entered(QModelIndex)),
            this, SLOT(_k_triggerPreview(QModelIndex)));

    updateViewActions();
    d->splitter->insertWidget(0, d->itemView);

    d->splitter->resize(size());
    d->itemView->show();

    if (listDir) {
        QApplication::setOverrideCursor(Qt::WaitCursor);
        d->openUrl(d->currUrl);
    }

    if (selectionModel != 0) {
        d->itemView->setSelectionModel(selectionModel);
        QMetaObject::invokeMethod(this, "_k_assureVisibleSelection", Qt::QueuedConnection);
    }

    connect(d->itemView->selectionModel(),
            SIGNAL(currentChanged(QModelIndex,QModelIndex)),
            this, SLOT(_k_triggerPreview(QModelIndex)));
    connect(d->itemView->selectionModel(),
            SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
            this, SLOT(_k_slotSelectionChanged()));

    // if we cannot cast it to a QListView, disable the "Icon Position" menu. Note that this check
    // needs to be done here, and not in createView, since we can be set an external view
    d->decorationMenu->setEnabled(qobject_cast<QListView*>(d->itemView));

    d->shouldFetchForItems = qobject_cast<QTreeView*>(view);
    if (d->shouldFetchForItems) {
        connect(d->dirModel, SIGNAL(expand(QModelIndex)), this, SLOT(_k_slotExpandToUrl(QModelIndex)));
    } else {
        d->itemsToBeSetAsCurrent.clear();
    }

    const bool previewForcedToTrue = d->inlinePreviewState == Private::ForcedToTrue;
    const bool previewShown = d->inlinePreviewState == Private::NotForced ? d->showPreviews : previewForcedToTrue;
    d->previewGenerator = new KFilePreviewGenerator(d->itemView);
    const int maxSize = KIconLoader::SizeEnormous - KIconLoader::SizeSmall;
    const int val = (maxSize * d->iconsZoom / 100) + KIconLoader::SizeSmall;
    d->itemView->setIconSize(previewForcedToTrue ? QSize(KIconLoader::SizeHuge, KIconLoader::SizeHuge) : QSize(val, val));
    d->previewGenerator->setPreviewShown(previewShown);
    d->actionCollection->action("inline preview")->setChecked(previewShown);

    // ensure we change everything needed
    d->_k_slotChangeDecorationPosition();

    emit viewChanged(view);

    const int zoom = previewForcedToTrue ? (KIconLoader::SizeHuge - KIconLoader::SizeSmall + 1) * 100 / maxSize : d->iconSizeForViewType(view);

    // this will make d->iconsZoom be updated, since setIconsZoom slot will be called
    emit currentIconSizeChanged(zoom);
}

void KDirOperator::setDirLister(KDirLister *lister)
{
    if (lister == d->dirLister)   // sanity check
        return;

    delete d->dirModel;
    d->dirModel = 0;

    delete d->proxyModel;
    d->proxyModel = 0;

    //delete d->dirLister; // deleted by KDirModel already, which took ownership
    d->dirLister = lister;

    d->dirModel = new KDirModel();
    d->dirModel->setDirLister(d->dirLister);
    d->dirModel->setDropsAllowed(KDirModel::DropOnDirectory);

    d->shouldFetchForItems = qobject_cast<QTreeView*>(d->itemView);
    if (d->shouldFetchForItems) {
        connect(d->dirModel, SIGNAL(expand(QModelIndex)), this, SLOT(_k_slotExpandToUrl(QModelIndex)));
    } else {
        d->itemsToBeSetAsCurrent.clear();
    }

    d->proxyModel = new KDirSortFilterProxyModel(this);
    d->proxyModel->setSourceModel(d->dirModel);

    d->dirLister->setAutoUpdate(true);
    d->dirLister->setDelayedMimeTypes(true);

    QWidget* mainWidget = topLevelWidget();
    d->dirLister->setMainWindow(mainWidget);
    kDebug(kfile_area) << "mainWidget=" << mainWidget;

    connect(d->dirLister, SIGNAL(percent(int)),
            SLOT(_k_slotProgress(int)));
    connect(d->dirLister, SIGNAL(started(KUrl)), SLOT(_k_slotStarted()));
    connect(d->dirLister, SIGNAL(completed()), SLOT(_k_slotIOFinished()));
    connect(d->dirLister, SIGNAL(canceled()), SLOT(_k_slotCanceled()));
    connect(d->dirLister, SIGNAL(redirection(KUrl)),
            SLOT(_k_slotRedirected(KUrl)));
    connect(d->dirLister, SIGNAL(newItems(KFileItemList)), SLOT(_k_slotItemsChanged()));
    connect(d->dirLister, SIGNAL(itemsDeleted(KFileItemList)), SLOT(_k_slotItemsChanged()));
    connect(d->dirLister, SIGNAL(itemsFilteredByMime(KFileItemList)), SLOT(_k_slotItemsChanged()));
    connect(d->dirLister, SIGNAL(clear()), SLOT(_k_slotItemsChanged()));
}

void KDirOperator::selectDir(const KFileItem &item)
{
    setUrl(item.targetUrl(), true);
}

void KDirOperator::selectFile(const KFileItem &item)
{
    QApplication::restoreOverrideCursor();

    emit fileSelected(item);
}

void KDirOperator::highlightFile(const KFileItem &item)
{
    if ((d->preview != 0 && !d->preview->isHidden()) && !item.isNull()) {
        d->preview->showPreview(item.url());
    }

    emit fileHighlighted(item);
}

void KDirOperator::setCurrentItem(const QString& url)
{
    kDebug(kfile_area);

    KFileItem item = d->dirLister->findByUrl(url);
    if (d->shouldFetchForItems && item.isNull()) {
        d->itemsToBeSetAsCurrent << url;
        d->dirModel->expandToUrl(url);
        return;
    }

    setCurrentItem(item);
}

void KDirOperator::setCurrentItem(const KFileItem& item)
{
    kDebug(kfile_area);

    if (!d->itemView) {
        return;
    }

    QItemSelectionModel *selModel = d->itemView->selectionModel();
    if (selModel) {
        selModel->clear();
        if (!item.isNull()) {
            const QModelIndex dirIndex = d->dirModel->indexForItem(item);
            const QModelIndex proxyIndex = d->proxyModel->mapFromSource(dirIndex);
            selModel->setCurrentIndex(proxyIndex, QItemSelectionModel::Select);
        }
    }
}

void KDirOperator::setCurrentItems(const QStringList& urls)
{
    kDebug(kfile_area);

    if (!d->itemView) {
        return;
    }

    KFileItemList itemList;
    foreach (const QString &url, urls) {
        KFileItem item = d->dirLister->findByUrl(url);
        if (d->shouldFetchForItems && item.isNull()) {
            d->itemsToBeSetAsCurrent << url;
            d->dirModel->expandToUrl(url);
            continue;
        }
        itemList << item;
    }

    setCurrentItems(itemList);
}

void KDirOperator::setCurrentItems(const KFileItemList& items)
{
    kDebug(kfile_area);

    if (d->itemView == 0) {
        return;
    }

    QItemSelectionModel *selModel = d->itemView->selectionModel();
    if (selModel) {
        selModel->clear();
        QModelIndex proxyIndex;
        foreach (const KFileItem &item, items) {
            if (!item.isNull()) {
                const QModelIndex dirIndex = d->dirModel->indexForItem(item);
                proxyIndex = d->proxyModel->mapFromSource(dirIndex);
                selModel->select(proxyIndex, QItemSelectionModel::Select);
            }
        }
        if (proxyIndex.isValid()) {
            selModel->setCurrentIndex(proxyIndex, QItemSelectionModel::NoUpdate);
        }
    }
}

QString KDirOperator::makeCompletion(const QString& string)
{
    if (string.isEmpty()) {
        d->itemView->selectionModel()->clear();
        return QString();
    }

    prepareCompletionObjects();
    return d->completion.makeCompletion(string);
}

QString KDirOperator::makeDirCompletion(const QString& string)
{
    if (string.isEmpty()) {
        d->itemView->selectionModel()->clear();
        return QString();
    }

    prepareCompletionObjects();
    return d->dirCompletion.makeCompletion(string);
}

void KDirOperator::prepareCompletionObjects()
{
    if (d->itemView == 0) {
        return;
    }

    if (d->completeListDirty) {   // create the list of all possible completions
        const KFileItemList itemList = d->dirLister->items();
        foreach (const KFileItem &item, itemList) {
            d->completion.addItem(item.name());
            if (item.isDir()) {
                d->dirCompletion.addItem(item.name());
            }
        }
        d->completeListDirty = false;
    }
}

void KDirOperator::slotCompletionMatch(const QString& match)
{
    setCurrentItem(match);
    emit completion(match);
}

void KDirOperator::setupActions()
{
    d->actionCollection = new KActionCollection(this);
    d->actionCollection->setObjectName("KDirOperator::actionCollection");

    d->actionMenu = new KActionMenu(i18n("Menu"), this);
    d->actionCollection->addAction("popupMenu", d->actionMenu);

    QAction* upAction = d->actionCollection->addAction(KStandardAction::Up, "up", this, SLOT(cdUp()));
    upAction->setText(i18n("Parent Folder"));

    d->actionCollection->addAction(KStandardAction::Back, "back", this, SLOT(back()));

    d->actionCollection->addAction(KStandardAction::Forward, "forward", this, SLOT(forward()));

    QAction* homeAction = d->actionCollection->addAction(KStandardAction::Home, "home", this, SLOT(home()));
    homeAction->setText(i18n("Home Folder"));

    KAction* reloadAction = d->actionCollection->addAction(KStandardAction::Redisplay, "reload", this, SLOT(rereadDir()));
    reloadAction->setText(i18n("Reload"));
    reloadAction->setShortcuts(KStandardShortcut::shortcut(KStandardShortcut::Reload));

    KAction* mkdirAction = new KAction(i18n("New Folder..."), this);
    d->actionCollection->addAction("mkdir", mkdirAction);
    mkdirAction->setIcon(KIcon(QLatin1String("folder-new")));
    connect(mkdirAction, SIGNAL(triggered(bool)), this, SLOT(mkdir()));

    KAction* trash = new KAction(i18n("Move to Trash"), this);
    d->actionCollection->addAction("trash", trash);
    trash->setIcon(KIcon("user-trash"));
    trash->setShortcuts(KShortcut(Qt::Key_Delete));
    connect(trash, SIGNAL(triggered(bool)), SLOT(trashSelected()));

    KAction* action = new KAction(i18n("Delete"), this);
    d->actionCollection->addAction("delete", action);
    action->setIcon(KIcon("edit-delete"));
    action->setShortcuts(KShortcut(Qt::SHIFT + Qt::Key_Delete));
    connect(action, SIGNAL(triggered(bool)), this, SLOT(deleteSelected()));

    // the sort menu actions
    KActionMenu *sortMenu = new KActionMenu(i18n("Sorting"), this);
    d->actionCollection->addAction("sorting menu",  sortMenu);

    KToggleAction *byNameAction = new KToggleAction(i18n("By Name"), this);
    d->actionCollection->addAction("by name", byNameAction);
    connect(byNameAction, SIGNAL(triggered(bool)), this, SLOT(_k_slotSortByName()));

    KToggleAction *bySizeAction = new KToggleAction(i18n("By Size"), this);
    d->actionCollection->addAction("by size", bySizeAction);
    connect(bySizeAction, SIGNAL(triggered(bool)), this, SLOT(_k_slotSortBySize()));

    KToggleAction *byDateAction = new KToggleAction(i18n("By Date"), this);
    d->actionCollection->addAction("by date", byDateAction);
    connect(byDateAction, SIGNAL(triggered(bool)), this, SLOT(_k_slotSortByDate()));

    KToggleAction *byTypeAction = new KToggleAction(i18n("By Type"), this);
    d->actionCollection->addAction("by type", byTypeAction);
    connect(byTypeAction, SIGNAL(triggered(bool)), this, SLOT(_k_slotSortByType()));

    KToggleAction *descendingAction = new KToggleAction(i18n("Descending"), this);
    d->actionCollection->addAction("descending", descendingAction);
    connect(descendingAction, SIGNAL(triggered(bool)), this, SLOT(_k_slotSortReversed(bool)));

    KToggleAction *dirsFirstAction = new KToggleAction(i18n("Folders First"), this);
    d->actionCollection->addAction("dirs first", dirsFirstAction);
    connect(dirsFirstAction, SIGNAL(triggered(bool)), this, SLOT(_k_slotToggleDirsFirst()));

    QActionGroup* sortGroup = new QActionGroup(this);
    byNameAction->setActionGroup(sortGroup);
    bySizeAction->setActionGroup(sortGroup);
    byDateAction->setActionGroup(sortGroup);
    byTypeAction->setActionGroup(sortGroup);

    d->decorationMenu = new KActionMenu(i18n("Icon Position"), this);
    d->actionCollection->addAction("decoration menu", d->decorationMenu);

    d->leftAction = new KToggleAction(i18n("Next to File Name"), this);
    d->actionCollection->addAction("decorationAtLeft", d->leftAction);
    connect(d->leftAction, SIGNAL(triggered(bool)), this, SLOT(_k_slotChangeDecorationPosition()));

    KToggleAction *topAction = new KToggleAction(i18n("Above File Name"), this);
    d->actionCollection->addAction("decorationAtTop", topAction);
    connect(topAction, SIGNAL(triggered(bool)), this, SLOT(_k_slotChangeDecorationPosition()));

    d->decorationMenu->addAction(d->leftAction);
    d->decorationMenu->addAction(topAction);

    QActionGroup* decorationGroup = new QActionGroup(this);
    d->leftAction->setActionGroup(decorationGroup);
    topAction->setActionGroup(decorationGroup);

    KToggleAction *shortAction = new KToggleAction(i18n("Short View"), this);
    d->actionCollection->addAction("short view",  shortAction);
    shortAction->setIcon(KIcon(QLatin1String("view-list-icons")));
    connect(shortAction, SIGNAL(triggered()), SLOT(_k_slotSimpleView()));

    KToggleAction *detailedAction = new KToggleAction(i18n("Detailed View"), this);
    d->actionCollection->addAction("detailed view", detailedAction);
    detailedAction->setIcon(KIcon(QLatin1String("view-list-details")));
    connect(detailedAction, SIGNAL(triggered()), SLOT(_k_slotDetailedView()));

    KToggleAction *treeAction = new KToggleAction(i18n("Tree View"), this);
    d->actionCollection->addAction("tree view", treeAction);
    treeAction->setIcon(KIcon(QLatin1String("view-list-tree")));
    connect(treeAction, SIGNAL(triggered()), SLOT(_k_slotTreeView()));

    KToggleAction *detailedTreeAction = new KToggleAction(i18n("Detailed Tree View"), this);
    d->actionCollection->addAction("detailed tree view", detailedTreeAction);
    detailedTreeAction->setIcon(KIcon(QLatin1String("view-list-tree")));
    connect(detailedTreeAction, SIGNAL(triggered()), SLOT(_k_slotDetailedTreeView()));

    QActionGroup* viewGroup = new QActionGroup(this);
    shortAction->setActionGroup(viewGroup);
    detailedAction->setActionGroup(viewGroup);
    treeAction->setActionGroup(viewGroup);
    detailedTreeAction->setActionGroup(viewGroup);

    KToggleAction *showHiddenAction = new KToggleAction(i18n("Show Hidden Files"), this);
    d->actionCollection->addAction("show hidden", showHiddenAction);
    connect(showHiddenAction, SIGNAL(toggled(bool)), SLOT(_k_slotToggleHidden(bool)));

    KToggleAction *previewAction = new KToggleAction(i18n("Show Aside Preview"), this);
    d->actionCollection->addAction("preview", previewAction);
    connect(previewAction, SIGNAL(toggled(bool)),
            SLOT(_k_togglePreview(bool)));

    KToggleAction *inlinePreview = new KToggleAction(KIcon("view-preview"),
                                                     i18n("Show Preview"), this);
    d->actionCollection->addAction("inline preview", inlinePreview);
    connect(inlinePreview, SIGNAL(toggled(bool)), SLOT(_k_toggleInlinePreviews(bool)));

    KAction *fileManager = new KAction(i18n("Open File Manager"), this);
    d->actionCollection->addAction("file manager", fileManager);
    fileManager->setIcon(KIcon(QLatin1String("system-file-manager")));
    connect(fileManager, SIGNAL(triggered()), SLOT(_k_slotOpenFileManager()));

    action = new KAction(i18n("Properties"), this);
    d->actionCollection->addAction("properties", action);
    action->setIcon(KIcon("document-properties"));
    action->setShortcut(KShortcut(Qt::ALT + Qt::Key_Return));
    connect(action, SIGNAL(triggered(bool)), this, SLOT(_k_slotProperties()));

    // the view menu actions
    KActionMenu* viewMenu = new KActionMenu(i18n("&View"), this);
    d->actionCollection->addAction("view menu", viewMenu);
    viewMenu->addAction(shortAction);
    viewMenu->addAction(detailedAction);
    // Comment following lines to hide the extra two modes
    viewMenu->addAction(treeAction);
    viewMenu->addAction(detailedTreeAction);
    // TODO: QAbstractItemView does not offer an action collection. Provide
    // an interface to add a custom action collection.

    d->newFileMenu = new KNewFileMenu(d->actionCollection, "new", this);
    connect(d->newFileMenu, SIGNAL(directoryCreated(KUrl)), this, SLOT(_k_slotDirectoryCreated(KUrl)));

    d->actionCollection->addAssociatedWidget(this);
    foreach (QAction* action, d->actionCollection->actions())
      action->setShortcutContext(Qt::WidgetWithChildrenShortcut);
}

void KDirOperator::setupMenu()
{
    setupMenu(SortActions | ViewActions | FileActions);
}

void KDirOperator::setupMenu(int whichActions)
{
    // first fill the submenus (sort and view)
    KActionMenu *sortMenu = static_cast<KActionMenu*>(d->actionCollection->action("sorting menu"));
    sortMenu->menu()->clear();
    sortMenu->addAction(d->actionCollection->action("by name"));
    sortMenu->addAction(d->actionCollection->action("by size"));
    sortMenu->addAction(d->actionCollection->action("by date"));
    sortMenu->addAction(d->actionCollection->action("by type"));
    sortMenu->addSeparator();
    sortMenu->addAction(d->actionCollection->action("descending"));
    sortMenu->addAction(d->actionCollection->action("dirs first"));

    // now plug everything into the popupmenu
    d->actionMenu->menu()->clear();
    if (whichActions & NavActions) {
        d->actionMenu->addAction(d->actionCollection->action("up"));
        d->actionMenu->addAction(d->actionCollection->action("back"));
        d->actionMenu->addAction(d->actionCollection->action("forward"));
        d->actionMenu->addAction(d->actionCollection->action("home"));
        d->actionMenu->addSeparator();
    }

    if (whichActions & FileActions) {
        d->actionMenu->addAction(d->actionCollection->action("new"));
        if (d->currUrl.isLocalFile() && !(QApplication::keyboardModifiers() & Qt::ShiftModifier)) {
            d->actionMenu->addAction(d->actionCollection->action("trash"));
        }
        KConfigGroup cg(KGlobal::config(), QLatin1String("KDE"));
        const bool del = !d->currUrl.isLocalFile() ||
                         (QApplication::keyboardModifiers() & Qt::ShiftModifier) ||
                         cg.readEntry("ShowDeleteCommand", false);
        if (del) {
            d->actionMenu->addAction(d->actionCollection->action("delete"));
        }
        d->actionMenu->addSeparator();
    }

    if (whichActions & SortActions) {
        d->actionMenu->addAction(sortMenu);
        if (!(whichActions & ViewActions)) {
            d->actionMenu->addSeparator();
        }
    }

    if (whichActions & ViewActions) {
        d->actionMenu->addAction(d->actionCollection->action("view menu"));
        d->actionMenu->addSeparator();
    }

    if (whichActions & FileActions) {
        d->actionMenu->addAction(d->actionCollection->action("file manager"));
        d->actionMenu->addAction(d->actionCollection->action("properties"));
    }
}

void KDirOperator::updateSortActions()
{
    if (KFile::isSortByName(d->sorting)) {
        d->actionCollection->action("by name")->setChecked(true);
    } else if (KFile::isSortByDate(d->sorting)) {
        d->actionCollection->action("by date")->setChecked(true);
    } else if (KFile::isSortBySize(d->sorting)) {
        d->actionCollection->action("by size")->setChecked(true);
    } else if (KFile::isSortByType(d->sorting)) {
        d->actionCollection->action("by type")->setChecked(true);
    }
    d->actionCollection->action("descending")->setChecked(d->sorting & QDir::Reversed);
    d->actionCollection->action("dirs first")->setChecked(d->sorting & QDir::DirsFirst);
}

void KDirOperator::updateViewActions()
{
    KFile::FileView fv = static_cast<KFile::FileView>(d->viewKind);

    //QAction *separateDirs = d->actionCollection->action("separate dirs");
    //separateDirs->setChecked(KFile::isSeparateDirs(fv) &&
    //                         separateDirs->isEnabled());

    d->actionCollection->action("short view")->setChecked(KFile::isSimpleView(fv));
    d->actionCollection->action("detailed view")->setChecked(KFile::isDetailView(fv));
    d->actionCollection->action("tree view")->setChecked(KFile::isTreeView(fv));
    d->actionCollection->action("detailed tree view")->setChecked(KFile::isDetailTreeView(fv));
}

void KDirOperator::readConfig(const KConfigGroup& configGroup)
{
    d->defaultView = 0;
    QString viewStyle = configGroup.readEntry("View Style", "Simple");
    if (viewStyle == QLatin1String("Detail")) {
        d->defaultView |= KFile::Detail;
    } else if (viewStyle == QLatin1String("Tree")) {
        d->defaultView |= KFile::Tree;
    } else if (viewStyle == QLatin1String("DetailTree")) {
        d->defaultView |= KFile::DetailTree;
    } else {
        d->defaultView |= KFile::Simple;
    }
    //if (configGroup.readEntry(QLatin1String("Separate Directories"),
    //                          DefaultMixDirsAndFiles)) {
    //    d->defaultView |= KFile::SeparateDirs;
    //}
    if (configGroup.readEntry(QLatin1String("Show Preview"), false)) {
        d->defaultView |= KFile::PreviewContents;
    }

    d->previewWidth = configGroup.readEntry(QLatin1String("Preview Width"), 100);

    if (configGroup.readEntry(QLatin1String("Show hidden files"),
                              DefaultShowHidden)) {
        d->actionCollection->action("show hidden")->setChecked(true);
        d->dirLister->setShowingDotFiles(true);
    }

    QDir::SortFlags sorting = QDir::Name;
    if (configGroup.readEntry(QLatin1String("Sort directories first"),
                              DefaultDirsFirst)) {
        sorting |= QDir::DirsFirst;
    }
    QString name = QLatin1String("Name");
    QString sortBy = configGroup.readEntry(QLatin1String("Sort by"), name);
    if (sortBy == name) {
        sorting |= QDir::Name;
    } else if (sortBy == QLatin1String("Size")) {
        sorting |= QDir::Size;
    } else if (sortBy == QLatin1String("Date")) {
        sorting |= QDir::Time;
    } else if (sortBy == QLatin1String("Type")) {
        sorting |= QDir::Type;
    }
    if (configGroup.readEntry(QLatin1String("Sort reversed"), DefaultSortReversed)) {
        sorting |= QDir::Reversed;
    }
    d->updateSorting(sorting);

    if (d->inlinePreviewState == Private::NotForced) {
        d->showPreviews = configGroup.readEntry(QLatin1String("Previews"), false);
    }
    QStyleOptionViewItem::Position pos = (QStyleOptionViewItem::Position) configGroup.readEntry(QLatin1String("Decoration position"), (int) QStyleOptionViewItem::Left);
    setDecorationPosition(pos);
}

void KDirOperator::writeConfig(KConfigGroup& configGroup)
{
    QString sortBy = QLatin1String("Name");
    if (KFile::isSortBySize(d->sorting)) {
        sortBy = QLatin1String("Size");
    } else if (KFile::isSortByDate(d->sorting)) {
        sortBy = QLatin1String("Date");
    } else if (KFile::isSortByType(d->sorting)) {
        sortBy = QLatin1String("Type");
    }

    configGroup.writeEntry(QLatin1String("Sort by"), sortBy);

    configGroup.writeEntry(QLatin1String("Sort reversed"),
                           d->actionCollection->action("descending")->isChecked());

    configGroup.writeEntry(QLatin1String("Sort directories first"),
                           d->actionCollection->action("dirs first")->isChecked());

    // don't save the preview when an application specific preview is in use.
    bool appSpecificPreview = false;
    if (d->preview) {
        KFileMetaPreview *tmp = dynamic_cast<KFileMetaPreview*>(d->preview);
        appSpecificPreview = (tmp == 0);
    }

    if (!appSpecificPreview) {
        KToggleAction *previewAction = static_cast<KToggleAction*>(d->actionCollection->action("preview"));
        if (previewAction->isEnabled()) {
            bool hasPreview = previewAction->isChecked();
            configGroup.writeEntry(QLatin1String("Show Preview"), hasPreview);

            if (hasPreview) {
                // remember the width of the preview widget
                QList<int> sizes = d->splitter->sizes();
                Q_ASSERT(sizes.count() == 2);
                configGroup.writeEntry(QLatin1String("Preview Width"), sizes[1]);
            }
        }
    }

    configGroup.writeEntry(QLatin1String("Show hidden files"),
                           d->actionCollection->action("show hidden")->isChecked());

    KFile::FileView fv = static_cast<KFile::FileView>(d->viewKind);
    QString style;
    if (KFile::isDetailView(fv))
        style = QLatin1String("Detail");
    else if (KFile::isSimpleView(fv))
        style = QLatin1String("Simple");
    else if (KFile::isTreeView(fv))
        style = QLatin1String("Tree");
    else if (KFile::isDetailTreeView(fv))
        style = QLatin1String("DetailTree");
    configGroup.writeEntry(QLatin1String("View Style"), style);

    if (d->inlinePreviewState == Private::NotForced) {
        configGroup.writeEntry(QLatin1String("Previews"), d->showPreviews);
        if (qobject_cast<QListView*>(d->itemView)) {
            configGroup.writeEntry(QLatin1String("listViewIconSize"), d->iconsZoom);
        } else {
            configGroup.writeEntry(QLatin1String("detailedViewIconSize"), d->iconsZoom);
        }
    }

    configGroup.writeEntry(QLatin1String("Decoration position"), (int) d->decorationPosition);
}

void KDirOperator::resizeEvent(QResizeEvent *)
{
    // resize the splitter and assure that the width of
    // the preview widget is restored
    QList<int> sizes = d->splitter->sizes();
    const bool hasPreview = (sizes.count() == 2);

    d->splitter->resize(size());
    sizes = d->splitter->sizes();

    const bool restorePreviewWidth = hasPreview && (d->previewWidth != sizes[1]);
    if (restorePreviewWidth) {
        const int availableWidth = sizes[0] + sizes[1];
        sizes[0] = availableWidth - d->previewWidth;
        sizes[1] = d->previewWidth;
        d->splitter->setSizes(sizes);
    }
    if (hasPreview) {
        d->previewWidth = sizes[1];
    }

    if (d->progressBar->parent() == this) {
        // might be reparented into a statusbar
        d->progressBar->move(2, height() - d->progressBar->height() - 2);
    }
}

void KDirOperator::setOnlyDoubleClickSelectsFiles(bool enable)
{
    d->onlyDoubleClickSelectsFiles = enable;
    // TODO: port to Qt4's QAbstractItemModel
    //if (d->itemView != 0) {
    //    d->itemView->setOnlyDoubleClickSelectsFiles(enable);
    //}
}

bool KDirOperator::onlyDoubleClickSelectsFiles() const
{
    return d->onlyDoubleClickSelectsFiles;
}

void KDirOperator::Private::_k_slotStarted()
{
    progressBar->setValue(0);
    // delay showing the progressbar for one second
    progressDelayTimer->setSingleShot(true);
    progressDelayTimer->start(1000);
}

void KDirOperator::Private::_k_slotShowProgress()
{
    progressBar->raise();
    progressBar->show();
    QApplication::flush();
}

void KDirOperator::Private::_k_slotProgress(int percent)
{
    progressBar->setValue(percent);
    // we have to redraw this as fast as possible
    if (progressBar->isVisible())
        QApplication::flush();
}


void KDirOperator::Private::_k_slotIOFinished()
{
    progressDelayTimer->stop();
    _k_slotProgress(100);
    progressBar->hide();
    emit parent->finishedLoading();
    parent->resetCursor();

    if (preview) {
        preview->clearPreview();
    }
}

void KDirOperator::Private::_k_slotCanceled()
{
    emit parent->finishedLoading();
    parent->resetCursor();
}

QProgressBar * KDirOperator::progressBar() const
{
    return d->progressBar;
}

void KDirOperator::clearHistory()
{
    qDeleteAll(d->backStack);
    d->backStack.clear();
    d->actionCollection->action("back")->setEnabled(false);

    qDeleteAll(d->forwardStack);
    d->forwardStack.clear();
    d->actionCollection->action("forward")->setEnabled(false);
}

void KDirOperator::setEnableDirHighlighting(bool enable)
{
    d->dirHighlighting = enable;
}

bool KDirOperator::dirHighlighting() const
{
    return d->dirHighlighting;
}

bool KDirOperator::dirOnlyMode() const
{
    return dirOnlyMode(d->mode);
}

bool KDirOperator::dirOnlyMode(uint mode)
{
    return ((mode & KFile::Directory) &&
            (mode & (KFile::File | KFile::Files)) == 0);
}

void KDirOperator::Private::_k_slotProperties()
{
    if (itemView == 0) {
        return;
    }

    const KFileItemList list = parent->selectedItems();
    if (!list.isEmpty()) {
        KPropertiesDialog dialog(list, parent);
        dialog.exec();
    }
}

void KDirOperator::Private::_k_slotActivated(const QModelIndex& index)
{
    const QModelIndex dirIndex = proxyModel->mapToSource(index);
    KFileItem item = dirModel->itemForIndex(dirIndex);

    const Qt::KeyboardModifiers modifiers = QApplication::keyboardModifiers();
    if (item.isNull() || (modifiers & Qt::ShiftModifier) || (modifiers & Qt::ControlModifier))
        return;

    if (item.isDir()) {
        parent->selectDir(item);
    } else {
        parent->selectFile(item);
    }
}

void KDirOperator::Private::_k_slotSelectionChanged()
{
    if (itemView == 0) {
        return;
    }

    // In the multiselection mode each selection change is indicated by
    // emitting a null item. Also when the selection has been cleared, a
    // null item must be emitted.
    const bool multiSelectionMode = (itemView->selectionMode() == QAbstractItemView::ExtendedSelection);
    const bool hasSelection = itemView->selectionModel()->hasSelection();
    if (multiSelectionMode || !hasSelection) {
        KFileItem nullItem;
        parent->highlightFile(nullItem);
    }
    else {
        KFileItem selectedItem = parent->selectedItems().first();
        parent->highlightFile(selectedItem);
    }
}

void KDirOperator::Private::_k_openContextMenu(const QPoint& pos)
{
    const QModelIndex proxyIndex = itemView->indexAt(pos);
    const QModelIndex dirIndex = proxyModel->mapToSource(proxyIndex);
    KFileItem item = dirModel->itemForIndex(dirIndex);

    if (item.isNull())
        return;

    parent->activatedMenu(item, QCursor::pos());
}

void KDirOperator::Private::_k_triggerPreview(const QModelIndex& index)
{
    if ((preview != 0 && !preview->isHidden()) && index.isValid() && (index.column() == KDirModel::Name)) {
        const QModelIndex dirIndex = proxyModel->mapToSource(index);
        const KFileItem item = dirModel->itemForIndex(dirIndex);

        if (item.isNull())
            return;

        if (!item.isDir()) {
            previewUrl = item.url();
            _k_showPreview();
        } else {
            preview->clearPreview();
        }
    }
}

void KDirOperator::Private::_k_showPreview()
{
    if (preview != 0) {
        preview->showPreview(previewUrl);
    }
}

void KDirOperator::Private::_k_slotSplitterMoved(int, int)
{
    const QList<int> sizes = splitter->sizes();
    if (sizes.count() == 2) {
        // remember the width of the preview widget (see KDirOperator::resizeEvent())
        previewWidth = sizes[1];
    }
}

void KDirOperator::Private::_k_assureVisibleSelection()
{
    if (itemView == 0) {
        return;
    }

    QItemSelectionModel* selModel = itemView->selectionModel();
    if (selModel->hasSelection()) {
        const QModelIndex index = selModel->currentIndex();
        itemView->scrollTo(index, QAbstractItemView::EnsureVisible);
        _k_triggerPreview(index);
    }
}


void KDirOperator::Private::_k_synchronizeSortingState(int logicalIndex, Qt::SortOrder order)
{
    QDir::SortFlags newSort = sorting & ~(QDirSortMask | QDir::Reversed);

    switch (logicalIndex) {
    case KDirModel::Name:
        newSort |= QDir::Name;
        break;
    case KDirModel::Size:
        newSort |= QDir::Size;
        break;
    case KDirModel::ModifiedTime:
        newSort |= QDir::Time;
        break;
    case KDirModel::Type:
        newSort |= QDir::Type;
        break;
    default:
        Q_ASSERT(false);
    }

    if (order == Qt::DescendingOrder) {
        newSort |= QDir::Reversed;
    }

    updateSorting(newSort);

    QMetaObject::invokeMethod(parent, "_k_assureVisibleSelection", Qt::QueuedConnection);
}

void KDirOperator::Private::_k_slotChangeDecorationPosition()
{
    if (!itemView) {
        return;
    }

    QListView *view = qobject_cast<QListView*>(itemView);

    if (!view) {
        return;
    }

    const bool leftChecked = actionCollection->action("decorationAtLeft")->isChecked();

    if (leftChecked) {
        decorationPosition = QStyleOptionViewItem::Left;
        view->setFlow(QListView::TopToBottom);
    } else {
        decorationPosition = QStyleOptionViewItem::Top;
        view->setFlow(QListView::LeftToRight);
    }

    updateListViewGrid();

    itemView->update();
}

void KDirOperator::Private::_k_slotExpandToUrl(const QModelIndex &index)
{
    QTreeView *treeView = qobject_cast<QTreeView*>(itemView);

    if (!treeView) {
        return;
    }

    const KFileItem item = dirModel->itemForIndex(index);

    if (item.isNull()) {
        return;
    }

    if (!item.isDir()) {
        const QModelIndex proxyIndex = proxyModel->mapFromSource(index);

        KUrl::List::Iterator it = itemsToBeSetAsCurrent.begin();
        while (it != itemsToBeSetAsCurrent.end()) {
            const KUrl url = *it;
            if (url.isParentOf(item.url())) {
                const KFileItem _item = dirLister->findByUrl(url);
                if (!_item.isNull() && _item.isDir()) {
                    const QModelIndex _index = dirModel->indexForItem(_item);
                    const QModelIndex _proxyIndex = proxyModel->mapFromSource(_index);
                    treeView->expand(_proxyIndex);

                    // if we have expanded the last parent of this item, select it
                    if (item.url().directory() == url.path(KUrl::RemoveTrailingSlash)) {
                        treeView->selectionModel()->select(proxyIndex, QItemSelectionModel::Select);
                    }
                }
                it = itemsToBeSetAsCurrent.erase(it);
            } else {
                ++it;
            }
        }
    } else if (!itemsToBeSetAsCurrent.contains(item.url())) {
        itemsToBeSetAsCurrent << item.url();
    }
}

void KDirOperator::Private::_k_slotItemsChanged()
{
    completeListDirty = true;
}

void KDirOperator::Private::updateListViewGrid()
{
    if (!itemView) {
        return;
    }

    QListView *view = qobject_cast<QListView*>(itemView);

    if (!view) {
        return;
    }

    const bool leftChecked = actionCollection->action("decorationAtLeft")->isChecked();

    if (leftChecked) {
        view->setGridSize(QSize());
        KFileItemDelegate *delegate = qobject_cast<KFileItemDelegate*>(view->itemDelegate());
        if (delegate) {
            delegate->setMaximumSize(QSize());
        }
    } else {
        const QFontMetrics metrics(itemView->viewport()->font());
        int size = itemView->iconSize().height() + metrics.height() * 2;
        // some heuristics for good looking. let's guess width = height * (3 / 2) is nice
        view->setGridSize(QSize(size * (3.0 / 2.0), size + metrics.height()));
        KFileItemDelegate *delegate = qobject_cast<KFileItemDelegate*>(view->itemDelegate());
        if (delegate) {
            delegate->setMaximumSize(QSize(size * (3.0 / 2.0), size + metrics.height()));
        }
    }
}

int KDirOperator::Private::iconSizeForViewType(QAbstractItemView *itemView) const
{
    if (!itemView || !configGroup) {
        return 0;
    }

    if (qobject_cast<QListView*>(itemView)) {
        return configGroup->readEntry("listViewIconSize", 0);
    } else {
        return configGroup->readEntry("detailedViewIconSize", 0);
    }
}

void KDirOperator::setViewConfig(KConfigGroup& configGroup)
{
    delete d->configGroup;
    d->configGroup = new KConfigGroup(configGroup);
}

KConfigGroup* KDirOperator::viewConfigGroup() const
{
    return d->configGroup;
}

void KDirOperator::setShowHiddenFiles(bool s)
{
    d->actionCollection->action("show hidden")->setChecked(s);
}

bool KDirOperator::showHiddenFiles() const
{
    return d->actionCollection->action("show hidden")->isChecked();
}

QStyleOptionViewItem::Position KDirOperator::decorationPosition() const
{
    return d->decorationPosition;
}

void KDirOperator::setDecorationPosition(QStyleOptionViewItem::Position position)
{
    d->decorationPosition = position;
    const bool decorationAtLeft = d->decorationPosition == QStyleOptionViewItem::Left;
    d->actionCollection->action("decorationAtLeft")->setChecked(decorationAtLeft);
    d->actionCollection->action("decorationAtTop")->setChecked(!decorationAtLeft);
}

// ### temporary code
#include <dirent.h>
bool KDirOperator::Private::isReadable(const KUrl& url)
{
    if (!url.isLocalFile())
        return true; // what else can we say?

    KDE_struct_stat buf;
#ifdef Q_WS_WIN
    QString ts = url.toLocalFile();
#else
    QString ts = url.path(KUrl::AddTrailingSlash);
#endif
    bool readable = (KDE::stat(ts, &buf) == 0);
    if (readable) { // further checks
        DIR *test;
        test = opendir(QFile::encodeName(ts));    // we do it just to test here
        readable = (test != 0);
        if (test)
            closedir(test);
    }
    return readable;
}

void KDirOperator::Private::_k_slotDirectoryCreated(const KUrl& url)
{
    parent->setUrl(url, true);
}

#include "kdiroperator.moc"