aboutsummaryrefslogtreecommitdiffstats
path: root/calendar/calobj.h
Commit message (Expand)AuthorAgeFilesLines
* new file -- things shared between the client and server go in thisSeth Alves2000-03-041-263/+0
* Change iCalObject.organizer from char* to iCalPerson*Russell Steinthal2000-02-161-4/+43
* Added get_uids() method to get a list of UIDs based on object types.Federico Mena Quintero2000-02-091-0/+9
* About to rehash conduit.Eskil Heyn Olsen1999-09-191-1/+1
* added sources to calendar-conduitEskil Heyn Olsen1999-09-151-2/+2
* New file. Implements PalmPilot syncronization with the Gnome Calendar.Miguel de Icaza1999-07-281-0/+11
* GNOME PIM livesMichael Fulbright1998-12-091-1/+1
* Changed name from time_start_of_day() to be consistent with the otherFederico Mena Quintero1998-10-031-2/+7
* Do not add the spurious padding.Miguel de Icaza1998-05-151-0/+2
* Fixed alarm saving code. Fixed alarm loading code. New -partial-Arturo Espinosa1998-04-251-0/+4
* Yes.Arturo Espinosa1998-04-181-0/+7
* Year view, double click -migArturo Espinosa1998-04-181-1/+0
* The event dialog is beautified, recurrences are saner.Federico Mena Quintero1998-04-181-1/+4
* We load the alarms -migArturo Espinosa1998-04-181-1/+2
* Large number of updates. Recurrence basically works now in most of itsArturo Espinosa1998-04-181-4/+14
* Remove deadly excessive abuse of encapsulation -migArturo Espinosa1998-04-171-4/+3
* Use menu_shell->children, not menu->children. Why does GtkMenu have aFederico Mena Quintero1998-04-171-1/+2
* The general_owner may be null. Do the proper thing when creating theFederico Mena Quintero1998-04-161-1/+5
* Year view marks ranges of new dates (on update view). Recurrence iteratorArturo Espinosa1998-04-151-4/+8
* Load recurrence rules; Paint the recurrence screen according to the rules.Arturo Espinosa1998-04-141-1/+12
* Now takes object and flags parameters. Likewise. Likewise.Federico Mena Quintero1998-04-141-0/+7
* Begginning of the create-appointment-on-range-selection-and-enter code -miguelArturo Espinosa1998-04-121-0/+2
* More work on the recurrence dialog box, day navigation -migArturo Espinosa1998-04-121-0/+17
* Show instead of just map the child widget (otherwise the text widget getsFederico Mena Quintero1998-04-091-0/+1
* Lots -migArturo Espinosa1998-04-041-9/+29
* add test.vcf, more code progress -migArturo Espinosa1998-04-031-0/+2
* New main program that uses our new datatypes and objects.Miguel de Icaza1998-04-021-2/+5
* Removed #include "gtkcalendar.h", because it now comes from libgnomeui.Federico Mena Quintero1998-04-011-2/+4
* Calendar objects as defined by the iCalendar IETF draft. Calendar holderArturo Espinosa1998-04-011-0/+100
='n350' href='#n350'>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
/*
 * e-attachment.c
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) version 3.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with the program; if not, see <http://www.gnu.org/licenses/>
 *
 *
 * Copyright (C) 1999-2008 Novell, Inc. (www.novell.com)
 *
 */

#include "e-attachment.h"

#include <errno.h>
#include <config.h>
#include <glib/gi18n.h>
#include <glib/gstdio.h>

#include <libedataserver/e-data-server-util.h>

#include "e-util/e-icon-factory.h"
#include "e-util/e-util.h"
#include "e-util/e-mktemp.h"
#include "e-attachment-store.h"

#define E_ATTACHMENT_GET_PRIVATE(obj) \
    (G_TYPE_INSTANCE_GET_PRIVATE \
    ((obj), E_TYPE_ATTACHMENT, EAttachmentPrivate))

/* Fallback Icon */
#define DEFAULT_ICON_NAME   "mail-attachment"

/* Emblems */
#define EMBLEM_CANCELLED    "gtk-cancel"
#define EMBLEM_LOADING      "emblem-downloads"
#define EMBLEM_SAVING       "document-save"
#define EMBLEM_ENCRYPT_WEAK "security-low"
#define EMBLEM_ENCRYPT_STRONG   "security-high"
#define EMBLEM_ENCRYPT_UNKNOWN  "security-medium"
#define EMBLEM_SIGN_BAD     "stock_signature-bad"
#define EMBLEM_SIGN_GOOD    "stock_signature-ok"
#define EMBLEM_SIGN_UNKNOWN "stock_signature"

/* Attributes needed for EAttachmentStore columns. */
#define ATTACHMENT_QUERY "standard::*,preview::*,thumbnail::*"

struct _EAttachmentPrivate {
    GFile *file;
    GIcon *icon;
    GFileInfo *file_info;
    GCancellable *cancellable;
    CamelMimePart *mime_part;
    guint emblem_timeout_id;
    gchar *disposition;
    gint percent;

    guint can_show : 1;
    guint loading  : 1;
    guint saving   : 1;
    guint shown    : 1;

    camel_cipher_validity_encrypt_t encrypted;
    camel_cipher_validity_sign_t signed_;

    /* This is a reference to our row in an EAttachmentStore,
     * serving as a means of broadcasting "row-changed" signals.
     * If we are removed from the store, we lazily free the
     * reference when it is found to be to be invalid. */
    GtkTreeRowReference *reference;
};

enum {
    PROP_0,
    PROP_CAN_SHOW,
    PROP_DISPOSITION,
    PROP_ENCRYPTED,
    PROP_FILE,
    PROP_FILE_INFO,
    PROP_ICON,
    PROP_LOADING,
    PROP_MIME_PART,
    PROP_PERCENT,
    PROP_REFERENCE,
    PROP_SAVING,
    PROP_SHOWN,
    PROP_SIGNED
};

static gpointer parent_class;

static gboolean
create_system_thumbnail (EAttachment *attachment, GIcon **icon)
{
    GFile *file;
    GFile *icon_file;
    gchar *thumbnail = NULL;

    g_return_val_if_fail (attachment != NULL, FALSE);
    g_return_val_if_fail (icon != NULL, FALSE);

    file = e_attachment_get_file (attachment);

    if (file && g_file_has_uri_scheme (file, "file")) {
        gchar *path = g_file_get_path (file);
        if (path) {
            thumbnail = e_icon_factory_create_thumbnail (path);
            g_free (path);
        }
    }

    if (thumbnail == NULL)
        return FALSE;

    icon_file = g_file_new_for_path (thumbnail);

    if (*icon)
        g_object_unref (*icon);

    *icon = g_file_icon_new (icon_file);

    g_object_unref (icon_file);

    if (file) {
        GFileInfo *file_info;
        const gchar *attribute;

        file_info = e_attachment_get_file_info (attachment);
        attribute = G_FILE_ATTRIBUTE_THUMBNAIL_PATH;

        if (file_info != NULL)
            g_file_info_set_attribute_byte_string (
                file_info, attribute, thumbnail);
    }

    g_free (thumbnail);

    return TRUE;
}

static gchar *
attachment_get_default_charset (void)
{
    GConfClient *client;
    const gchar *key;
    gchar *charset;

    /* XXX This doesn't really belong here. */

    client = gconf_client_get_default ();
    key = "/apps/evolution/mail/composer/charset";
    charset = gconf_client_get_string (client, key, NULL);
    if (charset == NULL || *charset == '\0') {
        g_free (charset);
        key = "/apps/evolution/mail/format/charset";
        charset = gconf_client_get_string (client, key, NULL);
        if (charset == NULL || *charset == '\0') {
            g_free (charset);
            charset = NULL;
        }
    }
    g_object_unref (client);

    if (charset == NULL)
        charset = g_strdup (camel_iconv_locale_charset ());

    if (charset == NULL)
        charset = g_strdup ("us-ascii");

    return charset;
}

static void
attachment_update_file_info_columns (EAttachment *attachment)
{
    GtkTreeRowReference *reference;
    GtkTreeModel *model;
    GtkTreePath *path;
    GtkTreeIter iter;
    GFileInfo *file_info;
    const gchar *content_type;
    const gchar *description;
    const gchar *display_name;
    gchar *content_desc;
    gchar *display_size;
    gchar *caption;
    goffset size;

    reference = e_attachment_get_reference (attachment);
    if (!gtk_tree_row_reference_valid (reference))
        return;

    file_info = e_attachment_get_file_info (attachment);
    if (file_info == NULL)
        return;

    model = gtk_tree_row_reference_get_model (reference);
    path = gtk_tree_row_reference_get_path (reference);
    gtk_tree_model_get_iter (model, &iter, path);
    gtk_tree_path_free (path);

    content_type = g_file_info_get_content_type (file_info);
    display_name = g_file_info_get_display_name (file_info);
    size = g_file_info_get_size (file_info);

    content_desc = g_content_type_get_description (content_type);
    display_size = g_format_size_for_display (size);

    description = e_attachment_get_description (attachment);
    if (description == NULL || *description == '\0')
        description = display_name;

    if (size > 0)
        caption = g_strdup_printf (
            "%s\n(%s)", description, display_size);
    else
        caption = g_strdup (description);

    gtk_list_store_set (
        GTK_LIST_STORE (model), &iter,
        E_ATTACHMENT_STORE_COLUMN_CAPTION, caption,
        E_ATTACHMENT_STORE_COLUMN_CONTENT_TYPE, content_desc,
        E_ATTACHMENT_STORE_COLUMN_DESCRIPTION, description,
        E_ATTACHMENT_STORE_COLUMN_SIZE, size,
        -1);

    g_free (content_desc);
    g_free (display_size);
    g_free (caption);
}

static void
attachment_update_icon_column (EAttachment *attachment)
{
    GtkTreeRowReference *reference;
    GtkTreeModel *model;
    GtkTreePath *path;
    GtkTreeIter iter;
    GFileInfo *file_info;
    GCancellable *cancellable;
    GIcon *icon = NULL;
    const gchar *emblem_name = NULL;
    const gchar *thumbnail_path = NULL;

    reference = e_attachment_get_reference (attachment);
    if (!gtk_tree_row_reference_valid (reference))
        return;

    model = gtk_tree_row_reference_get_model (reference);
    path = gtk_tree_row_reference_get_path (reference);
    gtk_tree_model_get_iter (model, &iter, path);
    gtk_tree_path_free (path);

    cancellable = attachment->priv->cancellable;
    file_info = e_attachment_get_file_info (attachment);

    if (file_info != NULL) {
        icon = g_file_info_get_icon (file_info);
        thumbnail_path = g_file_info_get_attribute_byte_string (
            file_info, G_FILE_ATTRIBUTE_THUMBNAIL_PATH);
    }

    /* Prefer the thumbnail if we have one. */
    if (thumbnail_path != NULL && *thumbnail_path != '\0') {
        GFile *file;

        file = g_file_new_for_path (thumbnail_path);
        icon = g_file_icon_new (file);
        g_object_unref (file);

    /* Try the system thumbnailer. */
    } else if (create_system_thumbnail (attachment, &icon)) {
        /* Nothing to do, just use the icon. */

    /* Else use the standard icon for the content type. */
    } else if (icon != NULL)
        g_object_ref (icon);

    /* Last ditch fallback.  (GFileInfo not yet loaded?) */
    else
        icon = g_themed_icon_new (DEFAULT_ICON_NAME);

    /* Pick an emblem, limit one.  Choices listed by priority. */

    if (g_cancellable_is_cancelled (cancellable))
        emblem_name = EMBLEM_CANCELLED;

    else if (e_attachment_get_loading (attachment))
        emblem_name = EMBLEM_LOADING;

    else if (e_attachment_get_saving (attachment))
        emblem_name = EMBLEM_SAVING;

    else if (e_attachment_get_encrypted (attachment))
        switch (e_attachment_get_encrypted (attachment)) {
            case CAMEL_CIPHER_VALIDITY_ENCRYPT_WEAK:
                emblem_name = EMBLEM_ENCRYPT_WEAK;
                break;

            case CAMEL_CIPHER_VALIDITY_ENCRYPT_ENCRYPTED:
                emblem_name = EMBLEM_ENCRYPT_UNKNOWN;
                break;

            case CAMEL_CIPHER_VALIDITY_ENCRYPT_STRONG:
                emblem_name = EMBLEM_ENCRYPT_STRONG;
                break;

            default:
                g_warn_if_reached ();
                break;
        }

    else if (e_attachment_get_signed (attachment))
        switch (e_attachment_get_signed (attachment)) {
            case CAMEL_CIPHER_VALIDITY_SIGN_GOOD:
                emblem_name = EMBLEM_SIGN_GOOD;
                break;

            case CAMEL_CIPHER_VALIDITY_SIGN_BAD:
                emblem_name = EMBLEM_SIGN_BAD;
                break;

            case CAMEL_CIPHER_VALIDITY_SIGN_UNKNOWN:
            case CAMEL_CIPHER_VALIDITY_SIGN_NEED_PUBLIC_KEY:
                emblem_name = EMBLEM_SIGN_UNKNOWN;
                break;

            default:
                g_warn_if_reached ();
                break;
        }

    if (emblem_name != NULL) {
        GIcon *emblemed_icon;
        GEmblem *emblem;

        emblemed_icon = g_themed_icon_new (emblem_name);
        emblem = g_emblem_new (emblemed_icon);
        g_object_unref (emblemed_icon);

        emblemed_icon = g_emblemed_icon_new (icon, emblem);
        g_object_unref (emblem);
        g_object_unref (icon);

        icon = emblemed_icon;
    }

    gtk_list_store_set (
        GTK_LIST_STORE (model), &iter,
        E_ATTACHMENT_STORE_COLUMN_ICON, icon,
        -1);

    /* Cache the icon to reuse for things like drag-n-drop. */
    if (attachment->priv->icon != NULL)
        g_object_unref (attachment->priv->icon);
    attachment->priv->icon = icon;
    g_object_notify (G_OBJECT (attachment), "icon");
}

static void
attachment_update_progress_columns (EAttachment *attachment)
{
    GtkTreeRowReference *reference;
    GtkTreeModel *model;
    GtkTreePath *path;
    GtkTreeIter iter;
    gboolean loading;
    gboolean saving;
    gint percent;

    reference = e_attachment_get_reference (attachment);
    if (!gtk_tree_row_reference_valid (reference))
        return;

    model = gtk_tree_row_reference_get_model (reference);
    path = gtk_tree_row_reference_get_path (reference);
    gtk_tree_model_get_iter (model, &iter, path);
    gtk_tree_path_free (path);

    /* Don't show progress bars until we have progress to report. */
    percent = e_attachment_get_percent (attachment);
    loading = e_attachment_get_loading (attachment) && (percent > 0);
    saving = e_attachment_get_saving (attachment) && (percent > 0);

    gtk_list_store_set (
        GTK_LIST_STORE (model), &iter,
        E_ATTACHMENT_STORE_COLUMN_LOADING, loading,
        E_ATTACHMENT_STORE_COLUMN_PERCENT, percent,
        E_ATTACHMENT_STORE_COLUMN_SAVING, saving,
        -1);
}

void
e_attachment_set_file_info (EAttachment *attachment,
                            GFileInfo *file_info)
{
    GtkTreeRowReference *reference;
    GIcon *icon;

    reference = e_attachment_get_reference (attachment);

    if (file_info != NULL)
        g_object_ref (file_info);

    if (attachment->priv->file_info != NULL)
        g_object_unref (attachment->priv->file_info);

    attachment->priv->file_info = file_info;

    /* If the GFileInfo contains a GThemedIcon, append a
     * fallback icon name to ensure we display something. */
    icon = g_file_info_get_icon (file_info);
    if (G_IS_THEMED_ICON (icon))
        g_themed_icon_append_name (
            G_THEMED_ICON (icon), DEFAULT_ICON_NAME);

    g_object_notify (G_OBJECT (attachment), "file-info");

    /* Tell the EAttachmentStore its total size changed. */
    if (gtk_tree_row_reference_valid (reference)) {
        GtkTreeModel *model;
        model = gtk_tree_row_reference_get_model (reference);
        g_object_notify (G_OBJECT (model), "total-size");
    }
}

static void
attachment_set_loading (EAttachment *attachment,
                        gboolean loading)
{
    GtkTreeRowReference *reference;

    reference = e_attachment_get_reference (attachment);

    attachment->priv->percent = 0;
    attachment->priv->loading = loading;

    g_object_freeze_notify (G_OBJECT (attachment));
    g_object_notify (G_OBJECT (attachment), "percent");
    g_object_notify (G_OBJECT (attachment), "loading");
    g_object_thaw_notify (G_OBJECT (attachment));

    if (gtk_tree_row_reference_valid (reference)) {
        GtkTreeModel *model;
        model = gtk_tree_row_reference_get_model (reference);
        g_object_notify (G_OBJECT (model), "num-loading");
    }
}

static void
attachment_set_saving (EAttachment *attachment,
                       gboolean saving)
{
    attachment->priv->percent = 0;
    attachment->priv->saving = saving;

    g_object_freeze_notify (G_OBJECT (attachment));
    g_object_notify (G_OBJECT (attachment), "percent");
    g_object_notify (G_OBJECT (attachment), "saving");
    g_object_thaw_notify (G_OBJECT (attachment));
}

static void
attachment_progress_cb (goffset current_num_bytes,
                        goffset total_num_bytes,
                        EAttachment *attachment)
{
    /* Avoid dividing by zero. */
    if (total_num_bytes == 0)
        return;

    attachment->priv->percent =
        (current_num_bytes * 100) / total_num_bytes;

    g_object_notify (G_OBJECT (attachment), "percent");
}

static gboolean
attachment_cancelled_timeout_cb (EAttachment *attachment)
{
    attachment->priv->emblem_timeout_id = 0;
    g_cancellable_reset (attachment->priv->cancellable);

    attachment_update_icon_column (attachment);

    return FALSE;
}

static void
attachment_cancelled_cb (EAttachment *attachment)
{
    /* Reset the GCancellable after one second.  This causes a
     * cancel emblem to be briefly shown on the attachment icon
     * as visual feedback that an operation was cancelled. */

    if (attachment->priv->emblem_timeout_id > 0)
        g_source_remove (attachment->priv->emblem_timeout_id);

    attachment->priv->emblem_timeout_id = g_timeout_add_seconds (
        1, (GSourceFunc) attachment_cancelled_timeout_cb, attachment);

    attachment_update_icon_column (attachment);
}

static void
attachment_set_property (GObject *object,
                         guint property_id,
                         const GValue *value,
                         GParamSpec *pspec)
{
    switch (property_id) {
        case PROP_CAN_SHOW:
            e_attachment_set_can_show (
                E_ATTACHMENT (object),
                g_value_get_boolean (value));
            return;

        case PROP_DISPOSITION:
            e_attachment_set_disposition (
                E_ATTACHMENT (object),
                g_value_get_string (value));
            return;

        case PROP_ENCRYPTED:
            e_attachment_set_encrypted (
                E_ATTACHMENT (object),
                g_value_get_int (value));
            return;

        case PROP_FILE:
            e_attachment_set_file (
                E_ATTACHMENT (object),
                g_value_get_object (value));
            return;

        case PROP_SHOWN:
            e_attachment_set_shown (
                E_ATTACHMENT (object),
                g_value_get_boolean (value));
            return;

        case PROP_MIME_PART:
            e_attachment_set_mime_part (
                E_ATTACHMENT (object),
                g_value_get_boxed (value));
            return;

        case PROP_REFERENCE:
            e_attachment_set_reference (
                E_ATTACHMENT (object),
                g_value_get_boxed (value));
            return;

        case PROP_SIGNED:
            e_attachment_set_signed (
                E_ATTACHMENT (object),
                g_value_get_int (value));
            return;
    }

    G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
}

static void
attachment_get_property (GObject *object,
                         guint property_id,
                         GValue *value,
                         GParamSpec *pspec)
{
    switch (property_id) {
        case PROP_CAN_SHOW:
            g_value_set_boolean (
                value, e_attachment_get_can_show (
                E_ATTACHMENT (object)));
            return;

        case PROP_DISPOSITION:
            g_value_set_string (
                value, e_attachment_get_disposition (
                E_ATTACHMENT (object)));
            return;

        case PROP_ENCRYPTED:
            g_value_set_int (
                value, e_attachment_get_encrypted (
                E_ATTACHMENT (object)));
            return;

        case PROP_FILE:
            g_value_set_object (
                value, e_attachment_get_file (
                E_ATTACHMENT (object)));
            return;

        case PROP_FILE_INFO:
            g_value_set_object (
                value, e_attachment_get_file_info (
                E_ATTACHMENT (object)));
            return;

        case PROP_ICON:
            g_value_set_object (
                value, e_attachment_get_icon (
                E_ATTACHMENT (object)));
            return;

        case PROP_SHOWN:
            g_value_set_boolean (
                value, e_attachment_get_shown (
                E_ATTACHMENT (object)));
            return;

        case PROP_LOADING:
            g_value_set_boolean (
                value, e_attachment_get_loading (
                E_ATTACHMENT (object)));
            return;

        case PROP_MIME_PART:
            g_value_set_boxed (
                value, e_attachment_get_mime_part (
                E_ATTACHMENT (object)));
            return;

        case PROP_PERCENT:
            g_value_set_int (
                value, e_attachment_get_percent (
                E_ATTACHMENT (object)));
            return;

        case PROP_REFERENCE:
            g_value_set_boxed (
                value, e_attachment_get_reference (
                E_ATTACHMENT (object)));
            return;

        case PROP_SAVING:
            g_value_set_boolean (
                value, e_attachment_get_saving (
                E_ATTACHMENT (object)));
            return;

        case PROP_SIGNED:
            g_value_set_int (
                value, e_attachment_get_signed (
                E_ATTACHMENT (object)));
            return;
    }

    G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
}

static void
attachment_dispose (GObject *object)
{
    EAttachmentPrivate *priv;

    priv = E_ATTACHMENT_GET_PRIVATE (object);

    if (priv->file != NULL) {
        g_object_unref (priv->file);
        priv->file = NULL;
    }

    if (priv->icon != NULL) {
        g_object_unref (priv->icon);
        priv->icon = NULL;
    }

    if (priv->file_info != NULL) {
        g_object_unref (priv->file_info);
        priv->file_info = NULL;
    }

    if (priv->cancellable != NULL) {
        g_object_unref (priv->cancellable);
        priv->cancellable = NULL;
    }

    if (priv->mime_part != NULL) {
        g_object_unref (priv->mime_part);
        priv->mime_part = NULL;
    }

    if (priv->emblem_timeout_id > 0) {
        g_source_remove (priv->emblem_timeout_id);
        priv->emblem_timeout_id = 0;
    }

    /* This accepts NULL arguments. */
    gtk_tree_row_reference_free (priv->reference);
    priv->reference = NULL;

    /* Chain up to parent's dispose() method. */
    G_OBJECT_CLASS (parent_class)->dispose (object);
}

static void
attachment_finalize (GObject *object)
{
    EAttachmentPrivate *priv;

    priv = E_ATTACHMENT_GET_PRIVATE (object);

    g_free (priv->disposition);

    /* Chain up to parent's finalize() method. */
    G_OBJECT_CLASS (parent_class)->finalize (object);
}

static void
attachment_class_init (EAttachmentClass *class)
{
    GObjectClass *object_class;

    parent_class = g_type_class_peek_parent (class);
    g_type_class_add_private (class, sizeof (EAttachmentPrivate));

    object_class = G_OBJECT_CLASS (class);
    object_class->set_property = attachment_set_property;
    object_class->get_property = attachment_get_property;
    object_class->dispose = attachment_dispose;
    object_class->finalize = attachment_finalize;

    g_object_class_install_property (
        object_class,
        PROP_CAN_SHOW,
        g_param_spec_boolean (
            "can-show",
            "Can Show",
            NULL,
            FALSE,
            G_PARAM_READWRITE |
            G_PARAM_CONSTRUCT));

    g_object_class_install_property (
        object_class,
        PROP_DISPOSITION,
        g_param_spec_string (
            "disposition",
            "Disposition",
            NULL,
            "attachment",
            G_PARAM_READWRITE |
            G_PARAM_CONSTRUCT));

    /* FIXME Define a GEnumClass for this. */
    g_object_class_install_property (
        object_class,
        PROP_ENCRYPTED,
        g_param_spec_int (
            "encrypted",
            "Encrypted",
            NULL,
            CAMEL_CIPHER_VALIDITY_ENCRYPT_NONE,
            CAMEL_CIPHER_VALIDITY_ENCRYPT_STRONG,
            CAMEL_CIPHER_VALIDITY_ENCRYPT_NONE,
            G_PARAM_READWRITE |
            G_PARAM_CONSTRUCT));

    g_object_class_install_property (
        object_class,
        PROP_FILE,
        g_param_spec_object (
            "file",
            "File",
            NULL,
            G_TYPE_FILE,
            G_PARAM_READWRITE |
            G_PARAM_CONSTRUCT));

    g_object_class_install_property (
        object_class,
        PROP_FILE_INFO,
        g_param_spec_object (
            "file-info",
            "File Info",
            NULL,
            G_TYPE_FILE_INFO,
            G_PARAM_READABLE));

    g_object_class_install_property (
        object_class,
        PROP_ICON,
        g_param_spec_object (
            "icon",
            "Icon",
            NULL,
            G_TYPE_ICON,
            G_PARAM_READABLE));

    g_object_class_install_property (
        object_class,
        PROP_LOADING,
        g_param_spec_boolean (
            "loading",
            "Loading",
            NULL,
            FALSE,
            G_PARAM_READABLE));

    g_object_class_install_property (
        object_class,
        PROP_MIME_PART,
        g_param_spec_object (
            "mime-part",
            "MIME Part",
            NULL,
            CAMEL_TYPE_MIME_PART,
            G_PARAM_READWRITE));

    g_object_class_install_property (
        object_class,
        PROP_PERCENT,
        g_param_spec_int (
            "percent",
            "Percent",
            NULL,
            0,
            100,
            0,
            G_PARAM_READABLE));

    g_object_class_install_property (
        object_class,
        PROP_REFERENCE,
        g_param_spec_boxed (
            "reference",
            "Reference",
            NULL,
            GTK_TYPE_TREE_ROW_REFERENCE,
            G_PARAM_READWRITE));

    g_object_class_install_property (
        object_class,
        PROP_SAVING,
        g_param_spec_boolean (
            "saving",
            "Saving",
            NULL,
            FALSE,
            G_PARAM_READABLE));

    g_object_class_install_property (
        object_class,
        PROP_SHOWN,
        g_param_spec_boolean (
            "shown",
            "Shown",
            NULL,
            FALSE,
            G_PARAM_READWRITE |
            G_PARAM_CONSTRUCT));

    /* FIXME Define a GEnumClass for this. */
    g_object_class_install_property (
        object_class,
        PROP_SIGNED,
        g_param_spec_int (
            "signed",
            "Signed",
            NULL,
            CAMEL_CIPHER_VALIDITY_SIGN_NONE,
            CAMEL_CIPHER_VALIDITY_SIGN_NEED_PUBLIC_KEY,
            CAMEL_CIPHER_VALIDITY_SIGN_NONE,
            G_PARAM_READWRITE |
            G_PARAM_CONSTRUCT));
}

static void
attachment_init (EAttachment *attachment)
{
    attachment->priv = E_ATTACHMENT_GET_PRIVATE (attachment);
    attachment->priv->cancellable = g_cancellable_new ();
    attachment->priv->encrypted = CAMEL_CIPHER_VALIDITY_ENCRYPT_NONE;
    attachment->priv->signed_ = CAMEL_CIPHER_VALIDITY_SIGN_NONE;

    g_signal_connect (
        attachment, "notify::encrypted",
        G_CALLBACK (attachment_update_icon_column), NULL);

    g_signal_connect (
        attachment, "notify::file-info",
        G_CALLBACK (attachment_update_file_info_columns), NULL);

    g_signal_connect (
        attachment, "notify::file-info",
        G_CALLBACK (attachment_update_icon_column), NULL);

    g_signal_connect (
        attachment, "notify::loading",
        G_CALLBACK (attachment_update_icon_column), NULL);

    g_signal_connect (
        attachment, "notify::loading",
        G_CALLBACK (attachment_update_progress_columns), NULL);

    g_signal_connect (
        attachment, "notify::percent",
        G_CALLBACK (attachment_update_progress_columns), NULL);

    g_signal_connect (
        attachment, "notify::reference",
        G_CALLBACK (attachment_update_file_info_columns), NULL);

    g_signal_connect (
        attachment, "notify::reference",
        G_CALLBACK (attachment_update_icon_column), NULL);

    g_signal_connect (
        attachment, "notify::reference",
        G_CALLBACK (attachment_update_progress_columns), NULL);

    g_signal_connect (
        attachment, "notify::saving",
        G_CALLBACK (attachment_update_icon_column), NULL);

    g_signal_connect (
        attachment, "notify::saving",
        G_CALLBACK (attachment_update_progress_columns), NULL);

    g_signal_connect (
        attachment, "notify::signed",
        G_CALLBACK (attachment_update_icon_column), NULL);

    g_signal_connect_swapped (
        attachment->priv->cancellable, "cancelled",
        G_CALLBACK (attachment_cancelled_cb), attachment);
}

GType
e_attachment_get_type (void)
{
    static GType type = 0;

    if (G_UNLIKELY (type == 0)) {
        static const GTypeInfo type_info = {
            sizeof (EAttachmentClass),
            (GBaseInitFunc) NULL,
            (GBaseFinalizeFunc) NULL,
            (GClassInitFunc) attachment_class_init,
            (GClassFinalizeFunc) NULL,
            NULL,  /* class_data */
            sizeof (EAttachment),
            0,     /* n_preallocs */
            (GInstanceInitFunc) attachment_init,
            NULL   /* value_table */
        };

        type = g_type_register_static (
            G_TYPE_OBJECT, "EAttachment", &type_info, 0);
    }

    return type;
}

EAttachment *
e_attachment_new (void)
{
    return g_object_new (E_TYPE_ATTACHMENT, NULL);
}

EAttachment *
e_attachment_new_for_path (const gchar *path)
{
    EAttachment *attachment;
    GFile *file;

    g_return_val_if_fail (path != NULL, NULL);

    file = g_file_new_for_path (path);
    attachment = g_object_new (E_TYPE_ATTACHMENT, "file", file, NULL);
    g_object_unref (file);

    return attachment;
}

EAttachment *
e_attachment_new_for_uri (const gchar *uri)
{
    EAttachment *attachment;
    GFile *file;

    g_return_val_if_fail (uri != NULL, NULL);

    file = g_file_new_for_uri (uri);
    attachment = g_object_new (E_TYPE_ATTACHMENT, "file", file, NULL);
    g_object_unref (file);

    return attachment;
}

EAttachment *
e_attachment_new_for_message (CamelMimeMessage *message)
{
    CamelDataWrapper *wrapper;
    CamelMimePart *mime_part;
    EAttachment *attachment;
    GString *description;
    const gchar *subject;

    g_return_val_if_fail (CAMEL_IS_MIME_MESSAGE (message), NULL);

    mime_part = camel_mime_part_new ();
    camel_mime_part_set_disposition (mime_part, "inline");
    subject = camel_mime_message_get_subject (message);

    /* To Translators: This text is set as a description of an attached
     * message when, for example, attaching it to a composer. When the
     * message to be attached has also filled Subject, then this text is
     * of form "Attached message - Subject", otherwise it's left as is. */
    description = g_string_new (_("Attached message"));
    if (subject != NULL)
        g_string_append_printf (description, " - %s", subject);
    camel_mime_part_set_description (mime_part, description->str);
    g_string_free (description, TRUE);

    wrapper = CAMEL_DATA_WRAPPER (message);
    camel_medium_set_content (CAMEL_MEDIUM (mime_part), wrapper);
    camel_mime_part_set_content_type (mime_part, "message/rfc822");

    attachment = e_attachment_new ();
    e_attachment_set_mime_part (attachment, mime_part);
    g_object_unref (mime_part);

    return attachment;
}

void
e_attachment_add_to_multipart (EAttachment *attachment,
                               CamelMultipart *multipart,
                               const gchar *default_charset)
{
    CamelContentType *content_type;
    CamelDataWrapper *wrapper;
    CamelMimePart *mime_part;

    /* XXX EMsgComposer might be a better place for this function. */

    g_return_if_fail (E_IS_ATTACHMENT (attachment));
    g_return_if_fail (CAMEL_IS_MULTIPART (multipart));

    /* Still loading?  Too bad. */
    mime_part = e_attachment_get_mime_part (attachment);
    if (mime_part == NULL)
        return;

    content_type = camel_mime_part_get_content_type (mime_part);
    wrapper = camel_medium_get_content (CAMEL_MEDIUM (mime_part));

    if (CAMEL_IS_MULTIPART (wrapper))
        goto exit;

    /* For text content, determine the best encoding and character set. */
    if (camel_content_type_is (content_type, "text", "*")) {
        CamelTransferEncoding encoding;
        CamelStream *filtered_stream;
        CamelMimeFilter *filter;
        CamelStream *stream;
        const gchar *charset;

        charset = camel_content_type_param (content_type, "charset");

        /* Determine the best encoding by writing the MIME
         * part to a NULL stream with a "bestenc" filter. */
        stream = camel_stream_null_new ();
        filtered_stream = camel_stream_filter_new (stream);
        filter = camel_mime_filter_bestenc_new (
            CAMEL_BESTENC_GET_ENCODING);
        camel_stream_filter_add (
            CAMEL_STREAM_FILTER (filtered_stream),
            CAMEL_MIME_FILTER (filter));
        camel_data_wrapper_decode_to_stream (
            wrapper, filtered_stream);
        g_object_unref (filtered_stream);
        g_object_unref (stream);

        /* Retrieve the best encoding from the filter. */
        encoding = camel_mime_filter_bestenc_get_best_encoding (
            CAMEL_MIME_FILTER_BESTENC (filter),
            CAMEL_BESTENC_8BIT);
        camel_mime_part_set_encoding (mime_part, encoding);
        g_object_unref (filter);

        if (encoding == CAMEL_TRANSFER_ENCODING_7BIT) {
            /* The text fits within us-ascii, so this is safe.
             * FIXME Check that this isn't iso-2022-jp? */
            default_charset = "us-ascii";

        } else if (charset == NULL && default_charset == NULL) {
            default_charset = attachment_get_default_charset ();
            /* FIXME Check that this fits within the
             *       default_charset and if not, find one
             *       that does and/or allow the user to
             *       specify. */
        }

        if (charset == NULL) {
            gchar *type;

            camel_content_type_set_param (
                content_type, "charset", default_charset);
            type = camel_content_type_format (content_type);
            camel_mime_part_set_content_type (mime_part, type);
            g_free (type);
        }

    /* Otherwise, unless it's a message/rfc822, Base64 encode it. */
    } else if (!CAMEL_IS_MIME_MESSAGE (wrapper))
        camel_mime_part_set_encoding (
            mime_part, CAMEL_TRANSFER_ENCODING_BASE64);

exit:
    camel_multipart_add_part (multipart, mime_part);
}

void
e_attachment_cancel (EAttachment *attachment)
{
    g_return_if_fail (E_IS_ATTACHMENT (attachment));

    g_cancellable_cancel (attachment->priv->cancellable);
}

gboolean
e_attachment_get_can_show (EAttachment *attachment)
{
    g_return_val_if_fail (E_IS_ATTACHMENT (attachment), FALSE);

    return attachment->priv->can_show;
}

void
e_attachment_set_can_show (EAttachment *attachment,
                           gboolean can_show)
{
    g_return_if_fail (E_IS_ATTACHMENT (attachment));

    attachment->priv->can_show = can_show;

    g_object_notify (G_OBJECT (attachment), "can-show");
}

const gchar *
e_attachment_get_disposition (EAttachment *attachment)
{
    g_return_val_if_fail (E_IS_ATTACHMENT (attachment), NULL);

    return attachment->priv->disposition;
}

void
e_attachment_set_disposition (EAttachment *attachment,
                              const gchar *disposition)
{
    g_return_if_fail (E_IS_ATTACHMENT (attachment));

    g_free (attachment->priv->disposition);
    attachment->priv->disposition = g_strdup (disposition);

    g_object_notify (G_OBJECT (attachment), "disposition");
}

GFile *
e_attachment_get_file (EAttachment *attachment)
{
    g_return_val_if_fail (E_IS_ATTACHMENT (attachment), NULL);

    return attachment->priv->file;
}

void
e_attachment_set_file (EAttachment *attachment,
                       GFile *file)
{
    g_return_if_fail (E_IS_ATTACHMENT (attachment));

    if (file != NULL) {
        g_return_if_fail (G_IS_FILE (file));
        g_object_ref (file);
    }

    if (attachment->priv->file != NULL)
        g_object_unref (attachment->priv->file);

    attachment->priv->file = file;

    g_object_notify (G_OBJECT (attachment), "file");
}

GFileInfo *
e_attachment_get_file_info (EAttachment *attachment)
{
    g_return_val_if_fail (E_IS_ATTACHMENT (attachment), NULL);

    return attachment->priv->file_info;
}

GIcon *
e_attachment_get_icon (EAttachment *attachment)
{
    g_return_val_if_fail (E_IS_ATTACHMENT (attachment), NULL);

    return attachment->priv->icon;
}

gboolean
e_attachment_get_loading (EAttachment *attachment)
{
    g_return_val_if_fail (E_IS_ATTACHMENT (attachment), FALSE);

    return attachment->priv->loading;
}

CamelMimePart *
e_attachment_get_mime_part (EAttachment *attachment)
{
    g_return_val_if_fail (E_IS_ATTACHMENT (attachment), NULL);

    return attachment->priv->mime_part;
}

void
e_attachment_set_mime_part (EAttachment *attachment,
                            CamelMimePart *mime_part)
{
    g_return_if_fail (E_IS_ATTACHMENT (attachment));

    if (mime_part != NULL) {
        g_return_if_fail (CAMEL_IS_MIME_PART (mime_part));
        g_object_ref (mime_part);
    }

    if (attachment->priv->mime_part != NULL)
        g_object_unref (attachment->priv->mime_part);

    attachment->priv->mime_part = mime_part;

    g_object_notify (G_OBJECT (attachment), "mime-part");
}

gint
e_attachment_get_percent (EAttachment *attachment)
{
    g_return_val_if_fail (E_IS_ATTACHMENT (attachment), 0);

    return attachment->priv->percent;
}

GtkTreeRowReference *
e_attachment_get_reference (EAttachment *attachment)
{
    g_return_val_if_fail (E_IS_ATTACHMENT (attachment), NULL);

    return attachment->priv->reference;
}

void
e_attachment_set_reference (EAttachment *attachment,
                            GtkTreeRowReference *reference)
{
    g_return_if_fail (E_IS_ATTACHMENT (attachment));

    if (reference != NULL)
        reference = gtk_tree_row_reference_copy (reference);

    gtk_tree_row_reference_free (attachment->priv->reference);
    attachment->priv->reference = reference;

    g_object_notify (G_OBJECT (attachment), "reference");
}

gboolean
e_attachment_get_saving (EAttachment *attachment)
{
    g_return_val_if_fail (E_IS_ATTACHMENT (attachment), FALSE);

    return attachment->priv->saving;
}

gboolean
e_attachment_get_shown (EAttachment *attachment)
{
    g_return_val_if_fail (E_IS_ATTACHMENT (attachment), FALSE);

    return attachment->priv->shown;
}

void
e_attachment_set_shown (EAttachment *attachment,
                        gboolean shown)
{
    g_return_if_fail (E_IS_ATTACHMENT (attachment));

    attachment->priv->shown = shown;

    g_object_notify (G_OBJECT (attachment), "shown");
}

camel_cipher_validity_encrypt_t
e_attachment_get_encrypted (EAttachment *attachment)
{
    g_return_val_if_fail (
        E_IS_ATTACHMENT (attachment),
        CAMEL_CIPHER_VALIDITY_ENCRYPT_NONE);

    return attachment->priv->encrypted;
}

void
e_attachment_set_encrypted (EAttachment *attachment,
                            camel_cipher_validity_encrypt_t encrypted)
{
    g_return_if_fail (E_IS_ATTACHMENT (attachment));

    attachment->priv->encrypted = encrypted;

    g_object_notify (G_OBJECT (attachment), "encrypted");
}

camel_cipher_validity_sign_t
e_attachment_get_signed (EAttachment *attachment)
{
    g_return_val_if_fail (
        E_IS_ATTACHMENT (attachment),
        CAMEL_CIPHER_VALIDITY_SIGN_NONE);

    return attachment->priv->signed_;
}

void
e_attachment_set_signed (EAttachment *attachment,
                         camel_cipher_validity_sign_t signed_)
{
    g_return_if_fail (E_IS_ATTACHMENT (attachment));

    attachment->priv->signed_ = signed_;

    g_object_notify (G_OBJECT (attachment), "signed");
}

const gchar *
e_attachment_get_description (EAttachment *attachment)
{
    GFileInfo *file_info;
    const gchar *attribute;

    g_return_val_if_fail (E_IS_ATTACHMENT (attachment), NULL);

    attribute = G_FILE_ATTRIBUTE_STANDARD_DESCRIPTION;
    file_info = e_attachment_get_file_info (attachment);

    if (file_info == NULL)
        return NULL;

    return g_file_info_get_attribute_string (file_info, attribute);
}

const gchar *
e_attachment_get_thumbnail_path (EAttachment *attachment)
{
    GFileInfo *file_info;
    const gchar *attribute;

    g_return_val_if_fail (E_IS_ATTACHMENT (attachment), NULL);

    attribute = G_FILE_ATTRIBUTE_THUMBNAIL_PATH;
    file_info = e_attachment_get_file_info (attachment);

    if (file_info == NULL)
        return NULL;

    return g_file_info_get_attribute_byte_string (file_info, attribute);
}

gboolean
e_attachment_is_rfc822 (EAttachment *attachment)
{
    GFileInfo *file_info;
    const gchar *content_type;
    gchar *mime_type;
    gboolean is_rfc822;

    g_return_val_if_fail (E_IS_ATTACHMENT (attachment), FALSE);

    file_info = e_attachment_get_file_info (attachment);
    if (file_info == NULL)
        return FALSE;

    content_type = g_file_info_get_content_type (file_info);
    if (content_type == NULL)
        return FALSE;

    mime_type = g_content_type_get_mime_type (content_type);
    is_rfc822 = (g_ascii_strcasecmp (mime_type, "message/rfc822") == 0);
    g_free (mime_type);

    return is_rfc822;
}

GList *
e_attachment_list_apps (EAttachment *attachment)
{
    GList *app_info_list;
    GList *guessed_infos;
    GFileInfo *file_info;
    const gchar *content_type;
    const gchar *display_name;
    gboolean type_is_unknown;
    gchar *allocated;

    g_return_val_if_fail (E_IS_ATTACHMENT (attachment), NULL);

    file_info = e_attachment_get_file_info (attachment);
    if (file_info == NULL)
        return NULL;

    content_type = g_file_info_get_content_type (file_info);
    display_name = g_file_info_get_display_name (file_info);
    g_return_val_if_fail (content_type != NULL, NULL);

    app_info_list = g_app_info_get_all_for_type (content_type);
    type_is_unknown = g_content_type_is_unknown (content_type);

    if (app_info_list != NULL && !type_is_unknown)
        goto exit;

    if (display_name == NULL)
        goto exit;

    allocated = g_content_type_guess (display_name, NULL, 0, NULL);
    guessed_infos = g_app_info_get_all_for_type (allocated);
    app_info_list = g_list_concat (guessed_infos, app_info_list);
    g_free (allocated);

exit:
    return app_info_list;
}

/************************* e_attachment_load_async() *************************/

typedef struct _LoadContext LoadContext;

struct _LoadContext {
    EAttachment *attachment;
    GSimpleAsyncResult *simple;

    GInputStream *input_stream;
    GOutputStream *output_stream;
    GFileInfo *file_info;
    goffset total_num_bytes;
    gssize bytes_read;
    gchar buffer[4096];
};

/* Forward Declaration */
static void
attachment_load_stream_read_cb (GInputStream *input_stream,
                                GAsyncResult *result,
                                LoadContext *load_context);

static LoadContext *
attachment_load_context_new (EAttachment *attachment,
                             GAsyncReadyCallback callback,
                             gpointer user_data)
{
    LoadContext *load_context;
    GSimpleAsyncResult *simple;

    simple = g_simple_async_result_new (
        G_OBJECT (attachment), callback,
        user_data, e_attachment_load_async);

    load_context = g_slice_new0 (LoadContext);
    load_context->attachment = g_object_ref (attachment);
    load_context->simple = simple;

    attachment_set_loading (load_context->attachment, TRUE);

    return load_context;
}

static void
attachment_load_context_free (LoadContext *load_context)
{
    g_object_unref (load_context->attachment);
    g_object_unref (load_context->simple);

    if (load_context->input_stream != NULL)
        g_object_unref (load_context->input_stream);

    if (load_context->output_stream != NULL)
        g_object_unref (load_context->output_stream);

    if (load_context->file_info != NULL)
        g_object_unref (load_context->file_info);

    g_slice_free (LoadContext, load_context);
}

static gboolean
attachment_load_check_for_error (LoadContext *load_context,
                                 GError *error)
{
    GSimpleAsyncResult *simple;

    if (error == NULL)
        return FALSE;

    simple = load_context->simple;
    g_simple_async_result_set_from_error (simple, error);
    g_simple_async_result_complete (simple);
    g_error_free (error);

    attachment_load_context_free (load_context);

    return TRUE;
}

static void
attachment_load_finish (LoadContext *load_context)
{
    GFileInfo *file_info;
    EAttachment *attachment;
    GMemoryOutputStream *output_stream;
    GSimpleAsyncResult *simple;
    CamelDataWrapper *wrapper;
    CamelMimePart *mime_part;
    CamelStream *stream;
    const gchar *attribute;
    const gchar *content_type;
    const gchar *display_name;
    const gchar *description;
    const gchar *disposition;
    gchar *mime_type;
    gpointer data;
    gsize size;

    simple = load_context->simple;

    file_info = load_context->file_info;
    attachment = load_context->attachment;
    output_stream = G_MEMORY_OUTPUT_STREAM (load_context->output_stream);

    if (e_attachment_is_rfc822 (attachment))
        wrapper = (CamelDataWrapper *) camel_mime_message_new ();
    else
        wrapper = camel_data_wrapper_new ();

    content_type = g_file_info_get_content_type (file_info);
    mime_type = g_content_type_get_mime_type (content_type);

    data = g_memory_output_stream_get_data (output_stream);
    size = g_memory_output_stream_get_data_size (output_stream);

    stream = camel_stream_mem_new_with_buffer (data, size);
    camel_data_wrapper_construct_from_stream (wrapper, stream);
    camel_data_wrapper_set_mime_type (wrapper, mime_type);
    camel_stream_close (stream);
    g_object_unref (stream);

    mime_part = camel_mime_part_new ();
    camel_medium_set_content (CAMEL_MEDIUM (mime_part), wrapper);

    g_object_unref (wrapper);
    g_free (mime_type);

    display_name = g_file_info_get_display_name (file_info);
    if (display_name != NULL)
        camel_mime_part_set_filename (mime_part, display_name);

    attribute = G_FILE_ATTRIBUTE_STANDARD_DESCRIPTION;
    description = g_file_info_get_attribute_string (file_info, attribute);
    if (description != NULL)
        camel_mime_part_set_description (mime_part, description);

    disposition = e_attachment_get_disposition (attachment);
    if (disposition != NULL)
        camel_mime_part_set_disposition (mime_part, disposition);

    /* Correctly report the size of zero length special files. */
    if (g_file_info_get_size (file_info) == 0) {
        g_file_info_set_size (file_info, size);
        e_attachment_set_file_info (attachment, file_info);
    }

    g_simple_async_result_set_op_res_gpointer (
        simple, mime_part, (GDestroyNotify) g_object_unref);

    g_simple_async_result_complete (simple);

    attachment_load_context_free (load_context);
}

static void
attachment_load_write_cb (GOutputStream *output_stream,
                          GAsyncResult *result,
                          LoadContext *load_context)
{
    EAttachment *attachment;
    GCancellable *cancellable;
    GInputStream *input_stream;
    gssize bytes_written;
    GError *error = NULL;

    bytes_written = g_output_stream_write_finish (
        output_stream, result, &error);

    if (attachment_load_check_for_error (load_context, error))
        return;

    attachment = load_context->attachment;
    cancellable = attachment->priv->cancellable;
    input_stream = load_context->input_stream;

    attachment_progress_cb (
        g_seekable_tell (G_SEEKABLE (output_stream)),
        load_context->total_num_bytes, attachment);

    if (bytes_written < load_context->bytes_read) {
        g_memmove (
            load_context->buffer,
            load_context->buffer + bytes_written,
            load_context->bytes_read - bytes_written);
        load_context->bytes_read -= bytes_written;

        g_output_stream_write_async (
            output_stream,
            load_context->buffer,
            load_context->bytes_read,
            G_PRIORITY_DEFAULT, cancellable,
            (GAsyncReadyCallback) attachment_load_write_cb,
            load_context);
    } else
        g_input_stream_read_async (
            input_stream,
            load_context->buffer,
            sizeof (load_context->buffer),
            G_PRIORITY_DEFAULT, cancellable,
            (GAsyncReadyCallback) attachment_load_stream_read_cb,
            load_context);
}

static void
attachment_load_stream_read_cb (GInputStream *input_stream,
                                GAsyncResult *result,
                                LoadContext *load_context)
{
    EAttachment *attachment;
    GCancellable *cancellable;
    GOutputStream *output_stream;
    gssize bytes_read;
    GError *error = NULL;

    bytes_read = g_input_stream_read_finish (
        input_stream, result, &error);

    if (attachment_load_check_for_error (load_context, error))
        return;

    if (bytes_read == 0) {
        attachment_load_finish (load_context);
        return;
    }

    attachment = load_context->attachment;
    cancellable = attachment->priv->cancellable;
    output_stream = load_context->output_stream;
    load_context->bytes_read = bytes_read;

    g_output_stream_write_async (
        output_stream,
        load_context->buffer,
        load_context->bytes_read,
        G_PRIORITY_DEFAULT, cancellable,
        (GAsyncReadyCallback) attachment_load_write_cb,
        load_context);
}

static void
attachment_load_file_read_cb (GFile *file,
                              GAsyncResult *result,
                              LoadContext *load_context)
{
    EAttachment *attachment;
    GCancellable *cancellable;
    GFileInputStream *input_stream;
    GOutputStream *output_stream;
    GError *error = NULL;

    /* Input stream might be NULL, so don't use cast macro. */
    input_stream = g_file_read_finish (file, result, &error);
    load_context->input_stream = (GInputStream *) input_stream;

    if (attachment_load_check_for_error (load_context, error))
        return;

    /* Load the contents into a GMemoryOutputStream. */
    output_stream = g_memory_output_stream_new (
        NULL, 0, g_realloc, g_free);

    attachment = load_context->attachment;
    cancellable = attachment->priv->cancellable;
    load_context->output_stream = output_stream;

    g_input_stream_read_async (
        load_context->input_stream,
        load_context->buffer,
        sizeof (load_context->buffer),
        G_PRIORITY_DEFAULT, cancellable,
        (GAsyncReadyCallback) attachment_load_stream_read_cb,
        load_context);
}

static void
attachment_load_query_info_cb (GFile *file,
                               GAsyncResult *result,
                               LoadContext *load_context)
{
    EAttachment *attachment;
    GCancellable *cancellable;
    GFileInfo *file_info;
    GError *error = NULL;

    attachment = load_context->attachment;
    cancellable = attachment->priv->cancellable;

    file_info = g_file_query_info_finish (file, result, &error);
    if (attachment_load_check_for_error (load_context, error))
        return;

    e_attachment_set_file_info (attachment, file_info);
    load_context->file_info = file_info;

    load_context->total_num_bytes = g_file_info_get_size (file_info);

    g_file_read_async (
        file, G_PRIORITY_DEFAULT,
        cancellable, (GAsyncReadyCallback)
        attachment_load_file_read_cb, load_context);
}

static void
attachment_load_from_mime_part (LoadContext *load_context)
{
    GFileInfo *file_info;
    EAttachment *attachment;
    GSimpleAsyncResult *simple;
    CamelContentType *content_type;
    CamelMimePart *mime_part;
    const gchar *attribute;
    const gchar *string;
    gchar *allocated;

    attachment = load_context->attachment;
    mime_part = e_attachment_get_mime_part (attachment);

    file_info = g_file_info_new ();
    load_context->file_info = file_info;

    content_type = camel_mime_part_get_content_type (mime_part);
    allocated = camel_content_type_simple (content_type);
    if (allocated != NULL) {
        GIcon *icon;
        gchar *cp;

        /* GIO expects lowercase MIME types. */
        for (cp = allocated; *cp != '\0'; cp++)
            *cp = g_ascii_tolower (*cp);

        /* Swap the MIME type for a content type. */
        cp = g_content_type_from_mime_type (allocated);
        g_free (allocated);
        allocated = cp;

        /* Use the MIME part's filename if we have to. */
        if (g_content_type_is_unknown (allocated)) {
            string = camel_mime_part_get_filename (mime_part);
            if (string != NULL) {
                g_free (allocated);
                allocated = g_content_type_guess (
                    string, NULL, 0, NULL);
            }
        }

        g_file_info_set_content_type (file_info, allocated);

        icon = g_content_type_get_icon (allocated);
        if (icon != NULL) {
            g_file_info_set_icon (file_info, icon);
            g_object_unref (icon);
        }
    }
    g_free (allocated);

    string = camel_mime_part_get_filename (mime_part);
    if (string == NULL)
        /* Translators: Default attachment filename. */
        string = _("attachment.dat");
    g_file_info_set_display_name (file_info, string);

    attribute = G_FILE_ATTRIBUTE_STANDARD_DESCRIPTION;
    string = camel_mime_part_get_description (mime_part);
    if (string != NULL)
        g_file_info_set_attribute_string (
            file_info, attribute, string);

    string = camel_mime_part_get_disposition (mime_part);
    e_attachment_set_disposition (attachment, string);

    e_attachment_set_file_info (attachment, file_info);

    g_object_ref (mime_part);

    simple = load_context->simple;
    g_simple_async_result_set_op_res_gpointer (
        simple, mime_part,
        (GDestroyNotify) g_object_unref);
    g_simple_async_result_complete (simple);

    attachment_load_context_free (load_context);
}

void
e_attachment_load_async (EAttachment *attachment,
                         GAsyncReadyCallback callback,
                         gpointer user_data)
{
    LoadContext *load_context;
    GCancellable *cancellable;
    CamelMimePart *mime_part;
    GFile *file;

    g_return_if_fail (E_IS_ATTACHMENT (attachment));

    if (e_attachment_get_loading (attachment)) {
        g_simple_async_report_error_in_idle (
            G_OBJECT (attachment), callback, user_data,
            G_IO_ERROR, G_IO_ERROR_BUSY,
            _("A load operation is already in progress"));
        return;
    }

    if (e_attachment_get_saving (attachment)) {
        g_simple_async_report_error_in_idle (
            G_OBJECT (attachment), callback, user_data,
            G_IO_ERROR, G_IO_ERROR_BUSY,
            _("A save operation is already in progress"));
        return;
    }

    file = e_attachment_get_file (attachment);
    mime_part = e_attachment_get_mime_part (attachment);
    g_return_if_fail (file != NULL || mime_part != NULL);

    load_context = attachment_load_context_new (
        attachment, callback, user_data);

    cancellable = attachment->priv->cancellable;
    g_cancellable_reset (cancellable);

    if (file != NULL)
        g_file_query_info_async (
            file, ATTACHMENT_QUERY,
            G_FILE_QUERY_INFO_NONE,G_PRIORITY_DEFAULT,
            cancellable, (GAsyncReadyCallback)
            attachment_load_query_info_cb, load_context);

    else if (mime_part != NULL)
        attachment_load_from_mime_part (load_context);

}

gboolean
e_attachment_load_finish (EAttachment *attachment,
                          GAsyncResult *result,
                          GError **error)
{
    GSimpleAsyncResult *simple;
    CamelMimePart *mime_part;

    g_return_val_if_fail (E_IS_ATTACHMENT (attachment), FALSE);
    g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (result), FALSE);

    simple = G_SIMPLE_ASYNC_RESULT (result);
    mime_part = g_simple_async_result_get_op_res_gpointer (simple);
    if (mime_part != NULL)
        e_attachment_set_mime_part (attachment, mime_part);
    g_simple_async_result_propagate_error (simple, error);

    attachment_set_loading (attachment, FALSE);

    return (mime_part != NULL);
}

