/*
 * 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 <glib.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
const char *_e_get_imagesdir (void) G_GNUC_CONST;
#undef EVOLUTION_ICONDIR
#define EVOLUTION_ICONDIR _e_get_imagesdir ()
#endif

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

#include <glib/gi18n.h>

#include <camel/camel-iconv.h>
#include <camel/camel-mime-message.h>
#include <camel/camel-stream.h>
#include <camel/camel-stream-filter.h>
#include <camel/camel-mime-filter.h>
#include <camel/camel-mime-filter-tohtml.h>
#include <camel/camel-mime-filter-enriched.h>
#include <camel/camel-mime-filter-basic.h>
#include <camel/camel-gpg-context.h>
#include <camel/camel-cipher-context.h>
#include <camel/camel-multipart.h>
#include <camel/camel-stream-mem.h>
#include <camel/camel-url.h>
#include <camel/camel-stream-fs.h>
#include <camel/camel-string-utils.h>
#include <camel/camel-http-stream.h>
#include <camel/camel-data-cache.h>
#include <camel/camel-file-utils.h>
#include <camel/camel-stream-null.h>

#include <libedataserver/e-msgport.h>

#include "mail-component.h"
#include "mail/mail-config.h"
#include "mail/mail-mt.h"
#include "mail/em-inline-filter.h"

#include "em-format-webkit.h"
#if HAVE_WEBKIT
#include "em-webkit-stream.h"
#endif

#if HAVE_MOZILLA
#include "em-mozembed-stream.h"
#endif

#include "mail/em-utils.h"
#include "mail-message-view.h"
#include "mail-utils.h"

#define d(x)

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

struct _EMFormatWebKitCache {
	CamelMultipart *textmp;

	char partid[1];
};

struct _EMFormatWebKitPrivate {
	struct _CamelMimeMessage *last_part;	/* not reffed, DO NOT dereference */
	volatile int 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, EMFormatWebKitCache * */
	GHashTable *text_inline_parts;

	EDList pending_jobs;
	GMutex *lock;
};

static void efw_format_message(EMFormat *emf, CamelStream *stream, CamelMimePart *part, const EMFormatHandler *info);

static void efw_format_clone(EMFormat *emf, CamelFolder *folder, const char *uid, CamelMimeMessage *msg, EMFormat *emfsource);
static void efw_format_error(EMFormat *emf, CamelStream *stream, const char *txt);
static void efw_format_source(EMFormat *, CamelStream *, CamelMimePart *);
static void efw_format_attachment(EMFormat *, CamelStream *, CamelMimePart *, const char *, const EMFormatHandler *);
static void efw_format_secure(EMFormat *emf, CamelStream *stream, CamelMimePart *part, CamelCipherValidity *valid);
static gboolean efw_busy(EMFormat *);

static void efw_builtin_init(EMFormatWebKitClass *efwc);

static void efw_write_image(EMFormat *emf, CamelStream *stream, EMFormatPURI *puri);

static EMFormatClass *efw_parent;

static void
efw_free_cache(struct _EMFormatWebKitCache *efwc)
{
	if (efwc->textmp)
		camel_object_unref(efwc->textmp);
	g_free(efwc);
}

static void
efw_init(GObject *o)
{
	EMFormatWebKit *efw = (EMFormatWebKit *)o;

	efw->priv = g_malloc0(sizeof(*efw->priv));

	e_dlist_init(&efw->pending_object_list);
	e_dlist_init(&efw->priv->pending_jobs);
	efw->priv->lock = g_mutex_new();
	efw->priv->format_id = -1;
	efw->priv->text_inline_parts = g_hash_table_new_full (
		g_str_hash, g_str_equal,
		(GDestroyNotify) NULL,
		(GDestroyNotify) efw_free_cache);

	efw->body_colour = 0xffffff;
	efw->header_colour = 0x000000;
	efw->text_colour = 0;
	efw->frame_colour = 0x3f3f3f;
	efw->content_colour = 0xffffff;
	efw->citation_colour = 0x808080;
	efw->text_html_flags = CAMEL_MIME_FILTER_TOHTML_CONVERT_NL | CAMEL_MIME_FILTER_TOHTML_CONVERT_SPACES
		| CAMEL_MIME_FILTER_TOHTML_MARK_CITATION;
	efw->show_icon = TRUE;
	efw->state = EM_FORMAT_WEBKIT_STATE_NONE;
}

static struct _EMFormatWebKitCache *
efw_insert_cache(EMFormatWebKit *efw, const char *partid)
{
	struct _EMFormatWebKitCache *efwc;

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

	return efwc;
}


static void
efw_finalise(GObject *o)
{
	EMFormatWebKit *efw = (EMFormatWebKit *)o;

	/* FIXME: check for leaked stuff */

	em_format_webkit_clear_pobject(efw);

	g_hash_table_destroy(efw->priv->text_inline_parts);

	g_free(efw->priv);

	((GObjectClass *)efw_parent)->finalize(o);
}

static void
efw_base_init(EMFormatWebKitClass *efwklass)
{
	efw_builtin_init(efwklass);
}

static void
efw_class_init(GObjectClass *klass)
{
	((EMFormatClass *)klass)->format_clone = efw_format_clone;
	((EMFormatClass *)klass)->format_error = efw_format_error;
	((EMFormatClass *)klass)->format_source = efw_format_source;
	((EMFormatClass *)klass)->format_attachment = efw_format_attachment;
	((EMFormatClass *)klass)->format_secure = efw_format_secure;
	((EMFormatClass *)klass)->busy = efw_busy;

	klass->finalize = efw_finalise;
}

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

	if (type == 0) {
		static const GTypeInfo info = {
			sizeof(EMFormatWebKitClass),
			(GBaseInitFunc)efw_base_init, NULL,
			(GClassInitFunc)efw_class_init,
			NULL, NULL,
			sizeof(EMFormatWebKit), 0,
			(GInstanceInitFunc)efw_init
		};

		/* Trigger creation of mail component. */
		mail_component_peek ();

		efw_parent = g_type_class_ref(em_format_get_type());
		type = g_type_register_static(em_format_get_type(), "EMFormatWebKit", &info, 0);

	}

	return type;
}

EMFormatWebKit *em_format_webkit_new(void)
{
	EMFormatWebKit *efw;

	efw = g_object_new(em_format_webkit_get_type(), NULL);

	return efw;
}

/* force loading of http images */
void em_format_webkit_load_http(EMFormatWebKit *emfh)
{
	if (emfh->load_http == MAIL_CONFIG_HTTP_ALWAYS)
		return;

	/* This will remain set while we're still rendering the same message, then it wont be */
	emfh->load_http_now = TRUE;
	d(printf("redrawing with images forced on\n"));
	em_format_redraw((EMFormat *)emfh);
}

void
em_format_webkit_set_load_http(EMFormatWebKit *emfh, int style)
{
	if (emfh->load_http != style) {
		emfh->load_http = style;
		em_format_redraw((EMFormat *)emfh);
	}
}

void
em_format_webkit_set_mark_citations(EMFormatWebKit *emfh, int state, guint32 citation_colour)
{
	if (emfh->mark_citations ^ state || emfh->citation_colour != citation_colour) {
		emfh->mark_citations = state;
		emfh->citation_colour = citation_colour;

		if (state)
			emfh->text_html_flags |= CAMEL_MIME_FILTER_TOHTML_MARK_CITATION;
		else
			emfh->text_html_flags &= ~CAMEL_MIME_FILTER_TOHTML_MARK_CITATION;

		em_format_redraw((EMFormat *)emfh);
	}
}

