aboutsummaryrefslogtreecommitdiffstats
path: root/mail/message-browser.c
blob: 6d8e4319c21e7e0d8e3830201836a983114ac389 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
/*
 *  Authors: Jeffrey Stedfast <fejj@ximian.com>
 *
 *  Copyright 2001 Ximian, Inc. (www.ximian.com)
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Street #330, Boston, MA 02111-1307, USA.
 *
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <gal/util/e-util.h>
#include <gal/widgets/e-unicode.h>

#include <bonobo/bonobo-exception.h>
#include <bonobo/bonobo-ui-component.h>
#include <bonobo/bonobo-ui-container.h>
#include <bonobo/bonobo-ui-util.h>

#include "message-browser.h"

#include "mail.h"
#include "mail-callbacks.h"
#include "mail-tools.h"
#include "message-list.h"
#include "mail-ops.h"
#include "mail-vfolder.h"
#include "mail-autofilter.h"
#include "mail-mt.h"

#include "mail-local.h"
#include "mail-config.h"

#include "folder-browser-ui.h"

#define d(x) x

#define MINIMUM_WIDTH  600
#define MINIMUM_HEIGHT 400

#define PARENT_TYPE BONOBO_TYPE_WINDOW

/* Size of the window last time it was changed.  */
static GtkAllocation last_allocation = { 0, 0 };

static BonoboWindowClass *message_browser_parent_class;

static void
message_browser_destroy (GtkObject *object)
{
    MessageBrowser *message_browser;
    
    message_browser = MESSAGE_BROWSER (object);
    
    gtk_object_unref (GTK_OBJECT (message_browser->fb));
    
    gtk_widget_destroy (GTK_WIDGET (message_browser));

    if (GTK_OBJECT_CLASS (message_browser_parent_class)->destroy)
        (GTK_OBJECT_CLASS (message_browser_parent_class)->destroy) (object);
}

static void
message_browser_class_init (GtkObjectClass *object_class)
{
    object_class->destroy = message_browser_destroy;
    
    message_browser_parent_class = gtk_type_class (PARENT_TYPE);
}

static void
message_browser_init (GtkObject *object)
{
    
}

/* UI callbacks */

static void
message_browser_close (BonoboUIComponent *uih, void *user_data, const char *path)
{
    gtk_widget_destroy (GTK_WIDGET (user_data));
}

static BonoboUIVerb 
browser_verbs [] = {
    BONOBO_UI_UNSAFE_VERB ("MessageBrowserClose", message_browser_close),
    BONOBO_UI_VERB_END
};

/* FB message loading hookups */

static void
message_browser_message_loaded (FolderBrowser *fb, const char *uid, MessageBrowser *mb)
{
    CamelMimeMessage *message;
    char *subject = NULL;
    char *title;
    
    g_warning ("got 'message_loaded' event");
    
    message = fb->mail_display->current_message;
    
    if (message)
        subject = (char *) camel_mime_message_get_subject (message);

    if (subject != NULL)
        subject = e_utf8_to_gtk_string (GTK_WIDGET (mb), subject);
    else
        subject = _("(No subject)");

    title = g_strdup_printf (_("%s - Message"), subject);
    
    gtk_window_set_title (GTK_WINDOW (mb), title);

    g_free (title);
}

static void
message_browser_message_list_built (MessageList *ml, MessageBrowser *mb)
{
    const char *uid = gtk_object_get_data (GTK_OBJECT (mb), "uid");
    
    g_warning ("got 'message_list_built' event");
    
    message_list_select_uid (ml, uid);
}

static void
message_browser_folder_loaded (FolderBrowser *fb, const char *uri, MessageBrowser *mb)
{
    g_warning ("got 'folder_loaded' event for '%s'", uri);
    
    gtk_signal_connect (GTK_OBJECT (fb->message_list), "message_list_built",
                message_browser_message_list_built, mb);
}

static void
message_browser_size_allocate_cb (GtkWidget *widget,
                  GtkAllocation *allocation)
{
    last_allocation = *allocation;

}

/* Construction */

static void
set_default_size (GtkWidget *widget)
{
    int width, height;
    
    width  = MAX (MINIMUM_WIDTH, last_allocation.width);
    height = MAX (MINIMUM_HEIGHT, last_allocation.height);
    
    gtk_window_set_default_size (GTK_WINDOW (widget), width, height);
}

static void 
set_bonobo_ui (GtkWidget *widget, FolderBrowser *fb)
{
    BonoboUIContainer *uicont;
    BonoboUIComponent *uic;
    CORBA_Environment ev;

    uicont = bonobo_ui_container_new ();
    bonobo_ui_container_set_win (uicont, BONOBO_WINDOW (widget));

    uic = bonobo_ui_component_new_default ();
    bonobo_ui_component_set_container (uic, BONOBO_OBJREF (uicont));
    folder_browser_set_ui_component (fb, uic);

    /* Load our UI */

    bonobo_ui_component_freeze (uic, NULL);
    bonobo_ui_util_set_ui (uic, EVOLUTION_DATADIR, "evolution-mail-messagedisplay.xml", "evolution-mail");

    /* Load the appropriate UI stuff from the folder browser */

    folder_browser_ui_add_message (fb);

    /* We just opened the message! We don't need to open it again. */

    CORBA_exception_init (&ev);
    bonobo_ui_component_rm (uic, "/menu/File/FileOps/MessageOpen", &ev);
    if (BONOBO_EX (&ev))
        g_warning ("Couldn't remove message open item. Weird. Error: %s",
               bonobo_exception_get_text (&ev));
    CORBA_exception_free (&ev);

    /* Add the Close item */

    bonobo_ui_component_add_verb_list_with_data (uic, browser_verbs, widget);

    /* Done */

    bonobo_ui_component_thaw (uic, NULL);

}

GtkWidget *
message_browser_new (const GNOME_Evolution_Shell shell, const char *uri, const char *uid)
{
    GtkWidget *vbox;
    MessageBrowser *new;
    FolderBrowser *fb;
    
    new = gtk_type_new (MESSAGE_BROWSER_TYPE);
    new = (MessageBrowser *) bonobo_window_construct (BONOBO_WINDOW (new), "Evolution", "");
    if (!new) {
        g_warning ("Failed to construct Bonobo window!");
        return NULL;
    }

    gtk_object_set_data_full (GTK_OBJECT (new), "uid", g_strdup (uid), g_free);

    fb = FOLDER_BROWSER (folder_browser_new (shell));
    new->fb = fb;

    set_bonobo_ui (GTK_WIDGET (new), fb);

    /* some evil hackery action... */
    vbox = gtk_vbox_new (TRUE, 0);
    gtk_widget_ref (GTK_WIDGET (fb->mail_display));
    gtk_widget_reparent (GTK_WIDGET (fb->mail_display), vbox);
    gtk_widget_show (GTK_WIDGET (fb->mail_display));
    gtk_widget_show (vbox);

    gtk_signal_connect(GTK_OBJECT(new), "size_allocate", 
               GTK_SIGNAL_FUNC(message_browser_size_allocate_cb), NULL);
    
    bonobo_window_set_contents (BONOBO_WINDOW (new), vbox);
    gtk_widget_grab_focus (GTK_WIDGET (MAIL_DISPLAY (fb->mail_display)->html));
    
    set_default_size (GTK_WIDGET (new));
    
    /* more evil hackery... */
    gtk_signal_connect (GTK_OBJECT (fb), "folder_loaded",
                message_browser_folder_loaded, new);
    
    gtk_signal_connect (GTK_OBJECT (fb), "message_loaded",
                message_browser_message_loaded, new);
    
    folder_browser_set_uri (fb, uri);
    
    return GTK_WIDGET (new);
}

/* Fin */

E_MAKE_TYPE (message_browser, "MessageBrowser", MessageBrowser, message_browser_class_init,
         message_browser_init, PARENT_TYPE);
/a> 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436
/*
 * 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/>
 *
 *
 * Authors:
 *      Michael Zucchi <notzed@ximian.com>
 *
 * Copyright (C) 1999-2008 Novell, Inc. (www.novell.com)
 *
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <ctype.h>

#include <gtk/gtk.h>
#ifdef G_OS_WIN32
/* Work around 'DATADIR' and 'interface' lossage in <windows.h> */
#define DATADIR crap_DATADIR
#include <windows.h>
#undef DATADIR
#undef interface
#endif

#include <libebackend/e-extensible.h>
#include <libedataserver/e-time-utils.h>
#include <libedataserver/e-data-server-util.h>  /* for e_utf8_strftime, what about e_time_format_time? */

#include "e-util/e-datetime-format.h"
#include "e-util/e-icon-factory.h"
#include "e-util/e-util-private.h"
#include "e-util/e-util.h"
#include "misc/e-web-view.h"

#include <shell/e-shell.h>

#include <gtkhtml/gtkhtml.h>
#include <gtkhtml/gtkhtml-stream.h>

#include <glib/gi18n.h>