void
e_attachment_load_handle_error (EAttachment *attachment,
                                GAsyncResult *result,
                                GtkWindow *parent)
{
    GtkWidget *dialog;
    GFileInfo *file_info;
    GtkTreeRowReference *reference;
    const gchar *display_name;
    const gchar *primary_text;
    GError *error = NULL;

    g_return_if_fail (E_IS_ATTACHMENT (attachment));
    g_return_if_fail (G_IS_ASYNC_RESULT (result));
    g_return_if_fail (GTK_IS_WINDOW (parent));

    if (e_attachment_load_finish (attachment, result, &error))
        return;

    /* XXX Calling EAttachmentStore functions from here violates
     *     the abstraction, but for now it's not hurting anything. */
    reference = e_attachment_get_reference (attachment);
    if (gtk_tree_row_reference_valid (reference)) {
        GtkTreeModel *model;

        model = gtk_tree_row_reference_get_model (reference);

        e_attachment_store_remove_attachment (
            E_ATTACHMENT_STORE (model), attachment);
    }

    /* Ignore cancellations. */
    if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
        return;

    file_info = e_attachment_get_file_info (attachment);

    if (file_info != NULL)
        display_name = g_file_info_get_display_name (file_info);
    else
        display_name = NULL;

    if (display_name != NULL)
        primary_text = g_strdup_printf (
            _("Could not load '%s'"), display_name);
    else
        primary_text = g_strdup_printf (
            _("Could not load the attachment"));

    dialog = gtk_message_dialog_new_with_markup (
        parent, GTK_DIALOG_DESTROY_WITH_PARENT,
        GTK_MESSAGE_ERROR, GTK_BUTTONS_OK,
        "<big><b>%s</b></big>", primary_text);

    gtk_message_dialog_format_secondary_text (
        GTK_MESSAGE_DIALOG (dialog), "%s", error->message);

    gtk_dialog_run (GTK_DIALOG (dialog));

    gtk_widget_destroy (dialog);
    g_error_free (error);
}