CamelMimePart *
em_format_webkit_file_part(EMFormatWebKit *efw, const char *mime_type, const char *filename)
{
	CamelMimePart *part;
	CamelStream *stream;
	CamelDataWrapper *dw;
	char *basename;

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

	part = camel_mime_part_new();
	dw = camel_data_wrapper_new();
	camel_data_wrapper_construct_from_stream(dw, stream);
	camel_object_unref(stream);
	if (mime_type)
		camel_data_wrapper_set_mime_type(dw, mime_type);
	part = camel_mime_part_new();
	camel_medium_set_content_object((CamelMedium *)part, dw);
	camel_object_unref(dw);
	basename = g_path_get_basename (filename);
	camel_mime_part_set_filename(part, basename);
	g_free (basename);

	return part;
}

/* PObject stuffs */

EMFormatWebKitPObject *
em_format_webkit_add_pobject(EMFormatWebKit *efw, size_t size, const char *classid, CamelMimePart *part, EMFormatWebKitPObjectFunc func)
{
	EMFormatWebKitPObject *pobj;

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

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

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

	e_dlist_addtail(&efw->pending_object_list, (EDListNode *)pobj);

	return pobj;
}

EMFormatWebKitPObject *
em_format_webkit_find_pobject(EMFormatWebKit *emf, const char *classid)
{
	EMFormatWebKitPObject *pw;

	pw = (EMFormatWebKitPObject *)emf->pending_object_list.head;
	while (pw->next) {
		if (!strcmp(pw->classid, classid))
			return pw;
		pw = pw->next;
	}

	return NULL;
}

EMFormatWebKitPObject *
em_format_webkit_find_pobject_func(EMFormatWebKit *emf, CamelMimePart *part, EMFormatWebKitPObjectFunc func)
{
	EMFormatWebKitPObject *pw;

	pw = (EMFormatWebKitPObject *)emf->pending_object_list.head;
	while (pw->next) {
		if (pw->func == func && pw->part == part)
			return pw;
		pw = pw->next;
	}

	return NULL;
}

void
em_format_webkit_remove_pobject(EMFormatWebKit *emf, EMFormatWebKitPObject *pobject)
{
	e_dlist_remove((EDListNode *)pobject);
	if (pobject->free)
		pobject->free(pobject);
	g_free(pobject->classid);
	g_free(pobject);
}

void
em_format_webkit_clear_pobject(EMFormatWebKit *emf)
{
	d(printf("clearing pending objects\n"));
	while (!e_dlist_empty(&emf->pending_object_list))
		em_format_webkit_remove_pobject(emf, (EMFormatWebKitPObject *)emf->pending_object_list.head);
}

struct _EMFormatWebKitJob *
em_format_webkit_job_new(EMFormatWebKit *emfh, void (*callback)(struct _EMFormatWebKitJob *job, int cancelled), void *data)
{
	struct _EMFormatWebKitJob *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_webkit_job_queue(EMFormatWebKit *emfh, struct _EMFormatWebKitJob *job)
{
	g_mutex_lock(emfh->priv->lock);
	e_dlist_addtail(&emfh->priv->pending_jobs, (EDListNode *)job);
	g_mutex_unlock(emfh->priv->lock);
}


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

/* FIXME: This is duplicated in em-format-webkit-display, should be exported or in security module */
static const struct {
	const char *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 char *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 char *smime_sign_colour[4] = {
	"", " bgcolor=\"#88bb88\"", " bgcolor=\"#bb8888\"", " bgcolor=\"#e8d122\""
};

/* TODO: this could probably be virtual on em-format-webkit
   then we only need one version of each type handler */

static void
efw_format_secure(EMFormat *emf, CamelStream *stream, CamelMimePart *part, CamelCipherValidity *valid)
{
	efw_parent->format_secure(emf, stream, part, valid);

	/* 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)) {
		char *classid, *iconpath;
		const char *icon;
		CamelMimePart *iconpart;

		camel_stream_printf (stream, "<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);
		camel_stream_printf(stream, "<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 = mail_utils_get_icon_path (icon, GTK_ICON_SIZE_DIALOG);
		iconpart = em_format_webkit_file_part((EMFormatWebKit *)emf, "image/png", iconpath);
		if (iconpart) {
			(void)em_format_add_puri(emf, sizeof(EMFormatPURI), classid, iconpart, efw_write_image);
			camel_object_unref(iconpart);
		}
		g_free (iconpath);
		g_free(classid);

		if (valid->sign.status != CAMEL_CIPHER_VALIDITY_SIGN_NONE) {
			camel_stream_printf(stream, "%s<br>", _(smime_sign_table[valid->sign.status].shortdesc));
		}

		if (valid->encrypt.status != CAMEL_CIPHER_VALIDITY_ENCRYPT_NONE) {
			camel_stream_printf(stream, "%s<br>", _(smime_encrypt_table[valid->encrypt.status].shortdesc));
		}

		camel_stream_printf(stream, "</td></tr></table>");
	}
}

static void
efw_text_plain(EMFormatWebKit *efw, CamelStream *stream, CamelMimePart *part, EMFormatHandler *info)
{
	CamelStreamFilter *filtered_stream;
	CamelMimeFilter *html_filter;
	CamelMultipart *mp;
	CamelDataWrapper *dw;
	CamelContentType *type;
	const char *format;
	guint32 flags;
	int i, count, len;
	struct _EMFormatWebKitCache *efwc;

	flags = efw->text_html_flags;

	dw = camel_medium_get_content_object((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 ... */

	efwc = g_hash_table_lookup(efw->priv->text_inline_parts, ((EMFormat *)efw)->part_id->str);
	if (efwc == NULL || (mp = efwc->textmp) == NULL) {
		EMInlineFilter *inline_filter;
		CamelStream *null;
		CamelContentType *ct;

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

		null = camel_stream_null_new();
		filtered_stream = camel_stream_filter_new_with_stream(null);
		camel_object_unref(null);
		inline_filter = em_inline_filter_new(camel_mime_part_get_encoding(part), ct);
		camel_stream_filter_add(filtered_stream, (CamelMimeFilter *)inline_filter);
		camel_data_wrapper_write_to_stream(dw, (CamelStream *)filtered_stream);
		camel_stream_close((CamelStream *)filtered_stream);
		camel_object_unref(filtered_stream);

		mp = em_inline_filter_get_multipart(inline_filter);
		if (efwc == NULL)
			efwc = efw_insert_cache(efw, ((EMFormat *)efw)->part_id->str);
		efwc->textmp = mp;

		camel_object_unref(inline_filter);
		camel_content_type_unref(ct);
	}

	filtered_stream = camel_stream_filter_new_with_stream(stream);
	html_filter = camel_mime_filter_tohtml_new(flags, efw->citation_colour);
	camel_stream_filter_add(filtered_stream, html_filter);
	camel_object_unref(html_filter);

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

	len = ((EMFormat *)efw)->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", "*") && !camel_content_type_is(type, "text", "calendar")) {
			camel_stream_printf (stream,
   					"<div style=\"border: solid #%06x 0px; background-color: #%06x; padding: 10px; color: #%06x;\">\n",
					     efw->frame_colour & 0xffffff, efw->content_colour & 0xffffff, efw->text_colour & 0xffffff);
			camel_stream_write_string(stream, "<tt>\n" EFH_MESSAGE_START);
			em_format_format_text((EMFormat *)efw, (CamelStream *)filtered_stream, (CamelDataWrapper *)newpart);
			camel_stream_flush((CamelStream *)filtered_stream);
			camel_stream_write_string(stream, "</tt>\n");
			camel_stream_write_string(stream, "</div>\n");
		} else {
			g_string_append_printf(((EMFormat *)efw)->part_id, ".inline.%d", i);
			em_format_part((EMFormat *)efw, stream, newpart);
			g_string_truncate(((EMFormat *)efw)->part_id, len);
		}
	}

	camel_object_unref(filtered_stream);
}

