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
/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */

/*
 *  Baul
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License as
 *  published by the Free Software Foundation; either version 2 of the
 *  License, or (at your option) any later version.
 *
 *  This 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
 *  General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this library; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *  Authors : Mr Jamie McCracken (jamiemcc at blueyonder dot co dot uk)
 *            Cosimo Cecchi <cosimoc@gnome.org>
 *
 */

#include <config.h>
#include <cairo-gobject.h>

#include <cdk/cdkkeysyms.h>
#include <ctk/ctk.h>
#include <glib/gi18n.h>
#include <gio/gio.h>
#include <libnotify/notify.h>

#include <eel/eel-debug.h>
#include <eel/eel-ctk-extensions.h>
#include <eel/eel-glib-extensions.h>
#include <eel/eel-graphic-effects.h>
#include <eel/eel-string.h>
#include <eel/eel-stock-dialogs.h>

#include <libbaul-private/baul-debug-log.h>
#include <libbaul-private/baul-dnd.h>
#include <libbaul-private/baul-bookmark.h>
#include <libbaul-private/baul-global-preferences.h>
#include <libbaul-private/baul-sidebar-provider.h>
#include <libbaul-private/baul-module.h>
#include <libbaul-private/baul-file.h>
#include <libbaul-private/baul-file-utilities.h>
#include <libbaul-private/baul-file-operations.h>
#include <libbaul-private/baul-trash-monitor.h>
#include <libbaul-private/baul-icon-names.h>
#include <libbaul-private/baul-autorun.h>
#include <libbaul-private/baul-window-info.h>
#include <libbaul-private/baul-window-slot-info.h>

#include "baul-bookmark-list.h"
#include "baul-places-sidebar.h"
#include "baul-window.h"

#define EJECT_BUTTON_XPAD 6
#define ICON_CELL_XPAD 6

typedef struct
{
    CtkScrolledWindow  parent;
    CtkTreeView        *tree_view;
    CtkCellRenderer    *eject_icon_cell_renderer;
    char               *uri;
    CtkListStore       *store;
    CtkTreeModel       *filter_model;
    BaulWindowInfo *window;
    BaulBookmarkList *bookmarks;
    GVolumeMonitor *volume_monitor;

    gboolean devices_header_added;
    gboolean bookmarks_header_added;

    /* DnD */
    GList     *drag_list;
    gboolean  drag_data_received;
    int       drag_data_info;
    gboolean  drop_occured;

    CtkWidget *popup_menu;
    CtkWidget *popup_menu_open_in_new_tab_item;
    CtkWidget *popup_menu_remove_item;
    CtkWidget *popup_menu_rename_item;
    CtkWidget *popup_menu_separator_item;
    CtkWidget *popup_menu_mount_item;
    CtkWidget *popup_menu_unmount_item;
    CtkWidget *popup_menu_eject_item;
    CtkWidget *popup_menu_rescan_item;
    CtkWidget *popup_menu_format_item;
    CtkWidget *popup_menu_empty_trash_item;
    CtkWidget *popup_menu_start_item;
    CtkWidget *popup_menu_stop_item;

    /* volume mounting - delayed open process */
    gboolean mounting;
    BaulWindowSlotInfo *go_to_after_mount_slot;
    BaulWindowOpenFlags go_to_after_mount_flags;

    CtkTreePath *eject_highlight_path;
} BaulPlacesSidebar;

typedef struct
{
    CtkScrolledWindowClass parent;
} BaulPlacesSidebarClass;

typedef struct
{
    GObject parent;
} BaulPlacesSidebarProvider;

typedef struct
{
    GObjectClass parent;
} BaulPlacesSidebarProviderClass;

enum
{
    PLACES_SIDEBAR_COLUMN_ROW_TYPE,
    PLACES_SIDEBAR_COLUMN_URI,
    PLACES_SIDEBAR_COLUMN_DRIVE,
    PLACES_SIDEBAR_COLUMN_VOLUME,
    PLACES_SIDEBAR_COLUMN_MOUNT,
    PLACES_SIDEBAR_COLUMN_NAME,
    PLACES_SIDEBAR_COLUMN_ICON,
    PLACES_SIDEBAR_COLUMN_INDEX,
    PLACES_SIDEBAR_COLUMN_EJECT,
    PLACES_SIDEBAR_COLUMN_NO_EJECT,
    PLACES_SIDEBAR_COLUMN_BOOKMARK,
    PLACES_SIDEBAR_COLUMN_TOOLTIP,
    PLACES_SIDEBAR_COLUMN_EJECT_ICON,
    PLACES_SIDEBAR_COLUMN_SECTION_TYPE,
    PLACES_SIDEBAR_COLUMN_HEADING_TEXT,

    PLACES_SIDEBAR_COLUMN_COUNT
};

typedef enum
{
    PLACES_BUILT_IN,
    PLACES_MOUNTED_VOLUME,
    PLACES_BOOKMARK,
    PLACES_HEADING,
} PlaceType;

typedef enum {
    SECTION_COMPUTER,
    SECTION_DEVICES,
    SECTION_BOOKMARKS,
    SECTION_NETWORK,
} SectionType;

static void  baul_places_sidebar_iface_init        (BaulSidebarIface         *iface);
static void  sidebar_provider_iface_init               (BaulSidebarProviderIface *iface);
static GType baul_places_sidebar_provider_get_type (void);
static void  open_selected_bookmark                    (BaulPlacesSidebar        *sidebar,
        CtkTreeModel                 *model,
        CtkTreePath                  *path,
        BaulWindowOpenFlags flags);

static void  baul_places_sidebar_style_updated         (CtkWidget                    *widget);

static gboolean eject_or_unmount_bookmark              (BaulPlacesSidebar *sidebar,
        CtkTreePath *path);
static gboolean eject_or_unmount_selection             (BaulPlacesSidebar *sidebar);
static void  check_unmount_and_eject                   (GMount *mount,
        GVolume *volume,
        GDrive *drive,
        gboolean *show_unmount,
        gboolean *show_eject);

static void bookmarks_check_popup_sensitivity          (BaulPlacesSidebar *sidebar);

/* Identifiers for target types */
enum
{
    CTK_TREE_MODEL_ROW,
    TEXT_URI_LIST
};

/* Target types for dragging from the shortcuts list */
static const CtkTargetEntry baul_shortcuts_source_targets[] =
{
    { "CTK_TREE_MODEL_ROW", CTK_TARGET_SAME_WIDGET, CTK_TREE_MODEL_ROW }
};

/* Target types for dropping into the shortcuts list */
static const CtkTargetEntry baul_shortcuts_drop_targets [] =
{
    { "CTK_TREE_MODEL_ROW", CTK_TARGET_SAME_WIDGET, CTK_TREE_MODEL_ROW },
    { "text/uri-list", 0, TEXT_URI_LIST }
};

/* Drag and drop interface declarations */
typedef struct
{
    CtkTreeModelFilter parent;

    BaulPlacesSidebar *sidebar;
} BaulShortcutsModelFilter;

typedef struct
{
    CtkTreeModelFilterClass parent_class;
} BaulShortcutsModelFilterClass;

#define BAUL_SHORTCUTS_MODEL_FILTER_TYPE (_baul_shortcuts_model_filter_get_type ())
#define BAUL_SHORTCUTS_MODEL_FILTER(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), BAUL_SHORTCUTS_MODEL_FILTER_TYPE, BaulShortcutsModelFilter))

GType _baul_shortcuts_model_filter_get_type (void);
static void baul_shortcuts_model_filter_drag_source_iface_init (CtkTreeDragSourceIface *iface);

G_DEFINE_TYPE_WITH_CODE (BaulShortcutsModelFilter,
                         _baul_shortcuts_model_filter,
                         CTK_TYPE_TREE_MODEL_FILTER,
                         G_IMPLEMENT_INTERFACE (CTK_TYPE_TREE_DRAG_SOURCE,
                                 baul_shortcuts_model_filter_drag_source_iface_init));

static CtkTreeModel *baul_shortcuts_model_filter_new (BaulPlacesSidebar *sidebar,
        CtkTreeModel          *child_model,
        CtkTreePath           *root);

G_DEFINE_TYPE_WITH_CODE (BaulPlacesSidebar, baul_places_sidebar, CTK_TYPE_SCROLLED_WINDOW,
                         G_IMPLEMENT_INTERFACE (BAUL_TYPE_SIDEBAR,
                                 baul_places_sidebar_iface_init));

G_DEFINE_TYPE_WITH_CODE (BaulPlacesSidebarProvider, baul_places_sidebar_provider, G_TYPE_OBJECT,
                         G_IMPLEMENT_INTERFACE (BAUL_TYPE_SIDEBAR_PROVIDER,
                                 sidebar_provider_iface_init));

static cairo_surface_t *
get_eject_icon (gboolean highlighted)
{
    GdkPixbuf *eject;
    cairo_surface_t *eject_surface;
    BaulIconInfo *eject_icon_info;
    int icon_size, icon_scale;

    icon_size = baul_get_icon_size_for_stock_size (CTK_ICON_SIZE_MENU);
    icon_scale = cdk_window_get_scale_factor (cdk_get_default_root_window ());

    eject_icon_info = baul_icon_info_lookup_from_name ("media-eject", icon_size, icon_scale);
    eject = baul_icon_info_get_pixbuf_at_size (eject_icon_info, icon_size);

    if (highlighted) {
        GdkPixbuf *high;
        high = eel_create_spotlight_pixbuf (eject);
        g_object_unref (eject);
        eject = high;
    }

    eject_surface = cdk_cairo_surface_create_from_pixbuf (eject, icon_scale, NULL);

    g_object_unref (eject_icon_info);
    g_object_unref (eject);

    return eject_surface;
}

static gboolean
is_built_in_bookmark (BaulFile *file)
{
    gboolean built_in;
    gint idx;

    built_in = FALSE;

    for (idx = 0; idx < G_USER_N_DIRECTORIES; idx++) {
        /* PUBLIC_SHARE and TEMPLATES are not in our built-in list */
        if (baul_file_is_user_special_directory (file, idx)) {
            if (idx != G_USER_DIRECTORY_PUBLIC_SHARE &&  idx != G_USER_DIRECTORY_TEMPLATES) {
                built_in = TRUE;
            }

            break;
        }
    }

    return built_in;
}

static CtkTreeIter
add_heading (BaulPlacesSidebar *sidebar,
         SectionType section_type,
         const gchar *title)
{
    CtkTreeIter iter, child_iter;

    ctk_list_store_append (sidebar->store, &iter);
    ctk_list_store_set (sidebar->store, &iter,
                PLACES_SIDEBAR_COLUMN_ROW_TYPE, PLACES_HEADING,
                PLACES_SIDEBAR_COLUMN_SECTION_TYPE, section_type,
                PLACES_SIDEBAR_COLUMN_HEADING_TEXT, title,
                PLACES_SIDEBAR_COLUMN_EJECT, FALSE,
                PLACES_SIDEBAR_COLUMN_NO_EJECT, TRUE,
                -1);

    ctk_tree_model_filter_refilter (CTK_TREE_MODEL_FILTER (sidebar->filter_model));
    ctk_tree_model_filter_convert_child_iter_to_iter (CTK_TREE_MODEL_FILTER (sidebar->filter_model),
                              &child_iter,
                              &iter);

    return child_iter;
}

static void
check_heading_for_section (BaulPlacesSidebar *sidebar,
               SectionType section_type)
{
    switch (section_type) {
    case SECTION_DEVICES:
        if (!sidebar->devices_header_added) {
            add_heading (sidebar, SECTION_DEVICES,
                     _("Devices"));
            sidebar->devices_header_added = TRUE;
        }

        break;
    case SECTION_BOOKMARKS:
        if (!sidebar->bookmarks_header_added) {
            add_heading (sidebar, SECTION_BOOKMARKS,
                     _("Bookmarks"));
            sidebar->bookmarks_header_added = TRUE;
        }

        break;
    default:
        break;
    }
}

static CtkTreeIter
add_place (BaulPlacesSidebar *sidebar,
           PlaceType place_type,
           SectionType section_type,
           const char *name,
           GIcon *icon,
           const char *uri,
           GDrive *drive,
           GVolume *volume,
           GMount *mount,
           const int index,
           const char *tooltip)
{
    GdkPixbuf       *pixbuf;
    cairo_surface_t *surface;
    CtkTreeIter      iter, child_iter;
    cairo_surface_t *eject;
    BaulIconInfo    *icon_info;
    int              icon_size;
    int              icon_scale;
    gboolean         show_eject;
    gboolean         show_unmount;
    gboolean         show_eject_button;

    check_heading_for_section (sidebar, section_type);

    icon_size = baul_get_icon_size_for_stock_size (CTK_ICON_SIZE_MENU);
    icon_scale = ctk_widget_get_scale_factor (CTK_WIDGET (sidebar));
    icon_info = baul_icon_info_lookup (icon, icon_size, icon_scale);

    pixbuf = baul_icon_info_get_pixbuf_at_size (icon_info, icon_size);
    g_object_unref (icon_info);

    if (pixbuf != NULL)
    {
       surface = cdk_cairo_surface_create_from_pixbuf (pixbuf, icon_scale, NULL);
       g_object_unref (pixbuf);
    }
    else
    {
       surface = NULL;
    }

    check_unmount_and_eject (mount, volume, drive,
                             &show_unmount, &show_eject);

    if (show_unmount || show_eject)
    {
        g_assert (place_type != PLACES_BOOKMARK);
    }

    if (mount == NULL)
    {
        show_eject_button = FALSE;
    }
    else
    {
        show_eject_button = (show_unmount || show_eject);
    }

    if (show_eject_button) {
        eject = get_eject_icon (FALSE);
    } else {
        eject = NULL;
    }

    ctk_list_store_append (sidebar->store, &iter);
    ctk_list_store_set (sidebar->store, &iter,
                        PLACES_SIDEBAR_COLUMN_ICON, surface,
                        PLACES_SIDEBAR_COLUMN_NAME, name,
                        PLACES_SIDEBAR_COLUMN_URI, uri,
                        PLACES_SIDEBAR_COLUMN_DRIVE, drive,
                        PLACES_SIDEBAR_COLUMN_VOLUME, volume,
                        PLACES_SIDEBAR_COLUMN_MOUNT, mount,
                        PLACES_SIDEBAR_COLUMN_ROW_TYPE, place_type,
                        PLACES_SIDEBAR_COLUMN_INDEX, index,
                        PLACES_SIDEBAR_COLUMN_EJECT, show_eject_button,
                        PLACES_SIDEBAR_COLUMN_NO_EJECT, !show_eject_button,
                        PLACES_SIDEBAR_COLUMN_BOOKMARK, place_type != PLACES_BOOKMARK,
                        PLACES_SIDEBAR_COLUMN_TOOLTIP, tooltip,
                        PLACES_SIDEBAR_COLUMN_EJECT_ICON, eject,
                        PLACES_SIDEBAR_COLUMN_SECTION_TYPE, section_type,
                        -1);

    if (surface != NULL)
    {
       cairo_surface_destroy (surface);
    }
    ctk_tree_model_filter_refilter (CTK_TREE_MODEL_FILTER (sidebar->filter_model));
    ctk_tree_model_filter_convert_child_iter_to_iter (CTK_TREE_MODEL_FILTER (sidebar->filter_model),
            &child_iter,
            &iter);
    return child_iter;
}