/************************* e_attachment_open_async() *************************/

typedef struct _OpenContext OpenContext;

struct _OpenContext {
    EAttachment *attachment;
    GSimpleAsyncResult *simple;

    GAppInfo *app_info;
};

static OpenContext *
attachment_open_context_new (EAttachment *attachment,
                             GAsyncReadyCallback callback,
                             gpointer user_data)
{
    OpenContext *open_context;
    GSimpleAsyncResult *simple;

    simple = g_simple_async_result_new (
        G_OBJECT (attachment), callback,
        user_data, e_attachment_open_async);

    open_context = g_slice_new0 (OpenContext);
    open_context->attachment = g_object_ref (attachment);
    open_context->simple = simple;

    return open_context;
}

static void
attachment_open_context_free (OpenContext *open_context)
{
    g_object_unref (open_context->attachment);
    g_object_unref (open_context->simple);

    if (open_context->app_info != NULL)
        g_object_unref (open_context->app_info);

    g_slice_free (OpenContext, open_context);
}

static gboolean
attachment_open_check_for_error (OpenContext *open_context,
                                 GError *error)
{
    GSimpleAsyncResult *simple;

    if (error == NULL)
        return FALSE;

    simple = open_context->simple;
    g_simple_async_result_set_from_error (simple, error);
    g_simple_async_result_complete (simple);
    g_error_free (error);

    attachment_open_context_free (open_context);

    return TRUE;
}

