File: gtkfilesel.c

package info (click to toggle)
gtk+2.0 2.24.32-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 128,080 kB
  • sloc: ansic: 574,621; makefile: 5,197; sh: 4,500; xml: 1,193; python: 1,119; perl: 749; awk: 72; cpp: 34
file content (4236 lines) | stat: -rw-r--r-- 113,334 bytes parent folder | download | duplicates (2)
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
/* GTK - The GIMP Toolkit
 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

/*
 * Modified by the GTK+ Team and others 1997-2000.  See the AUTHORS
 * file for a list of people on the GTK+ Team.  See the ChangeLog
 * files for a list of changes.  These files are distributed with
 * GTK+ at ftp://ftp.gtk.org/pub/gtk/. 
 */

#include "config.h"

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
#include <stdlib.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <string.h>
#include <errno.h>
#ifdef HAVE_PWD_H
#include <pwd.h>
#endif

#include <glib.h>		/* Include early to get G_OS_WIN32 etc */
#include <glib/gstdio.h>

#if defined(G_PLATFORM_WIN32)
#include <ctype.h>
#define STRICT
#include <windows.h>
#undef STRICT
#endif /* G_PLATFORM_WIN32 */

#include "gdk/gdkkeysyms.h"

#undef GTK_DISABLE_DEPRECATED /* GtkOptionMenu */

#include "gtkbutton.h"
#include "gtkcellrenderertext.h"
#include "gtkentry.h"
#include "gtkfilesel.h"
#include "gtkhbox.h"
#include "gtkhbbox.h"
#include "gtkintl.h"
#include "gtklabel.h"
#include "gtkliststore.h"
#include "gtkmain.h"
#include "gtkprivate.h"
#include "gtkscrolledwindow.h"
#include "gtkstock.h"
#include "gtktreeselection.h"
#include "gtktreeview.h"
#include "gtkvbox.h"
#include "gtkmenu.h"
#include "gtkmenuitem.h"
#include "gtkdialog.h"
#include "gtkmessagedialog.h"
#include "gtkdnd.h"
#include "gtkeventbox.h"
#include "gtkoptionmenu.h"

#include "gtkimage.h"

#define WANT_HPANED 1
#include "gtkhpaned.h"

#include "stock-icons/ximian-icons.h"

#include "gtkalias.h"

#ifdef G_OS_WIN32
#include <direct.h>
#include <io.h>
#ifndef S_ISDIR
#define S_ISDIR(mode) ((mode)&_S_IFDIR)
#endif
#endif /* G_OS_WIN32 */

#ifdef G_WITH_CYGWIN
#include <sys/cygwin.h>		/* For cygwin_conv_to_posix_path */
#endif

#define DIR_LIST_WIDTH   180
#define DIR_LIST_HEIGHT  180
#define FILE_LIST_WIDTH  180
#define FILE_LIST_HEIGHT 180

/* The Hurd doesn't define either PATH_MAX or MAXPATHLEN, so we put this
 * in here, since the rest of the code in the file does require some
 * fixed maximum.
 */
#ifndef MAXPATHLEN
#  ifdef PATH_MAX
#    define MAXPATHLEN PATH_MAX
#  else
#    define MAXPATHLEN 2048
#  endif
#endif

/* I've put this here so it doesn't get confused with the 
 * file completion interface */
typedef struct _HistoryCallbackArg HistoryCallbackArg;

struct _HistoryCallbackArg
{
  gchar *directory;
  GtkWidget *menu_item;
};


typedef struct _CompletionState    CompletionState;
typedef struct _CompletionDir      CompletionDir;
typedef struct _CompletionDirSent  CompletionDirSent;
typedef struct _CompletionDirEntry CompletionDirEntry;
typedef struct _CompletionUserDir  CompletionUserDir;
typedef struct _PossibleCompletion PossibleCompletion;

/* Non-external file completion decls and structures */

/* A contant telling PRCS how many directories to cache.  Its actually
 * kept in a list, so the geometry isn't important. */
#define CMPL_DIRECTORY_CACHE_SIZE 10

/* A constant used to determine whether a substring was an exact
 * match by first_diff_index()
 */
#define PATTERN_MATCH -1
#define CMPL_ERRNO_TOO_LONG ((1<<16)-1)
#define CMPL_ERRNO_DID_NOT_CONVERT ((1<<16)-2)

/* This structure contains all the useful information about a directory
 * for the purposes of filename completion.  These structures are cached
 * in the CompletionState struct.  CompletionDir's are reference counted.
 */
struct _CompletionDirSent
{
#ifndef G_PLATFORM_WIN32
  ino_t inode;
  time_t mtime;
  dev_t device;
#endif

  gint entry_count;
  struct _CompletionDirEntry *entries;
};

struct _CompletionDir
{
  CompletionDirSent *sent;

  gchar *fullname;
  gint fullname_len;

  struct _CompletionDir *cmpl_parent;
  gint cmpl_index;
  gchar *cmpl_text;
};

/* This structure contains pairs of directory entry names with a flag saying
 * whether or not they are a valid directory.  NOTE: This information is used
 * to provide the caller with information about whether to update its completions
 * or try to open a file.  Since directories are cached by the directory mtime,
 * a symlink which points to an invalid file (which will not be a directory),
 * will not be reevaluated if that file is created, unless the containing
 * directory is touched.  I consider this case to be worth ignoring (josh).
 */
struct _CompletionDirEntry
{
  gboolean is_dir;
  gchar *entry_name;
  gchar *sort_key;
};

struct _CompletionUserDir
{
  gchar *login;
  gchar *homedir;
};

struct _PossibleCompletion
{
  /* accessible fields, all are accessed externally by functions
   * declared above
   */
  gchar *text;
  gint is_a_completion;
  gboolean is_directory;

  /* Private fields
   */
  gint text_alloc;
};

struct _CompletionState
{
  gint last_valid_char;
  gchar *updated_text;
  gint updated_text_len;
  gint updated_text_alloc;
  gboolean re_complete;

  gchar *user_dir_name_buffer;
  gint user_directories_len;

  gchar *last_completion_text;

  gint user_completion_index; /* if >= 0, currently completing ~user */

  struct _CompletionDir *completion_dir; /* directory completing from */
  struct _CompletionDir *active_completion_dir;

  struct _PossibleCompletion the_completion;

  struct _CompletionDir *reference_dir; /* initial directory */

  GList* directory_storage;
  GList* directory_sent_storage;

  struct _CompletionUserDir *user_directories;
};

enum {
  PROP_0,
  PROP_SHOW_FILEOPS,
  PROP_FILENAME,
  PROP_SELECT_MULTIPLE
};

enum {
  DIR_COLUMN
};

enum {
  FILE_COLUMN
};

/* File completion functions which would be external, were they used
 * outside of this file.
 */

static CompletionState*    cmpl_init_state        (void);
static void                cmpl_free_state        (CompletionState *cmpl_state);
static gint                cmpl_state_okay        (CompletionState* cmpl_state);
static const gchar*        cmpl_strerror          (gint);

static PossibleCompletion* cmpl_completion_matches(gchar           *text_to_complete,
						   gchar          **remaining_text,
						   CompletionState *cmpl_state);

/* Returns a name for consideration, possibly a completion, this name
 * will be invalid after the next call to cmpl_next_completion.
 */
static char*               cmpl_this_completion   (PossibleCompletion*);

/* True if this completion matches the given text.  Otherwise, this
 * output can be used to have a list of non-completions.
 */
static gint                cmpl_is_a_completion   (PossibleCompletion*);

/* True if the completion is a directory
 */
static gboolean            cmpl_is_directory      (PossibleCompletion*);

/* Obtains the next completion, or NULL
 */
static PossibleCompletion* cmpl_next_completion   (CompletionState*);

/* Updating completions: the return value of cmpl_updated_text() will
 * be text_to_complete completed as much as possible after the most
 * recent call to cmpl_completion_matches.  For the present
 * application, this is the suggested replacement for the user's input
 * string.  You must CALL THIS AFTER ALL cmpl_text_completions have
 * been received.
 */
static gchar*              cmpl_updated_text       (CompletionState* cmpl_state);

/* After updating, to see if the completion was a directory, call
 * this.  If it was, you should consider re-calling completion_matches.
 */
static gboolean            cmpl_updated_dir        (CompletionState* cmpl_state);

/* Current location: if using file completion, return the current
 * directory, from which file completion begins.  More specifically,
 * the cwd concatenated with all exact completions up to the last
 * directory delimiter('/').
 */
static gchar*              cmpl_reference_position (CompletionState* cmpl_state);

#if 0
/* This doesn't work currently and would require changes
 * to fnmatch.c to get working.
 */
/* backing up: if cmpl_completion_matches returns NULL, you may query
 * the index of the last completable character into cmpl_updated_text.
 */
static gint                cmpl_last_valid_char    (CompletionState* cmpl_state);
#endif

/* When the user selects a non-directory, call cmpl_completion_fullname
 * to get the full name of the selected file.
 */
static gchar*              cmpl_completion_fullname (const gchar*, CompletionState* cmpl_state);

static void home_clicked (GtkWidget *widget, gpointer data);
static void desktop_clicked (GtkWidget *widget, gpointer data);
static void documents_clicked (GtkWidget *widget, gpointer data);

/* Directory operations. */
static CompletionDir* open_ref_dir         (gchar* text_to_complete,
					    gchar** remaining_text,
					    CompletionState* cmpl_state);
#ifndef G_PLATFORM_WIN32
static gboolean       check_dir            (gchar *dir_name, 
					    GStatBuf *result, 
					    gboolean *stat_subdirs);
#endif
static CompletionDir* open_dir             (gchar* dir_name,
					    CompletionState* cmpl_state);
#ifdef HAVE_PWD_H
static CompletionDir* open_user_dir        (const gchar* text_to_complete,
					    CompletionState *cmpl_state);
#endif
static CompletionDir* open_relative_dir    (gchar* dir_name, CompletionDir* dir,
					    CompletionState *cmpl_state);
static CompletionDirSent* open_new_dir     (gchar* dir_name, 
					    GStatBuf *sbuf,
					    gboolean stat_subdirs);
static gint           correct_dir_fullname (CompletionDir* cmpl_dir);
static gint           correct_parent       (CompletionDir* cmpl_dir,
					    GStatBuf *sbuf);
#ifndef G_PLATFORM_WIN32
static gchar*         find_parent_dir_fullname    (gchar* dirname);
#endif
static CompletionDir* attach_dir           (CompletionDirSent* sent,
					    gchar* dir_name,
					    CompletionState *cmpl_state);
static void           free_dir_sent (CompletionDirSent* sent);
static void           free_dir      (CompletionDir  *dir);
static void           prune_memory_usage(CompletionState *cmpl_state);

/* Completion operations */
#ifdef HAVE_PWD_H
static PossibleCompletion* attempt_homedir_completion(gchar* text_to_complete,
						      CompletionState *cmpl_state);
#endif
static PossibleCompletion* attempt_file_completion(CompletionState *cmpl_state);
static CompletionDir* find_completion_dir(gchar* text_to_complete,
					  gchar** remaining_text,
					  CompletionState* cmpl_state);
static PossibleCompletion* append_completion_text(gchar* text,
						  CompletionState* cmpl_state);
#ifdef HAVE_PWD_H
static gint get_pwdb(CompletionState* cmpl_state);
static gint compare_user_dir(const void* a, const void* b);
#endif
static gint first_diff_index(gchar* pat, gchar* text);
static gint compare_cmpl_dir(const void* a, const void* b);
static void update_cmpl(PossibleCompletion* poss,
			CompletionState* cmpl_state);

static void gtk_file_selection_set_property  (GObject         *object,
					      guint            prop_id,
					      const GValue    *value,
					      GParamSpec      *pspec);
static void gtk_file_selection_get_property  (GObject         *object,
					      guint            prop_id,
					      GValue          *value,
					      GParamSpec      *pspec);
static void gtk_file_selection_finalize      (GObject               *object);
static void gtk_file_selection_destroy       (GtkObject             *object);
static void gtk_file_selection_map           (GtkWidget             *widget);
static gint gtk_file_selection_key_press     (GtkWidget             *widget,
					      GdkEventKey           *event,
					      gpointer               user_data);
static gint gtk_file_selection_insert_text   (GtkWidget             *widget,
					      const gchar           *new_text,
					      gint                   new_text_length,
					      gint                  *position,
					      gpointer               user_data);
static void gtk_file_selection_update_fileops (GtkFileSelection     *filesel);

static void gtk_file_selection_file_activate (GtkTreeView       *tree_view,
					      GtkTreePath       *path,
					      GtkTreeViewColumn *column,
					      gpointer           user_data);
static void gtk_file_selection_file_changed  (GtkTreeSelection  *selection,
					      gpointer           user_data);
static void gtk_file_selection_dir_activate  (GtkTreeView       *tree_view,
					      GtkTreePath       *path,
					      GtkTreeViewColumn *column,
					      gpointer           user_data);

static void gtk_file_selection_populate      (GtkFileSelection      *fs,
					      gchar                 *rel_path,
					      gboolean               try_complete,
					      gboolean               reset_entry);
static void gtk_file_selection_abort         (GtkFileSelection      *fs);

static void gtk_file_selection_update_history_menu (GtkFileSelection       *fs,
						    gchar                  *current_dir);

static void gtk_file_selection_create_dir  (GtkWidget *widget, gpointer data);
static void gtk_file_selection_delete_file (GtkWidget *widget, gpointer data);
static void gtk_file_selection_rename_file (GtkWidget *widget, gpointer data);

static void free_selected_names (GPtrArray *names);

#ifndef G_PLATFORM_WIN32

#define compare_utf8_filenames(a, b) strcmp(a, b)
#define compare_sys_filenames(a, b) strcmp(a, b)

#else

static gint
compare_utf8_filenames (const gchar *a,
			const gchar *b)
{
  gchar *a_folded, *b_folded;
  gint retval;

  a_folded = g_utf8_strdown (a, -1);
  b_folded = g_utf8_strdown (b, -1);

  retval = strcmp (a_folded, b_folded);

  g_free (a_folded);
  g_free (b_folded);

  return retval;
}

static gint
compare_sys_filenames (const gchar *a,
		       const gchar *b)
{
  gchar *a_utf8, *b_utf8;
  gint retval;

  a_utf8 = g_filename_to_utf8 (a, -1, NULL, NULL, NULL);
  b_utf8 = g_filename_to_utf8 (b, -1, NULL, NULL, NULL);

  retval = compare_utf8_filenames (a_utf8, b_utf8);

  g_free (a_utf8);
  g_free (b_utf8);

  return retval;
}

#endif

/* Saves errno when something cmpl does fails. */
static gint cmpl_errno;

#ifdef G_WITH_CYGWIN
/*
 * Take the path currently in the file selection
 * entry field and translate as necessary from
 * a Win32 style to Cygwin style path.  For
 * instance translate:
 * x:\somepath\file.jpg
 * to:
 * /cygdrive/x/somepath/file.jpg
 *
 * Replace the path in the selection text field.
 * Return a boolean value concerning whether a
 * translation had to be made.
 */
static int
translate_win32_path (GtkFileSelection *filesel)
{
  int updated = 0;
  const gchar *path;
  gchar newPath[MAX_PATH];

  /*
   * Retrieve the current path
   */
  path = gtk_entry_get_text (GTK_ENTRY (filesel->selection_entry));

  cygwin_conv_to_posix_path (path, newPath);
  updated = (strcmp (path, newPath) != 0);

  if (updated)
    gtk_entry_set_text (GTK_ENTRY (filesel->selection_entry), newPath);
    
  return updated;
}
#endif

G_DEFINE_TYPE (GtkFileSelection, gtk_file_selection, GTK_TYPE_DIALOG)

