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
/* CTK - The GIMP Toolkit
 * ctkfilesystemmodel.c: CtkTreeModel wrapping a CtkFileSystem
 * Copyright (C) 2003, Red Hat, Inc.
 *
 * 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, see <http://www.gnu.org/licenses/>.
 */

#include "config.h"

#include "ctkfilesystemmodel.h"

#include <stdlib.h>
#include <string.h>

#include "ctkfilesystem.h"
#include "ctkintl.h"
#include "ctkmarshalers.h"
#include "ctktreedatalist.h"
#include "ctktreednd.h"
#include "ctktreemodel.h"

/*** Structure: how CtkFileSystemModel works
 *
 * This is a custom CtkTreeModel used to hold a collection of files for CtkFileChooser.  There are two use cases:
 *
 *   1. The model populates itself from a folder, using the GIO file enumerator API.  This happens if you use
 *      _ctk_file_system_model_new_for_directory().  This is the normal usage for showing the contents of a folder.
 *
 *   2. The caller populates the model by hand, with files not necessarily in the same folder.  This happens
 *      if you use _ctk_file_system_model_new() and then _ctk_file_system_model_add_and_query_file().  This is
 *      the special kind of usage for “search” and “recent-files”, where the file chooser gives the model the
 *      files to be displayed.
 *
 * Internal data structure
 * -----------------------
 *
 * Each file is kept in a FileModelNode structure.  Each FileModelNode holds a GFile* and other data.  All the
 * node structures have the same size, determined at runtime, depending on the number of columns that were passed
 * to _ctk_file_system_model_new() or _ctk_file_system_model_new_for_directory() (that is, the size of a node is
 * not sizeof (FileModelNode), but rather model->node_size).  The last field in the FileModelNode structure,
 * node->values[], is an array of GValue, used to hold the data for those columns.
 *
 * The model stores an array of FileModelNode structures in model->files.  This is a GArray where each element is
 * model->node_size bytes in size (the model computes that node size when initializing itself).  There are
 * convenience macros, get_node() and node_index(), to access that array based on an array index or a pointer to
 * a node inside the array.
 *
 * The model accesses files through two of its fields:
 *
 *   model->files - GArray of FileModelNode structures.
 *
 *   model->file_lookup - hash table that maps a GFile* to an index inside the model->files array.
 *
 * The model->file_lookup hash table is populated lazily.  It is both accessed and populated with the
 * node_get_for_file() function.  The invariant is that the files in model->files[n] for n < g_hash_table_size
 * (model->file_lookup) are already added to the hash table. The hash table will get cleared when we re-sort the
 * files, as the array will be in a different order and the indexes need to be rebuilt.
 *
 * Each FileModelNode has a node->visible field, which indicates whether the node is visible in the CtkTreeView.
 * A node may be invisible if, for example, it corresponds to a hidden file and the file chooser is not showing
 * hidden files.  Also, a file filter may be explicitly set onto the model, for example, to only show files that
 * match “*.jpg”.  In this case, node->filtered_out says whether the node failed the filter.  The ultimate
 * decision on whether a node is visible or not in the treeview is distilled into the node->visible field.
 * The reason for having a separate node->filtered_out field is so that the file chooser can query whether
 * a (filtered-out) folder should be made sensitive in the GUI.
 *
 * Visible rows vs. possibly-invisible nodes
 * -----------------------------------------
 *
 * Since not all nodes in the model->files array may be visible, we need a way to map visible row indexes from
 * the treeview to array indexes in our array of files.  And thus we introduce a bit of terminology:
 *
 *   index - An index in the model->files array.  All variables/fields that represent indexes are either called
 *   “index” or “i_*”, or simply “i” for things like loop counters.
 *
 *   row - An index in the CtkTreeView, i.e. the index of a row within the outward-facing API of the
 *   CtkFileSystemModel.  However, note that our rows are 1-based, not 0-based, for the reason explained in the
 *   following paragraph.  Variables/fields that represent visible rows are called “row”, or “r_*”, or simply
 *   “r”.
 *
 * Each FileModelNode has a node->row field which is the number of visible rows in the treeview, *before and
 * including* that node.  This means that node->row is 1-based, instead of 0-based --- this makes some code
 * simpler, believe it or not :)  This also means that when the calling CtkTreeView gives us a CtkTreePath, we
 * turn the 0-based treepath into a 1-based row for our purposes.  If a node is not visible, it will have the
 * same row number as its closest preceding visible node.
 *
 * We try to compute the node->row fields lazily.  A node is said to be “valid” if its node->row is accurate.
 * For this, the model keeps a model->n_nodes_valid field which is the count of valid nodes starting from the
 * beginning of the model->files array.  When a node changes its information, or when a node gets deleted, that
 * node and the following ones get invalidated by simply setting model->n_nodes_valid to the array index of the
 * node.  If the model happens to need a node’s row number and that node is in the model->files array after
 * model->n_nodes_valid, then the nodes get re-validated up to the sought node.  See node_validate_rows() for
 * this logic.
 *
 * You never access a node->row directly.  Instead, call node_get_tree_row().  That function will validate the nodes
 * up to the sought one if the node is not valid yet, and it will return a proper 0-based row.
 *
 * Sorting
 * -------
 *
 * The model implements the CtkTreeSortable interface.  To avoid re-sorting
 * every time a node gets added (which would lead to O(n^2) performance during
 * the initial population of the model), the model can freeze itself (with
 * freeze_updates()) during the intial population process.  When the model is
 * frozen, sorting will not happen.  The model will sort itself when the freeze
 * count goes back to zero, via corresponding calls to thaw_updates().
 */

/*** DEFINES ***/

/* priority used for all async callbacks in the main loop
 * This should be higher than redraw priorities so multiple callbacks
 * firing can be handled without intermediate redraws */
#define IO_PRIORITY G_PRIORITY_DEFAULT

/* random number that everyone else seems to use, too */
#define FILES_PER_QUERY 100

typedef struct _FileModelNode           FileModelNode;
typedef struct _CtkFileSystemModelClass CtkFileSystemModelClass;

struct _FileModelNode
{
  GFile *               file;           /* file represented by this node or NULL for editable */
  GFileInfo *           info;           /* info for this file or NULL if unknown */

  guint                 row;            /* if valid (see model->n_valid_indexes), visible nodes before and including
					 * this one - see the "Structure" comment above.
					 */

  guint                 visible :1;     /* if the file is currently visible */
  guint                 filtered_out :1;/* if the file is currently filtered out (i.e. it didn't pass the filters) */
  guint                 frozen_add :1;  /* true if the model was frozen and the entry has not been added yet */

  GValue                values[1];      /* actually n_columns values */
};

struct _CtkFileSystemModel
{
  GObject               parent_instance;

  GFile *               dir;            /* directory that's displayed */
  guint                 dir_thaw_source;/* GSource id for unfreezing the model */
  char *                attributes;     /* attributes the file info must contain, or NULL for all attributes */
  GFileMonitor *        dir_monitor;    /* directory that is monitored, or NULL if monitoring was not supported */

  GCancellable *        cancellable;    /* cancellable in use for all operations - cancelled on dispose */
  GArray *              files;          /* array of FileModelNode containing all our files */
  gsize                 node_size;	/* Size of a FileModelNode structure once its ->values field has n_columns */
  guint                 n_nodes_valid;  /* count of valid nodes (i.e. those whose node->row is accurate) */
  GHashTable *          file_lookup;    /* mapping of GFile => array index in model->files
					 * This hash table doesn't always have the same number of entries as the files array;
					 * it can get cleared completely when we resort.
					 * The hash table gets re-populated in node_get_for_file() if this mismatch is
					 * detected.
					 */

  guint                 n_columns;      /* number of columns */
  GType *               column_types;   /* types of each column */
  CtkFileSystemModelGetValue get_func;  /* function to call to fill in values in columns */
  gpointer              get_data;       /* data to pass to get_func */

  CtkFileFilter *       filter;         /* filter to use for deciding which nodes are visible */

  int                   sort_column_id; /* current sorting column */
  CtkSortType           sort_order;     /* current sorting order */
  GList *               sort_list;      /* list of sorting functions */
  CtkTreeIterCompareFunc default_sort_func; /* default sort function */
  gpointer              default_sort_data; /* data to pass to default sort func */
  GDestroyNotify        default_sort_destroy; /* function to call to destroy default_sort_data */

  guint                 frozen;         /* number of times we're frozen */

  gboolean              filter_on_thaw :1;/* set when filtering needs to happen upon thawing */
  gboolean              sort_on_thaw :1;/* set when sorting needs to happen upon thawing */

  guint                 show_hidden :1; /* whether to show hidden files */
  guint                 show_folders :1;/* whether to show folders */
  guint                 show_files :1;  /* whether to show files */
  guint                 filter_folders :1;/* whether filter applies to folders */
};