static void
compare_for_selection (BaulPlacesSidebar *sidebar,
                       const gchar *location,
                       const gchar *added_uri,
                       const gchar *last_uri,
                       CtkTreeIter *iter,
                       CtkTreePath **path)
{
    int res;

    res = g_strcmp0 (added_uri, last_uri);

    if (res == 0)
    {
        /* last_uri always comes first */
        if (*path != NULL)
        {
            ctk_tree_path_free (*path);
        }
        *path = ctk_tree_model_get_path (sidebar->filter_model,
                                         iter);
    }
    else if (g_strcmp0 (location, added_uri) == 0)
    {
        if (*path == NULL)
        {
            *path = ctk_tree_model_get_path (sidebar->filter_model,
                                             iter);
        }
    }
}

static void
update_places (BaulPlacesSidebar *sidebar)
{
    BaulBookmark *bookmark;
    CtkTreeSelection *selection;
    CtkTreeIter last_iter;
    CtkTreePath *select_path;
    CtkTreeModel *model;
    GVolumeMonitor *volume_monitor;
    GList *mounts, *l, *ll;
    GMount *mount;
    GList *drives;
    GDrive *drive;
    GList *volumes;
    GVolume *volume;
    int bookmark_count, index;
    char *location, *mount_uri, *name, *desktop_path, *last_uri;
    const gchar *path;
    GIcon *icon;
    GFile *root;
    BaulWindowSlotInfo *slot;
    char *tooltip;
    GList *network_mounts;
    GList *xdg_dirs;
    BaulFile *file;

    model = NULL;
    last_uri = NULL;
    select_path = NULL;
    bookmark = NULL;

    selection = ctk_tree_view_get_selection (sidebar->tree_view);
    if (ctk_tree_selection_get_selected (selection, &model, &last_iter))
    {
        ctk_tree_model_get (model,
                            &last_iter,
                            PLACES_SIDEBAR_COLUMN_URI, &last_uri, -1);
    }
    ctk_list_store_clear (sidebar->store);

    sidebar->devices_header_added = FALSE;
    sidebar->bookmarks_header_added = FALSE;

    slot = baul_window_info_get_active_slot (sidebar->window);
    location = baul_window_slot_info_get_current_location (slot);

    volume_monitor = sidebar->volume_monitor;

    /* COMPUTER */
    last_iter = add_heading (sidebar, SECTION_COMPUTER,<--- last_iter is assigned
                             _("Computer"));

    /* add built in bookmarks */

    /* home folder */
    char *display_name;

    mount_uri = baul_get_home_directory_uri ();
    display_name = g_filename_display_basename (g_get_home_dir ());
    icon = g_themed_icon_new (BAUL_ICON_HOME);
    last_iter = add_place (sidebar, PLACES_BUILT_IN,<--- last_iter is overwritten
                           SECTION_COMPUTER,
                           display_name, icon,
                           mount_uri, NULL, NULL, NULL, 0,
                           _("Open your personal folder"));
    g_object_unref (icon);
    g_free (display_name);
    compare_for_selection (sidebar,
                           location, mount_uri, last_uri,
                           &last_iter, &select_path);
    g_free (mount_uri);

    /* desktop */
    desktop_path = baul_get_desktop_directory ();
    if (strcmp (g_get_home_dir(), desktop_path) != 0) {
	    mount_uri = g_filename_to_uri (desktop_path, NULL, NULL);
	    icon = g_themed_icon_new (BAUL_ICON_DESKTOP);
	    last_iter = add_place (sidebar, PLACES_BUILT_IN,
	                           SECTION_COMPUTER,
	                           _("Desktop"), icon,
	                           mount_uri, NULL, NULL, NULL, 0,
	                           _("Open the contents of your desktop in a folder"));
	    g_object_unref (icon);
	    compare_for_selection (sidebar,
	                           location, mount_uri, last_uri,
	                           &last_iter, &select_path);
	    g_free (mount_uri);
    }
	g_free (desktop_path);

    /* file system root */
    mount_uri = "file:///"; /* No need to strdup */
    icon = g_themed_icon_new (BAUL_ICON_FILESYSTEM);
    last_iter = add_place (sidebar, PLACES_BUILT_IN,
                           SECTION_COMPUTER,
                           _("File System"), icon,
                           mount_uri, NULL, NULL, NULL, 0,
                           _("Open the contents of the File System"));
    g_object_unref (icon);
    compare_for_selection (sidebar,
                           location, mount_uri, last_uri,
                           &last_iter, &select_path);


    /* XDG directories */
    xdg_dirs = NULL;
    for (index = 0; index < G_USER_N_DIRECTORIES; index++) {

        if (index == G_USER_DIRECTORY_DESKTOP ||
            index == G_USER_DIRECTORY_TEMPLATES ||
            index == G_USER_DIRECTORY_PUBLIC_SHARE) {
            continue;
        }

        path = g_get_user_special_dir (index);

        /* xdg resets special dirs to the home directory in case
         * it's not finiding what it expects. We don't want the home
         * to be added multiple times in that weird configuration.
         */
        if (path == NULL
            || g_strcmp0 (path, g_get_home_dir ()) == 0
            || g_list_find_custom (xdg_dirs, path, (GCompareFunc) g_strcmp0) != NULL) {
            continue;
        }

        root = g_file_new_for_path (path);
        name = g_file_get_basename (root);
        icon = baul_user_special_directory_get_gicon (index);
        mount_uri = g_file_get_uri (root);
        tooltip = g_file_get_parse_name (root);

        last_iter = add_place (sidebar, PLACES_BUILT_IN,
                               SECTION_COMPUTER,
                               name, icon, mount_uri,
                               NULL, NULL, NULL, 0,
                               tooltip);
        compare_for_selection (sidebar,
                               location, mount_uri, last_uri,
                               &last_iter, &select_path);
        g_free (name);
        g_object_unref (root);
        g_object_unref (icon);
        g_free (mount_uri);
        g_free (tooltip);

        xdg_dirs = g_list_prepend (xdg_dirs, (char *)path);
    }
    g_list_free (xdg_dirs);

    mount_uri = "trash:///"; /* No need to strdup */
    icon = baul_trash_monitor_get_icon ();
    last_iter = add_place (sidebar, PLACES_BUILT_IN,
                           SECTION_COMPUTER,
                           _("Trash"), icon, mount_uri,
                           NULL, NULL, NULL, 0,
                           _("Open the trash"));
    compare_for_selection (sidebar,
                           location, mount_uri, last_uri,
                           &last_iter, &select_path);
    g_object_unref (icon);

    /* first go through all connected drives */
    drives = g_volume_monitor_get_connected_drives (volume_monitor);

    for (l = drives; l != NULL; l = l->next)
    {
        drive = l->data;

        volumes = g_drive_get_volumes (drive);
        if (volumes != NULL)
        {
            for (ll = volumes; ll != NULL; ll = ll->next)
            {
                volume = ll->data;
                mount = g_volume_get_mount (volume);
                if (mount != NULL)
                {
                    /* Show mounted volume in the sidebar */
                    icon = g_mount_get_icon (mount);
                    root = g_mount_get_default_location (mount);
                    mount_uri = g_file_get_uri (root);
                    name = g_mount_get_name (mount);
                    tooltip = g_file_get_parse_name (root);

                    last_iter = add_place (sidebar, PLACES_MOUNTED_VOLUME,
                                           SECTION_DEVICES,
                                           name, icon, mount_uri,
                                           drive, volume, mount, 0, tooltip);
                    compare_for_selection (sidebar,
                                           location, mount_uri, last_uri,
                                           &last_iter, &select_path);
                    g_object_unref (root);
                    g_object_unref (mount);
                    g_object_unref (icon);
                    g_free (tooltip);
                    g_free (name);
                    g_free (mount_uri);
                }
                else
                {
                    /* Do show the unmounted volumes in the sidebar;
                     * this is so the user can mount it (in case automounting
                     * is off).
                     *
                     * Also, even if automounting is enabled, this gives a visual
                     * cue that the user should remember to yank out the media if
                     * he just unmounted it.
                     */
                    icon = g_volume_get_icon (volume);
                    name = g_volume_get_name (volume);
                    tooltip = g_strdup_printf (_("Mount and open %s"), name);

                    last_iter = add_place (sidebar, PLACES_MOUNTED_VOLUME,
                                           SECTION_DEVICES,
                                           name, icon, NULL,
                                           drive, volume, NULL, 0, tooltip);
                    g_object_unref (icon);
                    g_free (name);
                    g_free (tooltip);
                }
                g_object_unref (volume);
            }
            g_list_free (volumes);
        }
        else
        {
            if (g_drive_is_media_removable (drive) && !g_drive_is_media_check_automatic (drive))
            {
                /* If the drive has no mountable volumes and we cannot detect media change.. we
                 * display the drive in the sidebar so the user can manually poll the drive by
                 * right clicking and selecting "Rescan..."
                 *
                 * This is mainly for drives like floppies where media detection doesn't
                 * work.. but it's also for human beings who like to turn off media detection
                 * in the OS to save battery juice.
                 */
                icon = g_drive_get_icon (drive);
                name = g_drive_get_name (drive);
                tooltip = g_strdup_printf (_("Mount and open %s"), name);

                last_iter = add_place (sidebar, PLACES_BUILT_IN,
                                       SECTION_DEVICES,
                                       name, icon, NULL,
                                       drive, NULL, NULL, 0, tooltip);
                g_object_unref (icon);
                g_free (tooltip);
                g_free (name);
            }
        }
        g_object_unref (drive);
    }
    g_list_free (drives);

    /* add all volumes that is not associated with a drive */
    volumes = g_volume_monitor_get_volumes (volume_monitor);
    for (l = volumes; l != NULL; l = l->next)
    {
        volume = l->data;
        drive = g_volume_get_drive (volume);
        if (drive != NULL)
        {
            g_object_unref (volume);
            g_object_unref (drive);
            continue;
        }
        mount = g_volume_get_mount (volume);
        if (mount != NULL)
        {
            icon = g_mount_get_icon (mount);
            root = g_mount_get_default_location (mount);
            mount_uri = g_file_get_uri (root);
            tooltip = g_file_get_parse_name (root);
            g_object_unref (root);
            name = g_mount_get_name (mount);
            last_iter = add_place (sidebar, PLACES_MOUNTED_VOLUME,
                                   SECTION_DEVICES,
                                   name, icon, mount_uri,
                                   NULL, volume, mount, 0, tooltip);
            compare_for_selection (sidebar,
                                   location, mount_uri, last_uri,
                                   &last_iter, &select_path);
            g_object_unref (mount);
            g_object_unref (icon);
            g_free (name);
            g_free (tooltip);
            g_free (mount_uri);
        }
        else
        {
            /* see comment above in why we add an icon for an unmounted mountable volume */
            icon = g_volume_get_icon (volume);
            name = g_volume_get_name (volume);
            last_iter = add_place (sidebar, PLACES_MOUNTED_VOLUME,
                                   SECTION_DEVICES,
                                   name, icon, NULL,
                                   NULL, volume, NULL, 0, name);
            g_object_unref (icon);
            g_free (name);
        }
        g_object_unref (volume);
    }
    g_list_free (volumes);

    /* add mounts that has no volume (/etc/mtab mounts, ftp, sftp,...) */
    network_mounts = NULL;
    mounts = g_volume_monitor_get_mounts (volume_monitor);

    for (l = mounts; l != NULL; l = l->next)
    {
        mount = l->data;
        if (g_mount_is_shadowed (mount))
        {
            g_object_unref (mount);
            continue;
        }
        volume = g_mount_get_volume (mount);
        if (volume != NULL)
        {
            g_object_unref (volume);
            g_object_unref (mount);
            continue;
        }
        root = g_mount_get_default_location (mount);

        if (!g_file_is_native (root)) {
            network_mounts = g_list_prepend (network_mounts, g_object_ref (mount));
            continue;
        }

        icon = g_mount_get_icon (mount);
        mount_uri = g_file_get_uri (root);
        name = g_mount_get_name (mount);
        tooltip = g_file_get_parse_name (root);
        last_iter = add_place (sidebar, PLACES_MOUNTED_VOLUME,
                               SECTION_COMPUTER,
                               name, icon, mount_uri,
                               NULL, NULL, mount, 0, tooltip);
        compare_for_selection (sidebar,
                               location, mount_uri, last_uri,
                               &last_iter, &select_path);
        g_object_unref (root);
        g_object_unref (mount);
        g_object_unref (icon);
        g_free (name);
        g_free (mount_uri);
        g_free (tooltip);
    }
    g_list_free (mounts);


    /* add bookmarks */
    bookmark_count = baul_bookmark_list_length (sidebar->bookmarks);

    for (index = 0; index < bookmark_count; ++index) {
        bookmark = baul_bookmark_list_item_at (sidebar->bookmarks, index);

        if (baul_bookmark_uri_known_not_to_exist (bookmark)) {
            continue;
        }

        root = baul_bookmark_get_location (bookmark);
        file = baul_file_get (root);

        if (is_built_in_bookmark (file)) {
            g_object_unref (root);
            baul_file_unref (file);
            continue;
        }

        name = baul_bookmark_get_name (bookmark);
        icon = baul_bookmark_get_icon (bookmark);
        mount_uri = baul_bookmark_get_uri (bookmark);
        tooltip = g_file_get_parse_name (root);

        last_iter = add_place (sidebar, PLACES_BOOKMARK,
                               SECTION_BOOKMARKS,
                               name, icon, mount_uri,
                               NULL, NULL, NULL, index,
                               tooltip);
        compare_for_selection (sidebar,
                               location, mount_uri, last_uri,
                               &last_iter, &select_path);
        g_free (name);
        g_object_unref (root);
        g_object_unref (icon);
        g_free (mount_uri);
        g_free (tooltip);
    }

    /* network */
    last_iter = add_heading (sidebar, SECTION_NETWORK,<--- last_iter is assigned
                             _("Network"));

    network_mounts = g_list_reverse (network_mounts);
    for (l = network_mounts; l != NULL; l = l->next) {
        mount = l->data;
        root = g_mount_get_default_location (mount);
        icon = g_mount_get_icon (mount);
        mount_uri = g_file_get_uri (root);
        name = g_mount_get_name (mount);
        tooltip = g_file_get_parse_name (root);
        last_iter = add_place (sidebar, PLACES_MOUNTED_VOLUME,
                               SECTION_NETWORK,
                               name, icon, mount_uri,
                               NULL, NULL, mount, 0, tooltip);
        compare_for_selection (sidebar,
                               location, mount_uri, last_uri,
                               &last_iter, &select_path);
        g_object_unref (root);
        g_object_unref (mount);
        g_object_unref (icon);
        g_free (name);
        g_free (mount_uri);
        g_free (tooltip);
    }

    g_list_free_full (network_mounts, g_object_unref);

    /* network:// */
    mount_uri = "network:///"; /* No need to strdup */
    icon = g_themed_icon_new (BAUL_ICON_NETWORK);
    last_iter = add_place (sidebar, PLACES_BUILT_IN,<--- last_iter is overwritten
                           SECTION_NETWORK,
                           _("Browse Network"), icon,
                           mount_uri, NULL, NULL, NULL, 0,
                           _("Browse the contents of the network"));
    g_object_unref (icon);
    compare_for_selection (sidebar,
                           location, mount_uri, last_uri,
                           &last_iter, &select_path);

    g_free (location);

    if (select_path != NULL) {
        ctk_tree_selection_select_path (selection, select_path);
    }

    if (select_path != NULL) {
        ctk_tree_path_free (select_path);
    }

    g_free (last_uri);
}