static void
gtk_file_selection_class_init (GtkFileSelectionClass *class)
{
  GObjectClass *gobject_class;
  GtkObjectClass *object_class;
  GtkWidgetClass *widget_class;

  gobject_class = (GObjectClass*) class;
  object_class = (GtkObjectClass*) class;
  widget_class = (GtkWidgetClass*) class;

  gobject_class->finalize = gtk_file_selection_finalize;
  gobject_class->set_property = gtk_file_selection_set_property;
  gobject_class->get_property = gtk_file_selection_get_property;
   
  g_object_class_install_property (gobject_class,
                                   PROP_FILENAME,
                                   g_param_spec_string ("filename",
                                                        P_("Filename"),
                                                        P_("The currently selected filename"),
                                                        NULL,
                                                        GTK_PARAM_READWRITE));
  g_object_class_install_property (gobject_class,
				   PROP_SHOW_FILEOPS,
				   g_param_spec_boolean ("show-fileops",
							 P_("Show file operations"),
							 P_("Whether buttons for creating/manipulating files should be displayed"),
							 TRUE,
							 GTK_PARAM_READWRITE));
  g_object_class_install_property (gobject_class,
				   PROP_SELECT_MULTIPLE,
				   g_param_spec_boolean ("select-multiple",
							 P_("Select Multiple"),
							 P_("Whether to allow multiple files to be selected"),
							 FALSE,
							 GTK_PARAM_READWRITE));
  object_class->destroy = gtk_file_selection_destroy;
  widget_class->map = gtk_file_selection_map;
}

static void gtk_file_selection_set_property (GObject         *object,
					     guint            prop_id,
					     const GValue    *value,
					     GParamSpec      *pspec)
{
  GtkFileSelection *filesel;

  filesel = GTK_FILE_SELECTION (object);

  switch (prop_id)
    {
    case PROP_FILENAME:
      gtk_file_selection_set_filename (filesel,
                                       g_value_get_string (value));
      break;
    case PROP_SHOW_FILEOPS:
      if (g_value_get_boolean (value))
	 gtk_file_selection_show_fileop_buttons (filesel);
      else
	 gtk_file_selection_hide_fileop_buttons (filesel);
      break;
    case PROP_SELECT_MULTIPLE:
      gtk_file_selection_set_select_multiple (filesel, g_value_get_boolean (value));
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
    }
}

static void gtk_file_selection_get_property (GObject         *object,
					     guint            prop_id,
					     GValue          *value,
					     GParamSpec      *pspec)
{
  GtkFileSelection *filesel;

  filesel = GTK_FILE_SELECTION (object);

  switch (prop_id)
    {
    case PROP_FILENAME:
      g_value_set_string (value,
                          gtk_file_selection_get_filename(filesel));
      break;

    case PROP_SHOW_FILEOPS:
      /* This is a little bit hacky, but doing otherwise would require
       * adding a field to the object.
       */
      g_value_set_boolean (value, (filesel->fileop_c_dir && 
				   filesel->fileop_del_file &&
				   filesel->fileop_ren_file));
      break;
    case PROP_SELECT_MULTIPLE:
      g_value_set_boolean (value, gtk_file_selection_get_select_multiple (filesel));
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
    }
}

static gboolean
grab_default (GtkWidget *widget)
{
  gtk_widget_grab_default (widget);
  return FALSE;
}
     
static void
gtk_file_selection_init (GtkFileSelection *filesel)
{
  GtkWidget *entry_vbox;
  GtkWidget *label;
  GtkWidget *list_hbox, *list_container;
  GtkWidget *pulldown_hbox;
  GtkWidget *scrolled_win;
  GtkWidget *eventbox;
  GtkWidget *spacer;
  GtkDialog *dialog;

  GdkPixbuf *ipixbuf;
  GtkWidget *bbox, *home_button, *desk_button, *docs_button, *xbox;
  GtkWidget *lbox;

  GtkListStore *model;
  GtkTreeViewColumn *column;
  
  gtk_widget_push_composite_child ();

  dialog = GTK_DIALOG (filesel);

  filesel->cmpl_state = cmpl_init_state ();

  /* The dialog-sized vertical box  */
  filesel->main_vbox = dialog->vbox;
  gtk_container_set_border_width (GTK_CONTAINER (filesel), 10);

  /* hbox for pulldown menu */
  pulldown_hbox = gtk_hbox_new (TRUE, 5);
  gtk_container_set_border_width (GTK_CONTAINER (pulldown_hbox), 4);
  gtk_box_pack_start (GTK_BOX (filesel->main_vbox), pulldown_hbox, FALSE, FALSE, 0);
  gtk_widget_show (pulldown_hbox);
  
  /* Pulldown menu */
  filesel->history_pulldown = gtk_option_menu_new ();
  gtk_widget_show (filesel->history_pulldown);
  gtk_box_pack_start (GTK_BOX (pulldown_hbox), filesel->history_pulldown, 
		      FALSE, FALSE, 0);
    
  /*  The horizontal box containing the directory and file listboxes  */

  xbox = gtk_hbox_new (FALSE, 0);
  gtk_box_pack_start (GTK_BOX (filesel->main_vbox), xbox, TRUE, TRUE, 0);
  gtk_widget_show (xbox);

  bbox = gtk_vbox_new (FALSE, 0);
  gtk_box_pack_start (GTK_BOX (xbox), bbox, FALSE, FALSE, 5);
  gtk_widget_show (bbox);

  lbox = gtk_vbox_new (FALSE, 0);
  gtk_box_pack_start (GTK_BOX (xbox), lbox, TRUE, TRUE, 5);
  gtk_widget_show (lbox);

  spacer = gtk_hbox_new (FALSE, 0);
  gtk_widget_set_size_request (spacer, -1, 5);
  gtk_box_pack_start (GTK_BOX (lbox), spacer, FALSE, FALSE, 0);
  gtk_widget_show (spacer);
  
  list_hbox = gtk_hbox_new (FALSE, 5);
  gtk_box_pack_start (GTK_BOX (lbox), list_hbox, TRUE, TRUE, 0);
  gtk_widget_show (list_hbox);

  if (WANT_HPANED)
    list_container = g_object_new (GTK_TYPE_HPANED,
				   "visible", TRUE,
				   "parent", list_hbox,
				   "border_width", 0,
				   NULL);
  else
    list_container = list_hbox;

  spacer = gtk_hbox_new (FALSE, 0);
  gtk_widget_set_size_request (spacer, -1, 5);
  gtk_box_pack_start (GTK_BOX (lbox), spacer, FALSE, FALSE, 0);  
  gtk_widget_show (spacer);
  

  /* The Pretty Icons */
  
  home_button = gtk_button_new ();
  gtk_container_set_border_width (GTK_CONTAINER (home_button), 4);
  gtk_box_pack_start (GTK_BOX (bbox), home_button, FALSE, FALSE, 0);
  gtk_widget_show (home_button);

  g_signal_connect (G_OBJECT (home_button), "clicked",
		    G_CALLBACK (home_clicked), filesel);

  xbox = gtk_vbox_new (FALSE, 0);
  gtk_container_add (GTK_CONTAINER (home_button), xbox);
  gtk_widget_show (xbox);

  ipixbuf = gdk_pixbuf_new_from_inline (-1, stock_home_48, FALSE, NULL);
  label = gtk_image_new_from_pixbuf (ipixbuf);
  gtk_box_pack_start (GTK_BOX (xbox), label, FALSE, FALSE, 0);
  gtk_widget_show (label);

  label = gtk_label_new_with_mnemonic ("_Home");
  gtk_label_set_mnemonic_widget (GTK_LABEL (label), home_button);
  gtk_box_pack_end (GTK_BOX (xbox), label, FALSE, FALSE, 0);
  gtk_widget_show (label);

  desk_button = gtk_button_new ();
  gtk_container_set_border_width (GTK_CONTAINER (desk_button), 4);
  gtk_box_pack_start (GTK_BOX (bbox), desk_button, FALSE, FALSE, 0);
  gtk_widget_show (desk_button);

  g_signal_connect (G_OBJECT (desk_button), "clicked",
		    G_CALLBACK (desktop_clicked), filesel);

  xbox = gtk_vbox_new (FALSE, 0);
  gtk_container_add (GTK_CONTAINER (desk_button), xbox);
  gtk_widget_show (xbox);

  ipixbuf = gdk_pixbuf_new_from_inline (-1, stock_desktop_48, FALSE, NULL);
  label = gtk_image_new_from_pixbuf (ipixbuf);
  gtk_box_pack_start (GTK_BOX (xbox), label, FALSE, FALSE, 0);
  gtk_widget_show (label);

  label = gtk_label_new_with_mnemonic ("D_esktop");
  gtk_label_set_mnemonic_widget (GTK_LABEL (label), desk_button);
  gtk_box_pack_end (GTK_BOX (xbox), label, FALSE, FALSE, 0);
  gtk_widget_show (label);

  docs_button = gtk_button_new ();
  gtk_container_set_border_width (GTK_CONTAINER (docs_button), 4);
  gtk_box_pack_start (GTK_BOX (bbox), docs_button, FALSE, FALSE, 0);
  gtk_widget_show (docs_button);

  g_signal_connect (G_OBJECT (docs_button), "clicked",
		    G_CALLBACK (documents_clicked), filesel);

  xbox = gtk_vbox_new (FALSE, 0);
  gtk_container_add (GTK_CONTAINER (docs_button), xbox);
  gtk_widget_show (xbox);

  ipixbuf = gdk_pixbuf_new_from_inline (-1, stock_documents_48, FALSE, NULL);
  label = gtk_image_new_from_pixbuf (ipixbuf);
  gtk_box_pack_start (GTK_BOX (xbox), label, FALSE, FALSE, 0);
  gtk_widget_show (label);

  label = gtk_label_new_with_mnemonic ("Docu_ments");
  gtk_label_set_mnemonic_widget (GTK_LABEL (label), docs_button);
  gtk_box_pack_end (GTK_BOX (xbox), label, FALSE, FALSE, 0);
  gtk_widget_show (label);

  /* The directories list */

  model = gtk_list_store_new (1, G_TYPE_STRING);
  filesel->dir_list = gtk_tree_view_new_with_model (GTK_TREE_MODEL (model));
  g_object_unref (model);

  column = gtk_tree_view_column_new_with_attributes (_("Folders"),
						     gtk_cell_renderer_text_new (),
						     "text", DIR_COLUMN,
						     NULL);
  label = gtk_label_new_with_mnemonic (_("Fol_ders"));
  gtk_label_set_mnemonic_widget (GTK_LABEL (label), filesel->dir_list);
  gtk_widget_show (label);
  gtk_tree_view_column_set_widget (column, label);
  gtk_tree_view_column_set_sizing (column, GTK_TREE_VIEW_COLUMN_AUTOSIZE);
  gtk_tree_view_append_column (GTK_TREE_VIEW (filesel->dir_list), column);

  gtk_widget_set_size_request (filesel->dir_list,
			       DIR_LIST_WIDTH, DIR_LIST_HEIGHT);
  g_signal_connect (filesel->dir_list, "row-activated",
		    G_CALLBACK (gtk_file_selection_dir_activate), filesel);

  /*  gtk_clist_column_titles_passive (GTK_CLIST (filesel->dir_list)); */

  scrolled_win = gtk_scrolled_window_new (NULL, NULL);
  gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (scrolled_win), GTK_SHADOW_IN);  
  gtk_container_add (GTK_CONTAINER (scrolled_win), filesel->dir_list);
  gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_win),
				  GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS);
  gtk_container_set_border_width (GTK_CONTAINER (scrolled_win), 0);
  if (GTK_IS_PANED (list_container))
    gtk_paned_pack1 (GTK_PANED (list_container), scrolled_win, TRUE, TRUE);
  else
    gtk_container_add (GTK_CONTAINER (list_container), scrolled_win);
  gtk_widget_show (filesel->dir_list);
  gtk_widget_show (scrolled_win);

  /* The files list */
  model = gtk_list_store_new (1, G_TYPE_STRING);
  filesel->file_list = gtk_tree_view_new_with_model (GTK_TREE_MODEL (model));
  g_object_unref (model);

  column = gtk_tree_view_column_new_with_attributes (_("Files"),
						     gtk_cell_renderer_text_new (),
						     "text", FILE_COLUMN,
						     NULL);
  label = gtk_label_new_with_mnemonic (_("_Files"));
  gtk_label_set_mnemonic_widget (GTK_LABEL (label), filesel->file_list);
  gtk_widget_show (label);
  gtk_tree_view_column_set_widget (column, label);
  gtk_tree_view_column_set_sizing (column, GTK_TREE_VIEW_COLUMN_AUTOSIZE);
  gtk_tree_view_append_column (GTK_TREE_VIEW (filesel->file_list), column);

  gtk_widget_set_size_request (filesel->file_list,
			       FILE_LIST_WIDTH, FILE_LIST_HEIGHT);
  g_signal_connect (filesel->file_list, "row-activated",
		    G_CALLBACK (gtk_file_selection_file_activate), filesel);
  g_signal_connect (gtk_tree_view_get_selection (GTK_TREE_VIEW (filesel->file_list)), "changed",
		    G_CALLBACK (gtk_file_selection_file_changed), filesel);

  /* gtk_clist_column_titles_passive (GTK_CLIST (filesel->file_list)); */

  scrolled_win = gtk_scrolled_window_new (NULL, NULL);
  gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (scrolled_win), GTK_SHADOW_IN);
  gtk_container_add (GTK_CONTAINER (scrolled_win), filesel->file_list);
  gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_win),
				  GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS);
  gtk_container_set_border_width (GTK_CONTAINER (scrolled_win), 0);
  gtk_container_add (GTK_CONTAINER (list_container), scrolled_win);
  gtk_widget_show (filesel->file_list);
  gtk_widget_show (scrolled_win);

  /* The horizontal box containing create, rename etc. buttons */
  filesel->button_area = gtk_hbox_new (FALSE, 0);
  gtk_box_set_spacing (GTK_BOX (filesel->button_area), 0);
  gtk_box_pack_start (GTK_BOX (lbox), filesel->button_area, 
		      FALSE, FALSE, 0);
  gtk_widget_show (filesel->button_area);
  
  gtk_file_selection_show_fileop_buttons (filesel);

  /* action area for packing buttons into. */
  filesel->action_area = gtk_hbox_new (TRUE, 0);
  gtk_box_pack_start (GTK_BOX (filesel->main_vbox), filesel->action_area, 
		      FALSE, FALSE, 0);
  gtk_widget_show (filesel->action_area);
  
  /*  The OK/Cancel button area */

  /*  The Cancel button  */
  filesel->cancel_button = gtk_dialog_add_button (dialog,
                                                  GTK_STOCK_CANCEL,
                                                  GTK_RESPONSE_CANCEL);
  /*  The OK button  */
  filesel->ok_button = gtk_dialog_add_button (dialog,
                                              GTK_STOCK_OK,
                                              GTK_RESPONSE_OK);

  gtk_dialog_set_alternative_button_order (dialog,
					   GTK_RESPONSE_OK,
					   GTK_RESPONSE_CANCEL,
					   -1);

  gtk_widget_grab_default (filesel->ok_button);

  /*  The selection entry widget  */
  entry_vbox = gtk_vbox_new (FALSE, 2);
  gtk_box_pack_end (GTK_BOX (filesel->main_vbox), entry_vbox, FALSE, FALSE, 2);
  gtk_widget_show (entry_vbox);
  
  eventbox = gtk_event_box_new ();
  filesel->selection_text = label = gtk_label_new ("");
  gtk_misc_set_alignment (GTK_MISC (label), 0.0, 0.5);
  gtk_container_add (GTK_CONTAINER (eventbox), label);
  gtk_box_pack_start (GTK_BOX (entry_vbox), eventbox, FALSE, FALSE, 0);
  gtk_widget_show (label);
  gtk_widget_show (eventbox);

  filesel->selection_entry = gtk_entry_new ();
  g_signal_connect (filesel->selection_entry, "key-press-event",
		    G_CALLBACK (gtk_file_selection_key_press), filesel);
  g_signal_connect (filesel->selection_entry, "insert-text",
		    G_CALLBACK (gtk_file_selection_insert_text), NULL);
  g_signal_connect_swapped (filesel->selection_entry, "changed",
			    G_CALLBACK (gtk_file_selection_update_fileops), filesel);
  g_signal_connect_swapped (filesel->selection_entry, "focus-in-event",
			    G_CALLBACK (grab_default),
			    filesel->ok_button);
  g_signal_connect_swapped (filesel->selection_entry, "activate",
			    G_CALLBACK (gtk_button_clicked),
			    filesel->ok_button);
  
  gtk_box_pack_start (GTK_BOX (entry_vbox), filesel->selection_entry, TRUE, TRUE, 0);
  gtk_widget_show (filesel->selection_entry);

  gtk_label_set_mnemonic_widget (GTK_LABEL (filesel->selection_text),
				 filesel->selection_entry);

  if (!cmpl_state_okay (filesel->cmpl_state))
    {
      gchar err_buf[256];

      g_snprintf (err_buf, sizeof (err_buf), _("Folder unreadable: %s"), cmpl_strerror (cmpl_errno));

      gtk_label_set_text (GTK_LABEL (filesel->selection_text), err_buf);
    }
  else
    {
      gtk_file_selection_populate (filesel, "", FALSE, TRUE);
    }

  gtk_widget_grab_focus (filesel->selection_entry);

  gtk_widget_pop_composite_child ();
}