#define CTK_FILE_SYSTEM_MODEL_CLASS(klass)     (G_TYPE_CHECK_CLASS_CAST ((klass), CTK_TYPE_FILE_SYSTEM_MODEL, CtkFileSystemModelClass))
#define CTK_IS_FILE_SYSTEM_MODEL_CLASS(klass)  (G_TYPE_CHECK_CLASS_TYPE ((klass), CTK_TYPE_FILE_SYSTEM_MODEL))
#define CTK_FILE_SYSTEM_MODEL_GET_CLASS(obj)   (G_TYPE_INSTANCE_GET_CLASS ((obj), CTK_TYPE_FILE_SYSTEM_MODEL, CtkFileSystemModelClass))

struct _CtkFileSystemModelClass
{
  GObjectClass parent_class;

  /* Signals */

  void (*finished_loading) (CtkFileSystemModel *model, GError *error);
};

static void freeze_updates (CtkFileSystemModel *model);
static void thaw_updates (CtkFileSystemModel *model);

static guint node_get_for_file (CtkFileSystemModel *model,
				GFile              *file);

static void add_file (CtkFileSystemModel *model,
		      GFile              *file,
		      GFileInfo          *info);
static void remove_file (CtkFileSystemModel *model,
			 GFile              *file);

/* iter setup:
 * @user_data: the model
 * @user_data2: GUINT_TO_POINTER of array index of current entry
 *
 * All other fields are unused. Note that the array index does not corrspond
 * 1:1 with the path index as entries might not be visible.
 */
#define ITER_INDEX(iter) GPOINTER_TO_UINT((iter)->user_data2)
#define ITER_IS_VALID(model, iter) ((model) == (iter)->user_data)
#define ITER_INIT_FROM_INDEX(model, _iter, _index) G_STMT_START {\
  g_assert (_index < (model)->files->len); \
  (_iter)->user_data = (model); \
  (_iter)->user_data2 = GUINT_TO_POINTER (_index); \
}G_STMT_END

/*** FileModelNode ***/

/* Get a FileModelNode structure given an index in the model->files array of nodes */
#define get_node(_model, _index) ((FileModelNode *) ((_model)->files->data + (_index) * (_model)->node_size))

/* Get an index within the model->files array of nodes, given a FileModelNode* */
#define node_index(_model, _node) (((gchar *) (_node) - (_model)->files->data) / (_model)->node_size)

/* @up_to_index: smallest model->files array index that will be valid after this call
 * @up_to_row: smallest node->row that will be valid after this call
 *
 * If you want to validate up to an index or up to a row, specify the index or
 * the row you want and specify G_MAXUINT for the other argument.  Pass
 * G_MAXUINT for both arguments for “validate everything”.
 */
static void
node_validate_rows (CtkFileSystemModel *model, guint up_to_index, guint up_to_row)
{
  guint i, row;

  if (model->files->len == 0)
    return;

  up_to_index = MIN (up_to_index, model->files->len - 1);

  i = model->n_nodes_valid;
  if (i != 0)
    row = get_node (model, i - 1)->row;
  else
    row = 0;

  while (i <= up_to_index && row <= up_to_row)
    {
      FileModelNode *node = get_node (model, i);
      if (node->visible)
        row++;
      node->row = row;
      i++;
    }
  model->n_nodes_valid = i;
}

static guint
node_get_tree_row (CtkFileSystemModel *model, guint index)
{
  if (model->n_nodes_valid <= index)
    node_validate_rows (model, index, G_MAXUINT);

  return get_node (model, index)->row - 1;
}

static void 
node_invalidate_index (CtkFileSystemModel *model, guint id)
{
  model->n_nodes_valid = MIN (model->n_nodes_valid, id);
}

static CtkTreePath *
tree_path_new_from_node (CtkFileSystemModel *model, guint id)
{
  guint r = node_get_tree_row (model, id);

  g_assert (r < model->files->len);

  return ctk_tree_path_new_from_indices (r, -1);
}

static void
emit_row_inserted_for_node (CtkFileSystemModel *model, guint id)
{
  CtkTreePath *path;
  CtkTreeIter iter;

  path = tree_path_new_from_node (model, id);
  ITER_INIT_FROM_INDEX (model, &iter, id);
  ctk_tree_model_row_inserted (CTK_TREE_MODEL (model), path, &iter);
  ctk_tree_path_free (path);
}

static void
emit_row_changed_for_node (CtkFileSystemModel *model, guint id)
{
  CtkTreePath *path;
  CtkTreeIter iter;

  path = tree_path_new_from_node (model, id);
  ITER_INIT_FROM_INDEX (model, &iter, id);
  ctk_tree_model_row_changed (CTK_TREE_MODEL (model), path, &iter);
  ctk_tree_path_free (path);
}

static void
emit_row_deleted_for_row (CtkFileSystemModel *model, guint row)
{
  CtkTreePath *path;

  path = ctk_tree_path_new_from_indices (row, -1);
  ctk_tree_model_row_deleted (CTK_TREE_MODEL (model), path);
  ctk_tree_path_free (path);
}

static void
node_set_visible_and_filtered_out (CtkFileSystemModel *model, guint id, gboolean visible, gboolean filtered_out)
{
  FileModelNode *node = get_node (model, id);

  /* Filteredness */

  if (node->filtered_out != filtered_out)
    {
      node->filtered_out = filtered_out;
      if (node->visible && visible)
        emit_row_changed_for_node (model, id);
    }

  /* Visibility */
  
  if (node->visible == visible ||
      node->frozen_add)
    return;

  if (visible)
    {
      node->visible = TRUE;
      node_invalidate_index (model, id);
      emit_row_inserted_for_node (model, id);
    }
  else
    {
      guint row;

      row = node_get_tree_row (model, id);
      g_assert (row < model->files->len);

      node->visible = FALSE;
      node_invalidate_index (model, id);
      emit_row_deleted_for_row (model, row);
    }
}

static gboolean
node_should_be_filtered_out (CtkFileSystemModel *model, guint id)
{
  FileModelNode *node = get_node (model, id);
  CtkFileFilterInfo filter_info = { 0, };
  CtkFileFilterFlags required;
  gboolean result;
  char *mime_type = NULL;
  char *filename = NULL;
  char *uri = NULL;

  if (node->info == NULL)
    return TRUE;

  if (model->filter == NULL)
    return FALSE;

  /* fill info */
  required = ctk_file_filter_get_needed (model->filter);

  filter_info.contains = CTK_FILE_FILTER_DISPLAY_NAME;
  filter_info.display_name = g_file_info_get_display_name (node->info);

  if (required & CTK_FILE_FILTER_MIME_TYPE)
    {
      const char *s = g_file_info_get_content_type (node->info);

      if (!s)
        s = g_file_info_get_attribute_string (node->info, G_FILE_ATTRIBUTE_STANDARD_FAST_CONTENT_TYPE);

      if (s)
	{
	  mime_type = g_content_type_get_mime_type (s);
	  if (mime_type)
	    {
	      filter_info.mime_type = mime_type;
	      filter_info.contains |= CTK_FILE_FILTER_MIME_TYPE;
	    }
	}
    }

  if (required & CTK_FILE_FILTER_FILENAME)
    {
      filename = g_file_get_path (node->file);
      if (filename)
        {
          filter_info.filename = filename;
	  filter_info.contains |= CTK_FILE_FILTER_FILENAME;
        }
    }

  if (required & CTK_FILE_FILTER_URI)
    {
      uri = g_file_get_uri (node->file);
      if (uri)
        {
          filter_info.uri = uri;
	  filter_info.contains |= CTK_FILE_FILTER_URI;
        }
    }

  result = !ctk_file_filter_filter (model->filter, &filter_info);

  g_free (mime_type);
  g_free (filename);
  g_free (uri);

  return result;
}

static gboolean
node_should_be_visible (CtkFileSystemModel *model, guint id, gboolean filtered_out)
{
  FileModelNode *node = get_node (model, id);
  gboolean result;

  if (node->info == NULL)
    return FALSE;

  if (!model->show_hidden &&
      (g_file_info_get_is_hidden (node->info) || g_file_info_get_is_backup (node->info)))
    return FALSE;

  if (_ctk_file_info_consider_as_directory (node->info))
    {
      if (!model->show_folders)
        return FALSE;

      if (!model->filter_folders)
        return TRUE;
    }
  else
    {
      if (!model->show_files)
        return FALSE;
    }

  result = !filtered_out;

  return result;
}

static void
node_compute_visibility_and_filters (CtkFileSystemModel *model, guint id)
{
  gboolean filtered_out;
  gboolean visible;

  filtered_out = node_should_be_filtered_out (model, id);
  visible = node_should_be_visible (model, id, filtered_out);

  node_set_visible_and_filtered_out (model, id, visible, filtered_out);
}