static void
mount_added_callback (GVolumeMonitor *volume_monitor,
                      GMount *mount,
                      BaulPlacesSidebar *sidebar)
{
    update_places (sidebar);
}

static void
mount_removed_callback (GVolumeMonitor *volume_monitor,
                        GMount *mount,
                        BaulPlacesSidebar *sidebar)
{
    update_places (sidebar);
}

static void
mount_changed_callback (GVolumeMonitor *volume_monitor,
                        GMount *mount,
                        BaulPlacesSidebar *sidebar)
{
    update_places (sidebar);
}

static void
volume_added_callback (GVolumeMonitor *volume_monitor,
                       GVolume *volume,
                       BaulPlacesSidebar *sidebar)
{
    update_places (sidebar);
}

static void
volume_removed_callback (GVolumeMonitor *volume_monitor,
                         GVolume *volume,
                         BaulPlacesSidebar *sidebar)
{
    update_places (sidebar);
}

static void
volume_changed_callback (GVolumeMonitor *volume_monitor,
                         GVolume *volume,
                         BaulPlacesSidebar *sidebar)
{
    update_places (sidebar);
}

static void
drive_disconnected_callback (GVolumeMonitor *volume_monitor,
                             GDrive         *drive,
                             BaulPlacesSidebar *sidebar)
{
    update_places (sidebar);
}

static void
drive_connected_callback (GVolumeMonitor *volume_monitor,
                          GDrive         *drive,
                          BaulPlacesSidebar *sidebar)
{
    update_places (sidebar);
}

static void
drive_changed_callback (GVolumeMonitor *volume_monitor,
                        GDrive         *drive,
                        BaulPlacesSidebar *sidebar)
{
    update_places (sidebar);
}

static gboolean
over_eject_button (BaulPlacesSidebar *sidebar,
                   gint x,
                   gint y,
                   CtkTreePath **path)
{
    CtkTreeViewColumn *column;
    int width, x_offset, hseparator;
    int eject_button_size;
    gboolean show_eject;
    CtkTreeIter iter;
    CtkTreeModel *model;

    *path = NULL;
    model = ctk_tree_view_get_model (sidebar->tree_view);

   if (ctk_tree_view_get_path_at_pos (sidebar->tree_view,
                                      x, y,
                                      path, &column, NULL, NULL)) {

        ctk_tree_model_get_iter (model, &iter, *path);
        ctk_tree_model_get (model, &iter,
                            PLACES_SIDEBAR_COLUMN_EJECT, &show_eject,
                            -1);

        if (!show_eject) {
            goto out;
        }

        ctk_widget_style_get (CTK_WIDGET (sidebar->tree_view),
                              "horizontal-separator",&hseparator,
                              NULL);
        /* Reload cell attributes for this particular row */
        ctk_tree_view_column_cell_set_cell_data (column,
                                                 model, &iter, FALSE, FALSE);

        ctk_tree_view_column_cell_get_position (column,
                                                sidebar->eject_icon_cell_renderer,
                                                &x_offset, &width);

        eject_button_size = baul_get_icon_size_for_stock_size (CTK_ICON_SIZE_MENU);

       /* This is kinda weird, but we have to do it to workaround ctk+ expanding
       * the eject cell renderer (even thought we told it not to) and we then
       * had to set it right-aligned */
        x_offset += width - hseparator - EJECT_BUTTON_XPAD - eject_button_size;

        if (x - x_offset >= 0 &&
        x - x_offset <= eject_button_size) {
            return TRUE;
        }
    }

out:
    if (*path != NULL) {
        ctk_tree_path_free (*path);
        *path = NULL;
    }

    return FALSE;
}

static gboolean
clicked_eject_button (BaulPlacesSidebar *sidebar,
                      CtkTreePath **path)
{
    CdkEvent *event = ctk_get_current_event ();
    CdkEventButton *button_event = (CdkEventButton *) event;

    if ((event->type == CDK_BUTTON_PRESS || event->type == CDK_BUTTON_RELEASE) &&
         over_eject_button (sidebar, button_event->x, button_event->y, path)) {
        return TRUE;
    }

    return FALSE;
}

static void
desktop_location_changed_callback (gpointer user_data)
{
    BaulPlacesSidebar *sidebar;

    sidebar = BAUL_PLACES_SIDEBAR (user_data);

    update_places (sidebar);
}

static void
loading_uri_callback (BaulWindowInfo *window,
                      char *location,
                      BaulPlacesSidebar *sidebar)
{
    CtkTreeIter       iter;
    gboolean          valid;
    char             *uri;

    if (strcmp (sidebar->uri, location) != 0)
    {
        CtkTreeSelection *selection;

        g_free (sidebar->uri);
        sidebar->uri = g_strdup (location);

        /* set selection if any place matches location */
        selection = ctk_tree_view_get_selection (sidebar->tree_view);
        ctk_tree_selection_unselect_all (selection);
        valid = ctk_tree_model_get_iter_first (sidebar->filter_model, &iter);

        while (valid)
        {
            ctk_tree_model_get (sidebar->filter_model, &iter,
                                PLACES_SIDEBAR_COLUMN_URI, &uri,
                                -1);
            if (uri != NULL)
            {
                if (strcmp (uri, location) == 0)
                {
                    g_free (uri);
                    ctk_tree_selection_select_iter (selection, &iter);
                    break;
                }
                g_free (uri);
            }
            valid = ctk_tree_model_iter_next (sidebar->filter_model, &iter);
        }
    }
}

/* Computes the appropriate row and position for dropping */
static gboolean
compute_drop_position (CtkTreeView *tree_view,
                       int                      x,
                       int                      y,
                       CtkTreePath            **path,
                       CtkTreeViewDropPosition *pos,
                       BaulPlacesSidebar *sidebar)<--- Parameter 'sidebar' can be declared as pointer to const
{
    CtkTreeModel *model;
    CtkTreeIter iter;
    PlaceType place_type;
    SectionType section_type;

    if (!ctk_tree_view_get_dest_row_at_pos (tree_view,
                                            x,
                                            y,
                                            path,
                                            pos)) {
        return FALSE;
    }

    model = ctk_tree_view_get_model (tree_view);

    ctk_tree_model_get_iter (model, &iter, *path);
    ctk_tree_model_get (model, &iter,
                        PLACES_SIDEBAR_COLUMN_ROW_TYPE, &place_type,
                        PLACES_SIDEBAR_COLUMN_SECTION_TYPE, &section_type,
                        -1);

    if (place_type == PLACES_HEADING &&
        section_type != SECTION_BOOKMARKS &&
        section_type != SECTION_NETWORK) {
        /* never drop on headings, but the bookmarks or network heading
         * is a special case, so we can create new bookmarks by dragging
         * at the beginning or end of the bookmark list.
         */
        ctk_tree_path_free (*path);
        *path = NULL;

        return FALSE;
    }

    if (section_type != SECTION_BOOKMARKS &&
        sidebar->drag_data_received &&
        sidebar->drag_data_info == CTK_TREE_MODEL_ROW) {
        /* don't allow dropping bookmarks into non-bookmark areas */
        ctk_tree_path_free (*path);
        *path = NULL;

        return FALSE;
    }

    /* drag to top or bottom of bookmark list to add a bookmark */
    if (place_type == PLACES_HEADING && section_type == SECTION_BOOKMARKS) {
        *pos = CTK_TREE_VIEW_DROP_AFTER;
    } else if (place_type == PLACES_HEADING && section_type == SECTION_NETWORK) {
        *pos = CTK_TREE_VIEW_DROP_BEFORE;
    } else {
        /* or else you want to drag items INTO the existing bookmarks */
        *pos = CTK_TREE_VIEW_DROP_INTO_OR_BEFORE;
    }

    if (*pos != CTK_TREE_VIEW_DROP_BEFORE &&
        sidebar->drag_data_received &&
        sidebar->drag_data_info == CTK_TREE_MODEL_ROW) {
        /* bookmark rows are never dragged into other bookmark rows */
        *pos = CTK_TREE_VIEW_DROP_AFTER;
    }

    return TRUE;
}

static gboolean
get_drag_data (CtkTreeView *tree_view,
               CdkDragContext *context,
               unsigned int time)
{
    CdkAtom target;

    target = ctk_drag_dest_find_target (CTK_WIDGET (tree_view),
                                        context,
                                        NULL);

    if (target == CDK_NONE)
    {
        return FALSE;
    }

    ctk_drag_get_data (CTK_WIDGET (tree_view),
                       context, target, time);

    return TRUE;
}

static void
free_drag_data (BaulPlacesSidebar *sidebar)
{
    sidebar->drag_data_received = FALSE;

    if (sidebar->drag_list)
    {
        baul_drag_destroy_selection_list (sidebar->drag_list);
        sidebar->drag_list = NULL;
    }
}

static gboolean
can_accept_file_as_bookmark (BaulFile *file)
{
    return (baul_file_is_directory (file) &&
            !is_built_in_bookmark (file));
}

static gboolean
can_accept_items_as_bookmarks (const GList *items)
{
    int max;
    BaulFile *file = NULL;

    /* Iterate through selection checking if item will get accepted as a bookmark.
     * If more than 100 items selected, return an over-optimistic result.
     */
    for (max = 100; items != NULL && max >= 0; items = items->next, max--)
    {
        char *uri;

        uri = ((BaulDragSelectionItem *)items->data)->uri;
        file = baul_file_get_by_uri (uri);
        if (!can_accept_file_as_bookmark (file))
        {
            baul_file_unref (file);
            return FALSE;
        }
        baul_file_unref (file);
    }

    return TRUE;
}

static gboolean
drag_motion_callback (CtkTreeView *tree_view,
                      CdkDragContext *context,
                      int x,
                      int y,
                      unsigned int time,
                      BaulPlacesSidebar *sidebar)
{
    CtkTreePath *path;
    CtkTreeViewDropPosition pos;
    int action = 0;
    CtkTreeIter iter;
    char *uri;
    gboolean res;

    if (!sidebar->drag_data_received)
    {
        if (!get_drag_data (tree_view, context, time))
        {
            return FALSE;
        }
    }

    path = NULL;
    res = compute_drop_position (tree_view, x, y, &path, &pos, sidebar);

    if (!res) {
        goto out;
    }

    if (pos == CTK_TREE_VIEW_DROP_BEFORE ||
        pos == CTK_TREE_VIEW_DROP_AFTER )
    {
        if (sidebar->drag_data_received &&
            sidebar->drag_data_info == CTK_TREE_MODEL_ROW)
        {
            action = CDK_ACTION_MOVE;
        }
        else if (can_accept_items_as_bookmarks (sidebar->drag_list))
        {
            action = CDK_ACTION_COPY;
        }
        else
        {
            action = 0;
        }
    }
    else
    {
        if (sidebar->drag_list == NULL)
        {
            action = 0;
        }
        else
        {
            ctk_tree_model_get_iter (sidebar->filter_model,
                                     &iter, path);
            ctk_tree_model_get (CTK_TREE_MODEL (sidebar->filter_model),
                                &iter,
                                PLACES_SIDEBAR_COLUMN_URI, &uri,
                                -1);
            baul_drag_default_drop_action_for_icons (context, uri,
                    sidebar->drag_list,
                    &action);
            g_free (uri);
        }
    }

    if (action != 0) {
        ctk_tree_view_set_drag_dest_row (tree_view, path, pos);
    }

    if (path != NULL) {
        ctk_tree_path_free (path);
    }

 out:
    g_signal_stop_emission_by_name (tree_view, "drag-motion");

    if (action != 0)
    {
        cdk_drag_status (context, action, time);
    }
    else
    {
        cdk_drag_status (context, 0, time);
    }

    return TRUE;
}

static void
drag_leave_callback (CtkTreeView *tree_view,
                     CdkDragContext *context,
                     unsigned int time,
                     BaulPlacesSidebar *sidebar)
{
    free_drag_data (sidebar);
    ctk_tree_view_set_drag_dest_row (tree_view, NULL, CTK_TREE_VIEW_DROP_BEFORE);
    g_signal_stop_emission_by_name (tree_view, "drag-leave");
}

