summaryrefslogtreecommitdiffstats
path: root/konqueror/konq_mainwindow.cc
blob: 09ea92c87f58414f402fc839dbfef4316f4b9f50 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
/* This file is part of the KDE project
   Copyright (C) 1998, 1999 Simon Hausmann <hausmann@kde.org>
   Copyright (C) 2000 Carsten Pfeiffer <pfeiffer@kde.org>
   Copyright (C) 2000-2005 David Faure <faure@kde.org>

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

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

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

#include "konq_mainwindow.h"
#include "konq_guiclients.h"
#include "KonqMainWindowIface.h"
#include "konq_view.h"
#include "konq_run.h"
#include "konq_misc.h"
#include "konq_viewmgr.h"
#include "konq_frame.h"
#include "konq_tabs.h"
#include "konq_events.h"
#include "konq_actions.h"
#include "konq_settingsxt.h"
#include "konq_extensionmanager.h"
#include "delayedinitializer.h"
#include <konq_pixmapprovider.h>
#include <konq_operations.h>
#include <konqbookmarkmanager.h>
#include <kinputdialog.h>
#include <kzip.h>
#include <config.h>
#include <pwd.h>
// we define STRICT_ANSI to get rid of some warnings in glibc
#ifndef __STRICT_ANSI__
#define __STRICT_ANSI__
#define _WE_DEFINED_IT_
#endif
#include <netdb.h>
#ifdef _WE_DEFINED_IT_
#undef __STRICT_ANSI__
#undef _WE_DEFINED_IT_
#endif
#include <assert.h>
#include <stdlib.h>
#include <time.h>
#include <klargefile.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>

#include <tqfile.h>
#include <tqclipboard.h>
#include <tqmetaobject.h>
#include <tqvbox.h>
#include <tqlayout.h>
#include <tqfileinfo.h>
#include <tqwhatsthis.h>

#include <dcopclient.h>
#include <kaboutdata.h>
#include <kbookmarkbar.h>
#include <kbookmarkmenu.h>
#include <kcmultidialog.h>
#include <kdebug.h>
#include <kedittoolbar.h>
#include <kkeydialog.h>
#include <kmenubar.h>
#include <kmessagebox.h>
#include <knewmenu.h>
#include <konq_defaults.h>
#include <konq_dirpart.h>
#include <konq_popupmenu.h>
#include <konq_settings.h>
#include "konq_main.h"
#include <konq_undo.h>
#include <kprotocolinfo.h>
#include <kstdaccel.h>
#include <kstdaction.h>
#include <kstandarddirs.h>
#include <tdesycoca.h>
#include <ktempfile.h>
#include <kurlrequesterdlg.h>
#include <kurlrequester.h>
#include <kuserprofile.h>
#include <twin.h>
#include <kfiledialog.h>
#include <klocale.h>
#include <kiconloader.h>
#include <kpopupmenu.h>
#include <kprocess.h>
#include <kio/scheduler.h>
#include <kio/netaccess.h>
#include <kaccelmanager.h>
#include <kstringhandler.h>
#include <kuser.h>
#include <netwm.h>

#ifdef KDE_MALLINFO_STDLIB
#include <stdlib.h>
#endif
#ifdef KDE_MALLINFO_MALLOC
#include <malloc.h>
#endif

#include <X11/Xlib.h>
#include <sys/time.h>
#include <X11/Xatom.h>
#include <fixx11h.h>

template class TQPtrList<TQPixmap>;
template class TQPtrList<KToggleAction>;

TQPtrList<KonqMainWindow> *KonqMainWindow::s_lstViews = 0;
TDEConfig * KonqMainWindow::s_comboConfig = 0;
KCompletion * KonqMainWindow::s_pCompletion = 0;
TQFile * KonqMainWindow::s_crashlog_file = 0;
bool KonqMainWindow::s_preloaded = false;
KonqMainWindow* KonqMainWindow::s_preloadedWindow = 0;
int KonqMainWindow::s_initialMemoryUsage = -1;
time_t KonqMainWindow::s_startupTime;
int KonqMainWindow::s_preloadUsageCount;

KonqOpenURLRequest KonqOpenURLRequest::null;

static int current_memory_usage( int* limit = NULL );

#include "konq_mainwindow_p.h"

KonqExtendedBookmarkOwner::KonqExtendedBookmarkOwner(KonqMainWindow *w)
{
   m_pKonqMainWindow = w;
}

KonqMainWindow::KonqMainWindow( const KURL &initialURL, bool openInitialURL, const char *name, const TQString& xmluiFile)
 : KParts::MainWindow( NoDCOPObject, 0L, name, (WFlags)(WDestructiveClose | WStyle_ContextHelp | TQt::WGroupLeader) )
{
  setPreloadedFlag( false );

  if ( !s_lstViews )
    s_lstViews = new TQPtrList<KonqMainWindow>;

  s_lstViews->append( this );

  m_urlCompletionStarted = false;

  m_currentView = 0L;
  m_pChildFrame = 0L;
  m_pActiveChild = 0L;
  m_pWorkingTab = 0L;
  m_initialKonqRun = 0L;
  m_pBookmarkMenu = 0L;
  m_dcopObject = new KonqMainWindowIface( this );
  m_combo = 0L;
  m_bURLEnterLock = false;
  m_bLocationBarConnected = false;
  m_paBookmarkBar = 0L;
  m_pURLCompletion = 0L;
  m_goBuffer = 0;
  m_configureDialog = 0L;

  m_bViewModeToggled = false;

  m_prevMenuBarVisible = true;

  m_pViewManager = new KonqViewManager( this );

  m_toggleViewGUIClient = new ToggleViewGUIClient( this );

  m_openWithActions.setAutoDelete( true );
  m_viewModeActions.setAutoDelete( true );
  m_toolBarViewModeActions.setAutoDelete( true );
  m_viewModeMenu = 0;
  m_paCopyFiles = 0;
  m_paMoveFiles = 0;
  m_paDelete = 0;
  m_paNewDir = 0;
  m_bookmarkBarActionCollection = 0L;
  KonqExtendedBookmarkOwner *extOwner = new KonqExtendedBookmarkOwner( this );
  m_pBookmarksOwner = extOwner;
  connect( extOwner,
           TQT_SIGNAL( signalFillBookmarksList(KExtendedBookmarkOwner::QStringPairList &) ),
           extOwner,
           TQT_SLOT( slotFillBookmarksList(KExtendedBookmarkOwner::QStringPairList &) ) );

  // init history-manager, load history, get completion object
  if ( !s_pCompletion ) {
    KonqHistoryManager *mgr = new KonqHistoryManager( TQT_TQOBJECT(kapp), "history mgr" );
    s_pCompletion = mgr->completionObject();


    // setup the completion object before createGUI(), so that the combo
    // picks up the correct mode from the HistoryManager (in slotComboPlugged)
    int mode = KonqSettings::settingsCompletionMode();
    s_pCompletion->setCompletionMode( (TDEGlobalSettings::Completion) mode );
  }
  connect(KParts::HistoryProvider::self(), TQT_SIGNAL(cleared()), TQT_SLOT(slotClearComboHistory()));

  KonqPixmapProvider *prov = KonqPixmapProvider::self();
  if ( !s_comboConfig ) {
      s_comboConfig = new TDEConfig( "konq_history", false, false );
      KonqCombo::setConfig( s_comboConfig );
      s_comboConfig->setGroup( "Location Bar" );
      prov->load( s_comboConfig, "ComboIconCache" );
  }
  connect( prov, TQT_SIGNAL( changed() ), TQT_SLOT( slotIconsChanged() ) );

  initCombo();
  initActions();

  setInstance( TDEGlobal::instance() );

  connect( KSycoca::self(), TQT_SIGNAL( databaseChanged() ),
           this, TQT_SLOT( slotDatabaseChanged() ) );

  connect( kapp, TQT_SIGNAL( kdisplayFontChanged()), TQT_SLOT(slotReconfigure()));

  //load the xmlui file specified in the profile or the default konqueror.rc
  setXMLFile( xmluiFile );

  setStandardToolBarMenuEnabled( true );

  createGUI( 0L );

  connect(toolBarMenuAction(),TQT_SIGNAL(activated()),this,TQT_SLOT(slotForceSaveMainWindowSettings()) );

  if ( !m_toggleViewGUIClient->empty() )
    plugActionList( TQString::fromLatin1( "toggleview" ), m_toggleViewGUIClient->actions() );
  else
  {
    delete m_toggleViewGUIClient;
    m_toggleViewGUIClient = 0;
  }

  // Those menus are created by konqueror.rc so their address will never change
  TQPopupMenu *popup = static_cast<TQPopupMenu*>(factory()->container("edit",this));
  if (popup)
    KAcceleratorManager::manage(popup);
  popup = static_cast<TQPopupMenu*>(factory()->container("tools",this));
  if (popup)
    KAcceleratorManager::manage(popup);

  m_bSaveViewPropertiesLocally = KonqSettings::saveViewPropertiesLocally();
  m_bHTMLAllowed = KonqSettings::htmlAllowed();

  m_ptaUseHTML->setChecked( m_bHTMLAllowed );
  m_paSaveViewPropertiesLocally->setChecked( m_bSaveViewPropertiesLocally );

  KonqUndoManager::incRef();

  connect( KonqUndoManager::self(), TQT_SIGNAL( undoAvailable( bool ) ),
           this, TQT_SLOT( slotUndoAvailable( bool ) ) );
  m_bNeedApplyKonqMainWindowSettings = true;

  if ( !initialURL.isEmpty() )
  {
    openFilteredURL( initialURL.url() );
  }
  else if ( openInitialURL )
  {
    KURL homeURL;
    homeURL.setPath( TQDir::homeDirPath() );
    openURL( 0L, homeURL );
  }
  else
      // silent
      m_bNeedApplyKonqMainWindowSettings = false;

  // Read basic main-view settings, and set to autosave
  setAutoSaveSettings( "KonqMainWindow", false );

  if ( !initialGeometrySet() )
      resize( 700, 480 );
  //kdDebug(1202) << "KonqMainWindow::KonqMainWindow " << this << " done" << endl;

  if( s_initialMemoryUsage == -1 )
  {
      s_initialMemoryUsage = current_memory_usage();
      s_startupTime = time( NULL );
      s_preloadUsageCount = 0;
  }
}

KonqMainWindow::~KonqMainWindow()
{
  kdDebug(1202) << "KonqMainWindow::~KonqMainWindow " << this << endl;

  delete m_pViewManager;

  if ( s_lstViews )
  {
    s_lstViews->removeRef( this );
    if ( s_lstViews->count() == 0 )
    {
      delete s_lstViews;
      s_lstViews = 0;
    }
  }

  disconnectActionCollection( actionCollection() );

  saveToolBarServicesMap();

  //  createShellGUI( false );

  delete m_pBookmarkMenu;
  delete m_paBookmarkBar;
  delete m_pBookmarksOwner;
  delete m_pURLCompletion;

  m_viewModeActions.clear();

  KonqUndoManager::decRef();

  if ( s_lstViews == 0 ) {
      delete KonqPixmapProvider::self();
      delete s_comboConfig;
      s_comboConfig = 0L;
  }

  delete m_configureDialog;
  m_configureDialog = 0L;
  delete m_dcopObject;
  m_dcopObject = 0L;
  delete m_combo;
  m_combo = 0L;
  delete m_locationLabel;
  m_locationLabel = 0L;

  kdDebug(1202) << "KonqMainWindow::~KonqMainWindow " << this << " done" << endl;
}

TQWidget * KonqMainWindow::createContainer( TQWidget *parent, int index, const TQDomElement &element, int &id )
{
  static TQString nameBookmarkBar = TQString::fromLatin1( "bookmarkToolBar" );
  static TQString tagToolBar = TQString::fromLatin1( "ToolBar" );

  TQWidget *res = KParts::MainWindow::createContainer( parent, index, element, id );

  if ( res && (element.tagName() == tagToolBar) && (element.attribute( "name" ) == nameBookmarkBar) )
  {
    assert( res->inherits( "KToolBar" ) );
    if (!kapp->authorizeKAction("bookmarks"))
    {
        delete res;
        return 0;
    }

    if ( !m_bookmarkBarActionCollection )
    {
        // The actual menu needs a different action collection, so that the bookmarks
        // don't appear in kedittoolbar
        m_bookmarkBarActionCollection = new KActionCollection( this );
        m_bookmarkBarActionCollection->setHighlightingEnabled( true );
        connectActionCollection( m_bookmarkBarActionCollection );
        DelayedInitializer *initializer = new DelayedInitializer( TQEvent::Show, TQT_TQOBJECT(res) );
        connect( initializer, TQT_SIGNAL( initialize() ), this, TQT_SLOT(initBookmarkBar()) );
    }
  }

  return res;
}

void KonqMainWindow::initBookmarkBar()
{
  KToolBar * bar = static_cast<KToolBar *>( TQT_TQWIDGET(child( "bookmarkToolBar", "KToolBar" )) );

  if (!bar) return;

  delete m_paBookmarkBar;
  m_paBookmarkBar = new KBookmarkBar( KonqBookmarkManager::self(), m_pBookmarksOwner, bar, m_bookmarkBarActionCollection, TQT_TQOBJECT(this) );
  connect( m_paBookmarkBar,
           TQT_SIGNAL( aboutToShowContextMenu(const KBookmark &, TQPopupMenu*) ),
           this, TQT_SLOT( slotFillContextMenu(const KBookmark &, TQPopupMenu*) ));
  connect( m_paBookmarkBar,
	   TQT_SIGNAL( openBookmark(const TQString &, TQt::ButtonState) ),
	   this, TQT_SLOT( slotOpenBookmarkURL(const TQString &, TQt::ButtonState) ));

  // hide if empty
  if (bar->count() == 0 )
     bar->hide();
}

void KonqMainWindow::removeContainer( TQWidget *container, TQWidget *parent, TQDomElement &element, int id )
{
  static TQString nameBookmarkBar = TQString::fromLatin1( "bookmarkToolBar" );
  static TQString tagToolBar = TQString::fromLatin1( "ToolBar" );

  if ( element.tagName() == tagToolBar && element.attribute( "name" ) == nameBookmarkBar )
  {
    assert( container->inherits( "KToolBar" ) );
    if (m_paBookmarkBar)
      m_paBookmarkBar->clear();
  }

  KParts::MainWindow::removeContainer( container, parent, element, id );
}

// Detect a name filter (e.g. *.txt) in the url.
// Note that KShortURIFilter does the same, but we have no way of getting it from there
//
// Note: this removes the filter from the URL.
static TQString detectNameFilter( KURL & url )
{
    if ( !KProtocolInfo::supportsListing(url) )
        return TQString::null;

    // Look for wildcard selection
    TQString nameFilter;
    TQString path = url.path();
    int lastSlash = path.findRev( '/' );
    if ( lastSlash > -1 )
    {
        if ( !url.query().isEmpty() && lastSlash == (int)path.length()-1 ) {  //  In /tmp/?foo, foo isn't a query
            path += url.query(); // includes the '?'
            url.setQuery( TQString::null );
        }
        const TQString fileName = path.mid( lastSlash + 1 );
        if ( fileName.find( '*' ) != -1 || fileName.find( '[' ) != -1 || fileName.find( '?' ) != -1 )
        {
            // Check that a file or dir with all the special chars in the filename doesn't exist
            if ( url.isLocalFile() ? !TQFile::exists( path ) : !TDEIO::NetAccess::exists( url, false, 0 ) )
            {
                nameFilter = fileName;
                url.setFileName( TQString::null );
                kdDebug(1202) << "Found wildcard. nameFilter=" << nameFilter << "  New url=" << url << endl;
            }
        }
    }

    return nameFilter;
}

void KonqMainWindow::openFilteredURL( const TQString & url, KonqOpenURLRequest & req )
{
    // Filter URL to build a correct one
    if (m_currentDir.isEmpty() && m_currentView)
       m_currentDir = m_currentView->url().path(1);

    KURL filteredURL ( KonqMisc::konqFilteredURL( this, url, m_currentDir ) );
    kdDebug(1202) << "url " << url << " filtered into " << filteredURL.prettyURL() << endl;

    if ( filteredURL.isEmpty() ) // initially empty, or error (e.g. ~unknown_user)
        return;

    m_currentDir = TQString::null;

    openURL( 0L, filteredURL, TQString::null, req );

    // #4070: Give focus to view after URL was entered manually
    // Note: we do it here if the view mode (i.e. part) wasn't changed
    // If it is changed, then it's done in KonqView::changeViewMode
    if ( m_currentView && m_currentView->part() )
      m_currentView->part()->widget()->setFocus();

}

void KonqMainWindow::openFilteredURL( const TQString & _url, bool inNewTab, bool tempFile )
{
    KonqOpenURLRequest req( _url );
    req.newTab = inNewTab;
    req.newTabInFront = true;
    req.tempFile = tempFile;

    openFilteredURL( _url, req );
}

void KonqMainWindow::openURL( KonqView *_view, const KURL &_url,
                              const TQString &_serviceType, KonqOpenURLRequest& req,
                              bool trustedSource )
{
#ifndef NDEBUG // needed for req.debug()
  kdDebug(1202) << "KonqMainWindow::openURL : url = '" << _url << "'  "
                << "serviceType='" << _serviceType << "' req=" << req.debug()
                << " view=" << _view << endl;
#endif

  KURL url( _url );
  if (url.url().startsWith("$(")) {
      // check for environment variables and make necessary translations
      TQString aValue = url.url();
      int nDollarPos = aValue.find( '$' );

      while( nDollarPos != -1 && nDollarPos+1 < static_cast<int>(aValue.length())) {
        // there is at least one $
        if( (aValue)[nDollarPos+1] == '(' ) {
          uint nEndPos = nDollarPos+1;
          // the next character is no $
          while ( (nEndPos <= aValue.length()) && (aValue[nEndPos]!=')') )
              nEndPos++;
          nEndPos++;
          TQString cmd = aValue.mid( nDollarPos+2, nEndPos-nDollarPos-3 );

          TQString result;
          FILE *fs = popen(TQFile::encodeName(cmd).data(), "r");
          if (fs)
          {
             {
             TQTextStream ts(fs, IO_ReadOnly);
             result = ts.read().stripWhiteSpace();
             }
             pclose(fs);
          }
          aValue.replace( nDollarPos, nEndPos-nDollarPos, result );
        } else if( (aValue)[nDollarPos+1] != '$' ) {
          uint nEndPos = nDollarPos+1;
          // the next character is no $
          TQString aVarName;
          if (aValue[nEndPos]=='{')
          {
            while ( (nEndPos <= aValue.length()) && (aValue[nEndPos]!='}') )
                nEndPos++;
            nEndPos++;
            aVarName = aValue.mid( nDollarPos+2, nEndPos-nDollarPos-3 );
          }
          else
          {
            while ( nEndPos <= aValue.length() && (aValue[nEndPos].isNumber()
                    || aValue[nEndPos].isLetter() || aValue[nEndPos]=='_' )  )
                nEndPos++;
            aVarName = aValue.mid( nDollarPos+1, nEndPos-nDollarPos-1 );
          }
          const char* pEnv = 0;
          if (!aVarName.isEmpty())
               pEnv = getenv( aVarName.ascii() );
          if( pEnv ) {
            // !!! Sergey A. Sukiyazov <corwin@micom.don.ru> !!!
            // A environment variables may contain values in 8bit
            // locale cpecified encoding or in UTF8 encoding.
            aValue.replace( nDollarPos, nEndPos-nDollarPos, KStringHandler::from8Bit( pEnv ) );
          } else
            aValue.remove( nDollarPos, nEndPos-nDollarPos );
        } else {
          // remove one of the dollar signs
          aValue.remove( nDollarPos, 1 );
          nDollarPos++;
        }
        nDollarPos = aValue.find( '$', nDollarPos );
      }
      url = KURL(aValue);
  }
  TQString serviceType( _serviceType );
  if ( url.url() == "about:blank" )
  {
    serviceType = "text/html";
  }
  else if ( !url.isValid() )
  {
      KMessageBox::error(0, i18n("Malformed URL\n%1").arg(url.url()));
      return;
  }
  else if ( !KProtocolInfo::isKnownProtocol( url ) && url.protocol() != "about" )
  {
      KMessageBox::error(0, i18n("Protocol not supported\n%1").arg(url.protocol()));
      return;
  }

  TQString nameFilter = detectNameFilter( url );
  if ( !nameFilter.isEmpty() )
  {
    req.nameFilter = nameFilter;
    url.setFileName( TQString::null );
  }

  KonqView *view = _view;

  // When clicking a 'follow active' view (e.g. view is the sidebar),
  // open the URL in the active view
  if ( view && view->isFollowActive() )
    view = m_currentView;

  if ( !view  && !req.newTab )
    view = m_currentView; /* Note, this can be 0L, e.g. on startup */
  else if ( !view && req.newTab ) {
    view = m_pViewManager->addTab(TQString::null,
                                  TQString::null,
                                  false,
                                  req.openAfterCurrentPage);
    if (view) {
      view->setCaption( _url.host() );
      view->setLocationBarURL( _url );
      if ( !req.args.frameName.isEmpty() )
          view->setViewName( req.args.frameName ); // #44961

      if ( req.newTabInFront )
        m_pViewManager->showTab( view );

      updateViewActions(); //A new tab created -- we may need to enable the "remove tab" button (#56318)
    }
    else
      req.newTab = false;
  }

  const TQString oldLocationBarURL = m_combo->currentText();
  if ( view )
  {
    if ( view == m_currentView )
    {
      //will do all the stuff below plus GUI stuff
      abortLoading();
    }
    else
    {
      view->stop();
      // Don't change location bar if not current view
    }
  }

  // Fast mode for local files: do the stat ourselves instead of letting KRun do it.
  if ( serviceType.isEmpty() && url.isLocalFile() )
  {
    TQCString _path( TQFile::encodeName(url.path()));
    KDE_struct_stat buff;
    if ( KDE_stat( _path.data(), &buff ) != -1 )
        serviceType = KMimeType::findByURL( url, buff.st_mode )->name();
  }

  kdDebug(1202) << "trying openView for " << url << " (serviceType " << serviceType << ")" << endl;
  if ( ( !serviceType.isEmpty() && serviceType != "application/octet-stream") ||
          url.url().startsWith("about:konqueror") || url.url() == "about:plugins" )
  {
    KService::Ptr offer = KServiceTypeProfile::preferredService(serviceType, "Application");
    // If the associated app is konqueror itself, then make sure we try to embed before bailing out.
    if ( isMimeTypeAssociatedWithSelf( serviceType, offer ) )
      req.forceAutoEmbed = true;

    // Built-in view ?
    if ( !openView( serviceType, url, view /* can be 0L */, req ) )
    {
        //kdDebug(1202) << "KonqMainWindow::openURL : openView returned false" << endl;
        // Are we following another view ? Then forget about this URL. Otherwise fire app.
        if ( !req.followMode )
        {
            //kdDebug(1202) << "KonqMainWindow::openURL : we were not following. Fire app." << endl;
            // We know the servicetype, let's try its preferred service
            if ( isMimeTypeAssociatedWithSelf( serviceType, offer ) ) {
                KMessageBox::error( this, i18n("There appears to be a configuration error. You have associated Konqueror with %1, but it cannot handle this file type.").arg(serviceType));
                return;
            }
            if ( !url.isLocalFile() && KonqRun::isTextExecutable( serviceType ) )
                serviceType = "text/plain"; // view, don't execute
            // Remote URL: save or open ?
            TQString protClass = KProtocolInfo::protocolClass(url.protocol());
            bool open = url.isLocalFile() || protClass==":local";
            if ( !open ) {
                KParts::BrowserRun::AskSaveResult res = KonqRun::askSave( url, offer, serviceType );
                if ( res == KParts::BrowserRun::Save )
                    KParts::BrowserRun::simpleSave( url, TQString::null, this );
                open = ( res == KParts::BrowserRun::Open );
            }
            if ( open )
            {
                KURL::List lst;
                lst.append(url);
                //kdDebug(1202) << "Got offer " << (offer ? offer->name().latin1() : "0") << endl;
                if ( ( trustedSource || KonqRun::allowExecution( serviceType, url ) ) &&
                     ( KonqRun::isExecutable( serviceType ) || !offer || !KRun::run( *offer, lst ) ) )
                {
                    setLocationBarURL( oldLocationBarURL ); // Revert to previous locationbar URL
                    (void)new KRun( url, this );
                }
            }
        }
    }
  }
  else // no known serviceType, use KonqRun
  {
      if ( ( !view || view->url().isEmpty() ) && !req.newTab ) // startup with argument
      {
          // Show it for now in the location bar, but we'll need to store it in the view
          // later on (can't do it yet since either view == 0 or updateHistoryEntry will be called).
          kdDebug(1202) << "setLocationBarURL (startup) : url = " << url << endl;
          setLocationBarURL( url );
      }

      kdDebug(1202) << "Creating new konqrun for " << url << " req.typedURL=" << req.typedURL << endl;

      KonqRun * run = new KonqRun( this, view /* can be 0L */, url, req, trustedSource );

      // Never start in external browser
      run->setEnableExternalBrowser(false);

      if ( view )
        view->setRun( run );
      else if ( !req.newTab )
      {
        // there can be only one :) (when not a new tab)
          delete m_initialKonqRun;
          m_initialKonqRun = run;
      }

      if ( view == m_currentView )
        startAnimation();

      connect( run, TQT_SIGNAL( finished() ), this, TQT_SLOT( slotRunFinished() ) );
  }
}