/*** CtkTreeModel ***/

static CtkTreeModelFlags
ctk_file_system_model_get_flags (CtkTreeModel *tree_model G_GNUC_UNUSED)
{
  /* CTK_TREE_MODEL_ITERS_PERSIST doesn't work with arrays :( */
  return CTK_TREE_MODEL_LIST_ONLY;
}

static gint
ctk_file_system_model_get_n_columns (CtkTreeModel *tree_model)
{
  CtkFileSystemModel *model = CTK_FILE_SYSTEM_MODEL (tree_model);
  
  return model->n_columns;
}

static GType
ctk_file_system_model_get_column_type (CtkTreeModel *tree_model,
				       gint          i)
{
  CtkFileSystemModel *model = CTK_FILE_SYSTEM_MODEL (tree_model);
  
  g_return_val_if_fail (i >= 0 && (guint) i < model->n_columns, G_TYPE_NONE);

  return model->column_types[i];
}

static int
compare_indices (gconstpointer key, gconstpointer _node)
{
  const FileModelNode *node = _node;

  return GPOINTER_TO_UINT (key) - node->row;
}

static gboolean
ctk_file_system_model_iter_nth_child (CtkTreeModel *tree_model,
				      CtkTreeIter  *iter,
				      CtkTreeIter  *parent,
				      gint          n)
{
  CtkFileSystemModel *model = CTK_FILE_SYSTEM_MODEL (tree_model);
  guint id;
  guint row_to_find;

  g_return_val_if_fail (n >= 0, FALSE);

  if (parent != NULL)
    return FALSE;

  row_to_find = n + 1; /* plus one as our node->row numbers are 1-based; see the "Structure" comment at the beginning */

  if (model->n_nodes_valid > 0 &&
      get_node (model, model->n_nodes_valid - 1)->row >= row_to_find)
    {
      char *node;

      /* Fast path - the nodes are valid up to the sought one.
       *
       * First, find a node with the sought row number...*/

      node = bsearch (GUINT_TO_POINTER (row_to_find), 
                      model->files->data,
                      model->n_nodes_valid,
                      model->node_size,
                      compare_indices);
      if (node == NULL)
        return FALSE;

      /* ... Second, back up until we find the first visible node with that row number */

      id = node_index (model, node);
      while (!get_node (model, id)->visible)
        id--;

      g_assert (get_node (model, id)->row == row_to_find);
    }
  else
    {
      /* Slow path - the nodes need to be validated up to the sought one */

      node_validate_rows (model, G_MAXUINT, n); /* note that this is really "n", not row_to_find - see node_validate_rows() */
      id = model->n_nodes_valid - 1;
      if (model->n_nodes_valid == 0 || get_node (model, id)->row != row_to_find)
        return FALSE;
    }

  ITER_INIT_FROM_INDEX (model, iter, id);
  return TRUE;
}

static gboolean
ctk_file_system_model_get_iter (CtkTreeModel *tree_model,
				CtkTreeIter  *iter,
				CtkTreePath  *path)
{
  g_return_val_if_fail (ctk_tree_path_get_depth (path) > 0, FALSE);

  if (ctk_tree_path_get_depth (path) > 1)
    return FALSE;

  return ctk_file_system_model_iter_nth_child (tree_model, 
                                               iter,
                                               NULL, 
                                               ctk_tree_path_get_indices (path)[0]);
}

static CtkTreePath *
ctk_file_system_model_get_path (CtkTreeModel *tree_model,
				CtkTreeIter  *iter)
{
  CtkFileSystemModel *model = CTK_FILE_SYSTEM_MODEL (tree_model);
      
  g_return_val_if_fail (ITER_IS_VALID (model, iter), NULL);

  return tree_path_new_from_node (model, ITER_INDEX (iter));
}

static void
ctk_file_system_model_get_value (CtkTreeModel *tree_model,
				 CtkTreeIter  *iter,
				 gint          column,
				 GValue       *value)
{
  CtkFileSystemModel *model = CTK_FILE_SYSTEM_MODEL (tree_model);
  const GValue *original;
  
  g_return_if_fail ((guint) column < model->n_columns);
  g_return_if_fail (ITER_IS_VALID (model, iter));

  original = _ctk_file_system_model_get_value (model, iter, column);
  if (original)
    {
      g_value_init (value, G_VALUE_TYPE (original));
      g_value_copy (original, value);
    }
  else
    g_value_init (value, model->column_types[column]);
}

static gboolean
ctk_file_system_model_iter_next (CtkTreeModel *tree_model,
				 CtkTreeIter  *iter)
{
  CtkFileSystemModel *model = CTK_FILE_SYSTEM_MODEL (tree_model);
  guint i;

  g_return_val_if_fail (ITER_IS_VALID (model, iter), FALSE);

  for (i = ITER_INDEX (iter) + 1; i < model->files->len; i++) 
    {
      FileModelNode *node = get_node (model, i);

      if (node->visible)
        {
          ITER_INIT_FROM_INDEX (model, iter, i);
          return TRUE;
        }
    }
      
  return FALSE;
}

static gboolean
ctk_file_system_model_iter_children (CtkTreeModel *tree_model G_GNUC_UNUSED,
				     CtkTreeIter  *iter G_GNUC_UNUSED,
				     CtkTreeIter  *parent G_GNUC_UNUSED)
{
  return FALSE;
}

static gboolean
ctk_file_system_model_iter_has_child (CtkTreeModel *tree_model G_GNUC_UNUSED,
				      CtkTreeIter  *iter G_GNUC_UNUSED)
{
  return FALSE;
}

static gint
ctk_file_system_model_iter_n_children (CtkTreeModel *tree_model,
				       CtkTreeIter  *iter)
{
  CtkFileSystemModel *model = CTK_FILE_SYSTEM_MODEL (tree_model);

  if (iter)
    return 0;

  return node_get_tree_row (model, model->files->len - 1) + 1;
}

static gboolean
ctk_file_system_model_iter_parent (CtkTreeModel *tree_model G_GNUC_UNUSED,
				   CtkTreeIter  *iter G_GNUC_UNUSED,
				   CtkTreeIter  *child G_GNUC_UNUSED)
{
  return FALSE;
}

static void
ctk_file_system_model_ref_node (CtkTreeModel *tree_model G_GNUC_UNUSED,
				CtkTreeIter  *iter G_GNUC_UNUSED)
{
  /* nothing to do */
}

static void
ctk_file_system_model_unref_node (CtkTreeModel *tree_model G_GNUC_UNUSED,
				  CtkTreeIter  *iter G_GNUC_UNUSED)
{
  /* nothing to do */
}

static void
ctk_file_system_model_iface_init (CtkTreeModelIface *iface)
{
  iface->get_flags =       ctk_file_system_model_get_flags;
  iface->get_n_columns =   ctk_file_system_model_get_n_columns;
  iface->get_column_type = ctk_file_system_model_get_column_type;
  iface->get_iter =        ctk_file_system_model_get_iter;
  iface->get_path =        ctk_file_system_model_get_path;
  iface->get_value =       ctk_file_system_model_get_value;
  iface->iter_next =       ctk_file_system_model_iter_next;
  iface->iter_children =   ctk_file_system_model_iter_children;
  iface->iter_has_child =  ctk_file_system_model_iter_has_child;
  iface->iter_n_children = ctk_file_system_model_iter_n_children;
  iface->iter_nth_child =  ctk_file_system_model_iter_nth_child;
  iface->iter_parent =     ctk_file_system_model_iter_parent;
  iface->ref_node =        ctk_file_system_model_ref_node;
  iface->unref_node =      ctk_file_system_model_unref_node;
}

/*** CtkTreeSortable ***/

typedef struct _SortData SortData;
struct _SortData {
  CtkFileSystemModel *    model;
  CtkTreeIterCompareFunc  func;
  gpointer                data;
  int                     order;        /* -1 to invert sort order or 1 to keep it */
};

/* returns FALSE if no sort necessary */
static gboolean
sort_data_init (SortData *data, CtkFileSystemModel *model)
{
  CtkTreeDataSortHeader *header;

  if (model->files->len <= 2)
    return FALSE;

  switch (model->sort_column_id)
    {
    case CTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID:
      if (!model->default_sort_func)
        return FALSE;
      data->func = model->default_sort_func;
      data->data = model->default_sort_data;
      break;
    case CTK_TREE_SORTABLE_UNSORTED_SORT_COLUMN_ID:
      return FALSE;
    default:
      header = _ctk_tree_data_list_get_header (model->sort_list, model->sort_column_id);
      if (header == NULL)
        return FALSE;
      data->func = header->func;
      data->data = header->data;
      break;
    }

  data->order = model->sort_order == CTK_SORT_DESCENDING ? -1 : 1;
  data->model = model;
  return TRUE;
}