static void
efw_text_enriched(EMFormatWebKit *efw, CamelStream *stream, CamelMimePart *part, EMFormatHandler *info)
{
	CamelStreamFilter *filtered_stream;
	CamelMimeFilter *enriched;
	CamelDataWrapper *dw;
	guint32 flags = 0;

	dw = camel_medium_get_content_object((CamelMedium *)part);

	if (!strcmp(info->mime_type, "text/richtext")) {
		flags = CAMEL_MIME_FILTER_ENRICHED_IS_RICHTEXT;
		camel_stream_write_string( stream, "\n<!-- text/richtext -->\n");
	} else {
		camel_stream_write_string( stream, "\n<!-- text/enriched -->\n");
	}

	enriched = camel_mime_filter_enriched_new(flags);
	filtered_stream = camel_stream_filter_new_with_stream (stream);
	camel_stream_filter_add(filtered_stream, enriched);
	camel_object_unref(enriched);

	camel_stream_printf (stream,
			     "<div style=\"border: solid #%06x 0px; background-color: #%06x; padding: 10px; color: #%06x;\">\n" EFH_MESSAGE_START,
			     efw->frame_colour & 0xffffff, efw->content_colour & 0xffffff, efw->text_colour & 0xffffff);

	em_format_format_text((EMFormat *)efw, (CamelStream *)filtered_stream, (CamelDataWrapper *)part);

	camel_object_unref(filtered_stream);
	camel_stream_write_string(stream, "</div>");
}

#ifdef NOT_USED
static void
efw_write_text_html(EMFormat *emf, CamelStream *stream, EMFormatPURI *puri)
{
	CamelStream *out;
	int fd;
	CamelDataWrapper *dw;

	fd = dup(STDOUT_FILENO);
	out = camel_stream_fs_new_with_fd(fd);
	printf("writing text content to frame '%s'\n", puri->cid);
	dw = camel_medium_get_content_object(puri->part);
	if (dw)
		camel_data_wrapper_write_to_stream(dw, out);
	camel_object_unref(out);
	em_format_format_text(emf, stream, (CamelDataWrapper *)puri->part);
}
#endif
static void
efw_text_html(EMFormatWebKit *efw, CamelStream *stream, CamelMimePart *part, EMFormatHandler *info)
{
	const char *location;
	/* This is set but never used for anything */
	char *cid = NULL;

	camel_stream_printf (stream,
			     "<div style=\"border: solid #%06x 0px; background-color: #%06x; color: #%06x;\">\n"
			     "<!-- text/html -->\n" EFH_MESSAGE_START,
			     efw->frame_colour & 0xffffff, efw->content_colour & 0xffffff, efw->text_colour & 0xffffff);

	/* TODO: perhaps we don't need to calculate this anymore now base is handled better */
	/* calculate our own location string so add_puri doesn't do it
	   for us. our iframes are special cases, we need to use the
	   proper base url to access them, but other children parts
	   shouldn't blindly inherit the container's location. */
	location = camel_mime_part_get_content_location(part);
	if (location == NULL) {
		if (((EMFormat *)efw)->base)
			cid = camel_url_to_string(((EMFormat *)efw)->base, 0);
		else
			cid = g_strdup(((EMFormat *)efw)->part_id->str);
	} else {
		if (strchr(location, ':') == NULL && ((EMFormat *)efw)->base != NULL) {
			CamelURL *uri;

			uri = camel_url_new_with_base(((EMFormat *)efw)->base, location);
			cid = camel_url_to_string(uri, 0);
			camel_url_free(uri);
		} else {
			cid = g_strdup(location);
		}
	}

	em_format_format_text((EMFormat *)efw, stream, (CamelDataWrapper *)part);
	d(printf("adding iframe, location %s\n", cid));
	/*camel_stream_printf(stream,
			    "<iframe src=\"%s\" frameborder=0 scrolling=no>could not get %s</iframe>\n"
			    "</div>\n",
			    cid, cid);*/
	g_free(cid);
}

/* This is a lot of code for something useless ... */
static void
efw_message_external(EMFormatWebKit *efw, CamelStream *stream, CamelMimePart *part, EMFormatHandler *info)
{
	CamelContentType *type;
	const char *access_type;
	char *url = NULL, *desc = NULL;

	if (!part) {
		camel_stream_printf(stream, _("Unknown external-body part."));
		return;
	}

	/* needs to be cleaner */
	type = camel_mime_part_get_content_type(part);
	access_type = camel_content_type_param (type, "access-type");
	if (!access_type) {
		camel_stream_printf(stream, _("Malformed external-body part."));
		return;
	}

	if (!g_ascii_strcasecmp(access_type, "ftp") ||
	    !g_ascii_strcasecmp(access_type, "anon-ftp")) {
		const char *name, *site, *dir, *mode;
		char *path;
		char ftype[16];

		name = camel_content_type_param (type, "name");
		site = camel_content_type_param (type, "site");
		dir = camel_content_type_param (type, "directory");
		mode = camel_content_type_param (type, "mode");
		if (name == NULL || site == NULL)
			goto fail;

		/* Generate the path. */
		if (dir)
			path = g_strdup_printf("/%s/%s", *dir=='/'?dir+1:dir, name);
		else
			path = g_strdup_printf("/%s", *name=='/'?name+1:name);

		if (mode && *mode)
			sprintf(ftype, ";type=%c",  *mode);
		else
			ftype[0] = 0;

		url = g_strdup_printf ("ftp://%s%s%s", site, path, ftype);
		g_free (path);
		desc = g_strdup_printf (_("Pointer to FTP site (%s)"), url);
	} else if (!g_ascii_strcasecmp (access_type, "local-file")) {
		const char *name, *site;

		name = camel_content_type_param (type, "name");
		site = camel_content_type_param (type, "site");
		if (name == NULL)
			goto fail;

		url = g_filename_to_uri (name, NULL, NULL);
		if (site)
			desc = g_strdup_printf(_("Pointer to local file (%s) valid at site \"%s\""), name, site);
		else
			desc = g_strdup_printf(_("Pointer to local file (%s)"), name);
	} else if (!g_ascii_strcasecmp (access_type, "URL")) {
		const char *urlparam;
		char *s, *d;

		/* RFC 2017 */

		urlparam = camel_content_type_param (type, "url");
		if (urlparam == NULL)
			goto fail;

		/* For obscure MIMEy reasons, the URL may be split into words */
		url = g_strdup (urlparam);
		s = d = url;
		while (*s) {
			/* FIXME: use camel_isspace */
			if (!isspace ((unsigned char)*s))
				*d++ = *s;
			s++;
		}
		*d = 0;
		desc = g_strdup_printf (_("Pointer to remote data (%s)"), url);
	} else
		goto fail;

	camel_stream_printf(stream, "<a href=\"%s\">%s</a>", url, desc);
	g_free(url);
	g_free(desc);

	return;

fail:
	camel_stream_printf(stream, _("Pointer to unknown external data (\"%s\" type)"), access_type);
}