bool KonqMainWindow::openView( TQString serviceType, const KURL &_url, KonqView *childView, KonqOpenURLRequest& req )
{
  // Second argument is referring URL
  if ( !kapp->authorizeURLAction("open", childView ? childView->url() : KURL(), _url) )
  {
     TQString msg = TDEIO::buildErrorString(TDEIO::ERR_ACCESS_DENIED, _url.prettyURL());
     KMessageBox::queuedMessageBox( this, KMessageBox::Error, msg );
     return true; // Nothing else to do.
  }

  if ( KonqRun::isExecutable( serviceType ) )
     return false; // execute, don't open
  // Contract: the caller of this method should ensure the view is stopped first.

#ifndef NDEBUG
  kdDebug(1202) << "KonqMainWindow::openView " << serviceType << " " << _url << " " << childView << " req:" << req.debug() << endl;
#endif
  bool bOthersFollowed = false;

  if ( childView )
  {
    // If we're not already following another view (and if we are not reloading)
    if ( !req.followMode && !req.args.reload && !m_pViewManager->isLoadingProfile() )
    {
      // When clicking a 'follow active' view (e.g. childView is the sidebar),
      // open the URL in the active view
      // (it won't do anything itself, since it's locked to its location)
      if ( childView->isFollowActive() && childView != m_currentView )
      {
        abortLoading();
        setLocationBarURL( _url );
        KonqOpenURLRequest newreq;
        newreq.followMode = true;
        newreq.args = req.args;
        bOthersFollowed = openView( serviceType, _url, m_currentView, newreq );
      }
      // "link views" feature, and "sidebar follows active view" feature
      bOthersFollowed = makeViewsFollow(_url, req.args, serviceType, childView) || bOthersFollowed;
    }
    if ( childView->isLockedLocation() && !req.args.reload /* allow to reload a locked view*/ )
      return bOthersFollowed;
  }

  TQString indexFile;

  KURL url( _url );

  // Generic mechanism for redirecting to tar:/<path>/ when clicking on a tar file,
  // zip:/<path>/ when clicking on a zip file, etc.
  // The name of the protocol to redirect to, is read from the mimetype's .desktop file
  if ( url.isLocalFile() )
  {
    KServiceType::Ptr ptr = KServiceType::serviceType( serviceType );
    if ( ptr )
    {
      const TQString protocol = ptr->property("X-TDE-LocalProtocol").toString();
      if ( !protocol.isEmpty() && KonqFMSettings::settings()->shouldEmbed( serviceType ) )
      {
        url.setProtocol( protocol );
        if ( serviceType == "application/x-webarchive" )
        {
          url.setPath( url.path() + "/index.html" );
          serviceType = "text/html";
        }
        else
        {
          url.setPath( url.path() + '/' );
          serviceType = "inode/directory";
        }
      }
    }
  }

  ///////////

  // In case we open an index.html, we want the location bar
  // to still display the original URL (so that 'up' uses that URL,
  // and since that's what the user entered).
  // changeViewMode will take care of setting and storing that url.
  TQString originalURL = url.pathOrURL();
  if ( !req.nameFilter.isEmpty() ) // keep filter in location bar
  {
    if (!originalURL.endsWith("/"))
        originalURL += '/';
    originalURL += req.nameFilter;
  }

  TQString serviceName; // default: none provided

  if ( url.url().startsWith("about:konqueror") || url.url() == "about:plugins" )
  {
      serviceType = "KonqAboutPage"; // not KParts/ReadOnlyPart, it fills the Location menu ! :)
      serviceName = "konq_aboutpage";
      originalURL = req.typedURL.isEmpty() ? TQString::null : url.url();
      // empty if from profile, about:konqueror if the user typed it (not req.typedURL, it could be "about:")
  }
  else if ( url.url() == "about:blank" && req.typedURL.isEmpty() )
  {
      originalURL = TQString::null;
  }

  // Look for which view mode to use, if a directory - not if view locked
  if ( ( !childView || (!childView->isLockedViewMode()) )
       && serviceType == "inode/directory" )
    { // Phew !

      // Set view mode if necessary (current view doesn't support directories)
      if ( !childView || !childView->supportsServiceType( serviceType ) )
        serviceName = KonqSettings::mainViewViewMode();

      if ( url.isLocalFile() ) // local, we can do better (.directory)
        {
          // Read it in the .directory file, default to m_bHTMLAllowed
          KURL urlDotDir( url );
          urlDotDir.addPath(".directory");
          bool HTMLAllowed = m_bHTMLAllowed;
          TQFile f( urlDotDir.path() );
          if ( f.open(IO_ReadOnly) )
            {
              f.close();
              KSimpleConfig config( urlDotDir.path(), true );
              config.setGroup( "URL properties" );
              HTMLAllowed = config.readBoolEntry( "HTMLAllowed", m_bHTMLAllowed );
              serviceName = config.readEntry( "ViewMode", serviceName );
              kdDebug(1202) << "serviceName=" << serviceName << endl;
            }
          if ( HTMLAllowed &&
               ( ( indexFile = findIndexFile( url.path() ) ) != TQString::null ) )
            {
              serviceType = "text/html";
              url = KURL();
              url.setPath( indexFile );
              serviceName = TQString::null; // cancel what we just set, this is not a dir finally
            }

          // Reflect this setting in the menu
          m_ptaUseHTML->setChecked( HTMLAllowed );
        }
    }

  bool ok = true;
  if ( !childView )
  {
      if (req.newTab)
      {
          KonqFrameTabs* tabContainer = 0L;
          int index = 0;
          if ( m_pViewManager->docContainer() && m_pViewManager->docContainer()->frameType() == "Tabs")
          {
              tabContainer = static_cast<KonqFrameTabs*>(m_pViewManager->docContainer());
              index = tabContainer->currentPageIndex();
          }
          childView = m_pViewManager->addTab( serviceType, serviceName, false, req.openAfterCurrentPage );

          if (req.newTabInFront && childView)
          {
              if ( !tabContainer )
                  tabContainer = static_cast<KonqFrameTabs*>(m_pViewManager->docContainer());
              if ( req.openAfterCurrentPage )
                  tabContainer->setCurrentPage( index + 1 );
              else
                  tabContainer->setCurrentPage( tabContainer->count()-1 );
          }
      }

      else
      {
        // Create a new view
        // Initialize always uses force auto-embed even if user setting is "separate viewer",
        // since this window has no view yet - we don't want to keep an empty mainwindow.
        // This can happen with e.g. application/pdf from a target="_blank" link, or window.open.
        childView = m_pViewManager->Initialize( serviceType, serviceName );

        if ( childView )
        {
            enableAllActions( true );
            m_currentView = childView;
        }
      }

      if ( !childView )
          return false; // It didn't work out.

      childView->setViewName( m_initialFrameName.isEmpty() ? req.args.frameName : m_initialFrameName );
      m_initialFrameName = TQString::null;
  }
  else // We know the child view
  {
      if ( !childView->isLockedViewMode() )
      {
          bool forceAutoEmbed = req.forceAutoEmbed || req.newTab || req.userRequestedReload;
          if ( !req.typedURL.isEmpty() ) // the user _typed_ the URL, he wants it in Konq.
              forceAutoEmbed = true;
          if ( url.protocol() == "about" )
              forceAutoEmbed = true;
          // Related to KonqFactory::createView
          if ( !forceAutoEmbed && !KonqFMSettings::settings()->shouldEmbed( serviceType ) )
          {
              kdDebug(1202) << "openView: KonqFMSettings says: don't embed this servicetype" << endl;
              ok = false;
          }

          // If the protocol doesn't support writing (e.g. HTTP) then we might want to save instead of just embedding.
          // So (if embedding would succeed, hence the checks above) we ask the user
          // Otherwise the user will get asked 'open or save' in openURL anyway.
          if ( ok && !forceAutoEmbed && !KProtocolInfo::supportsWriting( url ) ) {
              TQString suggestedFilename;

              KonqRun* run = childView->run();
              int attachment = 0;
              if (run) {
                  suggestedFilename = run->suggestedFilename();
                  attachment = (run->serverSuggestsSave()) ? KParts::BrowserRun::AttachmentDisposition : KParts::BrowserRun::InlineDisposition;
              }

              KParts::BrowserRun::AskSaveResult res = KParts::BrowserRun::askEmbedOrSave(
                  url, serviceType, suggestedFilename, attachment );
              if ( res == KParts::BrowserRun::Open )
                  forceAutoEmbed = true;
              else if ( res == KParts::BrowserRun::Cancel )
                  return true; // handled, don't do anything else
              else { // Save
                  KParts::BrowserRun::simpleSave( url, suggestedFilename, this );
                  return true; // handled
              }
          }
          if ( ok )
              ok = childView->changeViewMode( serviceType, serviceName, forceAutoEmbed );
      }
  }

  if (ok)
  {
      //kdDebug(1202) << "req.nameFilter= " << req.nameFilter << endl;
      //kdDebug(1202) << "req.typedURL= " << req.typedURL << endl;
      //kdDebug(1202) << "Browser extension? " << (childView->browserExtension() ? "YES" : "NO") << endl;
      //kdDebug(1202) << "Referrer: " << req.args.metaData()["referrer"] << endl;
      childView->setTypedURL( req.typedURL );
      if ( childView->browserExtension() )
          childView->browserExtension()->setURLArgs( req.args );
      if ( childView->part()->inherits("KonqDirPart") )
          static_cast<KonqDirPart *>(childView->part())->setFilesToSelect( req.filesToSelect );
      if ( !url.isEmpty() )
          childView->openURL( url, originalURL, req.nameFilter, req.tempFile );
  }
  kdDebug(1202) << "KonqMainWindow::openView ok=" << ok << " bOthersFollowed=" << bOthersFollowed << " returning "
                << (ok || bOthersFollowed)
                << endl;
  return ok || bOthersFollowed;
}

void KonqMainWindow::slotOpenURLRequest( const KURL &url, const KParts::URLArgs &args )
{
  kdDebug(1202) << "KonqMainWindow::slotOpenURLRequest frameName=" << args.frameName << endl;

  KParts::ReadOnlyPart *callingPart = static_cast<KParts::ReadOnlyPart *>( TQT_TQOBJECT_CONST(sender())->parent() );
  TQString frameName = args.frameName;

  if ( !frameName.isEmpty() )
  {
    static TQString _top = TQString::fromLatin1( "_top" );
    static TQString _self = TQString::fromLatin1( "_self" );
    static TQString _parent = TQString::fromLatin1( "_parent" );
    static TQString _blank = TQString::fromLatin1( "_blank" );

    if ( frameName.lower() == _blank )
    {
      slotCreateNewWindow( url, args );
      return;
    }

    if ( frameName.lower() != _top &&
         frameName.lower() != _self &&
         frameName.lower() != _parent )
    {
      KParts::BrowserHostExtension *hostExtension = 0;
      KonqView *view = childView( callingPart, frameName, &hostExtension, 0 );
      if ( !view )
      {
        KonqMainWindow *mainWindow = 0;
        view = findChildView( callingPart, frameName, &mainWindow, &hostExtension, 0 );

        if ( !view || !mainWindow )
        {
          slotCreateNewWindow( url, args );
          return;
        }

        if ( hostExtension )
          hostExtension->openURLInFrame( url, args );
        else
          mainWindow->openURL( view, url, args );
        return;
      }

      if ( hostExtension )
        hostExtension->openURLInFrame( url, args );
      else
        openURL( view, url, args );
      return;
    }
  }

  KonqView *view = childView( callingPart );
  openURL( view, url, args );
}

//Called by slotOpenURLRequest
void KonqMainWindow::openURL( KonqView *childView, const KURL &url, const KParts::URLArgs &args )
{
  kdDebug(1202) << "KonqMainWindow::openURL (from slotOpenURLRequest) url=" << url.prettyURL() << endl;
  KonqOpenURLRequest req;
  req.args = args;

  // Clicking on a link that points to the page itself (e.g. anchor)
  if ( !args.doPost() && !args.reload &&
          childView && urlcmp( url.url(), childView->url().url(), true, true ) )
  {
    TQString serviceType = args.serviceType;
    if ( serviceType.isEmpty() )
      serviceType = childView->serviceType();

    childView->stop();
    req.forceAutoEmbed = true;

    req.openAfterCurrentPage = KonqSettings::openAfterCurrentPage();
    openView( serviceType, url, childView, req );
    return;
  }

  openURL( childView, url, args.serviceType, req, args.trustedSource );
}

TQObject *KonqMainWindow::lastFrame( KonqView *view )
{
  TQObject *nextFrame, *viewFrame;
  nextFrame = TQT_TQOBJECT(view->frame());
  viewFrame = 0;
  while ( nextFrame != 0 && ! nextFrame->inherits( TQWIDGETSTACK_OBJECT_NAME_STRING ) ) {
    viewFrame = nextFrame;
    nextFrame = nextFrame->parent();
  }
  return nextFrame ? viewFrame : 0L;
}

// Linked-views feature, plus "sidebar follows URL opened in the active view" feature
bool KonqMainWindow::makeViewsFollow( const KURL & url, const KParts::URLArgs &args,
                                      const TQString & serviceType, KonqView * senderView )
{
  if ( !senderView->isLinkedView() && senderView != m_currentView )
    return false; // none of those features apply -> return

  bool res = false;
  //kdDebug(1202) << "makeViewsFollow " << senderView->className() << " url=" << url << " serviceType=" << serviceType << endl;
  KonqOpenURLRequest req;
  req.followMode = true;
  req.args = args;
  // We can't iterate over the map here, and openURL for each, because the map can get modified
  // (e.g. by part changes). Better copy the views into a list.
  TQPtrList<KonqView> listViews;
  MapViews::ConstIterator it = m_mapViews.begin();
  MapViews::ConstIterator end = m_mapViews.end();
  for (; it != end; ++it )
    listViews.append( it.data() );

  TQObject *senderFrame = lastFrame( senderView );

  for ( KonqView * view = listViews.first() ; view ; view = listViews.next())
  {
    bool followed = false;
    // Views that should follow this URL as both views are linked
    if ( (view != senderView) && view->isLinkedView() && senderView->isLinkedView() )
    {
      TQObject *viewFrame = lastFrame( view );

      // Only views in the same tab of the sender will follow
      if ( senderFrame && viewFrame && viewFrame != senderFrame )
        continue;

      kdDebug(1202) << "makeViewsFollow: Sending openURL to view " << view->part()->className() << " url=" << url << endl;

      // XXX duplicate code from ::openURL
      if ( view == m_currentView )
      {
        abortLoading();
        setLocationBarURL( url );
      }
      else
        view->stop();

      followed = openView( serviceType, url, view, req );
    }
    else
    {
      // Make the sidebar follow the URLs opened in the active view
      if ((view!=senderView) && view->isFollowActive() && senderView == m_currentView)
      {
        followed = openView(serviceType, url, view, req);
      }
    }

    // Ignore return value if the view followed but doesn't really
    // show the file contents. We still want to see that
    // file, e.g. in a separate viewer.
    // This happens in views locked to a directory mode,
    // like sidebar and konsolepart (#52161).
    bool ignore = view->isLockedViewMode() && view->supportsServiceType("inode/directory");
    //kdDebug(1202) << "View " << view->service()->name()
    //              << " supports dirs: " << view->supportsServiceType( "inode/directory" )
    //              << " is locked-view-mode:" << view->isLockedViewMode()
    //              << " ignore=" << ignore << endl;
    if ( !ignore )
      res = followed || res;
  }

  return res;
}

void KonqMainWindow::abortLoading()
{
  //kdDebug(1202) << "KonqMainWindow::abortLoading()" << endl;
  if ( m_currentView )
  {
    m_currentView->stop(); // will take care of the statusbar
    stopAnimation();
  }
}

void KonqMainWindow::slotCreateNewWindow( const KURL &url, const KParts::URLArgs &args )
{
    kdDebug(1202) << "KonqMainWindow::slotCreateNewWindow url=" << url.prettyURL() << endl;

    if ( args.newTab() || ( KonqSettings::mmbOpensTab() &&
         (const_cast<KParts::URLArgs*>(&args)->metaData()["forcenewwindow"]).isEmpty()) ) {
      KonqOpenURLRequest req;
      req.newTab = true;
      req.newTabInFront = KonqSettings::newTabsInFront();
      req.openAfterCurrentPage = KonqSettings::openAfterCurrentPage();

      if (TDEApplication::keyboardMouseState() & TQt::ShiftButton)
        req.newTabInFront = !req.newTabInFront;
      req.args = args;
      openURL( 0L, url, TQString::null, req );
    }
    else
    {
      KonqMisc::createNewWindow( url, args );
    }
}

// This is mostly for the JS window.open call
void KonqMainWindow::slotCreateNewWindow( const KURL &url, const KParts::URLArgs &args,
                                          const KParts::WindowArgs &windowArgs, KParts::ReadOnlyPart *&part )
{
    kdDebug(1202) << "KonqMainWindow::slotCreateNewWindow(4 args) url=" << url.prettyURL()
                  << " args.serviceType=" << args.serviceType
                  << " args.frameName=" << args.frameName << endl;

    part = 0; // Make sure to be initialized in case of failure...

    KonqMainWindow *mainWindow = 0L;
    if ( !args.frameName.isEmpty() && args.frameName.lower() != "_blank" )
    {
        KParts::BrowserHostExtension *hostExtension = 0;
        KParts::ReadOnlyPart *ro_part = 0L;
        KParts::BrowserExtension *be = ::tqqt_cast<KParts::BrowserExtension *>(sender());
        if (be)
            ro_part = ::tqqt_cast<KParts::ReadOnlyPart *>(be->parent());
        if ( findChildView( ro_part, args.frameName, &mainWindow, &hostExtension, &part ) )
        {
            // Found a view. If url isn't empty, we should open it - but this never happens currently
            // findChildView put the resulting part in 'part', so we can just return now
            //kdDebug() << " frame=" << args.frameName << " -> found part=" << part << " " << part->name() << endl;
            return;
        }
    }

    if ( KonqSettings::popupsWithinTabs() || ( KonqSettings::mmbOpensTab() && windowArgs.lowerWindow ) ) {
      bool aftercurrentpage = KonqSettings::openAfterCurrentPage();
      bool newtabsinfront = KonqSettings::newTabsInFront();
        if ( windowArgs.lowerWindow )
           newtabsinfront =! newtabsinfront;

        KonqView* newView = m_pViewManager->addTab(TQString::null, TQString::null, false, aftercurrentpage);
        if (newView == 0L) return;

        if (newtabsinfront)
          m_pViewManager->showTab( newView );

        openURL( newView, url.isEmpty() ? KURL("about:blank") : url, TQString::null);
        newView->setViewName( args.frameName );
        part=newView->part();

        return;
    }

    mainWindow = new KonqMainWindow( KURL(), false );
    mainWindow->setInitialFrameName( args.frameName );
    mainWindow->resetAutoSaveSettings(); // Don't autosave

    KonqOpenURLRequest req;
    req.args = args;

    if ( args.serviceType.isEmpty() )
      mainWindow->openURL( 0L, url, TQString::null, req );
    else if ( !mainWindow->openView( args.serviceType, url, 0L, req ) )
    {
      // we have problems. abort.
      delete mainWindow;
      part = 0;
      return;
    }

    KonqView * view = 0L;
    // cannot use activePart/currentView, because the activation through the partmanager
    // is delayed by a singleshot timer (see KonqViewManager::setActivePart)
    if ( mainWindow->viewMap().count() )
    {
      MapViews::ConstIterator it = mainWindow->viewMap().begin();
      view = it.data();
      part = it.key();
    }

    // activate the view _now_ in order to make the menuBar() hide call work
    if ( part ) {
       mainWindow->viewManager()->setActivePart( part, true );
    }

    TQString profileName = TQString::fromLatin1( url.isLocalFile() ? "konqueror/profiles/filemanagement" : "konqueror/profiles/webbrowsing" );
    KSimpleConfig cfg( locate( "data", profileName ), true );
    cfg.setGroup( "Profile" );

    if ( windowArgs.x != -1 )
        mainWindow->move( windowArgs.x, mainWindow->y() );
    if ( windowArgs.y != -1 )
        mainWindow->move( mainWindow->x(), windowArgs.y );

    TQSize size = KonqViewManager::readConfigSize( cfg, mainWindow );

    int width;
    if ( windowArgs.width != -1 )
        width = windowArgs.width;
    else
        width = size.isValid() ? size.width() : mainWindow->width();

    int height;
    if ( windowArgs.height != -1 )
        height = windowArgs.height;
    else
        height = size.isValid() ? size.height() : mainWindow->height();

    mainWindow->resize( width, height );

    // process the window args

    if ( !windowArgs.menuBarVisible )
    {
        mainWindow->menuBar()->hide();
        mainWindow->m_paShowMenuBar->setChecked( false );
    }

    if ( !windowArgs.toolBarsVisible )
    {
      for ( TQPtrListIterator<KToolBar> it( mainWindow->toolBarIterator() ); it.current(); ++it )
      {
        (*it)->hide();
      }
    }

    if ( view ) {
        if ( !windowArgs.scrollBarsVisible )
            view->disableScrolling();
        if ( !windowArgs.statusBarVisible )
            view->frame()->statusbar()->hide();
    }

    if ( !windowArgs.resizable )
        // ### this doesn't seem to work :-(
        mainWindow->setSizePolicy( TQSizePolicy( TQSizePolicy::Fixed, TQSizePolicy::Fixed ) );

// Trying to show the window initially behind the current window is a bit tricky,
// as this involves the window manager, which may see things differently.
// Many WMs raise and activate new windows, which means without WM support this won't work very
// well. If the WM has support for _NET_WM_USER_TIME, it will be just set to 0 (=don't focus on show),
// and the WM should take care of it itself.
    bool wm_usertime_support = false;
    Time saved_last_input_time = GET_QT_X_USER_TIME();
    if ( windowArgs.lowerWindow )
    {
        NETRootInfo wm_info( tqt_xdisplay(), NET::Supported );
        wm_usertime_support = wm_info.isSupported( NET::WM2UserTime );
        if( wm_usertime_support )
        {
        // *sigh*, and I thought nobody would need TQWidget::dontFocusOnShow().
        // Avoid Qt's support for user time by setting it to 0, and
        // set the property ourselves.
            SET_QT_X_USER_TIME(0);
            KWin::setUserTime( mainWindow->winId(), 0 );
        }
        // Put below the current window before showing, in case that actually works with the WM.
        // First do complete lower(), then stackUnder(), because the latter may not work with many WMs.
        mainWindow->lower();
        mainWindow->stackUnder( this );
    }

    mainWindow->show();

    if ( windowArgs.lowerWindow )
    {
        SET_QT_X_USER_TIME(saved_last_input_time);
        if( !wm_usertime_support )
        { // No WM support. Let's try ugly tricks.
            mainWindow->lower();
            mainWindow->stackUnder( this );
            if( this->isActiveWindow())
                this->setActiveWindow();
        }
    }

    if ( windowArgs.fullscreen )
        mainWindow->action( "fullscreen" )->activate();
}

void KonqMainWindow::slotNewWindow()
{
  // Use profile from current window, if set
  TQString profile = m_pViewManager->currentProfile();
  if ( profile.isEmpty() )
  {
    if ( m_currentView && m_currentView->url().protocol().startsWith( "http" ) )
       profile = TQString::fromLatin1("webbrowsing");
    else
       profile = TQString::fromLatin1("filemanagement");
  }
  KonqMisc::createBrowserWindowFromProfile(
    locate( "data", TQString::fromLatin1("konqueror/profiles/")+profile ),
    profile );
}

void KonqMainWindow::slotDuplicateWindow()
{
  KTempFile tempFile;
  tempFile.setAutoDelete( true );
  TDEConfig config( tempFile.name() );
  config.setGroup( "View Profile" );
  m_pViewManager->saveViewProfile( config, true, true );

  KonqMainWindow *mainWindow = new KonqMainWindow( KURL(), false, 0, xmlFile());
  mainWindow->viewManager()->loadViewProfile( config, m_pViewManager->currentProfile() );
  if (mainWindow->currentView())
  {
      mainWindow->copyHistory( childFrame() );
  }
  mainWindow->activateChild();
  mainWindow->show();
#ifndef NDEBUG
  mainWindow->viewManager()->printFullHierarchy( this );
#endif
}

void KonqMainWindow::slotSendURL()
{
  KURL::List lst = currentURLs();
  TQString body;
  TQString fileNameList;
  for ( KURL::List::Iterator it = lst.begin() ; it != lst.end() ; ++it )
  {
    if ( !body.isEmpty() ) body += '\n';
    body += (*it).prettyURL();
    if ( !fileNameList.isEmpty() ) fileNameList += ", ";
    fileNameList += (*it).fileName();
  }
  TQString subject;
  if ( m_currentView && !m_currentView->part()->inherits("KonqDirPart") )
    subject = m_currentView->caption();
  else
    subject = fileNameList;
  kapp->invokeMailer(TQString::null,TQString::null,TQString::null,
                     subject, body);
}

void KonqMainWindow::slotSendFile()
{
  KURL::List lst = currentURLs();
  TQStringList urls;
  TQString fileNameList;
  for ( KURL::List::Iterator it = lst.begin() ; it != lst.end() ; ++it )
  {
    if ( !fileNameList.isEmpty() ) fileNameList += ", ";
    if ( (*it).isLocalFile() && TQFileInfo((*it).path()).isDir() )
    {
        // Create a temp dir, so that we can put the ZIP file in it with a proper name
        KTempFile zipFile;
        TQString zipFileName = zipFile.name();
        zipFile.unlink();

        TQDir().mkdir(zipFileName,true);
        zipFileName = zipFileName+"/"+(*it).fileName()+".zip";
        KZip zip( zipFileName );
        if ( !zip.open( IO_WriteOnly ) )
            continue; // TODO error message
        zip.addLocalDirectory( (*it).path(), TQString::null );
        zip.close();
        fileNameList += (*it).fileName()+".zip";
        urls.append( zipFileName );
    }
    else
    {
        fileNameList += (*it).fileName();
        urls.append( (*it).url() );
    }
  }
  TQString subject;
  if ( m_currentView && !m_currentView->part()->inherits("KonqDirPart") )
    subject = m_currentView->caption();
  else
    subject = fileNameList;
  kapp->invokeMailer(TQString::null, TQString::null, TQString::null, subject,
                     TQString::null, //body
                     TQString::null,
                     urls); // attachments
}

void KonqMainWindow::slotOpenTerminal()
{
  TQString term = KonqSettings::terminalApplication();

  TQString dir ( TQDir::homeDirPath() );

  //Try to get the directory of the current view
  if ( m_currentView )
  {
      KURL u( m_currentView->url() );

      // If the given directory is not local, it can still be the URL of an
      // ioslave using UDS_LOCAL_PATH which to be converted first.
      u = TDEIO::NetAccess::mostLocalURL(u, this);

      //If the URL is local after the above conversion, set the directory.
      if ( u.isLocalFile() )
      {
          TQString mime = m_currentView->serviceType();
          if ( KMimeType::mimeType(mime)->is("inode/directory") )
              dir = u.path();
          else
              dir = u.directory();
      }
  }

  TDEProcess cmd;
  cmd.setWorkingDirectory(dir);

  // Compensate for terminal having arguments.
  TQStringList args = TQStringList::split(' ', term);
  for ( TQStringList::iterator it = args.begin(); it != args.end(); ++it )
    cmd << *it;

  kdDebug(1202) << "slotOpenTerminal: directory " << dir
		<< ", terminal:" << term << endl;
  cmd.start(TDEProcess::DontCare);
}

void KonqMainWindow::slotOpenLocation()
{
  // Don't pre-fill the url, as it is auto-selected and thus overwrites the
  // X clipboard, making it impossible to paste in the url you really wanted.
  // Another example of why the X clipboard sux
  KURLRequesterDlg dlg( TQString::null, this, 0, true);
  dlg.setCaption( i18n("Open Location") );
  // Set current directory for relative paths.
  // Testcase: konqueror www.kde.org; Ctrl+O; file in $HOME; would open http://$file
  TQString currentDir;
  if (m_currentView && m_currentView->url().isLocalFile())
      currentDir = m_currentView->url().path(1);
  dlg.urlRequester()->completionObject()->setDir( currentDir );
  dlg.urlRequester()->setMode( KFile::File | KFile::Directory | KFile::ExistingOnly );
  dlg.exec();
  const KURL& url = dlg.selectedURL();
  if (!url.isEmpty())
     openFilteredURL( url.url().stripWhiteSpace() );
}

void KonqMainWindow::slotToolFind()
{
  kdDebug(1202) << "KonqMainWindow::slotToolFind sender:" << TQT_TQOBJECT_CONST(sender())->className() << endl;

  if ( m_currentView && m_currentView->part()->inherits("KonqDirPart") )
  {
    KonqDirPart* dirPart = static_cast<KonqDirPart *>(m_currentView->part());

    if (!m_paFindFiles->isChecked())
    {
        dirPart->slotFindClosed();
        return;
    }

    KonqViewFactory factory = KonqFactory::createView( "Konqueror/FindPart" );
    if ( factory.isNull() )
    {
        KMessageBox::error( this, i18n("Cannot create the find part, check your installation.") );
        m_paFindFiles->setChecked(false);
        return;
    }

    KParts::ReadOnlyPart* findPart = factory.create( m_currentView->frame(), "findPartWidget", dirPart, "findPart" );
    dirPart->setFindPart( findPart );

    m_currentView->frame()->insertTopWidget( findPart->widget() );
    findPart->widget()->show();
    findPart->widget()->setFocus();

    connect( dirPart, TQT_SIGNAL( findClosed(KonqDirPart *) ),
             this, TQT_SLOT( slotFindClosed(KonqDirPart *) ) );
  }
  else if ( TQT_TQOBJECT_CONST(sender())->inherits( "KAction" ) ) // don't go there if called by the singleShot below
  {
      KURL url;
      if ( m_currentView && m_currentView->url().isLocalFile() )
          url = m_currentView->locationBarURL();
      else
          url.setPath( TQDir::homeDirPath() );
      KonqMainWindow * mw = KonqMisc::createBrowserWindowFromProfile(
          locate( "data", TQString::fromLatin1("konqueror/profiles/filemanagement") ),
          "filemanagement", url, KParts::URLArgs(), true /* forbid "use html"*/ );
      mw->m_paFindFiles->setChecked(true);
      // Delay it after the openURL call (hacky!)
      TQTimer::singleShot( 1, mw, TQT_SLOT(slotToolFind()));
      m_paFindFiles->setChecked(false);
  }
}

void KonqMainWindow::slotFindOpen( KonqDirPart * dirPart )
{
    kdDebug(1202) << "KonqMainWindow::slotFindOpen " << dirPart << endl;
    Q_ASSERT( m_currentView );
    Q_ASSERT( m_currentView->part() == dirPart );
    slotToolFind(); // lazy me
}

void KonqMainWindow::slotFindClosed( KonqDirPart * dirPart )
{
    kdDebug(1202) << "KonqMainWindow::slotFindClosed " << dirPart << endl;
    KonqView * dirView = m_mapViews.find( dirPart ).data();
    Q_ASSERT(dirView);
    kdDebug(1202) << "dirView=" << dirView << endl;
    if ( dirView && dirView == m_currentView )
        m_paFindFiles->setEnabled( true );
    m_paFindFiles->setChecked(false);
}

void KonqMainWindow::slotIconsChanged()
{
    //kdDebug(1202) << "KonqMainWindow::slotIconsChanged" << endl;
    m_combo->updatePixmaps();
    m_pViewManager->updatePixmaps();
    setIcon( KonqPixmapProvider::self()->pixmapFor( m_combo->currentText() ));
}

void KonqMainWindow::slotOpenWith()
{
  KURL::List lst;
  lst.append( m_currentView->url() );

  TQString serviceName = TQT_TQOBJECT_CONST(sender())->name();

  KTrader::OfferList offers = m_currentView->appServiceOffers();
  KTrader::OfferList::ConstIterator it = offers.begin();
  KTrader::OfferList::ConstIterator end = offers.end();
  for (; it != end; ++it )
    if ( (*it)->desktopEntryName() == serviceName )
    {
      KRun::run( **it, lst );
      return;
    }
}