/* Parses a "text/uri-list" string and inserts its URIs as bookmarks */
static void
bookmarks_drop_uris (BaulPlacesSidebar *sidebar,
                     CtkSelectionData      *selection_data,
                     int                    position)
{
    BaulBookmark *bookmark;
    char *name;
    char **uris;
    int i;
    GFile *location;
    GIcon *icon;
    BaulFile *file = NULL;

    uris = ctk_selection_data_get_uris (selection_data);
    if (!uris)
        return;

    for (i = 0; uris[i]; i++)
    {
        char *uri;

        uri = uris[i];
        file = baul_file_get_by_uri (uri);

        if (!can_accept_file_as_bookmark (file))
        {
            baul_file_unref (file);
            continue;
        }

        uri = baul_file_get_drop_target_uri (file);
        location = g_file_new_for_uri (uri);
        baul_file_unref (file);

        name = baul_compute_title_for_location (location);
        icon = g_themed_icon_new (BAUL_ICON_FOLDER);
        bookmark = baul_bookmark_new (location, name, TRUE, icon);

        if (!baul_bookmark_list_contains (sidebar->bookmarks, bookmark))
        {
            baul_bookmark_list_insert_item (sidebar->bookmarks, bookmark, position++);
        }

        g_object_unref (location);
        g_object_unref (bookmark);
        g_object_unref (icon);
        g_free (name);
        g_free (uri);
    }

    g_strfreev (uris);
}

static GList *
uri_list_from_selection (GList *selection)
{
    GList *ret;
    GList *l;
    BaulDragSelectionItem *item = NULL;

    ret = NULL;
    for (l = selection; l != NULL; l = l->next)
    {
        item = l->data;
        ret = g_list_prepend (ret, item->uri);
    }

    return g_list_reverse (ret);
}

static GList*
build_selection_list (const char *data)
{
    GList *result;
    char **uris;
    int i;
    BaulDragSelectionItem *item = NULL;

    uris = g_uri_list_extract_uris (data);

    result = NULL;
    for (i = 0; uris[i]; i++)
    {
        char *uri;

        uri = uris[i];
        item = baul_drag_selection_item_new ();
        item->uri = g_strdup (uri);
        item->got_icon_position = FALSE;
        result = g_list_prepend (result, item);
    }

    g_strfreev (uris);

    return g_list_reverse (result);
}

static gboolean
get_selected_iter (BaulPlacesSidebar *sidebar,
                   CtkTreeIter *iter)
{
    CtkTreeSelection *selection;

    selection = ctk_tree_view_get_selection (sidebar->tree_view);

    return ctk_tree_selection_get_selected (selection, NULL, iter);
}

/* Reorders the selected bookmark to the specified position */
static void
reorder_bookmarks (BaulPlacesSidebar *sidebar,
                   int                new_position)
{
    CtkTreeIter iter;
    PlaceType type;
    int old_position;

    /* Get the selected path */

    if (!get_selected_iter (sidebar, &iter))
        return;

    ctk_tree_model_get (CTK_TREE_MODEL (sidebar->filter_model), &iter,
                        PLACES_SIDEBAR_COLUMN_ROW_TYPE, &type,
                        PLACES_SIDEBAR_COLUMN_INDEX, &old_position,
                        -1);

    if (type != PLACES_BOOKMARK ||
            old_position < 0 ||
            old_position >= baul_bookmark_list_length (sidebar->bookmarks))
    {
        return;
    }

    baul_bookmark_list_move_item (sidebar->bookmarks, old_position,
                                  new_position);
}

static void
drag_data_received_callback (CtkWidget *widget,
                             CdkDragContext *context,
                             int x,
                             int y,
                             CtkSelectionData *selection_data,
                             unsigned int info,
                             unsigned int time,
                             BaulPlacesSidebar *sidebar)
{
    CtkTreeView *tree_view;
    CtkTreePath *tree_path;
    CtkTreeViewDropPosition tree_pos;
    CtkTreeIter iter;
    int position;
    CtkTreeModel *model;
    char *drop_uri;
    GList *selection_list, *uris;
    PlaceType place_type;
    SectionType section_type;
    gboolean success;

    tree_view = CTK_TREE_VIEW (widget);

    if (!sidebar->drag_data_received)
    {
        if (ctk_selection_data_get_target (selection_data) != CDK_NONE &&
                info == TEXT_URI_LIST)
        {
            sidebar->drag_list = build_selection_list (ctk_selection_data_get_data (selection_data));
        }
        else
        {
            sidebar->drag_list = NULL;
        }
        sidebar->drag_data_received = TRUE;
        sidebar->drag_data_info = info;
    }

    g_signal_stop_emission_by_name (widget, "drag-data-received");

    if (!sidebar->drop_occured)
    {
        return;
    }

    /* Compute position */
    success = compute_drop_position (tree_view, x, y, &tree_path, &tree_pos, sidebar);
    if (!success)
        goto out;

    success = FALSE;

    if (tree_pos == CTK_TREE_VIEW_DROP_BEFORE ||
        tree_pos == CTK_TREE_VIEW_DROP_AFTER)
    {
        model = ctk_tree_view_get_model (tree_view);

        if (!ctk_tree_model_get_iter (model, &iter, tree_path))
        {
            goto out;
        }

        ctk_tree_model_get (model, &iter,
                            PLACES_SIDEBAR_COLUMN_SECTION_TYPE, &section_type,
                            PLACES_SIDEBAR_COLUMN_ROW_TYPE, &place_type,
                            PLACES_SIDEBAR_COLUMN_INDEX, &position,
                            -1);

        if (section_type != SECTION_BOOKMARKS &&
            !(section_type == SECTION_NETWORK && place_type == PLACES_HEADING)) {
            goto out;
        }

        if (section_type == SECTION_NETWORK && place_type == PLACES_HEADING &&
            tree_pos == CTK_TREE_VIEW_DROP_BEFORE) {
            position = baul_bookmark_list_length (sidebar->bookmarks);
        }

        if (tree_pos == CTK_TREE_VIEW_DROP_AFTER && place_type != PLACES_HEADING) {
            /* heading already has position 0 */
            position++;
        }

        switch (info)
        {
        case TEXT_URI_LIST:
            bookmarks_drop_uris (sidebar, selection_data, position);
            success = TRUE;
            break;
        case CTK_TREE_MODEL_ROW:
            reorder_bookmarks (sidebar, position);
            success = TRUE;
            break;
        default:
            g_assert_not_reached ();
            break;
        }
    }
    else
    {
        CdkDragAction real_action;

        /* file transfer requested */
        real_action = cdk_drag_context_get_selected_action (context);

        if (real_action == CDK_ACTION_ASK)
        {
            real_action =
                baul_drag_drop_action_ask (CTK_WIDGET (tree_view),
                                           cdk_drag_context_get_actions (context));
        }

        if (real_action > 0)
        {
            model = ctk_tree_view_get_model (tree_view);

            ctk_tree_model_get_iter (model, &iter, tree_path);
            ctk_tree_model_get (model, &iter,
                                PLACES_SIDEBAR_COLUMN_URI, &drop_uri,
                                -1);

            switch (info)
            {
            case TEXT_URI_LIST:
                selection_list = build_selection_list (ctk_selection_data_get_data (selection_data));
                uris = uri_list_from_selection (selection_list);
                baul_file_operations_copy_move (uris, NULL, drop_uri,
                                                real_action, CTK_WIDGET (tree_view),
                                                NULL, NULL);
                baul_drag_destroy_selection_list (selection_list);
                g_list_free (uris);
                success = TRUE;
                break;
            case CTK_TREE_MODEL_ROW:
                success = FALSE;
                break;
            default:
                g_assert_not_reached ();
                break;
            }

            g_free (drop_uri);
        }
    }

out:
    sidebar->drop_occured = FALSE;
    free_drag_data (sidebar);
    ctk_drag_finish (context, success, FALSE, time);

    ctk_tree_path_free (tree_path);
}

static gboolean
drag_drop_callback (CtkTreeView *tree_view,
                    CdkDragContext *context,
                    int x,
                    int y,
                    unsigned int time,
                    BaulPlacesSidebar *sidebar)
{
    gboolean retval = FALSE;
    sidebar->drop_occured = TRUE;
    retval = get_drag_data (tree_view, context, time);
    g_signal_stop_emission_by_name (tree_view, "drag-drop");
    return retval;
}

/* Callback used when the file list's popup menu is detached */
static void
bookmarks_popup_menu_detach_cb (CtkWidget *attach_widget,
                                CtkMenu   *menu)
{
    BaulPlacesSidebar *sidebar;

    sidebar = BAUL_PLACES_SIDEBAR (attach_widget);
    g_assert (BAUL_IS_PLACES_SIDEBAR (sidebar));

    sidebar->popup_menu = NULL;
    sidebar->popup_menu_remove_item = NULL;
    sidebar->popup_menu_rename_item = NULL;
    sidebar->popup_menu_separator_item = NULL;
    sidebar->popup_menu_mount_item = NULL;
    sidebar->popup_menu_unmount_item = NULL;
    sidebar->popup_menu_eject_item = NULL;
    sidebar->popup_menu_rescan_item = NULL;
    sidebar->popup_menu_format_item = NULL;
    sidebar->popup_menu_start_item = NULL;
    sidebar->popup_menu_stop_item = NULL;
    sidebar->popup_menu_empty_trash_item = NULL;
}

static void
check_unmount_and_eject (GMount *mount,
                         GVolume *volume,
                         GDrive *drive,
                         gboolean *show_unmount,
                         gboolean *show_eject)
{
    *show_unmount = FALSE;
    *show_eject = FALSE;

    if (drive != NULL)
    {
        *show_eject = g_drive_can_eject (drive);
    }

    if (volume != NULL)
    {
        *show_eject |= g_volume_can_eject (volume);
    }
    if (mount != NULL)
    {
        *show_eject |= g_mount_can_eject (mount);
        *show_unmount = g_mount_can_unmount (mount) && !*show_eject;
    }
}

static void
check_visibility (GMount           *mount,
                  GVolume          *volume,
                  GDrive           *drive,
                  gboolean         *show_mount,
                  gboolean         *show_unmount,
                  gboolean         *show_eject,
                  gboolean         *show_rescan,
                  gboolean         *show_format,
                  gboolean         *show_start,
                  gboolean         *show_stop)
{
    *show_mount = FALSE;
    *show_format = FALSE;
    *show_rescan = FALSE;
    *show_start = FALSE;
    *show_stop = FALSE;

    check_unmount_and_eject (mount, volume, drive, show_unmount, show_eject);

    if (drive != NULL)
    {
        if (g_drive_is_media_removable (drive) &&
                !g_drive_is_media_check_automatic (drive) &&
                g_drive_can_poll_for_media (drive))
            *show_rescan = TRUE;

        *show_start = g_drive_can_start (drive) || g_drive_can_start_degraded (drive);
        *show_stop  = g_drive_can_stop (drive);

        if (*show_stop)
            *show_unmount = FALSE;
    }

    if (volume != NULL)
    {
        if (mount == NULL)
            *show_mount = g_volume_can_mount (volume);
    }
}

static void
bookmarks_check_popup_sensitivity (BaulPlacesSidebar *sidebar)
{
    CtkTreeIter iter;
    PlaceType type;
    GDrive *drive = NULL;
    GVolume *volume = NULL;
    GMount *mount = NULL;
    gboolean show_mount;
    gboolean show_unmount;
    gboolean show_eject;
    gboolean show_rescan;
    gboolean show_format;
    gboolean show_start;
    gboolean show_stop;
    gboolean show_empty_trash;
    char *uri = NULL;

    type = PLACES_BUILT_IN;

    if (sidebar->popup_menu == NULL)
    {
        return;
    }

    if (get_selected_iter (sidebar, &iter))
    {
        ctk_tree_model_get (CTK_TREE_MODEL (sidebar->filter_model), &iter,
                            PLACES_SIDEBAR_COLUMN_ROW_TYPE, &type,
                            PLACES_SIDEBAR_COLUMN_DRIVE, &drive,
                            PLACES_SIDEBAR_COLUMN_VOLUME, &volume,
                            PLACES_SIDEBAR_COLUMN_MOUNT, &mount,
                            PLACES_SIDEBAR_COLUMN_URI, &uri,
                            -1);
    }

    ctk_widget_show (sidebar->popup_menu_open_in_new_tab_item);

    ctk_widget_set_sensitive (sidebar->popup_menu_remove_item, (type == PLACES_BOOKMARK));
    ctk_widget_set_sensitive (sidebar->popup_menu_rename_item, (type == PLACES_BOOKMARK));
    ctk_widget_set_sensitive (sidebar->popup_menu_empty_trash_item, !baul_trash_monitor_is_empty ());

    check_visibility (mount, volume, drive,
                      &show_mount, &show_unmount, &show_eject, &show_rescan, &show_format, &show_start, &show_stop);

    /* We actually want both eject and unmount since eject will unmount all volumes.
     * TODO: hide unmount if the drive only has a single mountable volume
     */

    show_empty_trash = (uri != NULL) &&
                       (!strcmp (uri, "trash:///"));

    ctk_widget_set_visible (sidebar->popup_menu_separator_item,
                              show_mount || show_unmount || show_eject || show_format || show_empty_trash);
    ctk_widget_set_visible (sidebar->popup_menu_mount_item, show_mount);
    ctk_widget_set_visible (sidebar->popup_menu_unmount_item, show_unmount);
    ctk_widget_set_visible (sidebar->popup_menu_eject_item, show_eject);
    ctk_widget_set_visible (sidebar->popup_menu_rescan_item, show_rescan);
    ctk_widget_set_visible (sidebar->popup_menu_format_item, show_format);
    ctk_widget_set_visible (sidebar->popup_menu_start_item, show_start);
    ctk_widget_set_visible (sidebar->popup_menu_stop_item, show_stop);
    ctk_widget_set_visible (sidebar->popup_menu_empty_trash_item, show_empty_trash);

    /* Adjust start/stop items to reflect the type of the drive */
    ctk_menu_item_set_label (CTK_MENU_ITEM (sidebar->popup_menu_start_item), _("_Start"));
    ctk_menu_item_set_label (CTK_MENU_ITEM (sidebar->popup_menu_stop_item), _("_Stop"));
    if ((show_start || show_stop) && drive != NULL)
    {
        switch (g_drive_get_start_stop_type (drive))
        {
        case G_DRIVE_START_STOP_TYPE_SHUTDOWN:
            /* start() for type G_DRIVE_START_STOP_TYPE_SHUTDOWN is normally not used */
            ctk_menu_item_set_label (CTK_MENU_ITEM (sidebar->popup_menu_start_item), _("_Power On"));
            ctk_menu_item_set_label (CTK_MENU_ITEM (sidebar->popup_menu_stop_item), _("_Safely Remove Drive"));
            break;
        case G_DRIVE_START_STOP_TYPE_NETWORK:
            ctk_menu_item_set_label (CTK_MENU_ITEM (sidebar->popup_menu_start_item), _("_Connect Drive"));
            ctk_menu_item_set_label (CTK_MENU_ITEM (sidebar->popup_menu_stop_item), _("_Disconnect Drive"));
            break;
        case G_DRIVE_START_STOP_TYPE_MULTIDISK:
            ctk_menu_item_set_label (CTK_MENU_ITEM (sidebar->popup_menu_start_item), _("_Start Multi-disk Device"));
            ctk_menu_item_set_label (CTK_MENU_ITEM (sidebar->popup_menu_stop_item), _("_Stop Multi-disk Device"));
            break;
        case G_DRIVE_START_STOP_TYPE_PASSWORD:
            /* stop() for type G_DRIVE_START_STOP_TYPE_PASSWORD is normally not used */
            ctk_menu_item_set_label (CTK_MENU_ITEM (sidebar->popup_menu_start_item), _("_Unlock Drive"));
            ctk_menu_item_set_label (CTK_MENU_ITEM (sidebar->popup_menu_stop_item), _("_Lock Drive"));
            break;

        default:
        case G_DRIVE_START_STOP_TYPE_UNKNOWN:
            /* uses defaults set above */
            break;
        }
    }


    g_free (uri);
}