static void
efw_message_deliverystatus(EMFormatWebKit *efw, CamelStream *stream, CamelMimePart *part, EMFormatHandler *info)
{
	CamelStreamFilter *filtered_stream;
	CamelMimeFilter *html_filter;
	guint32 rgb = 0x737373;

	/* Yuck, this is copied from efw_text_plain */
	camel_stream_printf (stream,
			     "<div style=\"border: solid #%06x 1px; background-color: #%06x; padding: 10px; color: #%06x;\">\n",
			     efw->frame_colour & 0xffffff, efw->content_colour & 0xffffff, efw->text_colour & 0xffffff);

	filtered_stream = camel_stream_filter_new_with_stream(stream);
	html_filter = camel_mime_filter_tohtml_new(efw->text_html_flags, rgb);
	camel_stream_filter_add(filtered_stream, html_filter);
	camel_object_unref(html_filter);

	camel_stream_write_string(stream, "<tt>\n" EFH_MESSAGE_START);
	em_format_format_text((EMFormat *)efw, (CamelStream *)filtered_stream, (CamelDataWrapper *)part);
	camel_stream_flush((CamelStream *)filtered_stream);
	camel_stream_write_string(stream, "</tt>\n");

	camel_stream_write_string(stream, "</div>");
}

static void
emfh_write_related(EMFormat *emf, CamelStream *stream, EMFormatPURI *puri)
{
	em_format_format_content(emf, stream, puri->part);
	camel_stream_close(stream);
}

static void
emfh_multipart_related_check(struct _EMFormatWebKitJob *job, int cancelled)
{
	struct _EMFormatPURITree *ptree;
	EMFormatPURI *puri, *purin;
	char *oldpartid;

	if (cancelled)
		return;

	d(printf(" running multipart/related check task\n"));
	oldpartid = g_strdup(((EMFormat *)job->format)->part_id->str);

	ptree = job->puri_level;
	puri = (EMFormatPURI *)ptree->uri_list.head;
	purin = puri->next;
	while (purin) {
		if (puri->use_count == 0) {
			d(printf("part '%s' '%s' used '%d'\n", puri->uri?puri->uri:"", puri->cid, puri->use_count));
			if (puri->func == emfh_write_related) {
				g_string_printf(((EMFormat *)job->format)->part_id, "%s", puri->part_id);
				em_format_part((EMFormat *)job->format, (CamelStream *)job->stream, puri->part);
			}
			/* else it was probably added by a previous format this loop */
		}
		puri = purin;
		purin = purin->next;
	}

	g_string_printf(((EMFormat *)job->format)->part_id, "%s", oldpartid);
	g_free(oldpartid);
}

/* RFC 2387 */
static void
efw_multipart_related(EMFormat *emf, CamelStream *stream, CamelMimePart *part, const EMFormatHandler *info)
{
	CamelMultipart *mp = (CamelMultipart *)camel_medium_get_content_object((CamelMedium *)part);
	CamelMimePart *body_part, *display_part = NULL;
	CamelContentType *content_type;
	const char *start;
	int i, nparts, partidlen, displayid = 0;
	/* puri is set but never used */
	EMFormatPURI *puri;
	struct _EMFormatWebKitJob *job;

	if (!CAMEL_IS_MULTIPART(mp)) {
		em_format_format_source(emf, stream, part);
		return;
	}

	nparts = camel_multipart_get_number(mp);
	content_type = camel_mime_part_get_content_type(part);
	start = camel_content_type_param (content_type, "start");
	if (start && strlen(start)>2) {
		int len;
		const char *cid;

		/* strip <>'s */
		len = strlen (start) - 2;
		start++;

		for (i=0; i<nparts; i++) {
			body_part = camel_multipart_get_part(mp, i);
			cid = camel_mime_part_get_content_id(body_part);

			if (cid && !strncmp(cid, start, len) && strlen(cid) == len) {
				display_part = body_part;
				displayid = i;
				break;
			}
		}
	} else {
		display_part = camel_multipart_get_part(mp, 0);
	}

	if (display_part == NULL) {
		em_format_part_as(emf, stream, part, "multipart/mixed");
		return;
	}

	em_format_push_level(emf);

	partidlen = emf->part_id->len;

	/* queue up the parts for possible inclusion */
	for (i = 0; i < nparts; i++) {
		body_part = camel_multipart_get_part(mp, i);
		if (body_part != display_part) {
			g_string_append_printf(emf->part_id, "related.%d", i);
			puri = em_format_add_puri(emf, sizeof(EMFormatPURI), NULL, body_part, emfh_write_related);
			g_string_truncate(emf->part_id, partidlen);
			d(printf(" part '%s' '%s' added\n", puri->uri?puri->uri:"", puri->cid));
		}
	}

	g_string_append_printf(emf->part_id, "related.%d", displayid);
	em_format_part(emf, stream, display_part);
	g_string_truncate(emf->part_id, partidlen);
	camel_stream_flush(stream);

	/* queue a job to check for un-referenced parts to add as attachments */
	job = em_format_webkit_job_new((EMFormatWebKit *)emf, emfh_multipart_related_check, NULL);
	job->stream = stream;
	camel_object_ref(stream);
	em_format_webkit_job_queue((EMFormatWebKit *)emf, job);

	em_format_pull_level(emf);
}

static void
efw_write_image(EMFormat *emf, CamelStream *stream, EMFormatPURI *puri)
{
	CamelDataWrapper *dw = camel_medium_get_content_object((CamelMedium *)puri->part);

	d(printf("writing image '%s'\n", puri->cid));
	camel_data_wrapper_decode_to_stream(dw, stream);
	camel_stream_close(stream);
}

static void
efw_image(EMFormatWebKit *efw, CamelStream *stream, CamelMimePart *part, EMFormatHandler *info)
{
	EMFormatPURI *puri;

	puri = em_format_add_puri((EMFormat *)efw, sizeof(EMFormatPURI), NULL, part, efw_write_image);
	d(printf("adding image '%s'\n", puri->cid));
	camel_stream_printf(stream, "<img hspace=10 vspace=10 src=\"%s\">", puri->cid);
}

static EMFormatHandler type_builtin_table[] = {
	{ "image/gif", (EMFormatFunc)efw_image },
	{ "image/jpeg", (EMFormatFunc)efw_image },
	{ "image/png", (EMFormatFunc)efw_image },
	{ "image/x-png", (EMFormatFunc)efw_image },
	{ "image/tiff", (EMFormatFunc)efw_image },
	{ "image/x-bmp", (EMFormatFunc)efw_image },
	{ "image/bmp", (EMFormatFunc)efw_image },
	{ "image/svg", (EMFormatFunc)efw_image },
	{ "image/x-cmu-raster", (EMFormatFunc)efw_image },
	{ "image/x-ico", (EMFormatFunc)efw_image },
	{ "image/x-portable-anymap", (EMFormatFunc)efw_image },
	{ "image/x-portable-bitmap", (EMFormatFunc)efw_image },
	{ "image/x-portable-graymap", (EMFormatFunc)efw_image },
	{ "image/x-portable-pixmap", (EMFormatFunc)efw_image },
	{ "image/x-xpixmap", (EMFormatFunc)efw_image },
	{ "text/enriched", (EMFormatFunc)efw_text_enriched },
	{ "text/plain", (EMFormatFunc)efw_text_plain },
	{ "text/html", (EMFormatFunc)efw_text_html },
	{ "text/richtext", (EMFormatFunc)efw_text_enriched },
	{ "text/*", (EMFormatFunc)efw_text_plain },
	{ "message/external-body", (EMFormatFunc)efw_message_external },
	{ "message/delivery-status", (EMFormatFunc)efw_message_deliverystatus },
	{ "multipart/related", (EMFormatFunc)efw_multipart_related },

	/* This is where one adds those busted, non-registered types,
	   that some idiot mailer writers out there decide to pull out
	   of their proverbials at random. */

	{ "image/jpg", (EMFormatFunc)efw_image },
	{ "image/pjpeg", (EMFormatFunc)efw_image },

	/* special internal types */

	{ "x-evolution/message/rfc822", (EMFormatFunc)efw_format_message }
};