static void
attachment_open_file (GFile *file,
                      OpenContext *open_context)
{
    GdkAppLaunchContext *context;
    GSimpleAsyncResult *simple;
    gboolean success;
    GError *error = NULL;

    simple = open_context->simple;

    context = gdk_app_launch_context_new ();

    if (open_context->app_info != NULL) {
        GList *file_list;

        file_list = g_list_prepend (NULL, file);
        success = g_app_info_launch (
            open_context->app_info, file_list,
            G_APP_LAUNCH_CONTEXT (context), &error);
        g_list_free (file_list);
    } else {
        gchar *uri;

        uri = g_file_get_uri (file);
        success = g_app_info_launch_default_for_uri (
            uri, G_APP_LAUNCH_CONTEXT (context), &error);
        g_free (uri);
    }

    g_object_unref (context);

    g_simple_async_result_set_op_res_gboolean (simple, success);

    if (error != NULL) {
        g_simple_async_result_set_from_error (simple, error);
        g_error_free (error);
    }

    g_simple_async_result_complete (simple);
    attachment_open_context_free (open_context);
}

static void
attachment_open_save_finished_cb (EAttachment *attachment,
                                  GAsyncResult *result,
                                  OpenContext *open_context)
{
    GFile *file;
    gchar *path;
    GError *error = NULL;

    file = e_attachment_save_finish (attachment, result, &error);

    if (attachment_open_check_for_error (open_context, error))
        return;

    /* Make the temporary file read-only.
     *
     * This step is non-critical, so if an error occurs just
     * emit a warning and move on.
     *
     * XXX I haven't figured out how to do this through GIO.
     *     Attempting to set the "access::can-write" attribute via
     *     g_file_set_attribute() returned G_IO_ERROR_NOT_SUPPORTED
     *     and the only other possibility I see is "unix::mode",
     *     which is obviously not portable.
     */
    path = g_file_get_path (file);
#ifndef G_OS_WIN32
    if (g_chmod (path, S_IRUSR | S_IRGRP | S_IROTH) < 0)
        g_warning ("%s", g_strerror (errno));
#endif
    g_free (path);

    attachment_open_file (file, open_context);
    g_object_unref (file);
}