/* Callback used when the selection in the shortcuts tree changes */
static void
bookmarks_selection_changed_cb (CtkTreeSelection      *selection,
                                BaulPlacesSidebar *sidebar)
{
    bookmarks_check_popup_sensitivity (sidebar);
}

static void
volume_mounted_cb (GVolume *volume,
                   GObject *user_data)
{
    GMount *mount;
    BaulPlacesSidebar *sidebar;

    sidebar = BAUL_PLACES_SIDEBAR (user_data);

    sidebar->mounting = FALSE;

    mount = g_volume_get_mount (volume);
    if (mount != NULL)
    {
        GFile *location;

        location = g_mount_get_default_location (mount);

        if (sidebar->go_to_after_mount_slot != NULL)
        {
            if ((sidebar->go_to_after_mount_flags & BAUL_WINDOW_OPEN_FLAG_NEW_WINDOW) == 0)
            {
                baul_window_slot_info_open_location (sidebar->go_to_after_mount_slot, location,
                                                     BAUL_WINDOW_OPEN_ACCORDING_TO_MODE,
                                                     sidebar->go_to_after_mount_flags, NULL);
            }
            else
            {
                BaulWindow *cur, *new;

                cur = BAUL_WINDOW (sidebar->window);
                new = baul_application_create_navigation_window (cur->application,
                        ctk_window_get_screen (CTK_WINDOW (cur)));
                baul_window_go_to (new, location);
            }
        }

        g_object_unref (G_OBJECT (location));
        g_object_unref (G_OBJECT (mount));
    }


    eel_remove_weak_pointer (&(sidebar->go_to_after_mount_slot));
}

static void
drive_start_from_bookmark_cb (GObject      *source_object,
                              GAsyncResult *res,
                              gpointer      user_data)
{
    GError *error;

    error = NULL;
    if (!g_drive_start_finish (G_DRIVE (source_object), res, &error))
    {
        if (error->code != G_IO_ERROR_FAILED_HANDLED)
        {
            char *primary;
            char *name;

            name = g_drive_get_name (G_DRIVE (source_object));
            primary = g_strdup_printf (_("Unable to start %s"), name);
            g_free (name);
            eel_show_error_dialog (primary,
                                   error->message,
                                   NULL);
            g_free (primary);
        }
        g_error_free (error);
    }
}

static void
open_selected_bookmark (BaulPlacesSidebar   *sidebar,
                        CtkTreeModel        *model,
                        CtkTreePath         *path,
                        BaulWindowOpenFlags  flags)
{
    BaulWindowSlotInfo *slot;
    CtkTreeIter iter;
    char *uri;

    if (!path)
    {
        return;
    }

    if (!ctk_tree_model_get_iter (model, &iter, path))
    {
        return;
    }

    ctk_tree_model_get (model, &iter, PLACES_SIDEBAR_COLUMN_URI, &uri, -1);

    if (uri != NULL)
    {
        GFile *location;

        baul_debug_log (FALSE, BAUL_DEBUG_LOG_DOMAIN_USER,
                        "activate from places sidebar window=%p: %s",
                        sidebar->window, uri);
        location = g_file_new_for_uri (uri);
        /* Navigate to the clicked location */
        if ((flags & BAUL_WINDOW_OPEN_FLAG_NEW_WINDOW) == 0)
        {
            slot = baul_window_info_get_active_slot (sidebar->window);
            baul_window_slot_info_open_location (slot, location,
                                                 BAUL_WINDOW_OPEN_ACCORDING_TO_MODE,
                                                 flags, NULL);
        }
        else
        {
            BaulWindow *cur, *new;

            cur = BAUL_WINDOW (sidebar->window);
            new = baul_application_create_navigation_window (cur->application,
                    ctk_window_get_screen (CTK_WINDOW (cur)));
            baul_window_go_to (new, location);
        }
        g_object_unref (location);
        g_free (uri);

    }
    else
    {
        GDrive *drive;
        GVolume *volume;

        ctk_tree_model_get (model, &iter,
                            PLACES_SIDEBAR_COLUMN_DRIVE, &drive,
                            PLACES_SIDEBAR_COLUMN_VOLUME, &volume,
                            -1);

        if (volume != NULL && !sidebar->mounting)
        {
            sidebar->mounting = TRUE;

            g_assert (sidebar->go_to_after_mount_slot == NULL);

            slot = baul_window_info_get_active_slot (sidebar->window);
            sidebar->go_to_after_mount_slot = slot;
            eel_add_weak_pointer (&(sidebar->go_to_after_mount_slot));

            sidebar->go_to_after_mount_flags = flags;

            baul_file_operations_mount_volume_full (NULL, volume, FALSE,
                                                    volume_mounted_cb,
                                                    G_OBJECT (sidebar));
        }
        else if (volume == NULL && drive != NULL &&
                 (g_drive_can_start (drive) || g_drive_can_start_degraded (drive)))
        {
            GMountOperation *mount_op;

            mount_op = ctk_mount_operation_new (CTK_WINDOW (ctk_widget_get_toplevel (CTK_WIDGET (sidebar))));
            g_drive_start (drive, G_DRIVE_START_NONE, mount_op, NULL, drive_start_from_bookmark_cb, NULL);
            g_object_unref (mount_op);
        }

        if (drive != NULL)
            g_object_unref (drive);
        if (volume != NULL)
            g_object_unref (volume);
    }
}

static void
open_shortcut_from_menu (BaulPlacesSidebar   *sidebar,
                         BaulWindowOpenFlags  flags)
{
    CtkTreeModel *model;
    CtkTreePath *path;

    model = ctk_tree_view_get_model (sidebar->tree_view);
    ctk_tree_view_get_cursor (sidebar->tree_view, &path, NULL);

    open_selected_bookmark (sidebar, model, path, flags);

    ctk_tree_path_free (path);
}

static void
open_shortcut_cb (CtkMenuItem       *item,
                  BaulPlacesSidebar *sidebar)
{
    open_shortcut_from_menu (sidebar, 0);
}

static void
open_shortcut_in_new_window_cb (CtkMenuItem       *item,
                                BaulPlacesSidebar *sidebar)
{
    open_shortcut_from_menu (sidebar, BAUL_WINDOW_OPEN_FLAG_NEW_WINDOW);
}

static void
open_shortcut_in_new_tab_cb (CtkMenuItem       *item,
                             BaulPlacesSidebar *sidebar)
{
    open_shortcut_from_menu (sidebar, BAUL_WINDOW_OPEN_FLAG_NEW_TAB);
}

/* Rename the selected bookmark */
static void
rename_selected_bookmark (BaulPlacesSidebar *sidebar)
{
    CtkTreeIter iter;

    if (get_selected_iter (sidebar, &iter))
    {
        CtkTreePath *path;
        CtkTreeViewColumn *column;
        CtkCellRenderer *cell;
        GList *renderers;

        path = ctk_tree_model_get_path (CTK_TREE_MODEL (sidebar->filter_model), &iter);
        column = ctk_tree_view_get_column (CTK_TREE_VIEW (sidebar->tree_view), 0);
        renderers = ctk_cell_layout_get_cells (CTK_CELL_LAYOUT (column));
        cell = g_list_nth_data (renderers, 6);
        g_list_free (renderers);
        g_object_set (cell, "editable", TRUE, NULL);
        ctk_tree_view_set_cursor_on_cell (CTK_TREE_VIEW (sidebar->tree_view),
                                          path, column, cell, TRUE);
        ctk_tree_path_free (path);
    }
}

static void
rename_shortcut_cb (CtkMenuItem           *item,
                    BaulPlacesSidebar *sidebar)
{
    rename_selected_bookmark (sidebar);
}

/* Removes the selected bookmarks */
static void
remove_selected_bookmarks (BaulPlacesSidebar *sidebar)
{
    CtkTreeIter iter;
    PlaceType type;
    int index;

    if (!get_selected_iter (sidebar, &iter))
    {
        return;
    }

    ctk_tree_model_get (CTK_TREE_MODEL (sidebar->filter_model), &iter,
                        PLACES_SIDEBAR_COLUMN_ROW_TYPE, &type,
                        -1);

    if (type != PLACES_BOOKMARK)
    {
        return;
    }

    ctk_tree_model_get (CTK_TREE_MODEL (sidebar->filter_model), &iter,
                        PLACES_SIDEBAR_COLUMN_INDEX, &index,
                        -1);

    baul_bookmark_list_delete_item_at (sidebar->bookmarks, index);
}

static void
remove_shortcut_cb (CtkMenuItem           *item,
                    BaulPlacesSidebar *sidebar)
{
    remove_selected_bookmarks (sidebar);
}

static void
mount_shortcut_cb (CtkMenuItem           *item,
                   BaulPlacesSidebar *sidebar)
{
    CtkTreeIter iter;
    GVolume *volume;

    if (!get_selected_iter (sidebar, &iter))
    {
        return;
    }

    ctk_tree_model_get (CTK_TREE_MODEL (sidebar->filter_model), &iter,
                        PLACES_SIDEBAR_COLUMN_VOLUME, &volume,
                        -1);

    if (volume != NULL)
    {
        baul_file_operations_mount_volume (NULL, volume, FALSE);
        g_object_unref (volume);
    }
}

static void
unmount_done (gpointer data)
{
    BaulWindow *window;

    window = data;
    baul_window_info_set_initiated_unmount (window, FALSE);
    g_object_unref (window);
}

static void
do_unmount (GMount *mount,
            BaulPlacesSidebar *sidebar)
{
    if (mount != NULL)
    {
        baul_window_info_set_initiated_unmount (sidebar->window, TRUE);
        baul_file_operations_unmount_mount_full (NULL, mount, FALSE, TRUE,
                unmount_done,
                g_object_ref (sidebar->window));
    }
}

static void
do_unmount_selection (BaulPlacesSidebar *sidebar)
{
    CtkTreeIter iter;
    GMount *mount;

    if (!get_selected_iter (sidebar, &iter))
    {
        return;
    }

    ctk_tree_model_get (CTK_TREE_MODEL (sidebar->filter_model), &iter,
                        PLACES_SIDEBAR_COLUMN_MOUNT, &mount,
                        -1);

    if (mount != NULL)
    {
        do_unmount (mount, sidebar);
        g_object_unref (mount);
    }
}

static void
unmount_shortcut_cb (CtkMenuItem           *item,
                     BaulPlacesSidebar *sidebar)
{
    do_unmount_selection (sidebar);
}

static void
drive_eject_cb (GObject *source_object,
                GAsyncResult *res,
                gpointer user_data)
{
    BaulWindow *window;
    GError *error;

    window = user_data;
    baul_window_info_set_initiated_unmount (window, FALSE);
    g_object_unref (window);

    error = NULL;
    if (!g_drive_eject_with_operation_finish (G_DRIVE (source_object), res, &error))
    {
        if (error->code != G_IO_ERROR_FAILED_HANDLED)
        {
            char *primary;
            char *name;

            name = g_drive_get_name (G_DRIVE (source_object));
            primary = g_strdup_printf (_("Unable to eject %s"), name);
            g_free (name);
            eel_show_error_dialog (primary,
                                   error->message,
                                   NULL);
            g_free (primary);
        }
        g_error_free (error);
    }
}

static void
volume_eject_cb (GObject *source_object,
                 GAsyncResult *res,
                 gpointer user_data)
{
    BaulWindow *window;
    GError *error;

    window = user_data;
    baul_window_info_set_initiated_unmount (window, FALSE);
    g_object_unref (window);

    error = NULL;
    if (!g_volume_eject_with_operation_finish (G_VOLUME (source_object), res, &error))
    {
        if (error->code != G_IO_ERROR_FAILED_HANDLED)
        {
            char *primary;
            char *name;

            name = g_volume_get_name (G_VOLUME (source_object));
            primary = g_strdup_printf (_("Unable to eject %s"), name);
            g_free (name);
            eel_show_error_dialog (primary,
                                   error->message,
                                   NULL);
            g_free (primary);
        }
        g_error_free (error);
    }

    else {
        baul_application_notify_unmount_show (_("It is now safe to remove the drive"));
    }
}

static void
mount_eject_cb (GObject *source_object,
                GAsyncResult *res,
                gpointer user_data)
{
    BaulWindow *window;
    GError *error;

    window = user_data;
    baul_window_info_set_initiated_unmount (window, FALSE);
    g_object_unref (window);

    error = NULL;
    if (!g_mount_eject_with_operation_finish (G_MOUNT (source_object), res, &error))
    {
        if (error->code != G_IO_ERROR_FAILED_HANDLED)
        {
            char *primary;
            char *name;

            name = g_mount_get_name (G_MOUNT (source_object));
            primary = g_strdup_printf (_("Unable to eject %s"), name);
            g_free (name);
            eel_show_error_dialog (primary,
                                   error->message,
                                   NULL);
            g_free (primary);
        }
        g_error_free (error);
    }

    else {
        baul_application_notify_unmount_show (_("It is now safe to remove the drive"));
    }
}