static int
compare_array_element (gconstpointer a, gconstpointer b, gpointer user_data)
{
  SortData *data = user_data;
  CtkTreeIter itera, iterb;

  ITER_INIT_FROM_INDEX (data->model, &itera, node_index (data->model, a));
  ITER_INIT_FROM_INDEX (data->model, &iterb, node_index (data->model, b));
  return data->func (CTK_TREE_MODEL (data->model), &itera, &iterb, data->data) * data->order;
}

static void
ctk_file_system_model_sort (CtkFileSystemModel *model)
{
  SortData data;

  if (model->frozen)
    {
      model->sort_on_thaw = TRUE;
      return;
    }

  if (sort_data_init (&data, model))
    {
      guint i;
      guint r, n_visible_rows;

      node_validate_rows (model, G_MAXUINT, G_MAXUINT);
      n_visible_rows = node_get_tree_row (model, model->files->len - 1) + 1;
      model->n_nodes_valid = 0;
      g_hash_table_remove_all (model->file_lookup);
      g_qsort_with_data (get_node (model, 1), /* start at index 1; don't sort the editable row */
                         model->files->len - 1,
                         model->node_size,
                         compare_array_element,
                         &data);
      g_assert (model->n_nodes_valid == 0);
      g_assert (g_hash_table_size (model->file_lookup) == 0);
      if (n_visible_rows)
        {
          CtkTreePath *path;

          int *new_order = g_new (int, n_visible_rows);
        
          r = 0;
          for (i = 0; i < model->files->len; i++)
            {
              FileModelNode *node = get_node (model, i);
              if (!node->visible)
                {
                  node->row = r;
                  continue;
                }

              new_order[r] = node->row - 1;
              r++;
              node->row = r;
            }
          g_assert (r == n_visible_rows);
          path = ctk_tree_path_new ();
          ctk_tree_model_rows_reordered (CTK_TREE_MODEL (model),
                                         path,
                                         NULL,
                                         new_order);
          ctk_tree_path_free (path);
          g_free (new_order);
        }
    }

  model->sort_on_thaw = FALSE;
}

static void
ctk_file_system_model_sort_node (CtkFileSystemModel *model,
				 guint               node G_GNUC_UNUSED)
{
  /* FIXME: improve */
  ctk_file_system_model_sort (model);
}

static gboolean
ctk_file_system_model_get_sort_column_id (CtkTreeSortable  *sortable,
                                          gint             *sort_column_id,
                                          CtkSortType      *order)
{
  CtkFileSystemModel *model = CTK_FILE_SYSTEM_MODEL (sortable);

  if (sort_column_id)
    *sort_column_id = model->sort_column_id;
  if (order)
    *order = model->sort_order;

  if (model->sort_column_id == CTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID ||
      model->sort_column_id == CTK_TREE_SORTABLE_UNSORTED_SORT_COLUMN_ID)
    return FALSE;

  return TRUE;
}

static void
ctk_file_system_model_set_sort_column_id (CtkTreeSortable  *sortable,
                                          gint              sort_column_id,
                                          CtkSortType       order)
{
  CtkFileSystemModel *model = CTK_FILE_SYSTEM_MODEL (sortable);

  if ((model->sort_column_id == sort_column_id) &&
      (model->sort_order == order))
    return;

  if (sort_column_id != CTK_TREE_SORTABLE_UNSORTED_SORT_COLUMN_ID)
    {
      if (sort_column_id != CTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID)
	{
	  CtkTreeDataSortHeader *header = NULL;

	  header = _ctk_tree_data_list_get_header (model->sort_list, 
						   sort_column_id);

	  /* We want to make sure that we have a function */
	  g_return_if_fail (header != NULL);
	  g_return_if_fail (header->func != NULL);
	}
      else
	{
	  g_return_if_fail (model->default_sort_func != NULL);
	}
    }


  model->sort_column_id = sort_column_id;
  model->sort_order = order;

  ctk_tree_sortable_sort_column_changed (sortable);

  ctk_file_system_model_sort (model);
}

static void
ctk_file_system_model_set_sort_func (CtkTreeSortable        *sortable,
                                     gint                    sort_column_id,
                                     CtkTreeIterCompareFunc  func,
                                     gpointer                data,
                                     GDestroyNotify          destroy)
{
  CtkFileSystemModel *model = CTK_FILE_SYSTEM_MODEL (sortable);

  model->sort_list = _ctk_tree_data_list_set_header (model->sort_list, 
                                                     sort_column_id, 
                                                     func, data, destroy);

  if (model->sort_column_id == sort_column_id)
    ctk_file_system_model_sort (model);
}

static void
ctk_file_system_model_set_default_sort_func (CtkTreeSortable        *sortable,
                                             CtkTreeIterCompareFunc  func,
                                             gpointer                data,
                                             GDestroyNotify          destroy)
{
  CtkFileSystemModel *model = CTK_FILE_SYSTEM_MODEL (sortable);

  if (model->default_sort_destroy)
    {
      GDestroyNotify d = model->default_sort_destroy;

      model->default_sort_destroy = NULL;
      d (model->default_sort_data);
    }

  model->default_sort_func = func;
  model->default_sort_data = data;
  model->default_sort_destroy = destroy;

  if (model->sort_column_id == CTK_TREE_SORTABLE_DEFAULT_SORT_COLUMN_ID)
    ctk_file_system_model_sort (model);
}

static gboolean
ctk_file_system_model_has_default_sort_func (CtkTreeSortable *sortable)
{
  CtkFileSystemModel *model = CTK_FILE_SYSTEM_MODEL (sortable);

  return (model->default_sort_func != NULL);
}

static void
ctk_file_system_model_sortable_init (CtkTreeSortableIface *iface)
{
  iface->get_sort_column_id = ctk_file_system_model_get_sort_column_id;
  iface->set_sort_column_id = ctk_file_system_model_set_sort_column_id;
  iface->set_sort_func = ctk_file_system_model_set_sort_func;
  iface->set_default_sort_func = ctk_file_system_model_set_default_sort_func;
  iface->has_default_sort_func = ctk_file_system_model_has_default_sort_func;
}

/*** CtkTreeDragSource ***/

static gboolean
drag_source_row_draggable (CtkTreeDragSource *drag_source,
			   CtkTreePath       *path)
{
  CtkFileSystemModel *model = CTK_FILE_SYSTEM_MODEL (drag_source);
  CtkTreeIter iter;

  if (!ctk_file_system_model_get_iter (CTK_TREE_MODEL (model), &iter, path))
    return FALSE;

  return ITER_INDEX (&iter) != 0;
}

static gboolean
drag_source_drag_data_get (CtkTreeDragSource *drag_source,
			   CtkTreePath       *path,
			   CtkSelectionData  *selection_data)
{
  CtkFileSystemModel *model = CTK_FILE_SYSTEM_MODEL (drag_source);
  FileModelNode *node;
  CtkTreeIter iter;
  char *uris[2]; 

  if (!ctk_file_system_model_get_iter (CTK_TREE_MODEL (model), &iter, path))
    return FALSE;

  node = get_node (model, ITER_INDEX (&iter));
  if (node->file == NULL)
    return FALSE;

  uris[0] = g_file_get_uri (node->file);
  uris[1] = NULL;
  ctk_selection_data_set_uris (selection_data, uris);
  g_free (uris[0]);

  return TRUE;
}

static void
drag_source_iface_init (CtkTreeDragSourceIface *iface)
{
  iface->row_draggable = drag_source_row_draggable;
  iface->drag_data_get = drag_source_drag_data_get;
  iface->drag_data_delete = NULL;
}

/*** CtkFileSystemModel ***/

/* Signal IDs */
enum {
  FINISHED_LOADING,
  LAST_SIGNAL
};

static guint file_system_model_signals[LAST_SIGNAL] = { 0 };



G_DEFINE_TYPE_WITH_CODE (CtkFileSystemModel, _ctk_file_system_model, G_TYPE_OBJECT,<--- There is an unknown macro here somewhere. Configuration is required. If G_DEFINE_TYPE_WITH_CODE is a macro then please configure it.
			 G_IMPLEMENT_INTERFACE (CTK_TYPE_TREE_MODEL,
						ctk_file_system_model_iface_init)
			 G_IMPLEMENT_INTERFACE (CTK_TYPE_TREE_SORTABLE,
						ctk_file_system_model_sortable_init)
			 G_IMPLEMENT_INTERFACE (CTK_TYPE_TREE_DRAG_SOURCE,
						drag_source_iface_init))