static void
dnd_really_drop  (GtkWidget *dialog, gint response_id, GtkFileSelection *fs)
{
  gchar *filename;
  
  if (response_id == GTK_RESPONSE_YES)
    {
      filename = g_object_get_data (G_OBJECT (dialog), "gtk-fs-dnd-filename");

      gtk_file_selection_set_filename (fs, filename);
    }
  
  gtk_widget_destroy (dialog);
}

static void
filenames_dropped (GtkWidget        *widget,
		   GdkDragContext   *context,
		   gint              x,
		   gint              y,
		   GtkSelectionData *selection_data,
		   guint             info,
		   guint             time)
{
  char **uris = NULL;
  char *filename = NULL;
  char *hostname;
  const char *this_hostname;
  GError *error = NULL;

  uris = gtk_selection_data_get_uris (selection_data);
  if (!uris || !uris[0])
    {
      g_strfreev (uris);
      return;
    }

  filename = g_filename_from_uri (uris[0], &hostname, &error);
  g_strfreev (uris);
  
  if (!filename)
    {
      g_warning ("Error getting dropped filename: %s\n",
		 error->message);
      g_error_free (error);
      return;
    }

  this_hostname = g_get_host_name ();
  
  if ((hostname == NULL) ||
      (strcmp (hostname, this_hostname) == 0) ||
      (strcmp (hostname, "localhost") == 0))
    gtk_file_selection_set_filename (GTK_FILE_SELECTION (widget),
				     filename);
  else
    {
      GtkWidget *dialog;
      gchar *filename_utf8;

      /* Conversion back to UTF-8 should always succeed for the result
       * of g_filename_from_uri()
       */
      filename_utf8 = g_filename_to_utf8 (filename, -1, NULL, NULL, NULL);
      g_assert (filename_utf8);
      
      dialog = gtk_message_dialog_new (GTK_WINDOW (widget),
				       GTK_DIALOG_DESTROY_WITH_PARENT,
				       GTK_MESSAGE_QUESTION,
				       GTK_BUTTONS_YES_NO,
				       _("The file \"%s\" resides on another machine (called %s) and may not be available to this program.\n"
					 "Are you sure that you want to select it?"), filename_utf8, hostname);
      g_free (filename_utf8);

      g_object_set_data_full (G_OBJECT (dialog), I_("gtk-fs-dnd-filename"), g_strdup (filename), g_free);
      
      g_signal_connect_data (dialog, "response",
			     (GCallback) dnd_really_drop, 
			     widget, NULL, 0);
      
      gtk_widget_show (dialog);
    }

  g_free (hostname);
  g_free (filename);
}

static void
filenames_drag_get (GtkWidget        *widget,
		    GdkDragContext   *context,
		    GtkSelectionData *selection_data,
		    guint             info,
		    guint             time,
		    GtkFileSelection *filesel)
{
  const gchar *file;
  gchar *filename_utf8;

  file = gtk_file_selection_get_filename (filesel);
  if (!file)
    return;

  if (gtk_targets_include_uri (&selection_data->target, 1))
    {
      gchar *file_uri;
      const char *hostname;
      GError *error;
      char *uris[2];

      hostname = g_get_host_name ();

      error = NULL;
      file_uri = g_filename_to_uri (file, hostname, &error);
      if (!file_uri)
        {
          g_warning ("Error getting filename: %s\n",
                      error->message);
          g_error_free (error);
          return;
        }
	  
      uris[0] = file_uri;
      uris[1] = NULL;
      gtk_selection_data_set_uris (selection_data, uris);
      g_free (file_uri);

      return;
    }
	  
  filename_utf8 = g_filename_to_utf8 (file, -1, NULL, NULL, NULL);
  if (!filename_utf8)
    return;

  gtk_selection_data_set_text (selection_data, filename_utf8, -1);
  g_free (filename_utf8);
}

static void
file_selection_setup_dnd (GtkFileSelection *filesel)
{
  GtkWidget *eventbox;

  gtk_drag_dest_set (GTK_WIDGET (filesel),
		     GTK_DEST_DEFAULT_ALL,
		     NULL, 0,
		     GDK_ACTION_COPY);
  gtk_drag_dest_add_uri_targets (GTK_WIDGET (filesel));

  g_signal_connect (filesel, "drag-data-received",
		    G_CALLBACK (filenames_dropped), NULL);

  eventbox = gtk_widget_get_parent (filesel->selection_text);
  gtk_drag_source_set (eventbox,
		       GDK_BUTTON1_MASK,
		       NULL, 0,
		       GDK_ACTION_COPY);
  gtk_drag_source_add_uri_targets (eventbox);
  gtk_drag_source_add_text_targets (eventbox);

  g_signal_connect (eventbox, "drag-data-get",
		    G_CALLBACK (filenames_drag_get), filesel);
}

GtkWidget*
gtk_file_selection_new (const gchar *title)
{
  GtkFileSelection *filesel;

  filesel = g_object_new (GTK_TYPE_FILE_SELECTION, NULL);
  gtk_window_set_title (GTK_WINDOW (filesel), title);
  gtk_dialog_set_has_separator (GTK_DIALOG (filesel), FALSE);

  file_selection_setup_dnd (filesel);
  
  return GTK_WIDGET (filesel);
}

void
gtk_file_selection_show_fileop_buttons (GtkFileSelection *filesel)
{
  GtkWidget *label;
  GtkWidget *bbox;
  
  g_return_if_fail (GTK_IS_FILE_SELECTION (filesel));
    
  /* delete, create directory, and rename */
  if (!filesel->fileop_c_dir) 
    {
      filesel->fileop_c_dir = gtk_button_new ();
      gtk_container_set_border_width (GTK_CONTAINER (filesel->fileop_c_dir), 4);
      
      bbox = gtk_hbox_new (FALSE, 2);
      gtk_container_add (GTK_CONTAINER (filesel->fileop_c_dir), bbox);
      
      label = gtk_image_new_from_stock (GTK_STOCK_OPEN, GTK_ICON_SIZE_BUTTON);
      gtk_box_pack_start (GTK_BOX (bbox), label, FALSE, FALSE, 0);
      gtk_widget_show (label);
      
      label = gtk_label_new_with_mnemonic (_("_New Folder"));
      gtk_label_set_mnemonic_widget (GTK_LABEL (label), filesel->fileop_c_dir);
      gtk_box_pack_start (GTK_BOX (bbox), label, FALSE, FALSE, 0);
      gtk_widget_show (label);
      
      gtk_widget_show (bbox);
      
      g_signal_connect (filesel->fileop_c_dir, "clicked",
			G_CALLBACK (gtk_file_selection_create_dir), 
			(gpointer) filesel);
      gtk_box_pack_start (GTK_BOX (filesel->button_area), 
			  filesel->fileop_c_dir, FALSE, FALSE, 0);
      gtk_widget_show (filesel->fileop_c_dir);
    }
  
  if (!filesel->fileop_del_file) 
    {
      filesel->fileop_del_file = gtk_button_new ();
      gtk_container_set_border_width (GTK_CONTAINER (filesel->fileop_del_file), 4);
      
      bbox = gtk_hbox_new (FALSE, 2);
      gtk_container_add (GTK_CONTAINER (filesel->fileop_del_file), bbox);
      
      label = gtk_image_new_from_stock (GTK_STOCK_DELETE,
 					GTK_ICON_SIZE_BUTTON);
      gtk_box_pack_start (GTK_BOX (bbox), label, FALSE, FALSE, 0);
      gtk_widget_show (label);
      
      label = gtk_label_new (_("De_lete File"));
      gtk_label_set_use_underline (GTK_LABEL (label), TRUE);
      gtk_label_set_mnemonic_widget (GTK_LABEL (label), filesel->fileop_del_file);
      gtk_box_pack_start (GTK_BOX (bbox), label, FALSE, FALSE, 0);
      gtk_widget_show (label);
      
      gtk_widget_show (bbox);
      
      g_signal_connect (filesel->fileop_del_file, "clicked",
			G_CALLBACK (gtk_file_selection_delete_file),
			(gpointer) filesel);
      gtk_box_pack_end (GTK_BOX (filesel->button_area), 
			filesel->fileop_del_file, FALSE, FALSE, 0);
      gtk_widget_show (filesel->fileop_del_file);
    }
  
  if (!filesel->fileop_ren_file)
    {
      filesel->fileop_ren_file = gtk_button_new ();
      gtk_container_set_border_width (GTK_CONTAINER (filesel->fileop_ren_file), 4);
      
      bbox = gtk_hbox_new (FALSE, 2);
      gtk_container_add (GTK_CONTAINER (filesel->fileop_ren_file), bbox);
      
      label = gtk_image_new_from_stock (GTK_STOCK_SAVE_AS,
 					GTK_ICON_SIZE_BUTTON);
      gtk_box_pack_start (GTK_BOX (bbox), label, FALSE, FALSE, 0);
      gtk_widget_show (label);
      
      label = gtk_label_new (_("_Rename File"));
      gtk_label_set_use_underline (GTK_LABEL (label), TRUE);
      gtk_label_set_mnemonic_widget (GTK_LABEL (label), filesel->fileop_ren_file);
      gtk_box_pack_start (GTK_BOX (bbox), label, FALSE, FALSE, 0);
      gtk_widget_show (label);
      
      gtk_widget_show (bbox);
      
      g_signal_connect (filesel->fileop_ren_file, "clicked",
			G_CALLBACK (gtk_file_selection_rename_file),
			(gpointer) filesel);
      gtk_box_pack_end (GTK_BOX (filesel->button_area), 
			filesel->fileop_ren_file, FALSE, FALSE, 0);
      gtk_widget_show (filesel->fileop_ren_file);
    }
  
  gtk_file_selection_update_fileops (filesel);
  
  g_object_notify (G_OBJECT (filesel), "show-fileops");
}

void       
gtk_file_selection_hide_fileop_buttons (GtkFileSelection *filesel)
{
  g_return_if_fail (GTK_IS_FILE_SELECTION (filesel));
    
  if (filesel->fileop_ren_file)
    {
      gtk_widget_destroy (filesel->fileop_ren_file);
      filesel->fileop_ren_file = NULL;
    }

  if (filesel->fileop_del_file)
    {
      gtk_widget_destroy (filesel->fileop_del_file);
      filesel->fileop_del_file = NULL;
    }

  if (filesel->fileop_c_dir)
    {
      gtk_widget_destroy (filesel->fileop_c_dir);
      filesel->fileop_c_dir = NULL;
    }
  g_object_notify (G_OBJECT (filesel), "show-fileops");
}



/**
 * gtk_file_selection_set_filename:
 * @filesel: a #GtkFileSelection.
 * @filename:  a string to set as the default file name.
 * 
 * Sets a default path for the file requestor. If @filename includes a
 * directory path, then the requestor will open with that path as its
 * current working directory.
 *
 * This has the consequence that in order to open the requestor with a 
 * working directory and an empty filename, @filename must have a trailing
 * directory separator.
 *
 * The encoding of @filename is preferred GLib file name encoding, which
 * may not be UTF-8. See g_filename_from_utf8().
 **/
void
gtk_file_selection_set_filename (GtkFileSelection *filesel,
				 const gchar      *filename)
{
  gchar *buf;
  const char *name, *last_slash;
  char *filename_utf8;

  g_return_if_fail (GTK_IS_FILE_SELECTION (filesel));
  g_return_if_fail (filename != NULL);

  filename_utf8 = g_filename_to_utf8 (filename, -1, NULL, NULL, NULL);
  g_return_if_fail (filename_utf8 != NULL);

  last_slash = strrchr (filename_utf8, G_DIR_SEPARATOR);

  if (!last_slash)
    {
      buf = g_strdup ("");
      name = filename_utf8;
    }
  else
    {
      buf = g_strdup (filename_utf8);
      buf[last_slash - filename_utf8 + 1] = 0;
      name = last_slash + 1;
    }

  gtk_file_selection_populate (filesel, buf, FALSE, TRUE);

  if (filesel->selection_entry)
    gtk_entry_set_text (GTK_ENTRY (filesel->selection_entry), name);
  g_free (buf);
  g_object_notify (G_OBJECT (filesel), "filename");

  g_free (filename_utf8);
}

/**
 * gtk_file_selection_get_filename:
 * @filesel: a #GtkFileSelection
 * 
 * This function returns the selected filename in the GLib file name
 * encoding. To convert to UTF-8, call g_filename_to_utf8(). The
 * returned string points to a statically allocated buffer and should
 * be copied if you plan to keep it around.
 *
 * If no file is selected then the selected directory path is returned.
 * 
 * Return value: currently-selected filename in the on-disk encoding.
 **/
const gchar*
gtk_file_selection_get_filename (GtkFileSelection *filesel)
{
  static const gchar nothing[2] = "";
  static GString *something;
  char *sys_filename;
  const char *text;

  g_return_val_if_fail (GTK_IS_FILE_SELECTION (filesel), nothing);

#ifdef G_WITH_CYGWIN
  translate_win32_path (filesel);
#endif
  text = gtk_entry_get_text (GTK_ENTRY (filesel->selection_entry));
  if (text)
    {
      gchar *fullname = cmpl_completion_fullname (text, filesel->cmpl_state);
      sys_filename = g_filename_from_utf8 (fullname, -1, NULL, NULL, NULL);
      g_free (fullname);
      if (!sys_filename)
	return nothing;
      if (!something)
        something = g_string_new (sys_filename);
      else
        g_string_assign (something, sys_filename);
      g_free (sys_filename);

      return something->str;
    }

  return nothing;
}

void
gtk_file_selection_complete (GtkFileSelection *filesel,
			     const gchar      *pattern)
{
  g_return_if_fail (GTK_IS_FILE_SELECTION (filesel));
  g_return_if_fail (pattern != NULL);

  if (filesel->selection_entry)
    gtk_entry_set_text (GTK_ENTRY (filesel->selection_entry), pattern);
  gtk_file_selection_populate (filesel, (gchar*) pattern, TRUE, TRUE);
}

static void
gtk_file_selection_destroy (GtkObject *object)
{
  GtkFileSelection *filesel;
  GList *list;
  HistoryCallbackArg *callback_arg;
  
  g_return_if_fail (GTK_IS_FILE_SELECTION (object));
  
  filesel = GTK_FILE_SELECTION (object);
  
  if (filesel->fileop_dialog)
    {
      gtk_widget_destroy (filesel->fileop_dialog);
      filesel->fileop_dialog = NULL;
    }
  
  if (filesel->history_list)
    {
      list = filesel->history_list;
      while (list)
	{
	  callback_arg = list->data;
	  g_free (callback_arg->directory);
	  g_free (callback_arg);
	  list = list->next;
	}
      g_list_free (filesel->history_list);
      filesel->history_list = NULL;
    }

  if (filesel->cmpl_state)
    {
      cmpl_free_state (filesel->cmpl_state);
      filesel->cmpl_state = NULL;
    }
 
  if (filesel->selected_names)
    {
      free_selected_names (filesel->selected_names);
      filesel->selected_names = NULL;
    } 

  if (filesel->last_selected)
    {
      g_free (filesel->last_selected);
      filesel->last_selected = NULL;
    }

  GTK_OBJECT_CLASS (gtk_file_selection_parent_class)->destroy (object);
}

static void
gtk_file_selection_map (GtkWidget *widget)
{
  GtkFileSelection *filesel = GTK_FILE_SELECTION (widget);

  /* Refresh the contents */
  gtk_file_selection_populate (filesel, "", FALSE, FALSE);
  
  GTK_WIDGET_CLASS (gtk_file_selection_parent_class)->map (widget);
}

static void
gtk_file_selection_finalize (GObject *object)
{
  GtkFileSelection *filesel = GTK_FILE_SELECTION (object);

  g_free (filesel->fileop_file);

  G_OBJECT_CLASS (gtk_file_selection_parent_class)->finalize (object);
}

/* Begin file operations callbacks */