#include "e-mail-enumtypes.h"
#include "em-format-html.h"
#include "em-html-stream.h"
#include "em-utils.h"
#include "mail-config.h"
#include "mail-mt.h"

#define EM_FORMAT_HTML_GET_PRIVATE(obj) \
    (G_TYPE_INSTANCE_GET_PRIVATE \
    ((obj), EM_TYPE_FORMAT_HTML, EMFormatHTMLPrivate))

#define d(x)

#define EFM_MESSAGE_START_ANAME "evolution#message#start"
#define EFH_MESSAGE_START "<A name=\"" EFM_MESSAGE_START_ANAME "\"></A>"

struct _EMFormatHTMLCache {
    CamelMultipart *textmp;

    gchar partid[1];
};

struct _EMFormatHTMLPrivate {
    EWebView *web_view;

    CamelMimeMessage *last_part;    /* not reffed, DO NOT dereference */
    volatile gint format_id;        /* format thread id */
    guint format_timeout_id;
    struct _format_msg *format_timeout_msg;

    /* Table that re-maps text parts into a mutlipart/mixed, EMFormatHTMLCache * */
    GHashTable *text_inline_parts;

    GQueue pending_jobs;
    GMutex *lock;

    GdkColor colors[EM_FORMAT_HTML_NUM_COLOR_TYPES];
    EMailImageLoadingPolicy image_loading_policy;

    EMFormatHTMLHeadersState headers_state;
    gboolean headers_collapsable;

    guint load_images_now   : 1;
    guint only_local_photos : 1;
    guint show_sender_photo : 1;
    guint show_real_date    : 1;
};

enum {
    PROP_0,
    PROP_BODY_COLOR,
    PROP_CITATION_COLOR,
    PROP_CONTENT_COLOR,
    PROP_FRAME_COLOR,
    PROP_HEADER_COLOR,
    PROP_IMAGE_LOADING_POLICY,
    PROP_MARK_CITATIONS,
    PROP_ONLY_LOCAL_PHOTOS,
    PROP_SHOW_SENDER_PHOTO,
    PROP_SHOW_REAL_DATE,
    PROP_TEXT_COLOR,
    PROP_WEB_VIEW,
    PROP_HEADERS_STATE,
    PROP_HEADERS_COLLAPSABLE
};

static void efh_url_requested (GtkHTML *html, const gchar *url, GtkHTMLStream *handle, EMFormatHTML *efh);
static gboolean efh_object_requested (GtkHTML *html, GtkHTMLEmbedded *eb, EMFormatHTML *efh);
static void efh_gtkhtml_destroy (GtkHTML *html, EMFormatHTML *efh);

static void efh_format_message      (EMFormat *emf,
                         CamelStream *stream,
                         CamelMimePart *part,
                         const EMFormatHandler *info,
                         GCancellable *cancellable,
                         gboolean is_fallback);

static void efh_format_secure       (EMFormat *emf,
                         CamelStream *stream,
                         CamelMimePart *part,
                         CamelCipherValidity *valid,
                         GCancellable *cancellable);

static void efh_builtin_init        (EMFormatHTMLClass *efhc);

static void efh_write_image         (EMFormat *emf,
                         CamelStream *stream,
                         EMFormatPURI *puri,
                         GCancellable *cancellable);

static gpointer parent_class;
static CamelDataCache *emfh_http_cache;

#define EMFH_HTTP_CACHE_PATH "http"

/* Sigh, this is so we have a cancellable, async rendering thread */
struct _format_msg {
    MailMsg base;

    EMFormatHTML *format;
    EMFormat *format_source;
    EMHTMLStream *estream;
    CamelFolder *folder;
    gchar *uid;
    CamelMimeMessage *message;
    gboolean cancelled;
};

static gchar *
efh_format_desc (struct _format_msg *m)
{
    return g_strdup(_("Formatting message"));
}

static void
efh_format_exec (struct _format_msg *m,
                 GCancellable *cancellable,
                 GError **error)
{
    EMFormat *format;
    CamelStream *stream;
    struct _EMFormatHTMLJob *job;
    GNode *puri_level;
    CamelURL *base;
    gchar *content;

    if (m->format->priv->web_view == NULL) {
        m->cancelled = TRUE;
        return;
    }

    format = EM_FORMAT (m->format);
    stream = CAMEL_STREAM (m->estream);

    content = g_strdup_printf (
        "<!doctype html public \"-//W3C//DTD HTML 4.0 TRANSITIONAL//EN\">\n<html>\n"
        "<head>\n<meta name=\"generator\" content=\"Evolution Mail Component\">\n</head>\n"
        "<body bgcolor =\"#%06x\" text=\"#%06x\" marginwidth=6 marginheight=6>\n",
        e_color_to_value (
            &m->format->priv->colors[
            EM_FORMAT_HTML_COLOR_BODY]),
        e_color_to_value (
            &m->format->priv->colors[
            EM_FORMAT_HTML_COLOR_HEADER]));
    camel_stream_write_string (stream, content, cancellable, NULL);
    g_free (content);

    /* <insert top-header stuff here> */

    if (format->mode == EM_FORMAT_MODE_SOURCE) {
        em_format_format_source (
            format, stream,
            (CamelMimePart *) m->message, cancellable);
    } else {
        const EMFormatHandler *handle;
        const gchar *mime_type;

        mime_type = "x-evolution/message/prefix";
        handle = em_format_find_handler (format, mime_type);

        if (handle != NULL)
            handle->handler (
                format, stream,
                CAMEL_MIME_PART (m->message), handle,
                cancellable, FALSE);

        mime_type = "x-evolution/message/rfc822";
        handle = em_format_find_handler (format, mime_type);

        if (handle != NULL)
            handle->handler (
                format, stream,
                CAMEL_MIME_PART (m->message), handle,
                cancellable, FALSE);
    }

    camel_stream_flush (stream, cancellable, NULL);

    puri_level = format->pending_uri_level;
    base = format->base;

    do {
        /* now dispatch any added tasks ... */
        g_mutex_lock (m->format->priv->lock);
        while ((job = g_queue_pop_head (&m->format->priv->pending_jobs))) {
            g_mutex_unlock (m->format->priv->lock);

            /* This is an implicit check to see if the gtkhtml has been destroyed */
            if (m->format->priv->web_view == NULL)
                g_cancellable_cancel (cancellable);

            /* call jobs even if cancelled, so they can clean up resources */
            format->pending_uri_level = job->puri_level;
            if (job->base)
                format->base = job->base;
            job->callback (job, cancellable);
            format->base = base;

            /* clean up the job */
            g_object_unref (job->stream);
            if (job->base)
                camel_url_free (job->base);
            g_free (job);

            g_mutex_lock (m->format->priv->lock);
        }
        g_mutex_unlock (m->format->priv->lock);

        if (m->estream) {
            /* Closing this base stream can queue more jobs, so we need
             * to check the list again after we've finished */
            d(printf("out of jobs, closing root stream\n"));
            camel_stream_write_string (
                (CamelStream *) m->estream,
                "</body>\n</html>\n", cancellable, NULL);
            camel_stream_close ((CamelStream *) m->estream, cancellable, NULL);
            if (g_cancellable_is_cancelled (cancellable)) {
                m->cancelled = TRUE;
                m->estream->sync.cancel = TRUE;
            }
            g_object_unref (m->estream);
            m->estream = NULL;
        }

    } while (!g_queue_is_empty (&m->format->priv->pending_jobs));

    d(printf("out of jobs, done\n"));

    format->pending_uri_level = puri_level;
    m->cancelled = m->cancelled || g_cancellable_is_cancelled (cancellable);
}

static void
efh_format_done (struct _format_msg *m)
{
    d(printf("formatting finished\n"));

    m->format->priv->format_id = -1;
    m->format->priv->load_images_now = FALSE;
    m->format->state = EM_FORMAT_HTML_STATE_NONE;
    g_signal_emit_by_name(m->format, "complete");
}

static void
efh_format_free (struct _format_msg *m)
{
    d(printf("formatter freed\n"));
    g_object_unref (m->format);
    if (m->estream) {
        camel_stream_close ((CamelStream *) m->estream, NULL, NULL);
        if (m->cancelled)
            m->estream->sync.cancel = TRUE;
        g_object_unref (m->estream);
    }
    if (m->folder)
        g_object_unref (m->folder);
    g_free (m->uid);
    if (m->message)
        g_object_unref (m->message);
    if (m->format_source)
        g_object_unref (m->format_source);
}

static MailMsgInfo efh_format_info = {
    sizeof (struct _format_msg),
    (MailMsgDescFunc) efh_format_desc,
    (MailMsgExecFunc) efh_format_exec,
    (MailMsgDoneFunc) efh_format_done,
    (MailMsgFreeFunc) efh_format_free
};