static void
ctk_file_system_model_dispose (GObject *object)
{
  CtkFileSystemModel *model = CTK_FILE_SYSTEM_MODEL (object);

  if (model->dir_thaw_source)
    {
      g_source_remove (model->dir_thaw_source);
      model->dir_thaw_source = 0;
    }

  g_cancellable_cancel (model->cancellable);
  if (model->dir_monitor)
    g_file_monitor_cancel (model->dir_monitor);

  G_OBJECT_CLASS (_ctk_file_system_model_parent_class)->dispose (object);
}


static void
ctk_file_system_model_finalize (GObject *object)
{
  CtkFileSystemModel *model = CTK_FILE_SYSTEM_MODEL (object);
  guint i;

  for (i = 0; i < model->files->len; i++)
    {
      int v;

      FileModelNode *node = get_node (model, i);
      if (node->file)
        g_object_unref (node->file);
      if (node->info)
        g_object_unref (node->info);

      for (v = 0; v < model->n_columns; v++)
	if (G_VALUE_TYPE (&node->values[v]) != G_TYPE_INVALID)
	  g_value_unset (&node->values[v]);
    }
  g_array_free (model->files, TRUE);

  g_object_unref (model->cancellable);
  g_free (model->attributes);
  if (model->dir)
    g_object_unref (model->dir);
  if (model->dir_monitor)
    g_object_unref (model->dir_monitor);
  g_hash_table_destroy (model->file_lookup);
  if (model->filter)
    g_object_unref (model->filter);

  g_slice_free1 (sizeof (GType) * model->n_columns, model->column_types);

  _ctk_tree_data_list_header_free (model->sort_list);
  if (model->default_sort_destroy)
    model->default_sort_destroy (model->default_sort_data);

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

static void
_ctk_file_system_model_class_init (CtkFileSystemModelClass *class)
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (class);

  gobject_class->finalize = ctk_file_system_model_finalize;
  gobject_class->dispose = ctk_file_system_model_dispose;

  file_system_model_signals[FINISHED_LOADING] =
    g_signal_new (I_("finished-loading"),
		  G_OBJECT_CLASS_TYPE (gobject_class),
		  G_SIGNAL_RUN_LAST,
		  G_STRUCT_OFFSET (CtkFileSystemModelClass, finished_loading),
		  NULL, NULL,
		  NULL,
		  G_TYPE_NONE, 1, G_TYPE_POINTER);
}

static void
_ctk_file_system_model_init (CtkFileSystemModel *model)
{
  model->show_files = TRUE;
  model->show_folders = TRUE;
  model->show_hidden = FALSE;
  model->filter_folders = FALSE;

  model->sort_column_id = CTK_TREE_SORTABLE_UNSORTED_SORT_COLUMN_ID;

  model->file_lookup = g_hash_table_new (g_file_hash, (GEqualFunc) g_file_equal);
  model->cancellable = g_cancellable_new ();
}

/*** API ***/

static void
ctk_file_system_model_closed_enumerator (GObject      *object,
					 GAsyncResult *res,
					 gpointer      data G_GNUC_UNUSED)
{
  g_file_enumerator_close_finish (G_FILE_ENUMERATOR (object), res, NULL);
}

static gboolean
thaw_func (gpointer data)
{
  CtkFileSystemModel *model = data;

  thaw_updates (model);
  model->dir_thaw_source = 0;

  return FALSE;
}

static void
ctk_file_system_model_got_files (GObject *object, GAsyncResult *res, gpointer data)
{
  GFileEnumerator *enumerator = G_FILE_ENUMERATOR (object);
  CtkFileSystemModel *model = data;
  GList *walk, *files;
  GError *error = NULL;

  cdk_threads_enter ();

  files = g_file_enumerator_next_files_finish (enumerator, res, &error);

  if (files)
    {
      if (model->dir_thaw_source == 0)
        {
          freeze_updates (model);
          model->dir_thaw_source = cdk_threads_add_timeout_full (IO_PRIORITY + 1,
                                                                 50,
                                                                 thaw_func,
                                                                 model,
                                                                 NULL);
          g_source_set_name_by_id (model->dir_thaw_source, "[ctk+] thaw_func");
        }

      for (walk = files; walk; walk = walk->next)
        {
          const char *name;
          GFileInfo *info;
          GFile *file;
          
          info = walk->data;
          name = g_file_info_get_name (info);
          if (name == NULL)
            {
              /* Shouldn't happen, but the APIs allow it */
              g_object_unref (info);
              continue;
            }
          file = g_file_get_child (model->dir, name);
          add_file (model, file, info);
          g_object_unref (file);
          g_object_unref (info);
        }
      g_list_free (files);

      g_file_enumerator_next_files_async (enumerator,
					  g_file_is_native (model->dir) ? 50 * FILES_PER_QUERY : FILES_PER_QUERY,
					  IO_PRIORITY,
					  model->cancellable,
					  ctk_file_system_model_got_files,
					  model);
    }
  else
    {
      if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
        {
          g_file_enumerator_close_async (enumerator,
                                         IO_PRIORITY,
                                         model->cancellable,
                                         ctk_file_system_model_closed_enumerator,
                                         NULL);
          if (model->dir_thaw_source != 0)
            {
              g_source_remove (model->dir_thaw_source);
              model->dir_thaw_source = 0;
              thaw_updates (model);
            }

          g_signal_emit (model, file_system_model_signals[FINISHED_LOADING], 0, error);
        }

      if (error)
        g_error_free (error);
    }

  cdk_threads_leave ();
}

/* Helper for ctk_file_system_model_query_done and
 * ctk_file_system_model_one_query_done */
static void
query_done_helper (GObject *     object,
                   GAsyncResult *res,
                   gpointer      data,
                   gboolean      do_thaw_updates)
{
  CtkFileSystemModel *model;
  GFile *file = G_FILE (object);
  GFileInfo *info;
  guint id;

  info = g_file_query_info_finish (file, res, NULL);
  if (info == NULL)
    return;

  model = CTK_FILE_SYSTEM_MODEL (data);

  _ctk_file_system_model_update_file (model, file, info);

  id = node_get_for_file (model, file);
  ctk_file_system_model_sort_node (model, id);

  if (do_thaw_updates)
    thaw_updates (model);

  g_object_unref (info);
}

static void
ctk_file_system_model_query_done (GObject *     object,
                                  GAsyncResult *res,
                                  gpointer      data)
{
  cdk_threads_enter ();

  query_done_helper (object, res, data, FALSE);

  cdk_threads_leave ();
}

static void
ctk_file_system_model_monitor_change (GFileMonitor *      monitor G_GNUC_UNUSED,
                                      GFile *             file,
                                      GFile *             other_file G_GNUC_UNUSED,
                                      GFileMonitorEvent   type,
                                      CtkFileSystemModel *model)
{
  switch (type)
    {
      case G_FILE_MONITOR_EVENT_CREATED:
      case G_FILE_MONITOR_EVENT_CHANGED:
      case G_FILE_MONITOR_EVENT_ATTRIBUTE_CHANGED:
        /* We can treat all of these the same way */
        g_file_query_info_async (file,
                                 model->attributes,
                                 G_FILE_QUERY_INFO_NONE,
                                 IO_PRIORITY,
                                 model->cancellable,
                                 ctk_file_system_model_query_done,
                                 model);
        break;
      case G_FILE_MONITOR_EVENT_DELETED:
	cdk_threads_enter ();
        remove_file (model, file);
	cdk_threads_leave ();
        break;
      case G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT:
        /* FIXME: use freeze/thaw with this somehow? */
      case G_FILE_MONITOR_EVENT_PRE_UNMOUNT:
      case G_FILE_MONITOR_EVENT_UNMOUNTED:
      default:
        /* ignore these */
        break;
    }
}

static void
ctk_file_system_model_got_enumerator (GObject *dir, GAsyncResult *res, gpointer data)
{
  CtkFileSystemModel *model = data;
  GFileEnumerator *enumerator;
  GError *error = NULL;

  cdk_threads_enter ();

  enumerator = g_file_enumerate_children_finish (G_FILE (dir), res, &error);
  if (enumerator == NULL)
    {
      if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
      {
        g_signal_emit (model, file_system_model_signals[FINISHED_LOADING], 0, error);
        g_error_free (error);
      }
    }
  else
    {
      g_file_enumerator_next_files_async (enumerator,
                                          g_file_is_native (model->dir) ? 50 * FILES_PER_QUERY : FILES_PER_QUERY,
                                          IO_PRIORITY,
                                          model->cancellable,
                                          ctk_file_system_model_got_files,
                                          model);
      g_object_unref (enumerator);
      model->dir_monitor = g_file_monitor_directory (model->dir,
                                                     G_FILE_MONITOR_NONE,
                                                     model->cancellable,
                                                     NULL); /* we don't mind if directory monitoring isn't supported, so the GError is NULL here */
      if (model->dir_monitor)
        g_signal_connect (model->dir_monitor,
                          "changed",
                          G_CALLBACK (ctk_file_system_model_monitor_change),
                          model);
    }

  cdk_threads_leave ();
}