void KonqMainWindow::slotViewModeToggle( bool toggle )
{
  if ( !toggle )
    return;

  TQString modeName = TQT_TQOBJECT_CONST(sender())->name();

  if ( m_currentView->service()->desktopEntryName() == modeName )
    return;

  m_bViewModeToggled = true;

  m_currentView->stop();
  m_currentView->lockHistory();

  // Save those, because changeViewMode will lose them
  KURL url = m_currentView->url();
  TQString locationBarURL = m_currentView->locationBarURL();
  TQStringList filesToSelect;
  if( m_currentView->part()->inherits( "KonqDirPart" ) ) {
     KFileItemList fileItemsToSelect = static_cast<KonqDirPart*>(m_currentView->part())->selectedFileItems();
     KFileItemListIterator it( fileItemsToSelect );
     while( it.current() ){
         filesToSelect += it.current()->name();
         ++it;
     }
  }


  bool bQuickViewModeChange = false;

  // iterate over all services, update the toolbar service map
  // and check if we can do a quick property-based viewmode change
  const KTrader::OfferList offers = m_currentView->partServiceOffers();
  KTrader::OfferList::ConstIterator oIt = offers.begin();
  KTrader::OfferList::ConstIterator oEnd = offers.end();
  const TQString currentServiceKey = viewModeActionKey( m_currentView->service() );
  for (; oIt != oEnd; ++oIt )
  {
      KService::Ptr service = *oIt;

      if ( service->desktopEntryName() == modeName )
      {
          // we changed the viewmode of either iconview or listview
          // -> update the service in the corresponding map, so that
          // we can set the correct text, icon, etc. properties to the
          // KonqViewModeAction when rebuilding the view-mode actions in
          // updateViewModeActions
          // (I'm saying iconview/listview here, but theoretically it could be
          //  any view :)
          const TQString serviceKey = viewModeActionKey( service );
          m_viewModeToolBarServices[ serviceKey ] = service;

          if ( serviceKey == currentServiceKey )
          {
              TQVariant modeProp = service->property( "X-TDE-BrowserView-ModeProperty" );
              TQVariant modePropValue = service->property( "X-TDE-BrowserView-ModePropertyValue" );
              if ( !modeProp.isValid() || !modePropValue.isValid() )
                  break;

              m_currentView->part()->setProperty( modeProp.toString().latin1(), modePropValue );

              KService::Ptr oldService = m_currentView->service();

              // we aren't going to re-build the viewmode actions but instead of a
              // quick viewmode change (iconview) -> find the iconview-konqviewmode
              // action and set new text,icon,etc. properties, to show the new
              // current viewmode
              TQPtrListIterator<KAction> it( m_toolBarViewModeActions );
              for (; it.current(); ++it )
                  if ( TQString::fromLatin1( it.current()->name() ) == oldService->desktopEntryName() )
                  {
                      assert( it.current()->inherits( "KonqViewModeAction" ) );

                      KonqViewModeAction *action = static_cast<KonqViewModeAction *>( it.current() );

                      action->setChecked( true );
		      TQString servicename = service->genericName();
		      if (servicename.isEmpty())
		          servicename = service->name();
                      action->setText( servicename );
                      action->setIcon( service->icon() );
                      action->setName( service->desktopEntryName().ascii() );

                      break;
                  }

              m_currentView->setService( service );

              bQuickViewModeChange = true;
              break;
          }
      }
  }

  if ( !bQuickViewModeChange )
  {
    m_currentView->changeViewMode( m_currentView->serviceType(), modeName );
    KURL locURL = KURL::fromPathOrURL( locationBarURL );
    TQString nameFilter = detectNameFilter( locURL );
    if( m_currentView->part()->inherits( "KonqDirPart" ) )
       static_cast<KonqDirPart*>( m_currentView->part() )->setFilesToSelect( filesToSelect );
    m_currentView->openURL( locURL, locationBarURL, nameFilter );
  }

  // Now save this setting, either locally or globally (for directories only)
  // (We don't have views with viewmodes other than for dirs currently;
  // once we do, we might want to implement per-mimetype global-saving)
  if ( m_bSaveViewPropertiesLocally && m_currentView->supportsServiceType( "inode/directory" ) )
  {
      KURL u ( m_currentView->url() );
      u.addPath(".directory");
      if ( u.isLocalFile() )
      {
          KSimpleConfig config( u.path() ); // if we have no write access, just drop it
          config.setGroup( "URL properties" );
          config.writeEntry( "ViewMode", modeName );
          config.sync();
      }
  } else
  {
      // We save the global view mode only if the view is a built-in view
      if ( m_currentView->isBuiltinView() )
      {
          KonqSettings::setMainViewViewMode( modeName );
          KonqSettings::writeConfig();
      }
  }
}

void KonqMainWindow::showHTML( KonqView * _view, bool b, bool _activateView )
{
  // Save this setting, either locally or globally
  // This has to be done before calling openView since it relies on it
  if ( m_bSaveViewPropertiesLocally )
  {
      KURL u ( b ? _view->url() : KURL( _view->url().directory() ) );
      u.addPath(".directory");
      if ( u.isLocalFile() )
      {
          KSimpleConfig config( u.path() ); // No checks for access
          config.setGroup( "URL properties" );
          config.writeEntry( "HTMLAllowed", b );
          config.sync();
      }
  } else
  {
      KonqSettings::setHtmlAllowed( b );
      KonqSettings::writeConfig();
      if ( _activateView )
          m_bHTMLAllowed = b;
  }

  if ( b && _view->supportsServiceType( "inode/directory" ) )
  {
    _view->lockHistory();
    openView( "inode/directory", _view->url(), _view );
  }
  else if ( !b && _view->supportsServiceType( "text/html" ) )
  {
    KURL u( _view->url() );
    TQString fileName = u.fileName().lower();
    if ( KProtocolInfo::supportsListing( u ) && fileName.startsWith("index.htm") ) {
        _view->lockHistory();
        u.setPath( u.directory() );
        openView( "inode/directory", u, _view );
    }
  }
}

void KonqMainWindow::slotShowHTML()
{
  bool b = !m_currentView->allowHTML();

  m_currentView->stop();
  m_currentView->setAllowHTML( b );
  showHTML( m_currentView, b, true ); //current view
  m_pViewManager->showHTML(b );

}

void KonqMainWindow::setShowHTML( bool b )
{
    m_bHTMLAllowed = b;
    if ( m_currentView )
        m_currentView->setAllowHTML( b );
    m_ptaUseHTML->setChecked( b );
}

void KonqMainWindow::slotLockView()
{
  m_currentView->setLockedLocation( m_paLockView->isChecked() );
}

void KonqMainWindow::slotStop()
{
  abortLoading();
  if ( m_currentView )
  {
    m_currentView->frame()->statusbar()->message( i18n("Canceled.") );
  }
}

void KonqMainWindow::slotLinkView()
{
  // Can't access this action in passive mode anyway
  assert(!m_currentView->isPassiveMode());
  bool mode = !m_currentView->isLinkedView();

  if (linkableViewsCount() == 2)
  {
    // Exactly two linkable views : link both
    KonqMainWindow::MapViews::ConstIterator it = viewMap().begin();
    if( (*it)->isFollowActive() ) // skip sidebar
        ++it;
    (*it)->setLinkedView( mode );
    ++it;
    if( (*it)->isFollowActive() ) // skip sidebar
        ++it;
    (*it)->setLinkedView( mode );
  }
  else // Normal case : just this view
    m_currentView->setLinkedView( mode );
}

void KonqMainWindow::slotReload( KonqView* reloadView )
{
  if ( !reloadView )
    reloadView = m_currentView;

  if ( !reloadView || reloadView->url().isEmpty() )
    return;

  if ( reloadView->part() && (reloadView->part()->metaObject()->findProperty("modified") != -1)  ) {
    TQVariant prop = reloadView->part()->property("modified");
    if (prop.isValid() && prop.toBool())
      if ( KMessageBox::warningContinueCancel( this,
           i18n("This page contains changes that have not been submitted.\nReloading the page will discard these changes."),
           i18n("Discard Changes?"), KGuiItem(i18n("&Discard Changes"),"reload"), "discardchangesreload") != KMessageBox::Continue )
        return;
  }

  KonqOpenURLRequest req( reloadView->typedURL() );
  req.userRequestedReload = true;
  if ( reloadView->prepareReload( req.args ) )
  {
      reloadView->lockHistory();
      // Reuse current servicetype for local files, but not for remote files (it could have changed, e.g. over HTTP)
      TQString serviceType = reloadView->url().isLocalFile() ? reloadView->serviceType() : TQString::null;
      openURL( reloadView, reloadView->url(), serviceType, req );
  }
}

void KonqMainWindow::slotReloadStop() {
  if (m_paReloadStop->icon() == "reload") {
    slotReload();
    toggleReloadStopButton(true);
  } else {
    slotStop();
    toggleReloadStopButton(false);
  }
}

void KonqMainWindow::toggleReloadStopButton(bool isReload) {
  //m_paStop = new KAction( i18n( "&Stop" ), "stop", Key_Escape, this, TQT_SLOT( slotStop() ), actionCollection(), "stop" );
  if (isReload) {
    m_paReloadStop->setIcon("stop");
    m_paReloadStop->setWhatsThis( i18n( "Stop loading the document<p>"
                                        "All network transfers will be stopped and Konqueror will display the content "
                                        "that has been received so far." ) );
    m_paReloadStop->setToolTip( i18n( "Stop loading the document" ) );
  //m_paReloadStop = new KAction( i18n( "&Reload" ), "reload", reloadShortcut, this, TQT_SLOT( slotReloadStop() ), actionCollection(), "reload" );
  } else {
    m_paReloadStop->setIcon("reload");
    m_paReloadStop->setWhatsThis( i18n( "Reload the currently displayed document<p>"
                                        "This may, for example, be needed to refresh webpages that have been "
                                        "modified since they were loaded, in order to make the changes visible." ) );
    m_paReloadStop->setToolTip( i18n( "Reload the currently displayed document" ) );
  }
}

void KonqMainWindow::slotReloadPopup()
{
  if (m_pWorkingTab)
    slotReload( m_pWorkingTab->activeChildView() );
}

void KonqMainWindow::slotHome(KAction::ActivationReason, TQt::ButtonState state)
{
    TQString homeURL = m_pViewManager->profileHomeURL();

    if (homeURL.isEmpty())
	homeURL = KonqFMSettings::settings()->homeURL();

    KonqOpenURLRequest req;
    req.newTab = true;
    req.newTabInFront = KonqSettings::newTabsInFront();

    if (state & TQt::ShiftButton)
        req.newTabInFront = !req.newTabInFront;

    if( state & TQt::ControlButton ) // Ctrl Left/MMB
	openFilteredURL( homeURL, req);
    else if( state & Qt::MidButton )
    {
        if(KonqSettings::mmbOpensTab())
	    openFilteredURL( homeURL, req);
	else
	{
	    KURL finalURL = KonqMisc::konqFilteredURL( this, homeURL );
	    KonqMisc::createNewWindow( finalURL.url() );
	}
    }
    else
	openFilteredURL( homeURL, false );
}


void KonqMainWindow::slotHome()
{
    slotHome(KAction::UnknownActivation, Qt::LeftButton);
}

void KonqMainWindow::slotGoSystem()
{
  openURL( 0L, KURL( "system:/" ) );
}

void KonqMainWindow::slotGoApplications()
{
  openURL( 0L, KURL( "programs:/" ) );
}

void KonqMainWindow::slotGoMedia()
{
  openURL( 0L, KURL( "media:/" ) );
}

void KonqMainWindow::slotGoNetworkFolders()
{
    openURL( 0L, KURL( "remote:/" ) );
}

void KonqMainWindow::slotGoSettings()
{
  openURL( 0L, KURL( "settings:/" ) );
}

void KonqMainWindow::slotGoDirTree()
{
  KURL u;
  u.setPath( locateLocal( "data", "konqueror/dirtree/" ) );
  openURL( 0L, u );
}

void KonqMainWindow::slotGoTrash()
{
  openURL( 0L, KURL( "trash:/" ) );
}

void KonqMainWindow::slotGoAutostart()
{
  KURL u;
  u.setPath( TDEGlobalSettings::autostartPath() );
  openURL( 0L, u );
}

void KonqMainWindow::slotGoHistory()
{
  KAction *a = m_toggleViewGUIClient->action("konq_sidebartng");
  if (!a) {
    KMessageBox::sorry(0L, i18n("Your sidebar is not functional or unavailable."), i18n("Show History Sidebar"));
    return;
  }

  // Show the sidebar
  if (!static_cast<KToggleAction*>(a)->isChecked()) {
    a->activate();
    TQTimer::singleShot( 0, this, TQT_SLOT(slotGoHistory()));
    return;
  }

  // Tell it to show the history plugin
  MapViews::ConstIterator it;
  for (it = viewMap().begin(); it != viewMap().end(); ++it) {
    KonqView *view = it.data();
    if (view) {
      KService::Ptr svc = view->service();
      if (svc->desktopEntryName() == "konq_sidebartng") {
        if (!view->part()->openURL("sidebar:history.desktop"))
          KMessageBox::sorry(0L, i18n("Cannot find running history plugin in your sidebar."), i18n("Show History Sidebar"));
        break;
      }
    }
  }
}

TQStringList KonqMainWindow::configModules() const
{
    return m_configureModules;
}

void KonqMainWindow::slotConfigureExtensions()
{
    KonqExtensionManager extensionManager(0, this, m_currentView ? m_currentView->part() : 0);
    extensionManager.exec();
}

void KonqMainWindow::slotConfigure()
{
    if( !m_configureDialog )
    {
        m_configureDialog = new KCMultiDialog( this, "configureDialog" );

        TQStringList modules = configModules();
        TQStringList::ConstIterator end( modules.end() );

        for( TQStringList::ConstIterator it = modules.begin();
                it != end; ++it )
        {
            if ( kapp->authorizeControlModule( *it ) )
            {
                m_configureDialog->addModule( *it );
            }
        }

    }

    m_configureDialog->show();

}

void KonqMainWindow::slotConfigureSpellChecking()
{
    TDEApplication::startServiceByDesktopName("spellchecking");
}

void KonqMainWindow::slotConfigureToolbars()
{
  if ( autoSaveSettings() )
    saveMainWindowSettings( TDEGlobal::config(), "KonqMainWindow" );
  KEditToolbar dlg(factory());
  connect(&dlg,TQT_SIGNAL(newToolbarConfig()),this,TQT_SLOT(slotNewToolbarConfig()));
  connect(&dlg,TQT_SIGNAL(newToolbarConfig()),this,TQT_SLOT(initBookmarkBar()));
  dlg.exec();
}

void KonqMainWindow::slotNewToolbarConfig() // This is called when OK or Apply is clicked
{
    if ( m_toggleViewGUIClient )
      plugActionList( TQString::fromLatin1( "toggleview" ), m_toggleViewGUIClient->actions() );
    if ( m_currentView && m_currentView->appServiceOffers().count() > 0 )
      plugActionList( "openwith", m_openWithActions );

    plugViewModeActions();

    applyMainWindowSettings( TDEGlobal::config(), "KonqMainWindow" );
}

void KonqMainWindow::slotUndoAvailable( bool avail )
{
  bool enable = false;

  if ( avail && m_currentView && m_currentView->part() )
  {
    // Avoid tqWarning from TQObject::property if it doesn't exist
    if ( m_currentView->part()->metaObject()->findProperty( "supportsUndo" ) != -1 )
    {
      TQVariant prop = m_currentView->part()->property( "supportsUndo" );
      if ( prop.isValid() && prop.toBool() )
        enable = true;
    }
  }

  m_paUndo->setEnabled( enable );
}

void KonqMainWindow::slotPartChanged( KonqView *childView, KParts::ReadOnlyPart *oldPart, KParts::ReadOnlyPart *newPart )
{
  kdDebug(1202) << "KonqMainWindow::slotPartChanged" << endl;
  m_mapViews.remove( oldPart );
  m_mapViews.insert( newPart, childView );

  // Remove the old part, and add the new part to the manager
  // Note: this makes the new part active... so it calls slotPartActivated

  m_pViewManager->replacePart( oldPart, newPart, false );
  // Set active immediately
  m_pViewManager->setActivePart( newPart, true );

  viewsChanged();
}


void KonqMainWindow::slotRunFinished()
{
  kdDebug(1202) << "KonqMainWindow::slotRunFinished()" << endl;
  const KonqRun *run = static_cast<const KonqRun *>( sender() );

  if ( run == m_initialKonqRun )
      m_initialKonqRun = 0L;

  if ( !run->mailtoURL().isEmpty() )
  {
      kapp->invokeMailer( run->mailtoURL() );
  }

  if ( run->hasError() ) { // we had an error
      TQByteArray data;
      TQDataStream s( data, IO_WriteOnly );
      s << run->url().prettyURL() << kapp->dcopClient()->defaultObject();
      kapp->dcopClient()->send( "konqueror*", "KonquerorIface",
				"removeFromCombo(TQString,TQCString)", data);
  }

  KonqView *childView = run->childView();

  // Check if we found a mimetype _and_ we got no error (example: cancel in openwith dialog)
  if ( run->foundMimeType() && !run->hasError() )
  {

    // We do this here and not in the constructor, because
    // we are waiting for the first view to be set up before doing this...
    // Note: this is only used when konqueror is started from command line.....
    if ( m_bNeedApplyKonqMainWindowSettings )
    {
      m_bNeedApplyKonqMainWindowSettings = false; // only once
      applyKonqMainWindowSettings();
    }

    return;
  }

  if ( childView )
  {
    childView->setLoading( false );

    if ( childView == m_currentView )
    {
      stopAnimation();

      // Revert to working URL - unless the URL was typed manually
      kdDebug(1202) << " typed URL = " << run->typedURL() << endl;
      if ( run->typedURL().isEmpty() && childView->history().current() ) // not typed
        childView->setLocationBarURL( childView->history().current()->locationBarURL );
    }
  }
  else // No view, e.g. empty webbrowsing profile
    stopAnimation();
}

void KonqMainWindow::applyKonqMainWindowSettings()
{
  TQStringList toggableViewsShown = KonqSettings::toggableViewsShown();
  TQStringList::ConstIterator togIt = toggableViewsShown.begin();
  TQStringList::ConstIterator togEnd = toggableViewsShown.end();
  for ( ; togIt != togEnd ; ++togIt )
  {
    // Find the action by name
  //    KAction * act = m_toggleViewGUIClient->actionCollection()->action( (*togIt).latin1() );
    KAction *act = m_toggleViewGUIClient->action( *togIt );
    if ( act )
      act->activate();
    else
      kdWarning(1202) << "Unknown toggable view in ToggableViewsShown " << *togIt << endl;
  }
}

void KonqMainWindow::slotSetStatusBarText( const TQString & )
{
   // Reimplemented to disable KParts::MainWindow default behaviour
   // Does nothing here, see konq_frame.cc
}

void KonqMainWindow::slotViewCompleted( KonqView * view )
{
  assert( view );

  // Need to update the current working directory
  // of the completion object every time the user
  // changes the directory!! (DA)
  if( m_pURLCompletion )
  {
    KURL u( view->locationBarURL() );
    if( u.isLocalFile() )
      m_pURLCompletion->setDir( u.path() );
    else
      m_pURLCompletion->setDir( u.url() );  //needs work!! (DA)
  }
}

void KonqMainWindow::slotPartActivated( KParts::Part *part )
{
  kdDebug(1202) << "KonqMainWindow::slotPartActivated " << part << " "
                <<  ( part && part->instance() && part->instance()->aboutData() ? part->instance()->aboutData()->appName() : "" ) << endl;

  KonqView *newView = 0;
  KonqView *oldView = m_currentView;

  if ( part )
  {
    newView = m_mapViews.find( static_cast<KParts::ReadOnlyPart *>( part ) ).data();

    if ( newView->isPassiveMode() )
    {
      // Passive view. Don't connect anything, don't change m_currentView
      // Another view will become the current view very soon
      kdDebug(1202) << "KonqMainWindow::slotPartActivated: Passive mode - return" << endl;
      return;
    }
  }

  KParts::BrowserExtension *ext = 0;

  if ( oldView )
  {
    ext = oldView->browserExtension();
    if ( ext )
    {
      //kdDebug(1202) << "Disconnecting extension for view " << oldView << endl;
      disconnectExtension( ext );
    }

    if ( oldView->part() )
    {
      KActionCollection *coll = oldView->part()->actionCollection();
      if ( coll )
          disconnectActionCollection( coll );
    }
  }

  kdDebug(1202) << "KonqMainWindow::slotPartActivated: New current view " << newView << endl;
  m_currentView = newView;
  if ( !part )
  {
    kdDebug(1202) << "KonqMainWindow::slotPartActivated: No part activated - returning" << endl;
    unplugViewModeActions();
    createGUI( 0L );
    KParts::MainWindow::setCaption( "" );
    KParts::MainWindow::setIcon( kapp->icon());
    return;
  }

  ext = m_currentView->browserExtension();

  if ( ext )
  {
    connectExtension( ext );
  }
  else
  {
    kdDebug(1202) << "KonqMainWindow::slotPartActivated: No Browser Extension for the new part" << endl;
    // Disable all browser-extension actions

    KParts::BrowserExtension::ActionSlotMap * actionSlotMap = KParts::BrowserExtension::actionSlotMapPtr();
    KParts::BrowserExtension::ActionSlotMap::ConstIterator it = actionSlotMap->begin();
    KParts::BrowserExtension::ActionSlotMap::ConstIterator itEnd = actionSlotMap->end();

    for ( ; it != itEnd ; ++it )
    {
      KAction * act = actionCollection()->action( static_cast<const char *>(it.key()) );
      Q_ASSERT(act);
      if (act)
        act->setEnabled( false );
    }

    if ( m_paCopyFiles )
      m_paCopyFiles->setEnabled( false );
    if ( m_paMoveFiles )
      m_paMoveFiles->setEnabled( false );
    if ( m_paNewDir )
      m_paNewDir->setEnabled( false );
  }
  createGUI( part );

  KActionCollection *coll = m_currentView->part()->actionCollection();
  if ( coll )
      connectActionCollection( coll );

  // View-dependent GUI

  KParts::MainWindow::setCaption( m_currentView->caption() );
  m_currentView->frame()->setTitle( m_currentView->caption() , 0L);
  updateOpenWithActions();
  updateLocalPropsActions();
  updateViewActions(); // undo, lock, link and other view-dependent actions

  if ( m_bViewModeToggled )
  {
      // if we just toggled the view mode via the view mode actions, then
      // we don't need to do all the time-taking stuff below (Simon)
      const TQString currentServiceDesktopEntryName = m_currentView->service()->desktopEntryName();
      TQPtrListIterator<KRadioAction> it( m_viewModeActions );
      for (; it.current(); ++it ) {
          if ( it.current()->name() == currentServiceDesktopEntryName ) {
              it.current()->setChecked( true );
              break;
          }
      }
      const TQString currentServiceLibrary = viewModeActionKey( m_currentView->service() );
      TQPtrListIterator<KAction> ittb( m_toolBarViewModeActions );
      for (; ittb.current(); ++ittb ) {
          KService::Ptr serv = KService::serviceByDesktopName( ittb.current()->name() );
          if ( serv && viewModeActionKey( serv ) == currentServiceLibrary ) {
              KToggleAction* ta = static_cast<KToggleAction*>( ittb.current() );
              ta->setChecked( false );
	      TQString servicename = m_currentView->service()->genericName();
	      if (servicename.isEmpty())
	          servicename = m_currentView->service()->name();
              ta->setText( servicename );
              ta->setIcon( m_currentView->service()->icon() );
              ta->setName( m_currentView->service()->desktopEntryName().ascii() ) ;
              break;
          }
      }
  }
  else
  {
      updateViewModeActions();
  }

  m_bViewModeToggled = false;


  m_pMenuNew->setEnabled( m_currentView->supportsServiceType( "inode/directory" ) );

  m_currentView->frame()->statusbar()->updateActiveStatus();

  if ( oldView && oldView->frame() )
    oldView->frame()->statusbar()->updateActiveStatus();

  //kdDebug(1202) << "KonqMainWindow::slotPartActivated: setting location bar url to "
  //              << m_currentView->locationBarURL() << " m_currentView=" << m_currentView << endl;
  m_currentView->setLocationBarURL( m_currentView->locationBarURL() );

  updateToolBarActions();

  m_currentView->setActiveInstance();
}

void KonqMainWindow::insertChildView( KonqView *childView )
{
  kdDebug(1202) << "KonqMainWindow::insertChildView " << childView << endl;
  m_mapViews.insert( childView->part(), childView );

  connect( childView, TQT_SIGNAL( viewCompleted( KonqView * ) ),
           this, TQT_SLOT( slotViewCompleted( KonqView * ) ) );

  if ( !m_pViewManager->isLoadingProfile() ) // see KonqViewManager::loadViewProfile
    viewCountChanged();
  emit viewAdded( childView );
}

// Called by KonqViewManager, internal
void KonqMainWindow::removeChildView( KonqView *childView )
{
  kdDebug(1202) << "KonqMainWindow::removeChildView childView " << childView << endl;

  disconnect( childView, TQT_SIGNAL( viewCompleted( KonqView * ) ),
              this, TQT_SLOT( slotViewCompleted( KonqView * ) ) );

#ifndef NDEBUG
  dumpViewList();
#endif

  MapViews::Iterator it = m_mapViews.begin();
  MapViews::Iterator end = m_mapViews.end();

  // find it in the map - can't use the key since childView->part() might be 0L

  kdDebug(1202) << "Searching map" << endl;

  while ( it != end && it.data() != childView )
      ++it;

  kdDebug(1202) << "Verifying search results" << endl;

  if ( it == m_mapViews.end() )
  {
      kdWarning(1202) << "KonqMainWindow::removeChildView childView " << childView << " not in map !" << endl;
      return;
  }

  kdDebug(1202) << "Removing view " << childView << endl;

  m_mapViews.remove( it );

  kdDebug(1202) << "View " << childView << " removed from map" << endl;

  viewCountChanged();
  emit viewRemoved( childView );

#ifndef NDEBUG
  dumpViewList();
#endif

  // KonqViewManager takes care of m_currentView
}

void KonqMainWindow::viewCountChanged()
{
  // This is called when the number of views changes.
  kdDebug(1202) << "KonqMainWindow::viewCountChanged" << endl;

  int lvc = linkableViewsCount();
  m_paLinkView->setEnabled( lvc > 1 );

  // Only one view (or one view + sidebar) -> make it/them unlinked
  if ( lvc == 1 ) {
      MapViews::Iterator it = m_mapViews.begin();
      MapViews::Iterator end = m_mapViews.end();
      for (; it != end; ++it )
          it.data()->setLinkedView( false );
  }

  viewsChanged();

  m_pViewManager->viewCountChanged();
}

void KonqMainWindow::viewsChanged()
{
  // This is called when the number of views changes OR when
  // the type of some view changes.

  // Nothing here anymore, but don't cleanup, some might come back later.

  updateViewActions(); // undo, lock, link and other view-dependent actions
}

KonqView * KonqMainWindow::childView( KParts::ReadOnlyPart *view )
{
  MapViews::ConstIterator it = m_mapViews.find( view );
  if ( it != m_mapViews.end() )
    return it.data();
  else
    return 0L;
}

KonqView * KonqMainWindow::childView( KParts::ReadOnlyPart *callingPart, const TQString &name, KParts::BrowserHostExtension **hostExtension, KParts::ReadOnlyPart **part )
{
  kdDebug() << "KonqMainWindow::childView this=" << this << " looking for " << name << endl;

  MapViews::ConstIterator it = m_mapViews.begin();
  MapViews::ConstIterator end = m_mapViews.end();
  for (; it != end; ++it )
  {
    KonqView* view = it.data();
    TQString viewName = view->viewName();
    kdDebug() << "       - viewName=" << viewName << "   "
              << "frame names:" << view->frameNames().join( "," ) << endl;

    // First look for a hostextension containing this frame name
    KParts::BrowserHostExtension *ext = KParts::BrowserHostExtension::childObject( view->part() );
    if ( ext )
    {
      ext = ext->findFrameParent(callingPart, name);
      kdDebug() << "BrowserHostExtension found part " << ext << endl;
      if (!ext)
         continue; // Don't use this window
    }

    if ( !viewName.isEmpty() && viewName == name )
    {
      kdDebug() << "found existing view by name: " << view << endl;
      if ( hostExtension )
        *hostExtension = 0;
      if ( part )
        *part = view->part();
      return view;
    }

//    KParts::BrowserHostExtension* ext = KonqView::hostExtension( view->part(), name );

    if ( ext )
    {
      TQPtrList<KParts::ReadOnlyPart> frames = ext->frames();
      TQPtrListIterator<KParts::ReadOnlyPart> frameIt( frames );
      for ( ; frameIt.current() ; ++frameIt )
      {
        if ( frameIt.current()->name() == name )
        {
          kdDebug() << "found a frame of name " << name << " : " << frameIt.current() << endl;
          if ( hostExtension )
            *hostExtension = ext;
          if ( part )
            *part = frameIt.current();
          return view;
        }
      }
    }
  }

  return 0;
}

// static
KonqView * KonqMainWindow::findChildView( KParts::ReadOnlyPart *callingPart, const TQString &name, KonqMainWindow **mainWindow, KParts::BrowserHostExtension **hostExtension, KParts::ReadOnlyPart **part )
{
  if ( !s_lstViews )
    return 0;

  TQPtrListIterator<KonqMainWindow> it( *s_lstViews );
  for (; it.current(); ++it )
  {
    KonqView *res = it.current()->childView( callingPart, name, hostExtension, part );
    if ( res )
    {
      if ( mainWindow )
        *mainWindow = it.current();
      return res;
    }
  }

  return 0;
}

int KonqMainWindow::activeViewsCount() const
{
  int res = 0;
  MapViews::ConstIterator it = m_mapViews.begin();
  MapViews::ConstIterator end = m_mapViews.end();
  for (; it != end; ++it )
    if ( !it.data()->isPassiveMode() )
      ++res;

  return res;
}