static void
attachment_open_save_temporary (OpenContext *open_context)
{
    GFile *temp_directory;
    gchar *template;
    gchar *path;
    GError *error = NULL;

    errno = 0;

    /* Save the file to a temporary directory.
     * We use a directory so the files can retain their basenames.
     * XXX This could trigger a blocking temp directory cleanup. */
    template = g_strdup_printf (PACKAGE "-%s-XXXXXX", g_get_user_name ());
    path = e_mkdtemp (template);
    g_free (template);

    /* XXX Let's hope errno got set properly. */
    if (path == NULL)
        g_set_error (
            &error, G_FILE_ERROR,
            g_file_error_from_errno (errno),
            "%s", g_strerror (errno));

    /* We already know if there's an error, but this does the cleanup. */
    if (attachment_open_check_for_error (open_context, error))
        return;

    temp_directory = g_file_new_for_path (path);

    e_attachment_save_async (
        open_context->attachment,
        temp_directory, (GAsyncReadyCallback)
        attachment_open_save_finished_cb, open_context);

    g_object_unref (temp_directory);
    g_free (path);
}

void
e_attachment_open_async (EAttachment *attachment,
                         GAppInfo *app_info,
                         GAsyncReadyCallback callback,
                         gpointer user_data)
{
    OpenContext *open_context;
    CamelMimePart *mime_part;
    GFile *file;

    g_return_if_fail (E_IS_ATTACHMENT (attachment));

    file = e_attachment_get_file (attachment);
    mime_part = e_attachment_get_mime_part (attachment);
    g_return_if_fail (file != NULL || mime_part != NULL);

    open_context = attachment_open_context_new (
        attachment, callback, user_data);

    if (G_IS_APP_INFO (app_info))
        open_context->app_info = g_object_ref (app_info);

    /* If the attachment already references a GFile, we can launch
     * the application directly.  Otherwise we have to save the MIME
     * part to a temporary file and launch the application from that. */
    if (file != NULL) {
        attachment_open_file (file, open_context);

    } else if (mime_part != NULL)
        attachment_open_save_temporary (open_context);
}