static void
do_eject (GMount *mount,
          GVolume *volume,
          GDrive *drive,
          BaulPlacesSidebar *sidebar)
{

    GMountOperation *mount_op;

    mount_op = ctk_mount_operation_new (CTK_WINDOW (ctk_widget_get_toplevel (CTK_WIDGET (sidebar))));

    if (mount != NULL)
    {
        baul_window_info_set_initiated_unmount (sidebar->window, TRUE);
        g_mount_eject_with_operation (mount, 0, mount_op, NULL, mount_eject_cb,
                                      g_object_ref (sidebar->window));
    }
    else if (volume != NULL)
    {
        baul_window_info_set_initiated_unmount (sidebar->window, TRUE);
        g_volume_eject_with_operation (volume, 0, mount_op, NULL, volume_eject_cb,
                                       g_object_ref (sidebar->window));
    }
    else if (drive != NULL)
    {
        baul_window_info_set_initiated_unmount (sidebar->window, TRUE);
        g_drive_eject_with_operation (drive, 0, mount_op, NULL, drive_eject_cb,
                                      g_object_ref (sidebar->window));
    }

    baul_application_notify_unmount_show (_("Writing data to the drive -- do not unplug"));
    g_object_unref (mount_op);
}

static void
eject_shortcut_cb (CtkMenuItem           *item,
                   BaulPlacesSidebar *sidebar)
{
    CtkTreeIter iter;
    GMount *mount;
    GVolume *volume;
    GDrive *drive;

    if (!get_selected_iter (sidebar, &iter))
    {
        return;
    }

    ctk_tree_model_get (CTK_TREE_MODEL (sidebar->filter_model), &iter,
                        PLACES_SIDEBAR_COLUMN_MOUNT, &mount,
                        PLACES_SIDEBAR_COLUMN_VOLUME, &volume,
                        PLACES_SIDEBAR_COLUMN_DRIVE, &drive,
                        -1);

    do_eject (mount, volume, drive, sidebar);
}

static gboolean
eject_or_unmount_bookmark (BaulPlacesSidebar *sidebar,
                           CtkTreePath *path)
{
    CtkTreeModel *model;
    CtkTreeIter iter;
    gboolean can_unmount, can_eject;
    GMount *mount;
    GVolume *volume;
    GDrive *drive;
    gboolean ret;

    model = CTK_TREE_MODEL (sidebar->filter_model);

    if (!path)
    {
        return FALSE;
    }
    if (!ctk_tree_model_get_iter (model, &iter, path))
    {
        return FALSE;
    }

    ctk_tree_model_get (model, &iter,
                        PLACES_SIDEBAR_COLUMN_MOUNT, &mount,
                        PLACES_SIDEBAR_COLUMN_VOLUME, &volume,
                        PLACES_SIDEBAR_COLUMN_DRIVE, &drive,
                        -1);

    ret = FALSE;

    check_unmount_and_eject (mount, volume, drive, &can_unmount, &can_eject);
    /* if we can eject, it has priority over unmount */
    if (can_eject)
    {
        do_eject (mount, volume, drive, sidebar);
        ret = TRUE;
    }
    else if (can_unmount)
    {
        do_unmount (mount, sidebar);
        ret = TRUE;
    }

    if (mount != NULL)
        g_object_unref (mount);
    if (volume != NULL)
        g_object_unref (volume);
    if (drive != NULL)
        g_object_unref (drive);

    return ret;
}

static gboolean
eject_or_unmount_selection (BaulPlacesSidebar *sidebar)
{
    CtkTreeIter iter;
    CtkTreePath *path;
    gboolean ret;

    if (!get_selected_iter (sidebar, &iter)) {
        return FALSE;
    }

    path = ctk_tree_model_get_path (CTK_TREE_MODEL (sidebar->filter_model), &iter);
    if (path == NULL) {
        return FALSE;
    }

    ret = eject_or_unmount_bookmark (sidebar, path);

    ctk_tree_path_free (path);

    return ret;
}

static void
drive_poll_for_media_cb (GObject *source_object,
                         GAsyncResult *res,
                         gpointer user_data)
{
    GError *error;

    error = NULL;
    if (!g_drive_poll_for_media_finish (G_DRIVE (source_object), res, &error))
    {
        if (error->code != G_IO_ERROR_FAILED_HANDLED)
        {
            char *primary;
            char *name;

            name = g_drive_get_name (G_DRIVE (source_object));
            primary = g_strdup_printf (_("Unable to poll %s for media changes"), name);
            g_free (name);
            eel_show_error_dialog (primary,
                                   error->message,
                                   NULL);
            g_free (primary);
        }
        g_error_free (error);
    }
}

static void
rescan_shortcut_cb (CtkMenuItem           *item,
                    BaulPlacesSidebar *sidebar)
{
    CtkTreeIter iter;
    GDrive  *drive;

    if (!get_selected_iter (sidebar, &iter))
    {
        return;
    }

    ctk_tree_model_get (CTK_TREE_MODEL (sidebar->filter_model), &iter,
                        PLACES_SIDEBAR_COLUMN_DRIVE, &drive,
                        -1);

    if (drive != NULL)
    {
        g_drive_poll_for_media (drive, NULL, drive_poll_for_media_cb, NULL);
    }
    g_object_unref (drive);
}

static void
format_shortcut_cb (CtkMenuItem           *item,
                    BaulPlacesSidebar *sidebar)
{
    g_spawn_command_line_async ("gfloppy", NULL);
}

static void
drive_start_cb (GObject      *source_object,
                GAsyncResult *res,
                gpointer      user_data)
{
    GError *error;

    error = NULL;
    if (!g_drive_start_finish (G_DRIVE (source_object), res, &error))
    {
        if (error->code != G_IO_ERROR_FAILED_HANDLED)
        {
            char *primary;
            char *name;

            name = g_drive_get_name (G_DRIVE (source_object));
            primary = g_strdup_printf (_("Unable to start %s"), name);
            g_free (name);
            eel_show_error_dialog (primary,
                                   error->message,
                                   NULL);
            g_free (primary);
        }
        g_error_free (error);
    }
}

static void
start_shortcut_cb (CtkMenuItem           *item,
                   BaulPlacesSidebar *sidebar)
{
    CtkTreeIter iter;
    GDrive  *drive;

    if (!get_selected_iter (sidebar, &iter))
    {
        return;
    }

    ctk_tree_model_get (CTK_TREE_MODEL (sidebar->filter_model), &iter,
                        PLACES_SIDEBAR_COLUMN_DRIVE, &drive,
                        -1);

    if (drive != NULL)
    {
        GMountOperation *mount_op;

        mount_op = ctk_mount_operation_new (CTK_WINDOW (ctk_widget_get_toplevel (CTK_WIDGET (sidebar))));

        g_drive_start (drive, G_DRIVE_START_NONE, mount_op, NULL, drive_start_cb, NULL);

        g_object_unref (mount_op);
    }
    g_object_unref (drive);
}

static void
drive_stop_cb (GObject *source_object,
               GAsyncResult *res,
               gpointer user_data)
{
    BaulWindow *window;
    GError *error;

    window = user_data;
    baul_window_info_set_initiated_unmount (window, FALSE);
    g_object_unref (window);

    error = NULL;
    if (!g_drive_stop_finish(G_DRIVE (source_object), res, &error))
    {
        if (error->code != G_IO_ERROR_FAILED_HANDLED)
        {
            char *primary;
            char *name;

            name = g_drive_get_name (G_DRIVE (source_object));
            primary = g_strdup_printf (_("Unable to stop %s"), name);
            g_free (name);
            eel_show_error_dialog (primary,
                                   error->message,
                                   NULL);
            g_free (primary);
        }
        g_error_free (error);
    }
}

static void
stop_shortcut_cb (CtkMenuItem           *item,
                  BaulPlacesSidebar *sidebar)
{
    CtkTreeIter iter;
    GDrive  *drive;

    if (!get_selected_iter (sidebar, &iter))
    {
        return;
    }

    ctk_tree_model_get (CTK_TREE_MODEL (sidebar->filter_model), &iter,
                        PLACES_SIDEBAR_COLUMN_DRIVE, &drive,
                        -1);

    if (drive != NULL)
    {
        GMountOperation *mount_op;

        mount_op = ctk_mount_operation_new (CTK_WINDOW (ctk_widget_get_toplevel (CTK_WIDGET (sidebar))));
        baul_window_info_set_initiated_unmount (sidebar->window, TRUE);
        g_drive_stop (drive, G_MOUNT_UNMOUNT_NONE, mount_op, NULL, drive_stop_cb,
                      g_object_ref (sidebar->window));
        g_object_unref (mount_op);
    }
    g_object_unref (drive);
}

static void
empty_trash_cb (CtkMenuItem           *item,
                BaulPlacesSidebar *sidebar)
{
    baul_file_operations_empty_trash (CTK_WIDGET (sidebar->window));
}

/* Handler for CtkWidget::key-press-event on the shortcuts list */
static gboolean
bookmarks_key_press_event_cb (CtkWidget             *widget,
                              CdkEventKey           *event,<--- Parameter 'event' can be declared as pointer to const
                              BaulPlacesSidebar *sidebar)
{
    guint modifiers;
    CtkTreePath *path;
    BaulWindowOpenFlags flags = 0;

    modifiers = ctk_accelerator_get_default_mod_mask ();

    if (event->keyval == CDK_KEY_Return ||
        event->keyval == CDK_KEY_KP_Enter ||
        event->keyval == CDK_KEY_ISO_Enter ||
        event->keyval == CDK_KEY_space)
    {
        CtkTreeModel *model;

        if ((event->state & modifiers) == CDK_SHIFT_MASK)
            flags = BAUL_WINDOW_OPEN_FLAG_NEW_TAB;
        else if ((event->state & modifiers) == CDK_CONTROL_MASK)
            flags = BAUL_WINDOW_OPEN_FLAG_NEW_WINDOW;

        model = ctk_tree_view_get_model(sidebar->tree_view);
        ctk_tree_view_get_cursor(sidebar->tree_view, &path, NULL);

        open_selected_bookmark(sidebar, model, path, flags);

        ctk_tree_path_free(path);
        return TRUE;
    }

    if (event->keyval == CDK_KEY_Down &&
            (event->state & modifiers) == CDK_MOD1_MASK)
    {
        return eject_or_unmount_selection (sidebar);
    }

    if ((event->keyval == CDK_KEY_Delete
            || event->keyval == CDK_KEY_KP_Delete)
            && (event->state & modifiers) == 0)
    {
        remove_selected_bookmarks (sidebar);
        return TRUE;
    }

    if ((event->keyval == CDK_KEY_F2)
            && (event->state & modifiers) == 0)
    {
        rename_selected_bookmark (sidebar);
        return TRUE;
    }

    return FALSE;
}

/* Constructs the popup menu for the file list if needed */
static void
bookmarks_build_popup_menu (BaulPlacesSidebar *sidebar)
{
    CtkWidget *item;

    if (sidebar->popup_menu)
    {
        return;
    }

    sidebar->popup_menu = ctk_menu_new ();

    ctk_menu_set_reserve_toggle_size (CTK_MENU (sidebar->popup_menu), FALSE);

    ctk_menu_attach_to_widget (CTK_MENU (sidebar->popup_menu),
                               CTK_WIDGET (sidebar),
                               bookmarks_popup_menu_detach_cb);

    item = eel_image_menu_item_new_from_icon ("document-open", _("_Open"));

    g_signal_connect (item, "activate",
                      G_CALLBACK (open_shortcut_cb), sidebar);
    ctk_widget_show (item);
    ctk_menu_shell_append (CTK_MENU_SHELL (sidebar->popup_menu), item);

    item = eel_image_menu_item_new_from_icon (NULL, _("Open in New _Tab"));
    sidebar->popup_menu_open_in_new_tab_item = item;
    g_signal_connect (item, "activate",
                      G_CALLBACK (open_shortcut_in_new_tab_cb), sidebar);
    ctk_widget_show (item);
    ctk_menu_shell_append (CTK_MENU_SHELL (sidebar->popup_menu), item);

    item = eel_image_menu_item_new_from_icon (NULL, _("Open in New _Window"));
    g_signal_connect (item, "activate",
                      G_CALLBACK (open_shortcut_in_new_window_cb), sidebar);
    ctk_widget_show (item);
    ctk_menu_shell_append (CTK_MENU_SHELL (sidebar->popup_menu), item);

    eel_ctk_menu_append_separator (CTK_MENU (sidebar->popup_menu));

    item = eel_image_menu_item_new_from_icon ("list-remove", _("Remove"));

    sidebar->popup_menu_remove_item = item;

    g_signal_connect (item, "activate",
                      G_CALLBACK (remove_shortcut_cb), sidebar);
    ctk_widget_show (item);
    ctk_menu_shell_append (CTK_MENU_SHELL (sidebar->popup_menu), item);

    item = eel_image_menu_item_new_from_icon (NULL, _("Rename..."));
    sidebar->popup_menu_rename_item = item;
    g_signal_connect (item, "activate",
                      G_CALLBACK (rename_shortcut_cb), sidebar);
    ctk_widget_show (item);
    ctk_menu_shell_append (CTK_MENU_SHELL (sidebar->popup_menu), item);

    /* Mount/Unmount/Eject menu items */

    sidebar->popup_menu_separator_item =
        CTK_WIDGET (eel_ctk_menu_append_separator (CTK_MENU (sidebar->popup_menu)));

    item = eel_image_menu_item_new_from_icon (NULL, _("_Mount"));
    sidebar->popup_menu_mount_item = item;
    g_signal_connect (item, "activate",
                      G_CALLBACK (mount_shortcut_cb), sidebar);
    ctk_widget_show (item);
    ctk_menu_shell_append (CTK_MENU_SHELL (sidebar->popup_menu), item);

    item = eel_image_menu_item_new_from_icon ("media-eject", _("_Unmount"));
    sidebar->popup_menu_unmount_item = item;
    g_signal_connect (item, "activate",
                      G_CALLBACK (unmount_shortcut_cb), sidebar);
    ctk_widget_show (item);
    ctk_menu_shell_append (CTK_MENU_SHELL (sidebar->popup_menu), item);

    item = eel_image_menu_item_new_from_icon ("media-eject", _("_Eject"));
    sidebar->popup_menu_eject_item = item;
    g_signal_connect (item, "activate",
                      G_CALLBACK (eject_shortcut_cb), sidebar);
    ctk_widget_show (item);
    ctk_menu_shell_append (CTK_MENU_SHELL (sidebar->popup_menu), item);

    item = eel_image_menu_item_new_from_icon (NULL, _("_Detect Media"));
    sidebar->popup_menu_rescan_item = item;
    g_signal_connect (item, "activate",
                      G_CALLBACK (rescan_shortcut_cb), sidebar);
    ctk_widget_show (item);
    ctk_menu_shell_append (CTK_MENU_SHELL (sidebar->popup_menu), item);

    item = eel_image_menu_item_new_from_icon (NULL, _("_Format"));
    sidebar->popup_menu_format_item = item;
    g_signal_connect (item, "activate",
                      G_CALLBACK (format_shortcut_cb), sidebar);
    ctk_widget_show (item);
    ctk_menu_shell_append (CTK_MENU_SHELL (sidebar->popup_menu), item);

    item = eel_image_menu_item_new_from_icon (NULL, _("_Start"));
    sidebar->popup_menu_start_item = item;
    g_signal_connect (item, "activate",
                      G_CALLBACK (start_shortcut_cb), sidebar);
    ctk_widget_show (item);
    ctk_menu_shell_append (CTK_MENU_SHELL (sidebar->popup_menu), item);

    item = eel_image_menu_item_new_from_icon (NULL, _("_Stop"));
    sidebar->popup_menu_stop_item = item;
    g_signal_connect (item, "activate",
                      G_CALLBACK (stop_shortcut_cb), sidebar);
    ctk_widget_show (item);
    ctk_menu_shell_append (CTK_MENU_SHELL (sidebar->popup_menu), item);

    /* Empty Trash menu item */

    item = eel_image_menu_item_new_from_icon (BAUL_ICON_TRASH, _("Empty _Trash"));
    sidebar->popup_menu_empty_trash_item = item;
    g_signal_connect (item, "activate",
                      G_CALLBACK (empty_trash_cb), sidebar);
    ctk_widget_show (item);
    ctk_menu_shell_append (CTK_MENU_SHELL (sidebar->popup_menu), item);

    bookmarks_check_popup_sensitivity (sidebar);
}