int KonqMainWindow::linkableViewsCount() const
{
  int res = 0;
  MapViews::ConstIterator it = m_mapViews.begin();
  MapViews::ConstIterator end = m_mapViews.end();
  for (; it != end; ++it )
    if ( !it.data()->isFollowActive() )
      ++res;

  return res;
}

int KonqMainWindow::mainViewsCount() const
{
  int res = 0;
  MapViews::ConstIterator it = m_mapViews.begin();
  MapViews::ConstIterator end = m_mapViews.end();
  for (; it != end; ++it )
    if ( !it.data()->isPassiveMode() && !it.data()->isToggleView() )
    {
      //kdDebug(1202) << "KonqMainWindow::mainViewsCount " << res << " " << it.data() << " " << it.data()->part()->widget() << endl;
      ++res;
    }

  return res;
}

KParts::ReadOnlyPart * KonqMainWindow::currentPart() const
{
  /// ### This is currently unused. Check in the final version (!) if still unused.
  if ( m_currentView )
    return m_currentView->part();
  else
    return 0L;
}

void KonqMainWindow::customEvent( TQCustomEvent *event )
{
  KParts::MainWindow::customEvent( event );

  if ( KonqFileSelectionEvent::test( event ) ||
       KonqFileMouseOverEvent::test( event ) )
  {
    // Forward the event to all views
    MapViews::ConstIterator it = m_mapViews.begin();
    MapViews::ConstIterator end = m_mapViews.end();
    for (; it != end; ++it )
      TQApplication::sendEvent( (*it)->part(), event );
    return;
  }
  if ( KParts::OpenURLEvent::test( event ) )
  {
    KParts::OpenURLEvent * ev = static_cast<KParts::OpenURLEvent*>(event);
    KonqView * senderChildView = childView(ev->part());

    // Enable/disable local properties actions if current view
    if ( senderChildView == m_currentView )
        updateLocalPropsActions();

    // Forward the event to all views
    MapViews::ConstIterator it = m_mapViews.begin();
    MapViews::ConstIterator end = m_mapViews.end();
    for (; it != end; ++it )
    {
      // Don't resend to sender
      if (it.key() != ev->part())
      {
        //kdDebug(1202) << "Sending event to view " << it.key()->className() << endl;
        TQApplication::sendEvent( it.key(), event );

      }
    }
  }
}

void KonqMainWindow::updateLocalPropsActions()
{
    bool canWrite = false;
    if ( m_currentView && m_currentView->url().isLocalFile() )
    {
        // Can we write ?
        TQFileInfo info( m_currentView->url().path() );
        canWrite = info.isDir() && info.isWritable();
    }
    m_paSaveViewPropertiesLocally->setEnabled( canWrite );
    m_paRemoveLocalProperties->setEnabled( canWrite );
}

void KonqMainWindow::slotURLEntered( const TQString &text, int state )
{
  if ( m_bURLEnterLock || text.isEmpty() )
    return;

  m_bURLEnterLock = true;

  if (state & ControlButton || state & AltButton)
  {
      m_combo->setURL( m_currentView ? m_currentView->url().prettyURL() : TQString::null );
      openFilteredURL( text.stripWhiteSpace(), true );
  }
  else
      openFilteredURL( text.stripWhiteSpace() );

  m_bURLEnterLock = false;
}

void KonqMainWindow::slotFileNewAboutToShow()
{
  // As requested by KNewMenu :
  m_pMenuNew->slotCheckUpToDate();
  // And set the files that the menu apply on :
  m_pMenuNew->setPopupFiles( KURL( m_currentView->url().url() ) );
}

void KonqMainWindow::slotSplitViewHorizontal()
{
  KonqView * newView = m_pViewManager->splitView( Qt::Horizontal );
  if (newView == 0L) return;
  newView->openURL( m_currentView->url(), m_currentView->locationBarURL() );
}

void KonqMainWindow::slotSplitViewVertical()
{
  KonqView * newView = m_pViewManager->splitView( Qt::Vertical );
  if (newView == 0L) return;
  newView->openURL( m_currentView->url(), m_currentView->locationBarURL() );
}

void KonqMainWindow::slotAddTab()
{
  KonqView* newView = m_pViewManager->addTab(TQString("text/html"), // this is what about:blank will use anyway
                                             TQString::null,
                                             false,
                                             KonqSettings::openAfterCurrentPage());
  if (newView == 0L) return;
  openURL( newView, KURL("about:blank"),TQString::null);
  m_pViewManager->showTab( newView );
  focusLocationBar();
  m_pWorkingTab = 0L;
}

void KonqMainWindow::slotDuplicateTab()
{
  m_pViewManager->duplicateTab( 0, KonqSettings::openAfterCurrentPage() );
}

void KonqMainWindow::slotDuplicateTabPopup()
{
  m_pViewManager->duplicateTab( m_pWorkingTab, KonqSettings::openAfterCurrentPage() );
}

void KonqMainWindow::slotBreakOffTab()
{
  if (m_currentView && m_currentView->part() &&
      (m_currentView->part()->metaObject()->findProperty("modified") != -1) ) {
    TQVariant prop = m_currentView->part()->property("modified");
    if (prop.isValid() && prop.toBool())
      if ( KMessageBox::warningContinueCancel( this,
           i18n("This tab contains changes that have not been submitted.\nDetaching the tab will discard these changes."),
           i18n("Discard Changes?"), KGuiItem(i18n("&Discard Changes"),"tab_breakoff"), "discardchangesdetach") != KMessageBox::Continue )
        return;
  }

  m_pViewManager->breakOffTab();
  updateViewActions();
}

void KonqMainWindow::slotBreakOffTabPopup()
{
  KonqView* originalView = m_currentView;
  KonqView *view = m_pWorkingTab->activeChildView();
  if (view && view->part() && (view->part()->metaObject()->findProperty("modified") != -1) ) {
    TQVariant prop = view->part()->property("modified");
    if (prop.isValid() && prop.toBool()) {
      m_pViewManager->showTab( view );
      if ( KMessageBox::warningContinueCancel( this,
           i18n("This tab contains changes that have not been submitted.\nDetaching the tab will discard these changes."),
           i18n("Discard Changes?"), KGuiItem(i18n("&Discard Changes"),"tab_breakoff"), "discardchangesdetach") != KMessageBox::Continue )
      {
        m_pViewManager->showTab( originalView );
        return;
      }
    }
  }
  m_pViewManager->showTab( originalView );

  //Can't do this safely here as the tabbar may disappear and we're
  //hanging off here.
  TQTimer::singleShot(0, this, TQT_SLOT( slotBreakOffTabPopupDelayed() ) );
}

void KonqMainWindow::slotBreakOffTabPopupDelayed()
{
  m_pViewManager->breakOffTab( m_pWorkingTab );
  updateViewActions();
}

void KonqMainWindow::slotPopupNewWindow()
{
    kdDebug(1202) << "KonqMainWindow::slotPopupNewWindow()" << endl;

    KFileItemListIterator it ( popupItems );
    for ( ; it.current(); ++it )
    {
        KonqMisc::createNewWindow( (*it)->url(), popupUrlArgs );
    }
}

void KonqMainWindow::slotPopupThisWindow()
{
    kdDebug(1202) << "KonqMainWindow::slotPopupThisWindow()" << endl;

    openURL( 0L, popupItems.getFirst()->url() );
}

void KonqMainWindow::slotPopupNewTabAtFront()
{
    TDEConfig *config = TDEGlobal::config();
    TDEConfigGroupSaver cs( config, TQString::fromLatin1("FMSettings") );
    bool openAfterCurrentPage = config->readBoolEntry( "OpenAfterCurrentPage", false );
    popupNewTab(true, openAfterCurrentPage);
}

void KonqMainWindow::slotPopupNewTab()
{
    bool openAfterCurrentPage = KonqSettings::openAfterCurrentPage();
    bool newTabsInFront = KonqSettings::newTabsInFront();

    if (TDEApplication::keyboardMouseState() & TQt::ShiftButton)
      newTabsInFront = !newTabsInFront;

    popupNewTab(newTabsInFront, openAfterCurrentPage);
}

void KonqMainWindow::slotPopupNewTabRight()
{
    bool newTabsInFront = KonqSettings::newTabsInFront();

    if (TDEApplication::keyboardMouseState() & ShiftButton)
      newTabsInFront = !newTabsInFront;

    popupNewTab(newTabsInFront, false);
}

void KonqMainWindow::popupNewTab(bool infront, bool openAfterCurrentPage)
{
  kdDebug(1202) << "KonqMainWindow::popupNewTab()" << endl;

  KFileItemListIterator it ( popupItems );
  KonqOpenURLRequest req;
  req.newTab = true;
  req.newTabInFront = false;
  req.openAfterCurrentPage = openAfterCurrentPage;
  req.args = popupUrlArgs;

  for ( ; it.current(); ++it )
  {
    if ( infront && it.atLast() )
    {
      req.newTabInFront = true;
    }
    openURL( 0L, (*it)->url(), TQString::null, req );
  }
}

void KonqMainWindow::openMultiURL( KURL::List url )
{
    KURL::List::ConstIterator it = url.begin();
    KURL::List::ConstIterator end = url.end();
    for (; it != end; ++it )
    {
        KonqView* newView = m_pViewManager->addTab();
        Q_ASSERT( newView );
        if (newView == 0L) continue;
        openURL( newView, *it,TQString::null);
        m_pViewManager->showTab( newView );
        focusLocationBar();
        m_pWorkingTab = 0L;
    }
}

void KonqMainWindow::slotRemoveView()
{
  if (m_currentView && m_currentView->part() &&
      (m_currentView->part()->metaObject()->findProperty("modified") != -1) ) {
    TQVariant prop = m_currentView->part()->property("modified");
    if (prop.isValid() && prop.toBool())
      if ( KMessageBox::warningContinueCancel( this,
           i18n("This view contains changes that have not been submitted.\nClosing the view will discard these changes."),
           i18n("Discard Changes?"), KGuiItem(i18n("&Discard Changes"),"view_remove"), "discardchangesclose") != KMessageBox::Continue )
        return;
  }

  // takes care of choosing the new active view
  m_pViewManager->removeView( m_currentView );
}

void KonqMainWindow::slotRemoveTab()
{
  if (m_currentView && m_currentView->part() &&
      (m_currentView->part()->metaObject()->findProperty("modified") != -1) ) {
    TQVariant prop = m_currentView->part()->property("modified");
    if (prop.isValid() && prop.toBool())
      if ( KMessageBox::warningContinueCancel( this,
           i18n("This tab contains changes that have not been submitted.\nClosing the tab will discard these changes."),
           i18n("Discard Changes?"), KGuiItem(i18n("&Discard Changes"),"tab_remove"), "discardchangesclose") != KMessageBox::Continue )
        return;
  }

  m_pViewManager->removeTab();
}

void KonqMainWindow::slotRemoveTabPopup()
{
  KonqView *originalView = m_currentView;
  KonqView *view = m_pWorkingTab->activeChildView();
  if (view && view->part() && (view->part()->metaObject()->findProperty("modified") != -1) ) {
    TQVariant prop = view->part()->property("modified");
    if (prop.isValid() && prop.toBool()) {
      m_pViewManager->showTab( view );
      if ( KMessageBox::warningContinueCancel( this,
           i18n("This tab contains changes that have not been submitted.\nClosing the tab will discard these changes."),
           i18n("Discard Changes?"), KGuiItem(i18n("&Discard Changes"),"tab_remove"), "discardchangesclose") != KMessageBox::Continue )
      {
        m_pViewManager->showTab( originalView );
        return;
      }
    }
    m_pViewManager->showTab( originalView );
  }

  //Can't do immediately - may kill the tabbar, and we're in an event path down from it
  TQTimer::singleShot( 0, this, TQT_SLOT( slotRemoveTabPopupDelayed() ) );
}

void KonqMainWindow::slotRemoveTabPopupDelayed()
{
  m_pViewManager->removeTab( m_pWorkingTab );
}

void KonqMainWindow::slotRemoveOtherTabsPopup()
{
  if ( KMessageBox::warningContinueCancel( this,
       i18n("Do you really want to close all other tabs?"),
       i18n("Close Other Tabs Confirmation"), KGuiItem(i18n("Close &Other Tabs"),"tab_remove_other"),
       "CloseOtherTabConfirm") != KMessageBox::Continue )
    return;

  KonqView *originalView = m_currentView;
  MapViews::ConstIterator it = m_mapViews.begin();
  MapViews::ConstIterator end = m_mapViews.end();
  for (; it != end; ++it ) {
    KonqView *view = it.data();
    if ( view != originalView && view && view->part() && (view->part()->metaObject()->findProperty("modified") != -1) ) {
      TQVariant prop = view->part()->property("modified");
      if (prop.isValid() && prop.toBool()) {
        m_pViewManager->showTab( view );
        if ( KMessageBox::warningContinueCancel( this,
           i18n("This tab contains changes that have not been submitted.\nClosing other tabs will discard these changes."),
           i18n("Discard Changes?"), KGuiItem(i18n("&Discard Changes"),"tab_remove"), "discardchangescloseother") != KMessageBox::Continue )
        {
           m_pViewManager->showTab( originalView );
           return;
        }
      }
    }
  }
  m_pViewManager->showTab( originalView );

  //Can't do immediately - kills the tabbar, and we're in an event path down from it
  TQTimer::singleShot( 0, this, TQT_SLOT( slotRemoveOtherTabsPopupDelayed() ) );
}

void KonqMainWindow::slotRemoveOtherTabsPopupDelayed()
{
  m_pViewManager->removeOtherTabs( m_pWorkingTab );
  updateViewActions();
}

void KonqMainWindow::slotReloadAllTabs()
{
  KonqView *originalView = m_currentView;
  MapViews::ConstIterator it = m_mapViews.begin();
  MapViews::ConstIterator end = m_mapViews.end();
  for (; it != end; ++it ) {
    KonqView *view = it.data();
    if (view && view->part() && (view->part()->metaObject()->findProperty("modified") != -1) ) {
      TQVariant prop = view->part()->property("modified");
      if (prop.isValid() && prop.toBool()) {
        m_pViewManager->showTab( view );
        if ( KMessageBox::warningContinueCancel( this,
           i18n("This tab contains changes that have not been submitted.\nReloading all tabs will discard these changes."),
           i18n("Discard Changes?"), KGuiItem(i18n("&Discard Changes"),"reload"), "discardchangesreload") != KMessageBox::Continue )
        {
            m_pViewManager->showTab( originalView );
            return;
        }
      }
    }
  }
  m_pViewManager->showTab( originalView );

  m_pViewManager->reloadAllTabs();
  updateViewActions();
}


void KonqMainWindow::slotActivateNextTab()
{
  m_pViewManager->activateNextTab();
}

void KonqMainWindow::slotActivatePrevTab()
{
  m_pViewManager->activatePrevTab();
}

void KonqMainWindow::slotActivateTab()
{
  m_pViewManager->activateTab( TQString( TQT_TQOBJECT_CONST(sender())->name() ).right( 2 ).toInt() -1 );
}

void KonqMainWindow::slotDumpDebugInfo()
{
#ifndef NDEBUG
  dumpViewList();
  m_pViewManager->printFullHierarchy( 0L );
#endif
}

void KonqMainWindow::slotSaveViewPropertiesLocally()
{
  m_bSaveViewPropertiesLocally = !m_bSaveViewPropertiesLocally;
  // And this is a main-view setting, so save it
  KonqSettings::setSaveViewPropertiesLocally( m_bSaveViewPropertiesLocally );
  KonqSettings::writeConfig();
  // Now tell the views
  MapViews::ConstIterator it = m_mapViews.begin();
  MapViews::ConstIterator end = m_mapViews.end();
  for (; it != end; ++it )
    (*it)->callExtensionBoolMethod( "setSaveViewPropertiesLocally(bool)", m_bSaveViewPropertiesLocally );
}

void KonqMainWindow::slotRemoveLocalProperties()
{
  assert( m_currentView );
  KURL u ( m_currentView->url() );
  u.addPath(".directory");
  if ( u.isLocalFile() )
  {
      TQFile f( u.path() );
      if ( f.open(IO_ReadWrite) )
      {
          f.close();
          KSimpleConfig config( u.path() );
          config.deleteGroup( "URL properties" ); // Bye bye
          config.sync();
          // TODO: Notify the view...
          // Or the hard way: (and hoping it doesn't cache the values!)
          slotReload();
      } else
      {
         Q_ASSERT( TQFile::exists(u.path()) ); // The action shouldn't be enabled, otherwise.
         KMessageBox::sorry( this, i18n("No permissions to write to %1").arg(u.path()) );
      }
  }
}

bool KonqMainWindow::askForTarget(const TQString& text, KURL& url)
{
   const KURL initialUrl = (viewCount()==2) ? otherView(m_currentView)->url() : m_currentView->url();
   TQString label = text.arg( m_currentView->url().pathOrURL() );
   KURLRequesterDlg dlg(initialUrl.pathOrURL(), label, this, "urlrequester", true);
   dlg.setCaption(i18n("Enter Target"));
   dlg.urlRequester()->setMode( KFile::File | KFile::ExistingOnly | KFile::Directory );
   if (dlg.exec())
   {
      url = dlg.selectedURL();
      if ( url.isValid() )
        return true;
      else
      {
        KMessageBox::error( this, i18n("<qt><b>%1</b> is not valid</qt>").arg(url.url()));
        return false;
      }
   }
   return false;
}

void KonqMainWindow::slotRequesterClicked( KURLRequester *req )
{
    req->fileDialog()->setMode(KFile::Directory|KFile::ExistingOnly);
}

void KonqMainWindow::slotCopyFiles()
{
  //kdDebug(1202) << "KonqMainWindow::slotCopyFiles()" << endl;
  KURL dest;
  if (!askForTarget(i18n("Copy selected files from %1 to:"),dest))
     return;

  KonqOperations::copy(this,KonqOperations::COPY,currentURLs(),dest);
}

void KonqMainWindow::slotMoveFiles()
{
  //kdDebug(1202) << "KonqMainWindow::slotMoveFiles()" << endl;
  KURL dest;
  if (!askForTarget(i18n("Move selected files from %1 to:"),dest))
     return;

  KonqOperations::copy(this,KonqOperations::MOVE,currentURLs(),dest);
}

void KonqMainWindow::slotNewDir()
{
    Q_ASSERT( m_currentView );
    if ( m_currentView )
        KonqOperations::newDir(this, m_currentView->url());
}

KURL::List KonqMainWindow::currentURLs() const
{
  KURL::List urls;
  if ( m_currentView )
  {
    urls.append( m_currentView->url() );
    if ( m_currentView->part()->inherits("KonqDirPart") )
    {
      KFileItemList tmpList= static_cast<KonqDirPart *>(m_currentView->part())->selectedFileItems();
      KFileItem *item=tmpList.first();
      if (item) // Return list of selected items only if we have a selection
      {
        urls.clear();
        for (; item!=0; item=tmpList.next())
          urls.append(item->url());
      }
    }
  }
  return urls;
}

// Only valid if there are one or two views
KonqView * KonqMainWindow::otherView( KonqView * view ) const
{
  assert( viewCount() <= 2 );
  MapViews::ConstIterator it = m_mapViews.begin();
  if ( (*it) == view )
    ++it;
  if ( it != m_mapViews.end() )
    return (*it);
  return 0L;
}

void KonqMainWindow::slotSaveViewProfile()
{
#if 0
    if ( m_pViewManager->currentProfile().isEmpty() )
    {
        // The action should be disabled...........
        kdWarning(1202) << "No known profile. Use the Save Profile dialog box" << endl;
    } else {

        m_pViewManager->saveViewProfile( m_pViewManager->currentProfile(),
                                         m_pViewManager->currentProfileText(),
                                         false /* URLs */, true /* size */ );

    }
#endif
    m_pViewManager->showProfileDlg( m_pViewManager->currentProfile() );
}

void KonqMainWindow::slotUpAboutToShow()
{
  TQPopupMenu *popup = m_paUp->popupMenu();

  popup->clear();

  uint i = 0;

  // Use the location bar URL, because in case we display a index.html
  // we want to go up from the dir, not from the index.html
  KURL u( m_currentView->locationBarURL() );
  u = u.upURL();
  while ( u.hasPath() )
  {
    popup->insertItem( KonqPixmapProvider::self()->pixmapFor( u.url() ),
                       u.pathOrURL() );

    if ( u.path() == "/" )
        break;

    if ( ++i > 10 )
      break;

    u = u.upURL();
  }
}

void KonqMainWindow::slotUp(KAction::ActivationReason, TQt::ButtonState state)
{
    m_goState = state;
    TQTimer::singleShot( 0, this, TQT_SLOT( slotUpDelayed() ) );
}

void KonqMainWindow::slotUp()
{
    m_goState = Qt::LeftButton;
    TQTimer::singleShot( 0, this, TQT_SLOT( slotUpDelayed() ) );
}

void KonqMainWindow::slotUpDelayed()
{
    KonqOpenURLRequest req;
    req.newTab = true;

    req.openAfterCurrentPage = KonqSettings::openAfterCurrentPage();
    req.newTabInFront = KonqSettings::newTabsInFront();

    if (m_goState & TQt::ShiftButton)
        req.newTabInFront = !req.newTabInFront;

    const TQString& url = m_currentView->upURL().url();
    if(m_goState & TQt::ControlButton)
	openFilteredURL(url, req );
    else if(m_goState & Qt::MidButton)
    {
        if(KonqSettings::mmbOpensTab())
	    openFilteredURL( url, req);
	else
	    KonqMisc::createNewWindow( url );
    }
    else
	openFilteredURL( url, false );
    m_goState = Qt::LeftButton;
}

void KonqMainWindow::slotUpActivated( int id )
{
  KURL u( m_currentView->locationBarURL() );
  kdDebug(1202) << "slotUpActivated. Start URL is " << u << endl;
  for ( int i = 0 ; i < m_paUp->popupMenu()->indexOf( id ) + 1 ; i ++ )
      u = u.upURL();
  openURL( 0L, u );
}

void KonqMainWindow::slotGoMenuAboutToShow()
{
  kdDebug(1202) << "KonqMainWindow::slotGoMenuAboutToShow" << endl;
  if ( m_paHistory && m_currentView ) // (maybe this is before initialisation)
      m_paHistory->fillGoMenu( m_currentView->history() );
}

void KonqMainWindow::slotGoHistoryActivated( int steps )
{
    slotGoHistoryActivated( steps, Qt::LeftButton );
}

void KonqMainWindow::slotGoHistoryActivated( int steps, TQt::ButtonState state )
{
  kdDebug() <<"slotGoHistoryActivated( "<<steps<<", "<<state<<" )"<<endl;
  if (!m_goBuffer)
  {
    // Only start 1 timer.
    m_goBuffer = steps;
    m_goState = state;
    TQTimer::singleShot( 0, this, TQT_SLOT(slotGoHistoryDelayed()));
  }
}

void KonqMainWindow::slotGoHistoryDelayed()
{
  if (!m_currentView) return;

  bool openAfterCurrentPage = KonqSettings::openAfterCurrentPage();
  bool mmbOpensTab = KonqSettings::mmbOpensTab();
  bool inFront = KonqSettings::newTabsInFront();
  if(m_goState & TQt::ShiftButton)
      inFront = !inFront;

  if(m_goState & TQt::ControlButton)
  {
      KonqView * newView = m_pViewManager->addTabFromHistory( m_goBuffer, openAfterCurrentPage );
      if (newView && inFront)
	  m_pViewManager->showTab( newView );
  }
  else if(m_goState & Qt::MidButton)
  {
      if(mmbOpensTab)
      {
	  KonqView * newView = m_pViewManager->addTabFromHistory( m_goBuffer, openAfterCurrentPage );
	  if (newView && inFront)
	      m_pViewManager->showTab( newView );
      }
      else
	  KonqMisc::newWindowFromHistory(this->currentView(), m_goBuffer);
  }
  else
  {
      m_currentView->go( m_goBuffer );
      makeViewsFollow(m_currentView->url(), KParts::URLArgs(),m_currentView->serviceType(),m_currentView);
  }

  m_goBuffer = 0;
  m_goState = Qt::LeftButton;
}


void KonqMainWindow::slotBackAboutToShow()
{
  m_paBack->popupMenu()->clear();
  if ( m_currentView )
      KonqBidiHistoryAction::fillHistoryPopup( m_currentView->history(), m_paBack->popupMenu(), true, false );
}

void KonqMainWindow::slotBack()
{
  slotGoHistoryActivated(-1);
}

void KonqMainWindow::slotBack(KAction::ActivationReason, TQt::ButtonState state)
{
  slotGoHistoryActivated( -1, state );
}

void KonqMainWindow::slotBackActivated( int id )
{
    slotGoHistoryActivated( -(m_paBack->popupMenu()->indexOf( id ) + 1), m_paBack->popupMenu()->state());
}

void KonqMainWindow::slotForwardAboutToShow()
{
  m_paForward->popupMenu()->clear();
  if ( m_currentView )
      KonqBidiHistoryAction::fillHistoryPopup( m_currentView->history(), m_paForward->popupMenu(), false, true );
}

void KonqMainWindow::slotForward()
{
  slotGoHistoryActivated( 1 );
}

void KonqMainWindow::slotForward(KAction::ActivationReason, TQt::ButtonState state)
{
    slotGoHistoryActivated( 1, state );
}

void KonqMainWindow::slotForwardActivated( int id )
{
    slotGoHistoryActivated( m_paForward->popupMenu()->indexOf( id ) + 1, m_paForward->popupMenu()->state() );
}

void KonqMainWindow::initCombo()
{
  m_combo = new KonqCombo( 0L, "history combo");

  m_combo->init( s_pCompletion );

  connect( m_combo, TQT_SIGNAL(activated(const TQString&,int)),
           this, TQT_SLOT(slotURLEntered(const TQString&,int)) );
  connect( m_combo, TQT_SIGNAL(showPageSecurity()),
           this, TQT_SLOT(showPageSecurity()) );

  m_pURLCompletion = new KURLCompletion();
  m_pURLCompletion->setCompletionMode( s_pCompletion->completionMode() );

  // This only turns completion off. ~ is still there in the result
  // We do want completion of user names, right?
  //m_pURLCompletion->setReplaceHome( false );  // Leave ~ alone! Will be taken care of by filters!!

  connect( m_combo, TQT_SIGNAL(completionModeChanged(TDEGlobalSettings::Completion)),
           TQT_SLOT( slotCompletionModeChanged( TDEGlobalSettings::Completion )));
  connect( m_combo, TQT_SIGNAL( completion( const TQString& )),
           TQT_SLOT( slotMakeCompletion( const TQString& )));
  connect( m_combo, TQT_SIGNAL( substringCompletion( const TQString& )),
           TQT_SLOT( slotSubstringcompletion( const TQString& )));
  connect( m_combo, TQT_SIGNAL( textRotation( KCompletionBase::KeyBindingType) ),
           TQT_SLOT( slotRotation( KCompletionBase::KeyBindingType )));
  connect( m_combo, TQT_SIGNAL( cleared() ),
           TQT_SLOT ( slotClearHistory() ) );
  connect( m_pURLCompletion, TQT_SIGNAL( match(const TQString&) ),
           TQT_SLOT( slotMatch(const TQString&) ));

  m_combo->lineEdit()->installEventFilter(this);

  static bool bookmarkCompletionInitialized = false;
  if ( !bookmarkCompletionInitialized )
  {
      bookmarkCompletionInitialized = true;
      DelayedInitializer *initializer = new DelayedInitializer( TQEvent::KeyPress, TQT_TQOBJECT(m_combo->lineEdit()) );
      connect( initializer, TQT_SIGNAL( initialize() ), this, TQT_SLOT( bookmarksIntoCompletion() ) );
  }
}

void KonqMainWindow::bookmarksIntoCompletion()
{
    // add all bookmarks to the completion list for easy access
    bookmarksIntoCompletion( KonqBookmarkManager::self()->root() );
}

// the user changed the completion mode in the combo
void KonqMainWindow::slotCompletionModeChanged( TDEGlobalSettings::Completion m )
{
  s_pCompletion->setCompletionMode( m );

  KonqSettings::setSettingsCompletionMode( (int)m_combo->completionMode() );
  KonqSettings::writeConfig();

  // tell the other windows too (only this instance currently)
  KonqMainWindow *window = s_lstViews->first();
  while ( window ) {
    if ( window->m_combo ) {
      window->m_combo->setCompletionMode( m );
      window->m_pURLCompletion->setCompletionMode( m );
    }
    window = s_lstViews->next();
  }
}