gboolean
e_attachment_open_finish (EAttachment *attachment,
                          GAsyncResult *result,
                          GError **error)
{
    GSimpleAsyncResult *simple;
    gboolean success;

    g_return_val_if_fail (E_IS_ATTACHMENT (attachment), FALSE);
    g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (result), FALSE);

    simple = G_SIMPLE_ASYNC_RESULT (result);
    success = g_simple_async_result_get_op_res_gboolean (simple);
    g_simple_async_result_propagate_error (simple, error);

    return success;
}

void
e_attachment_open_handle_error (EAttachment *attachment,
                                GAsyncResult *result,
                                GtkWindow *parent)
{
    GtkWidget *dialog;
    GFileInfo *file_info;
    const gchar *display_name;
    const gchar *primary_text;
    GError *error = NULL;

    g_return_if_fail (E_IS_ATTACHMENT (attachment));
    g_return_if_fail (G_IS_ASYNC_RESULT (result));
    g_return_if_fail (GTK_IS_WINDOW (parent));

    if (e_attachment_open_finish (attachment, result, &error))
        return;

    /* Ignore cancellations. */
    if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
        return;

    file_info = e_attachment_get_file_info (attachment);

    if (file_info != NULL)
        display_name = g_file_info_get_display_name (file_info);
    else
        display_name = NULL;

    if (display_name != NULL)
        primary_text = g_strdup_printf (
            _("Could not open '%s'"), display_name);
    else
        primary_text = g_strdup_printf (
            _("Could not open the attachment"));

    dialog = gtk_message_dialog_new_with_markup (
        parent, GTK_DIALOG_DESTROY_WITH_PARENT,
        GTK_MESSAGE_ERROR, GTK_BUTTONS_OK,
        "<big><b>%s</b></big>", primary_text);

    gtk_message_dialog_format_secondary_text (
        GTK_MESSAGE_DIALOG (dialog), "%s", error->message);

    gtk_dialog_run (GTK_DIALOG (dialog));

    gtk_widget_destroy (dialog);
    g_error_free (error);
}