static void
ctk_file_system_model_set_n_columns (CtkFileSystemModel *model,
                                     gint                n_columns,
                                     va_list             args)
{
  guint i;

  g_assert (model->files == NULL);
  g_assert (n_columns > 0);

  model->n_columns = n_columns;
  model->column_types = g_slice_alloc (sizeof (GType) * n_columns);

  model->node_size = sizeof (FileModelNode) + sizeof (GValue) * (n_columns - 1); /* minus 1 because FileModelNode.values[] has a default size of 1 */

  for (i = 0; i < (guint) n_columns; i++)
    {
      GType type = va_arg (args, GType);
      if (! _ctk_tree_data_list_check_type (type))
	{
	  g_error ("%s: type %s cannot be a column type for CtkFileSystemModel\n", G_STRLOC, g_type_name (type));
          return; /* not reached */
	}

      model->column_types[i] = type;
    }

  model->sort_list = _ctk_tree_data_list_header_new (n_columns, model->column_types);

  model->files = g_array_sized_new (FALSE, FALSE, model->node_size, FILES_PER_QUERY);
  /* add editable node at start */
  g_array_set_size (model->files, 1);
  memset (get_node (model, 0), 0, model->node_size);
}

static void
ctk_file_system_model_set_directory (CtkFileSystemModel *model,
                                     GFile *             dir,
			             const gchar *       attributes)
{
  g_assert (G_IS_FILE (dir));

  model->dir = g_object_ref (dir);
  model->attributes = g_strdup (attributes);

  g_file_enumerate_children_async (model->dir,
                                   attributes,
                                   G_FILE_QUERY_INFO_NONE,
                                   IO_PRIORITY,
                                   model->cancellable,
                                   ctk_file_system_model_got_enumerator,
                                   model);

}

static CtkFileSystemModel *
_ctk_file_system_model_new_valist (CtkFileSystemModelGetValue get_func,
                                   gpointer            get_data,
                                   guint               n_columns,
                                   va_list             args)
{
  CtkFileSystemModel *model;

  model = g_object_new (CTK_TYPE_FILE_SYSTEM_MODEL, NULL);
  model->get_func = get_func;
  model->get_data = get_data;

  ctk_file_system_model_set_n_columns (model, n_columns, args);

  return model;
}

/**
 * _ctk_file_system_model_new:
 * @get_func: function to call for getting a value
 * @get_data: user data argument passed to @get_func
 * @n_columns: number of columns
 * @...: @n_columns #GType types for the columns
 *
 * Creates a new #CtkFileSystemModel object. You need to add files
 * to the list using _ctk_file_system_model_add_and_query_file()
 * or _ctk_file_system_model_update_file().
 *
 * Returns: the newly created #CtkFileSystemModel
 **/
CtkFileSystemModel *
_ctk_file_system_model_new (CtkFileSystemModelGetValue get_func,
                            gpointer            get_data,
                            guint               n_columns,
                            ...)
{
  CtkFileSystemModel *model;
  va_list args;

  g_return_val_if_fail (get_func != NULL, NULL);
  g_return_val_if_fail (n_columns > 0, NULL);

  va_start (args, n_columns);
  model = _ctk_file_system_model_new_valist (get_func, get_data, n_columns, args);
  va_end (args);

  return model;
}

/**
 * _ctk_file_system_model_new_for_directory:
 * @directory: the directory to show.
 * @attributes: (allow-none): attributes to immediately load or %NULL for all
 * @get_func: function that the model should call to query data about a file
 * @get_data: user data to pass to the @get_func
 * @n_columns: number of columns
 * @...: @n_columns #GType types for the columns
 *
 * Creates a new #CtkFileSystemModel object. The #CtkFileSystemModel
 * object wraps the given @directory as a #CtkTreeModel.
 * The model will query the given directory with the given @attributes
 * and add all files inside the directory automatically. If supported,
 * it will also monitor the drectory and update the model's
 * contents to reflect changes, if the @directory supports monitoring.
 * 
 * Returns: the newly created #CtkFileSystemModel
 **/
CtkFileSystemModel *
_ctk_file_system_model_new_for_directory (GFile *                    dir,
                                          const gchar *              attributes,
                                          CtkFileSystemModelGetValue get_func,
                                          gpointer                   get_data,
                                          guint                      n_columns,
                                          ...)
{
  CtkFileSystemModel *model;
  va_list args;

  g_return_val_if_fail (G_IS_FILE (dir), NULL);
  g_return_val_if_fail (get_func != NULL, NULL);
  g_return_val_if_fail (n_columns > 0, NULL);

  va_start (args, n_columns);
  model = _ctk_file_system_model_new_valist (get_func, get_data, n_columns, args);
  va_end (args);

  ctk_file_system_model_set_directory (model, dir, attributes);

  return model;
}

static void
ctk_file_system_model_refilter_all (CtkFileSystemModel *model)
{
  guint i;

  if (model->frozen)
    {
      model->filter_on_thaw = TRUE;
      return;
    }

  freeze_updates (model);

  /* start at index 1, don't change the editable */
  for (i = 1; i < model->files->len; i++)
    node_compute_visibility_and_filters (model, i);

  model->filter_on_thaw = FALSE;
  thaw_updates (model);
}

/**
 * _ctk_file_system_model_set_show_hidden:
 * @model: a #CtkFileSystemModel
 * @show_hidden: whether hidden files should be displayed
 * 
 * Sets whether hidden files should be included in the #CtkTreeModel
 * for display.
 **/
void
_ctk_file_system_model_set_show_hidden (CtkFileSystemModel *model,
					gboolean            show_hidden)
{
  g_return_if_fail (CTK_IS_FILE_SYSTEM_MODEL (model));

  show_hidden = show_hidden != FALSE;

  if (show_hidden != model->show_hidden)
    {
      model->show_hidden = show_hidden;
      ctk_file_system_model_refilter_all (model);
    }
}

/**
 * _ctk_file_system_model_set_show_folders:
 * @model: a #CtkFileSystemModel
 * @show_folders: whether folders should be displayed
 * 
 * Sets whether folders should be included in the #CtkTreeModel for
 * display.
 **/
void
_ctk_file_system_model_set_show_folders (CtkFileSystemModel *model,
					 gboolean            show_folders)
{
  g_return_if_fail (CTK_IS_FILE_SYSTEM_MODEL (model));

  show_folders = show_folders != FALSE;

  if (show_folders != model->show_folders)
    {
      model->show_folders = show_folders;
      ctk_file_system_model_refilter_all (model);
    }
}

/**
 * _ctk_file_system_model_set_show_files:
 * @model: a #CtkFileSystemModel
 * @show_files: whether files (as opposed to folders) should
 *              be displayed.
 * 
 * Sets whether files (as opposed to folders) should be included
 * in the #CtkTreeModel for display.
 **/
void
_ctk_file_system_model_set_show_files (CtkFileSystemModel *model,
				       gboolean            show_files)
{
  g_return_if_fail (CTK_IS_FILE_SYSTEM_MODEL (model));

  show_files = show_files != FALSE;

  if (show_files != model->show_files)
    {
      model->show_files = show_files;
      ctk_file_system_model_refilter_all (model);
    }
}

/**
 * _ctk_file_system_model_set_filter_folders:
 * @model: a #CtkFileSystemModel
 * @filter_folders: whether the filter applies to folders
 * 
 * Sets whether the filter set by _ctk_file_system_model_set_filter()
 * applies to folders. By default, it does not and folders are always
 * visible.
 **/
void
_ctk_file_system_model_set_filter_folders (CtkFileSystemModel *model,
					   gboolean            filter_folders)
{
  g_return_if_fail (CTK_IS_FILE_SYSTEM_MODEL (model));

  filter_folders = filter_folders != FALSE;

  if (filter_folders != model->filter_folders)
    {
      model->filter_folders = filter_folders;
      ctk_file_system_model_refilter_all (model);
    }
}

/**
 * _ctk_file_system_model_get_cancellable:
 * @model: the model
 *
 * Gets the cancellable used by the @model. This is the cancellable used
 * internally by the @model that will be cancelled when @model is 
 * disposed. So you can use it for operations that should be cancelled
 * when the model goes away.
 *
 * Returns: The cancellable used by @model
 **/
GCancellable *
_ctk_file_system_model_get_cancellable (CtkFileSystemModel *model)
{
  g_return_val_if_fail (CTK_IS_FILE_SYSTEM_MODEL (model), NULL);

  return model->cancellable;
}