static void
bookmarks_update_popup_menu (BaulPlacesSidebar *sidebar)
{
    bookmarks_build_popup_menu (sidebar);
}

static void
bookmarks_popup_menu (BaulPlacesSidebar *sidebar,
                      CdkEventButton        *event)
{
    bookmarks_update_popup_menu (sidebar);
    eel_pop_up_context_menu (CTK_MENU(sidebar->popup_menu),
                             event);
}

/* Callback used for the CtkWidget::popup-menu signal of the shortcuts list */
static gboolean
bookmarks_popup_menu_cb (CtkWidget *widget,
                         BaulPlacesSidebar *sidebar)
{
    bookmarks_popup_menu (sidebar, NULL);
    return TRUE;
}

static gboolean
bookmarks_button_release_event_cb (CtkWidget *widget,
                                   CdkEventButton *event,
                                   BaulPlacesSidebar *sidebar)
{
    CtkTreePath *path;
    CtkTreeModel *model;
    CtkTreeView *tree_view;

    path = NULL;

    if (event->type != CDK_BUTTON_RELEASE)
    {
        return TRUE;
    }

    if (clicked_eject_button (sidebar, &path))
    {
        eject_or_unmount_bookmark (sidebar, path);
        ctk_tree_path_free (path);
        return FALSE;
    }

    tree_view = CTK_TREE_VIEW (widget);
    model = ctk_tree_view_get_model (tree_view);

    if (event->button == 1)
    {

        if (event->window != ctk_tree_view_get_bin_window (tree_view))
        {
            return FALSE;
        }

        ctk_tree_view_get_path_at_pos (tree_view, (int) event->x, (int) event->y,
                                       &path, NULL, NULL, NULL);

        open_selected_bookmark (sidebar, model, path, 0);

        ctk_tree_path_free (path);
    }

    return FALSE;
}

static void
update_eject_buttons (BaulPlacesSidebar *sidebar,
                      CtkTreePath         *path)
{
    CtkTreeIter iter;
    gboolean icon_visible, path_same;

    icon_visible = TRUE;

    if (path == NULL && sidebar->eject_highlight_path == NULL) {
        /* Both are null - highlight up to date */
        return;
    }

    path_same = (path != NULL) &&
        (sidebar->eject_highlight_path != NULL) &&
        (ctk_tree_path_compare (sidebar->eject_highlight_path, path) == 0);

    if (path_same) {
        /* Same path - highlight up to date */
        return;
    }

    if (path) {
        ctk_tree_model_get_iter (CTK_TREE_MODEL (sidebar->filter_model),
                     &iter,
                     path);

        ctk_tree_model_get (CTK_TREE_MODEL (sidebar->filter_model),
                    &iter,
                    PLACES_SIDEBAR_COLUMN_EJECT, &icon_visible,
                    -1);
    }

    if (!icon_visible || path == NULL || !path_same) {
        /* remove highlighting and reset the saved path, as we are leaving
         * an eject button area.
         */
        if (sidebar->eject_highlight_path) {
            ctk_tree_model_get_iter (CTK_TREE_MODEL (sidebar->store),
                         &iter,
                         sidebar->eject_highlight_path);

            ctk_list_store_set (sidebar->store,
                        &iter,
                        PLACES_SIDEBAR_COLUMN_EJECT_ICON, get_eject_icon (FALSE),
                        -1);
            ctk_tree_model_filter_refilter (CTK_TREE_MODEL_FILTER (sidebar->filter_model));

            ctk_tree_path_free (sidebar->eject_highlight_path);
            sidebar->eject_highlight_path = NULL;
        }

        if (!icon_visible) {
            return;
        }
    }

    if (path != NULL) {
        /* add highlighting to the selected path, as the icon is visible and
         * we're hovering it.
         */
        ctk_tree_model_get_iter (CTK_TREE_MODEL (sidebar->store),
                     &iter,
                     path);
        ctk_list_store_set (sidebar->store,
                    &iter,
                    PLACES_SIDEBAR_COLUMN_EJECT_ICON, get_eject_icon (TRUE),
                    -1);
        ctk_tree_model_filter_refilter (CTK_TREE_MODEL_FILTER (sidebar->filter_model));

        sidebar->eject_highlight_path = ctk_tree_path_copy (path);
    }
}

static gboolean
bookmarks_motion_event_cb (CtkWidget             *widget,
                           CdkEventMotion        *event,
                           BaulPlacesSidebar *sidebar)
{
    CtkTreePath *path;

    path = NULL;

    if (over_eject_button (sidebar, event->x, event->y, &path)) {
        update_eject_buttons (sidebar, path);
        ctk_tree_path_free (path);

        return TRUE;
    }

    update_eject_buttons (sidebar, NULL);

    return FALSE;
}

/* Callback used when a button is pressed on the shortcuts list.
 * We trap button 3 to bring up a popup menu, and button 2 to
 * open in a new tab.
 */
static gboolean
bookmarks_button_press_event_cb (CtkWidget             *widget,
                                 CdkEventButton        *event,
                                 BaulPlacesSidebar *sidebar)
{
    if (event->type != CDK_BUTTON_PRESS)
    {
        /* ignore multiple clicks */
        return TRUE;
    }

    if (event->button == 3)
    {
        bookmarks_popup_menu (sidebar, event);
    }
    else if (event->button == 2)
    {
        CtkTreeModel *model;
        CtkTreePath *path;
        CtkTreeView *tree_view;

        tree_view = CTK_TREE_VIEW (widget);
        g_assert (tree_view == sidebar->tree_view);

        model = ctk_tree_view_get_model (tree_view);

        ctk_tree_view_get_path_at_pos (tree_view, (int) event->x, (int) event->y,
                                       &path, NULL, NULL, NULL);

        open_selected_bookmark (sidebar, model, path,
                                event->state & CDK_CONTROL_MASK ?
                                BAUL_WINDOW_OPEN_FLAG_NEW_WINDOW :
                                BAUL_WINDOW_OPEN_FLAG_NEW_TAB);

        if (path != NULL)
        {
            ctk_tree_path_free (path);
            return TRUE;
        }
    }

    return FALSE;
}


static void
bookmarks_edited (CtkCellRenderer       *cell,
                  gchar                 *path_string,
                  gchar                 *new_text,
                  BaulPlacesSidebar *sidebar)
{
    CtkTreePath *path;
    CtkTreeIter iter;
    BaulBookmark *bookmark;
    int index;

    g_object_set (cell, "editable", FALSE, NULL);

    path = ctk_tree_path_new_from_string (path_string);
    ctk_tree_model_get_iter (CTK_TREE_MODEL (sidebar->filter_model), &iter, path);
    ctk_tree_model_get (CTK_TREE_MODEL (sidebar->filter_model), &iter,
                        PLACES_SIDEBAR_COLUMN_INDEX, &index,
                        -1);
    ctk_tree_path_free (path);
    bookmark = baul_bookmark_list_item_at (sidebar->bookmarks, index);

    if (bookmark != NULL)
    {
        baul_bookmark_set_name (bookmark, new_text);
    }
}

static void
bookmarks_editing_canceled (CtkCellRenderer       *cell,
                            BaulPlacesSidebar *sidebar)
{
    g_object_set (cell, "editable", FALSE, NULL);
}

static void
trash_state_changed_cb (BaulTrashMonitor    *trash_monitor,
                        gboolean             state,
                        gpointer             data)
{
    BaulPlacesSidebar *sidebar;

    sidebar = BAUL_PLACES_SIDEBAR (data);

    /* The trash icon changed, update the sidebar */
    update_places (sidebar);

    bookmarks_check_popup_sensitivity (sidebar);
}

static gboolean
tree_selection_func (CtkTreeSelection *selection,
                     CtkTreeModel *model,
                     CtkTreePath *path,
                     gboolean path_currently_selected,
                     gpointer user_data)
{
    CtkTreeIter iter;
    PlaceType row_type;

    ctk_tree_model_get_iter (model, &iter, path);
    ctk_tree_model_get (model, &iter,
                PLACES_SIDEBAR_COLUMN_ROW_TYPE, &row_type,
                -1);

    if (row_type == PLACES_HEADING) {
        return FALSE;
    }

    return TRUE;
}

static void
icon_cell_renderer_func (CtkTreeViewColumn *column,
                         CtkCellRenderer *cell,
                         CtkTreeModel *model,
                         CtkTreeIter *iter,
                         gpointer user_data)
{
    PlaceType type;

    ctk_tree_model_get (model, iter,
                PLACES_SIDEBAR_COLUMN_ROW_TYPE, &type,
                -1);

    if (type == PLACES_HEADING) {
        g_object_set (cell,
                  "visible", FALSE,
                  NULL);
    } else {
        g_object_set (cell,
                  "visible", TRUE,
                  NULL);
    }
}

static void
padding_cell_renderer_func (CtkTreeViewColumn *column,
                            CtkCellRenderer *cell,
                            CtkTreeModel *model,
                            CtkTreeIter *iter,
                            gpointer user_data)
{
    PlaceType type;

    ctk_tree_model_get (model, iter,
                        PLACES_SIDEBAR_COLUMN_ROW_TYPE, &type,
                        -1);

    if (type == PLACES_HEADING) {
        g_object_set (cell,
                      "visible", FALSE,
                      "xpad", 0,
                      "ypad", 0,
                      NULL);
    } else {
        g_object_set (cell,
                      "visible", TRUE,
                      "xpad", 3,
                      "ypad", 0,
                      NULL);
    }
}

static void
heading_cell_renderer_func (CtkTreeViewColumn *column,
                        CtkCellRenderer *cell,
                        CtkTreeModel *model,
                        CtkTreeIter *iter,
                        gpointer user_data)
{
    PlaceType type;

    ctk_tree_model_get (model, iter,
                        PLACES_SIDEBAR_COLUMN_ROW_TYPE, &type,
                        -1);

    if (type == PLACES_HEADING) {
        g_object_set (cell,
                      "visible", TRUE,
                      NULL);
    } else {
        g_object_set (cell,
                      "visible", FALSE,
                      NULL);
    }
}