static void
gtk_file_selection_fileop_error (GtkFileSelection *fs,
				 gchar            *error_message)
{
  GtkWidget *dialog;
    
  g_return_if_fail (error_message != NULL);

  /* main dialog */
  dialog = gtk_message_dialog_new (GTK_WINDOW (fs),
				   GTK_DIALOG_DESTROY_WITH_PARENT,
				   GTK_MESSAGE_ERROR,
				   GTK_BUTTONS_OK,
				   "%s", error_message);

  /* yes, we free it */
  g_free (error_message);

  gtk_window_set_modal (GTK_WINDOW (dialog), TRUE);
 
  g_signal_connect_swapped (dialog, "response",
			    G_CALLBACK (gtk_widget_destroy),
			    dialog);

  gtk_widget_show (dialog);
}

static void
gtk_file_selection_fileop_destroy (GtkWidget *widget,
				   gpointer   data)
{
  GtkFileSelection *fs = data;

  g_return_if_fail (GTK_IS_FILE_SELECTION (fs));
  
  fs->fileop_dialog = NULL;
}

static gboolean
entry_is_empty (GtkEntry *entry)
{
  const gchar *text = gtk_entry_get_text (entry);
  
  return *text == '\0';
}

static void
gtk_file_selection_fileop_entry_changed (GtkEntry   *entry,
					 GtkWidget  *button)
{
  gtk_widget_set_sensitive (button, !entry_is_empty (entry));
}

static void
gtk_file_selection_create_dir_confirmed (GtkWidget *widget,
					 gpointer   data)
{
  GtkFileSelection *fs = data;
  const gchar *dirname;
  gchar *path;
  gchar *full_path;
  gchar *sys_full_path;
  gchar *buf;
  GError *error = NULL;
  CompletionState *cmpl_state;
  
  g_return_if_fail (GTK_IS_FILE_SELECTION (fs));

  dirname = gtk_entry_get_text (GTK_ENTRY (fs->fileop_entry));
  cmpl_state = (CompletionState*) fs->cmpl_state;
  path = cmpl_reference_position (cmpl_state);
  
  full_path = g_strconcat (path, G_DIR_SEPARATOR_S, dirname, NULL);
  sys_full_path = g_filename_from_utf8 (full_path, -1, NULL, NULL, &error);
  if (error)
    {
      if (g_error_matches (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE))
	buf = g_strdup_printf (_("The folder name \"%s\" contains symbols that are not allowed in filenames"), dirname);
      else
	buf = g_strdup_printf (_("Error creating folder '%s': %s"), 
			       dirname, error->message);
      gtk_file_selection_fileop_error (fs, buf);
      g_error_free (error);
      goto out;
    }

  if (g_mkdir (sys_full_path, 0777) < 0)
    {
      int errsv = errno;

      buf = g_strdup_printf (_("Error creating folder '%s': %s"), 
			     dirname, g_strerror (errsv));
      gtk_file_selection_fileop_error (fs, buf);
    }

 out:
  g_free (full_path);
  g_free (sys_full_path);
  
  gtk_widget_destroy (fs->fileop_dialog);
  gtk_file_selection_populate (fs, "", FALSE, FALSE);
}
  
static void
gtk_file_selection_create_dir (GtkWidget *widget,
			       gpointer   data)
{
  GtkFileSelection *fs = data;
  GtkWidget *label;
  GtkWidget *dialog;
  GtkWidget *vbox;
  GtkWidget *button;

  g_return_if_fail (GTK_IS_FILE_SELECTION (fs));

  if (fs->fileop_dialog)
    return;
  
  /* main dialog */
  dialog = gtk_dialog_new ();
  fs->fileop_dialog = dialog;
  g_signal_connect (dialog, "destroy",
		    G_CALLBACK (gtk_file_selection_fileop_destroy),
		    fs);
  gtk_window_set_title (GTK_WINDOW (dialog), _("New Folder"));
  gtk_window_set_position (GTK_WINDOW (dialog), GTK_WIN_POS_MOUSE);
  gtk_window_set_transient_for (GTK_WINDOW (dialog), GTK_WINDOW (fs));

  /* If file dialog is grabbed, grab option dialog */
  /* When option dialog is closed, file dialog will be grabbed again */
  if (GTK_WINDOW (fs)->modal)
      gtk_window_set_modal (GTK_WINDOW (dialog), TRUE);

  vbox = gtk_vbox_new (FALSE, 0);
  gtk_container_set_border_width (GTK_CONTAINER (vbox), 8);
  gtk_box_pack_start (GTK_BOX (GTK_DIALOG (dialog)->vbox), vbox,
		     FALSE, FALSE, 0);
  gtk_widget_show( vbox);
  
  label = gtk_label_new_with_mnemonic (_("_Folder name:"));
  gtk_misc_set_alignment(GTK_MISC (label), 0.0, 0.0);
  gtk_box_pack_start (GTK_BOX (vbox), label, FALSE, FALSE, 5);
  gtk_widget_show (label);

  /*  The directory entry widget  */
  fs->fileop_entry = gtk_entry_new ();
  gtk_label_set_mnemonic_widget (GTK_LABEL (label), fs->fileop_entry);
  gtk_box_pack_start (GTK_BOX (vbox), fs->fileop_entry, 
		      TRUE, TRUE, 5);
  gtk_widget_set_can_default (fs->fileop_entry, TRUE);
  gtk_entry_set_activates_default (GTK_ENTRY (fs->fileop_entry), TRUE); 
  gtk_widget_show (fs->fileop_entry);
  
  /* buttons */
  button = gtk_dialog_add_button (GTK_DIALOG (dialog), 
				  GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL);
  g_signal_connect_swapped (button, "clicked",
			    G_CALLBACK (gtk_widget_destroy),
			    dialog);

  gtk_widget_grab_focus (fs->fileop_entry);

  button = gtk_dialog_add_button (GTK_DIALOG (dialog), 
				  _("C_reate"), GTK_RESPONSE_OK);
  gtk_widget_set_sensitive (button, FALSE);
  g_signal_connect (button, "clicked",
		    G_CALLBACK (gtk_file_selection_create_dir_confirmed),
		    fs);
  g_signal_connect (fs->fileop_entry, "changed",
                    G_CALLBACK (gtk_file_selection_fileop_entry_changed),
		    button);

  gtk_widget_grab_default (button);
  
  gtk_widget_show (dialog);
}

static void
gtk_file_selection_delete_file_response (GtkDialog *dialog, 
                                         gint       response_id,
                                         gpointer   data)
{
  GtkFileSelection *fs = data;
  CompletionState *cmpl_state;
  gchar *path;
  gchar *full_path;
  gchar *sys_full_path;
  GError *error = NULL;
  gchar *buf;
  
  g_return_if_fail (GTK_IS_FILE_SELECTION (fs));

  if (response_id != GTK_RESPONSE_OK)
    {
      gtk_widget_destroy (GTK_WIDGET (dialog));
      return;
    }

  cmpl_state = (CompletionState*) fs->cmpl_state;
  path = cmpl_reference_position (cmpl_state);
  
  full_path = g_strconcat (path, G_DIR_SEPARATOR_S, fs->fileop_file, NULL);
  sys_full_path = g_filename_from_utf8 (full_path, -1, NULL, NULL, &error);
  if (error)
    {
      if (g_error_matches (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE))
	buf = g_strdup_printf (_("The filename \"%s\" contains symbols that are not allowed in filenames"),
			       fs->fileop_file);
      else
	buf = g_strdup_printf (_("Error deleting file '%s': %s"),
			       fs->fileop_file, error->message);
      
      gtk_file_selection_fileop_error (fs, buf);
      g_error_free (error);
      goto out;
    }

  if (g_unlink (sys_full_path) < 0) 
    {
      int errsv = errno;

      buf = g_strdup_printf (_("Error deleting file '%s': %s"),
			     fs->fileop_file, g_strerror (errsv));
      gtk_file_selection_fileop_error (fs, buf);
    }
  
 out:
  g_free (full_path);
  g_free (sys_full_path);
  
  gtk_widget_destroy (fs->fileop_dialog);
  gtk_file_selection_populate (fs, "", FALSE, TRUE);
}

static void
gtk_file_selection_delete_file (GtkWidget *widget,
				gpointer   data)
{
  GtkFileSelection *fs = data;
  GtkWidget *dialog;
  const gchar *filename;
  
  g_return_if_fail (GTK_IS_FILE_SELECTION (fs));

  if (fs->fileop_dialog)
    return;

#ifdef G_WITH_CYGWIN
  translate_win32_path (fs);
#endif

  filename = gtk_entry_get_text (GTK_ENTRY (fs->selection_entry));
  if (strlen (filename) < 1)
    return;

  g_free (fs->fileop_file);
  fs->fileop_file = g_strdup (filename);
  
  /* main dialog */
  fs->fileop_dialog = dialog = 
    gtk_message_dialog_new (GTK_WINDOW (fs),
                            GTK_WINDOW (fs)->modal ? GTK_DIALOG_MODAL : 0,
                            GTK_MESSAGE_QUESTION,
                            GTK_BUTTONS_NONE,
                            _("Really delete file \"%s\"?"), filename);

  g_signal_connect (dialog, "destroy",
		    G_CALLBACK (gtk_file_selection_fileop_destroy),
		    fs);
  gtk_window_set_title (GTK_WINDOW (dialog), _("Delete File"));
  gtk_window_set_position (GTK_WINDOW (dialog), GTK_WIN_POS_MOUSE);
  
  /* buttons */
  gtk_dialog_add_buttons (GTK_DIALOG (dialog),
                          GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
                          GTK_STOCK_DELETE, GTK_RESPONSE_OK,
                          NULL);

  gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_CANCEL);

  g_signal_connect (dialog, "response",
                    G_CALLBACK (gtk_file_selection_delete_file_response),
                    fs);
  
  gtk_widget_show (dialog);
}

static void
gtk_file_selection_rename_file_confirmed (GtkWidget *widget,
					  gpointer   data)
{
  GtkFileSelection *fs = data;
  gchar *buf;
  const gchar *file;
  gchar *path;
  gchar *new_filename;
  gchar *old_filename;
  gchar *sys_new_filename;
  gchar *sys_old_filename;
  CompletionState *cmpl_state;
  GError *error = NULL;
  
  g_return_if_fail (GTK_IS_FILE_SELECTION (fs));

  file = gtk_entry_get_text (GTK_ENTRY (fs->fileop_entry));
  cmpl_state = (CompletionState*) fs->cmpl_state;
  path = cmpl_reference_position (cmpl_state);
  
  new_filename = g_strconcat (path, G_DIR_SEPARATOR_S, file, NULL);
  old_filename = g_strconcat (path, G_DIR_SEPARATOR_S, fs->fileop_file, NULL);

  sys_new_filename = g_filename_from_utf8 (new_filename, -1, NULL, NULL, &error);
  if (error)
    {
      if (g_error_matches (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE))
	buf = g_strdup_printf (_("The filename \"%s\" contains symbols that are not allowed in filenames"), new_filename);
      else
	buf = g_strdup_printf (_("Error renaming file to \"%s\": %s"),
			       new_filename, error->message);
      gtk_file_selection_fileop_error (fs, buf);
      g_error_free (error);
      goto out1;
    }

  sys_old_filename = g_filename_from_utf8 (old_filename, -1, NULL, NULL, &error);
  if (error)
    {
      if (g_error_matches (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE))
	buf = g_strdup_printf (_("The filename \"%s\" contains symbols that are not allowed in filenames"), old_filename);
      else
	buf = g_strdup_printf (_("Error renaming file \"%s\": %s"),
			       old_filename, error->message);
      gtk_file_selection_fileop_error (fs, buf);
      g_error_free (error);
      goto out2;
    }
  
  if (g_rename (sys_old_filename, sys_new_filename) < 0) 
    {
      int errsv = errno;

      buf = g_strdup_printf (_("Error renaming file \"%s\" to \"%s\": %s"),
			     sys_old_filename, sys_new_filename,
			     g_strerror (errsv));
      gtk_file_selection_fileop_error (fs, buf);
      goto out2;
    }
  
  gtk_file_selection_populate (fs, "", FALSE, FALSE);
  gtk_entry_set_text (GTK_ENTRY (fs->selection_entry), file);
  
 out2:
  g_free (sys_old_filename);

 out1:
  g_free (new_filename);
  g_free (old_filename);
  g_free (sys_new_filename);
  
  gtk_widget_destroy (fs->fileop_dialog);
}
  
static void
gtk_file_selection_rename_file (GtkWidget *widget,
				gpointer   data)
{
  GtkFileSelection *fs = data;
  GtkWidget *label;
  GtkWidget *dialog;
  GtkWidget *vbox;
  GtkWidget *button;
  gchar *buf;
  
  g_return_if_fail (GTK_IS_FILE_SELECTION (fs));

  if (fs->fileop_dialog)
	  return;

  g_free (fs->fileop_file);
  fs->fileop_file = g_strdup (gtk_entry_get_text (GTK_ENTRY (fs->selection_entry)));
  if (strlen (fs->fileop_file) < 1)
    return;
  
  /* main dialog */
  fs->fileop_dialog = dialog = gtk_dialog_new ();
  g_signal_connect (dialog, "destroy",
		    G_CALLBACK (gtk_file_selection_fileop_destroy),
		    fs);
  gtk_window_set_title (GTK_WINDOW (dialog), _("Rename File"));
  gtk_window_set_position (GTK_WINDOW (dialog), GTK_WIN_POS_MOUSE);
  gtk_window_set_transient_for (GTK_WINDOW (dialog), GTK_WINDOW (fs));

  /* If file dialog is grabbed, grab option dialog */
  /* When option dialog  closed, file dialog will be grabbed again */
  if (GTK_WINDOW (fs)->modal)
    gtk_window_set_modal (GTK_WINDOW (dialog), TRUE);
  
  vbox = gtk_vbox_new (FALSE, 0);
  gtk_container_set_border_width (GTK_CONTAINER (vbox), 8);
  gtk_box_pack_start (GTK_BOX (GTK_DIALOG (dialog)->vbox), vbox,
		      FALSE, FALSE, 0);
  gtk_widget_show(vbox);
  
  buf = g_strdup_printf (_("Rename file \"%s\" to:"), fs->fileop_file);
  label = gtk_label_new (buf);
  gtk_misc_set_alignment (GTK_MISC (label), 0.0, 0.0);
  gtk_box_pack_start (GTK_BOX (vbox), label, FALSE, FALSE, 5);
  gtk_widget_show (label);
  g_free (buf);

  /* New filename entry */
  fs->fileop_entry = gtk_entry_new ();
  gtk_box_pack_start (GTK_BOX (vbox), fs->fileop_entry, 
		      TRUE, TRUE, 5);
  gtk_widget_set_can_default (fs->fileop_entry, TRUE);
  gtk_entry_set_activates_default (GTK_ENTRY (fs->fileop_entry), TRUE); 
  gtk_widget_show (fs->fileop_entry);
  
  gtk_entry_set_text (GTK_ENTRY (fs->fileop_entry), fs->fileop_file);
  gtk_editable_select_region (GTK_EDITABLE (fs->fileop_entry),
			      0, strlen (fs->fileop_file));

  /* buttons */
  button = gtk_dialog_add_button (GTK_DIALOG (dialog), 
				  GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL);
  g_signal_connect_swapped (button, "clicked",
			    G_CALLBACK (gtk_widget_destroy),
			    dialog);

  gtk_widget_grab_focus (fs->fileop_entry);

  button = gtk_dialog_add_button (GTK_DIALOG (dialog), 
				  _("_Rename"), GTK_RESPONSE_OK);
  g_signal_connect (button, "clicked",
		    G_CALLBACK (gtk_file_selection_rename_file_confirmed),
		    fs);
  g_signal_connect (fs->fileop_entry, "changed",
		    G_CALLBACK (gtk_file_selection_fileop_entry_changed),
		    button);

  gtk_widget_grab_default (button);
  
  gtk_widget_show (dialog);
}

static gint
gtk_file_selection_insert_text (GtkWidget   *widget,
				const gchar *new_text,
				gint         new_text_length,
				gint        *position,
				gpointer     user_data)
{
  gchar *filename;

  filename = g_filename_from_utf8 (new_text, new_text_length, NULL, NULL, NULL);

  if (!filename)
    {
      gdk_display_beep (gtk_widget_get_display (widget));
      g_signal_stop_emission_by_name (widget, "insert-text");
      return FALSE;
    }
  
  g_free (filename);
  
  return TRUE;
}