/**
 * _ctk_file_system_model_iter_is_visible:
 * @model: the model
 * @iter: a valid iterator
 *
 * Checks if the iterator is visible. A visible iterator references
 * a row that is currently exposed using the #CtkTreeModel API. If
 * the iterator is invisible, it references a file that is not shown
 * for some reason, such as being filtered out by the current filter or
 * being a hidden file.
 *
 * Returns: %TRUE if the iterator is visible
 **/
gboolean
_ctk_file_system_model_iter_is_visible (CtkFileSystemModel *model,
					CtkTreeIter        *iter)
{
  FileModelNode *node;

  g_return_val_if_fail (CTK_IS_FILE_SYSTEM_MODEL (model), FALSE);
  g_return_val_if_fail (iter != NULL, FALSE);

  node = get_node (model, ITER_INDEX (iter));
  return node->visible;
}

/**
 * _ctk_file_system_model_iter_is_filtered_out:
 * @model: the model
 * @iter: a valid iterator
 *
 * Checks if the iterator is filtered out.  This is only useful for rows
 * that refer to folders, as those are always visible regardless
 * of what the current filter says.  This function lets you see
 * the results of the filter.
 *
 * Returns: %TRUE if the iterator passed the current filter; %FALSE if the
 * filter would not have let the row pass.
 **/
gboolean
_ctk_file_system_model_iter_is_filtered_out (CtkFileSystemModel *model,
					     CtkTreeIter        *iter)
{
  FileModelNode *node;

  g_return_val_if_fail (CTK_IS_FILE_SYSTEM_MODEL (model), FALSE);
  g_return_val_if_fail (iter != NULL, FALSE);

  node = get_node (model, ITER_INDEX (iter));
  return node->filtered_out;
}

/**
 * _ctk_file_system_model_get_info:
 * @model: a #CtkFileSystemModel
 * @iter: a #CtkTreeIter pointing to a row of @model
 * 
 * Gets the #GFileInfo-struct for a particular row
 * of @model.
 * 
 * Returns: a #GFileInfo-struct. This value
 *   is owned by @model and must not be modified or freed.
 *   If you want to keep the information for later use,
 *   you must take a reference, since the #GFileInfo-struct may be
 *   freed on later changes to the file system.
 **/
GFileInfo *
_ctk_file_system_model_get_info (CtkFileSystemModel *model,
				 CtkTreeIter        *iter)
{
  FileModelNode *node;

  g_return_val_if_fail (CTK_IS_FILE_SYSTEM_MODEL (model), NULL);
  g_return_val_if_fail (iter != NULL, NULL);

  node = get_node (model, ITER_INDEX (iter));
  g_assert (node->info == NULL || G_IS_FILE_INFO (node->info));
  return node->info;
}

/**
 * _ctk_file_system_model_get_file:
 * @model: a #CtkFileSystemModel
 * @iter: a #CtkTreeIter pointing to a row of @model
 * 
 * Gets the file for a particular row in @model. 
 *
 * Returns: the file. This object is owned by @model and
 *   or freed. If you want to save the path for later use,
 *   you must take a ref, since the object may be freed
 *   on later changes to the file system.
 **/
GFile *
_ctk_file_system_model_get_file (CtkFileSystemModel *model,
				 CtkTreeIter        *iter)
{
  FileModelNode *node;

  g_return_val_if_fail (CTK_IS_FILE_SYSTEM_MODEL (model), NULL);

  node = get_node (model, ITER_INDEX (iter));
  return node->file;
}

/**
 * _ctk_file_system_model_get_value:
 * @model: a #CtkFileSystemModel
 * @iter: a #CtkTreeIter pointing to a row of @model
 * @column: the column to get the value for
 *
 * Gets the value associated with the given row @iter and @column.
 * If no value is available yet and the default value should be used,
 * %NULL is returned.
 * This is a performance optimization for the calls 
 * ctk_tree_model_get() or ctk_tree_model_get_value(), which copy 
 * the value and spend a considerable amount of time in iterator 
 * lookups. Both of which are slow.
 *
 * Returns: a pointer to the actual value as stored in @model or %NULL
 *          if no value available yet.
 **/
const GValue *
_ctk_file_system_model_get_value (CtkFileSystemModel *model,
                                  CtkTreeIter *       iter,
                                  int                 column)
{
  FileModelNode *node;

  g_return_val_if_fail (CTK_IS_FILE_SYSTEM_MODEL (model), NULL);
  g_return_val_if_fail (column >= 0 && (guint) column < model->n_columns, NULL);

  node = get_node (model, ITER_INDEX (iter));
    
  if (!G_VALUE_TYPE (&node->values[column]))
    {
      g_value_init (&node->values[column], model->column_types[column]);
      if (!model->get_func (model, 
                            node->file, 
                            node->info, 
                            column, 
                            &node->values[column],
                            model->get_data))
        {
          g_value_unset (&node->values[column]);
          return NULL;
        }
    }
  
  return &node->values[column];
}

static guint
node_get_for_file (CtkFileSystemModel *model,
                   GFile *             file)
{
  guint i;

  i = GPOINTER_TO_UINT (g_hash_table_lookup (model->file_lookup, file));
  if (i != 0)
    return i;

  /* Node 0 is the editable row and has no associated file or entry in the table, so we start counting from 1.
   *
   * The invariant here is that the files in model->files[n] for n < g_hash_table_size (model->file_lookup)
   * are already added to the hash table. The table can get cleared when we re-sort; this loop merely rebuilds
   * our (file -> index) mapping on demand.
   *
   * If we exit the loop, the next pending batch of mappings will be resolved when this function gets called again
   * with another file that is not yet in the mapping.
   */
  for (i = g_hash_table_size (model->file_lookup) + 1; i < model->files->len; i++)
    {
      FileModelNode *node = get_node (model, i);

      g_hash_table_insert (model->file_lookup, node->file, GUINT_TO_POINTER (i));
      if (g_file_equal (node->file, file))
        return i;
    }

  return 0;
}

/**
 * _ctk_file_system_model_get_iter_for_file:
 * @model: the model
 * @iter: the iterator to be initialized
 * @file: the file to look up
 *
 * Initializes @iter to point to the row used for @file, if @file is part 
 * of the model. Note that upon successful return, @iter may point to an 
 * invisible row in the @model. Use 
 * _ctk_file_system_model_iter_is_visible() to make sure it is visible to
 * the tree view.
 *
 * Returns: %TRUE if file is part of the model and @iter was initialized
 **/
gboolean
_ctk_file_system_model_get_iter_for_file (CtkFileSystemModel *model,
					  CtkTreeIter        *iter,
					  GFile *             file)
{
  guint i;

  g_return_val_if_fail (CTK_IS_FILE_SYSTEM_MODEL (model), FALSE);
  g_return_val_if_fail (iter != NULL, FALSE);
  g_return_val_if_fail (G_IS_FILE (file), FALSE);

  i = node_get_for_file (model, file);

  if (i == 0)
    return FALSE;

  ITER_INIT_FROM_INDEX (model, iter, i);
  return TRUE;
}

/* When an element is added or removed to the model->files array, we need to
 * update the model->file_lookup mappings of (node, index), as the indexes
 * change.  This function adds the specified increment to the index in that pair
 * if the index is equal or after the specified id.  We use this to slide the
 * mappings up or down when a node is added or removed, respectively.
 */
static void
adjust_file_lookup (CtkFileSystemModel *model, guint id, int increment)
{
  GHashTableIter iter;
  gpointer key;
  gpointer value;

  g_hash_table_iter_init (&iter, model->file_lookup);

  while (g_hash_table_iter_next (&iter, &key, &value))
    {
      guint index = GPOINTER_TO_UINT (value);

      if (index >= id)
	{
	  index += increment;
	  g_hash_table_iter_replace (&iter, GUINT_TO_POINTER (index));
	}
    }
}

/**
 * add_file:
 * @model: the model
 * @file: the file to add
 * @info: the information to associate with the file
 *
 * Adds the given @file with its associated @info to the @model. 
 * If the model is frozen, the file will only show up after it is thawn.
 **/
static void
add_file (CtkFileSystemModel *model,
	  GFile              *file,
	  GFileInfo          *info)
{
  FileModelNode *node;
  
  g_return_if_fail (CTK_IS_FILE_SYSTEM_MODEL (model));
  g_return_if_fail (G_IS_FILE (file));
  g_return_if_fail (G_IS_FILE_INFO (info));

  node = g_slice_alloc0 (model->node_size);
  node->file = g_object_ref (file);
  if (info)
    node->info = g_object_ref (info);
  node->frozen_add = model->frozen ? TRUE : FALSE;

  g_array_append_vals (model->files, node, 1);
  g_slice_free1 (model->node_size, node);

  if (!model->frozen)
    node_compute_visibility_and_filters (model, model->files->len -1);

  ctk_file_system_model_sort_node (model, model->files->len -1);
}