// at first, try to find a completion in the current view, then use the global
// completion (history)
void KonqMainWindow::slotMakeCompletion( const TQString& text )
{
  if( m_pURLCompletion )
  {
    m_urlCompletionStarted = true; // flag for slotMatch()

    // kdDebug(1202) << "Local Completion object found!" << endl;
    TQString completion = m_pURLCompletion->makeCompletion( text );
    m_currentDir = TQString::null;

    if ( completion.isNull() && !m_pURLCompletion->isRunning() )
    {
      // No match() signal will come from m_pURLCompletion
      // ask the global one
      // tell the static completion object about the current completion mode
      completion = s_pCompletion->makeCompletion( text );

      // some special handling necessary for CompletionPopup
      if ( m_combo->completionMode() == TDEGlobalSettings::CompletionPopup ||
           m_combo->completionMode() == TDEGlobalSettings::CompletionPopupAuto )
        m_combo->setCompletedItems( historyPopupCompletionItems( text ) );

      else if ( !completion.isNull() )
        m_combo->setCompletedText( completion );
    }
    else
    {
      // To be continued in slotMatch()...
      if( !m_pURLCompletion->dir().isEmpty() )
        m_currentDir = m_pURLCompletion->dir();
    }
  }
  // kdDebug(1202) << "Current dir: " << m_currentDir << "  Current text: " << text << endl;
}

void KonqMainWindow::slotSubstringcompletion( const TQString& text )
{
    bool filesFirst = currentURL().startsWith( "/" ) ||
                      currentURL().startsWith( "file:/" );
    TQStringList items;
    if ( filesFirst && m_pURLCompletion )
        items = m_pURLCompletion->substringCompletion( text );

    items += s_pCompletion->substringCompletion( text );
    if ( !filesFirst && m_pURLCompletion )
        items += m_pURLCompletion->substringCompletion( text );

    m_combo->setCompletedItems( items );
}

void KonqMainWindow::slotRotation( KCompletionBase::KeyBindingType type )
{
  // Tell slotMatch() to do nothing
  m_urlCompletionStarted = false;

  bool prev = (type == KCompletionBase::PrevCompletionMatch);
  if ( prev || type == KCompletionBase::NextCompletionMatch ) {
    TQString completion = prev ? m_pURLCompletion->previousMatch() :
                                m_pURLCompletion->nextMatch();

    if( completion.isNull() ) { // try the history KCompletion object
        completion = prev ? s_pCompletion->previousMatch() :
                            s_pCompletion->nextMatch();
    }
    if ( completion.isEmpty() || completion == m_combo->currentText() )
      return;

    m_combo->setCompletedText( completion );
  }
}

// Handle match() from m_pURLCompletion
void KonqMainWindow::slotMatch( const TQString &match )
{
  if ( match.isEmpty() ) // this case is handled directly
    return;

  // Check flag to avoid match() raised by rotation
  if ( m_urlCompletionStarted ) {
    m_urlCompletionStarted = false;

    // some special handling necessary for CompletionPopup
    if ( m_combo->completionMode() == TDEGlobalSettings::CompletionPopup ||
         m_combo->completionMode() == TDEGlobalSettings::CompletionPopupAuto ) {
      TQStringList items = m_pURLCompletion->allMatches();
      items += historyPopupCompletionItems( m_combo->currentText() );
      // items.sort(); // should we?
      m_combo->setCompletedItems( items );
    }
    else if ( !match.isNull() )
       m_combo->setCompletedText( match );
  }
}

void KonqMainWindow::slotCtrlTabPressed()
{
   KonqView * view = m_pViewManager->chooseNextView( m_currentView );
   if ( view )
      m_pViewManager->setActivePart( view->part() );
}

void KonqMainWindow::slotClearHistory()
{
   KonqHistoryManager::kself()->emitClear();
}

void KonqMainWindow::slotClearComboHistory()
{
   if (m_combo && m_combo->count())
      m_combo->clearHistory();
}

bool KonqMainWindow::eventFilter(TQObject*obj,TQEvent *ev)
{
  if ( ( ev->type()==TQEvent::FocusIn || ev->type()==TQEvent::FocusOut ) &&
       m_combo && TQT_BASE_OBJECT(m_combo->lineEdit()) == TQT_BASE_OBJECT(obj) )
  {
    //kdDebug(1202) << "KonqMainWindow::eventFilter " << obj << " " << obj->className() << " " << obj->name() << endl;

    TQFocusEvent * focusEv = TQT_TQFOCUSEVENT(ev);
    if (focusEv->reason() == TQFocusEvent::Popup)
    {
      return KParts::MainWindow::eventFilter( obj, ev );
    }

    KParts::BrowserExtension * ext = 0;
    if ( m_currentView )
        ext = m_currentView->browserExtension();
    TQStrList slotNames;
    if (ext)
      slotNames = ext->metaObject()->slotNames();

    //for ( char * s = slotNames.first() ; s ; s = slotNames.next() )
    //{
    //    kdDebug(1202) << "slotNames=" << s << endl;
    //}


    if (ev->type()==TQEvent::FocusIn)
    {
      //kdDebug(1202) << "ComboBox got the focus..." << endl;
      if (m_bLocationBarConnected)
      {
        //kdDebug(1202) << "Was already connected..." << endl;
        return KParts::MainWindow::eventFilter( obj, ev );
      }
      m_bLocationBarConnected = true;

      // Workaround for Qt issue: usually, TQLineEdit reacts on Ctrl-D,
      // but the duplicate_window action also has Ctrl-D as accel and
      // prevents the lineedit from getting this event. IMHO the accel
      // should be disabled in favor of the focus-widget.
      KAction *duplicate = actionCollection()->action("duplicate_window");
      if ( duplicate->shortcut() == TQKeySequence(CTRL+Key_D) )
          duplicate->setEnabled( false );

      if (slotNames.contains("cut()"))
        disconnect( m_paCut, TQT_SIGNAL( activated() ), ext, TQT_SLOT( cut() ) );
      if (slotNames.contains("copy()"))
        disconnect( m_paCopy, TQT_SIGNAL( activated() ), ext, TQT_SLOT( copy() ) );
      if (slotNames.contains("paste()"))
        disconnect( m_paPaste, TQT_SIGNAL( activated() ), ext, TQT_SLOT( paste() ) );
      if (slotNames.contains("del()"))
        disconnect( m_paDelete, TQT_SIGNAL( activated() ), ext, TQT_SLOT( del() ) );
      disconnect( m_paTrash, TQT_SIGNAL( activated( KAction::ActivationReason, TQt::ButtonState ) ),
                  this, TQT_SLOT( slotTrashActivated( KAction::ActivationReason, TQt::ButtonState ) ) );

      connect( m_paCut, TQT_SIGNAL( activated() ), m_combo->lineEdit(), TQT_SLOT( cut() ) );
      connect( m_paCopy, TQT_SIGNAL( activated() ), m_combo->lineEdit(), TQT_SLOT( copy() ) );
      connect( m_paPaste, TQT_SIGNAL( activated() ), m_combo->lineEdit(), TQT_SLOT( paste() ) );
      connect( TQApplication::clipboard(), TQT_SIGNAL(dataChanged()), this, TQT_SLOT(slotClipboardDataChanged()) );
      connect( m_combo->lineEdit(), TQT_SIGNAL(textChanged(const TQString &)), this, TQT_SLOT(slotCheckComboSelection()) );
      connect( m_combo->lineEdit(), TQT_SIGNAL(selectionChanged()), this, TQT_SLOT(slotCheckComboSelection()) );

      m_paTrash->setEnabled(false);
      m_paDelete->setEnabled(false);

      slotClipboardDataChanged();

    }
    else if ( ev->type()==TQEvent::FocusOut)
    {
      //kdDebug(1202) << "ComboBox lost focus..." << endl;
      if (!m_bLocationBarConnected)
      {
        //kdDebug(1202) << "Was already disconnected..." << endl;
        return KParts::MainWindow::eventFilter( obj, ev );
      }
      m_bLocationBarConnected = false;

      // see above in FocusIn for explanation
      // we use new_window as reference, as it's always in the same state
      // as duplicate_window
      KAction *duplicate = actionCollection()->action("duplicate_window");
      if ( duplicate->shortcut() == TQKeySequence(CTRL+Key_D) )
          duplicate->setEnabled( actionCollection()->action("new_window")->isEnabled() );

      if (slotNames.contains("cut()"))
        connect( m_paCut, TQT_SIGNAL( activated() ), ext, TQT_SLOT( cut() ) );
      if (slotNames.contains("copy()"))
        connect( m_paCopy, TQT_SIGNAL( activated() ), ext, TQT_SLOT( copy() ) );
      if (slotNames.contains("paste()"))
        connect( m_paPaste, TQT_SIGNAL( activated() ), ext, TQT_SLOT( paste() ) );
      if (slotNames.contains("del()"))
        connect( m_paDelete, TQT_SIGNAL( activated() ), ext, TQT_SLOT( del() ) );
      connect( m_paTrash, TQT_SIGNAL( activated( KAction::ActivationReason, TQt::ButtonState ) ),
               this, TQT_SLOT( slotTrashActivated( KAction::ActivationReason, TQt::ButtonState ) ) );

      disconnect( m_paCut, TQT_SIGNAL( activated() ), m_combo->lineEdit(), TQT_SLOT( cut() ) );
      disconnect( m_paCopy, TQT_SIGNAL( activated() ), m_combo->lineEdit(), TQT_SLOT( copy() ) );
      disconnect( m_paPaste, TQT_SIGNAL( activated() ), m_combo->lineEdit(), TQT_SLOT( paste() ) );
      disconnect( TQApplication::clipboard(), TQT_SIGNAL(dataChanged()), this, TQT_SLOT(slotClipboardDataChanged()) );
      disconnect( m_combo->lineEdit(), TQT_SIGNAL(textChanged(const TQString &)), this, TQT_SLOT(slotCheckComboSelection()) );
      disconnect( m_combo->lineEdit(), TQT_SIGNAL(selectionChanged()), this, TQT_SLOT(slotCheckComboSelection()) );

      if ( ext )
      {
          m_paCut->setEnabled( ext->isActionEnabled( "cut" ) );
          m_paCopy->setEnabled( ext->isActionEnabled( "copy" ) );
          m_paPaste->setEnabled( ext->isActionEnabled( "paste" ) );
          m_paDelete->setEnabled( ext->isActionEnabled( "delete" ) );
          m_paTrash->setEnabled( ext->isActionEnabled( "trash" ) );
      }
      else
      {
          m_paCut->setEnabled( false );
          m_paCopy->setEnabled( false );
          m_paPaste->setEnabled( false );
          m_paDelete->setEnabled( false );
          m_paTrash->setEnabled( false );
      }
    }
  }
  return KParts::MainWindow::eventFilter( obj, ev );
}

void KonqMainWindow::slotClipboardDataChanged()
{
  //kdDebug(1202) << "KonqMainWindow::slotClipboardDataChanged()" << endl;
  TQMimeSource *data = TQApplication::clipboard()->data();
  m_paPaste->setEnabled( data->provides( "text/plain" ) );
  slotCheckComboSelection();
}

void KonqMainWindow::slotCheckComboSelection()
{
  //kdDebug(1202) << "m_combo->lineEdit()->hasMarkedText() : " << hasSelection << endl;
  bool hasSelection = m_combo->lineEdit()->hasSelectedText();
  m_paCopy->setEnabled( hasSelection );
  m_paCut->setEnabled( hasSelection );
}

void KonqMainWindow::slotClearLocationBar( KAction::ActivationReason, TQt::ButtonState state )
{
  kdDebug(1202) << "slotClearLocationBar" << endl;
  slotStop();
  m_combo->clearTemporary();
  focusLocationBar();
  if ( state & Qt::MidButton )
      m_combo->setURL( TQApplication::clipboard()->text( TQClipboard::Selection ) );
}

void KonqMainWindow::slotForceSaveMainWindowSettings()
{
//  kdDebug(1202)<<"slotForceSaveMainWindowSettings()"<<endl;
  if ( autoSaveSettings() ) // don't do it on e.g. JS window.open windows with no toolbars!
  {
      saveMainWindowSettings( TDEGlobal::config(), "KonqMainWindow" );
      TDEGlobal::config()->sync();
  }
}

void KonqMainWindow::slotShowMenuBar()
{
  if (menuBar()->isVisible())
    menuBar()->hide();
  else
    menuBar()->show();
  slotForceSaveMainWindowSettings();
}

void KonqMainWindow::slotUpdateFullScreen( bool set )
{
  if( set )
  {
    showFullScreen();
    // Create toolbar button for exiting from full-screen mode
    // ...but only if there isn't one already...

    bool haveFullScreenButton = false;

    //Walk over the toolbars and check whether there is a show fullscreen button in any of them
    TQPtrListIterator<KToolBar> barIt = toolBarIterator();
    for (; barIt.current(); ++barIt )
    {
        //Are we plugged here, in a visible toolbar?
        if (barIt.current()->isVisible() &&
            action( "fullscreen" )->isPlugged(barIt.current()))
        {
            haveFullScreenButton = true;
            break;
        }
    }

    if (!haveFullScreenButton)
    {
        TQPtrList<KAction> lst;
        lst.append( m_ptaFullScreen );
        plugActionList( "fullscreen", lst );
    }

    m_prevMenuBarVisible = menuBar()->isVisible();
    menuBar()->hide();
    m_paShowMenuBar->setChecked( false );

    // Qt bug, the flags are lost. They know about it.
    // happens only with the hackish non-_NET_WM_STATE_FULLSCREEN way
    setWFlags( WDestructiveClose );
    // Qt bug (see below)
    setAcceptDrops( FALSE );
    topData()->dnd = 0;
    setAcceptDrops( TRUE );
  }
  else
  {
#if TQT_VERSION >= 0x030300
    setWindowState( windowState() & ~WindowFullScreen );
#else
    if( isMaximized())
        {
        showNormal();
        showMaximized(); // showNormal() would reset maximize state
        }
    else
        showNormal();
#endif
    unplugActionList( "fullscreen" );

    if (m_prevMenuBarVisible)
    {
        menuBar()->show();
        m_paShowMenuBar->setChecked( true );
    }

    // Qt bug, the flags aren't restored. They know about it.
    setWFlags( WType_TopLevel | WDestructiveClose );
    // Other Qt bug
    setAcceptDrops( FALSE );
    topData()->dnd = 0;
    setAcceptDrops( TRUE );
  }
}

void KonqMainWindow::setLocationBarURL( const KURL &url )
{
    setLocationBarURL( url.pathOrURL() );
}

void KonqMainWindow::setLocationBarURL( const TQString &url )
{
  kdDebug(1202) << "KonqMainWindow::setLocationBarURL: url = " << url << endl;

  m_combo->setURL( url );

  setIcon( KonqPixmapProvider::self()->pixmapFor( url ) );
}

void KonqMainWindow::setPageSecurity( PageSecurity pageSecurity )
{
  m_combo->setPageSecurity( pageSecurity );
}

void KonqMainWindow::showPageSecurity()
{
    if ( m_currentView && m_currentView->part() ) {
      KAction *act = m_currentView->part()->action( "security" );
      if ( act )
        act->activate();
    }
}

// called via DCOP from KonquerorIface
void KonqMainWindow::comboAction( int action, const TQString& url, const TQCString& objId )
{
    if (!s_lstViews) // this happens in "konqueror --silent"
        return;

    KonqCombo *combo = 0L;
    KonqMainWindow *window = s_lstViews->first();
    while ( window ) {
        if ( window->m_combo ) {
            combo = window->m_combo;

            switch ( action ) {
            case ComboAdd:
              combo->insertPermanent( url );
              break;
            case ComboClear:
              combo->clearHistory();
              break;
            case ComboRemove:
              combo->removeURL( url );
              break;
            default:
              break;
            }
        }
        window = s_lstViews->next();
    }

    // only one instance should save...
    if ( combo && objId == kapp->dcopClient()->defaultObject() )
      combo->saveItems();
}

TQString KonqMainWindow::locationBarURL() const
{
    return m_combo->currentText();
}

void KonqMainWindow::focusLocationBar()
{
  if ( m_combo->isVisible() || !isVisible() )
    m_combo->setFocus();
}

void KonqMainWindow::startAnimation()
{
  //kdDebug(1202) << "KonqMainWindow::startAnimation" << endl;
  m_paAnimatedLogo->start();
  m_paStop->setEnabled( true );
  toggleReloadStopButton( true );
}

void KonqMainWindow::stopAnimation()
{
  //kdDebug(1202) << "KonqMainWindow::stopAnimation" << endl;
  m_paAnimatedLogo->stop();
  m_paStop->setEnabled( false );
  toggleReloadStopButton( false );
}

void KonqMainWindow::setUpEnabled( const KURL &url )
{
  //kdDebug(1202) << "KonqMainWindow::setUpEnabled(" << url << ")" << endl;
  //kdDebug(1202) << "hasPath=" << url.hasPath() << endl;
  bool bHasUpURL = false;

  bHasUpURL = ( ( url.hasPath() && url.path() != "/" && ( url.path()[0]=='/' ) )
                || !url.query().isEmpty() /*e.g. lists.kde.org*/ );
  if ( !bHasUpURL )
    bHasUpURL = url.hasSubURL();

  m_paUp->setEnabled( bHasUpURL );
}