static void
gtk_file_selection_update_fileops (GtkFileSelection *fs)
{
  gboolean sensitive;

  if (!fs->selection_entry)
    return;

  sensitive = !entry_is_empty (GTK_ENTRY (fs->selection_entry));

  if (fs->fileop_del_file)
    gtk_widget_set_sensitive (fs->fileop_del_file, sensitive);
  
  if (fs->fileop_ren_file)
    gtk_widget_set_sensitive (fs->fileop_ren_file, sensitive);
}

static void
home_clicked (GtkWidget *widget, gpointer data)
{
  char *dir;
  
  dir = g_strdup_printf ("%s/", g_get_home_dir());
  
  gtk_file_selection_populate (GTK_FILE_SELECTION (data), 
			       dir, FALSE, FALSE);
  g_free (dir);

  gtk_widget_grab_focus (GTK_FILE_SELECTION (data)->selection_entry);
}

static char *
get_desktop_directory (void)
{
  char *filename;
  struct stat buf;

  filename = g_build_filename (g_get_home_dir (), "Desktop", NULL);
  if (lstat (filename, &buf) == 0) 
    {
      if (S_ISLNK (buf.st_mode)) 
	{
	  char link_target[MAXPATHLEN + 1];
	  int len;

	  len = readlink (filename, link_target, MAXPATHLEN);
	  if (len > 0) 
	    {
	      char *desktop_filename;
	      /* Add a trailing / if there isn't already one */
	      link_target[len] = '\0';
	      if (link_target[len - 1] == G_DIR_SEPARATOR) 
		{
		  link_target[len - 1] = '\0';
		}

	      if (!strcmp (link_target, "Desktop")) 
		{
		  g_free (filename);
		  return g_build_filename (g_get_home_dir (), "Desktop", G_DIR_SEPARATOR_S, NULL);
		}
	      
	      desktop_filename = g_build_filename (g_get_home_dir (), "Desktop", NULL);
	      if (!strcmp (link_target, desktop_filename)) 
		{
		  g_free (desktop_filename);
		  g_free (filename);
		  return g_build_filename (g_get_home_dir (), "Desktop", G_DIR_SEPARATOR_S, NULL);
		}
	      g_free (desktop_filename);
	    }
	}
    }
  g_free (filename);

  return g_build_filename (g_get_home_dir (), "Desktop", G_DIR_SEPARATOR_S, NULL);
}


static void
desktop_clicked (GtkWidget *widget, gpointer data)
{
  char *dir;
  
  dir = get_desktop_directory ();
  gtk_file_selection_populate (GTK_FILE_SELECTION (data), 
			       dir, FALSE, FALSE);
  g_free (dir);

  gtk_widget_grab_focus (GTK_FILE_SELECTION (data)->selection_entry);
}

static void 
documents_clicked (GtkWidget *widget, gpointer data)
{
  char *dir;
  dir = g_strdup_printf ("%s/Documents/", g_get_home_dir ());
  
  gtk_file_selection_populate (GTK_FILE_SELECTION (data),
			       dir, FALSE, FALSE);
  
  g_free (dir);

  gtk_widget_grab_focus (GTK_FILE_SELECTION (data)->selection_entry);
}

static gint
gtk_file_selection_key_press (GtkWidget   *widget,
			      GdkEventKey *event,
			      gpointer     user_data)
{
  GtkFileSelection *fs;
  char *text;

  g_return_val_if_fail (widget != NULL, FALSE);
  g_return_val_if_fail (event != NULL, FALSE);

  if ((event->keyval == GDK_Tab || event->keyval == GDK_KP_Tab) &&
      (event->state & gtk_accelerator_get_default_mod_mask ()) == 0)
    {
      fs = GTK_FILE_SELECTION (user_data);
#ifdef G_WITH_CYGWIN
      translate_win32_path (fs);
#endif
      text = g_strdup (gtk_entry_get_text (GTK_ENTRY (fs->selection_entry)));

      gtk_file_selection_populate (fs, text, TRUE, TRUE);

      g_free (text);

      return TRUE;
    }

  return FALSE;
}

static void
gtk_file_selection_history_callback (GtkWidget *widget,
				     gpointer   data)
{
  GtkFileSelection *fs = data;
  HistoryCallbackArg *callback_arg;
  GList *list;

  g_return_if_fail (GTK_IS_FILE_SELECTION (fs));

  list = fs->history_list;
  
  while (list) {
    callback_arg = list->data;
    
    if (callback_arg->menu_item == widget)
      {
	gtk_file_selection_populate (fs, callback_arg->directory, FALSE, FALSE);
	break;
      }
    
    list = list->next;
  }
}

static void 
gtk_file_selection_update_history_menu (GtkFileSelection *fs,
					gchar            *current_directory)
{
  HistoryCallbackArg *callback_arg;
  GtkWidget *menu_item;
  GList *list;
  gchar *current_dir;
  gint dir_len;
  gint i;
  
  g_return_if_fail (GTK_IS_FILE_SELECTION (fs));
  g_return_if_fail (current_directory != NULL);
  
  list = fs->history_list;

  if (fs->history_menu) 
    {
      while (list) {
	callback_arg = list->data;
	g_free (callback_arg->directory);
	g_free (callback_arg);
	list = list->next;
      }
      g_list_free (fs->history_list);
      fs->history_list = NULL;
      
      gtk_widget_destroy (fs->history_menu);
    }
  
  fs->history_menu = gtk_menu_new ();

  current_dir = g_strdup (current_directory);

  dir_len = strlen (current_dir);

  for (i = dir_len; i >= 0; i--)
    {
      /* the i == dir_len is to catch the full path for the first 
       * entry. */
      if ( (current_dir[i] == G_DIR_SEPARATOR) || (i == dir_len))
	{
	  /* another small hack to catch the full path */
	  if (i != dir_len) 
		  current_dir[i + 1] = '\0';
#ifdef G_WITH_CYGWIN
	  if (!strcmp (current_dir, "//"))
	    continue;
#endif
	  menu_item = gtk_menu_item_new_with_label (current_dir);
	  
	  callback_arg = g_new (HistoryCallbackArg, 1);
	  callback_arg->menu_item = menu_item;
	  
	  /* since the autocompletion gets confused if you don't 
	   * supply a trailing '/' on a dir entry, set the full
	   * (current) path to "" which just refreshes the filesel */
	  if (dir_len == i)
	    {
	      callback_arg->directory = g_strdup ("");
	    }
	  else
	    {
	      callback_arg->directory = g_strdup (current_dir);
	    }
	  
	  fs->history_list = g_list_append (fs->history_list, callback_arg);
	  
	  g_signal_connect (menu_item, "activate",
			    G_CALLBACK (gtk_file_selection_history_callback),
			    fs);
	  gtk_menu_shell_append (GTK_MENU_SHELL (fs->history_menu), menu_item);
	  gtk_widget_show (menu_item);
	}
    }

  gtk_option_menu_set_menu (GTK_OPTION_MENU (fs->history_pulldown), 
			    fs->history_menu);
  g_free (current_dir);
}

static gchar *
get_real_filename (gchar    *filename,
                   gboolean  free_old)
{
#ifdef G_WITH_CYGWIN
  /* Check to see if the selection was a drive selector */
  if (isalpha (filename[0]) && (filename[1] == ':'))
    {
      gchar temp_filename[MAX_PATH];
      int len;

      cygwin_conv_to_posix_path (filename, temp_filename);

      /* we need trailing '/'. */
      len = strlen (temp_filename);
      if (len > 0 && temp_filename[len-1] != '/')
        {
          temp_filename[len]   = '/';
          temp_filename[len+1] = '\0';
        }
      
      if (free_old)
	g_free (filename);

      return g_strdup (temp_filename);
    }
#endif /* G_WITH_CYGWIN */
  return filename;
}

static void
gtk_file_selection_file_activate (GtkTreeView       *tree_view,
				  GtkTreePath       *path,
				  GtkTreeViewColumn *column,
				  gpointer           user_data)
{
  GtkFileSelection *fs = GTK_FILE_SELECTION (user_data);
  GtkTreeModel *model = gtk_tree_view_get_model (tree_view);
  GtkTreeIter iter;  
  gchar *filename;
  
  gtk_tree_model_get_iter (model, &iter, path);
  gtk_tree_model_get (model, &iter, FILE_COLUMN, &filename, -1);
  filename = get_real_filename (filename, TRUE);
  gtk_entry_set_text (GTK_ENTRY (fs->selection_entry), filename);
  gtk_button_clicked (GTK_BUTTON (fs->ok_button));

  g_free (filename);
}

static void
gtk_file_selection_dir_activate (GtkTreeView       *tree_view,
				 GtkTreePath       *path,
				 GtkTreeViewColumn *column,
				 gpointer           user_data)
{
  GtkFileSelection *fs = GTK_FILE_SELECTION (user_data);
  GtkTreeModel *model = gtk_tree_view_get_model (tree_view);
  GtkTreeIter iter;
  gchar *filename;

  gtk_tree_model_get_iter (model, &iter, path);
  gtk_tree_model_get (model, &iter, DIR_COLUMN, &filename, -1);
  filename = get_real_filename (filename, TRUE);
  gtk_file_selection_populate (fs, filename, FALSE, FALSE);
  g_free (filename);
}

#ifdef G_PLATFORM_WIN32

static void
win32_gtk_add_drives_to_dir_list (GtkListStore *model)
{
  gchar *textPtr;
  gchar buffer[128];
  char formatBuffer[128];
  GtkTreeIter iter;

  /* Get the drives string */
  GetLogicalDriveStrings (sizeof (buffer), buffer);

  /* Add the drives as necessary */
  textPtr = buffer;
  while (*textPtr != '\0')
    {
      /* Ignore floppies (?) */
      if (GetDriveType (textPtr) != DRIVE_REMOVABLE)
	{
	  /* Build the actual displayable string */
	  g_snprintf (formatBuffer, sizeof (formatBuffer), "%c:\\", toupper (textPtr[0]));

	  /* Add to the list */
	  gtk_list_store_append (model, &iter);
	  gtk_list_store_set (model, &iter, DIR_COLUMN, formatBuffer, -1);
	}
      textPtr += (strlen (textPtr) + 1);
    }
}
#endif

static gchar *
escape_underscores (const gchar *str)
{
  GString *result = g_string_new (NULL);
  while (*str)
    {
      if (*str == '_')
	g_string_append_c (result, '_');

      g_string_append_c (result, *str);
      str++;
    }

  return g_string_free (result, FALSE);
}

static void
gtk_file_selection_populate (GtkFileSelection *fs,
			     gchar            *rel_path,
			     gboolean          try_complete,
			     gboolean          reset_entry)
{
  CompletionState *cmpl_state;
  PossibleCompletion* poss;
  GtkTreeIter iter;
  GtkListStore *dir_model;
  GtkListStore *file_model;
  gchar* filename;
  gchar* rem_path = rel_path;
  gchar* sel_text;
  gint did_recurse = FALSE;
  gint possible_count = 0;
  
  g_return_if_fail (GTK_IS_FILE_SELECTION (fs));

  cmpl_state = (CompletionState*) fs->cmpl_state;
  poss = cmpl_completion_matches (rel_path, &rem_path, cmpl_state);

  if (!cmpl_state_okay (cmpl_state))
    {
      /* Something went wrong. */
      gtk_file_selection_abort (fs);
      return;
    }

  g_assert (cmpl_state->reference_dir);

  dir_model = GTK_LIST_STORE (gtk_tree_view_get_model (GTK_TREE_VIEW (fs->dir_list)));
  file_model = GTK_LIST_STORE (gtk_tree_view_get_model (GTK_TREE_VIEW (fs->file_list)));

  gtk_list_store_clear (dir_model);
  gtk_list_store_clear (file_model);

  /* Set the dir list to include ./ and ../ */
  gtk_list_store_append (dir_model, &iter);
  gtk_list_store_set (dir_model, &iter, DIR_COLUMN, "." G_DIR_SEPARATOR_S, -1);
  gtk_list_store_append (dir_model, &iter);
  gtk_list_store_set (dir_model, &iter, DIR_COLUMN, ".." G_DIR_SEPARATOR_S, -1);

  while (poss)
    {
      if (cmpl_is_a_completion (poss))
        {
          possible_count += 1;

          filename = cmpl_this_completion (poss);

          if (cmpl_is_directory (poss))
            {
              if (strcmp (filename, "." G_DIR_SEPARATOR_S) != 0 &&
                  strcmp (filename, ".." G_DIR_SEPARATOR_S) != 0)
		{
		  gtk_list_store_append (dir_model, &iter);
		  gtk_list_store_set (dir_model, &iter, DIR_COLUMN, filename, -1);
		}
	    }
          else
	    {
	      gtk_list_store_append (file_model, &iter);
	      gtk_list_store_set (file_model, &iter, DIR_COLUMN, filename, -1);
            }
	}

      poss = cmpl_next_completion (cmpl_state);
    }

#ifdef G_PLATFORM_WIN32
  /* For Windows, add drives as potential selections */
  win32_gtk_add_drives_to_dir_list (dir_model);
#endif

  /* File lists are set. */

  g_assert (cmpl_state->reference_dir);

  if (try_complete)
    {

      /* User is trying to complete filenames, so advance the user's input
       * string to the updated_text, which is the common leading substring
       * of all possible completions, and if its a directory attempt
       * attempt completions in it. */

      if (cmpl_updated_text (cmpl_state)[0])
        {

          if (cmpl_updated_dir (cmpl_state))
            {
	      gchar* dir_name = g_strdup (cmpl_updated_text (cmpl_state));

              did_recurse = TRUE;

              gtk_file_selection_populate (fs, dir_name, TRUE, TRUE);

              g_free (dir_name);
            }
          else
            {
	      if (fs->selection_entry)
		      gtk_entry_set_text (GTK_ENTRY (fs->selection_entry),
					  cmpl_updated_text (cmpl_state));
            }
        }
      else
        {
	  if (fs->selection_entry)
	    gtk_entry_set_text (GTK_ENTRY (fs->selection_entry), rem_path);
        }
    }
  else if (reset_entry)
    {
      if (fs->selection_entry)
	gtk_entry_set_text (GTK_ENTRY (fs->selection_entry), "");
    }

  if (!did_recurse)
    {
      if (fs->selection_entry && try_complete)
	gtk_editable_set_position (GTK_EDITABLE (fs->selection_entry), -1);

      if (fs->selection_entry)
	{
	  char *escaped = escape_underscores (cmpl_reference_position (cmpl_state));
	  sel_text = g_strconcat (_("_Selection: "), escaped, NULL);
	  g_free (escaped);

	  gtk_label_set_text_with_mnemonic (GTK_LABEL (fs->selection_text), sel_text);
	  g_free (sel_text);
	}

      if (fs->history_pulldown) 
	{
	  gtk_file_selection_update_history_menu (fs, cmpl_reference_position (cmpl_state));
	}
      
    }
}

static void
gtk_file_selection_abort (GtkFileSelection *fs)
{
  gchar err_buf[256];

  g_snprintf (err_buf, sizeof (err_buf), _("Folder unreadable: %s"), cmpl_strerror (cmpl_errno));

  /*  BEEP gdk_beep();  */

  if (fs->selection_entry)
    gtk_label_set_text (GTK_LABEL (fs->selection_text), err_buf);
}

/**
 * gtk_file_selection_set_select_multiple:
 * @filesel: a #GtkFileSelection
 * @select_multiple: whether or not the user is allowed to select multiple
 * files in the file list.
 *
 * Sets whether the user is allowed to select multiple files in the file list.
 * Use gtk_file_selection_get_selections () to get the list of selected files.
 **/
void
gtk_file_selection_set_select_multiple (GtkFileSelection *filesel,
					gboolean          select_multiple)
{
  GtkTreeSelection *sel;
  GtkSelectionMode mode;

  g_return_if_fail (GTK_IS_FILE_SELECTION (filesel));

  sel = gtk_tree_view_get_selection (GTK_TREE_VIEW (filesel->file_list));

  mode = select_multiple ? GTK_SELECTION_MULTIPLE : GTK_SELECTION_SINGLE;

  if (mode != gtk_tree_selection_get_mode (sel))
    {
      gtk_tree_selection_set_mode (sel, mode);

      g_object_notify (G_OBJECT (filesel), "select-multiple");
    }
}