/************************* e_attachment_save_async() *************************/

typedef struct _SaveContext SaveContext;

struct _SaveContext {
    EAttachment *attachment;
    GSimpleAsyncResult *simple;

    GFile *directory;
    GFile *destination;
    GInputStream *input_stream;
    GOutputStream *output_stream;
    goffset total_num_bytes;
    gssize bytes_read;
    gchar buffer[4096];
    gint count;
};

/* Forward Declaration */
static void
attachment_save_read_cb (GInputStream *input_stream,
                         GAsyncResult *result,
                         SaveContext *save_context);

static SaveContext *
attachment_save_context_new (EAttachment *attachment,
                             GAsyncReadyCallback callback,
                             gpointer user_data)
{
    SaveContext *save_context;
    GSimpleAsyncResult *simple;

    simple = g_simple_async_result_new (
        G_OBJECT (attachment), callback,
        user_data, e_attachment_save_async);

    save_context = g_slice_new0 (SaveContext);
    save_context->attachment = g_object_ref (attachment);
    save_context->simple = simple;

    attachment_set_saving (save_context->attachment, TRUE);

    return save_context;
}

static void
attachment_save_context_free (SaveContext *save_context)
{
    g_object_unref (save_context->attachment);
    g_object_unref (save_context->simple);

    if (save_context->directory != NULL)
        g_object_unref (save_context->directory);

    if (save_context->destination != NULL)
        g_object_unref (save_context->destination);

    if (save_context->input_stream != NULL)
        g_object_unref (save_context->input_stream);

    if (save_context->output_stream != NULL)
        g_object_unref (save_context->output_stream);

    g_slice_free (SaveContext, save_context);
}

static gboolean
attachment_save_check_for_error (SaveContext *save_context,
                                 GError *error)
{
    GSimpleAsyncResult *simple;

    if (error == NULL)
        return FALSE;

    simple = save_context->simple;
    g_simple_async_result_set_from_error (simple, error);
    g_simple_async_result_complete (simple);
    g_error_free (error);

    attachment_save_context_free (save_context);

    return TRUE;
}

static GFile *
attachment_save_new_candidate (SaveContext *save_context)
{
    GFile *candidate;
    GFileInfo *file_info;
    EAttachment *attachment;
    const gchar *display_name = NULL;
    gchar *basename;

    attachment = save_context->attachment;
    file_info = e_attachment_get_file_info (attachment);

    if (file_info != NULL)
        display_name = g_file_info_get_display_name (file_info);
    if (display_name == NULL)
        /* Translators: Default attachment filename. */
        display_name = _("attachment.dat");

    if (save_context->count == 0)
        basename = g_strdup (display_name);
    else {
        GString *string;
        const gchar *ext;
        gsize length;

        string = g_string_sized_new (strlen (display_name));
        ext = g_utf8_strchr (display_name, -1, '.');

        if (ext != NULL)
            length = ext - display_name;
        else
            length = strlen (display_name);

        g_string_append_len (string, display_name, length);
        g_string_append_printf (string, " (%d)", save_context->count);
        g_string_append (string, (ext != NULL) ? ext : "");

        basename = g_string_free (string, FALSE);
    }

    save_context->count++;

    candidate = g_file_get_child (save_context->directory, basename);

    g_free (basename);

    return candidate;
}

static void
attachment_save_write_cb (GOutputStream *output_stream,
                          GAsyncResult *result,
                          SaveContext *save_context)
{
    EAttachment *attachment;
    GCancellable *cancellable;
    GInputStream *input_stream;
    gssize bytes_written;
    GError *error = NULL;

    bytes_written = g_output_stream_write_finish (
        output_stream, result, &error);

    if (attachment_save_check_for_error (save_context, error))
        return;

    attachment = save_context->attachment;
    cancellable = attachment->priv->cancellable;
    input_stream = save_context->input_stream;

    if (bytes_written < save_context->bytes_read) {
        g_memmove (
            save_context->buffer,
            save_context->buffer + bytes_written,
            save_context->bytes_read - bytes_written);
        save_context->bytes_read -= bytes_written;

        g_output_stream_write_async (
            output_stream,
            save_context->buffer,
            save_context->bytes_read,
            G_PRIORITY_DEFAULT, cancellable,
            (GAsyncReadyCallback) attachment_save_write_cb,
            save_context);
    } else
        g_input_stream_read_async (
            input_stream,
            save_context->buffer,
            sizeof (save_context->buffer),
            G_PRIORITY_DEFAULT, cancellable,
            (GAsyncReadyCallback) attachment_save_read_cb,
            save_context);
}