void KonqMainWindow::initActions()
{
  actionCollection()->setHighlightingEnabled( true );
  connectActionCollection( actionCollection() );


  // Note about this method : don't call setEnabled() on any of the actions.
  // They are all disabled then re-enabled with enableAllActions
  // If any one needs to be initially disabled, put that code in enableAllActions

  // File menu
  m_pMenuNew = new KNewMenu ( actionCollection(), this, "new_menu" );
  TQObject::connect( m_pMenuNew->popupMenu(), TQT_SIGNAL(aboutToShow()),
                    this, TQT_SLOT(slotFileNewAboutToShow()) );

  (void) new KAction( i18n( "&Edit File Type..." ), 0, actionCollection(), "editMimeType" );
  (void) new KAction( i18n( "Properties" ), ALT+Key_Return, actionCollection(), "properties" );
  (void) new KAction( i18n( "New &Window" ), "window_new", KStdAccel::shortcut(KStdAccel::New), TQT_TQOBJECT(this), TQT_SLOT( slotNewWindow() ), actionCollection(), "new_window" );
  (void) new KAction( i18n( "&Duplicate Window" ), "window_duplicate", CTRL+Key_D, TQT_TQOBJECT(this), TQT_SLOT( slotDuplicateWindow() ), actionCollection(), "duplicate_window" );
  (void) new KAction( i18n( "Send &Link Address..." ), "mail_generic", 0, TQT_TQOBJECT(this), TQT_SLOT( slotSendURL() ), actionCollection(), "sendURL" );
  (void) new KAction( i18n( "S&end File..." ), "mail_generic", 0, TQT_TQOBJECT(this), TQT_SLOT( slotSendFile() ), actionCollection(), "sendPage" );
  if (kapp->authorize("shell_access"))
  {
     (void) new KAction( i18n( "Open &Terminal" ), "openterm", Key_F4, TQT_TQOBJECT(this), TQT_SLOT( slotOpenTerminal() ), actionCollection(), "open_terminal" );
  }
  (void) new KAction( i18n( "&Open Location..." ), "fileopen", KStdAccel::shortcut(KStdAccel::Open), TQT_TQOBJECT(this), TQT_SLOT( slotOpenLocation() ), actionCollection(), "open_location" );

  m_paFindFiles = new KToggleAction( i18n( "&Find File..." ), "filefind", KStdAccel::shortcut(KStdAccel::Find), TQT_TQOBJECT(this), TQT_SLOT( slotToolFind() ), actionCollection(), "findfile" );

  m_paPrint = KStdAction::print( 0, 0, actionCollection(), "print" );
  (void) KStdAction::quit( TQT_TQOBJECT(this), TQT_SLOT( close() ), actionCollection(), "quit" );

  m_ptaUseHTML = new KToggleAction( i18n( "&Use index.html" ), 0, TQT_TQOBJECT(this), TQT_SLOT( slotShowHTML() ), actionCollection(), "usehtml" );
  m_paLockView = new KToggleAction( i18n( "Lock to Current Location"), 0, TQT_TQOBJECT(this), TQT_SLOT( slotLockView() ), actionCollection(), "lock" );
  m_paLinkView = new KToggleAction( i18n( "Lin&k View"), 0, TQT_TQOBJECT(this), TQT_SLOT( slotLinkView() ), actionCollection(), "link" );

  // Go menu
  m_paUp = new KToolBarPopupAction( i18n( "&Up" ), "up", KStdAccel::shortcut(KStdAccel::Up), actionCollection(), "up" );
  connect( m_paUp, TQT_SIGNAL( activated( KAction::ActivationReason, TQt::ButtonState) ), TQT_TQOBJECT(this),
	   TQT_SLOT( slotUp(KAction::ActivationReason, TQt::ButtonState) ) );
  connect( m_paUp->popupMenu(), TQT_SIGNAL( aboutToShow() ), TQT_TQOBJECT(this), TQT_SLOT( slotUpAboutToShow() ) );
  connect( m_paUp->popupMenu(), TQT_SIGNAL( activated( int ) ), TQT_TQOBJECT(this), TQT_SLOT( slotUpActivated( int ) ) );

  TQPair< KGuiItem, KGuiItem > backForward = KStdGuiItem::backAndForward();
  m_paBack = new KToolBarPopupAction( backForward.first, KStdAccel::shortcut(KStdAccel::Back), 0, "", actionCollection(), "back" );
  connect( m_paBack, TQT_SIGNAL( activated( KAction::ActivationReason, TQt::ButtonState) ), TQT_TQOBJECT(this),
	   TQT_SLOT( slotBack(KAction::ActivationReason, TQt::ButtonState) ) );
  connect( m_paBack->popupMenu(), TQT_SIGNAL( aboutToShow() ), TQT_TQOBJECT(this), TQT_SLOT( slotBackAboutToShow() ) );
  connect( m_paBack->popupMenu(), TQT_SIGNAL( activated( int ) ), TQT_TQOBJECT(this), TQT_SLOT( slotBackActivated( int ) ) );

  m_paForward = new KToolBarPopupAction( backForward.second, KStdAccel::shortcut(KStdAccel::Forward), 0, "", actionCollection(), "forward" );
  connect( m_paForward, TQT_SIGNAL( activated( KAction::ActivationReason, TQt::ButtonState) ), TQT_TQOBJECT(this),
	   TQT_SLOT( slotForward(KAction::ActivationReason, TQt::ButtonState) ) );
  connect( m_paForward->popupMenu(), TQT_SIGNAL( aboutToShow() ), TQT_TQOBJECT(this), TQT_SLOT( slotForwardAboutToShow() ) );
  connect( m_paForward->popupMenu(), TQT_SIGNAL( activated( int ) ), TQT_TQOBJECT(this), TQT_SLOT( slotForwardActivated( int ) ) );

  m_paHistory = new KonqBidiHistoryAction( i18n("History"), actionCollection(), "history" );
  connect( m_paHistory, TQT_SIGNAL( menuAboutToShow() ), TQT_TQOBJECT(this), TQT_SLOT( slotGoMenuAboutToShow() ) );
  connect( m_paHistory, TQT_SIGNAL( activated( int ) ), TQT_TQOBJECT(this), TQT_SLOT( slotGoHistoryActivated( int ) ) );

  m_paHome = new KAction( i18n( "Home" ), "gohome", KStdAccel::shortcut(KStdAccel::Home), actionCollection(), "home" );
  connect( m_paHome, TQT_SIGNAL( activated( KAction::ActivationReason, TQt::ButtonState) ), TQT_TQOBJECT(this),
	   TQT_SLOT( slotHome(KAction::ActivationReason, TQt::ButtonState) ) );

  (void) new KAction( i18n( "S&ystem" ), "system", 0, TQT_TQOBJECT(this), TQT_SLOT( slotGoSystem() ), actionCollection(), "go_system" );
  (void) new KAction( i18n( "App&lications" ), "kmenu", 0, TQT_TQOBJECT(this), TQT_SLOT( slotGoApplications() ), actionCollection(), "go_applications" );
  (void) new KAction( i18n( "&Storage Media" ), "system", 0, TQT_TQOBJECT(this), TQT_SLOT( slotGoMedia() ), actionCollection(), "go_media" );
  (void) new KAction( i18n( "&Network Folders" ), "network", 0, TQT_TQOBJECT(this), TQT_SLOT( slotGoNetworkFolders() ), actionCollection(), "go_network_folders" );
  (void) new KAction( i18n( "Sett&ings" ), "kcontrol", 0, TQT_TQOBJECT(this), TQT_SLOT( slotGoSettings() ), actionCollection(), "go_settings" );
  //(void) new KAction( i18n( "Sidebar Configuration" ), 0, this, TQT_SLOT( slotGoDirTree() ), actionCollection(), "go_dirtree" );
  (void) new KAction( i18n( "Trash" ), "trashcan_full", 0, TQT_TQOBJECT(this), TQT_SLOT( slotGoTrash() ), actionCollection(), "go_trash" );
  (void) new KAction( i18n( "Autostart" ), 0, TQT_TQOBJECT(this), TQT_SLOT( slotGoAutostart() ), actionCollection(), "go_autostart" );
  KonqMostOftenURLSAction *mostOften = new KonqMostOftenURLSAction( i18n("Most Often Visited"), actionCollection(), "go_most_often" );
  connect( mostOften, TQT_SIGNAL( activated( const KURL& )),
	   TQT_SLOT( slotOpenURL( const KURL& )));
  (void) new KAction( i18n( "History" ), "history", 0, TQT_TQOBJECT(this), TQT_SLOT( slotGoHistory() ), actionCollection(), "go_history" );

  // Settings menu

  m_paSaveViewProfile = new KAction( i18n( "&Save View Profile..." ), 0, TQT_TQOBJECT(this), TQT_SLOT( slotSaveViewProfile() ), actionCollection(), "saveviewprofile" );
  m_paSaveViewPropertiesLocally = new KToggleAction( i18n( "Save View Changes per &Folder" ), 0, TQT_TQOBJECT(this), TQT_SLOT( slotSaveViewPropertiesLocally() ), actionCollection(), "saveViewPropertiesLocally" );
   // "Remove" ? "Reset" ? The former is more correct, the latter is more kcontrol-like...
  m_paRemoveLocalProperties = new KAction( i18n( "Remove Folder Properties" ), 0, TQT_TQOBJECT(this), TQT_SLOT( slotRemoveLocalProperties() ), actionCollection(), "removeLocalProperties" );


  m_configureModules << "kde-filebehavior.desktop" << "kde-fileappearance.desktop" <<
      "kde-filepreviews.desktop" << "tde-filetypes.desktop" <<
      "tde-tdehtml_behavior.desktop" << "tde-tdehtml_java_js.desktop" <<
      "tde-tdehtml_filter.desktop" <<
      "tde-tdehtml_fonts.desktop" << "tde-ebrowsing.desktop" <<
      "tde-kcmhistory.desktop" << "tde-cookies.desktop" <<
      "tde-cache.desktop" << "tde-proxy.desktop" << "tde-kcmcss.desktop" <<
      "tde-crypto.desktop" << "tde-useragent.desktop" <<
      "tde-tdehtml_plugins.desktop" << "kde-kcmkonqyperformance.desktop";


  if (!kapp->authorizeControlModules(configModules()).isEmpty())
     KStdAction::preferences (TQT_TQOBJECT(this), TQT_SLOT (slotConfigure()), actionCollection() );

  KStdAction::keyBindings( guiFactory(), TQT_SLOT( configureShortcuts() ), actionCollection() );
  KStdAction::configureToolbars( TQT_TQOBJECT(this), TQT_SLOT( slotConfigureToolbars() ), actionCollection() );

  m_paConfigureExtensions = new KAction( i18n("Configure Extensions..."), 0, TQT_TQOBJECT(this), TQT_SLOT( slotConfigureExtensions()), actionCollection(), "options_configure_extensions");
  m_paConfigureSpellChecking = new KAction( i18n("Configure Spell Checking..."), "spellcheck", 0,TQT_TQOBJECT(this), TQT_SLOT( slotConfigureSpellChecking()), actionCollection(), "configurespellcheck");

  // Window menu
  m_paSplitViewHor = new KAction( i18n( "Split View &Left/Right" ), "view_left_right", CTRL+SHIFT+Key_L, TQT_TQOBJECT(this), TQT_SLOT( slotSplitViewHorizontal() ), actionCollection(), "splitviewh" );
  m_paSplitViewVer = new KAction( i18n( "Split View &Top/Bottom" ), "view_top_bottom", CTRL+SHIFT+Key_T, TQT_TQOBJECT(this), TQT_SLOT( slotSplitViewVertical() ), actionCollection(), "splitviewv" );
  m_paAddTab = new KAction( i18n( "&New Tab" ), "tab_new", "CTRL+SHIFT+N;CTRL+T", TQT_TQOBJECT(this), TQT_SLOT( slotAddTab() ), actionCollection(), "newtab" );
  m_paDuplicateTab = new KAction( i18n( "&Duplicate Current Tab" ), "tab_duplicate", CTRL+SHIFT+Key_D, TQT_TQOBJECT(this), TQT_SLOT( slotDuplicateTab() ), actionCollection(), "duplicatecurrenttab" );
  m_paBreakOffTab = new KAction( i18n( "Detach Current Tab" ), "tab_breakoff", CTRL+SHIFT+Key_B, TQT_TQOBJECT(this), TQT_SLOT( slotBreakOffTab() ), actionCollection(), "breakoffcurrenttab" );
  m_paRemoveView = new KAction( i18n( "&Close Active View" ),"view_remove", CTRL+SHIFT+Key_R, TQT_TQOBJECT(this), TQT_SLOT( slotRemoveView() ), actionCollection(), "removeview" );
  m_paRemoveTab = new KAction( i18n( "Close Current Tab" ), "tab_remove", CTRL+Key_W, TQT_TQOBJECT(this), TQT_SLOT( slotRemoveTab() ), actionCollection(), "removecurrenttab" );
  m_paRemoveOtherTabs = new KAction( i18n( "Close &Other Tabs" ), "tab_remove_other", 0, TQT_TQOBJECT(this), TQT_SLOT( slotRemoveOtherTabsPopup() ), actionCollection(), "removeothertabs" );

  m_paActivateNextTab = new KAction( i18n( "Activate Next Tab" ), "tab_next", TQApplication::reverseLayout() ? KStdAccel::tabPrev() : KStdAccel::tabNext(), TQT_TQOBJECT(this), TQT_SLOT( slotActivateNextTab() ), actionCollection(), "activatenexttab" );
  m_paActivatePrevTab = new KAction( i18n( "Activate Previous Tab" ), "tab_previous", TQApplication::reverseLayout() ? KStdAccel::tabNext() : KStdAccel::tabPrev(), TQT_TQOBJECT(this), TQT_SLOT( slotActivatePrevTab() ), actionCollection(), "activateprevtab" );

  TQCString actionname;
  for (int i=1;i<13;i++) {
    actionname.sprintf("activate_tab_%02d", i);
    new KAction(i18n("Activate Tab %1").arg(i), 0, TQT_TQOBJECT(this), TQT_SLOT(slotActivateTab()), actionCollection(), actionname);
  }

  m_paMoveTabLeft = new KAction( i18n("Move Tab Left"), 0 , CTRL+SHIFT+Key_Left,TQT_TQOBJECT(this), TQT_SLOT( slotMoveTabLeft()),actionCollection(),"tab_move_left");
  m_paMoveTabRight = new KAction( i18n("Move Tab Right"), 0 , CTRL+SHIFT+Key_Right,TQT_TQOBJECT(this), TQT_SLOT( slotMoveTabRight()),actionCollection(),"tab_move_right");

#ifndef NDEBUG
  (void) new KAction( i18n( "Dump Debug Info" ), "view_dump_debug_info", 0, TQT_TQOBJECT(this), TQT_SLOT( slotDumpDebugInfo() ), actionCollection(), "dumpdebuginfo" );
#endif

  m_paSaveRemoveViewProfile = new KAction( i18n( "C&onfigure View Profiles..." ), 0, m_pViewManager, TQT_SLOT( slotProfileDlg() ), actionCollection(), "saveremoveviewprofile" );
  m_pamLoadViewProfile = new KActionMenu( i18n( "Load &View Profile" ), actionCollection(), "loadviewprofile" );

  m_pViewManager->setProfiles( m_pamLoadViewProfile );

  m_ptaFullScreen = KStdAction::fullScreen( 0, 0, actionCollection(), this );
  KShortcut fullScreenShortcut = m_ptaFullScreen->shortcut();
  fullScreenShortcut.append( KKey( Key_F11 ) );
  m_ptaFullScreen->setShortcut( fullScreenShortcut );
  connect( m_ptaFullScreen, TQT_SIGNAL( toggled( bool )), TQT_TQOBJECT(this), TQT_SLOT( slotUpdateFullScreen( bool )));

  KShortcut reloadShortcut = KStdAccel::shortcut(KStdAccel::Reload);
  reloadShortcut.append(KKey(CTRL + Key_R));
  m_paReload = new KAction( i18n( "&Reload" ), "reload", reloadShortcut, TQT_TQOBJECT(this), TQT_SLOT( slotReload() ), actionCollection(), "reload" );
  m_paReloadAllTabs = new KAction( i18n( "&Reload All Tabs" ), "reload_all_tabs", SHIFT+Key_F5, TQT_TQOBJECT(this), TQT_SLOT( slotReloadAllTabs() ), actionCollection(), "reload_all_tabs" );
  
  m_paReloadStop = new KAction( i18n( "&Reload/Stop" ), "reload", 0, TQT_TQOBJECT(this), TQT_SLOT( slotReloadStop() ), actionCollection(), "reload_stop" );

  m_paUndo = KStdAction::undo( KonqUndoManager::self(), TQT_SLOT( undo() ), actionCollection(), "undo" );
  //m_paUndo->setEnabled( KonqUndoManager::self()->undoAvailable() );
  connect( KonqUndoManager::self(), TQT_SIGNAL( undoTextChanged( const TQString & ) ),
           m_paUndo, TQT_SLOT( setText( const TQString & ) ) );

  // Those are connected to the browserextension directly
  m_paCut = KStdAction::cut( 0, 0, actionCollection(), "cut" );
  KShortcut cutShortCut = m_paCut->shortcut();
  cutShortCut.remove( KKey( SHIFT + Key_Delete ) ); // used for deleting files
  m_paCut->setShortcut( cutShortCut );

  m_paCopy = KStdAction::copy( 0, 0, actionCollection(), "copy" );
  m_paPaste = KStdAction::paste( 0, 0, actionCollection(), "paste" );
  m_paStop = new KAction( i18n( "&Stop" ), "stop", Key_Escape, TQT_TQOBJECT(this), TQT_SLOT( slotStop() ), actionCollection(), "stop" );

  m_paRename = new KAction( i18n( "&Rename" ), /*"editrename",*/ Key_F2, actionCollection(), "rename" );
  m_paTrash = new KAction( i18n( "&Move to Trash" ), "edittrash", Key_Delete, actionCollection(), "trash" );
  connect( m_paTrash, TQT_SIGNAL( activated( KAction::ActivationReason, TQt::ButtonState ) ),
           TQT_TQOBJECT(this), TQT_SLOT( slotTrashActivated( KAction::ActivationReason, TQt::ButtonState ) ) );

  m_paDelete = new KAction( i18n( "&Delete" ), "editdelete", SHIFT+Key_Delete, actionCollection(), "del" );

  m_paAnimatedLogo = new KonqLogoAction( i18n("Animated Logo"), 0, TQT_TQOBJECT(this), TQT_SLOT( slotDuplicateWindow() ), actionCollection(), "animated_logo" );

  // Location bar
  m_locationLabel = new KonqDraggableLabel( this, i18n("L&ocation: ") );
  (void) new KWidgetAction( m_locationLabel, i18n("L&ocation: "), Key_F6, TQT_TQOBJECT(this), TQT_SLOT( slotLocationLabelActivated() ), actionCollection(), "location_label" );
  m_locationLabel->setBuddy( m_combo );

  KWidgetAction* comboAction = new KWidgetAction( m_combo, i18n( "Location Bar" ), 0,
                  0, 0, actionCollection(), "toolbar_url_combo" );
  comboAction->setShortcutConfigurable( false );
  comboAction->setAutoSized( true );

  TQWhatsThis::add( m_combo, i18n( "Location Bar<p>"
				  "Enter a web address or search term." ) );

  KAction *clearLocation = new KAction( i18n( "Clear Location Bar" ),
					TQApplication::reverseLayout() ? "clear_left" : "locationbar_erase",
					CTRL+Key_L, actionCollection(), "clear_location" );
  connect( clearLocation, TQT_SIGNAL( activated( KAction::ActivationReason, TQt::ButtonState ) ),
           TQT_SLOT( slotClearLocationBar( KAction::ActivationReason, TQt::ButtonState ) ) );
  clearLocation->setWhatsThis( i18n( "Clear Location bar<p>"
				     "Clears the content of the location bar." ) );

  // Bookmarks menu
  m_pamBookmarks = new KActionMenu( i18n( "&Bookmarks" ), "bookmark", actionCollection(), "bookmarks" );
  m_pamBookmarks->setDelayed( false );

  // The actual menu needs a different action collection, so that the bookmarks
  // don't appear in kedittoolbar
  m_bookmarksActionCollection = new KActionCollection( this );
  m_bookmarksActionCollection->setHighlightingEnabled( true );
  connectActionCollection( m_bookmarksActionCollection );

  m_pBookmarkMenu = new KBookmarkMenu( KonqBookmarkManager::self(), m_pBookmarksOwner, m_pamBookmarks->popupMenu(), m_bookmarksActionCollection, true );
  connect( m_pBookmarkMenu,
           TQT_SIGNAL( aboutToShowContextMenu(const KBookmark &, TQPopupMenu*) ),
           this, TQT_SLOT( slotFillContextMenu(const KBookmark &, TQPopupMenu*) ));
  connect( m_pBookmarkMenu,
	   TQT_SIGNAL( openBookmark(const TQString &, TQt::ButtonState) ),
	   this, TQT_SLOT( slotOpenBookmarkURL(const TQString &, TQt::ButtonState) ));

  KAction *addBookmark = actionCollection()->action("add_bookmark");
  if (addBookmark)
     addBookmark->setText(i18n("Bookmark This Location"));

  m_paShowMenuBar = KStdAction::showMenubar( TQT_TQOBJECT(this), TQT_SLOT( slotShowMenuBar() ), actionCollection() );

  (void) new KAction( i18n( "Kon&queror Introduction" ), 0, TQT_TQOBJECT(this), TQT_SLOT( slotIntro() ), actionCollection(), "konqintro" );

  KAction *goUrl = new KAction( i18n( "Go" ), "key_enter", 0, TQT_TQOBJECT(this), TQT_SLOT( goURL() ), actionCollection(), "go_url" );
  goUrl->setWhatsThis( i18n( "Go<p>"
			     "Goes to the page that has been entered into the location bar." ) );

  enableAllActions( false );

  // help stuff
  m_paUp->setWhatsThis( i18n( "Enter the parent folder<p>"
                              "For instance, if the current location is file:/home/%1 clicking this "
                              "button will take you to file:/home." ).arg( KUser().loginName() ) );
  m_paUp->setToolTip( i18n( "Enter the parent folder" ) );

  m_paBack->setWhatsThis( i18n( "Move backwards one step in the browsing history<p>" ) );
  m_paBack->setToolTip( i18n( "Move backwards one step in the browsing history" ) );

  m_paForward->setWhatsThis( i18n( "Move forward one step in the browsing history<p>" ) );
  m_paForward->setToolTip( i18n( "Move forward one step in the browsing history" ) );

  m_paHome->setWhatsThis( i18n( "Navigate to your 'Home Location'<p>"
                                "You can configure the location this button takes you to in the "
                                "<b>TDE Control Center</b>, under <b>File Manager</b>/<b>Behavior</b>." ) );
  m_paHome->setToolTip( i18n( "Navigate to your 'Home Location'" ) );

  m_paReload->setWhatsThis( i18n( "Reload the currently displayed document<p>"
                                  "This may, for example, be needed to refresh webpages that have been "
                                  "modified since they were loaded, in order to make the changes visible." ) );
  m_paReload->setToolTip( i18n( "Reload the currently displayed document" ) );

  m_paReloadAllTabs->setWhatsThis( i18n( "Reload all currently displayed documents in tabs<p>"
                                  "This may, for example, be needed to refresh webpages that have been "
                                  "modified since they were loaded, in order to make the changes visible." ) );
  m_paReloadAllTabs->setToolTip( i18n( "Reload all currently displayed document in tabs" ) );

  m_paStop->setWhatsThis( i18n( "Stop loading the document<p>"
                                "All network transfers will be stopped and Konqueror will display the content "
                                "that has been received so far." ) );
  m_paStop->setToolTip( i18n( "Stop loading the document" ) );

  m_paCut->setWhatsThis( i18n( "Cut the currently selected text or item(s) and move it "
                               "to the system clipboard<p> "
                               "This makes it available to the <b>Paste</b> command in Konqueror "
                               "and other TDE applications." ) );
  m_paCut->setToolTip( i18n( "Move the selected text or item(s) to the clipboard" ) );

  m_paCopy->setWhatsThis( i18n( "Copy the currently selected text or item(s) to the "
                                "system clipboard<p>"
                                "This makes it available to the <b>Paste</b> command in Konqueror "
                                "and other TDE applications." ) );
  m_paCopy->setToolTip( i18n( "Copy the selected text or item(s) to the clipboard" ) );

  m_paPaste->setWhatsThis( i18n( "Paste the previously cut or copied clipboard "
                                 "contents<p>"
                                 "This also works for text copied or cut from other TDE applications." ) );
  m_paPaste->setToolTip( i18n( "Paste the clipboard contents" ) );

  m_paPrint->setWhatsThis( i18n( "Print the currently displayed document<p>"
                                 "You will be presented with a dialog where you can set various "
                                 "options, such as the number of copies to print and which printer "
                                 "to use.<p>"
                                 "This dialog also provides access to special TDE printing "
                                 "services such as creating a PDF file from the current document." ) );
  m_paPrint->setToolTip( i18n( "Print the current document" ) );



  // Please proof-read those (David)

  m_ptaUseHTML->setToolTip( i18n("If present, open index.html when entering a folder.") );
  m_paLockView->setToolTip( i18n("A locked view cannot change folders. Use in combination with 'link view' to explore many files from one folder") );
  m_paLinkView->setToolTip( i18n("Sets the view as 'linked'. A linked view follows folder changes made in other linked views.") );
}

void KonqMainWindow::slotFillContextMenu( const KBookmark &bk, TQPopupMenu * pm )
{
  kdDebug() << "KonqMainWindow::slotFillContextMenu(bk, pm == " << pm << ")" << endl;
  popupItems.clear();
  popupUrlArgs = KParts::URLArgs();

  //Set tab_new_x to point to the correct icon based on NewTabsInFront
  bool newtabsinfront = KonqSettings::newTabsInFront();
  TQString tab_new_x ;
  if ( newtabsinfront )
    tab_new_x = "tab_new" ;
  else
    tab_new_x = "tab_new_bg" ;

  if ( bk.isGroup() )
  {
    KBookmarkGroup grp = bk.toGroup();
    TQValueList<KURL> list = grp.groupUrlList();
    TQValueList<KURL>::Iterator it = list.begin();
    for (; it != list.end(); ++it )
      popupItems.append( new KFileItem( (*it), TQString::null, KFileItem::Unknown) );
    pm->insertItem( SmallIcon(tab_new_x), i18n( "Open Folder in Tabs" ), this, TQT_SLOT( slotPopupNewTabRight() ) );
  }
  else
  {
    popupItems.append( new KFileItem( bk.url(), TQString::null, KFileItem::Unknown) );
    pm->insertItem( SmallIcon("window_new"), i18n( "Open in New Window" ), this, TQT_SLOT( slotPopupNewWindow() ) );
    pm->insertItem( SmallIcon(tab_new_x), i18n( "Open in New Tab" ), this, TQT_SLOT( slotPopupNewTabRight() ) );
  }
}

void KonqMainWindow::slotOpenBookmarkURL( const TQString & url, TQt::ButtonState state)
{
    kdDebug(1202) << "KonqMainWindow::slotOpenBookmarkURL(" << url << ", " << state << ")" << endl;

    KonqOpenURLRequest req;
    req.newTab = true;
    req.newTabInFront = KonqSettings::newTabsInFront();

    if (state & TQt::ShiftButton)
        req.newTabInFront = !req.newTabInFront;

    if( state & TQt::ControlButton ) // Ctrl Left/MMB
	openFilteredURL( url, req);
    else if( state & Qt::MidButton )
    {
        if(KonqSettings::mmbOpensTab())
	    openFilteredURL( url, req);
	else
	{
	    KURL finalURL = KonqMisc::konqFilteredURL( this, url );
	    KonqMisc::createNewWindow( finalURL.url() );
	}
    }
    else
	openFilteredURL( url, false );
}

void KonqMainWindow::slotMoveTabLeft()
{
  if ( TQApplication::reverseLayout() )
    m_pViewManager->moveTabForward();
  else
    m_pViewManager->moveTabBackward();
}

void KonqMainWindow::slotMoveTabRight()
{
  if ( TQApplication::reverseLayout() )
    m_pViewManager->moveTabBackward();
  else
    m_pViewManager->moveTabForward();
}

void KonqMainWindow::updateToolBarActions( bool pendingAction /*=false*/)
{
  // Enables/disables actions that depend on the current view & url (mostly toolbar)
  // Up, back, forward, the edit extension, stop button, wheel
  setUpEnabled( m_currentView->url() );
  m_paBack->setEnabled( m_currentView->canGoBack() );
  m_paForward->setEnabled( m_currentView->canGoForward() );

  if ( m_currentView->isLoading() )
  {
    startAnimation(); // takes care of m_paStop
  }
  else
  {
    m_paAnimatedLogo->stop();
    m_paStop->setEnabled( pendingAction );  //enable/disable based on any pending actions...
    toggleReloadStopButton( pendingAction );
  }

  if ( m_currentView && m_currentView->url().isLocalFile() &&
       !m_currentView->isLockedViewMode() ) {
      if ( m_currentView->serviceTypes().contains( "inode/directory" ) )
          m_ptaUseHTML->setEnabled( true );
      else if ( m_currentView->serviceTypes().contains(  "text/html" ) ) {
          // Currently viewing an index.html file via this feature (i.e. url points to a dir)
          TQString locPath = KURL( m_currentView->locationBarURL() ).path();
          m_ptaUseHTML->setEnabled( TQFileInfo( locPath ).isDir() );
      } else
          m_ptaUseHTML->setEnabled( false );
  }
  else
  {
      m_ptaUseHTML->setEnabled( false );
  }
}

void KonqMainWindow::updateViewActions()
{
  // Update actions that depend on the current view and its mode, or on the number of views etc.

  // Don't do things in this method that depend on m_currentView->url().
  // When going 'back' in history this will be called before opening the url.
  // Use updateToolBarActions instead.

  slotUndoAvailable( KonqUndoManager::self()->undoAvailable() );

  // Can lock a view only if there is a next view
  //m_paLockView->setEnabled( m_pViewManager->chooseNextView(m_currentView) != 0L && );
  //kdDebug(1202) << "KonqMainWindow::updateViewActions m_paLockView enabled ? " << m_paLockView->isEnabled() << endl;

  m_paLockView->setEnabled( viewCount() > 1 );
  m_paLockView->setChecked( m_currentView && m_currentView->isLockedLocation() );

  // Can remove view if we'll still have a main view after that
  m_paRemoveView->setEnabled( mainViewsCount() > 1 ||
                              ( m_currentView && m_currentView->isToggleView() ) );

  KonqFrameBase* docContainer = m_pViewManager->docContainer();

  if ( docContainer == 0L && !(currentView() && currentView()->frame()))
  {
    m_paAddTab->setEnabled( false );
    m_paDuplicateTab->setEnabled( false );
    m_paRemoveTab->setEnabled( false );
    m_paRemoveOtherTabs->setEnabled( false );
    m_paBreakOffTab->setEnabled( false );
    m_paActivateNextTab->setEnabled( false );
    m_paActivatePrevTab->setEnabled( false );
    m_paMoveTabLeft->setEnabled( false );
    m_paMoveTabRight->setEnabled( false );
  }
  else
  {
    m_paAddTab->setEnabled( true );
    m_paDuplicateTab->setEnabled( true );
    if ( docContainer && docContainer->frameType() == "Tabs" )
    {
        KonqFrameTabs* tabContainer = static_cast<KonqFrameTabs*>(docContainer);
        bool state = (tabContainer->count()>1);
        m_paRemoveTab->setEnabled( state );
	m_paRemoveOtherTabs->setEnabled( state );
        m_paBreakOffTab->setEnabled( state );
        m_paActivateNextTab->setEnabled( state );
        m_paActivatePrevTab->setEnabled( state );

        TQPtrList<KonqFrameBase>* childFrameList = tabContainer->childFrameList();
        m_paMoveTabLeft->setEnabled( currentView() ? currentView()->frame()!=
	    (TQApplication::reverseLayout() ? childFrameList->last() : childFrameList->first()) : false );
        m_paMoveTabRight->setEnabled( currentView() ? currentView()->frame()!=
	    (TQApplication::reverseLayout() ? childFrameList->first() : childFrameList->last()) : false );
    }
    else
    {
      m_paRemoveTab->setEnabled( false );
      m_paRemoveOtherTabs->setEnabled( false );
      m_paBreakOffTab->setEnabled( false );
      m_paActivateNextTab->setEnabled( false );
      m_paActivatePrevTab->setEnabled( false );
      m_paMoveTabLeft->setEnabled( false );
      m_paMoveTabRight->setEnabled( false );

    }
  }

  // Can split a view if it's not a toggle view (because a toggle view can be here only once)
  bool isNotToggle = m_currentView && !m_currentView->isToggleView();
  m_paSplitViewHor->setEnabled( isNotToggle );
  m_paSplitViewVer->setEnabled( isNotToggle );

  m_paLinkView->setChecked( m_currentView && m_currentView->isLinkedView() );

  if ( m_currentView && m_currentView->part() &&
       m_currentView->part()->inherits("KonqDirPart") )
  {
    KonqDirPart * dirPart = static_cast<KonqDirPart *>(m_currentView->part());
    m_paFindFiles->setEnabled( dirPart->findPart() == 0 );

    // Create the copy/move options if not already done
    if ( !m_paCopyFiles )
    {
      // F5 is the default key binding for Reload.... a la Windows.
      // mc users want F5 for Copy and F6 for move, but I can't make that default.
      m_paCopyFiles = new KAction( i18n("Copy &Files..."), Key_F7, TQT_TQOBJECT(this), TQT_SLOT( slotCopyFiles() ), actionCollection(), "copyfiles" );
      m_paMoveFiles = new KAction( i18n("M&ove Files..."), Key_F8, TQT_TQOBJECT(this), TQT_SLOT( slotMoveFiles() ), actionCollection(), "movefiles" );

      // This action doesn't appear in the GUI, it's for the shortcut only.
      // KNewMenu takes care of the GUI stuff.
      m_paNewDir = new KAction( i18n("Create Folder..." ), Key_F10, TQT_TQOBJECT(this), TQT_SLOT( slotNewDir() ),
                                actionCollection(), "konq_create_dir" );

      TQPtrList<KAction> lst;
      lst.append( m_paCopyFiles );
      lst.append( m_paMoveFiles );
      m_paCopyFiles->setEnabled( false );
      m_paMoveFiles->setEnabled( false );
      plugActionList( "operations", lst );
    }
  }
  else
  {
      m_paFindFiles->setEnabled( false );

      if (m_paCopyFiles)
      {
          unplugActionList( "operations" );
          delete m_paCopyFiles;
          m_paCopyFiles = 0;
          delete m_paMoveFiles;
          m_paMoveFiles = 0;
          delete m_paNewDir;
          m_paNewDir = 0;
      }
  }
}

TQString KonqMainWindow::findIndexFile( const TQString &dir )
{
  TQDir d( dir );

  TQString f = d.filePath( "index.html", false );
  if ( TQFile::exists( f ) )
    return f;

  f = d.filePath( "index.htm", false );
  if ( TQFile::exists( f ) )
    return f;

  f = d.filePath( "index.HTML", false );
  if ( TQFile::exists( f ) )
    return f;

  return TQString::null;
}

void KonqMainWindow::connectExtension( KParts::BrowserExtension *ext )
{
  //kdDebug(1202) << "Connecting extension " << ext << endl;
  KParts::BrowserExtension::ActionSlotMap * actionSlotMap = KParts::BrowserExtension::actionSlotMapPtr();
  KParts::BrowserExtension::ActionSlotMap::ConstIterator it = actionSlotMap->begin();
  KParts::BrowserExtension::ActionSlotMap::ConstIterator itEnd = actionSlotMap->end();

  TQStrList slotNames = ext->metaObject()->slotNames();

  for ( ; it != itEnd ; ++it )
  {
    KAction * act = actionCollection()->action( static_cast<const char *>(it.key()) );
    //kdDebug(1202) << it.key() << endl;
    if ( act )
    {
      // Does the extension have a slot with the name of this action ?
      if ( slotNames.contains( it.key()+"()" ) )
      {
          if ( it.key() != "trash" )
              connect( act, TQT_SIGNAL( activated() ), ext, it.data() /* TQT_SLOT(slot name) */ );
          act->setEnabled( ext->isActionEnabled( it.key() ) );
          const TQString text = ext->actionText( it.key() );
          if ( !text.isEmpty() )
              act->setText( text );
          // TODO how to re-set the original action text, when switching to a part that didn't call setAction?
          // Can't test with Paste...
      } else
          act->setEnabled(false);

    } else kdError(1202) << "Error in BrowserExtension::actionSlotMap(), unknown action : " << it.key() << endl;
  }

}

void KonqMainWindow::disconnectExtension( KParts::BrowserExtension *ext )
{
  //kdDebug(1202) << "Disconnecting extension " << ext << endl;
  KParts::BrowserExtension::ActionSlotMap * actionSlotMap = KParts::BrowserExtension::actionSlotMapPtr();
  KParts::BrowserExtension::ActionSlotMap::ConstIterator it = actionSlotMap->begin();
  KParts::BrowserExtension::ActionSlotMap::ConstIterator itEnd = actionSlotMap->end();

  TQStrList slotNames =  ext->metaObject()->slotNames();

  for ( ; it != itEnd ; ++it )
  {
    KAction * act = actionCollection()->action( static_cast<const char *>(it.key()) );
    //kdDebug(1202) << it.key() << endl;
    if ( act && slotNames.contains( it.key()+"()" ) )
    {
        //kdDebug(1202) << "disconnectExtension: " << act << " " << act->name() << endl;
        act->disconnect( ext );
    }
  }
}

void KonqMainWindow::slotTrashActivated( KAction::ActivationReason reason, TQt::ButtonState state )
{
  if ( !m_currentView )
    return;
  if ( reason == KAction::PopupMenuActivation && ( state & TQt::ShiftButton ) )
      m_currentView->callExtensionMethod( "del()" );
  else
      m_currentView->callExtensionMethod( "trash()" );
}

void KonqMainWindow::enableAction( const char * name, bool enabled )
{
  KAction * act = actionCollection()->action( name );
  if (!act)
    kdWarning(1202) << "Unknown action " << name << " - can't enable" << endl;
  else
  {
    if ( m_bLocationBarConnected && (
      act==m_paCopy || act==m_paCut || act==m_paPaste || act==m_paDelete || act==m_paTrash ) )
        // Don't change action state while the location bar has focus.
        return;
    //kdDebug(1202) << "KonqMainWindow::enableAction " << name << " " << enabled << endl;
    act->setEnabled( enabled );
  }

  // Update "copy files" and "move files" accordingly
  if (m_paCopyFiles && !strcmp( name, "copy" ))
  {
    m_paCopyFiles->setEnabled( enabled );
  }
  else if (m_paMoveFiles && !strcmp( name, "cut" ))
  {
    m_paMoveFiles->setEnabled( enabled );
  }
}

void KonqMainWindow::setActionText( const char * name, const TQString& text )
{
  KAction * act = actionCollection()->action( name );
  if (!act)
    kdWarning(1202) << "Unknown action " << name << " - can't enable" << endl;
  else
  {
    kdDebug(1202) << "KonqMainWindow::setActionText " << name << " " << text << endl;
    act->setText( text );
  }
}

void KonqMainWindow::currentProfileChanged()
{
    bool enabled = !m_pViewManager->currentProfile().isEmpty();
    m_paSaveViewProfile->setEnabled( enabled );
    m_paSaveViewProfile->setText( enabled ? i18n("&Save View Profile \"%1\"...").arg(m_pViewManager->currentProfileText())
                                          : i18n("&Save View Profile...") );
}

void KonqMainWindow::enableAllActions( bool enable )
{
  kdDebug(1202) << "KonqMainWindow::enableAllActions " << enable << endl;
  KParts::BrowserExtension::ActionSlotMap * actionSlotMap = KParts::BrowserExtension::actionSlotMapPtr();

  TQValueList<KAction *> actions = actionCollection()->actions();
  TQValueList<KAction *>::Iterator it = actions.begin();
  TQValueList<KAction *>::Iterator end = actions.end();
  for (; it != end; ++it )
  {
    KAction *act = *it;
    if ( !TQString(act->name()).startsWith("options_configure") /* do not touch the configureblah actions */
         && ( !enable || !actionSlotMap->contains( act->name() ) ) ) /* don't enable BE actions */
      act->setEnabled( enable );
  }
  // This method is called with enable=false on startup, and
  // then only once with enable=true when the first view is setup.
  // So the code below is where actions that should initially be disabled are disabled.
  if (enable)
  {
      setUpEnabled( m_currentView ? m_currentView->url() : KURL() );
      // we surely don't have any history buffers at this time
      m_paBack->setEnabled( false );
      m_paForward->setEnabled( false );

      // Load profile submenu
      m_pViewManager->profileListDirty( false );

      currentProfileChanged();

      updateViewActions(); // undo, lock, link and other view-dependent actions

      m_paStop->setEnabled( m_currentView && m_currentView->isLoading() );
      toggleReloadStopButton( m_currentView && m_currentView->isLoading() );

      if (m_toggleViewGUIClient)
      {
          TQPtrList<KAction> actions = m_toggleViewGUIClient->actions();
          for ( KAction * it = actions.first(); it ; it = actions.next() )
              it->setEnabled( true );
      }

  }
  actionCollection()->action( "quit" )->setEnabled( true );
}