/**
 * remove_file:
 * @model: the model
 * @file: file to remove from the model. The file must have been 
 *        added to the model previously
 *
 * Removes the given file from the model. If the file is not part of 
 * @model, this function does nothing.
 **/
static void
remove_file (CtkFileSystemModel *model,
	     GFile              *file)
{
  FileModelNode *node;
  gboolean was_visible;
  guint id;
  guint row;

  g_return_if_fail (CTK_IS_FILE_SYSTEM_MODEL (model));
  g_return_if_fail (G_IS_FILE (file));

  id = node_get_for_file (model, file);
  if (id == 0)
    return;

  node = get_node (model, id);
  was_visible = node->visible;
  row = node_get_tree_row (model, id);

  node_invalidate_index (model, id);

  g_hash_table_remove (model->file_lookup, file);
  g_object_unref (node->file);
  adjust_file_lookup (model, id, -1);

  if (node->info)
    g_object_unref (node->info);

  g_array_remove_index (model->files, id);

  /* We don't need to resort, as removing a row doesn't change the sorting order of the other rows */

  if (was_visible)
    emit_row_deleted_for_row (model, row);
}

/**
 * _ctk_file_system_model_update_file:
 * @model: the model
 * @file: the file
 * @info: the new file info
 *
 * Tells the file system model that the file changed and that the 
 * new @info should be used for it now.  If the file is not part of 
 * @model, it will get added automatically.
 **/
void
_ctk_file_system_model_update_file (CtkFileSystemModel *model,
                                    GFile              *file,
                                    GFileInfo          *info)
{
  FileModelNode *node;
  guint i, id;
  GFileInfo *old_info;

  g_return_if_fail (CTK_IS_FILE_SYSTEM_MODEL (model));
  g_return_if_fail (G_IS_FILE (file));
  g_return_if_fail (G_IS_FILE_INFO (info));

  id = node_get_for_file (model, file);
  if (id == 0)
    {
      add_file (model, file, info);
      id = node_get_for_file (model, file);
    }

  node = get_node (model, id);

  old_info = node->info;
  node->info = g_object_ref (info);
  if (old_info)
    g_object_unref (old_info);

  for (i = 0; i < model->n_columns; i++)
    {
      if (G_VALUE_TYPE (&node->values[i]))
        g_value_unset (&node->values[i]);
    }

  if (node->visible)
    emit_row_changed_for_node (model, id);
}

void
_ctk_file_system_model_update_files (CtkFileSystemModel *model,
                                     GList              *files,
                                     GList              *infos)
{
  GList *l, *i;

  g_return_if_fail (CTK_IS_FILE_SYSTEM_MODEL (model));

  freeze_updates (model);

  for (l = files, i = infos; l; l = l->next, i = i->next)
    _ctk_file_system_model_update_file (model, (GFile *)l->data, (GFileInfo *)i->data);

  thaw_updates (model);
}

/**
 * _ctk_file_system_model_set_filter:
 * @mode: a #CtkFileSystemModel
 * @filter: (allow-none): %NULL or filter to use
 * 
 * Sets a filter to be used for deciding if a row should be visible or not.
 * Whether this filter applies to directories can be toggled with
 * _ctk_file_system_model_set_filter_folders().
 **/
void
_ctk_file_system_model_set_filter (CtkFileSystemModel      *model,
				   CtkFileFilter *          filter)
{
  CtkFileFilter *old_filter;

  g_return_if_fail (CTK_IS_FILE_SYSTEM_MODEL (model));
  g_return_if_fail (filter == NULL || CTK_IS_FILE_FILTER (filter));
  
  if (filter)
    g_object_ref (filter);

  old_filter = model->filter;
  model->filter = filter;

  if (old_filter)
    g_object_unref (old_filter);

  ctk_file_system_model_refilter_all (model);
}

/**
 * freeze_updates:
 * @model: a #CtkFileSystemModel
 *
 * Freezes most updates on the model, so that performing multiple operations on
 * the files in the model do not cause any events.  Use thaw_updates() to resume
 * proper operations. It is fine to call this function multiple times as long as
 * freeze and thaw calls are balanced.
 **/
static void
freeze_updates (CtkFileSystemModel *model)
{
  g_return_if_fail (CTK_IS_FILE_SYSTEM_MODEL (model));

  model->frozen++;
}

/**
 * thaw_updates:
 * @model: a #CtkFileSystemModel
 *
 * Undoes the effect of a previous call to freeze_updates() 
 **/
static void
thaw_updates (CtkFileSystemModel *model)
{
  gboolean stuff_added;

  g_return_if_fail (CTK_IS_FILE_SYSTEM_MODEL (model));
  g_return_if_fail (model->frozen > 0);

  model->frozen--;
  if (model->frozen > 0)
    return;

  stuff_added = get_node (model, model->files->len - 1)->frozen_add;

  if (model->filter_on_thaw)
    ctk_file_system_model_refilter_all (model);
  if (model->sort_on_thaw)
    ctk_file_system_model_sort (model);
  if (stuff_added)
    {
      guint i;

      for (i = 0; i < model->files->len; i++)
        {
          FileModelNode *node = get_node (model, i);

          if (!node->frozen_add)
            continue;
          node->frozen_add = FALSE;
          node_compute_visibility_and_filters (model, i);
        }
    }
}

/**
 * _ctk_file_system_model_clear_cache:
 * @model: a #CtkFileSystemModel
 * @column: the column to clear or -1 for all columns
 *
 * Clears the cached values in the model for the given @column. Use 
 * this function whenever your get_value function would return different
 * values for a column.
 * The file chooser uses this for example when the icon theme changes to 
 * invalidate the cached pixbufs.
 **/
void
_ctk_file_system_model_clear_cache (CtkFileSystemModel *model,
                                    int                 column)
{
  guint i;
  int start, end;
  gboolean changed;

  g_return_if_fail (CTK_IS_FILE_SYSTEM_MODEL (model));
  g_return_if_fail (column >= -1 && (guint) column < model->n_columns);

  if (column > -1)
    {
      start = column;
      end = column + 1;
    }
  else
    {
      start = 0;
      end = model->n_columns;
    }

  for (i = 0; i < model->files->len; i++)
    {
      FileModelNode *node = get_node (model, i);
      changed = FALSE;
      for (column = start; column < end; column++)
        {
          if (!G_VALUE_TYPE (&node->values[column]))
            continue;
          
          g_value_unset (&node->values[column]);
          changed = TRUE;
        }

      if (changed && node->visible)
	emit_row_changed_for_node (model, i);
    }

  /* FIXME: resort? */
}

/**
 * _ctk_file_system_model_add_and_query_file:
 * @model: a #CtkFileSystemModel
 * @file: the file to add
 * @attributes: attributes to query before adding the file
 *
 * This is a conenience function that calls g_file_query_info_async() on 
 * the given file, and when successful, adds it to the model.
 * Upon failure, the @file is discarded.
 **/
void
_ctk_file_system_model_add_and_query_file (CtkFileSystemModel *model,
                                           GFile *             file,
                                           const char *        attributes)
{
  g_return_if_fail (CTK_IS_FILE_SYSTEM_MODEL (model));
  g_return_if_fail (G_IS_FILE (file));
  g_return_if_fail (attributes != NULL);

  g_file_query_info_async (file,
                           attributes,
                           G_FILE_QUERY_INFO_NONE,
                           IO_PRIORITY,
                           model->cancellable,
                           ctk_file_system_model_query_done,
                           model);
}

static void
ctk_file_system_model_one_query_done (GObject *     object,
                                      GAsyncResult *res,
                                      gpointer      data)
{
  query_done_helper (object, res, data, TRUE);
}

void
_ctk_file_system_model_add_and_query_files (CtkFileSystemModel *model,
                                            GList              *list,
                                            const char         *attributes)
{
  GList *l;

  g_return_if_fail (CTK_IS_FILE_SYSTEM_MODEL (model));
  g_return_if_fail (attributes != NULL);

  for (l = list; l; l = l->next)
    {
      GFile *file;

      file = (GFile *)l->data;
      freeze_updates (model);
      g_file_query_info_async (file,
                               attributes,
                               G_FILE_QUERY_INFO_NONE,
                               IO_PRIORITY,
                               model->cancellable,
                               ctk_file_system_model_one_query_done,
                               model);
    }
}

GFile *
_ctk_file_system_model_get_directory (CtkFileSystemModel *model)
{
  g_return_val_if_fail (CTK_IS_FILE_SYSTEM_MODEL (model), NULL);

  return model->dir;
}