/**
 * gtk_file_selection_get_select_multiple:
 * @filesel: a #GtkFileSelection
 *
 * Determines whether or not the user is allowed to select multiple files in
 * the file list. See gtk_file_selection_set_select_multiple().
 *
 * Return value: %TRUE if the user is allowed to select multiple files in the
 * file list
 **/
gboolean
gtk_file_selection_get_select_multiple (GtkFileSelection *filesel)
{
  GtkTreeSelection *sel;

  g_return_val_if_fail (GTK_IS_FILE_SELECTION (filesel), FALSE);

  sel = gtk_tree_view_get_selection (GTK_TREE_VIEW (filesel->file_list));
  return (gtk_tree_selection_get_mode (sel) == GTK_SELECTION_MULTIPLE);
}

static void
multiple_changed_foreach (GtkTreeModel *model,
			  GtkTreePath  *path,
			  GtkTreeIter  *iter,
			  gpointer      data)
{
  GPtrArray *names = data;
  gchar *filename;

  gtk_tree_model_get (model, iter, FILE_COLUMN, &filename, -1);

  g_ptr_array_add (names, filename);
}

static void
free_selected_names (GPtrArray *names)
{
  gint i;

  for (i = 0; i < names->len; i++)
    g_free (g_ptr_array_index (names, i));

  g_ptr_array_free (names, TRUE);
}

static void
gtk_file_selection_file_changed (GtkTreeSelection *selection,
				 gpointer          user_data)
{
  GtkFileSelection *fs = GTK_FILE_SELECTION (user_data);
  GPtrArray *new_names;
  gchar *filename;
  const gchar *entry;
  gint index = -1;

  new_names = g_ptr_array_sized_new (8);

  gtk_tree_selection_selected_foreach (selection,
				       multiple_changed_foreach,
				       new_names);

  /* nothing selected */
  if (new_names->len == 0)
    {
      g_ptr_array_free (new_names, TRUE);

      if (fs->selected_names != NULL)
	{
	  free_selected_names (fs->selected_names);
	  fs->selected_names = NULL;
	}

      goto maybe_clear_entry;
    }

  if (new_names->len != 1)
    {
      GPtrArray *old_names = fs->selected_names;

      if (old_names != NULL)
	{
	  /* A common case is selecting a range of files from top to bottom,
	   * so quickly check for that to avoid looping over the entire list
	   */
	  if (compare_utf8_filenames (g_ptr_array_index (old_names, old_names->len - 1),
				      g_ptr_array_index (new_names, new_names->len - 1)) != 0)
	    index = new_names->len - 1;
	  else
	    {
	      gint i = 0, j = 0, cmp;

	      /* do a quick diff, stopping at the first file not in the
	       * old list
	       */
	      while (i < old_names->len && j < new_names->len)
		{
		  cmp = compare_utf8_filenames (g_ptr_array_index (old_names, i),
						g_ptr_array_index (new_names, j));
		  if (cmp < 0)
		    {
		      i++;
		    }
		  else if (cmp == 0)
		    {
		      i++;
		      j++;
		    }
		  else if (cmp > 0)
		    {
		      index = j;
		      break;
		    }
		}

	      /* we ran off the end of the old list */
	      if (index == -1 && i < new_names->len)
		index = j;
	    }
	}
      else
	{
	  /* A phantom anchor still exists at the point where the last item
	   * was selected, which is used for subsequent range selections.
	   * So search up from there.
	   */
	  if (fs->last_selected &&
	      compare_utf8_filenames (fs->last_selected,
				      g_ptr_array_index (new_names, 0)) == 0)
	    index = new_names->len - 1;
	  else
	    index = 0;
	}
    }
  else
    index = 0;

  if (fs->selected_names != NULL)
    free_selected_names (fs->selected_names);

  fs->selected_names = new_names;

  if (index != -1)
    {
      g_free (fs->last_selected);

      fs->last_selected = g_strdup (g_ptr_array_index (new_names, index));
      filename = get_real_filename (fs->last_selected, FALSE);

      gtk_entry_set_text (GTK_ENTRY (fs->selection_entry), filename);

      if (filename != fs->last_selected)
	g_free (filename);
      
      return;
    }
  
maybe_clear_entry:

  entry = gtk_entry_get_text (GTK_ENTRY (fs->selection_entry));
  if ((entry != NULL) && (fs->last_selected != NULL) &&
      (compare_utf8_filenames (entry, fs->last_selected) == 0))
    gtk_entry_set_text (GTK_ENTRY (fs->selection_entry), "");
}

/**
 * gtk_file_selection_get_selections:
 * @filesel: a #GtkFileSelection
 *
 * Retrieves the list of file selections the user has made in the dialog box.
 * This function is intended for use when the user can select multiple files
 * in the file list. 
 *
 * The filenames are in the GLib file name encoding. To convert to
 * UTF-8, call g_filename_to_utf8() on each string.
 *
 * Return value: a newly-allocated %NULL-terminated array of strings. Use
 * g_strfreev() to free it.
 **/
gchar **
gtk_file_selection_get_selections (GtkFileSelection *filesel)
{
  GPtrArray *names;
  gchar **selections;
  gchar *filename, *dirname;
  gchar *current, *buf;
  gint i, count;
  gboolean unselected_entry;

  g_return_val_if_fail (GTK_IS_FILE_SELECTION (filesel), NULL);

  filename = g_strdup (gtk_file_selection_get_filename (filesel));

  if (strlen (filename) == 0)
    {
      g_free (filename);
      return NULL;
    }

  names = filesel->selected_names;

  if (names != NULL)
    selections = g_new (gchar *, names->len + 2);
  else
    selections = g_new (gchar *, 2);

  count = 0;
  unselected_entry = TRUE;

  if (names != NULL)
    {
      dirname = g_path_get_dirname (filename);

      if ((names->len >= 1) && 
	  (strcmp (gtk_entry_get_text (GTK_ENTRY (filesel->selection_entry)), "") == 0))
	{ /* multiple files are selected and last selection was removed via ctrl click */
	  g_free (dirname);
	  dirname = g_strdup (filename); /* as gtk_file_selection_get_filename returns dir 
					    if no file is selected */
	  unselected_entry = FALSE;
	}

      for (i = 0; i < names->len; i++)
	{
	  buf = g_filename_from_utf8 (g_ptr_array_index (names, i), -1,
				      NULL, NULL, NULL);
	  current = g_build_filename (dirname, buf, NULL);
	  g_free (buf);

	  selections[count++] = current;

	  if (unselected_entry && compare_sys_filenames (current, filename) == 0)
	    unselected_entry = FALSE;
	}

      g_free (dirname);
    }

  if (unselected_entry)
    selections[count++] = filename;
  else
    g_free (filename);

  selections[count] = NULL;

  return selections;
}

/**********************************************************************/
/*			  External Interface                          */
/**********************************************************************/

/* The four completion state selectors
 */
static gchar*
cmpl_updated_text (CompletionState *cmpl_state)
{
  return cmpl_state->updated_text;
}

static gboolean
cmpl_updated_dir (CompletionState *cmpl_state)
{
  return cmpl_state->re_complete;
}

static gchar*
cmpl_reference_position (CompletionState *cmpl_state)
{
  return cmpl_state->reference_dir->fullname;
}

#if 0
/* This doesn't work currently and would require changes
 * to fnmatch.c to get working.
 */
static gint
cmpl_last_valid_char (CompletionState *cmpl_state)
{
  return cmpl_state->last_valid_char;
}
#endif

static gchar*
cmpl_completion_fullname (const gchar     *text,
			  CompletionState *cmpl_state)
{
  if (!cmpl_state_okay (cmpl_state))
    {
      return g_strdup ("");
    }
  else if (g_path_is_absolute (text))
    {
      return g_strdup (text);
    }
#ifdef HAVE_PWD_H
  else if (text[0] == '~')
    {
      CompletionDir* dir;
      char* slash;

      dir = open_user_dir (text, cmpl_state);

      if (dir)
	{
	  slash = strchr (text, G_DIR_SEPARATOR);
	  
	  /* slash may be NULL, that works too */
	  return g_strconcat (dir->fullname, slash, NULL);
	}
    }
#endif
  
  return g_build_filename (cmpl_state->reference_dir->fullname,
			   text,
			   NULL);
}

/* The three completion selectors
 */
static gchar*
cmpl_this_completion (PossibleCompletion* pc)
{
  return pc->text;
}

static gboolean
cmpl_is_directory (PossibleCompletion* pc)
{
  return pc->is_directory;
}

static gint
cmpl_is_a_completion (PossibleCompletion* pc)
{
  return pc->is_a_completion;
}

/**********************************************************************/
/*	                 Construction, deletion                       */
/**********************************************************************/

/* Get the nearest parent of the current directory for which
 * we can convert the filename into UTF-8. With paranoia.
 * Returns "." when all goes wrong.
 */
static gchar *
get_current_dir_utf8 (void)
{
  gchar *dir = g_get_current_dir ();
  gchar *dir_utf8 = NULL;

  while (TRUE)
    {
      gchar *last_slash;

      dir_utf8 = g_filename_to_utf8 (dir, -1, NULL, NULL, NULL);
      if (dir_utf8)
	break;

      last_slash = strrchr (dir, G_DIR_SEPARATOR);
      if (!last_slash)		/* g_get_current_dir() wasn't absolute! */
	break;

      if (last_slash + 1 == g_path_skip_root (dir)) /* Parent directory is a root directory */
	{
	  if (last_slash[1] == '\0') /* Root misencoded! */
	    break;
	  else
	    last_slash[1] = '\0';
	}
      else
	last_slash[0] = '\0';
      
      g_assert (last_slash);
    }

  g_free (dir);
  
  return dir_utf8 ? dir_utf8 : g_strdup (".");
}

static CompletionState*
cmpl_init_state (void)
{
  gchar *utf8_cwd;
  CompletionState *new_state;
  gint tries = 0;

  new_state = g_new (CompletionState, 1);

  utf8_cwd = get_current_dir_utf8 ();

tryagain:
  tries++;
  new_state->reference_dir = NULL;
  new_state->completion_dir = NULL;
  new_state->active_completion_dir = NULL;
  new_state->directory_storage = NULL;
  new_state->directory_sent_storage = NULL;
  new_state->last_valid_char = 0;
  new_state->updated_text = g_new (gchar, MAXPATHLEN);
  new_state->updated_text_alloc = MAXPATHLEN;
  new_state->the_completion.text = g_new (gchar, MAXPATHLEN);
  new_state->the_completion.text_alloc = MAXPATHLEN;
  new_state->user_dir_name_buffer = NULL;
  new_state->user_directories = NULL;

  new_state->reference_dir = open_dir (utf8_cwd, new_state);

  if (!new_state->reference_dir)
    {
      /* Directories changing from underneath us, grumble */
      strcpy (utf8_cwd, G_DIR_SEPARATOR_S);
      if (tries < 2)
	goto tryagain;
    }

  g_free (utf8_cwd);
  return new_state;
}

static void
cmpl_free_dir_list (GList* dp0)
{
  GList *dp = dp0;

  while (dp)
    {
      free_dir (dp->data);
      dp = dp->next;
    }

  g_list_free (dp0);
}

static void
cmpl_free_dir_sent_list (GList* dp0)
{
  GList *dp = dp0;

  while (dp)
    {
      free_dir_sent (dp->data);
      dp = dp->next;
    }

  g_list_free (dp0);
}

static void
cmpl_free_state (CompletionState* cmpl_state)
{
  g_return_if_fail (cmpl_state != NULL);

  cmpl_free_dir_list (cmpl_state->directory_storage);
  cmpl_free_dir_sent_list (cmpl_state->directory_sent_storage);

  g_free (cmpl_state->user_dir_name_buffer);
  g_free (cmpl_state->user_directories);
  g_free (cmpl_state->the_completion.text);
  g_free (cmpl_state->updated_text);

  g_free (cmpl_state);
}

static void
free_dir (CompletionDir* dir)
{
  g_free (dir->cmpl_text);
  g_free (dir->fullname);
  g_free (dir);
}

static void
free_dir_sent (CompletionDirSent* sent)
{
  gint i;
  for (i = 0; i < sent->entry_count; i++)
    {
      g_free (sent->entries[i].entry_name);
      g_free (sent->entries[i].sort_key);
    }
  g_free (sent->entries);
  g_free (sent);
}

static void
prune_memory_usage (CompletionState *cmpl_state)
{
  GList* cdsl = cmpl_state->directory_sent_storage;
  GList* cdl = cmpl_state->directory_storage;
  GList* cdl0 = cdl;
  gint len = 0;

  for (; cdsl && len < CMPL_DIRECTORY_CACHE_SIZE; len += 1)
    cdsl = cdsl->next;

  if (cdsl)
    {
      cmpl_free_dir_sent_list (cdsl->next);
      cdsl->next = NULL;
    }

  cmpl_state->directory_storage = NULL;
  while (cdl)
    {
      if (cdl->data == cmpl_state->reference_dir)
	cmpl_state->directory_storage = g_list_prepend (NULL, cdl->data);
      else
	free_dir (cdl->data);
      cdl = cdl->next;
    }

  g_list_free (cdl0);
}

/**********************************************************************/
/*                        The main entrances.                         */
/**********************************************************************/

static PossibleCompletion*
cmpl_completion_matches (gchar           *text_to_complete,
			 gchar          **remaining_text,
			 CompletionState *cmpl_state)
{
#ifdef HAVE_PWD_H
  gchar* first_slash;
#endif
  PossibleCompletion *poss;

  prune_memory_usage (cmpl_state);

  g_assert (text_to_complete != NULL);

  cmpl_state->user_completion_index = -1;
  cmpl_state->last_completion_text = text_to_complete;
  cmpl_state->the_completion.text[0] = 0;
  cmpl_state->last_valid_char = 0;
  cmpl_state->updated_text_len = -1;
  cmpl_state->updated_text[0] = 0;
  cmpl_state->re_complete = FALSE;

#ifdef HAVE_PWD_H
  first_slash = strchr (text_to_complete, G_DIR_SEPARATOR);

  if (text_to_complete[0] == '~' && !first_slash)
    {
      /* Text starts with ~ and there is no slash, show all the
       * home directory completions.
       */
      poss = attempt_homedir_completion (text_to_complete, cmpl_state);

      update_cmpl (poss, cmpl_state);

      return poss;
    }
#endif
  cmpl_state->reference_dir =
    open_ref_dir (text_to_complete, remaining_text, cmpl_state);

  if (!cmpl_state->reference_dir)
    return NULL;

  cmpl_state->completion_dir =
    find_completion_dir (*remaining_text, remaining_text, cmpl_state);

  cmpl_state->last_valid_char = *remaining_text - text_to_complete;

  if (!cmpl_state->completion_dir)
    return NULL;

  cmpl_state->completion_dir->cmpl_index = -1;
  cmpl_state->completion_dir->cmpl_parent = NULL;
  cmpl_state->completion_dir->cmpl_text = g_strdup (*remaining_text);

  cmpl_state->active_completion_dir = cmpl_state->completion_dir;

  cmpl_state->reference_dir = cmpl_state->completion_dir;

  poss = attempt_file_completion (cmpl_state);

  update_cmpl (poss, cmpl_state);

  return poss;
}

static PossibleCompletion*
cmpl_next_completion (CompletionState* cmpl_state)
{
  PossibleCompletion* poss = NULL;

  cmpl_state->the_completion.text[0] = 0;

#ifdef HAVE_PWD_H
  if (cmpl_state->user_completion_index >= 0)
    poss = attempt_homedir_completion (cmpl_state->last_completion_text, cmpl_state);
  else
    poss = attempt_file_completion (cmpl_state);
#else
  poss = attempt_file_completion (cmpl_state);
#endif

  update_cmpl (poss, cmpl_state);

  return poss;
}

/**********************************************************************/
/*			 Directory Operations                         */
/**********************************************************************/