static void
efw_builtin_init(EMFormatWebKitClass *efwc)
{
	int i;

	for (i=0;i<sizeof(type_builtin_table)/sizeof(type_builtin_table[0]);i++)
		em_format_class_add_handler((EMFormatClass *)efwc, &type_builtin_table[i]);
}

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

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

	EMFormatWebKit *format;
	EMFormat *format_source;
	CamelStream *estream;
	CamelFolder *folder;
	char *uid;
	CamelMimeMessage *message;
};

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

static void
efw_format_exec (struct _format_msg *m)
{
	struct _EMFormatWebKitJob *job;
	struct _EMFormatPURITree *puri_level;
	int cancelled = FALSE;
	CamelURL *base;

	camel_stream_printf((CamelStream *)m->estream,
			    "<!doctype html public \"-//W3C//DTD HTML 4.0 TRANSITIONAL//EN\">\n<html>\n"
			    "<head>\n<meta name=\"generator\" content=\"Evolution Mail Component\">\n"
				"<script language=\"JavaScript\"><!--"
				"function height() {"
				"    if (document.all) "
				"        alert('Document height = ' + document.body.offsetHeight);"
				"    else if (document.layers)"
				"        alert('Document height = ' + document.body.document.height);"
				" }"
				"//--></script>			    "
			    "</head>\n"
			    "<body onLoad=\"height()\" bgcolor =\"#%06x\" text=\"#%06x\" marginwidth=6 marginheight=6>\n",
			    m->format->body_colour & 0xffffff,
			    m->format->header_colour & 0xffffff);

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

	if (((EMFormat *)m->format)->mode == EM_FORMAT_SOURCE) {
		em_format_format_source((EMFormat *)m->format, (CamelStream *)m->estream, (CamelMimePart *)m->message);
	} else {
		const EMFormatHandler *handle;

		handle = em_format_find_handler((EMFormat *)m->format, "x-evolution/message/rfc822");
		if (handle)
			handle->handler((EMFormat *)m->format, (CamelStream *)m->estream, (CamelMimePart *)m->message, handle);
	}

	camel_stream_flush((CamelStream *)m->estream);

	puri_level = ((EMFormat *)m->format)->pending_uri_level;
	base = ((EMFormat *)m->format)->base;
	do {
		/* now dispatch any added tasks ... */
		g_mutex_lock(m->format->priv->lock);
		while ((job = (struct _EMFormatWebKitJob *)e_dlist_remhead(&m->format->priv->pending_jobs))) {
			g_mutex_unlock(m->format->priv->lock);

			/* Now do an explicit check for user cancellation */
			if (!cancelled)
				cancelled = camel_operation_cancel_check(NULL);

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

			/* clean up the job */
			camel_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");
			camel_stream_close((CamelStream *)m->estream);
			camel_object_unref(m->estream);
			m->estream = NULL;
		}

		/* e_dlist_empty is atomic and doesn't need locking */
	} while (!e_dlist_empty(&m->format->priv->pending_jobs));

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

	((EMFormat *)m->format)->pending_uri_level = puri_level;
}

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

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

static void
efw_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);
		camel_object_unref(m->estream);
	}
	if (m->folder)
		camel_object_unref(m->folder);
	g_free(m->uid);
	if (m->message)
		camel_object_unref(m->message);
	if (m->format_source)
		g_object_unref(m->format_source);
}

static MailMsgInfo efw_format_info = {
	sizeof (struct _format_msg),
	(MailMsgDescFunc) efw_format_desc,
	(MailMsgExecFunc) efw_format_exec,
	(MailMsgDoneFunc) efw_format_done,
	(MailMsgFreeFunc) efw_format_free
};