static void
attachment_save_read_cb (GInputStream *input_stream,
                         GAsyncResult *result,
                         SaveContext *save_context)
{
    EAttachment *attachment;
    GCancellable *cancellable;
    GOutputStream *output_stream;
    gssize bytes_read;
    GError *error = NULL;

    bytes_read = g_input_stream_read_finish (
        input_stream, result, &error);

    if (attachment_save_check_for_error (save_context, error))
        return;

    if (bytes_read == 0) {
        GSimpleAsyncResult *simple;
        GFile *destination;

        /* Steal the destination. */
        destination = save_context->destination;
        save_context->destination = NULL;

        simple = save_context->simple;
        g_simple_async_result_set_op_res_gpointer (
            simple, destination, (GDestroyNotify) g_object_unref);
        g_simple_async_result_complete (simple);

        attachment_save_context_free (save_context);

        return;
    }

    attachment = save_context->attachment;
    cancellable = attachment->priv->cancellable;
    output_stream = save_context->output_stream;
    save_context->bytes_read = bytes_read;

    attachment_progress_cb (
        g_seekable_tell (G_SEEKABLE (input_stream)),
        save_context->total_num_bytes, attachment);

    g_output_stream_write_async (
        output_stream,
        save_context->buffer,
        save_context->bytes_read,
        G_PRIORITY_DEFAULT, cancellable,
        (GAsyncReadyCallback) attachment_save_write_cb,
        save_context);
}

static void
attachment_save_got_output_stream (SaveContext *save_context)
{
    GCancellable *cancellable;
    GInputStream *input_stream;
    CamelDataWrapper *wrapper;
    CamelMimePart *mime_part;
    CamelStream *stream;
    EAttachment *attachment;
    GByteArray *buffer;

    attachment = save_context->attachment;
    cancellable = attachment->priv->cancellable;
    mime_part = e_attachment_get_mime_part (attachment);

    /* Decode the MIME part to an in-memory buffer.  We have to do
     * this because CamelStream is synchronous-only, and using threads
     * is dangerous because CamelDataWrapper is not reentrant. */
    buffer = g_byte_array_new ();
    stream = camel_stream_mem_new ();
    camel_stream_mem_set_byte_array (CAMEL_STREAM_MEM (stream), buffer);
    wrapper = camel_medium_get_content (CAMEL_MEDIUM (mime_part));
    camel_data_wrapper_decode_to_stream (wrapper, stream);
    g_object_unref (stream);

    /* Load the buffer into a GMemoryInputStream.
     * But watch out for zero length MIME parts. */
    input_stream = g_memory_input_stream_new ();
    if (buffer->len > 0)
        g_memory_input_stream_add_data (
            G_MEMORY_INPUT_STREAM (input_stream),
            buffer->data, (gssize) buffer->len,
            (GDestroyNotify) g_free);
    save_context->input_stream = input_stream;
    save_context->total_num_bytes = (goffset) buffer->len;
    g_byte_array_free (buffer, FALSE);

    g_input_stream_read_async (
        input_stream,
        save_context->buffer,
        sizeof (save_context->buffer),
        G_PRIORITY_DEFAULT, cancellable,
        (GAsyncReadyCallback) attachment_save_read_cb,
        save_context);
}

static void
attachment_save_create_cb (GFile *destination,
                           GAsyncResult *result,
                           SaveContext *save_context)
{
    EAttachment *attachment;
    GCancellable *cancellable;
    GFileOutputStream *output_stream;
    GError *error = NULL;

    /* Output stream might be NULL, so don't use cast macro. */
    output_stream = g_file_create_finish (destination, result, &error);
    save_context->output_stream = (GOutputStream *) output_stream;

    attachment = save_context->attachment;
    cancellable = attachment->priv->cancellable;

    if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_EXISTS)) {
        destination = attachment_save_new_candidate (save_context);

        g_file_create_async (
            destination, G_FILE_CREATE_NONE,
            G_PRIORITY_DEFAULT, cancellable,
            (GAsyncReadyCallback) attachment_save_create_cb,
            save_context);

        g_object_unref (destination);
        g_error_free (error);
        return;
    }

    if (attachment_save_check_for_error (save_context, error))
        return;

    save_context->destination = g_object_ref (destination);
    attachment_save_got_output_stream (save_context);
}

static void
attachment_save_replace_cb (GFile *destination,
                            GAsyncResult *result,
                            SaveContext *save_context)
{
    GFileOutputStream *output_stream;
    GError *error = NULL;

    /* Output stream might be NULL, so don't use cast macro. */
    output_stream = g_file_replace_finish (destination, result, &error);
    save_context->output_stream = (GOutputStream *) output_stream;

    if (attachment_save_check_for_error (save_context, error))
        return;

    save_context->destination = g_object_ref (destination);
    attachment_save_got_output_stream (save_context);
}

static void
attachment_save_query_info_cb (GFile *destination,
                               GAsyncResult *result,
                               SaveContext *save_context)
{
    EAttachment *attachment;
    GCancellable *cancellable;
    GFileInfo *file_info;
    GFileType file_type;
    GError *error = NULL;

    attachment = save_context->attachment;
    cancellable = attachment->priv->cancellable;

    file_info = g_file_query_info_finish (destination, result, &error);

    /* G_IO_ERROR_NOT_FOUND just means we're creating a new file. */
    if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND)) {
        g_error_free (error);
        goto replace;
    }

    if (attachment_save_check_for_error (save_context, error))
        return;

    file_type = g_file_info_get_file_type (file_info);
    g_object_unref (file_info);

    if (file_type == G_FILE_TYPE_DIRECTORY) {
        save_context->directory = g_object_ref (destination);
        destination = attachment_save_new_candidate (save_context);

        g_file_create_async (
            destination, G_FILE_CREATE_NONE,
            G_PRIORITY_DEFAULT, cancellable,
            (GAsyncReadyCallback) attachment_save_create_cb,
            save_context);

        g_object_unref (destination);

        return;
    }

replace:
    g_file_replace_async (
        destination, NULL, FALSE,
        G_FILE_CREATE_REPLACE_DESTINATION,
        G_PRIORITY_DEFAULT, cancellable,
        (GAsyncReadyCallback) attachment_save_replace_cb,
        save_context);
}

void
e_attachment_save_async (EAttachment *attachment,
                         GFile *destination,
                         GAsyncReadyCallback callback,
                         gpointer user_data)
{
    SaveContext *save_context;
    GCancellable *cancellable;

    g_return_if_fail (E_IS_ATTACHMENT (attachment));
    g_return_if_fail (G_IS_FILE (destination));

    if (e_attachment_get_loading (attachment)) {
        g_simple_async_report_error_in_idle (
            G_OBJECT (attachment), callback, user_data,
            G_IO_ERROR, G_IO_ERROR_BUSY,
            _("A load operation is already in progress"));
        return;
    }

    if (e_attachment_get_saving (attachment)) {
        g_simple_async_report_error_in_idle (
            G_OBJECT (attachment), callback, user_data,
            G_IO_ERROR, G_IO_ERROR_BUSY,
            _("A save operation is already in progress"));
        return;
    }

    if (e_attachment_get_mime_part (attachment) == NULL) {
        g_simple_async_report_error_in_idle (
            G_OBJECT (attachment), callback, user_data,
            G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
            _("Attachment contents not loaded"));
        return;
    }

    save_context = attachment_save_context_new (
        attachment, callback, user_data);

    cancellable = attachment->priv->cancellable;
    g_cancellable_reset (cancellable);

    /* First we need to know if destination is a directory. */
    g_file_query_info_async (
        destination, G_FILE_ATTRIBUTE_STANDARD_TYPE,
        G_FILE_QUERY_INFO_NONE, G_PRIORITY_DEFAULT,
        cancellable, (GAsyncReadyCallback)
        attachment_save_query_info_cb, save_context);
}

GFile *
e_attachment_save_finish (EAttachment *attachment,
                          GAsyncResult *result,
                          GError **error)
{
    GSimpleAsyncResult *simple;
    GFile *destination;

    g_return_val_if_fail (E_IS_ATTACHMENT (attachment), NULL);
    g_return_val_if_fail (G_IS_SIMPLE_ASYNC_RESULT (result), NULL);

    simple = G_SIMPLE_ASYNC_RESULT (result);
    destination = g_simple_async_result_get_op_res_gpointer (simple);
    if (destination != NULL)
        g_object_ref (destination);
    g_simple_async_result_propagate_error (simple, error);

    attachment_set_saving (attachment, FALSE);

    return destination;
}

void
e_attachment_save_handle_error (EAttachment *attachment,
                                GAsyncResult *result,
                                GtkWindow *parent)
{
    GFile *file;
    GFileInfo *file_info;
    GtkWidget *dialog;
    const gchar *display_name;
    const gchar *primary_text;
    GError *error = NULL;

    g_return_if_fail (E_IS_ATTACHMENT (attachment));
    g_return_if_fail (G_IS_ASYNC_RESULT (result));
    g_return_if_fail (GTK_IS_WINDOW (parent));

    file = e_attachment_save_finish (attachment, result, &error);

    if (file != NULL) {
        g_object_unref (file);
        return;
    }

    /* Ignore cancellations. */
    if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
        return;

    file_info = e_attachment_get_file_info (attachment);

    if (file_info != NULL)
        display_name = g_file_info_get_display_name (file_info);
    else
        display_name = NULL;

    if (display_name != NULL)
        primary_text = g_strdup_printf (
            _("Could not save '%s'"), display_name);
    else
        primary_text = g_strdup_printf (
            _("Could not save the attachment"));

    dialog = gtk_message_dialog_new_with_markup (
        parent, GTK_DIALOG_DESTROY_WITH_PARENT,
        GTK_MESSAGE_ERROR, GTK_BUTTONS_OK,
        "<big><b>%s</b></big>", primary_text);

    gtk_message_dialog_format_secondary_text (
        GTK_MESSAGE_DIALOG (dialog), "%s", error->message);

    gtk_dialog_run (GTK_DIALOG (dialog));

    gtk_widget_destroy (dialog);
    g_error_free (error);
}