static gboolean
efh_format_helper (struct _format_msg *m, gboolean async)
{
    GtkHTMLStream *hstream;
    EMFormatHTML *efh = m->format;
    struct _EMFormatHTMLPrivate *p = efh->priv;
    EWebView *web_view;

    web_view = em_format_html_get_web_view (m->format);

    if (web_view == NULL) {
        mail_msg_unref (m);
        return FALSE;
    }

    if (async) {
        d(printf("timeout called ...\n"));
        if (p->format_id != -1) {
            d(printf(" still waiting for cancellation to take effect, waiting ...\n"));
            return TRUE;
        }
    }

    g_return_val_if_fail (g_queue_is_empty (&p->pending_jobs), FALSE);

    d(printf(" ready to go, firing off format thread\n"));

    /* call super-class to kick it off */
    /* FIXME Not passing a GCancellable here. */
    EM_FORMAT_CLASS (parent_class)->format_clone (
        EM_FORMAT (efh), m->folder, m->uid,
        m->message, m->format_source, NULL);
    em_format_html_clear_pobject (m->format);

    /* FIXME: method off EMFormat? */
    if (((EMFormat *) efh)->valid) {
        camel_cipher_validity_free (((EMFormat *) efh)->valid);
        ((EMFormat *) efh)->valid = NULL;
        ((EMFormat *) efh)->valid_parent = NULL;
    }

    if (m->message == NULL) {
        hstream = gtk_html_begin (GTK_HTML (web_view));
        gtk_html_stream_close (hstream, GTK_HTML_STREAM_OK);
        mail_msg_unref (m);
        p->last_part = NULL;
    } else {
        efh->state = EM_FORMAT_HTML_STATE_RENDERING;
#if HAVE_CLUTTER
        if (p->last_part != m->message && !e_shell_get_express_mode (e_shell_get_default ())) {
#else
        if (p->last_part != m->message) {
#endif
            hstream = gtk_html_begin (GTK_HTML (web_view));
            gtk_html_stream_printf (hstream, "<h5>%s</h5>", _("Formatting Message..."));
            gtk_html_stream_close (hstream, GTK_HTML_STREAM_OK);
        }

        hstream = NULL;
        m->estream = (EMHTMLStream *) em_html_stream_new (
            GTK_HTML (web_view), hstream);

        if (p->last_part == m->message) {
            em_html_stream_set_flags (m->estream,
                          GTK_HTML_BEGIN_KEEP_SCROLL | GTK_HTML_BEGIN_KEEP_IMAGES
                          | GTK_HTML_BEGIN_BLOCK_UPDATES | GTK_HTML_BEGIN_BLOCK_IMAGES);
        } else {
            /* clear cache of inline-scanned text parts */
            g_hash_table_remove_all (p->text_inline_parts);

            p->last_part = m->message;
        }

        efh->priv->format_id = m->base.seq;

        if (async) {
            mail_msg_unordered_push (m);
        } else {
            efh_format_exec(m, NULL, NULL);
        }
    }

    efh->priv->format_timeout_id = 0;
    efh->priv->format_timeout_msg = NULL;

    return FALSE;
}

static void
efh_free_cache (struct _EMFormatHTMLCache *efhc)
{
    if (efhc->textmp)
        g_object_unref (efhc->textmp);
    g_free (efhc);
}

static void
efh_gtkhtml_destroy (GtkHTML *html,
                     EMFormatHTML *efh)
{
    if (efh->priv->format_timeout_id != 0) {
        g_source_remove (efh->priv->format_timeout_id);
        efh->priv->format_timeout_id = 0;
        mail_msg_unref (efh->priv->format_timeout_msg);
        efh->priv->format_timeout_msg = NULL;
    }

    /* This probably works ... */
    if (efh->priv->format_id != -1)
        mail_msg_cancel (efh->priv->format_id);

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

static struct _EMFormatHTMLCache *
efh_insert_cache (EMFormatHTML *efh,
                  const gchar *partid)
{
    struct _EMFormatHTMLCache *efhc;

    efhc = g_malloc0 (sizeof (*efh) + strlen (partid));
    strcpy (efhc->partid, partid);
    g_hash_table_insert (efh->priv->text_inline_parts, efhc->partid, efhc);

    return efhc;
}

static void
efh_set_property (GObject *object,
                  guint property_id,
                  const GValue *value,
                  GParamSpec *pspec)
{
    switch (property_id) {
        case PROP_BODY_COLOR:
            em_format_html_set_color (
                EM_FORMAT_HTML (object),
                EM_FORMAT_HTML_COLOR_BODY,
                g_value_get_boxed (value));
            return;

        case PROP_CITATION_COLOR:
            em_format_html_set_color (
                EM_FORMAT_HTML (object),
                EM_FORMAT_HTML_COLOR_CITATION,
                g_value_get_boxed (value));
            return;

        case PROP_CONTENT_COLOR:
            em_format_html_set_color (
                EM_FORMAT_HTML (object),
                EM_FORMAT_HTML_COLOR_CONTENT,
                g_value_get_boxed (value));
            return;

        case PROP_FRAME_COLOR:
            em_format_html_set_color (
                EM_FORMAT_HTML (object),
                EM_FORMAT_HTML_COLOR_FRAME,
                g_value_get_boxed (value));
            return;

        case PROP_HEADER_COLOR:
            em_format_html_set_color (
                EM_FORMAT_HTML (object),
                EM_FORMAT_HTML_COLOR_HEADER,
                g_value_get_boxed (value));
            return;

        case PROP_IMAGE_LOADING_POLICY:
            em_format_html_set_image_loading_policy (
                EM_FORMAT_HTML (object),
                g_value_get_enum (value));
            return;

        case PROP_MARK_CITATIONS:
            em_format_html_set_mark_citations (
                EM_FORMAT_HTML (object),
                g_value_get_boolean (value));
            return;

        case PROP_ONLY_LOCAL_PHOTOS:
            em_format_html_set_only_local_photos (
                EM_FORMAT_HTML (object),
                g_value_get_boolean (value));
            return;

        case PROP_SHOW_SENDER_PHOTO:
            em_format_html_set_show_sender_photo (
                EM_FORMAT_HTML (object),
                g_value_get_boolean (value));
            return;

        case PROP_SHOW_REAL_DATE:
            em_format_html_set_show_real_date (
                EM_FORMAT_HTML (object),
                g_value_get_boolean (value));
            return;

        case PROP_TEXT_COLOR:
            em_format_html_set_color (
                EM_FORMAT_HTML (object),
                EM_FORMAT_HTML_COLOR_TEXT,
                g_value_get_boxed (value));
            return;
        case PROP_HEADERS_STATE:
            em_format_html_set_headers_state (
                EM_FORMAT_HTML (object),
                g_value_get_int (value));
            return;
        case PROP_HEADERS_COLLAPSABLE:
            em_format_html_set_headers_collapsable (
                EM_FORMAT_HTML (object),
                g_value_get_boolean (value));
    }

    G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
}

static void
efh_get_property (GObject *object,
                  guint property_id,
                  GValue *value,
                  GParamSpec *pspec)
{
    GdkColor color;

    switch (property_id) {
        case PROP_BODY_COLOR:
            em_format_html_get_color (
                EM_FORMAT_HTML (object),
                EM_FORMAT_HTML_COLOR_BODY,
                &color);
            g_value_set_boxed (value, &color);
            return;

        case PROP_CITATION_COLOR:
            em_format_html_get_color (
                EM_FORMAT_HTML (object),
                EM_FORMAT_HTML_COLOR_CITATION,
                &color);
            g_value_set_boxed (value, &color);
            return;

        case PROP_CONTENT_COLOR:
            em_format_html_get_color (
                EM_FORMAT_HTML (object),
                EM_FORMAT_HTML_COLOR_CONTENT,
                &color);
            g_value_set_boxed (value, &color);
            return;

        case PROP_FRAME_COLOR:
            em_format_html_get_color (
                EM_FORMAT_HTML (object),
                EM_FORMAT_HTML_COLOR_FRAME,
                &color);
            g_value_set_boxed (value, &color);
            return;

        case PROP_HEADER_COLOR:
            em_format_html_get_color (
                EM_FORMAT_HTML (object),
                EM_FORMAT_HTML_COLOR_HEADER,
                &color);
            g_value_set_boxed (value, &color);
            return;

        case PROP_IMAGE_LOADING_POLICY:
            g_value_set_enum (
                value,
                em_format_html_get_image_loading_policy (
                EM_FORMAT_HTML (object)));
            return;

        case PROP_MARK_CITATIONS:
            g_value_set_boolean (
                value, em_format_html_get_mark_citations (
                EM_FORMAT_HTML (object)));
            return;

        case PROP_ONLY_LOCAL_PHOTOS:
            g_value_set_boolean (
                value, em_format_html_get_only_local_photos (
                EM_FORMAT_HTML (object)));
            return;

        case PROP_SHOW_SENDER_PHOTO:
            g_value_set_boolean (
                value, em_format_html_get_show_sender_photo (
                EM_FORMAT_HTML (object)));
            return;

        case PROP_SHOW_REAL_DATE:
            g_value_set_boolean (
                value, em_format_html_get_show_real_date (
                EM_FORMAT_HTML (object)));
            return;

        case PROP_TEXT_COLOR:
            em_format_html_get_color (
                EM_FORMAT_HTML (object),
                EM_FORMAT_HTML_COLOR_TEXT,
                &color);
            g_value_set_boxed (value, &color);
            return;

        case PROP_WEB_VIEW:
            g_value_set_object (
                value, em_format_html_get_web_view (
                EM_FORMAT_HTML (object)));
            return;
        case PROP_HEADERS_STATE:
            g_value_set_int (
                value, em_format_html_get_headers_state (
                EM_FORMAT_HTML (object)));
            return;
        case PROP_HEADERS_COLLAPSABLE:
            g_value_set_boolean (
                value, em_format_html_get_headers_collapsable (
                EM_FORMAT_HTML (object)));
    }

    G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
}

static void
efh_finalize (GObject *object)
{
    EMFormatHTML *efh = EM_FORMAT_HTML (object);

    em_format_html_clear_pobject (efh);
    efh_gtkhtml_destroy (GTK_HTML (efh->priv->web_view), efh);

    g_hash_table_destroy (efh->priv->text_inline_parts);

    g_mutex_free (efh->priv->lock);

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

static gboolean
efh_format_timeout (struct _format_msg *m)
{
    return efh_format_helper (m, TRUE);
}

void
em_format_html_clone_sync (CamelFolder *folder,
                           const gchar *uid,
                           CamelMimeMessage *msg,
                           EMFormatHTML *efh,
                           EMFormat *source)
{
    struct _format_msg *m;

    m = mail_msg_new (&efh_format_info);
    m->format = g_object_ref (efh);
    if (source)
        m->format_source = g_object_ref (source);
    m->folder = g_object_ref (folder);
    m->uid = g_strdup (uid);
    m->message = g_object_ref (msg);

    efh_format_helper (m, FALSE);
    efh_format_free (m);
}

static void
efh_format_clone (EMFormat *emf,
                  CamelFolder *folder,
                  const gchar *uid,
                  CamelMimeMessage *msg,
                  EMFormat *emfsource,
                  GCancellable *cancellable)
{
    EMFormatHTML *efh = EM_FORMAT_HTML (emf);
    struct _format_msg *m;

    /* How to sub-class ?  Might need to adjust api ... */

    if (efh->priv->web_view == NULL)
        return;

    d(printf("efh_format called\n"));
    if (efh->priv->format_timeout_id != 0) {
        d(printf(" timeout for last still active, removing ...\n"));
        g_source_remove (efh->priv->format_timeout_id);
        efh->priv->format_timeout_id = 0;
        mail_msg_unref (efh->priv->format_timeout_msg);
        efh->priv->format_timeout_msg = NULL;
    }

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

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

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

    m = mail_msg_new (&efh_format_info);
    m->format = g_object_ref (emf);
    m->format_source = emfsource;
    m->folder = folder;
    m->uid = g_strdup (uid);
    m->message = msg;

    if (efh->priv->format_id == -1) {
        d(printf(" idle, forcing format\n"));
        efh_format_timeout (m);
    } else {
        d(printf(" still busy, cancelling and queuing wait\n"));
        /* cancel and poll for completion */
        mail_msg_cancel (efh->priv->format_id);
        efh->priv->format_timeout_msg = m;
        efh->priv->format_timeout_id = g_timeout_add (
            100, (GSourceFunc) efh_format_timeout, m);
    }
}

static void
efh_format_error (EMFormat *emf,
                  CamelStream *stream,
                  const gchar *txt)
{
    GString *buffer;
    gchar *html;

    buffer = g_string_new ("<em><font color=\"red\">");

    html = camel_text_to_html (
        txt, CAMEL_MIME_FILTER_TOHTML_CONVERT_NL |
        CAMEL_MIME_FILTER_TOHTML_CONVERT_URLS, 0);
    g_string_append (buffer, html);
    g_free (html);

    g_string_append (buffer, "</font></em><br>");

    camel_stream_write (stream, buffer->str, buffer->len, NULL, NULL);

    g_string_free (buffer, TRUE);
}

static void
efh_format_source (EMFormat *emf,
                   CamelStream *stream,
                   CamelMimePart *part,
                   GCancellable *cancellable)
{
    CamelStream *filtered_stream;
    CamelMimeFilter *filter;
    CamelDataWrapper *dw = (CamelDataWrapper *) part;

    filtered_stream = camel_stream_filter_new (stream);

    filter = camel_mime_filter_tohtml_new (
        CAMEL_MIME_FILTER_TOHTML_CONVERT_NL |
        CAMEL_MIME_FILTER_TOHTML_CONVERT_SPACES |
        CAMEL_MIME_FILTER_TOHTML_PRESERVE_8BIT, 0);
    camel_stream_filter_add (
        CAMEL_STREAM_FILTER (filtered_stream), filter);
    g_object_unref (filter);

    camel_stream_write_string (
        stream, "<table><tr><td><tt>", cancellable, NULL);
    em_format_format_text (emf, filtered_stream, dw, cancellable);
    camel_stream_write_string (
        stream, "</tt></td></tr></table>", cancellable, NULL);

    g_object_unref (filtered_stream);
}

static void
efh_format_attachment (EMFormat *emf,
                       CamelStream *stream,
                       CamelMimePart *part,
                       const gchar *mime_type,
                       const EMFormatHandler *handle,
                       GCancellable *cancellable)
{
    gchar *text, *html;

    /* we display all inlined attachments only */

    /* this could probably be cleaned up ... */
    camel_stream_write_string (
        stream,
        "<table border=1 cellspacing=0 cellpadding=0><tr><td>"
        "<table width=10 cellspacing=0 cellpadding=0>"
        "<tr><td></td></tr></table></td>"
        "<td><table width=3 cellspacing=0 cellpadding=0>"
        "<tr><td></td></tr></table></td><td><font size=-1>\n",
        cancellable, NULL);

    /* output some info about it */
    text = em_format_describe_part (part, mime_type);
    html = camel_text_to_html (
        text, ((EMFormatHTML *) emf)->text_html_flags &
        CAMEL_MIME_FILTER_TOHTML_CONVERT_URLS, 0);
    camel_stream_write_string (stream, html, cancellable, NULL);
    g_free (html);
    g_free (text);

    camel_stream_write_string (
        stream, "</font></td></tr><tr></table>", cancellable, NULL);

    if (handle && em_format_is_inline (emf, emf->part_id->str, part, handle))
        handle->handler (emf, stream, part, handle, cancellable, FALSE);
}

static gboolean
efh_busy (EMFormat *emf)
{
    EMFormatHTMLPrivate *priv;

    priv = EM_FORMAT_HTML_GET_PRIVATE (emf);

    return (priv->format_id != -1);
}
static void
efh_base_init (EMFormatHTMLClass *class)
{
    efh_builtin_init (class);
}

static void
efh_class_init (EMFormatHTMLClass *class)
{
    GObjectClass *object_class;
    EMFormatClass *format_class;
    const gchar *user_cache_dir;

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

    object_class = G_OBJECT_CLASS (class);
    object_class->set_property = efh_set_property;
    object_class->get_property = efh_get_property;
    object_class->finalize = efh_finalize;

    format_class = EM_FORMAT_CLASS (class);
    format_class->format_clone = efh_format_clone;
    format_class->format_error = efh_format_error;
    format_class->format_source = efh_format_source;
    format_class->format_attachment = efh_format_attachment;
    format_class->format_secure = efh_format_secure;
    format_class->busy = efh_busy;

    class->html_widget_type = E_TYPE_WEB_VIEW;

    g_object_class_install_property (
        object_class,
        PROP_BODY_COLOR,
        g_param_spec_boxed (
            "body-color",
            "Body Color",
            NULL,
            GDK_TYPE_COLOR,
            G_PARAM_READWRITE));

    g_object_class_install_property (
        object_class,
        PROP_CITATION_COLOR,
        g_param_spec_boxed (
            "citation-color",
            "Citation Color",
            NULL,
            GDK_TYPE_COLOR,
            G_PARAM_READWRITE));

    g_object_class_install_property (
        object_class,
        PROP_CONTENT_COLOR,
        g_param_spec_boxed (
            "content-color",
            "Content Color",
            NULL,
            GDK_TYPE_COLOR,
            G_PARAM_READWRITE));

    g_object_class_install_property (
        object_class,
        PROP_FRAME_COLOR,
        g_param_spec_boxed (
            "frame-color",
            "Frame Color",
            NULL,
            GDK_TYPE_COLOR,
            G_PARAM_READWRITE));

    g_object_class_install_property (
        object_class,
        PROP_HEADER_COLOR,
        g_param_spec_boxed (
            "header-color",
            "Header Color",
            NULL,
            GDK_TYPE_COLOR,
            G_PARAM_READWRITE));

    /* FIXME Make this a proper enum property. */
    g_object_class_install_property (
        object_class,
        PROP_IMAGE_LOADING_POLICY,
        g_param_spec_enum (
            "image-loading-policy",
            "Image Loading Policy",
            NULL,
            E_TYPE_MAIL_IMAGE_LOADING_POLICY,
            E_MAIL_IMAGE_LOADING_POLICY_ALWAYS,
            G_PARAM_READWRITE));

    g_object_class_install_property (
        object_class,
        PROP_MARK_CITATIONS,
        g_param_spec_boolean (
            "mark-citations",
            "Mark Citations",
            NULL,
            TRUE,
            G_PARAM_READWRITE));

    g_object_class_install_property (
        object_class,
        PROP_ONLY_LOCAL_PHOTOS,
        g_param_spec_boolean (
            "only-local-photos",
            "Only Local Photos",
            NULL,
            TRUE,
            G_PARAM_READWRITE |
            G_PARAM_CONSTRUCT));

    g_object_class_install_property (
        object_class,
        PROP_SHOW_SENDER_PHOTO,
        g_param_spec_boolean (
            "show-sender-photo",
            "Show Sender Photo",
            NULL,
            TRUE,
            G_PARAM_READWRITE |
            G_PARAM_CONSTRUCT));

    g_object_class_install_property (
        object_class,
        PROP_SHOW_REAL_DATE,
        g_param_spec_boolean (
            "show-real-date",
            "Show real Date header value",
            NULL,
            TRUE,
            G_PARAM_READWRITE |
            G_PARAM_CONSTRUCT));

    g_object_class_install_property (
        object_class,
        PROP_TEXT_COLOR,
        g_param_spec_boxed (
            "text-color",
            "Text Color",
            NULL,
            GDK_TYPE_COLOR,
            G_PARAM_READWRITE));

    g_object_class_install_property (
        object_class,
        PROP_WEB_VIEW,
        g_param_spec_object (
            "web-view",
            "Web View",
            NULL,
            E_TYPE_WEB_VIEW,
            G_PARAM_READABLE));

    g_object_class_install_property (
        object_class,
        PROP_HEADERS_STATE,
        g_param_spec_int (
            "headers-state",
            "Headers state",
            NULL,
            EM_FORMAT_HTML_HEADERS_STATE_EXPANDED,
            EM_FORMAT_HTML_HEADERS_STATE_COLLAPSED,
            EM_FORMAT_HTML_HEADERS_STATE_EXPANDED,
            G_PARAM_READWRITE));

    g_object_class_install_property (
        object_class,
        PROP_HEADERS_STATE,
        g_param_spec_boolean (
            "headers-collapsable",
            NULL,
            NULL,
            FALSE,
            G_PARAM_READWRITE));

    /* cache expiry - 2 hour access, 1 day max */
    user_cache_dir = e_get_user_cache_dir ();
    emfh_http_cache = camel_data_cache_new (user_cache_dir, NULL);
    if (emfh_http_cache) {
        camel_data_cache_set_expire_age (emfh_http_cache, 24 *60 *60);
        camel_data_cache_set_expire_access (emfh_http_cache, 2 *60 *60);
    }
}

static void
efh_init (EMFormatHTML *efh,
          EMFormatHTMLClass *class)
{
    EWebView *web_view;
    GdkColor *color;

    efh->priv = EM_FORMAT_HTML_GET_PRIVATE (efh);

    g_queue_init (&efh->pending_object_list);
    g_queue_init (&efh->priv->pending_jobs);
    efh->priv->lock = g_mutex_new ();
    efh->priv->format_id = -1;
    efh->priv->text_inline_parts = g_hash_table_new_full (
        g_str_hash, g_str_equal,
        (GDestroyNotify) NULL,
        (GDestroyNotify) efh_free_cache);

    web_view = g_object_new (class->html_widget_type, NULL);
    efh->priv->web_view = g_object_ref_sink (web_view);

    gtk_html_set_blocking (GTK_HTML (web_view), FALSE);
    gtk_html_set_caret_first_focus_anchor (
        GTK_HTML (web_view), EFM_MESSAGE_START_ANAME);
    gtk_html_set_default_content_type (
        GTK_HTML (web_view), "text/html; charset=utf-8");
    e_web_view_set_editable (web_view, FALSE);

    g_signal_connect (
        web_view, "url-requested",
        G_CALLBACK (efh_url_requested), efh);
    g_signal_connect (
        web_view, "object-requested",
        G_CALLBACK (efh_object_requested), efh);

    color = &efh->priv->colors[EM_FORMAT_HTML_COLOR_BODY];
    gdk_color_parse ("#eeeeee", color);

    color = &efh->priv->colors[EM_FORMAT_HTML_COLOR_CONTENT];
    gdk_color_parse ("#ffffff", color);

    color = &efh->priv->colors[EM_FORMAT_HTML_COLOR_FRAME];
    gdk_color_parse ("#3f3f3f", color);

    color = &efh->priv->colors[EM_FORMAT_HTML_COLOR_HEADER];
    gdk_color_parse ("#eeeeee", color);

    color = &efh->priv->colors[EM_FORMAT_HTML_COLOR_TEXT];
    gdk_color_parse ("#000000", color);

    efh->text_html_flags =
        CAMEL_MIME_FILTER_TOHTML_CONVERT_NL |
        CAMEL_MIME_FILTER_TOHTML_CONVERT_SPACES |
        CAMEL_MIME_FILTER_TOHTML_MARK_CITATION;
    efh->show_icon = TRUE;
    efh->state = EM_FORMAT_HTML_STATE_NONE;

    g_signal_connect_swapped (
        efh, "notify::mark-citations",
        G_CALLBACK (em_format_queue_redraw), NULL);

    e_extensible_load_extensions (E_EXTENSIBLE (efh));
}

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

    if (G_UNLIKELY (type == 0)) {
        static const GTypeInfo type_info = {
            sizeof (EMFormatHTMLClass),
            (GBaseInitFunc) efh_base_init,
            (GBaseFinalizeFunc) NULL,
            (GClassInitFunc) efh_class_init,
            (GClassFinalizeFunc) NULL,
            NULL,  /* class_data */
            sizeof (EMFormatHTML),
            0,     /* n_preallocs */
            (GInstanceInitFunc) efh_init,
            NULL   /* value_table */
        };

        static const GInterfaceInfo extensible_info = {
            (GInterfaceInitFunc) NULL,
            (GInterfaceFinalizeFunc) NULL,
            NULL   /* interface_data */
        };

        type = g_type_register_static (
            em_format_get_type(), "EMFormatHTML",
            &type_info, G_TYPE_FLAG_ABSTRACT);

        g_type_add_interface_static (
            type, E_TYPE_EXTENSIBLE, &extensible_info);
    }

    return type;
}

EWebView *
em_format_html_get_web_view (EMFormatHTML *efh)
{
    g_return_val_if_fail (EM_IS_FORMAT_HTML (efh), NULL);

    return efh->priv->web_view;
}

void
em_format_html_load_images (EMFormatHTML *efh)
{
    g_return_if_fail (EM_IS_FORMAT_HTML (efh));

    if (efh->priv->image_loading_policy == E_MAIL_IMAGE_LOADING_POLICY_ALWAYS)
        return;

    /* This will remain set while we're still
     * rendering the same message, then it wont be. */
    efh->priv->load_images_now = TRUE;
    em_format_queue_redraw (EM_FORMAT (efh));
}

void
em_format_html_get_color (EMFormatHTML *efh,
                          EMFormatHTMLColorType type,
                          GdkColor *color)
{
    GdkColor *format_color;

    g_return_if_fail (EM_IS_FORMAT_HTML (efh));
    g_return_if_fail (type < EM_FORMAT_HTML_NUM_COLOR_TYPES);
    g_return_if_fail (color != NULL);

    format_color = &efh->priv->colors[type];

    color->red   = format_color->red;
    color->green = format_color->green;
    color->blue  = format_color->blue;
}

void
em_format_html_set_color (EMFormatHTML *efh,
                          EMFormatHTMLColorType type,
                          const GdkColor *color)
{
    GdkColor *format_color;
    const gchar *property_name;

    g_return_if_fail (EM_IS_FORMAT_HTML (efh));
    g_return_if_fail (type < EM_FORMAT_HTML_NUM_COLOR_TYPES);
    g_return_if_fail (color != NULL);

    format_color = &efh->priv->colors[type];

    if (gdk_color_equal (color, format_color))
        return;

    format_color->red   = color->red;
    format_color->green = color->green;
    format_color->blue  = color->blue;

    switch (type) {
        case EM_FORMAT_HTML_COLOR_BODY:
            property_name = "body-color";
            break;
        case EM_FORMAT_HTML_COLOR_CITATION:
            property_name = "citation-color";
            break;
        case EM_FORMAT_HTML_COLOR_CONTENT:
            property_name = "content-color";
            break;
        case EM_FORMAT_HTML_COLOR_FRAME:
            property_name = "frame-color";
            break;
        case EM_FORMAT_HTML_COLOR_HEADER:
            property_name = "header-color";
            break;
        case EM_FORMAT_HTML_COLOR_TEXT:
            property_name = "text-color";
            break;
        default:
            g_return_if_reached ();
    }

    g_object_notify (G_OBJECT (efh), property_name);
}

EMailImageLoadingPolicy
em_format_html_get_image_loading_policy (EMFormatHTML *efh)
{
    g_return_val_if_fail (EM_IS_FORMAT_HTML (efh), 0);

    return efh->priv->image_loading_policy;
}

void
em_format_html_set_image_loading_policy (EMFormatHTML *efh,
                                         EMailImageLoadingPolicy policy)
{
    g_return_if_fail (EM_IS_FORMAT_HTML (efh));

    if (policy == efh->priv->image_loading_policy)
        return;

    efh->priv->image_loading_policy = policy;

    g_object_notify (G_OBJECT (efh), "image-loading-policy");
}

gboolean
em_format_html_get_mark_citations (EMFormatHTML *efh)
{
    guint32 flags;

    g_return_val_if_fail (EM_IS_FORMAT_HTML (efh), FALSE);

    flags = efh->text_html_flags;

    return ((flags & CAMEL_MIME_FILTER_TOHTML_MARK_CITATION) != 0);
}

void
em_format_html_set_mark_citations (EMFormatHTML *efh,
                                   gboolean mark_citations)
{
    g_return_if_fail (EM_IS_FORMAT_HTML (efh));

    if (mark_citations)
        efh->text_html_flags |=
            CAMEL_MIME_FILTER_TOHTML_MARK_CITATION;
        efh->text_html_flags &=
            ~CAMEL_MIME_FILTER_TOHTML_MARK_CITATION;

    g_object_notify (G_OBJECT (efh), "mark-citations");
}

gboolean
em_format_html_get_only_local_photos (EMFormatHTML *efh)
{
    g_return_val_if_fail (EM_IS_FORMAT_HTML (efh), FALSE);

    return efh->priv->only_local_photos;
}

void
em_format_html_set_only_local_photos (EMFormatHTML *efh,
                                      gboolean only_local_photos)
{
    g_return_if_fail (EM_IS_FORMAT_HTML (efh));

    efh->priv->only_local_photos = only_local_photos;

    g_object_notify (G_OBJECT (efh), "only-local-photos");
}

gboolean
em_format_html_get_show_sender_photo (EMFormatHTML *efh)
{
    g_return_val_if_fail (EM_IS_FORMAT_HTML (efh), FALSE);

    return efh->priv->show_sender_photo;
}

void
em_format_html_set_show_sender_photo (EMFormatHTML *efh,
                                      gboolean show_sender_photo)
{
    g_return_if_fail (EM_IS_FORMAT_HTML (efh));

    efh->priv->show_sender_photo = show_sender_photo;

    g_object_notify (G_OBJECT (efh), "show-sender-photo");
}

gboolean
em_format_html_get_show_real_date (EMFormatHTML *efh)
{
    g_return_val_if_fail (EM_IS_FORMAT_HTML (efh), FALSE);

    return efh->priv->show_real_date;
}

void
em_format_html_set_show_real_date (EMFormatHTML *efh,
                                   gboolean show_real_date)
{
    g_return_if_fail (EM_IS_FORMAT_HTML (efh));

    efh->priv->show_real_date = show_real_date;

    g_object_notify (G_OBJECT (efh), "show-real-date");
}

EMFormatHTMLHeadersState
em_format_html_get_headers_state (EMFormatHTML *efh)
{
    g_return_val_if_fail (EM_IS_FORMAT_HTML (efh), EM_FORMAT_HTML_HEADERS_STATE_EXPANDED);

    return efh->priv->headers_state;
}

void
em_format_html_set_headers_state (EMFormatHTML *efh,
                                  EMFormatHTMLHeadersState state)
{
    g_return_if_fail (EM_IS_FORMAT_HTML (efh));

    efh->priv->headers_state = state;

    g_object_notify (G_OBJECT (efh), "headers-state");
}

gboolean
em_format_html_get_headers_collapsable (EMFormatHTML *efh)
{
    g_return_val_if_fail (EM_IS_FORMAT_HTML (efh), FALSE);

    return efh->priv->headers_collapsable;
}

void
em_format_html_set_headers_collapsable (EMFormatHTML *efh,
                                        gboolean collapsable)
{
    g_return_if_fail (EM_IS_FORMAT_HTML (efh));

    efh->priv->headers_collapsable = collapsable;

    g_object_notify (G_OBJECT (efh), "headers-collapsable");
}

CamelMimePart *
em_format_html_file_part (EMFormatHTML *efh,
                          const gchar *mime_type,
                          const gchar *filename,
                          GCancellable *cancellable)
{
    CamelMimePart *part;
    CamelStream *stream;
    CamelDataWrapper *dw;
    gchar *basename;

    stream = camel_stream_fs_new_with_name (filename, O_RDONLY, 0, NULL);
    if (stream == NULL)
        return NULL;

    dw = camel_data_wrapper_new ();
    camel_data_wrapper_construct_from_stream_sync (
        dw, stream, cancellable, NULL);
    g_object_unref (stream);
    if (mime_type)
        camel_data_wrapper_set_mime_type (dw, mime_type);
    part = camel_mime_part_new ();
    camel_medium_set_content ((CamelMedium *) part, dw);
    g_object_unref (dw);
    basename = g_path_get_basename (filename);
    camel_mime_part_set_filename (part, basename);
    g_free (basename);

    return part;
}

/* all this api is a pain in the bum ... */

EMFormatHTMLPObject *
em_format_html_add_pobject (EMFormatHTML *efh,
                            gsize size,
                            const gchar *classid,
                            CamelMimePart *part,
                            EMFormatHTMLPObjectFunc func)
{
    EMFormatHTMLPObject *pobj;

    if (size < sizeof (EMFormatHTMLPObject)) {
        g_warning ("size is less than the size of EMFormatHTMLPObject\n");
        size = sizeof (EMFormatHTMLPObject);
    }

    pobj = g_malloc0 (size);
    if (classid)
        pobj->classid = g_strdup (classid);
    else
        pobj->classid = g_strdup_printf("e-object:///%s", ((EMFormat *)efh)->part_id->str);

    pobj->format = efh;
    pobj->func = func;
    pobj->part = part;

    g_queue_push_tail (&efh->pending_object_list, pobj);

    return pobj;
}

EMFormatHTMLPObject *
em_format_html_find_pobject (EMFormatHTML *emf,
                             const gchar *classid)
{
    GList *link;

    g_return_val_if_fail (EM_IS_FORMAT_HTML (emf), NULL);
    g_return_val_if_fail (classid != NULL, NULL);

    link = g_queue_peek_head_link (&emf->pending_object_list);

    while (link != NULL) {
        EMFormatHTMLPObject *pw = link->data;

        if (!strcmp (pw->classid, classid))
            return pw;

        link = g_list_next (link);
    }

    return NULL;
}

EMFormatHTMLPObject *
em_format_html_find_pobject_func (EMFormatHTML *emf,
                                  CamelMimePart *part,
                                  EMFormatHTMLPObjectFunc func)
{
    GList *link;

    g_return_val_if_fail (EM_IS_FORMAT_HTML (emf), NULL);

    link = g_queue_peek_head_link (&emf->pending_object_list);

    while (link != NULL) {
        EMFormatHTMLPObject *pw = link->data;

        if (pw->func == func && pw->part == part)
            return pw;

        link = g_list_next (link);
    }

    return NULL;
}

void
em_format_html_remove_pobject (EMFormatHTML *emf,
                               EMFormatHTMLPObject *pobject)
{
    g_return_if_fail (EM_IS_FORMAT_HTML (emf));
    g_return_if_fail (pobject != NULL);

    g_queue_remove (&emf->pending_object_list, pobject);

    if (pobject->free != NULL)
        pobject->free (pobject);

    g_free (pobject->classid);
    g_free (pobject);
}

void
em_format_html_clear_pobject (EMFormatHTML *emf)
{
    g_return_if_fail (EM_IS_FORMAT_HTML (emf));

    while (!g_queue_is_empty (&emf->pending_object_list)) {
        EMFormatHTMLPObject *pobj;

        pobj = g_queue_pop_head (&emf->pending_object_list);
        em_format_html_remove_pobject (emf, pobj);
    }
}

struct _EMFormatHTMLJob *
em_format_html_job_new (EMFormatHTML *emfh,
                        void (*callback) (struct _EMFormatHTMLJob *job,
                                          GCancellable *cancellable),
                        gpointer data)
{
    struct _EMFormatHTMLJob *job = g_malloc0 (sizeof (*job));

    job->format = emfh;
    job->puri_level = ((EMFormat *) emfh)->pending_uri_level;
    job->callback = callback;
    job->u.data = data;
    if (((EMFormat *) emfh)->base)
        job->base = camel_url_copy (((EMFormat *) emfh)->base);

    return job;
}

void
em_format_html_job_queue (EMFormatHTML *emfh,
                          struct _EMFormatHTMLJob *job)
{
    g_mutex_lock (emfh->priv->lock);
    g_queue_push_tail (&emfh->priv->pending_jobs, job);
    g_mutex_unlock (emfh->priv->lock);
}

/* ********************************************************************** */

static void
emfh_getpuri (struct _EMFormatHTMLJob *job,
              GCancellable *cancellable)
{
    d(printf(" running getpuri task\n"));
    if (!g_cancellable_is_cancelled (cancellable))
        job->u.puri->func (
            EM_FORMAT (job->format), job->stream,
            job->u.puri, cancellable);
}

static void
emfh_configure_stream_for_proxy (CamelHttpStream *stream,
                                 const gchar *uri)
{
    EProxy *proxy;
    SoupURI *proxy_uri;
    gchar *basic;
    gchar *basic64;
    const gchar *user = "";
    const gchar *password = "";

    proxy = em_utils_get_proxy ();

    if (!e_proxy_require_proxy_for_uri (proxy, uri))
        return;

    proxy_uri = e_proxy_peek_uri_for (proxy, uri);

    if (proxy_uri == NULL)
        return;

    if (proxy_uri->user != NULL)
        user = proxy_uri->user;

    if (proxy_uri->password != NULL)
        password = proxy_uri->password;

    if (*user == '\0' && *password == '\0')
        return;

    basic = g_strdup_printf ("%s:%s", user, password);
    basic64 = g_base64_encode ((guchar *) basic, strlen (basic));
    camel_http_stream_set_proxy_authpass (stream, basic64);
    g_free (basic64);
    g_free (basic);
}

static void
emfh_gethttp (struct _EMFormatHTMLJob *job,
              GCancellable *cancellable)
{
    CamelStream *cistream = NULL, *costream = NULL, *instream = NULL;
    CamelURL *url;
    CamelContentType *content_type;
    CamelHttpStream *tmp_stream;
    gssize n, total = 0, pc_complete = 0, nread = 0;
    gchar buffer[1500];
    const gchar *length;

    if (g_cancellable_is_cancelled (cancellable)
        || (url = camel_url_new (job->u.uri, NULL)) == NULL)
        goto badurl;

    d(printf(" running load uri task: %s\n", job->u.uri));

    if (emfh_http_cache)
        instream = cistream = camel_data_cache_get (emfh_http_cache, EMFH_HTTP_CACHE_PATH, job->u.uri, NULL);

    if (instream == NULL) {
        EMailImageLoadingPolicy policy;

        policy = em_format_html_get_image_loading_policy (job->format);

        if (!(job->format->priv->load_images_now
              || policy == E_MAIL_IMAGE_LOADING_POLICY_ALWAYS
              || (policy == E_MAIL_IMAGE_LOADING_POLICY_SOMETIMES
              && em_utils_in_addressbook ((CamelInternetAddress *) camel_mime_message_get_from (job->format->parent.message), FALSE)))) {
            /* TODO: Ideally we would put the http requests into
             * another queue and only send them out if the user
             * selects 'load images', when they do.  The problem
             * is how to maintain this state with multiple
             * renderings, and how to adjust the thread
             * dispatch/setup routine to handle it */
            camel_url_free (url);
            goto done;
        }

        instream = camel_http_stream_new (CAMEL_HTTP_METHOD_GET, ((EMFormat *) job->format)->session, url);
        camel_http_stream_set_user_agent((CamelHttpStream *) instream, "CamelHttpStream/1.0 Evolution/" VERSION);
        emfh_configure_stream_for_proxy ((CamelHttpStream *) instream, job->u.uri);

        camel_operation_push_message (
            cancellable, _("Retrieving '%s'"), job->u.uri);
        tmp_stream = (CamelHttpStream *) instream;
        content_type = camel_http_stream_get_content_type (tmp_stream);
        length = camel_header_raw_find(&tmp_stream->headers, "Content-Length", NULL);
        d(printf("  Content-Length: %s\n", length));
        if (length != NULL)
            total = atoi (length);
        camel_content_type_unref (content_type);
    } else
        camel_operation_push_message (
            cancellable, _("Retrieving '%s'"), job->u.uri);

    camel_url_free (url);

    if (instream == NULL)
        goto done;

    if (emfh_http_cache != NULL && cistream == NULL)
        costream = camel_data_cache_add (emfh_http_cache, EMFH_HTTP_CACHE_PATH, job->u.uri, NULL);

    do {
        if (g_cancellable_is_cancelled (cancellable)) {
            n = -1;
            break;
        }
        /* FIXME: progress reporting in percentage, can we get the length always?  do we care? */
        n = camel_stream_read (instream, buffer, sizeof (buffer), cancellable, NULL);
        if (n > 0) {
            nread += n;
            /* If we didn't get a valid Content-Length header, do not try to calculate percentage */
            if (total != 0) {
                pc_complete = ((nread * 100) / total);
                camel_operation_progress (cancellable, pc_complete);
            }
            d(printf("  read %d bytes\n", n));
            if (costream && camel_stream_write (costream, buffer, n, cancellable, NULL) == -1) {
                n = -1;
                break;
            }

            camel_stream_write (job->stream, buffer, n, cancellable, NULL);
        }
    } while (n > 0);

    /* indicates success */
    if (n == 0)
        camel_stream_close (job->stream, cancellable, NULL);

    if (costream) {
        /* do not store broken files in a cache */
        if (n != 0)
            camel_data_cache_remove (emfh_http_cache, EMFH_HTTP_CACHE_PATH, job->u.uri, NULL);
        g_object_unref (costream);
    }

    g_object_unref (instream);
done:
    camel_operation_pop_message (cancellable);
badurl:
    g_free (job->u.uri);
}

/* ********************************************************************** */

static void
efh_url_requested (GtkHTML *html,
                   const gchar *url,
                   GtkHTMLStream *handle,
                   EMFormatHTML *efh)
{
    EMFormatPURI *puri;
    struct _EMFormatHTMLJob *job = NULL;

    d(printf("url requested, html = %p, url '%s'\n", html, url));

    puri = em_format_find_visible_puri ((EMFormat *) efh, url);
    if (puri) {
        CamelDataWrapper *dw = camel_medium_get_content ((CamelMedium *) puri->part);
        CamelContentType *ct = dw ? dw->mime_type : NULL;

        /* GtkHTML only handles text and images.
         * application/octet-stream parts are the only ones
         * which are snooped for other content.  So only try
         * to pass these to it - any other types are badly
         * formed or intentionally malicious emails.  They
         * will still show as attachments anyway */

        if (ct && (camel_content_type_is(ct, "text", "*")
               || camel_content_type_is(ct, "image", "*")
               || camel_content_type_is(ct, "application", "octet-stream"))) {
            puri->use_count++;

            d(printf(" adding puri job\n"));
            job = em_format_html_job_new (efh, emfh_getpuri, puri);
        } else {
            d(printf(" part is unknown type '%s', not using\n", ct?camel_content_type_format(ct):"<unset>"));
            gtk_html_stream_close (handle, GTK_HTML_STREAM_ERROR);
        }
    } else if (g_ascii_strncasecmp(url, "http:", 5) == 0 || g_ascii_strncasecmp(url, "https:", 6) == 0) {
        d(printf(" adding job, get %s\n", url));
        job = em_format_html_job_new (efh, emfh_gethttp, g_strdup (url));
    } else if  (g_str_has_prefix (url, "file://")) {
        gchar *data = NULL;
        gsize length = 0;
        gboolean status;
        gchar *path;

        path = g_filename_from_uri (url, NULL, NULL);
        g_return_if_fail (path != NULL);

        status = g_file_get_contents (path, &data, &length, NULL);
        if (status)
            gtk_html_stream_write (handle, data, length);

        gtk_html_stream_close (handle, status ? GTK_HTML_STREAM_OK : GTK_HTML_STREAM_ERROR);
        g_free (data);
        g_free (path);
    } else {
        d(printf("HTML Includes reference to unknown uri '%s'\n", url));
        gtk_html_stream_close (handle, GTK_HTML_STREAM_ERROR);
    }

    if (job) {
        job->stream = em_html_stream_new (html, handle);
        em_format_html_job_queue (efh, job);
    }

    g_signal_stop_emission_by_name (html, "url-requested");
}

static gboolean
efh_object_requested (GtkHTML *html,
                      GtkHTMLEmbedded *eb,
                      EMFormatHTML *efh)
{
    EMFormatHTMLPObject *pobject;
    gint res = FALSE;

    if (eb->classid == NULL)
        return FALSE;

    pobject = em_format_html_find_pobject (efh, eb->classid);
    if (pobject) {
        /* This stops recursion of the part */
        g_queue_remove (&efh->pending_object_list, pobject);
        res = pobject->func (efh, eb, pobject);
        g_queue_push_head (&efh->pending_object_list, pobject);
    } else {
        d(printf("HTML Includes reference to unknown object '%s'\n", eb->classid));
    }

    return res;
}

/* ********************************************************************** */
#include "em-format/em-inline-filter.h"

/* FIXME: This is duplicated in em-format-html-display, should be exported or in security module */
static const struct {
    const gchar *icon, *shortdesc;
} smime_sign_table[5] = {
    { "stock_signature-bad", N_("Unsigned") },
    { "stock_signature-ok", N_("Valid signature") },
    { "stock_signature-bad", N_("Invalid signature") },
    { "stock_signature", N_("Valid signature, but cannot verify sender") },
    { "stock_signature-bad", N_("Signature exists, but need public key") },
};

static const struct {
    const gchar *icon, *shortdesc;
} smime_encrypt_table[4] = {
    { "stock_lock-broken", N_("Unencrypted") },
    { "stock_lock", N_("Encrypted, weak"),},
    { "stock_lock-ok", N_("Encrypted") },
    { "stock_lock-ok", N_("Encrypted, strong") },
};

static const gchar *smime_sign_colour[4] = {
    "", " bgcolor=\"#88bb88\"", " bgcolor=\"#bb8888\"", " bgcolor=\"#e8d122\""
};

/* TODO: this could probably be virtual on em-format-html
 * then we only need one version of each type handler */
static void
efh_format_secure (EMFormat *emf,
                   CamelStream *stream,
                   CamelMimePart *part,
                   CamelCipherValidity *valid,
                   GCancellable *cancellable)
{
    EMFormatClass *format_class;

    format_class = EM_FORMAT_CLASS (parent_class);
    g_return_if_fail (format_class->format_secure != NULL);
    format_class->format_secure (emf, stream, part, valid, cancellable);

    /* To explain, if the validity is the same, then we are the
     * base validity and now have a combined sign/encrypt validity
     * we can display.  Primarily a new verification context is
     * created when we have an embeded message. */
    if (emf->valid == valid
        && (valid->encrypt.status != CAMEL_CIPHER_VALIDITY_ENCRYPT_NONE
        || valid->sign.status != CAMEL_CIPHER_VALIDITY_SIGN_NONE)) {
        gchar *classid, *iconpath;
        const gchar *icon;
        CamelMimePart *iconpart;
        GString *buffer;

        buffer = g_string_sized_new (1024);

        g_string_append_printf (
            buffer,
            "<table border=0 width=\"100%%\" "
            "cellpadding=3 cellspacing=0%s><tr>",
            smime_sign_colour[valid->sign.status]);

        classid = g_strdup_printf (
            "smime:///em-format-html/%s/icon/signed",
            emf->part_id->str);
        g_string_append_printf (
            buffer,
            "<td valign=\"top\"><img src=\"%s\"></td>"
            "<td valign=\"top\" width=\"100%%\">", classid);

        if (valid->sign.status != 0)
            icon = smime_sign_table[valid->sign.status].icon;
        else
            icon = smime_encrypt_table[valid->encrypt.status].icon;
        iconpath = e_icon_factory_get_icon_filename (icon, GTK_ICON_SIZE_DIALOG);
        iconpart = em_format_html_file_part((EMFormatHTML *)emf, "image/png", iconpath, cancellable);
        if (iconpart) {
            (void) em_format_add_puri (emf, sizeof (EMFormatPURI), classid, iconpart, efh_write_image);
            g_object_unref (iconpart);
        }
        g_free (iconpath);
        g_free (classid);

        if (valid->sign.status != CAMEL_CIPHER_VALIDITY_SIGN_NONE) {
            gchar *signers;

            g_string_append (
                buffer, _(smime_sign_table[valid->sign.status].shortdesc));

            signers = em_format_html_format_cert_infos (
                (CamelCipherCertInfo *) valid->sign.signers.head);
            if (signers && *signers) {
                g_string_append_printf (
                    buffer, " (%s)", signers);
            }
            g_free (signers);
        }

        if (valid->encrypt.status != CAMEL_CIPHER_VALIDITY_ENCRYPT_NONE) {
            if (valid->sign.status != CAMEL_CIPHER_VALIDITY_SIGN_NONE)
                g_string_append (buffer, "<br>");

            g_string_append (
                buffer, _(smime_encrypt_table[valid->encrypt.status].shortdesc));
        }

        g_string_append (buffer, "</td></tr></table>");

        camel_stream_write (
            stream, buffer->str,
            buffer->len, cancellable, NULL);

        g_string_free (buffer, TRUE);
    }
}

static void
efh_text_plain (EMFormat *emf,
                CamelStream *stream,
                CamelMimePart *part,
                const EMFormatHandler *info,
                GCancellable *cancellable,
                gboolean is_fallback)
{
    EMFormatHTML *efh = EM_FORMAT_HTML (emf);
    CamelStream *filtered_stream;
    CamelMimeFilter *html_filter;
    CamelMultipart *mp;
    CamelDataWrapper *dw;
    CamelContentType *type;
    const gchar *format;
    guint32 flags;
    guint32 rgb;
    gint i, count, len;
    struct _EMFormatHTMLCache *efhc;

    flags = efh->text_html_flags;

    dw = camel_medium_get_content ((CamelMedium *) part);

    /* Check for RFC 2646 flowed text. */
    if (camel_content_type_is(dw->mime_type, "text", "plain")
        && (format = camel_content_type_param(dw->mime_type, "format"))
        && !g_ascii_strcasecmp(format, "flowed"))
        flags |= CAMEL_MIME_FILTER_TOHTML_FORMAT_FLOWED;

    /* This scans the text part for inline-encoded data, creates
     * a multipart of all the parts inside it. */

    /* FIXME: We should discard this multipart if it only contains
     * the original text, but it makes this hash lookup more complex */

    /* TODO: We could probably put this in the superclass, since
     * no knowledge of html is required - but this messes with
     * filters a bit.  Perhaps the superclass should just deal with
     * html anyway and be done with it ... */

    efhc = g_hash_table_lookup (
        efh->priv->text_inline_parts,
        emf->part_id->str);

    if (efhc == NULL || (mp = efhc->textmp) == NULL) {
        EMInlineFilter *inline_filter;
        CamelStream *null;
        CamelContentType *ct;
        gboolean charset_added = FALSE;

        /* if we had to snoop the part type to get here, then
         * use that as the base type, yuck */
        if (emf->snoop_mime_type == NULL
            || (ct = camel_content_type_decode (emf->snoop_mime_type)) == NULL) {
            ct = dw->mime_type;
            camel_content_type_ref (ct);
        }

        if (dw->mime_type && ct != dw->mime_type && camel_content_type_param (dw->mime_type, "charset")) {
            camel_content_type_set_param (ct, "charset", camel_content_type_param (dw->mime_type, "charset"));
            charset_added = TRUE;
        }

        null = camel_stream_null_new ();
        filtered_stream = camel_stream_filter_new (null);
        g_object_unref (null);
        inline_filter = em_inline_filter_new (camel_mime_part_get_encoding (part), ct);
        camel_stream_filter_add (
            CAMEL_STREAM_FILTER (filtered_stream),
            CAMEL_MIME_FILTER (inline_filter));
        camel_data_wrapper_decode_to_stream_sync (
            dw, (CamelStream *) filtered_stream, cancellable, NULL);
        camel_stream_close ((CamelStream *) filtered_stream, cancellable, NULL);
        g_object_unref (filtered_stream);

        mp = em_inline_filter_get_multipart (inline_filter);
        if (efhc == NULL)
            efhc = efh_insert_cache (efh, emf->part_id->str);
        efhc->textmp = mp;

        if (charset_added) {
            camel_content_type_set_param (ct, "charset", NULL);
        }

        g_object_unref (inline_filter);
        camel_content_type_unref (ct);
    }

    rgb = e_color_to_value (
        &efh->priv->colors[EM_FORMAT_HTML_COLOR_CITATION]);
    filtered_stream = camel_stream_filter_new (stream);
    html_filter = camel_mime_filter_tohtml_new (flags, rgb);
    camel_stream_filter_add (
        CAMEL_STREAM_FILTER (filtered_stream), html_filter);
    g_object_unref (html_filter);

    /* We handle our made-up multipart here, so we don't recursively call ourselves */

    len = emf->part_id->len;
    count = camel_multipart_get_number (mp);
    for (i = 0; i < count; i++) {
        CamelMimePart *newpart = camel_multipart_get_part (mp, i);

        if (!newpart)
            continue;

        type = camel_mime_part_get_content_type (newpart);
        if (camel_content_type_is (type, "text", "*") && (is_fallback || !camel_content_type_is (type, "text", "calendar"))) {
            gchar *content;

            content = g_strdup_printf (
                "<div style=\"border: solid #%06x 1px; "
                "background-color: #%06x; padding: 10px; "
                "color: #%06x;\">\n<tt>\n" EFH_MESSAGE_START,
                e_color_to_value (
                    &efh->priv->colors[
                    EM_FORMAT_HTML_COLOR_FRAME]),
                e_color_to_value (
                    &efh->priv->colors[
                    EM_FORMAT_HTML_COLOR_CONTENT]),
                e_color_to_value (