static gboolean
efw_format_timeout(struct _format_msg *m)
{
	EMFormatWebKit *efw = m->format;
	struct _EMFormatWebKitPrivate *p = efw->priv;

	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 (e_dlist_empty(&p->pending_jobs), FALSE);

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

	/* call super-class to kick it off */
	efw_parent->format_clone((EMFormat *)efw, m->folder, m->uid, m->message, m->format_source);
	em_format_webkit_clear_pobject(m->format);

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

	if (m->message == NULL) {
		mail_msg_unref(m);
		p->last_part = NULL;
	} else {
		efw->state = EM_FORMAT_WEBKIT_STATE_RENDERING;
		m->estream = mail_message_view_create_webstream(mail_message_view_create_webview (efw->msg_view, efw->body), efw->body);

		if (p->last_part == m->message) {
			mail_message_view_set_web_flags (m->estream,
						  WEB_BEGIN_KEEP_SCROLL | WEB_BEGIN_KEEP_IMAGES
						  | WEB_BEGIN_BLOCK_UPDATES | WEB_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;
		}

		efw->priv->format_id = m->base.seq;
		mail_msg_unordered_push (m);
	}

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

	return FALSE;
}

static void efw_format_clone(EMFormat *emf, CamelFolder *folder, const char *uid, CamelMimeMessage *msg, EMFormat *emfsource)
{
	EMFormatWebKit *efw = (EMFormatWebKit *)emf;
	struct _format_msg *m;
	/* How to sub-class ?  Might need to adjust api ... */

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

	m = mail_msg_new(&efw_format_info);
	m->format = (EMFormatWebKit *)emf;
	g_object_ref(emf);
	m->format_source = emfsource;
	if (emfsource)
		g_object_ref(emfsource);
	m->folder = folder;
	if (folder)
		camel_object_ref(folder);
	m->uid = g_strdup(uid);
	m->message = msg;
	if (msg)
		camel_object_ref(msg);

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

static void efw_format_error(EMFormat *emf, CamelStream *stream, const char *txt)
{
	char *html;

	html = camel_text_to_html (txt, CAMEL_MIME_FILTER_TOHTML_CONVERT_NL|CAMEL_MIME_FILTER_TOHTML_CONVERT_URLS, 0);
	camel_stream_printf(stream, "<em><font color=\"red\">%s</font></em><br>", html);
	g_free(html);
}

static void
efw_format_text_header (EMFormatWebKit *emfh, CamelStream *stream, const char *label, const char *value, guint32 flags)
{
	const char *fmt, *html;
	char *mhtml = NULL;
	gboolean is_rtl;
	
	if (value == NULL)
		return;

	while (*value == ' ')
		value++;
	
	if (!(flags & EM_FORMAT_WEBKIT_HEADER_HTML))
		html = mhtml = camel_text_to_html (value, emfh->text_html_flags, 0);
	else 
		html = value;
	
	is_rtl = gtk_widget_get_default_direction () == GTK_TEXT_DIR_RTL;
	if (emfh->simple_headers) {
		fmt = "<b>%s</b>: %s<br>";
	} else {
		if (flags & EM_FORMAT_WEBKIT_HEADER_NOCOLUMNS) {
			if (flags & EM_FORMAT_HEADER_BOLD) {
				fmt = "<tr><td><b>%s:</b> %s</td></tr>";
			} else {
				fmt = "<tr><td>%s: %s</td></tr>";
			}
		} else if (flags & EM_FORMAT_WEBKIT_HEADER_NODEC) {
			if (is_rtl)
				fmt = "<tr><td align=\"right\" valign=\"top\" width=\"100%%\">%2$s</td><th valign=top align=\"left\" nowrap>%1$s<b>&nbsp;</b></th></tr>";
			else
				fmt = "<tr><th align=\"right\" valign=\"top\" nowrap>%s<b>&nbsp;</b></th><td valign=top>%s</td></tr>";
		} else {
			
			if (flags & EM_FORMAT_HEADER_BOLD) {
				if (is_rtl)
					fmt = "<tr><td align=\"right\" valign=\"top\" width=\"100%%\">%2$s</td><th align=\"left\" nowrap>%1$s:<b>&nbsp;</b></th></tr>";
				else
					fmt = "<tr><th align=\"right\" valign=\"top\" nowrap>%s:<b>&nbsp;</b></th><td>%s</td></tr>";
			} else {
				if (is_rtl)
					fmt = "<tr><td align=\"right\" valign=\"top\" width=\"100%\">%2$s</td><td align=\"left\" nowrap>%1$s:<b>&nbsp;</b></td></tr>";
				else
					fmt = "<tr><td align=\"right\" valign=\"top\" nowrap>%s:<b>&nbsp;</b></td><td>%s</td></tr>";
			}
		}
	}

	camel_stream_printf(stream, fmt, label, html);
	g_free(mhtml);
}

static char *addrspec_hdrs[] = {
	"Sender", "From", "Reply-To", "To", "Cc", "Bcc",
	"Resent-Sender", "Resent-From", "Resent-Reply-To",
	"Resent-To", "Resent-Cc", "Resent-Bcc", NULL
};

static gchar *
efw_format_address (EMFormatWebKit *efw, GString *out, struct _camel_header_address *a, gchar *field)
{
	guint32 flags = CAMEL_MIME_FILTER_TOHTML_CONVERT_SPACES;
	char *name, *mailto, *addr;
	int i=0;
	gboolean wrap = FALSE;
	char *str = NULL;
	int limit = mail_config_get_address_count ();

	if (field ) {
		if ((!strcmp (field, _("To")) && !(efw->header_wrap_flags & EM_FORMAT_WEBKIT_HEADER_TO))
		    || (!strcmp (field, _("Cc")) && !(efw->header_wrap_flags & EM_FORMAT_WEBKIT_HEADER_CC))
		    || (!strcmp (field, _("Bcc")) && !(efw->header_wrap_flags & EM_FORMAT_WEBKIT_HEADER_BCC)))
		    wrap = TRUE;
	}

	while (a) {
		if (a->name)
			name = camel_text_to_html (a->name, flags, 0);
		else
			name = NULL;

		switch (a->type) {
		case CAMEL_HEADER_ADDRESS_NAME:
			if (name && *name) {
				char *real, *mailaddr;

				g_string_append_printf (out, "%s &lt;", name);
				/* rfc2368 for mailto syntax and url encoding extras */
				if ((real = camel_header_encode_phrase ((unsigned char *)a->name))) {
					mailaddr = g_strdup_printf("%s <%s>", real, a->v.addr);
					g_free (real);
					mailto = camel_url_encode (mailaddr, "?=&()");
					g_free (mailaddr);
				} else {
					mailto = camel_url_encode (a->v.addr, "?=&()");
				}
			} else {
				mailto = camel_url_encode (a->v.addr, "?=&()");
			}
			addr = camel_text_to_html (a->v.addr, flags, 0);
			g_string_append_printf (out, "<a href=\"mailto:%s\">%s</a>", mailto, addr);
			g_free (mailto);
			g_free (addr);

			if (name && *name)
				g_string_append (out, "&gt;");
			break;
		case CAMEL_HEADER_ADDRESS_GROUP:
			g_string_append_printf (out, "%s: ", name);
			efw_format_address (efw, out, a->v.members, field);
			g_string_append_printf (out, ";");
			break;
		default:
			g_warning ("Invalid address type");
			break;
		}

		g_free (name);

		i++;
		a = a->next;
		if (a)
			g_string_append (out, ", ");

		/* Let us add a '...' if we have more addresses */
		if (limit > 0 && wrap && a && (i>(limit-1))) {

			if (!strcmp (field, _("To"))) {

				g_string_append (out, "<a href=\"##TO##\">...</a>");
				str = g_strdup_printf ("<a href=\"##TO##\"><img src=\"%s/plus.png\" /></a>  ", "EVOLUTION_ICONSDIR");

				return str;
			}
			else if (!strcmp (field, _("Cc"))) {
				g_string_append (out, "<a href=\"##CC##\">...</a>");
				str = g_strdup_printf ("<a href=\"##CC##\"><img src=\"%s/plus.png\" /></a>  ", "EVOLUTION_ICONSDIR");

				return str;
			}
			else if (!strcmp (field, _("Bcc"))) {
				g_string_append (out, "<a href=\"##BCC##\">...</a>");
				str = g_strdup_printf ("<a href=\"##BCC##\"><img src=\"%s/plus.png\" /></a>  ", "EVOLUTION_ICONSDIR");

				return str;
			}
		}

	}

	if (limit > 0 && i>(limit)) {


		if (!strcmp (field, _("To"))) {
			str = g_strdup_printf ("<a href=\"##TO##\"><img src=\"%s/minus.png\" /></a>  ", "EVOLUTION_ICONSDIR");
		}
		else if (!strcmp (field, _("Cc"))) {
			str = g_strdup_printf ("<a href=\"##CC##\"><img src=\"%s/minus.png\" /></a>  ", "EVOLUTION_ICONSDIR");
		}
		else if (!strcmp (field, _("Bcc"))) {
			str = g_strdup_printf ("<a href=\"##BCC##\"><img src=\"%s/minus.png\" /></a>  ", "EVOLUTION_ICONSDIR");
		}
	}

	return str;

}

static void
canon_header_name (char *name)
{
	char *inptr = name;
	
	/* canonicalise the header name... first letter is
	 * capitalised and any letter following a '-' also gets
	 * capitalised */
	
	if (*inptr >= 'a' && *inptr <= 'z')
		*inptr -= 0x20;
	
	inptr++;
	
	while (*inptr) {
		if (inptr[-1] == '-' && *inptr >= 'a' && *inptr <= 'z')
			*inptr -= 0x20;
		else if (*inptr >= 'A' && *inptr <= 'Z')
			*inptr += 0x20;
		
		inptr++;
	}
}

static void
efw_format_header(EMFormat *emf, CamelStream *stream, CamelMedium *part, struct _camel_header_raw *header, guint32 flags, const char *charset)
{
	EMFormatWebKit *efw = (EMFormatWebKit *)emf;
	char *name, *buf, *value = NULL;
	const char *label, *txt;
	gboolean addrspec = FALSE;
	char *str_field = NULL;
	int i;

	name = alloca(strlen(header->name)+1);
	strcpy(name, header->name);
	canon_header_name (name);

	for (i = 0; addrspec_hdrs[i]; i++) {
		if (!strcmp(name, addrspec_hdrs[i])) {
			addrspec = TRUE;
			break;
		}
	}
	
	label = _(name);
	
	if (addrspec) {
		struct _camel_header_address *addrs;
		GString *html;
		char *img;
		
		buf = camel_header_unfold (header->value);
		if (!(addrs = camel_header_address_decode (buf, emf->charset ? emf->charset : emf->default_charset))) {
			g_free (buf);
			return;
		}
		
		g_free (buf);
		
		html = g_string_new("");
		img = efw_format_address(efw, html, addrs, (char *)label);

		if (img) {
			str_field = g_strdup_printf ("%s%s:", img, label);
			label = str_field;
			flags |= EM_FORMAT_WEBKIT_HEADER_NODEC;
			g_free (img);
		}
		
		camel_header_address_unref(addrs);
		txt = value = html->str;
		g_string_free(html, FALSE);

		flags |= EM_FORMAT_HEADER_BOLD | EM_FORMAT_WEBKIT_HEADER_HTML;
	} else if (!strcmp (name, "Subject")) {
		buf = camel_header_unfold (header->value);
		txt = value = camel_header_decode_string (buf, charset);
		g_free (buf);
		
		flags |= EM_FORMAT_HEADER_BOLD;
	} else if (!strcmp(name, "X-evolution-mailer")) {
		/* pseudo-header */
		label = _("Mailer");
		txt = value = camel_header_format_ctext (header->value, charset);
		flags |= EM_FORMAT_HEADER_BOLD;
	} else if (!strcmp (name, "Date") || !strcmp (name, "Resent-Date")) {
		int msg_offset, local_tz;
		time_t msg_date;
		struct tm local;

		txt = header->value;
		while (*txt == ' ' || *txt == '\t')
			txt++;

		/* Show the local timezone equivalent in brackets if the sender is remote */
		msg_date = camel_header_decode_date(txt, &msg_offset);
		e_localtime_with_offset(msg_date, &local, &local_tz);

		/* Convert message offset to minutes (e.g. -0400 --> -240) */
		msg_offset = ((msg_offset / 100) * 60) + (msg_offset % 100);
		/* Turn into offset from localtime, not UTC */
		msg_offset -= local_tz / 60;

		if (msg_offset) {
			char buf[256], *html;
			
			msg_offset += (local.tm_hour * 60) + local.tm_min;
			if (msg_offset >= (24 * 60) || msg_offset < 0) {
				/* translators: strftime format for local time equivalent in Date header display, with day */
				char *msg = g_strdup_printf("<I>%s</I>", _(" (%a, %R %Z)"));
				e_utf8_strftime(buf, sizeof(buf), msg, &local);
				g_free(msg);
			} else {
				/* translators: strftime format for local time equivalent in Date header display, without day */
				char *msg = g_strdup_printf("<I>%s</I>", _(" (%R %Z)"));
				e_utf8_strftime(buf, sizeof(buf), msg, &local);
				g_free(msg);
			}
			
			html = camel_text_to_html(txt, efw->text_html_flags, 0);
			txt = value = g_strdup_printf("%s %s", html, buf);
			g_free(html);
			flags |= EM_FORMAT_WEBKIT_HEADER_HTML;
		}
		
		flags |= EM_FORMAT_HEADER_BOLD;
	} else if (!strcmp(name, "Newsgroups")) {
		struct _camel_header_newsgroup *ng, *scan;
		GString *html;
		
		buf = camel_header_unfold (header->value);
		
		if (!(ng = camel_header_newsgroups_decode (buf))) {
			g_free (buf);
			return;
		}
		
		g_free (buf);
		
		html = g_string_new("");
		scan = ng;
		while (scan) {
			g_string_append_printf(html, "<a href=\"news:%s\">%s</a>", scan->newsgroup, scan->newsgroup);
			scan = scan->next;
			if (scan)
				g_string_append_printf(html, ", ");
		}
		
		camel_header_newsgroups_free(ng);
		
		txt = html->str;
		g_string_free(html, FALSE);
		flags |= EM_FORMAT_HEADER_BOLD|EM_FORMAT_WEBKIT_HEADER_HTML;
	} else if (!strcmp (name, "Received") || !strncmp (name, "X-", 2)) {
		/* don't unfold Received nor extension headers */
		txt = value = camel_header_decode_string(header->value, charset);
	} else {
		/* don't unfold Received nor extension headers */
		buf = camel_header_unfold (header->value);
		txt = value = camel_header_decode_string (buf, charset);
		g_free (buf);
	}
	
	efw_format_text_header(efw, stream, label, txt, flags);
	
	g_free (value);
	g_free (str_field);
}

static void
efw_format_headers(EMFormatWebKit *efw, CamelStream *stream, CamelMedium *part)
{
	EMFormat *emf = (EMFormat *) efw;
	EMFormatHeader *h;
	const char *charset;
	CamelContentType *ct;
	struct _camel_header_raw *header;
	gboolean have_icon = FALSE;
	const char *photo_name = NULL;
	CamelInternetAddress *cia = NULL;
	gboolean face_decoded  = FALSE, contact_has_photo = FALSE;
	guchar *face_header_value = NULL;
	gsize face_header_len = 0;
	char *header_sender = NULL, *header_from = NULL, *name;
	gboolean mail_from_delegate = FALSE;
	const char *hdr_charset;
	
	if (!part)
		return;

	ct = camel_mime_part_get_content_type((CamelMimePart *)part);
	charset = camel_content_type_param (ct, "charset");
	charset = camel_iconv_charset_name(charset);

	if (!efw->simple_headers)
		camel_stream_printf(stream,
				    "<font color=\"#%06x\">\n"
				    "<table cellpadding=\"0\" width=\"100%%\">",
				    efw->header_colour & 0xffffff);
	
	hdr_charset = emf->charset ? emf->charset : emf->default_charset;
	
	header = ((CamelMimePart *)part)->headers;
	while (header) {
		if (!g_ascii_strcasecmp (header->name, "Sender")) {
			struct _camel_header_address *addrs;
			GString *html;

			if (!(addrs = camel_header_address_decode (header->value, hdr_charset)))
				break;

			html = g_string_new("");
			name = efw_format_address(efw, html, addrs, header->name);

			header_sender = html->str;
			camel_header_address_unref(addrs);

			g_string_free(html, FALSE);
			g_free (name);
		} else if (!g_ascii_strcasecmp (header->name, "From")) {
			struct _camel_header_address *addrs;
			GString *html;

			if (!(addrs = camel_header_address_decode (header->value, hdr_charset)))
				break;

			html = g_string_new("");
			name = efw_format_address(efw, html, addrs, header->name);

			header_from = html->str;
			camel_header_address_unref(addrs);

			g_string_free(html, FALSE);
			g_free(name);
		} else if (!g_ascii_strcasecmp (header->name, "X-Evolution-Mail-From-Delegate")) {
			mail_from_delegate = TRUE;
		}

		header = header->next;
	}
	
	if (header_sender && header_from && mail_from_delegate) {
		camel_stream_printf(stream, "<tr><td><table border=1 width=\"100%%\" cellspacing=2 cellpadding=2><tr>");
		if(gtk_widget_get_default_direction () == GTK_TEXT_DIR_RTL)
			camel_stream_printf (stream, "<td align=\"right\" width=\"100%%\">");
		else
			camel_stream_printf (stream, "<td align=\"left\" width=\"100%%\">");
		/* To translators: This message suggests to the receipients that the sender of the mail is
		   different from the one listed in From field.
		*/
		camel_stream_printf(stream, _("This message was sent by <b>%s</b> on behalf of <b>%s</b>"), header_sender, header_from);
		camel_stream_printf(stream, "</td></tr></table></td></tr>");
	}

	g_free (header_sender);
	g_free (header_from);

	if (gtk_widget_get_default_direction () == GTK_TEXT_DIR_RTL)
		camel_stream_printf (stream, "<tr><td><table width=\"100%%\" border=0 cellpadding=\"0\">\n");
	else
		camel_stream_printf (stream, "<tr><td><table border=0 cellpadding=\"0\">\n");

	/* dump selected headers */
	h = (EMFormatHeader *)emf->header_list.head;
	if (emf->mode == EM_FORMAT_ALLHEADERS) {
		header = ((CamelMimePart *)part)->headers;
		while (header) {
			efw_format_header(emf, stream, part, header, EM_FORMAT_WEBKIT_HEADER_NOCOLUMNS, charset);
			header = header->next;
		}
	} else {
		int mailer_shown = FALSE;
		while (h->next) {
			int mailer, face;

			header = ((CamelMimePart *)part)->headers;
			mailer = !g_ascii_strcasecmp (h->name, "X-Evolution-Mailer");
			face = !g_ascii_strcasecmp (h->name, "Face");

			while (header) {
				if (emf->show_photo && !photo_name && !g_ascii_strcasecmp (header->name, "From"))
					photo_name = header->value;

				if (!mailer_shown && mailer && (!g_ascii_strcasecmp (header->name, "X-Mailer") ||
								!g_ascii_strcasecmp (header->name, "User-Agent") ||
								!g_ascii_strcasecmp (header->name, "X-Newsreader") ||
								!g_ascii_strcasecmp (header->name, "X-MimeOLE"))) {
					struct _camel_header_raw xmailer, *use_header = NULL;

					if (!g_ascii_strcasecmp (header->name, "X-MimeOLE")) {
						for (use_header = header->next; use_header; use_header = use_header->next) {
							if (!g_ascii_strcasecmp (use_header->name, "X-Mailer") ||
							    !g_ascii_strcasecmp (use_header->name, "User-Agent") ||
							    !g_ascii_strcasecmp (use_header->name, "X-Newsreader")) {
								/* even we have X-MimeOLE, then use rather the standard one, when available */
								break;
							}
						}
					}

					if (!use_header)
						use_header = header;

					xmailer.name = "X-Evolution-Mailer";
					xmailer.value = use_header->value;
					mailer_shown = TRUE;

					efw_format_header (emf, stream, part, &xmailer, h->flags, charset);
					if (strstr(use_header->value, "Evolution"))
						have_icon = TRUE;
				} else if (!face_decoded && face && !g_ascii_strcasecmp (header->name, "Face")) {
					char *cp = header->value;
					
					/* Skip over spaces */
					while (*cp == ' ')
						cp++;
					
					face_header_value = g_base64_decode (cp, &face_header_len);
					face_header_value = g_realloc (face_header_value, face_header_len + 1);
					face_header_value[face_header_len] = 0;
					face_decoded = TRUE;
				/* Showing an encoded "Face" header makes little sense */
				} else if (!g_ascii_strcasecmp (header->name, h->name) && !face) {
					efw_format_header(emf, stream, part, header, h->flags, charset);
				}

				header = header->next;
			}
			h = h->next;
		}
	}

	if (!efw->simple_headers) {
		camel_stream_printf(stream, "</table></td>");

		if (photo_name) {
			char *classid;
			CamelMimePart *photopart;

			cia = camel_internet_address_new();
			camel_address_decode((CamelAddress *) cia, (const char *) photo_name);
			photopart = em_utils_contact_photo (cia, emf->photo_local);

			if (photopart) {
				contact_has_photo = TRUE;
				classid = g_strdup_printf("icon:///em-format-html/%s/photo/header",
				emf->part_id->str);
				camel_stream_printf(stream,
					"<td align=\"right\" valign=\"top\"><img width=64 src=\"%s\"></td>",
					classid);
				em_format_add_puri(emf, sizeof(EMFormatPURI), classid,
					photopart, efw_write_image);
				camel_object_unref(photopart);

				g_free(classid);
			}
			camel_object_unref(cia);
		}

		if (!contact_has_photo && face_decoded) {
			char *classid;
			CamelMimePart *part;

			part = camel_mime_part_new ();
			camel_mime_part_set_content ((CamelMimePart *) part, (const char *) face_header_value, face_header_len, "image/png");
			classid = g_strdup_printf("icon:///em-format-html/face/photo/header");
			camel_stream_printf(stream, "<td align=\"right\" valign=\"top\"><img width=48 src=\"%s\"></td>", classid);
			em_format_add_puri(emf, sizeof(EMFormatPURI), classid, part, efw_write_image);
			camel_object_unref(part);
		}

		if (have_icon && efw->show_icon) {
			GtkIconInfo *icon_info;
			char *classid;
			CamelMimePart *iconpart = NULL;

			classid = g_strdup_printf("icon:///em-format-html/%s/icon/header", emf->part_id->str);
			camel_stream_printf(stream, "<td align=\"right\" valign=\"top\"><img width=16 height=16 src=\"%s\"></td>", classid);

			icon_info = gtk_icon_theme_lookup_icon (
				gtk_icon_theme_get_default (),
				"evolution", 16, GTK_ICON_LOOKUP_NO_SVG);
			if (icon_info != NULL) {
				iconpart = em_format_webkit_file_part (
					(EMFormatWebKit *) emf, "image/png",
					gtk_icon_info_get_filename (icon_info));
				gtk_icon_info_free (icon_info);
			}

			if (iconpart) {
				em_format_add_puri(emf, sizeof(EMFormatPURI), classid, iconpart, efw_write_image);
				camel_object_unref(iconpart);
			}
			g_free(classid);
		}
		camel_stream_printf (stream, "</tr></table>\n</font>\n");
	}
}

static void efw_format_message(EMFormat *emf, CamelStream *stream, CamelMimePart *part, const EMFormatHandler *info)
{

	/* TODO: make this validity stuff a method */
	EMFormatWebKit *efw = (EMFormatWebKit *) emf;
	CamelCipherValidity *save = emf->valid, *save_parent = emf->valid_parent;

	emf->valid = NULL;
	emf->valid_parent = NULL;

	if (emf->message != (CamelMimeMessage *)part)
		camel_stream_printf(stream, "<blockquote>\n");

	if (!efw->hide_headers && emf->message != (CamelMimeMessage *)part)
		efw_format_headers(efw, stream, (CamelMedium *)part);

	camel_stream_printf(stream, EM_FORMAT_WEBKIT_VPAD);
	em_format_part(emf, stream, part);

	if (emf->message != (CamelMimeMessage *)part)
		camel_stream_printf(stream, "</blockquote>\n");

	camel_cipher_validity_free(emf->valid);

	emf->valid = save;
	emf->valid_parent = save_parent;
}

static void efw_format_source(EMFormat *emf, CamelStream *stream, CamelMimePart *part)
{
	CamelStreamFilter *filtered_stream;
	CamelMimeFilter *html_filter;
	CamelDataWrapper *dw = (CamelDataWrapper *)part;

	filtered_stream = camel_stream_filter_new_with_stream ((CamelStream *) stream);
	html_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(filtered_stream, html_filter);
	camel_object_unref(html_filter);

	camel_stream_write_string((CamelStream *)stream, "<table><tr><td><tt>");
	em_format_format_text(emf, (CamelStream *)filtered_stream, dw);
	camel_object_unref(filtered_stream);

	camel_stream_write_string(stream, "</tt></td></tr></table>");
}

static void
efw_format_attachment(EMFormat *emf, CamelStream *stream, CamelMimePart *part, const char *mime_type, const EMFormatHandler *handle)
{

	/* we display all inlined attachments only */

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

static gboolean
efw_busy(EMFormat *emf)
{
	return (((EMFormatWebKit *)emf)->priv->format_id != -1);
}

void
em_format_webkit_set_message_view (EMFormatWebKit *efw, struct _MailMessageView *mmv, GtkWidget *body)
{
	efw->msg_view = mmv;
	efw->body = body;
}