/* Open the directory where completion will begin from, if possible. */
static CompletionDir*
open_ref_dir (gchar           *text_to_complete,
	      gchar          **remaining_text,
	      CompletionState *cmpl_state)
{
  gchar* first_slash;
  CompletionDir *new_dir;

  first_slash = strchr (text_to_complete, G_DIR_SEPARATOR);

#ifdef G_WITH_CYGWIN
  if (text_to_complete[0] == '/' && text_to_complete[1] == '/')
    {
      char root_dir[5];
      g_snprintf (root_dir, sizeof (root_dir), "//%c", text_to_complete[2]);

      new_dir = open_dir (root_dir, cmpl_state);

      if (new_dir) {
	*remaining_text = text_to_complete + 4;
      }
    }
#else
  if (FALSE)
    ;
#endif
#ifdef HAVE_PWD_H
  else if (text_to_complete[0] == '~')
    {
      new_dir = open_user_dir (text_to_complete, cmpl_state);

      if (new_dir)
	{
	  if (first_slash)
	    *remaining_text = first_slash + 1;
	  else
	    *remaining_text = text_to_complete + strlen (text_to_complete);
	}
      else
	{
	  return NULL;
	}
    }
#endif
  else if (g_path_is_absolute (text_to_complete) || !cmpl_state->reference_dir)
    {
      gchar *tmp = g_strdup (text_to_complete);
      gchar *p;

      p = tmp;
      while (*p && *p != '*' && *p != '?')
	p++;

      *p = '\0';
      p = strrchr (tmp, G_DIR_SEPARATOR);
      if (p)
	{
	  if (p + 1 == g_path_skip_root (tmp))
	    p++;
      
	  *p = '\0';
	  new_dir = open_dir (tmp, cmpl_state);

	  if (new_dir)
	    *remaining_text = text_to_complete + 
	      ((p == g_path_skip_root (tmp)) ? (p - tmp) : (p + 1 - tmp));
	}
      else
	{
	  /* If no possible candidates, use the cwd */
	  gchar *utf8_curdir = get_current_dir_utf8 ();

	  new_dir = open_dir (utf8_curdir, cmpl_state);

	  if (new_dir)
	    *remaining_text = text_to_complete;

	  g_free (utf8_curdir);
	}

      g_free (tmp);
    }
  else
    {
      *remaining_text = text_to_complete;

      new_dir = open_dir (cmpl_state->reference_dir->fullname, cmpl_state);
    }

  if (new_dir)
    {
      new_dir->cmpl_index = -1;
      new_dir->cmpl_parent = NULL;
    }

  return new_dir;
}

#ifdef HAVE_PWD_H

/* open a directory by user name */
static CompletionDir*
open_user_dir (const gchar     *text_to_complete,
	       CompletionState *cmpl_state)
{
  CompletionDir *result;
  gchar *first_slash;
  gint cmp_len;

  g_assert (text_to_complete && text_to_complete[0] == '~');

  first_slash = strchr (text_to_complete, G_DIR_SEPARATOR);

  if (first_slash)
    cmp_len = first_slash - text_to_complete - 1;
  else
    cmp_len = strlen (text_to_complete + 1);

  if (!cmp_len)
    {
      /* ~/ */
      const gchar *homedir = g_get_home_dir ();
      gchar *utf8_homedir = g_filename_to_utf8 (homedir, -1, NULL, NULL, NULL);

      if (utf8_homedir)
	result = open_dir (utf8_homedir, cmpl_state);
      else
	result = NULL;
      
      g_free (utf8_homedir);
    }
  else
    {
      /* ~user/ */
      gchar* copy = g_new (char, cmp_len + 1);
      gchar *utf8_dir;
      struct passwd *pwd;

      strncpy (copy, text_to_complete + 1, cmp_len);
      copy[cmp_len] = 0;
      pwd = getpwnam (copy);
      g_free (copy);
      if (!pwd)
	{
	  cmpl_errno = errno;
	  return NULL;
	}
      utf8_dir = g_filename_to_utf8 (pwd->pw_dir, -1, NULL, NULL, NULL);
      result = open_dir (utf8_dir, cmpl_state);
      g_free (utf8_dir);
    }
  return result;
}

#endif

/* open a directory relative to the current relative directory */
static CompletionDir*
open_relative_dir (gchar           *dir_name,
		   CompletionDir   *dir,
		   CompletionState *cmpl_state)
{
  CompletionDir *result;
  GString *path;

  path = g_string_sized_new (dir->fullname_len + strlen (dir_name) + 10);
  g_string_assign (path, dir->fullname);

  if (dir->fullname_len > 1
      && path->str[dir->fullname_len - 1] != G_DIR_SEPARATOR)
    g_string_append_c (path, G_DIR_SEPARATOR);
  g_string_append (path, dir_name);

  result = open_dir (path->str, cmpl_state);

  g_string_free (path, TRUE);

  return result;
}

/* after the cache lookup fails, really open a new directory */
static CompletionDirSent*
open_new_dir (gchar    *dir_name,
	      GStatBuf *sbuf,
	      gboolean  stat_subdirs)
{
  CompletionDirSent *sent;
  GDir *directory;
  const char *dirent;
  GError *error = NULL;
  gint entry_count = 0;
  gint n_entries = 0;
  gint i;
  GStatBuf ent_sbuf;
  GString *path;
  gchar *sys_dir_name;

  sent = g_new (CompletionDirSent, 1);
#ifndef G_PLATFORM_WIN32
  sent->mtime = sbuf->st_mtime;
  sent->inode = sbuf->st_ino;
  sent->device = sbuf->st_dev;
#endif
  path = g_string_sized_new (2*MAXPATHLEN + 10);

  sys_dir_name = g_filename_from_utf8 (dir_name, -1, NULL, NULL, NULL);
  if (!sys_dir_name)
    {
      cmpl_errno = CMPL_ERRNO_DID_NOT_CONVERT;
      g_free (sent);
      return NULL;
    }

  directory = g_dir_open (sys_dir_name, 0, &error);
  if (!directory)
    {
      cmpl_errno = error->code; /* ??? */
      g_free (sys_dir_name);
      g_free (sent);
      return NULL;
    }

  while ((dirent = g_dir_read_name (directory)) != NULL)
    entry_count++;
  entry_count += 2;		/* For ".",".." */

  sent->entries = g_new (CompletionDirEntry, entry_count);
  sent->entry_count = entry_count;

  g_dir_rewind (directory);

  for (i = 0; i < entry_count; i += 1)
    {
      GError *error = NULL;

      if (i == 0)
	dirent = ".";
      else if (i == 1)
	dirent = "..";
      else
	{
	  dirent = g_dir_read_name (directory);
	  if (!dirent)		/* Directory changed */
	    break;
	}

      sent->entries[n_entries].entry_name = g_filename_to_utf8 (dirent, -1, NULL, NULL, &error);
      if (sent->entries[n_entries].entry_name == NULL
	  || !g_utf8_validate (sent->entries[n_entries].entry_name, -1, NULL))
	{
	  gchar *escaped_str = g_strescape (dirent, NULL);
	  g_message (_("The filename \"%s\" couldn't be converted to UTF-8. "
		       "(try setting the environment variable G_FILENAME_ENCODING): %s"),
		     escaped_str,
		     error->message ? error->message : _("Invalid UTF-8"));
	  g_free (escaped_str);
	  g_clear_error (&error);
	  continue;
	}
      g_clear_error (&error);
      
      sent->entries[n_entries].sort_key = g_utf8_collate_key (sent->entries[n_entries].entry_name, -1);
      
      g_string_assign (path, sys_dir_name);
      if (path->str[path->len-1] != G_DIR_SEPARATOR)
	{
	  g_string_append_c (path, G_DIR_SEPARATOR);
	}
      g_string_append (path, dirent);

      if (stat_subdirs)
	{
	  /* Here we know path->str is a "system charset" string */
	  if (g_stat (path->str, &ent_sbuf) >= 0 && S_ISDIR (ent_sbuf.st_mode))
	    sent->entries[n_entries].is_dir = TRUE;
	  else
	    /* stat may fail, and we don't mind, since it could be a
	     * dangling symlink. */
	    sent->entries[n_entries].is_dir = FALSE;
	}
      else
	sent->entries[n_entries].is_dir = 1;

      n_entries++;
    }
  sent->entry_count = n_entries;
  
  g_free (sys_dir_name);
  g_string_free (path, TRUE);
  qsort (sent->entries, sent->entry_count, sizeof (CompletionDirEntry), compare_cmpl_dir);

  g_dir_close (directory);

  return sent;
}

#ifndef G_PLATFORM_WIN32

static gboolean
check_dir (gchar    *dir_name,
	   GStatBuf *result,
	   gboolean *stat_subdirs)
{
  /* A list of directories that we know only contain other directories.
   * Trying to stat every file in these directories would be very
   * expensive.
   */

  static struct {
    const gchar name[5];
    gboolean present;
    GStatBuf statbuf;
  } no_stat_dirs[] = {
    { "/afs", FALSE, { 0 } },
    { "/net", FALSE, { 0 } }
  };

  static const gint n_no_stat_dirs = G_N_ELEMENTS (no_stat_dirs);
  static gboolean initialized = FALSE;
  gchar *sys_dir_name;
  gint i;

  if (!initialized)
    {
      initialized = TRUE;
      for (i = 0; i < n_no_stat_dirs; i++)
	{
	  if (g_stat (no_stat_dirs[i].name, &no_stat_dirs[i].statbuf) == 0)
	    no_stat_dirs[i].present = TRUE;
	}
    }

  sys_dir_name = g_filename_from_utf8 (dir_name, -1, NULL, NULL, NULL);
  if (!sys_dir_name)
    {
      cmpl_errno = CMPL_ERRNO_DID_NOT_CONVERT;
      return FALSE;
    }
  
  if (g_stat (sys_dir_name, result) < 0)
    {
      g_free (sys_dir_name);
      cmpl_errno = errno;
      return FALSE;
    }
  g_free (sys_dir_name);

  *stat_subdirs = TRUE;
  for (i = 0; i < n_no_stat_dirs; i++)
    {
      if (no_stat_dirs[i].present &&
	  (no_stat_dirs[i].statbuf.st_dev == result->st_dev) &&
	  (no_stat_dirs[i].statbuf.st_ino == result->st_ino))
	{
	  *stat_subdirs = FALSE;
	  break;
	}
    }

  return TRUE;
}

#endif

/* open a directory by absolute pathname */
static CompletionDir*
open_dir (gchar           *dir_name,
	  CompletionState *cmpl_state)
{
#ifndef G_PLATFORM_WIN32
  GStatBuf sbuf;
  gboolean stat_subdirs;
  GList* cdsl;
#endif
  CompletionDirSent *sent;

#ifndef G_PLATFORM_WIN32
  if (!check_dir (dir_name, &sbuf, &stat_subdirs))
    return NULL;

  cdsl = cmpl_state->directory_sent_storage;

  while (cdsl)
    {
      sent = cdsl->data;

      if (sent->inode == sbuf.st_ino &&
	  sent->mtime == sbuf.st_mtime &&
	  sent->device == sbuf.st_dev)
	return attach_dir (sent, dir_name, cmpl_state);

      cdsl = cdsl->next;
    }

  sent = open_new_dir (dir_name, &sbuf, stat_subdirs);
#else
  sent = open_new_dir (dir_name, NULL, TRUE);
#endif

  if (sent)
    {
      cmpl_state->directory_sent_storage =
	g_list_prepend (cmpl_state->directory_sent_storage, sent);

      return attach_dir (sent, dir_name, cmpl_state);
    }

  return NULL;
}

static CompletionDir*
attach_dir (CompletionDirSent *sent,
	    gchar             *dir_name,
	    CompletionState   *cmpl_state)
{
  CompletionDir* new_dir;

  new_dir = g_new (CompletionDir, 1);

  cmpl_state->directory_storage =
    g_list_prepend (cmpl_state->directory_storage, new_dir);

  new_dir->sent = sent;
  new_dir->fullname = g_strdup (dir_name);
  new_dir->fullname_len = strlen (dir_name);
  new_dir->cmpl_text = NULL;

  return new_dir;
}

static gint
correct_dir_fullname (CompletionDir* cmpl_dir)
{
  gint length = strlen (cmpl_dir->fullname);
  gchar *first_slash = strchr (cmpl_dir->fullname, G_DIR_SEPARATOR);
  gchar *sys_filename;
  GStatBuf sbuf;

  /* Does it end with /. (\.) ? */
  if (length >= 2 &&
      strcmp (cmpl_dir->fullname + length - 2, G_DIR_SEPARATOR_S ".") == 0)
    {
      /* Is it just the root directory (on a drive) ? */
      if (cmpl_dir->fullname + length - 2 == first_slash)
	{
	  cmpl_dir->fullname[length - 1] = 0;
	  cmpl_dir->fullname_len = length - 1;
	  return TRUE;
	}
      else
	{
	  cmpl_dir->fullname[length - 2] = 0;
	}
    }

  /* Ends with /./ (\.\)? */
  else if (length >= 3 &&
	   strcmp (cmpl_dir->fullname + length - 3,
		   G_DIR_SEPARATOR_S "." G_DIR_SEPARATOR_S) == 0)
    cmpl_dir->fullname[length - 2] = 0;

  /* Ends with /.. (\..) ? */
  else if (length >= 3 &&
	   strcmp (cmpl_dir->fullname + length - 3,
		   G_DIR_SEPARATOR_S "..") == 0)
    {
      /* Is it just /.. (X:\..)? */
      if (cmpl_dir->fullname + length - 3 == first_slash)
	{
	  cmpl_dir->fullname[length - 2] = 0;
	  cmpl_dir->fullname_len = length - 2;
	  return TRUE;
	}

      sys_filename = g_filename_from_utf8 (cmpl_dir->fullname, -1, NULL, NULL, NULL);
      if (!sys_filename)
	{
	  cmpl_errno = CMPL_ERRNO_DID_NOT_CONVERT;
	  return FALSE;
	}
      
      if (g_stat (sys_filename, &sbuf) < 0)
	{
	  g_free (sys_filename);
	  cmpl_errno = errno;
	  return FALSE;
	}
      g_free (sys_filename);

      cmpl_dir->fullname[length - 3] = 0;

      if (!correct_parent (cmpl_dir, &sbuf))
	return FALSE;
    }

  /* Ends with /../ (\..\)? */
  else if (length >= 4 &&
	   strcmp (cmpl_dir->fullname + length - 4,
		   G_DIR_SEPARATOR_S ".." G_DIR_SEPARATOR_S) == 0)
    {
      /* Is it just /../ (X:\..\)? */
      if (cmpl_dir->fullname + length - 4 == first_slash)
	{
	  cmpl_dir->fullname[length - 3] = 0;
	  cmpl_dir->fullname_len = length - 3;
	  return TRUE;
	}

      sys_filename = g_filename_from_utf8 (cmpl_dir->fullname, -1, NULL, NULL, NULL);
      if (!sys_filename)
	{
	  cmpl_errno = CMPL_ERRNO_DID_NOT_CONVERT;
	  return FALSE;
	}
      
      if (g_stat (sys_filename, &sbuf) < 0)
	{
	  g_free (sys_filename);
	  cmpl_errno = errno;
	  return FALSE;
	}
      g_free (sys_filename);

      cmpl_dir->fullname[length - 4] = 0;

      if (!correct_parent (cmpl_dir, &sbuf))
	return FALSE;
    }

  cmpl_dir->fullname_len = strlen (cmpl_dir->fullname);

  return TRUE;
}

static gint
correct_parent (CompletionDir *cmpl_dir,
		GStatBuf      *sbuf)
{
  GStatBuf parbuf;
  gchar *last_slash;
  gchar *first_slash;
#ifndef G_PLATFORM_WIN32
  gchar *new_name;
#endif
  gchar *sys_filename;
  gchar c = 0;

  last_slash = strrchr (cmpl_dir->fullname, G_DIR_SEPARATOR);
  g_assert (last_slash);
  first_slash = strchr (cmpl_dir->fullname, G_DIR_SEPARATOR);

  /* Clever (?) way to check for top-level directory that works also on
   * Win32, where there is a drive letter and colon prefixed...
   */
  if (last_slash != first_slash)
    {
      last_slash[0] = 0;
    }
  else
    {
      c = last_slash[1];
      last_slash[1] = 0;
    }

  sys_filename = g_filename_from_utf8 (cmpl_dir->fullname, -1, NULL, NULL, NULL);
  if (!sys_filename)
    {
      cmpl_errno = CMPL_ERRNO_DID_NOT_CONVERT;
      if (!c)
	last_slash[0] = G_DIR_SEPARATOR;
      return FALSE;
    }
  
  if (g_stat (sys_filename, &parbuf) < 0)
    {
      g_free (sys_filename);
      cmpl_errno = errno;
      if (!c)
	last_slash[0] = G_DIR_SEPARATOR;
      return FALSE;
    }
  g_free (sys_filename);

#ifndef G_PLATFORM_WIN32	/* No inode numbers on Win32 */
  if (parbuf.st_ino == sbuf->st_ino && parbuf.st_dev == sbuf->st_dev)
    /* it wasn't a link */
    return TRUE;

  if (c)
    last_slash[1] = c;
  else
    last_slash[0] = G_DIR_SEPARATOR;

  /* it was a link, have to figure it out the hard way */

  new_name = find_parent_dir_fullname (cmpl_dir->fullname);

  if (!new_name)
    return FALSE;

  g_free (cmpl_dir->fullname);

  cmpl_dir->fullname = new_name;
#endif

  return TRUE;
}