static void
baul_places_sidebar_init (BaulPlacesSidebar *sidebar)
{
    CtkTreeView       *tree_view;
    CtkTreeViewColumn *col;
    CtkCellRenderer   *cell;
    CtkTreeSelection  *selection;

    sidebar->volume_monitor = g_volume_monitor_get ();

    ctk_scrolled_window_set_policy (CTK_SCROLLED_WINDOW (sidebar),
                                    CTK_POLICY_NEVER,
                                    CTK_POLICY_AUTOMATIC);
    ctk_scrolled_window_set_hadjustment (CTK_SCROLLED_WINDOW (sidebar), NULL);
    ctk_scrolled_window_set_vadjustment (CTK_SCROLLED_WINDOW (sidebar), NULL);
    ctk_scrolled_window_set_shadow_type (CTK_SCROLLED_WINDOW (sidebar), CTK_SHADOW_IN);
    ctk_scrolled_window_set_overlay_scrolling(CTK_SCROLLED_WINDOW (sidebar), FALSE);

    /* tree view */
    tree_view = CTK_TREE_VIEW (ctk_tree_view_new ());
    ctk_tree_view_set_headers_visible (tree_view, FALSE);

    col = CTK_TREE_VIEW_COLUMN (ctk_tree_view_column_new ());

    /* initial padding */
    cell = ctk_cell_renderer_text_new ();
    ctk_tree_view_column_pack_start (col, cell, FALSE);
    g_object_set (cell,
                  "xpad", 6,
                  NULL);

    /* headings */
    cell = ctk_cell_renderer_text_new ();
    ctk_tree_view_column_pack_start (col, cell, FALSE);
    ctk_tree_view_column_set_attributes (col, cell,
                                         "text", PLACES_SIDEBAR_COLUMN_HEADING_TEXT,
                                         NULL);
    g_object_set (cell,
                  "weight", PANGO_WEIGHT_BOLD,
                  "weight-set", TRUE,
                  "ypad", 1,
                  "xpad", 0,
                  NULL);
    ctk_tree_view_column_set_cell_data_func (col, cell,
                         heading_cell_renderer_func,
                         sidebar, NULL);

    /* icon padding */
    cell = ctk_cell_renderer_text_new ();
    ctk_tree_view_column_pack_start (col, cell, FALSE);
    ctk_tree_view_column_set_cell_data_func (col, cell,
                                             padding_cell_renderer_func,
                                             sidebar, NULL);

    /* icon renderer */
    cell = ctk_cell_renderer_pixbuf_new ();
    ctk_tree_view_column_pack_start (col, cell, FALSE);
    ctk_tree_view_column_set_attributes (col, cell,
                                         "surface", PLACES_SIDEBAR_COLUMN_ICON,
                                         NULL);
    ctk_tree_view_column_set_cell_data_func (col, cell,
                                             icon_cell_renderer_func,
                                             sidebar, NULL);

    /* eject text renderer */
    cell = ctk_cell_renderer_text_new ();
    ctk_tree_view_column_pack_start (col, cell, TRUE);
    ctk_tree_view_column_set_attributes (col, cell,
                                         "text", PLACES_SIDEBAR_COLUMN_NAME,
                                         "visible", PLACES_SIDEBAR_COLUMN_EJECT,
                                         NULL);
    g_object_set (cell,
                  "ellipsize", PANGO_ELLIPSIZE_END,
                  "ellipsize-set", TRUE,
                  NULL);

    /* eject icon renderer */
    cell = ctk_cell_renderer_pixbuf_new ();
    sidebar->eject_icon_cell_renderer = cell;
    g_object_set (cell,
                  "mode", CTK_CELL_RENDERER_MODE_ACTIVATABLE,
                  "stock-size", CTK_ICON_SIZE_MENU,
                  "xpad", EJECT_BUTTON_XPAD,
                  /* align right, because for some reason ctk+ expands
                  this even though we tell it not to. */
                  "xalign", 1.0,
                  NULL);
    ctk_tree_view_column_pack_start (col, cell, FALSE);
    ctk_tree_view_column_set_attributes (col, cell,
                                         "visible", PLACES_SIDEBAR_COLUMN_EJECT,
                                         "surface", PLACES_SIDEBAR_COLUMN_EJECT_ICON,
                                         NULL);

    /* normal text renderer */
    cell = ctk_cell_renderer_text_new ();
    ctk_tree_view_column_pack_start (col, cell, TRUE);
    g_object_set (G_OBJECT (cell), "editable", FALSE, NULL);
    ctk_tree_view_column_set_attributes (col, cell,
                                         "text", PLACES_SIDEBAR_COLUMN_NAME,
                                         "visible", PLACES_SIDEBAR_COLUMN_NO_EJECT,
                                         "editable-set", PLACES_SIDEBAR_COLUMN_BOOKMARK,
                                         NULL);
    g_object_set (cell,
                  "ellipsize", PANGO_ELLIPSIZE_END,
                  "ellipsize-set", TRUE,
                  NULL);

    g_signal_connect (cell, "edited",
                      G_CALLBACK (bookmarks_edited), sidebar);
    g_signal_connect (cell, "editing-canceled",
                      G_CALLBACK (bookmarks_editing_canceled), sidebar);

    /* this is required to align the eject buttons to the right */
    ctk_tree_view_column_set_max_width (CTK_TREE_VIEW_COLUMN (col), BAUL_ICON_SIZE_SMALLER);
    ctk_tree_view_append_column (tree_view, col);

    sidebar->store = ctk_list_store_new (PLACES_SIDEBAR_COLUMN_COUNT,
                                         G_TYPE_INT,
                                         G_TYPE_STRING,
                                         G_TYPE_DRIVE,
                                         G_TYPE_VOLUME,
                                         G_TYPE_MOUNT,
                                         G_TYPE_STRING,
                                         CAIRO_GOBJECT_TYPE_SURFACE,
                                         G_TYPE_INT,
                                         G_TYPE_BOOLEAN,
                                         G_TYPE_BOOLEAN,
                                         G_TYPE_BOOLEAN,
                                         G_TYPE_STRING,
                                         CAIRO_GOBJECT_TYPE_SURFACE,
                                         G_TYPE_INT,
                                         G_TYPE_STRING);

    ctk_tree_view_set_tooltip_column (tree_view, PLACES_SIDEBAR_COLUMN_TOOLTIP);

    sidebar->filter_model = baul_shortcuts_model_filter_new (sidebar,
                            CTK_TREE_MODEL (sidebar->store),
                            NULL);

    ctk_tree_view_set_model (tree_view, sidebar->filter_model);
    ctk_container_add (CTK_CONTAINER (sidebar), CTK_WIDGET (tree_view));
    ctk_widget_show (CTK_WIDGET (tree_view));

    ctk_widget_show (CTK_WIDGET (sidebar));
    sidebar->tree_view = tree_view;

    ctk_tree_view_set_search_column (tree_view, PLACES_SIDEBAR_COLUMN_NAME);
    selection = ctk_tree_view_get_selection (tree_view);
    ctk_tree_selection_set_mode (selection, CTK_SELECTION_BROWSE);

    ctk_tree_selection_set_select_function (selection,
                                            tree_selection_func,
                                            sidebar,
                                            NULL);

    ctk_tree_view_enable_model_drag_source (CTK_TREE_VIEW (tree_view),
                                            CDK_BUTTON1_MASK,
                                            baul_shortcuts_source_targets,
                                            G_N_ELEMENTS (baul_shortcuts_source_targets),
                                            CDK_ACTION_MOVE);
    ctk_drag_dest_set (CTK_WIDGET (tree_view),
                       0,
                       baul_shortcuts_drop_targets, G_N_ELEMENTS (baul_shortcuts_drop_targets),
                       CDK_ACTION_MOVE | CDK_ACTION_COPY | CDK_ACTION_LINK);

    g_signal_connect (tree_view, "key-press-event",
                      G_CALLBACK (bookmarks_key_press_event_cb), sidebar);<--- You might need to cast the function pointer here

    g_signal_connect (tree_view, "drag-motion",
                      G_CALLBACK (drag_motion_callback), sidebar);
    g_signal_connect (tree_view, "drag-leave",
                      G_CALLBACK (drag_leave_callback), sidebar);
    g_signal_connect (tree_view, "drag-data-received",
                      G_CALLBACK (drag_data_received_callback), sidebar);
    g_signal_connect (tree_view, "drag-drop",
                      G_CALLBACK (drag_drop_callback), sidebar);

    g_signal_connect (selection, "changed",
                      G_CALLBACK (bookmarks_selection_changed_cb), sidebar);
    g_signal_connect (tree_view, "popup-menu",
                      G_CALLBACK (bookmarks_popup_menu_cb), sidebar);
    g_signal_connect (tree_view, "button-press-event",
                      G_CALLBACK (bookmarks_button_press_event_cb), sidebar);
    g_signal_connect (tree_view, "motion-notify-event",
                      G_CALLBACK (bookmarks_motion_event_cb), sidebar);
    g_signal_connect (tree_view, "button-release-event",
                      G_CALLBACK (bookmarks_button_release_event_cb), sidebar);

    eel_ctk_tree_view_set_activate_on_single_click (sidebar->tree_view,
            TRUE);

    g_signal_connect_swapped (baul_preferences, "changed::" BAUL_PREFERENCES_DESKTOP_IS_HOME_DIR,
                              G_CALLBACK(desktop_location_changed_callback),
                              sidebar);

    g_signal_connect_object (baul_trash_monitor_get (),
                             "trash_state_changed",
                             G_CALLBACK (trash_state_changed_cb),
                             sidebar, 0);
}

static void
baul_places_sidebar_dispose (GObject *object)
{
    BaulPlacesSidebar *sidebar;

    sidebar = BAUL_PLACES_SIDEBAR (object);

    sidebar->window = NULL;
    sidebar->tree_view = NULL;

    g_free (sidebar->uri);
    sidebar->uri = NULL;

    free_drag_data (sidebar);

    if (sidebar->eject_highlight_path != NULL) {
        ctk_tree_path_free (sidebar->eject_highlight_path);
        sidebar->eject_highlight_path = NULL;
    }

    g_clear_object (&sidebar->store);
    g_clear_object (&sidebar->volume_monitor);
    g_clear_object (&sidebar->bookmarks);
    g_clear_object (&sidebar->filter_model);

    eel_remove_weak_pointer (&(sidebar->go_to_after_mount_slot));

    g_signal_handlers_disconnect_by_func (baul_preferences,
                                          desktop_location_changed_callback,
                                          sidebar);

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

static void
baul_places_sidebar_class_init (BaulPlacesSidebarClass *class)
{
    G_OBJECT_CLASS (class)->dispose = baul_places_sidebar_dispose;

    CTK_WIDGET_CLASS (class)->style_updated = baul_places_sidebar_style_updated;
}

static const char *
baul_places_sidebar_get_sidebar_id (BaulSidebar *sidebar)
{
    return BAUL_PLACES_SIDEBAR_ID;
}

static char *
baul_places_sidebar_get_tab_label (BaulSidebar *sidebar)
{
    return g_strdup (_("Places"));
}

static char *
baul_places_sidebar_get_tab_tooltip (BaulSidebar *sidebar)
{
    return g_strdup (_("Show Places"));
}

static GdkPixbuf *
baul_places_sidebar_get_tab_icon (BaulSidebar *sidebar)
{
    return NULL;
}

static void
baul_places_sidebar_is_visible_changed (BaulSidebar *sidebar,
                                        gboolean         is_visible)
{
    /* Do nothing */
}

static void
baul_places_sidebar_iface_init (BaulSidebarIface *iface)
{
    iface->get_sidebar_id = baul_places_sidebar_get_sidebar_id;
    iface->get_tab_label = baul_places_sidebar_get_tab_label;
    iface->get_tab_tooltip = baul_places_sidebar_get_tab_tooltip;
    iface->get_tab_icon = baul_places_sidebar_get_tab_icon;
    iface->is_visible_changed = baul_places_sidebar_is_visible_changed;
}

static void
baul_places_sidebar_set_parent_window (BaulPlacesSidebar *sidebar,
                                       BaulWindowInfo *window)
{
    BaulWindowSlotInfo *slot;

    sidebar->window = window;

    slot = baul_window_info_get_active_slot (window);

    sidebar->bookmarks = baul_bookmark_list_new ();
    sidebar->uri = baul_window_slot_info_get_current_location (slot);

    g_signal_connect_object (sidebar->bookmarks, "contents_changed",
                             G_CALLBACK (update_places),
                             sidebar, G_CONNECT_SWAPPED);

    g_signal_connect_object (window, "loading_uri",
                             G_CALLBACK (loading_uri_callback),
                             sidebar, 0);

    g_signal_connect_object (sidebar->volume_monitor, "volume_added",
                             G_CALLBACK (volume_added_callback), sidebar, 0);
    g_signal_connect_object (sidebar->volume_monitor, "volume_removed",
                             G_CALLBACK (volume_removed_callback), sidebar, 0);
    g_signal_connect_object (sidebar->volume_monitor, "volume_changed",
                             G_CALLBACK (volume_changed_callback), sidebar, 0);
    g_signal_connect_object (sidebar->volume_monitor, "mount_added",
                             G_CALLBACK (mount_added_callback), sidebar, 0);
    g_signal_connect_object (sidebar->volume_monitor, "mount_removed",
                             G_CALLBACK (mount_removed_callback), sidebar, 0);
    g_signal_connect_object (sidebar->volume_monitor, "mount_changed",
                             G_CALLBACK (mount_changed_callback), sidebar, 0);
    g_signal_connect_object (sidebar->volume_monitor, "drive_disconnected",
                             G_CALLBACK (drive_disconnected_callback), sidebar, 0);
    g_signal_connect_object (sidebar->volume_monitor, "drive_connected",
                             G_CALLBACK (drive_connected_callback), sidebar, 0);
    g_signal_connect_object (sidebar->volume_monitor, "drive_changed",
                             G_CALLBACK (drive_changed_callback), sidebar, 0);

    update_places (sidebar);
}

static void
baul_places_sidebar_style_updated (CtkWidget *widget)
{
    BaulPlacesSidebar *sidebar;

    sidebar = BAUL_PLACES_SIDEBAR (widget);

    update_places (sidebar);
}

static BaulSidebar *
baul_places_sidebar_create (BaulSidebarProvider *provider,
                            BaulWindowInfo *window)
{
    BaulPlacesSidebar *sidebar;

    sidebar = g_object_new (baul_places_sidebar_get_type (), NULL);
    baul_places_sidebar_set_parent_window (sidebar, window);
    g_object_ref_sink (sidebar);

    return BAUL_SIDEBAR (sidebar);
}

static void
sidebar_provider_iface_init (BaulSidebarProviderIface *iface)
{
    iface->create = baul_places_sidebar_create;
}

static void
baul_places_sidebar_provider_init (BaulPlacesSidebarProvider *sidebar)
{
}

static void
baul_places_sidebar_provider_class_init (BaulPlacesSidebarProviderClass *class)
{
}

void
baul_places_sidebar_register (void)
{
    baul_module_add_type (baul_places_sidebar_provider_get_type ());
}

/* Drag and drop interfaces */

static void
_baul_shortcuts_model_filter_class_init (BaulShortcutsModelFilterClass *class)
{
}

static void
_baul_shortcuts_model_filter_init (BaulShortcutsModelFilter *model)
{
    model->sidebar = NULL;
}

/* CtkTreeDragSource::row_draggable implementation for the shortcuts filter model */
static gboolean
baul_shortcuts_model_filter_row_draggable (CtkTreeDragSource *drag_source,
                                           CtkTreePath       *path)
{
    CtkTreeModel *model;
    CtkTreeIter iter;
    PlaceType place_type;
    SectionType section_type;

    model = CTK_TREE_MODEL (drag_source);

    ctk_tree_model_get_iter (model, &iter, path);
    ctk_tree_model_get (model, &iter,
                        PLACES_SIDEBAR_COLUMN_ROW_TYPE, &place_type,
                        PLACES_SIDEBAR_COLUMN_SECTION_TYPE, &section_type,
                        -1);

    if (place_type != PLACES_HEADING && section_type == SECTION_BOOKMARKS)
        return TRUE;

    return FALSE;
}

/* Fill the CtkTreeDragSourceIface vtable */
static void
baul_shortcuts_model_filter_drag_source_iface_init (CtkTreeDragSourceIface *iface)
{
    iface->row_draggable = baul_shortcuts_model_filter_row_draggable;
}

static CtkTreeModel *
baul_shortcuts_model_filter_new (BaulPlacesSidebar *sidebar,
                                 CtkTreeModel          *child_model,
                                 CtkTreePath           *root)
{
    BaulShortcutsModelFilter *model;

    model = g_object_new (BAUL_SHORTCUTS_MODEL_FILTER_TYPE,
                          "child-model", child_model,
                          "virtual-root", root,
                          NULL);

    model->sidebar = sidebar;

    return CTK_TREE_MODEL (model);
}