void KonqMainWindow::disableActionsNoView()
{
    // No view -> there are some things we can't do
    m_paUp->setEnabled( false );
    m_paReload->setEnabled( false );
    m_paReloadAllTabs->setEnabled( false );
    m_paBack->setEnabled( false );
    m_paForward->setEnabled( false );
    m_ptaUseHTML->setEnabled( false );
    m_pMenuNew->setEnabled( false );
    m_paLockView->setEnabled( false );
    m_paLockView->setChecked( false );
    m_paSplitViewVer->setEnabled( false );
    m_paSplitViewHor->setEnabled( false );
    m_paRemoveView->setEnabled( false );
    m_paLinkView->setEnabled( false );
    if (m_toggleViewGUIClient)
    {
        TQPtrList<KAction> actions = m_toggleViewGUIClient->actions();
        for ( KAction * it = actions.first(); it ; it = actions.next() )
            it->setEnabled( false );
    }
    // There are things we can do, though : bookmarks, view profile, location bar, new window,
    // settings, etc.
    m_paHome->setEnabled( true );
    m_pamBookmarks->setEnabled( true );
    static const char* const s_enActions[] = { "new_window", "duplicate_window", "open_location",
                                         "toolbar_url_combo", "clear_location", "animated_logo",
                                         "konqintro", "go_most_often", "go_applications", "go_dirtree",
                                         "go_trash", "go_settings", "go_network_folders", "go_autostart",
                                         "go_url", "go_media", "go_history", "options_configure_extensions", 0 };
    for ( int i = 0 ; s_enActions[i] ; ++i )
    {
        KAction * act = action(s_enActions[i]);
        if (act)
            act->setEnabled( true );
    }
    m_pamLoadViewProfile->setEnabled( true );
    m_paSaveViewProfile->setEnabled( true );
    m_paSaveRemoveViewProfile->setEnabled( true );
    m_combo->clearTemporary();
    updateLocalPropsActions();
}

void KonqExtendedBookmarkOwner::openBookmarkURL( const TQString & /*url*/ )
{
  // Do nothing, we catch the signal
}

void KonqMainWindow::setCaption( const TQString &caption )
{
  // KParts sends us empty captions when activating a brand new part
  // We can't change it there (in case of apps removing all parts altogether)
  // but here we never do that.
  if ( !caption.isEmpty() && m_currentView )
  {
    kdDebug(1202) << "KonqMainWindow::setCaption(" << caption << ")" << endl;

    // Keep an unmodified copy of the caption (before kapp->makeStdCaption is applied)
    m_currentView->setCaption( caption );
    KParts::MainWindow::setCaption( m_currentView->caption() );
  }
}

void KonqMainWindow::show()
{
  // We need to check if our toolbars are shown/hidden here, and set
  // our menu items accordingly. We can't do it in the constructor because
  // view profiles store toolbar info, and that info is read after
  // construct time.
  m_paShowMenuBar->setChecked( !menuBar()->isHidden() );
  updateBookmarkBar(); // hide if empty

  // Call parent method
  KParts::MainWindow::show();
}

TQString KonqExtendedBookmarkOwner::currentURL() const
{
   return m_pKonqMainWindow->currentURL();
}

TQString KonqMainWindow::currentProfile() const
{
   return m_pViewManager->currentProfile();
}

TQString KonqMainWindow::currentURL() const
{
  if ( !m_currentView )
    return TQString::null;
  TQString url = m_currentView->url().prettyURL();
  if ( m_currentView->part() && m_currentView->part()->inherits("KonqDirPart") )
  {
      TQString nameFilter = static_cast<KonqDirPart *>(m_currentView->part())->nameFilter();
      if ( !nameFilter.isEmpty() )
      {
          if (!url.endsWith("/"))
              url += '/';
          url += nameFilter;
      }
  }
  return url;
}

void KonqExtendedBookmarkOwner::slotFillBookmarksList( KExtendedBookmarkOwner::QStringPairList & list )
{
  KonqFrameBase *docContainer = m_pKonqMainWindow->viewManager()->docContainer();
  if (docContainer == 0L) return;
  if (docContainer->frameType() != "Tabs") return;

  KonqFrameTabs* tabContainer = static_cast<KonqFrameTabs*>(docContainer);

  TQPtrList<KonqFrameBase> frameList = *tabContainer->childFrameList();
  TQPtrListIterator<KonqFrameBase> it( frameList );

  for ( it.toFirst(); it != 0L; ++it )
  {
    if ( !it.current()->activeChildView() )
      continue;
    if( it.current()->activeChildView()->locationBarURL().isEmpty() )
      continue;
    list << qMakePair( it.current()->activeChildView()->caption(),
                       it.current()->activeChildView()->url().url() );
  }
}

TQString KonqExtendedBookmarkOwner::currentTitle() const
{
   return m_pKonqMainWindow->currentTitle();
}

TQString KonqMainWindow::currentTitle() const
{
  return m_currentView ? m_currentView->caption() : TQString::null;
}

void KonqMainWindow::slotPopupMenu( const TQPoint &_global, const KURL &url, const TQString &_mimeType, mode_t _mode )
{
  slotPopupMenu( 0L, _global, url, _mimeType, _mode );
}

void KonqMainWindow::slotPopupMenu( KXMLGUIClient *client, const TQPoint &_global, const KURL &url, const TQString &_mimeType, mode_t _mode )
{
  KFileItem item( url, _mimeType, _mode );
  KFileItemList items;
  items.append( &item );
  slotPopupMenu( client, _global, items, KParts::URLArgs(), KParts::BrowserExtension::DefaultPopupItems, false ); //BE CAREFUL WITH sender() !
}

void KonqMainWindow::slotPopupMenu( KXMLGUIClient *client, const TQPoint &_global, const KURL &url, const KParts::URLArgs &_args, KParts::BrowserExtension::PopupFlags f, mode_t _mode )
{
  KFileItem item( url, _args.serviceType, _mode );
  KFileItemList items;
  items.append( &item );
  slotPopupMenu( client, _global, items, _args, f, false ); //BE CAREFUL WITH sender() !
}

void KonqMainWindow::slotPopupMenu( const TQPoint &_global, const KFileItemList &_items )
{
  slotPopupMenu( 0L, _global, _items );
}

void KonqMainWindow::slotPopupMenu( KXMLGUIClient *client, const TQPoint &_global, const KFileItemList &_items )
{
  slotPopupMenu( client, _global, _items, KParts::URLArgs(), KParts::BrowserExtension::DefaultPopupItems, true );
}

void KonqMainWindow::slotPopupMenu( KXMLGUIClient *client, const TQPoint &_global, const KFileItemList &_items, const KParts::URLArgs &_args, KParts::BrowserExtension::PopupFlags _flags )
{
  slotPopupMenu( client, _global, _items, _args, _flags, true );
}

void KonqMainWindow::slotPopupMenu( KXMLGUIClient *client, const TQPoint &_global, const KFileItemList &_items, const KParts::URLArgs &_args, KParts::BrowserExtension::PopupFlags itemFlags, bool showProperties )
{
  KonqView * m_oldView = m_currentView;

  KonqView * currentView = childView( static_cast<KParts::ReadOnlyPart *>( TQT_TQOBJECT_CONST(sender())->parent() ) );

  //kdDebug() << "KonqMainWindow::slotPopupMenu m_oldView=" << m_oldView << " new currentView=" << currentView << " passive:" << currentView->isPassiveMode() << endl;

  if ( (m_oldView != currentView) && currentView->isPassiveMode() )
  {
      // Make this view active only temporarily (because it's passive)
      m_currentView = currentView;

      if ( m_oldView && m_oldView->browserExtension() )
          disconnectExtension( m_oldView->browserExtension() );
      if ( m_currentView->browserExtension() )
          connectExtension( m_currentView->browserExtension() );
  }
  // Note that if m_oldView!=currentView and currentView isn't passive,
  // then the KParts mechanism has already noticed the click in it,
  // but KonqViewManager delays the GUI-rebuilding with a single-shot timer.
  // Right after the popup shows up, currentView _will_ be m_currentView.

  //kdDebug(1202) << "KonqMainWindow::slotPopupMenu( " << client << "...)" << " current view=" << m_currentView << " " << m_currentView->part()->className() << endl;

  // This action collection is used to pass actions to KonqPopupMenu.
  // It has to be a KActionCollection instead of a KActionPtrList because we need
  // the actionStatusText signal...
  KActionCollection popupMenuCollection( (TQWidget*)0 );
  popupMenuCollection.insert( m_paBack );
  popupMenuCollection.insert( m_paForward );
  popupMenuCollection.insert( m_paUp );
  popupMenuCollection.insert( m_paReload );

  popupMenuCollection.insert( m_paFindFiles );

  popupMenuCollection.insert( m_paUndo );
  popupMenuCollection.insert( m_paCut );
  popupMenuCollection.insert( m_paCopy );
  popupMenuCollection.insert( m_paPaste );
  popupMenuCollection.insert( m_paTrash );
  popupMenuCollection.insert( m_paRename );
  popupMenuCollection.insert( m_paDelete );

  // The pasteto action is used when clicking on a dir, to paste into it.
  KAction *actPaste = KStdAction::paste( TQT_TQOBJECT(this), TQT_SLOT( slotPopupPasteTo() ), &popupMenuCollection, "pasteto" );
  actPaste->setEnabled( m_paPaste->isEnabled() );
  popupMenuCollection.insert( actPaste );

  bool sReading = false;
  if ( _items.count() > 0 )
  {
    m_popupURL = _items.getFirst()->url();
    sReading = KProtocolInfo::supportsReading( m_popupURL );
    if (sReading)
      m_popupServiceType = _items.getFirst()->mimetype();
  }
  else
  {
    m_popupURL = KURL();
    m_popupServiceType = TQString::null;
  }

  if ( (_items.count() == 1) && !m_popupServiceType.isEmpty() ) {
      TQString currentServiceName = currentView->service()->desktopEntryName();

      // List of services for the "Preview In" submenu.
      m_popupEmbeddingServices = KTrader::self()->query(
          m_popupServiceType,
          "KParts/ReadOnlyPart",
          // Obey "HideFromMenus". It defaults to false so we want "absent or true"
          // (wow, testing for 'true' if absent doesn't work, so order matters)
          "(not exist [X-TDE-BrowserView-HideFromMenus] or not [X-TDE-BrowserView-HideFromMenus]) "
          "and DesktopEntryName != '"+currentServiceName+"' "
          // I had an old local dirtree.desktop without lib, no need for invalid entries
          "and exist [Library]",
          TQString::null );
  }


  // Don't set the view URL for a toggle view.
  // (This is a bit of a hack for the directory tree....)
  // ## should use the new currentView->isHierarchicalView() instead?
  // Would this be correct for the konqlistview tree view?
  KURL viewURL = currentView->isToggleView() ? KURL() : currentView->url();

  bool openedForViewURL = false;
  //bool dirsSelected = false;
  bool devicesFile = false;

  if ( _items.count() == 1 )
  {
      KURL firstURL = _items.getFirst()->url();
      if ( !viewURL.isEmpty() )
      {
	  //firstURL.cleanPath();
          openedForViewURL = firstURL.equals( viewURL, true );
      }
      devicesFile = firstURL.protocol().find("device", 0, false) == 0;
      //dirsSelected = S_ISDIR( _items.getFirst()->mode() );
  }
    //check if current url is trash
  KURL url = viewURL;
  url.cleanPath();
  bool isIntoTrash = url.protocol() == "trash" || url.url().startsWith( "system:/trash" );
  bool doTabHandling = !openedForViewURL && !isIntoTrash && sReading;
  bool showEmbeddingServices = !isIntoTrash && !devicesFile && (itemFlags & KParts::BrowserExtension::ShowTextSelectionItems) == 0;
  PopupMenuGUIClient *konqyMenuClient = new PopupMenuGUIClient( this, m_popupEmbeddingServices,
                                                                showEmbeddingServices, doTabHandling );

  //kdDebug(1202) << "KonqMainWindow::slotPopupMenu " << viewURL.prettyURL() << endl;


  // Those actions go into the PopupMenuGUIClient, since that's the one defining them.
  KAction *actNewWindow = 0L, *actNewTab = 0L;
  if( doTabHandling )
  {
      if (_args.forcesNewWindow()) {
        actNewWindow = new KAction( i18n( "Open in T&his Window" ), 0, TQT_TQOBJECT(this), TQT_SLOT( slotPopupThisWindow() ), konqyMenuClient->actionCollection(), "sameview" );
        actNewWindow->setToolTip( i18n( "Open the document in current window" ) );
      }
      actNewWindow = new KAction( i18n( "Open in New &Window" ), "window_new", 0, TQT_TQOBJECT(this), TQT_SLOT( slotPopupNewWindow() ), konqyMenuClient->actionCollection(), "newview" );
      actNewWindow->setToolTip( i18n( "Open the document in a new window" ) );

      //Set tab_new_x to point to the correct icon based on NewTabsInFront
      bool newtabsinfront = KonqSettings::newTabsInFront();
      TQString tab_new_x ;
      if ( newtabsinfront )
        tab_new_x = "tab_new" ;
      else
        tab_new_x = "tab_new_bg" ;

      KAction *actNewTab = new KAction( i18n( "Open in &Background Tab" ), "tab_new_bg", 0, TQT_TQOBJECT(this), TQT_SLOT( slotPopupNewTab() ), actionCollection(), "openintab" );
      actNewTab->setStatusText( i18n( "Open the document in a new background tab" ) );
      KAction *actNewTabFront = new KAction( i18n( "Open in &New Tab" ), "tab_new", 0, TQT_TQOBJECT(this), TQT_SLOT( slotPopupNewTabAtFront() ), actionCollection(), "openintabfront" );
      actNewTabFront->setStatusText( i18n( "Open the document in a new foreground tab" ) );
      actNewTab = new KAction( i18n( "Open in &Background Tab" ), tab_new_x, 0, TQT_TQOBJECT(this), TQT_SLOT( slotPopupNewTab() ), konqyMenuClient->actionCollection(), "openintab" );
      actNewTabFront = new KAction( i18n( "Open in &New Tab" ), tab_new_x, 0, TQT_TQOBJECT(this), TQT_SLOT( slotPopupNewTabAtFront() ), konqyMenuClient->actionCollection(), "openintabfront" );
      actNewTab->setToolTip( i18n( "Open the document in a new background tab" ) );
      actNewTabFront->setToolTip( i18n( "Open the document in a new foreground tab" ) );
      doTabHandling = true;
  }

  if (currentView->isHierarchicalView())
    itemFlags |= KParts::BrowserExtension::ShowCreateDirectory;

  KonqPopupMenu::KonqPopupFlags kpf = 0;
  if ( showProperties )
      kpf |= KonqPopupMenu::ShowProperties;
  else
      kpf |= KonqPopupMenu::IsLink; // HACK

  TQGuardedPtr<KonqPopupMenu> pPopupMenu = new KonqPopupMenu(
      KonqBookmarkManager::self(), _items,
      viewURL,
      popupMenuCollection,
      m_pMenuNew,
      // This parent ensures that if the part destroys itself (e.g. KHTML redirection),
      // it will close the popupmenu
      currentView->part()->widget(),
      kpf,
      itemFlags );

  if ( openedForViewURL && !viewURL.isLocalFile() )
      pPopupMenu->setURLTitle( currentView->caption() );

  // We will need these if we call the newTab slot
  popupItems = _items;
  popupUrlArgs = _args;
  popupUrlArgs.serviceType = TQString::null; // Reset so that Open in New Window/Tab does mimetype detection

  connectActionCollection( pPopupMenu->actionCollection() );

  pPopupMenu->factory()->addClient( konqyMenuClient );

  if ( client )
    pPopupMenu->factory()->addClient( client );

  KParts::BrowserExtension *be = ::tqqt_cast<KParts::BrowserExtension *>(sender());

  if ( be )
  {
    TQObject::connect( this, TQT_SIGNAL(popupItemsDisturbed()), pPopupMenu, TQT_SLOT(close()) );
    TQObject::connect( be, TQT_SIGNAL(itemsRemoved(const KFileItemList &)),
                      this, TQT_SLOT(slotItemsRemoved(const KFileItemList &)) );
  }

  TQObject::disconnect( m_pMenuNew->popupMenu(), TQT_SIGNAL(aboutToShow()),
                       this, TQT_SLOT(slotFileNewAboutToShow()) );

  TQGuardedPtr<TQObject> guard(TQT_TQOBJECT(this)); // #149736
  pPopupMenu->exec( _global );

  delete pPopupMenu;

  // We're sort of misusing KActionCollection here, but we need it for the actionStatusText signal...
  // Anyway. If the action belonged to the view, and the view got deleted, we don't want ~KActionCollection
  // to iterate over those deleted actions
  KActionPtrList lst = popupMenuCollection.actions();
  KActionPtrList::iterator it = lst.begin();
  for ( ; it != lst.end() ; ++it )
      popupMenuCollection.take( *it );

  if (guard.isNull()) { // the placement of this test is very important, double-check #149736 if moving stuff around
      return;
  }

  TQObject::connect( m_pMenuNew->popupMenu(), TQT_SIGNAL(aboutToShow()),
                       this, TQT_SLOT(slotFileNewAboutToShow()) );

  if ( be )
  {
    TQObject::disconnect( be, TQT_SIGNAL(itemsRemoved(const KFileItemList &)),
                         this, TQT_SLOT(slotItemsRemoved(const KFileItemList &)) );
  }

  delete konqyMenuClient;
  m_popupEmbeddingServices.clear();
  popupItems.clear();

  // Deleted by konqyMenuClient's actioncollection
  //delete actNewTab;
  //delete actNewWindow;

  delete actPaste;


  //kdDebug(1202) << "-------- KonqMainWindow::slotPopupMenu() - m_oldView = " << m_oldView << ", currentView = " << currentView
  //<< ", m_currentView = " << m_currentView << endl;

  // Restore current view if current is passive
  if ( (m_oldView != currentView) && (currentView == m_currentView) && currentView->isPassiveMode() )
  {
    //kdDebug() << "KonqMainWindow::slotPopupMenu restoring active view " << m_oldView << endl;
    if ( m_currentView->browserExtension() )
      disconnectExtension( m_currentView->browserExtension() );
    if ( m_oldView )
    {
        if ( m_oldView->browserExtension() )
        {
            connectExtension( m_oldView->browserExtension() );
            m_currentView = m_oldView;
        }
        // Special case: RMB + renaming in sidebar; setFocus would abort editing.
        TQWidget* fw = focusWidget();
        if ( !fw || !::tqqt_cast<TQLineEdit*>( fw ) )
            m_oldView->part()->widget()->setFocus();
    }
  }
}

void KonqMainWindow::slotItemsRemoved( const KFileItemList &items )
{
  TQPtrListIterator<KFileItem> it( items );
  for ( ; it.current(); ++it )
  {
    if ( popupItems.contains( it.current() ) )
    {
      emit popupItemsDisturbed();
      return;
    }
  }
}

void KonqMainWindow::slotOpenEmbedded()
{
  TQCString name = TQT_TQOBJECT_CONST(sender())->name();

  m_popupService = m_popupEmbeddingServices[ name.toInt() ]->desktopEntryName();

  m_popupEmbeddingServices.clear();

  TQTimer::singleShot( 0, this, TQT_SLOT( slotOpenEmbeddedDoIt() ) );
}

void KonqMainWindow::slotOpenEmbeddedDoIt()
{
  m_currentView->stop();
  m_currentView->setLocationBarURL(m_popupURL);
  m_currentView->setTypedURL(TQString::null);
  if ( m_currentView->changeViewMode( m_popupServiceType,
                                      m_popupService ) )
      m_currentView->openURL( m_popupURL, m_popupURL.pathOrURL() );
}

void KonqMainWindow::slotDatabaseChanged()
{
  if ( KSycoca::isChanged("mimetypes") )
  {
    MapViews::ConstIterator it = m_mapViews.begin();
    MapViews::ConstIterator end = m_mapViews.end();
    for (; it != end; ++it )
      (*it)->callExtensionMethod( "refreshMimeTypes()" );
  }
}

void KonqMainWindow::slotPopupPasteTo()
{
    if ( !m_currentView || m_popupURL.isEmpty() )
        return;
    m_currentView->callExtensionURLMethod( "pasteTo(const KURL&)", m_popupURL );
}

void KonqMainWindow::slotReconfigure()
{
  reparseConfiguration();
}

void KonqMainWindow::reparseConfiguration()
{
  kdDebug(1202) << "KonqMainWindow::reparseConfiguration() !" << endl;

  KonqSettings::self()->readConfig();

  m_bSaveViewPropertiesLocally = KonqSettings::saveViewPropertiesLocally();
  m_bHTMLAllowed = KonqSettings::htmlAllowed();

  MapViews::ConstIterator it = m_mapViews.begin();
  MapViews::ConstIterator end = m_mapViews.end();
  for (; it != end; ++it )
      (*it)->reparseConfiguration();
}

void KonqMainWindow::saveProperties( TDEConfig *config )
{
  m_pViewManager->saveViewProfile( *config, true /* save URLs */, false );
}

void KonqMainWindow::readProperties( TDEConfig *config )
{
  kdDebug(1202) << "KonqMainWindow::readProperties( TDEConfig *config )" << endl;
  m_pViewManager->loadViewProfile( *config, TQString::null /*no profile name*/ );
}

void KonqMainWindow::setInitialFrameName( const TQString &name )
{
  m_initialFrameName = name;
}

void KonqMainWindow::slotActionStatusText( const TQString &text )
{
  if ( !m_currentView )
    return;

  KonqFrameStatusBar *statusBar = m_currentView->frame()->statusbar();

  if ( !statusBar )
    return;

  statusBar->message( text );
}

void KonqMainWindow::slotClearStatusText()
{
  if ( !m_currentView )
    return;

  KonqFrameStatusBar *statusBar = m_currentView->frame()->statusbar();

  if ( !statusBar )
    return;

  statusBar->slotClear();
}

void KonqMainWindow::updateOpenWithActions()
{
  unplugActionList( "openwith" );

  m_openWithActions.clear();

  if (!kapp->authorizeKAction("openwith"))
     return;

  const KTrader::OfferList & services = m_currentView->appServiceOffers();
  KTrader::OfferList::ConstIterator it = services.begin();
  KTrader::OfferList::ConstIterator end = services.end();
  for (; it != end; ++it )
  {
    KAction *action = new KAction( i18n( "Open with %1" ).arg( (*it)->name() ), 0, 0, (*it)->desktopEntryName().latin1() );
    action->setIcon( (*it)->icon() );

    connect( action, TQT_SIGNAL( activated() ),
             this, TQT_SLOT( slotOpenWith() ) );

    m_openWithActions.append( action );
  }
  if ( services.count() > 0 )
  {
      m_openWithActions.append( new KActionSeparator );
      plugActionList( "openwith", m_openWithActions );
  }
}

TQString KonqMainWindow::viewModeActionKey( KService::Ptr service )
{
    TQString library = service->library();
    // Group all non-builtin views together
    TQVariant builtIntoProp = service->property( "X-TDE-BrowserView-Built-Into" );
    if ( !builtIntoProp.isValid() || builtIntoProp.toString() != "konqueror" )
        library = "external";
    return library;
}

void KonqMainWindow::updateViewModeActions()
{
  unplugViewModeActions();
  if ( m_viewModeMenu )
  {
    TQPtrListIterator<KRadioAction> it( m_viewModeActions );
    for (; it.current(); ++it )
      it.current()->unplugAll();
    delete m_viewModeMenu;
  }

  m_viewModeMenu = 0;
  m_toolBarViewModeActions.clear();
  m_viewModeActions.clear();

  // if we changed the viewmode to something new, then we have to
  // make sure to also clear our [libiconview,liblistview]->service-for-viewmode
  // map
  if ( m_viewModeToolBarServices.count() > 0 &&
       !m_viewModeToolBarServices.begin().data()->serviceTypes().contains( m_currentView->serviceType() ) )
  {
      // Save the current map to the config file, for later reuse
      saveToolBarServicesMap();

      m_viewModeToolBarServices.clear();
  }

  KTrader::OfferList services = m_currentView->partServiceOffers();

  if ( services.count() <= 1 )
    return;

  m_viewModeMenu = new KActionMenu( i18n( "&View Mode" ), TQT_TQOBJECT(this) );

  // a temporary map, just like the m_viewModeToolBarServices map, but
  // mapping to a KonqViewModeAction object. It's just temporary as we
  // of use it to group the viewmode actions (iconview,multicolumnview,
  // treeview, etc.) into to two groups -> icon/list
  // Although I wrote this now only of icon/listview it has to work for
  // any view, that's why it's so general :)
  TQMap<TQString,KonqViewModeAction*> groupedServiceMap;

  // Another temporary map, the preferred service for each library (2 entries in our example)
  TQMap<TQString,TQString> preferredServiceMap;

  TDEConfig * config = TDEGlobal::config();
  config->setGroup( "ModeToolBarServices" );

  KTrader::OfferList::ConstIterator it = services.begin();
  KTrader::OfferList::ConstIterator end = services.end();
  for (; it != end; ++it )
  {
      TQVariant prop = (*it)->property( "X-TDE-BrowserView-Toggable" );
      if ( prop.isValid() && prop.toBool() ) // No toggable views in view mode
          continue;

      KRadioAction *action;

      TQString itname = (*it)->genericName();
      if (itname.isEmpty())
          itname = (*it)->name();

      TQString icon = (*it)->icon();
      if ( icon != TQString::fromLatin1( "unknown" ) )
          // we *have* to specify a parent qobject, otherwise the exclusive group stuff doesn't work!(Simon)
          action = new KRadioAction( itname, icon, 0, TQT_TQOBJECT(this), (*it)->desktopEntryName().ascii() );
      else
          action = new KRadioAction( itname, 0, TQT_TQOBJECT(this), (*it)->desktopEntryName().ascii() );

      action->setExclusiveGroup( "KonqMainWindow_ViewModes" );

      connect( action, TQT_SIGNAL( toggled( bool ) ),
               this, TQT_SLOT( slotViewModeToggle( bool ) ) );

      m_viewModeActions.append( action );
      action->plug( m_viewModeMenu->popupMenu() );

      const TQString library = viewModeActionKey( *it );

      // look if we already have a KonqViewModeAction (in the toolbar)
      // for this component
      TQMap<TQString,KonqViewModeAction*>::Iterator mapIt = groupedServiceMap.find( library );

      // if we don't have -> create one
      if ( mapIt == groupedServiceMap.end() )
      {
          // default service on this action: the current one (i.e. the first one)
          TQString text = itname;
          TQString icon = (*it)->icon();
          TQCString name = (*it)->desktopEntryName().latin1();
          //kdDebug(1202) << " Creating action for " << library << ". Default service " << itname << endl;

          // if we previously changed the viewmode (see slotViewModeToggle!)
          // then we will want to use the previously used settings (previous as
          // in before the actions got deleted)
          TQMap<TQString,KService::Ptr>::ConstIterator serviceIt = m_viewModeToolBarServices.find( library );
          if ( serviceIt != m_viewModeToolBarServices.end() )
          {
              kdDebug(1202) << " Setting action for " << library << " to " << (*serviceIt)->name() << endl;
              text = (*serviceIt)->genericName();
              if (text.isEmpty())
                  text = (*serviceIt)->name();
              icon = (*serviceIt)->icon();
              name = (*serviceIt)->desktopEntryName().ascii();
          } else
          {
              // if we don't have it in the map, we should look for a setting
              // for this library in the config file.
              TQString preferredService = config->readEntry( library );
              if ( !preferredService.isEmpty() && name != preferredService.latin1() )
              {
                  //kdDebug(1202) << " Inserting into preferredServiceMap(" << library << ") : " << preferredService << endl;
                  // The preferred service isn't the current one, so remember to set it later
                  preferredServiceMap[ library ] = preferredService;
              }
          }

          KonqViewModeAction *tbAction = new KonqViewModeAction( text,
                                                                 icon,
                                                                 TQT_TQOBJECT(this),
                                                                 name );

          tbAction->setExclusiveGroup( "KonqMainWindow_ToolBarViewModes" );

          tbAction->setChecked( action->isChecked() );

          connect( tbAction, TQT_SIGNAL( toggled( bool ) ),
                   this, TQT_SLOT( slotViewModeToggle( bool ) ) );

          m_toolBarViewModeActions.append( tbAction );

          mapIt = groupedServiceMap.insert( library, tbAction );
      }

      // Check the actions (toolbar button and menu item) if they correspond to the current view
      bool bIsCurrentView = (*it)->desktopEntryName() == m_currentView->service()->desktopEntryName();
      if ( bIsCurrentView )
      {
          action->setChecked( true );
      }

      // Set the contents of the button from the current service, either if it's the current view
      // or if it's our preferred service for this button (library)
      if ( bIsCurrentView
           || ( preferredServiceMap.contains( library ) && (*it)->desktopEntryName() == preferredServiceMap[ library ] ) )
      {
          //kdDebug(1202) << " Changing action for " << library << " into service " << (*it)->name() << endl;

          TQString mapitname = (*it)->genericName();
          if (mapitname.isEmpty())
              mapitname = (*it)->name();
          (*mapIt)->setText( mapitname );
          (*mapIt)->setIcon( (*it)->icon() );
          (*mapIt)->setName( (*it)->desktopEntryName().ascii() ); // tricky...
          preferredServiceMap.remove( library ); // The current view has priority over the saved settings
      }

      // plug action also into the delayed popupmenu of appropriate toolbar action
      action->plug( (*mapIt)->popupMenu() );
  }

#ifndef NDEBUG
  // Note that this can happen (map not empty) when a inode/directory view is removed,
  // and remains in the TDEConfig file.
  Q_ASSERT( preferredServiceMap.isEmpty() );
  TQMap<TQString,TQString>::Iterator debugIt = preferredServiceMap.begin();
  TQMap<TQString,TQString>::Iterator debugEnd = preferredServiceMap.end();
  for ( ; debugIt != debugEnd ; ++debugIt )
      kdDebug(1202) << " STILL IN preferredServiceMap : " << debugIt.key() << " | " << debugIt.data() << endl;
#endif

  if ( !m_currentView->isToggleView() ) // No view mode for toggable views
      // (The other way would be to enforce a better servicetype for them, than Browser/View)
      if ( /* already tested: services.count() > 1 && */ m_viewModeMenu )
          plugViewModeActions();
}