#ifndef G_PLATFORM_WIN32

static gchar*
find_parent_dir_fullname (gchar* dirname)
{
  gchar *sys_orig_dir;
  gchar *result;
  gchar *sys_cwd;
  gchar *sys_dirname;

  sys_orig_dir = g_get_current_dir ();
  sys_dirname = g_filename_from_utf8 (dirname, -1, NULL, NULL, NULL);
  if (!sys_dirname)
    {
      g_free (sys_orig_dir);
      cmpl_errno = CMPL_ERRNO_DID_NOT_CONVERT;
      return NULL;
    }
  
  if (chdir (sys_dirname) != 0 || chdir ("..") != 0)
    {
      int ignored;

      cmpl_errno = errno;
      ignored = g_chdir (sys_orig_dir);
      g_free (sys_dirname);
      g_free (sys_orig_dir);
      return NULL;
    }
  g_free (sys_dirname);

  sys_cwd = g_get_current_dir ();
  result = g_filename_to_utf8 (sys_cwd, -1, NULL, NULL, NULL);
  g_free (sys_cwd);

  if (chdir (sys_orig_dir) != 0)
    {
      cmpl_errno = errno;
      g_free (sys_orig_dir);
      return NULL;
    }

  g_free (sys_orig_dir);
  return result;
}

#endif

/**********************************************************************/
/*                        Completion Operations                       */
/**********************************************************************/

#ifdef HAVE_PWD_H

static PossibleCompletion*
attempt_homedir_completion (gchar           *text_to_complete,
			    CompletionState *cmpl_state)
{
  gint index;

  if (!cmpl_state->user_dir_name_buffer &&
      !get_pwdb (cmpl_state))
    return NULL;

  cmpl_state->user_completion_index += 1;

  while (cmpl_state->user_completion_index < cmpl_state->user_directories_len)
    {
      index = first_diff_index (text_to_complete + 1,
				cmpl_state->user_directories
				[cmpl_state->user_completion_index].login);

      switch (index)
	{
	case PATTERN_MATCH:
	  break;
	default:
	  if (cmpl_state->last_valid_char < (index + 1))
	    cmpl_state->last_valid_char = index + 1;
	  cmpl_state->user_completion_index += 1;
	  continue;
	}

      cmpl_state->the_completion.is_a_completion = 1;
      cmpl_state->the_completion.is_directory = TRUE;

      append_completion_text ("~", cmpl_state);

      append_completion_text (cmpl_state->
			      user_directories[cmpl_state->user_completion_index].login,
			      cmpl_state);

      return append_completion_text (G_DIR_SEPARATOR_S, cmpl_state);
    }

  if (text_to_complete[1]
      || cmpl_state->user_completion_index > cmpl_state->user_directories_len)
    {
      cmpl_state->user_completion_index = -1;
      return NULL;
    }
  else
    {
      cmpl_state->user_completion_index += 1;
      cmpl_state->the_completion.is_a_completion = 1;
      cmpl_state->the_completion.is_directory = TRUE;

      return append_completion_text ("~" G_DIR_SEPARATOR_S, cmpl_state);
    }
}

#endif

#ifdef G_PLATFORM_WIN32
/* FIXME: determine whether we should casefold all Unicode letters
 * here, too (and in in first_diff_index() walk through the strings with
 * g_utf8_next_char()), or if this folding isn't actually needed at
 * all.
 */
#define FOLD(c) (tolower(c))
#else
#define FOLD(c) (c)
#endif

/* returns the index (>= 0) of the first differing character,
 * PATTERN_MATCH if the completion matches */
static gint
first_diff_index (gchar *pat,
		  gchar *text)
{
  gint diff = 0;

  while (*pat && *text && FOLD (*text) == FOLD (*pat))
    {
      pat += 1;
      text += 1;
      diff += 1;
    }

  if (*pat)
    return diff;

  return PATTERN_MATCH;
}

static PossibleCompletion*
append_completion_text (gchar           *text,
			CompletionState *cmpl_state)
{
  gint len, i = 1;

  if (!cmpl_state->the_completion.text)
    return NULL;

  len = strlen (text) + strlen (cmpl_state->the_completion.text) + 1;

  if (cmpl_state->the_completion.text_alloc > len)
    {
      strcat (cmpl_state->the_completion.text, text);
      return &cmpl_state->the_completion;
    }

  while (i < len)
    i <<= 1;

  cmpl_state->the_completion.text_alloc = i;

  cmpl_state->the_completion.text = (gchar*) g_realloc (cmpl_state->the_completion.text, i);

  if (!cmpl_state->the_completion.text)
    return NULL;
  else
    {
      strcat (cmpl_state->the_completion.text, text);
      return &cmpl_state->the_completion;
    }
}

static CompletionDir*
find_completion_dir (gchar          *text_to_complete,
		    gchar          **remaining_text,
		    CompletionState *cmpl_state)
{
  gchar* first_slash = strchr (text_to_complete, G_DIR_SEPARATOR);
  CompletionDir* dir = cmpl_state->reference_dir;
  CompletionDir* next;
  *remaining_text = text_to_complete;

  while (first_slash)
    {
      gint len = first_slash - *remaining_text;
      gint found = 0;
      gchar *found_name = NULL;         /* Quiet gcc */
      gint i;
      gchar* pat_buf = g_new (gchar, len + 1);

      strncpy (pat_buf, *remaining_text, len);
      pat_buf[len] = 0;

      for (i = 0; i < dir->sent->entry_count; i += 1)
	{
	  if (dir->sent->entries[i].is_dir &&
	      _gtk_fnmatch (pat_buf, dir->sent->entries[i].entry_name, TRUE))
	    {
	      if (found)
		{
		  g_free (pat_buf);
		  return dir;
		}
	      else
		{
		  found = 1;
		  found_name = dir->sent->entries[i].entry_name;
		}
	    }
	}

      if (!found)
	{
	  /* Perhaps we are trying to open an automount directory */
	  found_name = pat_buf;
	}

      next = open_relative_dir (found_name, dir, cmpl_state);
      
      if (!next)
	{
	  g_free (pat_buf);
	  return NULL;
}
      
      next->cmpl_parent = dir;
      
      dir = next;
      
      if (!correct_dir_fullname (dir))
	{
	  g_free (pat_buf);
	  return NULL;
	}
      
      *remaining_text = first_slash + 1;
      first_slash = strchr (*remaining_text, G_DIR_SEPARATOR);

      g_free (pat_buf);
    }

  return dir;
}

static void
update_cmpl (PossibleCompletion *poss,
	     CompletionState    *cmpl_state)
{
  gint cmpl_len;

  if (!poss || !cmpl_is_a_completion (poss))
    return;

  cmpl_len = strlen (cmpl_this_completion (poss));

  if (cmpl_state->updated_text_alloc < cmpl_len + 1)
    {
      cmpl_state->updated_text_alloc = 2*cmpl_len;
      cmpl_state->updated_text =
	(gchar*)g_realloc (cmpl_state->updated_text,
			   cmpl_state->updated_text_alloc);
    }

  if (cmpl_state->updated_text_len < 0)
    {
      strcpy (cmpl_state->updated_text, cmpl_this_completion (poss));
      cmpl_state->updated_text_len = cmpl_len;
      cmpl_state->re_complete = cmpl_is_directory (poss);
    }
  else if (cmpl_state->updated_text_len == 0)
    {
      cmpl_state->re_complete = FALSE;
    }
  else
    {
      gint first_diff =
	first_diff_index (cmpl_state->updated_text,
			  cmpl_this_completion (poss));

      cmpl_state->re_complete = FALSE;

      if (first_diff == PATTERN_MATCH)
	return;

      if (first_diff > cmpl_state->updated_text_len)
	strcpy (cmpl_state->updated_text, cmpl_this_completion (poss));

      cmpl_state->updated_text_len = first_diff;
      cmpl_state->updated_text[first_diff] = 0;
    }
}

static PossibleCompletion*
attempt_file_completion (CompletionState *cmpl_state)
{
  gchar *pat_buf, *first_slash;
  CompletionDir *dir = cmpl_state->active_completion_dir;

  dir->cmpl_index += 1;

  if (dir->cmpl_index == dir->sent->entry_count)
    {
      if (dir->cmpl_parent == NULL)
	{
	  cmpl_state->active_completion_dir = NULL;

	  return NULL;
	}
      else
	{
	  cmpl_state->active_completion_dir = dir->cmpl_parent;

	  return attempt_file_completion (cmpl_state);
	}
    }

  g_assert (dir->cmpl_text);

  first_slash = strchr (dir->cmpl_text, G_DIR_SEPARATOR);

  if (first_slash)
    {
      gint len = first_slash - dir->cmpl_text;

      pat_buf = g_new (gchar, len + 1);
      strncpy (pat_buf, dir->cmpl_text, len);
      pat_buf[len] = 0;
    }
  else
    {
      gint len = strlen (dir->cmpl_text);

      pat_buf = g_new (gchar, len + 2);
      strcpy (pat_buf, dir->cmpl_text);
      /* Don't append a * if the user entered one herself.
       * This way one can complete *.h and don't get matches
       * on any .help files, for instance.
       */
      if (strchr (pat_buf, '*') == NULL)
	strcpy (pat_buf + len, "*");
    }

  if (first_slash)
    {
      if (dir->sent->entries[dir->cmpl_index].is_dir)
	{
	  if (_gtk_fnmatch (pat_buf, dir->sent->entries[dir->cmpl_index].entry_name, TRUE))
	    {
	      CompletionDir* new_dir;

	      new_dir = open_relative_dir (dir->sent->entries[dir->cmpl_index].entry_name,
					   dir, cmpl_state);

	      if (!new_dir)
		{
		  g_free (pat_buf);
		  return NULL;
		}

	      new_dir->cmpl_parent = dir;

	      new_dir->cmpl_index = -1;
	      new_dir->cmpl_text = g_strdup (first_slash + 1);

	      cmpl_state->active_completion_dir = new_dir;

	      g_free (pat_buf);
	      return attempt_file_completion (cmpl_state);
	    }
	  else
	    {
	      g_free (pat_buf);
	      return attempt_file_completion (cmpl_state);
	    }
	}
      else
	{
	  g_free (pat_buf);
	  return attempt_file_completion (cmpl_state);
	}
    }
  else
    {
      if (dir->cmpl_parent != NULL)
	{
	  append_completion_text (dir->fullname +
				  strlen (cmpl_state->completion_dir->fullname) + 1,
				  cmpl_state);
	  append_completion_text (G_DIR_SEPARATOR_S, cmpl_state);
	}

      append_completion_text (dir->sent->entries[dir->cmpl_index].entry_name, cmpl_state);

      cmpl_state->the_completion.is_a_completion =
	_gtk_fnmatch (pat_buf, dir->sent->entries[dir->cmpl_index].entry_name, TRUE);

      cmpl_state->the_completion.is_directory = dir->sent->entries[dir->cmpl_index].is_dir;
      if (dir->sent->entries[dir->cmpl_index].is_dir)
	append_completion_text (G_DIR_SEPARATOR_S, cmpl_state);

      g_free (pat_buf);
      return &cmpl_state->the_completion;
    }
}

#ifdef HAVE_PWD_H

static gint
get_pwdb (CompletionState* cmpl_state)
{
  struct passwd *pwd_ptr;
  gchar* buf_ptr;
  gchar *utf8;
  gint len = 0, i, count = 0;

  if (cmpl_state->user_dir_name_buffer)
    return TRUE;
  setpwent ();

  while ((pwd_ptr = getpwent ()) != NULL)
    {
      utf8 = g_filename_to_utf8 (pwd_ptr->pw_name, -1, NULL, NULL, NULL);
      len += strlen (utf8);
      g_free (utf8);
      utf8 = g_filename_to_utf8 (pwd_ptr->pw_dir, -1, NULL, NULL, NULL);
      len += strlen (utf8);
      g_free (utf8);
      len += 2;
      count += 1;
    }

  setpwent ();

  cmpl_state->user_dir_name_buffer = g_new (gchar, len);
  cmpl_state->user_directories = g_new (CompletionUserDir, count);
  cmpl_state->user_directories_len = count;

  buf_ptr = cmpl_state->user_dir_name_buffer;

  for (i = 0; i < count; i += 1)
    {
      pwd_ptr = getpwent ();
      if (!pwd_ptr)
	{
	  cmpl_errno = errno;
	  goto error;
	}

      utf8 = g_filename_to_utf8 (pwd_ptr->pw_name, -1, NULL, NULL, NULL);
      strcpy (buf_ptr, utf8);
      g_free (utf8);

      cmpl_state->user_directories[i].login = buf_ptr;

      buf_ptr += strlen (buf_ptr);
      buf_ptr += 1;

      utf8 = g_filename_to_utf8 (pwd_ptr->pw_dir, -1, NULL, NULL, NULL);
      strcpy (buf_ptr, utf8);
      g_free (utf8);

      cmpl_state->user_directories[i].homedir = buf_ptr;

      buf_ptr += strlen (buf_ptr);
      buf_ptr += 1;
    }

  qsort (cmpl_state->user_directories,
	 cmpl_state->user_directories_len,
	 sizeof (CompletionUserDir),
	 compare_user_dir);

  endpwent ();

  return TRUE;

error:

  g_free (cmpl_state->user_dir_name_buffer);
  g_free (cmpl_state->user_directories);

  cmpl_state->user_dir_name_buffer = NULL;
  cmpl_state->user_directories = NULL;

  return FALSE;
}

static gint
compare_user_dir (const void *a,
		  const void *b)
{
  return strcmp ((((CompletionUserDir*)a))->login,
		 (((CompletionUserDir*)b))->login);
}

#endif

static gint
compare_cmpl_dir (const void *a,
		  const void *b)
{
  
  return strcmp (((CompletionDirEntry*)a)->sort_key,
		 (((CompletionDirEntry*)b))->sort_key);
}

static gint
cmpl_state_okay (CompletionState* cmpl_state)
{
  return  cmpl_state && cmpl_state->reference_dir;
}

static const gchar*
cmpl_strerror (gint err)
{
  if (err == CMPL_ERRNO_TOO_LONG)
    return _("Name too long");
  else if (err == CMPL_ERRNO_DID_NOT_CONVERT)
    return _("Couldn't convert filename");
  else
    return g_strerror (err);
}

#if defined (G_OS_WIN32) && !defined (_WIN64)

/* DLL ABI stability backward compatibility versions */

#undef gtk_file_selection_get_filename

const gchar*
gtk_file_selection_get_filename (GtkFileSelection *filesel)
{
  static gchar retval[MAXPATHLEN*2+1];
  gchar *tem;

  tem = g_locale_from_utf8 (gtk_file_selection_get_filename_utf8 (filesel),
			    -1, NULL, NULL, NULL);

  strncpy (retval, tem, sizeof (retval) - 1);
  retval[sizeof (retval) - 1] = '\0';
  g_free (tem);

  return retval;
}

#undef gtk_file_selection_set_filename

void
gtk_file_selection_set_filename (GtkFileSelection *filesel,
				 const gchar      *filename)
{
  gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
  gtk_file_selection_set_filename_utf8 (filesel, utf8_filename);
  g_free (utf8_filename);
}

#undef gtk_file_selection_get_selections

gchar **
gtk_file_selection_get_selections (GtkFileSelection *filesel)
{
  int i = 0;
  gchar **selections = gtk_file_selection_get_selections_utf8 (filesel);

  if (selections != NULL)
    while (selections[i] != NULL)
      {
	gchar *tem = selections[i];
	selections[i] = g_locale_from_utf8 (selections[i],
					    -1, NULL, NULL, NULL);
	g_free (tem);
	i++;
      }

  return selections;
}

#endif /* G_OS_WIN32 && !_WIN64 */

#define __GTK_FILESEL_C__
#include "gtkaliasdef.c"