void KonqMainWindow::saveToolBarServicesMap()
{
    TQMap<TQString,KService::Ptr>::ConstIterator serviceIt = m_viewModeToolBarServices.begin();
    TQMap<TQString,KService::Ptr>::ConstIterator serviceEnd = m_viewModeToolBarServices.end();
    TDEConfig * config = TDEGlobal::config();
    config->setGroup( "ModeToolBarServices" );
    for ( ; serviceIt != serviceEnd ; ++serviceIt )
        config->writeEntry( serviceIt.key(), serviceIt.data()->desktopEntryName() );
    config->sync();
}

void KonqMainWindow::plugViewModeActions()
{
  TQPtrList<KAction> lst;
  lst.append( m_viewModeMenu );
  plugActionList( "viewmode", lst );
  // display the toolbar viewmode icons only for inode/directory, as here we have dedicated icons
  if ( m_currentView && m_currentView->supportsServiceType( "inode/directory" ) )
    plugActionList( "viewmode_toolbar", m_toolBarViewModeActions );
}

void KonqMainWindow::unplugViewModeActions()
{
  unplugActionList( "viewmode" );
  unplugActionList( "viewmode_toolbar" );
}

KonqMainWindowIface* KonqMainWindow::dcopObject()
{
  return m_dcopObject;
}

void KonqMainWindow::updateBookmarkBar()
{
  KToolBar * bar = static_cast<KToolBar *>( TQT_TQWIDGET(child( "bookmarkToolBar", "KToolBar" )) );

  if (!bar) return;

  // hide if empty
  if (m_paBookmarkBar && bar->count() == 0 )
        bar->hide();

}

void KonqMainWindow::closeEvent( TQCloseEvent *e )
{
  kdDebug(1202) << "KonqMainWindow::closeEvent begin" << endl;
  // This breaks session management (the window is withdrawn in twin)
  // so let's do this only when closed by the user.
  if ( static_cast<KonquerorApplication *>(kapp)->closedByUser() )
  {
    if ( viewManager()->docContainer() && viewManager()->docContainer()->frameType()=="Tabs" )
    {
      KonqFrameTabs* tabContainer = static_cast<KonqFrameTabs*>(viewManager()->docContainer());
      if ( tabContainer->count() > 1 )
      {
        TDEConfig *config = TDEGlobal::config();
        TDEConfigGroupSaver cs( config, TQString::fromLatin1("Notification Messages") );

        if ( !config->hasKey( "MultipleTabConfirm" ) )
        {
          switch (
              KMessageBox::warningYesNoCancel(
                  this,
                  i18n("You have multiple tabs open in this window, "
                        "are you sure you want to quit?"),
                  i18n("Confirmation"),
                  KStdGuiItem::quit(),
                  KGuiItem(i18n( "C&lose Current Tab" ), "tab_remove"),
                  "MultipleTabConfirm"
              )
            ) {
            case KMessageBox::Yes :
            break;
            case KMessageBox::No :
            {
              e->ignore();
              slotRemoveTab();
              return;
            }
            break;
            case KMessageBox::Cancel :
            {
              e->ignore();
    	      return;
            }
          }
        }
      }

      KonqView *originalView = m_currentView;
      MapViews::ConstIterator it = m_mapViews.begin();
      MapViews::ConstIterator end = m_mapViews.end();
      for (; it != end; ++it ) {
        KonqView *view = it.data();
        if (view && view->part() && (view->part()->metaObject()->findProperty("modified") != -1) ) {
          TQVariant prop = view->part()->property("modified");
          if (prop.isValid() && prop.toBool()) {
            m_pViewManager->showTab( view );
            if ( KMessageBox::warningContinueCancel( this,
              i18n("This tab contains changes that have not been submitted.\nClosing the window will discard these changes."),
              i18n("Discard Changes?"), KGuiItem(i18n("&Discard Changes"),"exit"), "discardchangesclose") != KMessageBox::Continue )
            {
              e->ignore();
              m_pViewManager->showTab( originalView );
              return;
            }
          }
        }
      }
//      m_pViewManager->showTab( originalView );
    }
    else if ( m_currentView && m_currentView->part() &&
             (m_currentView->part()->metaObject()->findProperty("modified") != -1) )
    {
      TQVariant prop = m_currentView->part()->property("modified");
      if (prop.isValid() && prop.toBool())
         if ( KMessageBox::warningContinueCancel( this,
           i18n("This page contains changes that have not been submitted.\nClosing the window will discard these changes."),
           i18n("Discard Changes?"), KGuiItem(i18n("&Discard Changes"),"exit"), "discardchangesclose") != KMessageBox::Continue )
         {
           e->ignore();
           return;
         }
    }

    // save size to have something to restore if the profile does not contain size
    saveWindowSize();

    hide();
    tqApp->flushX();
  }
  // We're going to close - tell the parts
  MapViews::ConstIterator it = m_mapViews.begin();
  MapViews::ConstIterator end = m_mapViews.end();
  for (; it != end; ++it )
  {
      if ( (*it)->part() && (*it)->part()->widget() )
          TQApplication::sendEvent( (*it)->part()->widget(), e );
  }
  KParts::MainWindow::closeEvent( e );
  if( isPreloaded() && !kapp->sessionSaving())
  { // queryExit() refused closing, hide instead
      hide();
  }
  kdDebug(1202) << "KonqMainWindow::closeEvent end" << endl;
}

bool KonqMainWindow::queryExit()
{
    if( kapp->sessionSaving()) // *sigh*
        return true;
    return !stayPreloaded();
}

void KonqMainWindow::setIcon( const TQPixmap& pix )
{
  KParts::MainWindow::setIcon( pix );

  TQPixmap big = pix;

  TQString url = m_combo->currentText();

  if ( !url.isEmpty() )
    big = KonqPixmapProvider::self()->pixmapFor( url, KIcon::SizeMedium );

  KWin::setIcons( winId(), big, pix );
}

void KonqMainWindow::slotIntro()
{
  openURL( 0L, KURL("about:konqueror") );
}

void KonqMainWindow::goURL()
{
  TQLineEdit *lineEdit = m_combo->lineEdit();
  if ( !lineEdit )
    return;

  TQKeyEvent event( TQEvent::KeyPress, Key_Return, '\n', 0 );
  TQApplication::sendEvent( lineEdit, &event );
}

void KonqMainWindow::slotLocationLabelActivated()
{
  focusLocationBar();
  m_combo->lineEdit()->selectAll();
}

void KonqMainWindow::slotOpenURL( const KURL& url )
{
    openURL( 0L, url );
}

bool KonqMainWindow::sidebarVisible() const
{
KAction *a = m_toggleViewGUIClient->action("konq_sidebartng");
return (a && static_cast<KToggleAction*>(a)->isChecked());
}

void KonqMainWindow::slotAddWebSideBar(const KURL& url, const TQString& name)
{
    if (url.url().isEmpty() && name.isEmpty())
        return;

    kdDebug(1202) << "Requested to add URL " << url << " [" << name << "] to the sidebar!" << endl;

    KAction *a = m_toggleViewGUIClient->action("konq_sidebartng");
    if (!a) {
        KMessageBox::sorry(0L, i18n("Your sidebar is not functional or unavailable. A new entry cannot be added."), i18n("Web Sidebar"));
        return;
    }

    int rc = KMessageBox::questionYesNo(0L,
              i18n("Add new web extension \"%1\" to your sidebar?")
                                .arg(name.isEmpty() ? name : url.prettyURL()),
              i18n("Web Sidebar"),i18n("Add"),i18n("Do Not Add"));

    if (rc == KMessageBox::Yes) {
        // Show the sidebar
        if (!static_cast<KToggleAction*>(a)->isChecked()) {
            a->activate();
        }

        // Tell it to add a new panel
        MapViews::ConstIterator it;
        for (it = viewMap().begin(); it != viewMap().end(); ++it) {
            KonqView *view = it.data();
            if (view) {
                KService::Ptr svc = view->service();
                if (svc->desktopEntryName() == "konq_sidebartng") {
                    emit view->browserExtension()->addWebSideBar(url, name);
                    break;
                }
            }
        }
    }
}

void KonqMainWindow::bookmarksIntoCompletion( const KBookmarkGroup& group )
{
    static const TQString& http = TDEGlobal::staticQString( "http" );
    static const TQString& ftp = TDEGlobal::staticQString( "ftp" );

    if ( group.isNull() )
        return;

    for ( KBookmark bm = group.first();
          !bm.isNull(); bm = group.next(bm) ) {
        if ( bm.isGroup() ) {
            bookmarksIntoCompletion( bm.toGroup() );
            continue;
        }

        KURL url = bm.url();
        if ( !url.isValid() )
            continue;

        TQString u = url.prettyURL();
        s_pCompletion->addItem( u );

        if ( url.isLocalFile() )
            s_pCompletion->addItem( url.path() );
        else if ( url.protocol() == http )
            s_pCompletion->addItem( u.mid( 7 ));
        else if ( url.protocol() == ftp &&
                  url.host().startsWith( ftp ) )
            s_pCompletion->addItem( u.mid( 6 ) );
    }
}

void KonqMainWindow::connectActionCollection( KActionCollection *coll )
{
    connect( coll, TQT_SIGNAL( actionStatusText( const TQString & ) ),
             this, TQT_SLOT( slotActionStatusText( const TQString & ) ) );
    connect( coll, TQT_SIGNAL( clearStatusText() ),
             this, TQT_SLOT( slotClearStatusText() ) );
}

void KonqMainWindow::disconnectActionCollection( KActionCollection *coll )
{
    disconnect( coll, TQT_SIGNAL( actionStatusText( const TQString & ) ),
                this, TQT_SLOT( slotActionStatusText( const TQString & ) ) );
    disconnect( coll, TQT_SIGNAL( clearStatusText() ),
                this, TQT_SLOT( slotClearStatusText() ) );
}

//
// the smart popup completion code , <l.lunak@kde.org>
//

// prepend http://www. or http:// if there's no protocol in 's'
// used only when there are no completion matches
static TQString hp_tryPrepend( const TQString& s )
{
    if( s.isEmpty() || s[ 0 ] == '/' )
        return TQString::null;
    for( unsigned int pos = 0;
         pos < s.length() - 2; // 4 = ://x
         ++pos )
        {
        if( s[ pos ] == ':' && s[ pos + 1 ] == '/' && s[ pos + 2 ] == '/' )
            return TQString::null;
        if( !s[ pos ].isLetter() )
            break;
        }
    return ( s.startsWith( "www." ) ? "http://" : "http://www." ) + s;
}


static void hp_removeDupe( KCompletionMatches& l, const TQString& dupe,
    KCompletionMatches::Iterator it_orig )
{
    for( KCompletionMatches::Iterator it = l.begin();
         it != l.end();
         ) {
        if( it == it_orig ) {
            ++it;
            continue;
        }
        if( (*it).value() == dupe ) {
            (*it_orig).first = kMax( (*it_orig).first, (*it).index());
            it = l.remove( it );
            continue;
        }
        ++it;
    }
}

// remove duplicates like 'http://www.kde.org' and 'http://www.kde.org/'
// (i.e. the trailing slash)
// some duplicates are also created by prepending protocols
static void hp_removeDuplicates( KCompletionMatches& l )
{
    TQString http = "http://";
    TQString ftp = "ftp://ftp.";
    TQString file = "file:";
    TQString file2 = "file://";
    l.removeDuplicates();
    for( KCompletionMatches::Iterator it = l.begin();
         it != l.end();
         ++it ) {
        TQString str = (*it).value();
        if( str.startsWith( http )) {
            if( str.find( '/', 7 ) < 0 ) { // http://something<noslash>
                hp_removeDupe( l, str + '/', it );
                hp_removeDupe( l, str.mid( 7 ) + '/', it );
            } else if( str[ str.length() - 1 ] == '/' ) {
                hp_removeDupe( l, str.left( str.length() - 1 ), it );
                hp_removeDupe( l, str.left( str.length() - 1 ).mid( 7 ), it );
            }
            hp_removeDupe( l, str.mid( 7 ), it );
        }
        else if( str.startsWith( ftp )) // ftp://ftp.
            hp_removeDupe( l, str.mid( 6 ), it ); // remove dupes without ftp://
        else if( str.startsWith( file2 ))
            hp_removeDupe( l, str.mid( 7 ), it ); // remove dupes without file://
        else if( str.startsWith( file ))
            hp_removeDupe( l, str.mid( 5 ), it ); // remove dupes without file:
    }
}

static void hp_removeCommonPrefix( KCompletionMatches& l, const TQString& prefix )
{
    for( KCompletionMatches::Iterator it = l.begin();
         it != l.end();
         ) {
        if( (*it).value().startsWith( prefix )) {
            it = l.remove( it );
            continue;
        }
        ++it;
    }
}

// don't include common prefixes like 'http://', i.e. when s == 'h', include
// http://hotmail.com but don't include everything just starting with 'http://'
static void hp_checkCommonPrefixes( KCompletionMatches& matches, const TQString& s )
{
    static const char* const prefixes[] = {
        "http://",
        "https://",
        "www.",
        "ftp://",
        "http://www.",
        "https://www.",
        "ftp://ftp.",
        "file:",
        "file://",
        NULL };
    for( const char* const *pos = prefixes;
         *pos != NULL;
         ++pos ) {
        TQString prefix = *pos;
        if( prefix.startsWith( s )) {
            hp_removeCommonPrefix( matches, prefix );
        }
    }
}

TQStringList KonqMainWindow::historyPopupCompletionItems( const TQString& s)
{
    const TQString http = "http://";
    const TQString https = "https://";
    const TQString www = "http://www.";
    const TQString wwws = "https://www.";
    const TQString ftp = "ftp://";
    const TQString ftpftp = "ftp://ftp.";
    const TQString file = "file:"; // without /, because people enter /usr etc.
    const TQString file2 = "file://";
    if( s.isEmpty())
	    return TQStringList();
    KCompletionMatches matches= s_pCompletion->allWeightedMatches( s );
    hp_checkCommonPrefixes( matches, s );
    bool checkDuplicates = false;
    if ( !s.startsWith( ftp ) ) {
        matches += s_pCompletion->allWeightedMatches( ftp + s );
	if( TQString( "ftp." ).startsWith( s ))
            hp_removeCommonPrefix( matches, ftpftp );
        checkDuplicates = true;
    }
    if ( !s.startsWith( https ) ) {
        matches += s_pCompletion->allWeightedMatches( https + s );
	if( TQString( "www." ).startsWith( s ))
            hp_removeCommonPrefix( matches, wwws );
        checkDuplicates = true;
    }
    if ( !s.startsWith( http )) {
        matches += s_pCompletion->allWeightedMatches( http + s );
	if( TQString( "www." ).startsWith( s ))
            hp_removeCommonPrefix( matches, www );
        checkDuplicates = true;
    }
    if ( !s.startsWith( www ) ) {
        matches += s_pCompletion->allWeightedMatches( www + s );
        checkDuplicates = true;
    }
    if ( !s.startsWith( wwws ) ) {
        matches += s_pCompletion->allWeightedMatches( wwws + s );
        checkDuplicates = true;
    }
    if ( !s.startsWith( ftpftp ) ) {
        matches += s_pCompletion->allWeightedMatches( ftpftp + s );
        checkDuplicates = true;
    }
    if ( !s.startsWith( file ) ) {
        matches += s_pCompletion->allWeightedMatches( file + s );
        checkDuplicates = true;
    }
    if ( !s.startsWith( file2 ) ) {
        matches += s_pCompletion->allWeightedMatches( file2 + s );
        checkDuplicates = true;
    }
    if( checkDuplicates )
        hp_removeDuplicates( matches );
    TQStringList items = matches.list();
    if( items.count() == 0
	&& !s.contains( ':' ) && s[ 0 ] != '/' )
        {
        TQString pre = hp_tryPrepend( s );
        if( !pre.isNull())
            items += pre;
        }
    return items;
}

#ifndef NDEBUG
void KonqMainWindow::dumpViewList()
{
  MapViews::Iterator end = m_mapViews.end();

  kdDebug(1202) << m_mapViews.count() << "Views" << endl;

  for (MapViews::Iterator it = m_mapViews.begin(); it != end; it++)
  {
    kdDebug(1202) << it.data() << endl;
  }
}
#endif

// KonqFrameContainerBase implementation BEGIN

/**
 * Call this after inserting a new frame into the splitter.
 */
void KonqMainWindow::insertChildFrame( KonqFrameBase * frame, int /*index*/ )
{
  m_pChildFrame = frame;
  m_pActiveChild = frame;
  frame->setParentContainer(this);
  setCentralWidget( frame->widget() );
}

/**
 * Call this before deleting one of our children.
 */
void KonqMainWindow::removeChildFrame( KonqFrameBase * /*frame*/ )
{
  m_pChildFrame = 0L;
  m_pActiveChild = 0L;
}

void KonqMainWindow::saveConfig( TDEConfig* config, const TQString &prefix, bool saveURLs, KonqFrameBase* docContainer, int id, int depth ) { if( m_pChildFrame ) m_pChildFrame->saveConfig( config, prefix, saveURLs, docContainer, id, depth); }

void KonqMainWindow::copyHistory( KonqFrameBase *other ) { if( m_pChildFrame ) m_pChildFrame->copyHistory( other ); }

void KonqMainWindow::printFrameInfo( const TQString &spaces ) { if( m_pChildFrame ) m_pChildFrame->printFrameInfo( spaces ); }

void KonqMainWindow::reparentFrame( TQWidget* /*parent*/,
                                    const TQPoint & /*p*/, bool /*showIt*/ ) { return; }

KonqFrameContainerBase* KonqMainWindow::parentContainer()const { return 0L; }
void KonqMainWindow::setParentContainer(KonqFrameContainerBase* /*parent*/) { return; }

void KonqMainWindow::setTitle( const TQString &/*title*/ , TQWidget* /*sender*/) { return; }
void KonqMainWindow::setTabIcon( const KURL &/*url*/, TQWidget* /*sender*/ ) { return; }

TQWidget* KonqMainWindow::widget() { return this; }

void KonqMainWindow::listViews( ChildViewList *viewList ) { if( m_pChildFrame ) m_pChildFrame->listViews( viewList ); }

TQCString KonqMainWindow::frameType() { return TQCString("MainWindow"); }

KonqFrameBase* KonqMainWindow::childFrame()const { return m_pChildFrame; }

void KonqMainWindow::setActiveChild( KonqFrameBase* /*activeChild*/ ) { return; }

bool KonqMainWindow::isMimeTypeAssociatedWithSelf( const TQString &mimeType )
{
    return isMimeTypeAssociatedWithSelf( mimeType, KServiceTypeProfile::preferredService( mimeType, "Application" ) );
}

bool KonqMainWindow::isMimeTypeAssociatedWithSelf( const TQString &/*mimeType*/, const KService::Ptr &offer )
{
    // Prevention against user stupidity : if the associated app for this mimetype
    // is konqueror/kfmclient, then we'll loop forever. So we have to
    // 1) force embedding first, if that works we're ok
    // 2) check what KRun is going to do before calling it.
    return ( offer && ( offer->desktopEntryName() == "konqueror" ||
             offer->exec().stripWhiteSpace().startsWith( "kfmclient" ) ) );
}

// KonqFrameContainerBase implementation END

void KonqMainWindow::setPreloadedFlag( bool preloaded )
{
    if( s_preloaded == preloaded )
        return;
    s_preloaded = preloaded;
    if( s_preloaded )
    {
        kapp->disableSessionManagement(); // dont restore preloaded konqy's
        return; // was registered before calling this
    }
    delete s_preloadedWindow; // preloaded state was abandoned without reusing the window
    s_preloadedWindow = NULL;
    kapp->enableSessionManagement(); // enable SM again
    DCOPRef ref( "kded", "konqy_preloader" );
    ref.send( "unregisterPreloadedKonqy", kapp->dcopClient()->appId());
}

void KonqMainWindow::setPreloadedWindow( KonqMainWindow* window )
{
    s_preloadedWindow = window;
    if( window == NULL )
        return;
    window->viewManager()->clear();
    TDEIO::Scheduler::unregisterWindow( TQT_TQOBJECT(window) );
}

// used by preloading - this KonqMainWindow will be reused, reset everything
// that won't be reset by loading a profile
void KonqMainWindow::resetWindow()
{
    char data[ 1 ];
    // empty append to get current X timestamp
    TQWidget tmp_widget;
    XChangeProperty( tqt_xdisplay(), tmp_widget.winId(), XA_WM_CLASS, XA_STRING, 8,
		    PropModeAppend, (unsigned char*) &data, 0 );
    XEvent ev;
    XWindowEvent( tqt_xdisplay(), tmp_widget.winId(), PropertyChangeMask, &ev );
    long x_time = ev.xproperty.time;
    // bad hack - without updating the _KDE_NET_WM_USER_CREATION_TIME property,
    // KWin will apply don't_steal_focus to this window, and will not make it active
    // (shows mainly with 'konqueror --preload')
    static Atom atom = XInternAtom( tqt_xdisplay(), "_KDE_NET_WM_USER_CREATION_TIME", False );
    XChangeProperty( tqt_xdisplay(), winId(), atom, XA_CARDINAL, 32,
		     PropModeReplace, (unsigned char *) &x_time, 1);
    SET_QT_X_USER_TIME(CurrentTime); // won't have _NET_WM_USER_TIME set
#if !KDE_IS_VERSION( 3, 2, 90 ) // _KDE_NET_USER_TIME is obsolete
    static Atom atom2 = XInternAtom( tqt_xdisplay(), "_KDE_NET_USER_TIME", False );
    timeval tv;
    gettimeofday( &tv, NULL );
    unsigned long now = tv.tv_sec * 10 + tv.tv_usec / 100000;
    XChangeProperty(tqt_xdisplay(), winId(), atom2, XA_CARDINAL,
                    32, PropModeReplace, (unsigned char *)&now, 1);
#endif
    static Atom atom3 = XInternAtom( tqt_xdisplay(), "_NET_WM_USER_TIME", False );
    XDeleteProperty( tqt_xdisplay(), winId(), atom3 );
// Qt remembers the iconic state if the window was withdrawn while on another virtual desktop
    clearWState( WState_Minimized );
    ignoreInitialGeometry();
    kapp->setTopWidget( this ); // set again the default window icon
}

bool KonqMainWindow::event( TQEvent* e )
{
    if( e->type() == TQEvent::DeferredDelete )
    {
    // since the preloading code tries to reuse KonqMainWindow,
    // the last window shouldn't be really deleted, but only hidden
    // deleting WDestructiveClose windows is done using deleteLater(),
    // so catch TQEvent::DefferedDelete and check if this window should stay
        if( stayPreloaded())
        {
            setWFlags(WDestructiveClose); // was reset before deleteLater()
            return true; // no deleting
        }
    }
    return KParts::MainWindow::event( e );
}

bool KonqMainWindow::stayPreloaded()
{
    // last window?
    if( mainWindowList()->count() > 1 )
        return false;
    // not running in full KDE environment?
    if( getenv( "TDE_FULL_SESSION" ) == NULL || getenv( "TDE_FULL_SESSION" )[ 0 ] == '\0' )
        return false;
    // not the same user like the one running the session (most likely we're run via sudo or something)
    if( getenv( "TDE_SESSION_UID" ) != NULL && uid_t( atoi( getenv( "TDE_SESSION_UID" ))) != getuid())
        return false;
    if( KonqSettings::maxPreloadCount() == 0 )
        return false;
    viewManager()->clear(); // reduce resource usage before checking it
    if( !checkPreloadResourceUsage())
        return false;
    DCOPRef ref( "kded", "konqy_preloader" );
    if( !ref.callExt( "registerPreloadedKonqy", DCOPRef::NoEventLoop, 5000,
        kapp->dcopClient()->appId(), tqt_xscreen()))
    {
        return false;
    }
    KonqMainWindow::setPreloadedFlag( true );
    kdDebug(1202) << "Konqy kept for preloading :" << kapp->dcopClient()->appId() << endl;
    KonqMainWindow::setPreloadedWindow( this );
    return true;
}

// try to avoid staying running when leaking too much memory
// this is checked by using mallinfo() and comparing
// memory usage during konqy startup and now, if the difference
// is too large -> leaks -> quit
// also, if this process is running for too long, or has been
// already reused too many times -> quit, just in case
bool KonqMainWindow::checkPreloadResourceUsage()
{
    if(
#ifndef NDEBUG
        isatty( STDIN_FILENO ) ||
#endif
        isatty( STDOUT_FILENO ) || isatty( STDERR_FILENO ))
    {
        kdDebug(1202) << "Running from tty, not keeping for preloading" << endl;
        return false;
    }
    int limit;
    int usage = current_memory_usage( &limit );
    kdDebug(1202) << "Memory usage increase: " << ( usage - s_initialMemoryUsage )
        << " (" << usage << "/" << s_initialMemoryUsage << "), increase limit: " << limit << endl;
    int max_allowed_usage = s_initialMemoryUsage + limit;
    if( usage > max_allowed_usage ) // too much memory used?
    {
	kdDebug(1202) << "Not keeping for preloading due to high memory usage" << endl;
	return false;
    }
    // working memory usage test ( usage != 0 ) makes others less strict
    if( ++s_preloadUsageCount > ( usage != 0 ? 100 : 10 )) // reused too many times?
    {
	kdDebug(1202) << "Not keeping for preloading due to high usage count" << endl;
	return false;
    }
    if( time( NULL ) > s_startupTime + 60 * 60 * ( usage != 0 ? 4 : 1 )) // running for too long?
    {
	kdDebug(1202) << "Not keeping for preloading due to long usage time" << endl;
	return false;
    }
    return true;
}

static int current_memory_usage( int* limit )
{
#ifdef __linux__
// Check whole memory usage - VmSize
    TQFile f( TQCString().sprintf( "/proc/%i/statm", getpid()));
    if( f.open( IO_ReadOnly ))
    {
        TQString line;
        if( f.readLine( line, 1024 ) > 0 )
        {
            line = line.stripWhiteSpace();
            int usage = line.section( ' ', 0, 0 ).toInt();
            if( usage > 0 )
            {
                int pagesize = sysconf (_SC_PAGE_SIZE);
                if( pagesize < 0 )
                    pagesize = 4096;
                if( limit != NULL )
                    *limit = 16 * 1024 * 1024;
                return usage * pagesize;
            }
        }
    }
    kdWarning() << "Couldn't read VmSize from /proc/*/statm." << endl;
#endif
// Check malloc() usage - very imprecise, but better than nothing.
    int usage_sum = 0;
#if defined(KDE_MALLINFO_STDLIB) || defined(KDE_MALLINFO_MALLOC)
    // ugly hack for tdecore/malloc
    extern int kde_malloc_is_used;
    free( calloc( 4, 4 )); // trigger setting kde_malloc_is_used
    if( kde_malloc_is_used )
    {
	struct mallinfo m = mallinfo();
	usage_sum = m.hblkhd + m.uordblks;
    }
    else
    {
        struct mallinfo m = mallinfo();
#ifdef KDE_MALLINFO_FIELD_hblkhd
        usage_sum += m.hblkhd;
#endif
#ifdef KDE_MALLINFO_FIELD_uordblks
        usage_sum += m.uordblks;
#endif
#ifdef KDE_MALLINFO_FIELD_usmblks
        usage_sum += m.usmblks;
#endif
    }
    // unlike /proc , this doesn't include things like size of dlopened modules,
    // and also doesn't include malloc overhead
    if( limit != NULL )
        *limit = 6 * 1024 * 1024;
#endif
    return usage_sum;
}

void KonqMainWindow::saveWindowSize() const
{
    TQString savedGroup = TDEGlobal::config()->group();
    TDEGlobal::config()->setGroup( "KonqMainWindow_Size" );

    KParts::MainWindow::saveWindowSize( TDEGlobal::config() );

    TDEGlobal::config()->setGroup( savedGroup );
    TDEGlobal::config()->sync();
}

void KonqMainWindow::restoreWindowSize()
{
    TQString savedGroup = TDEGlobal::config()->group();
    TDEGlobal::config()->setGroup( "KonqMainWindow_Size" );

    KParts::MainWindow::restoreWindowSize( TDEGlobal::config() );

    TDEGlobal::config()->setGroup( savedGroup );
}


#include "konq_mainwindow.moc"
#include "konq_mainwindow_p.moc"
/* vim: et sw=4 ts=4
 */