/*
 * 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 <string.h>

#include <gtk/gtk.h>
#include <glib/gstdio.h>
#include <gdk/gdkkeysyms.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_gladedir (void) G_GNUC_CONST;
#endif

#include <glade/glade.h>

#include <glib/gi18n.h>

#include <camel/camel-stream.h>
#include <camel/camel-stream-filter.h>
#include <camel/camel-stream-mem.h>
#include <camel/camel-mime-filter-tohtml.h>
#include <camel/camel-mime-part.h>
#include <camel/camel-multipart.h>
#include <camel/camel-internet-address.h>
#include <camel/camel-mime-message.h>
#include <camel/camel-cipher-context.h>
#include <camel/camel-folder.h>
#include <camel/camel-string-utils.h>
#include <camel/camel-operation.h>

#include <misc/e-cursors.h>
#include <e-util/e-util.h>

#include <libedataserver/e-flag.h>
#include <libedataserver/e-msgport.h>
#ifdef EVOLUTION_2_28
#include <misc/e-gui-utils.h>
#else
#include <e-util/e-gui-utils.h>
#endif
#include <e-util/e-dialog-utils.h>

#ifdef HAVE_NSS
#include "certificate-viewer.h"
#include "e-cert-db.h"
#endif

#include "mail/mail-config.h"
#include "mail/mail-mt.h"
#include "em-format-webkit-display.h"
#ifdef EVOLUTION_2_26
#include "mail/em-marshal.h"
#else
#include <e-util/e-marshal.h>
#endif
//#include "mail/e-searching-tokenizer.h"
#include "mail/em-icon-stream.h"
#include "mail/em-utils.h"
#include "mail/em-popup.h"
#include <misc/e-attachment.h>
#include <misc/e-icon-entry.h>
#include "mail-message-view.h"
#include "mail-utils.h"

#ifdef G_OS_WIN32
/* Undefine the similar macro from <pthread.h>,it doesn't check if
 * localtime() returns NULL.
 */
#undef localtime_r

/* The localtime() in Microsoft's C library is MT-safe */
#define localtime_r(tp,tmp) (localtime(tp)?(*(tmp)=*localtime(tp),(tmp)):0)
#endif

#define d(x)

struct _EMFormatWebKitDisplayPrivate {
	/* For the interactive search dialogue */
	/* TODO: Should this be more subtle, like the mozilla one? */
	GtkHBox   *search_dialog;
	GtkWidget *search_entry;
	GtkWidget *search_entry_box;
	GtkWidget *search_matches_label;
	GtkWidget *search_case_check;
	char *search_text;
	int search_wrap;	/* are we doing a wrap search */
	gboolean search_active; /* if the search is active */

	/* for Attachment bar */
	GtkWidget *attachment_bar;
	GtkWidget *attachment_box;
	GtkWidget *label;
	GtkWidget *save_txt;
	GtkWidget *arrow;
	GtkWidget *forward;
	GtkWidget *down;
	GtkWidget *attachment_area;
	gboolean  show_bar;
	GHashTable *files;
	gboolean updated;
};

struct _preview_message_msg {
	MailMsg base;
	
	EMFormatWebKitPObject *pobject;
	EFlag *done;

	unsigned int allow_cancel:1;
	unsigned int result:1;
	unsigned int ismain:1;
};

static void efwd_draw_in_main_thread (EMFormatWebKitDisplay *efwd, EMFormatWebKitPObject *pobject);
#ifdef NOT_USED
static int efwd_html_button_press_event (GtkWidget *widget, GdkEventButton *event, EMFormatWebKitDisplay *efh);
#endif
//static void efwd_html_link_clicked (GtkHTML *html, const char *url, EMFormatWebKitDisplay *efwd);
//static void efwd_html_on_url (GtkHTML *html, const char *url, EMFormatWebKitDisplay *efwd);

static void efwd_attachment_frame(EMFormat *emf, CamelStream *stream, EMFormatPURI *puri);
static GtkWidget * efwd_attachment_image(EMFormatWebKit *efh, GtkWidget *eb, EMFormatWebKitPObject *pobject);

struct _attach_puri {
	EMFormatPURI puri;

	const EMFormatHandler *handle;

	const char *snoop_mime_type;
	char *mime_type;
	/* for the > and V buttons */
	GtkWidget *forward, *down;
	/* currently no way to correlate this data to the frame :( */
	//GtkHTML *frame;
	GtkWidget *child_box;
	CamelStream *output;
	unsigned int shown:1;
	unsigned int rendered:1;
	/* Embedded Frame */
	GtkWidget *html;
	EMFormatWebKitPObject *pobject;
	//GtkHTMLEmbedded *html;

	/* Attachment */
	EAttachment *attachment;

	/* image stuff */
	int fit_width;
	int fit_height;
	GtkImage *image;
	GtkWidget *event_box;

	/* Optional Text Mem Stream */
	CamelStreamMem *mstream;

	/* Signed / Encrypted */
        camel_cipher_validity_sign_t sign;
        camel_cipher_validity_encrypt_t encrypt;
};


//static void efwd_iframe_created(GtkHTML *html, GtkHTML *iframe, EMFormatWebKitDisplay *efh);
/*static void efwd_url_requested(GtkHTML *html, const char *url, GtkHTMLStream *handle, EMFormatWebKitDisplay *efh);
  static gboolean efwd_object_requested(GtkHTML *html, GtkHTMLEmbedded *eb, EMFormatWebKitDisplay *efh);*/

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

static const EMFormatHandler *efwd_find_handler(EMFormat *emf, const char *mime_type);
static void efwd_format_clone(EMFormat *, CamelFolder *folder, const char *, CamelMimeMessage *msg, EMFormat *);
static void efwd_format_error(EMFormat *emf, CamelStream *stream, const char *txt);
static void efwd_format_source(EMFormat *, CamelStream *, CamelMimePart *);
static void efwd_format_attachment(EMFormat *, CamelStream *, CamelMimePart *, const char *, const EMFormatHandler *);
/* static void efwd_format_optional(EMFormat *, CamelStream *, CamelMimePart *, CamelStream *);*/ 
static void efwd_format_secure(EMFormat *emf, CamelStream *stream, CamelMimePart *part, CamelCipherValidity *valid);
static void efwd_complete(EMFormat *);
gboolean efwd_mnemonic_show_bar (GtkWidget *widget, gboolean focus, GtkWidget *efwd);

/*static gboolean efwd_use_component(const char *mime_type);*/
static void efwd_builtin_init(EMFormatWebKitDisplayClass *efhc);

enum {
	EFHD_LINK_CLICKED,
	EFHD_POPUP_EVENT,
	EFHD_ON_URL,
	EFHD_LAST_SIGNAL,
};

static guint efwd_signals[EFHD_LAST_SIGNAL] = { 0 };

/* EMFormatHandler's for bonobo objects */
static GHashTable *efwd_bonobo_handlers;
static EMFormatWebKitClass *efwd_parent;
static EMFormatClass *efwd_format_class;

#if 0
static void
efwd_gtkhtml_realise(GtkHTML *html, EMFormatWebKitDisplay *efwd)
{
	GtkStyle *style;

	/* FIXME: does this have to be re-done every time we draw? */

	/* My favorite thing to do... muck around with colors so we respect people's stupid themes.
	   However, we only do this if we are rendering to the screen -- we ignore the theme
	   when we are printing. */
	style = gtk_widget_get_style((GtkWidget *)html);
	if (style) {
		int state = GTK_WIDGET_STATE(html);
		gushort r, g, b;

		r = style->fg[state].red >> 8;
		g = style->fg[state].green >> 8;
		b = style->fg[state].blue >> 8;		

		efwd->formathtml.header_colour = ((r<<16) | (g<< 8) | b) & 0xffffff;

		r = style->bg[state].red >> 8;
		g = style->bg[state].green >> 8;
		b = style->bg[state].blue >> 8;		

		efwd->formathtml.body_colour = ((r<<16) | (g<< 8) | b) & 0xffffff;

		r = style->dark[state].red >> 8;
		g = style->dark[state].green >> 8;
		b = style->dark[state].blue >> 8;

		efwd->formathtml.frame_colour = ((r<<16) | (g<< 8) | b) & 0xffffff;

		r = style->base[GTK_STATE_NORMAL].red >> 8;
		g = style->base[GTK_STATE_NORMAL].green >> 8;
		b = style->base[GTK_STATE_NORMAL].blue >> 8;

		efwd->formathtml.content_colour = ((r<<16) | (g<< 8) | b) & 0xffffff;

		r = style->text[state].red >> 8;
		g = style->text[state].green >> 8;
		b = style->text[state].blue >> 8;

		efwd->formathtml.text_colour = ((r<<16) | (g<< 8) | b) & 0xffffff;
#undef DARKER
	}
}

static void
efwd_gtkhtml_style_set(GtkHTML *html, GtkStyle *old, EMFormatWebKitDisplay *efwd)
{
	efwd_gtkhtml_realise(html, efwd);
	em_format_redraw((EMFormat *)efwd);
}
#endif

static void
efwd_init(GObject *o)
{
	EMFormatWebKitDisplay *efwd = (EMFormatWebKitDisplay *)o;
#define efh ((EMFormatWebKit *)efwd)

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

	//efwd->search_tok = (ESearchingTokenizer *)e_searching_tokenizer_new();
	//gtk_html_set_tokenizer (efh->html, (HTMLTokenizer *)efwd->search_tok);

	//g_signal_connect(efh->html, "realize", G_CALLBACK(efwd_gtkhtml_realise), o);
	//g_signal_connect(efh->html, "style-set", G_CALLBACK(efwd_gtkhtml_style_set), o);
	/* we want to convert url's etc */
	efh->text_html_flags |= CAMEL_MIME_FILTER_TOHTML_CONVERT_URLS | CAMEL_MIME_FILTER_TOHTML_CONVERT_ADDRESSES;
#undef efh

	//efwd->nobar = getenv("EVOLUTION_NO_BAR") != NULL;

	//efwd->priv->show_bar = FALSE;
	efwd->priv->files = NULL;
}

static void
efwd_finalise(GObject *o)
{
	EMFormatWebKitDisplay *efwd = (EMFormatWebKitDisplay *)o;

	/* check pending stuff */

	if (efwd->priv->files)
		g_hash_table_destroy(efwd->priv->files);

	g_free(efwd->priv->search_text);
	g_free(efwd->priv);

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

static gboolean
efwd_bool_accumulator(GSignalInvocationHint *ihint, GValue *out, const GValue *in, void *data)
{
	gboolean val = g_value_get_boolean(in);

	g_value_set_boolean(out, val);

	return !val;
}

static void
efwd_class_init(GObjectClass *klass)
{
	((EMFormatClass *)klass)->find_handler = efwd_find_handler;
	((EMFormatClass *)klass)->format_clone = efwd_format_clone;
	((EMFormatClass *)klass)->format_error = efwd_format_error;
	((EMFormatClass *)klass)->format_source = efwd_format_source;
	((EMFormatClass *)klass)->format_attachment = efwd_format_attachment;
	((EMFormatClass *)klass)->format_secure = efwd_format_secure;
	((EMFormatClass *)klass)->complete = efwd_complete;

	klass->finalize = efwd_finalise;

	efwd_signals[EFHD_LINK_CLICKED] =
		g_signal_new("link_clicked",
			     G_TYPE_FROM_CLASS(klass),
			     G_SIGNAL_RUN_LAST,
			     G_STRUCT_OFFSET(EMFormatWebKitDisplayClass, link_clicked),
			     NULL, NULL,
			     g_cclosure_marshal_VOID__POINTER,
			     G_TYPE_NONE, 1, G_TYPE_POINTER);

	efwd_signals[EFHD_POPUP_EVENT] =
		g_signal_new("popup_event",
			     G_TYPE_FROM_CLASS(klass),
			     G_SIGNAL_RUN_LAST,
			     G_STRUCT_OFFSET(EMFormatWebKitDisplayClass, popup_event),
			     efwd_bool_accumulator, NULL,
#ifdef EVOLUTION_2_26			      			     
			     em_marshal_BOOLEAN__BOXED_POINTER_POINTER,
#else
			     e_marshal_BOOLEAN__BOXED_POINTER_POINTER,
#endif			     
			     G_TYPE_BOOLEAN, 3,
			     GDK_TYPE_EVENT | G_SIGNAL_TYPE_STATIC_SCOPE,
			     G_TYPE_POINTER, G_TYPE_POINTER);

	efwd_signals[EFHD_ON_URL] =
		g_signal_new("on_url",
			     G_TYPE_FROM_CLASS(klass),
			     G_SIGNAL_RUN_LAST,
			     G_STRUCT_OFFSET(EMFormatWebKitDisplayClass, on_url),
			     NULL, NULL,
			     g_cclosure_marshal_VOID__STRING,
			     G_TYPE_NONE, 1,
			     G_TYPE_STRING);

	efwd_builtin_init((EMFormatWebKitDisplayClass *)klass);
}

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

	if (type == 0) {
		static const GTypeInfo info = {
			sizeof(EMFormatWebKitDisplayClass),
			NULL, NULL,
			(GClassInitFunc)efwd_class_init,
			NULL, NULL,
			sizeof(EMFormatWebKitDisplay), 0,
			(GInstanceInitFunc)efwd_init
		};
		efwd_parent = g_type_class_ref(em_format_webkit_get_type());
		efwd_format_class = g_type_class_ref(em_format_get_type());
		type = g_type_register_static(em_format_webkit_get_type(), "EMFormatWebKitDisplay", &info, 0);

		efwd_bonobo_handlers = g_hash_table_new(g_str_hash, g_str_equal);
	}

	return type;
}

#ifdef NOT_USED
static gboolean
efwd_scroll_event(GtkWidget *w, GdkEventScroll *event, EMFormatWebKitDisplay *efwd)
{
	if(event->state & GDK_CONTROL_MASK)
	{
		if(event->direction == GDK_SCROLL_UP)
		{
			//gtk_html_zoom_in (efwd->formathtml.html);
		}
		else if(event->direction == GDK_SCROLL_DOWN)
		{
			//gtk_html_zoom_out (efwd->formathtml.html);
		}
		return TRUE;
	}
	return FALSE;
}
#endif
EMFormatWebKitDisplay *em_format_webkit_display_new(void)
{
	EMFormatWebKitDisplay *efwd;

	efwd = g_object_new(em_format_webkit_display_get_type(), 0);

	//g_signal_connect(efwd->formathtml.html, "iframe_created", G_CALLBACK(efwd_iframe_created), efwd);
	//g_signal_connect(efwd->formathtml.html, "link_clicked", G_CALLBACK(efwd_html_link_clicked), efwd);
	//g_signal_connect(efwd->formathtml.html, "on_url", G_CALLBACK(efwd_html_on_url), efwd);
	//g_signal_connect(efwd->formathtml.html, "button_press_event", G_CALLBACK(efwd_html_button_press_event), efwd);
	//g_signal_connect(efwd->formathtml.html,"scroll_event", G_CALLBACK(efwd_scroll_event), efwd);

	return efwd;
}

void em_format_webkit_display_goto_anchor(EMFormatWebKitDisplay *efwd, const char *name)
{
	printf("FIXME: go to anchor '%s'\n", name);
}

void em_format_webkit_display_set_animate(EMFormatWebKitDisplay *efwd, gboolean state)
{
	efwd->animate = state;
	//gtk_html_set_animate(((EMFormatWebKit *)efwd)->html, state);
}

void em_format_webkit_display_set_caret_mode(EMFormatWebKitDisplay *efwd, gboolean state)
{
	efwd->caret_mode = state;
	//gtk_html_set_caret_mode(((EMFormatWebKit *)efwd)->html, state);
}

/*
EAttachmentBar *
em_format_webkit_display_get_bar (EMFormatWebKitDisplay *efwd)
{
	return E_ATTACHMENT_BAR (efwd->priv->attachment_bar);
}*/

void
em_format_webkit_display_set_search(EMFormatWebKitDisplay *efwd, int type, GSList *strings)
{
	switch(type&3) {
	case EM_FORMAT_WEBKIT_DISPLAY_SEARCH_PRIMARY:
		//e_searching_tokenizer_set_primary_case_sensitivity(efwd->search_tok, (type&EM_FORMAT_WEBKIT_DISPLAY_SEARCH_ICASE) == 0);
		//e_searching_tokenizer_set_primary_search_string(efwd->search_tok, NULL);
		while (strings) {
		//	e_searching_tokenizer_add_primary_search_string(efwd->search_tok, strings->data);
			strings = strings->next;
		}
		break;
	case EM_FORMAT_WEBKIT_DISPLAY_SEARCH_SECONDARY:
	default:
		//e_searching_tokenizer_set_secondary_case_sensitivity(efwd->search_tok, (type&EM_FORMAT_WEBKIT_DISPLAY_SEARCH_ICASE) == 0);
		//e_searching_tokenizer_set_secondary_search_string(efwd->search_tok, NULL);
		while (strings) {
		//	e_searching_tokenizer_add_secondary_search_string(efwd->search_tok, strings->data);
			strings = strings->next;
		}
		break;
	}

	d(printf("redrawing with search\n"));
	em_format_redraw((EMFormat *)efwd);
}

static void
efwd_update_matches(EMFormatWebKitDisplay *efwd)
{
	struct _EMFormatWebKitDisplayPrivate *p = efwd->priv;
	char *str;
	/* message-search popup match count string */
	char *fmt = _("Matches: %d");

	if (p->search_dialog) {
		str = alloca(strlen(fmt)+32);
	//	sprintf(str, fmt, e_searching_tokenizer_match_count(efwd->search_tok));
		gtk_label_set_text((GtkLabel *)p->search_matches_label, str);
	}
	gtk_widget_show((GtkWidget *)p->search_matches_label);

}

static void
efwd_update_search(EMFormatWebKitDisplay *efwd)
{
	struct _EMFormatWebKitDisplayPrivate *p = efwd->priv;
	GSList *words = NULL;
	int flags = 0;

	if (!gtk_toggle_button_get_active((GtkToggleButton *)p->search_case_check))
		flags = EM_FORMAT_WEBKIT_DISPLAY_SEARCH_ICASE | EM_FORMAT_WEBKIT_DISPLAY_SEARCH_PRIMARY;
	else
		flags = EM_FORMAT_WEBKIT_DISPLAY_SEARCH_PRIMARY;

	if (p->search_text)
		words = g_slist_append(words, p->search_text);

	em_format_webkit_display_set_search(efwd, flags, words);
	g_slist_free(words);
}

static void
efwd_search_response(GtkWidget *w, EMFormatWebKitDisplay *efwd)
{
	struct _EMFormatWebKitDisplayPrivate *p = efwd->priv;

	char *txt = g_strdup(gtk_entry_get_text((GtkEntry *)p->search_entry));

	g_strstrip(txt);
	if (p->search_text && strcmp(p->search_text, txt) == 0 && !p->search_wrap) {
		//gtk_html_engine_search_set_forward (((EMFormatWebKit *)efwd)->html, TRUE);
		//if (!gtk_html_engine_search_next(((EMFormatWebKit *)efwd)->html))
		//	p->search_wrap = TRUE;
		g_free(txt);
	} else {
		g_free(p->search_text);
		p->search_text = txt;
		if (!p->search_wrap)
			efwd_update_search(efwd);
		p->search_wrap = FALSE;
		//gtk_html_engine_search(((EMFormatWebKit *)efwd)->html, txt,
		//		       gtk_toggle_button_get_active((GtkToggleButton *)p->search_case_check),
		//		       TRUE, FALSE);
	}
}


static void
efwd_search_response_back (GtkWidget *w, EMFormatWebKitDisplay *efwd)
{
	struct _EMFormatWebKitDisplayPrivate *p = efwd->priv;

	char *txt = g_strdup(gtk_entry_get_text((GtkEntry *)p->search_entry));

	g_strstrip(txt);
	if (p->search_text && strcmp(p->search_text, txt) == 0 && !p->search_wrap) {
		//gtk_html_engine_search_set_forward (((EMFormatWebKit *)efwd)->html, FALSE);
		//if (!gtk_html_engine_search_next(((EMFormatWebKit *)efwd)->html))
		//	p->search_wrap = TRUE;
		g_free(txt);
	} else {
		g_free(p->search_text);
		p->search_text = txt;
		if (!p->search_wrap)
			efwd_update_search(efwd);
		p->search_wrap = FALSE;
		//gtk_html_engine_search(((EMFormatWebKit *)efwd)->html, txt,
		//		       gtk_toggle_button_get_active((GtkToggleButton *)p->search_case_check),
		//		       FALSE, FALSE);
	}
}


static void
efwd_search_destroy(GtkWidget *w, EMFormatWebKitDisplay *efwd)
{
	struct _EMFormatWebKitDisplayPrivate *p = efwd->priv;
	g_free(p->search_text);
	p->search_text = NULL;
	gtk_widget_hide((GtkWidget *)p->search_dialog);
	em_format_webkit_display_set_search(efwd, EM_FORMAT_WEBKIT_DISPLAY_SEARCH_PRIMARY, NULL);
	p->search_active = FALSE;
}

static void
efwd_search_case_toggled(GtkWidget *w, EMFormatWebKitDisplay *efwd)
{
	struct _EMFormatWebKitDisplayPrivate *p = efwd->priv;

	g_free(p->search_text);
	p->search_text = NULL;
	efwd_search_response(w, efwd);
}

static gboolean
efwd_key_pressed (GtkWidget *w, GdkEventKey *event, EMFormatWebKitDisplay *efwd)
{
	if (event->keyval == GDK_Escape){
		efwd_search_destroy (w, efwd);
		return TRUE;
	}
	return FALSE;
}

static void
clear_button_clicked_cb (GtkWidget *widget, gpointer dummy, EMFormatWebKitDisplay *efwd)
{
	struct _EMFormatWebKitDisplayPrivate *p = efwd->priv;

	gtk_entry_set_text (GTK_ENTRY (p->search_entry), "");

	g_signal_emit_by_name (p->search_entry, "activate", efwd);
}

/* Controlls the visibility of icon_entry's visibility */
static void
icon_entry_changed_cb (GtkWidget *widget, GtkWidget *clear_button)
{
	const char *text = gtk_entry_get_text (GTK_ENTRY (widget));

	if (text && *text)
		gtk_widget_show (clear_button);
	else
		gtk_widget_hide (clear_button);
}

GtkWidget *
em_format_webkit_get_search_dialog (EMFormatWebKitDisplay *efwd)
{
	struct _EMFormatWebKitDisplayPrivate *p = efwd->priv;
	GtkWidget *hbox2, *button3, *button2, *label1;
	GtkWidget *icon_entry, *clear_button;

	p->search_entry_box = gtk_hbox_new (FALSE, 0);

	label1 = gtk_label_new_with_mnemonic (_("Fin_d:"));
	gtk_widget_show (label1);
	gtk_box_pack_start ((GtkBox *)(p->search_entry_box), label1, FALSE, FALSE, 5);

	/* Icon entry */
	icon_entry = e_icon_entry_new ();
	p->search_entry = e_icon_entry_get_entry (E_ICON_ENTRY (icon_entry));
	gtk_label_set_mnemonic_widget (GTK_LABEL (label1), p->search_entry);
	gtk_widget_show (p->search_entry);
	clear_button = e_icon_entry_create_button ("gtk-clear");
	e_icon_entry_pack_widget (E_ICON_ENTRY (icon_entry), clear_button, FALSE);
	gtk_widget_show_all (icon_entry);
	gtk_widget_hide (clear_button);

	g_signal_connect (G_OBJECT (clear_button), "button-press-event", (GCallback) clear_button_clicked_cb, efwd);
	g_signal_connect (G_OBJECT (p->search_entry), "changed", (GCallback) icon_entry_changed_cb, clear_button);

	gtk_box_pack_start ((GtkBox *)(p->search_entry_box), icon_entry, FALSE, FALSE, 0);
//	gtk_box_pack_start ((GtkBox *)(p->search_entry_box), icon_entry, TRUE, TRUE, 0);

	hbox2 = gtk_hbox_new (FALSE, 0);
	gtk_box_pack_start ((GtkBox *)(hbox2), p->search_entry_box, FALSE, FALSE, 5);
//	gtk_box_pack_start ((GtkBox *)(hbox2), p->search_entry_box, TRUE, TRUE, 5);

	button3 = gtk_button_new_with_mnemonic (_("_Previous"));
	gtk_button_set_image (GTK_BUTTON (button3), GTK_WIDGET(gtk_image_new_from_stock(GTK_STOCK_GO_BACK, GTK_ICON_SIZE_BUTTON)));
	gtk_widget_show (button3);
	gtk_box_pack_start (GTK_BOX (hbox2), button3, FALSE, FALSE, 5);

	button2 = gtk_button_new_with_mnemonic (_("_Next"));
	gtk_button_set_image (GTK_BUTTON (button2), gtk_image_new_from_stock(GTK_STOCK_GO_FORWARD, GTK_ICON_SIZE_BUTTON));
	gtk_widget_show (button2);
	gtk_box_pack_start (GTK_BOX (hbox2), button2, FALSE, FALSE, 5);

	p->search_case_check = gtk_check_button_new_with_mnemonic (_("M_atch case"));
	gtk_widget_show (p->search_case_check);
	gtk_box_pack_start (GTK_BOX (hbox2), p->search_case_check, FALSE, FALSE, 0);

	p->search_matches_label = gtk_label_new ("");
	gtk_widget_show (p->search_matches_label);
	gtk_box_pack_start (GTK_BOX (hbox2), p->search_matches_label, TRUE, TRUE, 0);
	p->search_dialog = GTK_HBOX (hbox2);

	p->search_wrap = FALSE;

	g_signal_connect (p->search_entry, "activate", G_CALLBACK(efwd_search_response), efwd);
	g_signal_connect (p->search_entry, "key-press-event", G_CALLBACK(efwd_key_pressed), efwd);
	g_signal_connect (p->search_case_check, "toggled", G_CALLBACK(efwd_search_case_toggled), efwd);
	g_signal_connect (button2, "clicked", G_CALLBACK(efwd_search_response), efwd);
	g_signal_connect (button3, "clicked", G_CALLBACK(efwd_search_response_back), efwd);

	p->search_active = FALSE;

	efwd_update_matches(efwd);

	return (GtkWidget *)p->search_dialog;

}

static void
set_focus_cb (GtkWidget *window, GtkWidget *widget, EMFormatWebKitDisplay *efwd)
{
	struct _EMFormatWebKitDisplayPrivate *p = efwd->priv;
	GtkWidget *sbar = GTK_WIDGET (p->search_dialog);

	while (widget != NULL && widget != sbar) {
		widget = widget->parent;
    	}

	if (widget != sbar)
		efwd_search_destroy(widget, efwd);
}

/**
 * em_format_webkit_display_search:
 * @efwd:
 *
 * Run an interactive search dialogue.
 **/
void
em_format_webkit_display_search(EMFormatWebKitDisplay *efwd)
{
	struct _EMFormatWebKitDisplayPrivate *p = efwd->priv;

	if (p->search_dialog){
		GtkWidget *toplevel;

		gtk_widget_show (GTK_WIDGET (p->search_dialog));
		gtk_widget_grab_focus (p->search_entry);
		gtk_widget_show (p->search_entry_box);

		p->search_active = TRUE;

		toplevel = gtk_widget_get_toplevel (GTK_WIDGET (p->search_dialog));

		g_signal_connect (toplevel, "set-focus",
                                 G_CALLBACK (set_focus_cb), efwd);
	}

}
/**
 * em_format_webkit_display_search_with:
 * @efwd:
 *
 * Run an interactive search dialogue.
 **/
void
em_format_webkit_display_search_with (EMFormatWebKitDisplay *efwd, char *word)
{
	struct _EMFormatWebKitDisplayPrivate *p = efwd->priv;

	if (p->search_dialog){
		gtk_widget_show (GTK_WIDGET (p->search_dialog));
		p->search_active = TRUE;

		/* Set the query */
		gtk_entry_set_text (GTK_ENTRY (p->search_entry), word);
		gtk_widget_hide (p->search_entry_box);

		/* Trigger the search */
		g_signal_emit_by_name (p->search_entry, "activate", efwd);
	}
}

void
em_format_webkit_display_search_close (EMFormatWebKitDisplay *efwd)
{
	struct _EMFormatWebKitDisplayPrivate *p = efwd->priv;

	if (p->search_dialog && p->search_active)
		efwd_search_destroy(GTK_WIDGET (p->search_dialog), efwd);
}

void
em_format_webkit_display_cut (EMFormatWebKitDisplay *efwd)
{
	//gtk_html_cut (((EMFormatWebKit *) efwd)->html);
}

void
em_format_webkit_display_copy (EMFormatWebKitDisplay *efwd)
{
	//gtk_html_copy (((EMFormatWebKit *) efwd)->html);
}

void
em_format_webkit_display_paste (EMFormatWebKitDisplay *efwd)
{
	//gtk_html_paste (((EMFormatWebKit *) efwd)->html, FALSE);
}

void
em_format_webkit_display_zoom_in (EMFormatWebKitDisplay *efwd)
{
	//gtk_html_zoom_in (((EMFormatWebKit *) efwd)->html);
}

void
em_format_webkit_display_zoom_out (EMFormatWebKitDisplay *efwd)
{
	//gtk_html_zoom_out (((EMFormatWebKit *) efwd)->html);
}

void
em_format_webkit_display_zoom_reset (EMFormatWebKitDisplay *efwd)
{
	//gtk_html_zoom_reset (((EMFormatWebKit *) efwd)->html);
}

/* ********************************************************************** */
/*
static void
efwd_iframe_created(GtkHTML *html, GtkHTML *iframe, EMFormatWebKitDisplay *efh)
{
	d(printf("Iframe created %p ... \n", iframe));

	g_signal_connect(iframe, "button_press_event", G_CALLBACK (efwd_html_button_press_event), efh);

	return;
}*/
/*
static void
efwd_get_uri_puri (GtkWidget *html, GdkEventButton *event, EMFormatWebKitDisplay *efwd, char **uri, EMFormatPURI **puri)
{
	char *url, *img_url;

	g_return_if_fail (html != NULL);
	g_return_if_fail (GTK_IS_HTML (html));
	g_return_if_fail (efwd != NULL);

	if (event) {
		url = gtk_html_get_url_at (GTK_HTML (html), event->x, event->y);
		img_url = gtk_html_get_image_src_at (GTK_HTML (html), event->x, event->y);
	} else {
		url = gtk_html_get_cursor_url (GTK_HTML (html));
		img_url = gtk_html_get_cursor_image_src (GTK_HTML (html));
	}

	if (img_url) {
		if (!(strstr (img_url, "://") || g_ascii_strncasecmp (img_url, "cid:", 4) == 0)) {
			char *u = g_strconcat ("file://", img_url, NULL);
			g_free (img_url);
			img_url = u;
		}
	}

	if (puri) {
		if (url)
			*puri = em_format_find_puri ((EMFormat *)efwd, url);

		if (!*puri && img_url)
			*puri = em_format_find_puri ((EMFormat *)efwd, img_url);
	}

	if (uri) {
		*uri = NULL;
		if (img_url && g_ascii_strncasecmp (img_url, "cid:", 4) != 0) {
			if (url)
				*uri = g_strdup_printf ("%s\n%s", url, img_url);
			else {
				*uri = img_url;
				img_url = NULL;
			}
		} else {
			*uri = url;
			url = NULL;
		}
	}

	g_free (url);
	g_free (img_url);
}*/

#ifdef NOT_USED
static int
efwd_html_button_press_event (GtkWidget *widget, GdkEventButton *event, EMFormatWebKitDisplay *efwd)
{
	char *uri = NULL;
	EMFormatPURI *puri = NULL;
	gboolean res = FALSE;

	if (event->button != 3)
		return FALSE;

	d(printf("popup button pressed\n"));

	//efwd_get_uri_puri (widget, event, efwd, &uri, &puri);

	if (uri && !strncmp (uri, "##", 2)) {
		g_free (uri);
		return TRUE;
	}

	g_signal_emit((GtkObject *)efwd, efwd_signals[EFHD_POPUP_EVENT], 0, event, uri, puri?puri->part:NULL, &res);

	g_free (uri);

	return res;
}
#endif
gboolean
em_format_webkit_display_popup_menu (EMFormatWebKitDisplay *efwd)
{
	//GtkHTML *html;
	char *uri = NULL;
	EMFormatPURI *puri = NULL;
	gboolean res = FALSE;

	//html = efwd->formathtml.html;

	//efwd_get_uri_puri (GTK_WIDGET (html), NULL, efwd, &uri, &puri);

	g_signal_emit ((GtkObject *)efwd, efwd_signals[EFHD_POPUP_EVENT], 0, NULL, uri, puri?puri->part:NULL, &res);

	g_free (uri);

	return res;
}

/*
static void
efwd_html_link_clicked (GtkHTML *html, const char *url, EMFormatWebKitDisplay *efwd)
{
	d(printf("link clicked event '%s'\n", url));
	if (url && !strncmp(url, "##", 2)) {
		if (!strcmp (url, "##TO##"))
			if (!(((EMFormatWebKit *) efwd)->header_wrap_flags & EM_FORMAT_WEBKIT_HEADER_TO))
				((EMFormatWebKit *) efwd)->header_wrap_flags |= EM_FORMAT_WEBKIT_HEADER_TO;
			else
				((EMFormatWebKit *) efwd)->header_wrap_flags &= ~EM_FORMAT_WEBKIT_HEADER_TO;
		else if (!strcmp (url, "##CC##"))
			if (!(((EMFormatWebKit *) efwd)->header_wrap_flags & EM_FORMAT_WEBKIT_HEADER_CC))
				((EMFormatWebKit *) efwd)->header_wrap_flags |= EM_FORMAT_WEBKIT_HEADER_CC;
			else
				((EMFormatWebKit *) efwd)->header_wrap_flags &= ~EM_FORMAT_WEBKIT_HEADER_CC;
		else if (!strcmp (url, "##BCC##")) {
			if (!(((EMFormatWebKit *) efwd)->header_wrap_flags & EM_FORMAT_WEBKIT_HEADER_BCC))
				((EMFormatWebKit *) efwd)->header_wrap_flags |= EM_FORMAT_WEBKIT_HEADER_BCC;
			else
				((EMFormatWebKit *) efwd)->header_wrap_flags &= ~EM_FORMAT_WEBKIT_HEADER_BCC;
		}
		em_format_redraw((EMFormat *)efwd);
	} else
	    g_signal_emit((GObject *)efwd, efwd_signals[EFHD_LINK_CLICKED], 0, url);
}

static void
efwd_html_on_url (GtkHTML *html, const char *url, EMFormatWebKitDisplay *efwd)
{
	d(printf("on_url event '%s'\n", url));

	g_signal_emit((GObject *)efwd, efwd_signals[EFHD_ON_URL], 0, url);
}
*/
static void
efwd_complete(EMFormat *emf)
{
	EMFormatWebKitDisplay *efwd = (EMFormatWebKitDisplay *)emf;

	if (efwd->priv->search_dialog && efwd->priv->search_active)
		efwd_update_matches(efwd);

	
	if (efwd->priv->files) {
		g_hash_table_destroy (efwd->priv->files);
		efwd->priv->files = NULL;
	}
}

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

/* TODO: move the dialogue elsehwere */
/* FIXME: also in em-format-html.c */
static const struct {
	const char *icon, *shortdesc, *description;
} smime_sign_table[5] = {
	{ "stock_signature-bad", N_("Unsigned"), N_("This message is not signed. There is no guarantee that this message is authentic.") },
	{ "stock_signature-ok", N_("Valid signature"), N_("This message is signed and is valid meaning that it is very likely that this message is authentic.") },
	{ "stock_signature-bad", N_("Invalid signature"), N_("The signature of this message cannot be verified, it may have been altered in transit.") },
	{ "stock_signature", N_("Valid signature, but cannot verify sender"), N_("This message is signed with a valid signature, but the sender of the message cannot be verified.") },
	{ "stock_signature-bad", N_("Signature exists, but need public key"), N_("This message is signed with a signature, but there is no corresponding public key.") },

};

static const struct {
	const char *icon, *shortdesc, *description;
} smime_encrypt_table[4] = {
	{ "stock_lock-broken", N_("Unencrypted"), N_("This message is not encrypted. Its content may be viewed in transit across the Internet.") },
	{ "stock_lock-ok", N_("Encrypted, weak"), N_("This message is encrypted, but with a weak encryption algorithm. It would be difficult, but not impossible for an outsider to view the content of this message in a practical amount of time.") },
	{ "stock_lock-ok", N_("Encrypted"), N_("This message is encrypted.  It would be difficult for an outsider to view the content of this message.") },
	{ "stock_lock-ok", N_("Encrypted, strong"), N_("This message is encrypted, with a strong encryption algorithm. It would be very difficult for an outsider to view the content of this message in a practical amount of time.") },
};

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

struct _smime_pobject {
	EMFormatWebKitPObject object;

	int signature;
	CamelCipherValidity *valid;
	GtkWidget *widget;
};

static void
efwd_xpkcs7mime_free(EMFormatWebKitPObject *o)
{
	struct _smime_pobject *po = (struct _smime_pobject *)o;

	if (po->widget)
		gtk_widget_destroy(po->widget);
	camel_cipher_validity_free(po->valid);
}

static void
efwd_xpkcs7mime_info_response(GtkWidget *w, guint button, struct _smime_pobject *po)
{
	gtk_widget_destroy(w);
	po->widget = NULL;
}

#ifdef HAVE_NSS
static void
efwd_xpkcs7mime_viewcert_foad(GtkWidget *w, guint button, struct _smime_pobject *po)
{
	gtk_widget_destroy(w);
}

static void
efwd_xpkcs7mime_viewcert_clicked(GtkWidget *button, struct _smime_pobject *po)
{
	CamelCipherCertInfo *info = g_object_get_data((GObject *)button, "e-cert-info");
	ECertDB *db = e_cert_db_peek();
	ECert *ec = NULL;

	if (info->email)
		ec = e_cert_db_find_cert_by_email_address(db, info->email, NULL);

	if (ec == NULL && info->name)
		ec = e_cert_db_find_cert_by_nickname(db, info->name, NULL);

	if (ec != NULL) {
		GtkWidget *w = certificate_viewer_show(ec);

		/* oddly enough certificate_viewer_show doesn't ... */
		gtk_widget_show(w);
		g_signal_connect(w, "response", G_CALLBACK(efwd_xpkcs7mime_viewcert_foad), po);

		if (w && po->widget)
			gtk_window_set_transient_for((GtkWindow *)w, (GtkWindow *)po->widget);

		g_object_unref(ec);
	} else {
		g_warning("can't find certificate for %s <%s>", info->name?info->name:"", info->email?info->email:"");
	}
}
#endif

static void
efwd_xpkcs7mime_add_cert_table(GtkWidget *vbox, CamelDList *certlist, struct _smime_pobject *po)
{
	CamelCipherCertInfo *info = (CamelCipherCertInfo *)certlist->head;
	GtkTable *table = (GtkTable *)gtk_table_new(camel_dlist_length(certlist), 2, FALSE);
	int n = 0;

	while (info->next) {
		char *la = NULL;
		const char *l = NULL;

		if (info->name) {
			if (info->email && strcmp(info->name, info->email) != 0)
				l = la = g_strdup_printf("%s <%s>", info->name, info->email);
			else
				l = info->name;
		} else {
			if (info->email)
				l = info->email;
		}

		if (l) {
			GtkWidget *w;
#if defined(HAVE_NSS)
			ECertDB *db = e_cert_db_peek();
			ECert *ec = NULL;
#endif
			w = gtk_label_new(l);
			gtk_misc_set_alignment((GtkMisc *)w, 0.0, 0.5);
			g_free(la);
			gtk_table_attach(table, w, 0, 1, n, n+1, GTK_FILL, GTK_FILL, 3, 3);
#if defined(HAVE_NSS)
			w = gtk_button_new_with_mnemonic(_("_View Certificate"));
			gtk_table_attach(table, w, 1, 2, n, n+1, 0, 0, 3, 3);
			g_object_set_data((GObject *)w, "e-cert-info", info);
			g_signal_connect(w, "clicked", G_CALLBACK(efwd_xpkcs7mime_viewcert_clicked), po);

			if (info->email)
				ec = e_cert_db_find_cert_by_email_address(db, info->email, NULL);
			if (ec == NULL && info->name)
				ec = e_cert_db_find_cert_by_nickname(db, info->name, NULL);

			if (ec == NULL)
				gtk_widget_set_sensitive(w, FALSE);
			else
				g_object_unref(ec);
#else
			w = gtk_label_new (_("This certificate is not viewable"));
			gtk_table_attach(table, w, 1, 2, n, n+1, 0, 0, 3, 3);
#endif
			n++;
		}

		info = info->next;
	}

	gtk_box_pack_start((GtkBox *)vbox, (GtkWidget *)table, TRUE, TRUE, 6);
}

static void
efwd_xpkcs7mime_validity_clicked(GtkWidget *button, EMFormatWebKitPObject *pobject)
{
	struct _smime_pobject *po = (struct _smime_pobject *)pobject;
	GladeXML *xml;
	GtkWidget *vbox, *w;
	char *gladefile;

	if (po->widget)
		/* FIXME: window raise? */
		return;
	gladefile = g_build_filename (
#ifndef _WIN32
#ifdef EVOLUTION_2_26
				      EVOLUTION226_PRIVDATADIR"glade/",
#else
				      EVOLUTION228_PRIVDATADIR"glade/",
#endif
#else
				      _e_get_gladedir (),
#endif
				      "mail-dialogs.glade",
				      NULL);
	xml = glade_xml_new(gladefile, "message_security_dialog", NULL);
	g_free (gladefile);

	po->widget = glade_xml_get_widget(xml, "message_security_dialog");

	vbox = glade_xml_get_widget(xml, "signature_vbox");
	w = gtk_label_new (_(smime_sign_table[po->valid->sign.status].description));
	gtk_misc_set_alignment((GtkMisc *)w, 0.0, 0.5);
	gtk_label_set_line_wrap((GtkLabel *)w, TRUE);
	gtk_box_pack_start((GtkBox *)vbox, w, TRUE, TRUE, 6);
	if (po->valid->sign.description) {
		GtkTextBuffer *buffer;

		buffer = gtk_text_buffer_new(NULL);
		gtk_text_buffer_set_text(buffer, po->valid->sign.description, strlen(po->valid->sign.description));
		w = g_object_new(gtk_scrolled_window_get_type(),
				 "hscrollbar_policy", GTK_POLICY_AUTOMATIC,
				 "vscrollbar_policy", GTK_POLICY_AUTOMATIC,
				 "shadow_type", GTK_SHADOW_IN,
				 "child", g_object_new(gtk_text_view_get_type(),
						       "buffer", buffer,
						       "cursor_visible", FALSE,
						       "editable", FALSE,
						       "width_request", 500,
						       "height_request", 160,
						       NULL),
				 NULL);
		g_object_unref(buffer);

		gtk_box_pack_start((GtkBox *)vbox, w, TRUE, TRUE, 6);
	}

	if (!camel_dlist_empty(&po->valid->sign.signers))
		efwd_xpkcs7mime_add_cert_table(vbox, &po->valid->sign.signers, po);

	gtk_widget_show_all(vbox);

	vbox = glade_xml_get_widget(xml, "encryption_vbox");
	w = gtk_label_new(_(smime_encrypt_table[po->valid->encrypt.status].description));
	gtk_misc_set_alignment((GtkMisc *)w, 0.0, 0.5);
	gtk_label_set_line_wrap((GtkLabel *)w, TRUE);
	gtk_box_pack_start((GtkBox *)vbox, w, TRUE, TRUE, 6);
	if (po->valid->encrypt.description) {
		GtkTextBuffer *buffer;

		buffer = gtk_text_buffer_new(NULL);
		gtk_text_buffer_set_text(buffer, po->valid->encrypt.description, strlen(po->valid->encrypt.description));
		w = g_object_new(gtk_scrolled_window_get_type(),
				 "hscrollbar_policy", GTK_POLICY_AUTOMATIC,
				 "vscrollbar_policy", GTK_POLICY_AUTOMATIC,
				 "shadow_type", GTK_SHADOW_IN,
				 "child", g_object_new(gtk_text_view_get_type(),
						       "buffer", buffer,
						       "cursor_visible", FALSE,
						       "editable", FALSE,
						       "width_request", 500,
						       "height_request", 160,
						       NULL),
				 NULL);
		g_object_unref(buffer);

		gtk_box_pack_start((GtkBox *)vbox, w, TRUE, TRUE, 6);
	}

	if (!camel_dlist_empty(&po->valid->encrypt.encrypters))
		efwd_xpkcs7mime_add_cert_table(vbox, &po->valid->encrypt.encrypters, po);

	gtk_widget_show_all(vbox);

	g_object_unref(xml);

	g_signal_connect(po->widget, "response", G_CALLBACK(efwd_xpkcs7mime_info_response), po);
	gtk_widget_show(po->widget);
}

static GtkWidget *
efwd_xpkcs7mime_button(EMFormatWebKit *efh, GtkWidget * eb, EMFormatWebKitPObject *pobject)
{
	GtkWidget *icon, *button, *box, *label;
	struct _smime_pobject *po = (struct _smime_pobject *)pobject;
	const char *icon_name;

	/* FIXME: need to have it based on encryption and signing too */
	if (po->valid->sign.status != 0)
		icon_name = smime_sign_table[po->valid->sign.status].icon;
	else
		icon_name = smime_encrypt_table[po->valid->encrypt.status].icon;

	icon = gtk_image_new_from_icon_name (
		icon_name, GTK_ICON_SIZE_LARGE_TOOLBAR);
	gtk_widget_show(icon);

	button = gtk_button_new();
	g_signal_connect(button, "clicked", G_CALLBACK(efwd_xpkcs7mime_validity_clicked), pobject);

	gtk_container_add((GtkContainer *)button, icon);
	gtk_widget_show(button);
	box = gtk_hbox_new (FALSE, 0);
	gtk_box_pack_start ((GtkBox *)box, button, FALSE, FALSE, 6);
	gtk_box_pack_start ((GtkBox *)eb, box, FALSE, FALSE, 0);

	if (po->valid->sign.status != CAMEL_CIPHER_VALIDITY_SIGN_NONE) {
		label = gtk_label_new(_(smime_sign_table[po->valid->sign.status].shortdesc));
		gtk_box_pack_start ((GtkBox *)box, label, FALSE, FALSE, 3);
	}

	if (po->valid->encrypt.status != CAMEL_CIPHER_VALIDITY_ENCRYPT_NONE) {
		 /* FIXME: Make way to show both these text in the next line */
		/* if (po->valid->sign.status != CAMEL_CIPHER_VALIDITY_SIGN_NONE) {
			camel_stream_printf (stream, "<br>");
		}*/
		label = gtk_label_new(_(smime_encrypt_table[po->valid->encrypt.status].shortdesc));
		gtk_box_pack_start ((GtkBox *)box, label, FALSE, FALSE, 3);
	}

	gtk_widget_show_all(box);
	return NULL;
}

static void
efwd_format_secure(EMFormat *emf, CamelStream *stream, CamelMimePart *part, CamelCipherValidity *valid)
{
	/* Note: We call EMFormatClass directly, not EMFormatWebKit, our parent */
	efwd_format_class->format_secure(emf, stream, part, valid);

	if (emf->valid == valid
	    && (valid->encrypt.status != CAMEL_CIPHER_VALIDITY_ENCRYPT_NONE
		|| valid->sign.status != CAMEL_CIPHER_VALIDITY_SIGN_NONE)) {
		char *classid;
		struct _smime_pobject *pobj;

		classid = g_strdup_printf("smime:///em-format-html/%s/icon/signed", emf->part_id->str);
		pobj = (struct _smime_pobject *)em_format_webkit_add_pobject((EMFormatWebKit *)emf, sizeof(*pobj), classid, part, efwd_xpkcs7mime_button);
		pobj->valid = camel_cipher_validity_clone(valid);
		pobj->object.free = efwd_xpkcs7mime_free;
		pobj->object.body = mail_message_view_get_body(stream);
		efwd_draw_in_main_thread ((EMFormatWebKitDisplay *)emf, (EMFormatWebKitPObject *)pobj);
		g_free(classid);
	}
}

static void
efwd_image(EMFormatWebKit *efh, CamelStream *stream, CamelMimePart *part, EMFormatHandler *handle)
{
	char *classid;
	struct _attach_puri *info;
	EMFormatWebKitPObject *pobject;

	classid = g_strdup_printf("image%s", ((EMFormat *)efh)->part_id->str);
	info = (struct _attach_puri *)em_format_add_puri((EMFormat *)efh, sizeof(*info), classid, part, efwd_attachment_frame);
	pobject = em_format_webkit_add_pobject(efh, sizeof(EMFormatWebKitPObject), classid, part, efwd_attachment_image);

	info->handle = handle;
	info->shown = TRUE;
	info->rendered = TRUE;
	info->snoop_mime_type = ((EMFormat *) efh)->snoop_mime_type;
	if (camel_operation_cancel_check (NULL) || !info->puri.format || !((EMFormatWebKit *)info->puri.format)->msg_view) {
		/* some fake value, we are cancelled anyway, thus doesn't matter */
		info->fit_width = 256;
	} else {
		info->fit_width = ((GtkWidget *)((EMFormatWebKit *)info->puri.format)->msg_view)->allocation.width - 12;
	}

	info->pobject = pobject;
	pobject->body = mail_message_view_get_body(stream);
	efwd_draw_in_main_thread ((EMFormatWebKitDisplay *)efh, pobject);
	

	//camel_stream_printf(stream, "<td><object classid=\"%s\"></object></td>", classid);
	g_free(classid);
}

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

static EMFormatHandler type_builtin_table[] = {
	{ "image/gif", (EMFormatFunc)efwd_image },
	{ "image/jpeg", (EMFormatFunc)efwd_image },
	{ "image/png", (EMFormatFunc)efwd_image },
	{ "image/x-png", (EMFormatFunc)efwd_image },
	{ "image/tiff", (EMFormatFunc)efwd_image },
	{ "image/x-bmp", (EMFormatFunc)efwd_image },
	{ "image/bmp", (EMFormatFunc)efwd_image },
	{ "image/svg", (EMFormatFunc)efwd_image },
	{ "image/x-cmu-raster", (EMFormatFunc)efwd_image },
	{ "image/x-ico", (EMFormatFunc)efwd_image },
	{ "image/x-portable-anymap", (EMFormatFunc)efwd_image },
	{ "image/x-portable-bitmap", (EMFormatFunc)efwd_image },
	{ "image/x-portable-graymap", (EMFormatFunc)efwd_image },
	{ "image/x-portable-pixmap", (EMFormatFunc)efwd_image },
	{ "image/x-xpixmap", (EMFormatFunc)efwd_image },

	/* 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)efwd_image },
	{ "image/pjpeg", (EMFormatFunc)efwd_image },

	{ "x-evolution/message/prefix", (EMFormatFunc)efwd_message_prefix },

};

static void
efwd_builtin_init(EMFormatWebKitDisplayClass *efhc)
{
	int i;

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

/* ********************************************************************** */
 	 
	  	 
	 /* ********************************************************************** */
static const EMFormatHandler *efwd_find_handler(EMFormat *emf, const char *mime_type)
{
	  	 
	return ((EMFormatClass *)efwd_parent)->find_handler(emf, mime_type);
}

static void efwd_format_clone(EMFormat *emf, CamelFolder *folder, const char *uid, CamelMimeMessage *msg, EMFormat *src)
{
	EMFormatWebKitDisplay *efwd = (EMFormatWebKitDisplay *) emf;
	if (emf != src) {
		if (src)
			efwd->priv->show_bar = ((EMFormatWebKitDisplay *)src)->priv->show_bar;
		else
			efwd->priv->show_bar = FALSE;
		((EMFormatWebKit *) emf)->header_wrap_flags = 0;
	}

	((EMFormatClass *)efwd_parent)->format_clone(emf, folder, uid, msg, src);
}

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

	/* TODO: identical to efh_write_image */
	d(printf("writing image '%s'\n", puri->cid));
	camel_data_wrapper_decode_to_stream(dw, stream);
	camel_stream_close(stream);
}

static void efwd_message_prefix(EMFormat *emf, CamelStream *stream, CamelMimePart *part, EMFormatHandler *info)
{
	const char *flag, *comp, *due;
	time_t date;
	char due_date[128];
	struct tm due_tm;
	char *iconpath;

	if (emf->folder == NULL || emf->uid == NULL
	    || (flag = camel_folder_get_message_user_tag(emf->folder, emf->uid, "follow-up")) == NULL
	    || flag[0] == 0)
		return;

	/* header displayed for message-flags in mail display */
	camel_stream_printf(stream, "<table border=1 width=\"100%%\" cellspacing=2 cellpadding=2><tr>");

	comp = camel_folder_get_message_user_tag(emf->folder, emf->uid, "completed-on");

	iconpath = mail_utils_get_icon_path (comp && comp[0] ? "stock_flag-for-followup-done" : "stock_flag-for-followup", GTK_ICON_SIZE_MENU);
	if (iconpath) {
		CamelMimePart *iconpart;

		iconpart = em_format_webkit_file_part((EMFormatWebKit *)emf, "image/png", iconpath);
		g_free (iconpath);
		if (iconpart) {
			char *classid;

			classid = g_strdup_printf("icon:///em-format-html-display/%s/%s", emf->part_id->str, comp&&comp[0]?"comp":"uncomp");
			camel_stream_printf(stream, "<td align=\"left\"><img src=\"%s\"></td>", classid);
			(void)em_format_add_puri(emf, sizeof(EMFormatPURI), classid, iconpart, efwd_write_image);
			g_free(classid);
			camel_object_unref(iconpart);
		}
	}

	camel_stream_printf(stream, "<td align=\"left\" width=\"100%%\">");

	if (comp && comp[0]) {
		date = camel_header_decode_date(comp, NULL);
		localtime_r(&date, &due_tm);
		e_utf8_strftime_fix_am_pm(due_date, sizeof (due_date), _("Completed on %B %d, %Y, %l:%M %p"), &due_tm);
		camel_stream_printf(stream, "%s, %s", flag, due_date);
	} else if ((due = camel_folder_get_message_user_tag(emf->folder, emf->uid, "due-by")) != NULL && due[0]) {
		time_t now;

		date = camel_header_decode_date(due, NULL);
		now = time(NULL);
		if (now > date)
			camel_stream_printf(stream, "<b>%s</b>&nbsp;", _("Overdue:"));

		localtime_r(&date, &due_tm);
		e_utf8_strftime_fix_am_pm(due_date, sizeof (due_date), _("by %B %d, %Y, %l:%M %p"), &due_tm);
		camel_stream_printf(stream, "%s %s", flag, due_date);
	} else {
		camel_stream_printf(stream, "%s", flag);
	}

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

/* TODO: if these aren't going to do anything should remove */
static void efwd_format_error(EMFormat *emf, CamelStream *stream, const char *txt)
{
	((EMFormatClass *)efwd_parent)->format_error(emf, stream, txt);
}

static void efwd_format_source(EMFormat *emf, CamelStream *stream, CamelMimePart *part)
{
	((EMFormatClass *)efwd_parent)->format_source(emf, stream, part);
}

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

/* Checks on the widget whether it can be processed, based on the state of EMFormatWebKit.
   The widget should have set "efh" data as the EMFormatWebKit instance. */
static gboolean
efwd_can_process_attachment (GtkWidget *button)
{
	EMFormatWebKit *efh;

	if (!button)
		return FALSE;

	efh = g_object_get_data (G_OBJECT (button), "efh");

	return efh && efh->state != EM_FORMAT_WEBKIT_STATE_RENDERING;
}

struct _inline_render_msg {
	MailMsg base;

	struct _attach_puri *info;
};

static void
inline_render_exec (struct _inline_render_msg *m)
{
	struct _attach_puri *info = m->info;
	EMFormatWebKitPObject *pobj = info->pobject;

	camel_stream_printf (pobj->stream, "<HTML> <HEAD> </HEAD> <BODY>");

	info->handle->handler(info->puri.format, pobj->stream, info->puri.part, info->handle);
	camel_stream_printf (pobj->stream, "</BODY> </HTML>");
	camel_stream_close (pobj->stream);
	camel_object_unref(pobj->stream);
	pobj->stream = NULL;
}

static void
inline_render_free (struct _inline_render_msg *m)
{
}

static MailMsgInfo inline_render_info = {
	sizeof (struct _inline_render_msg),
	(MailMsgDescFunc) NULL,
	(MailMsgExecFunc) inline_render_exec,
	(MailMsgDoneFunc) NULL,
	(MailMsgFreeFunc) inline_render_free
};

static void
efwd_set_inline (struct _attach_puri *info)
{
	struct _inline_render_msg *m;

	m = mail_msg_new (&inline_render_info);
	m->info = info;
	mail_msg_unordered_push (m);
}

/* if it hasn't been processed yet, format the attachment */
static void
efwd_attachment_show(EPopup *ep, EPopupItem *item, void *data)
{
	struct _attach_puri *info = data;

	printf("show attachment button called %p:%d %d\n", info, info->shown, info->rendered);

	info->shown = ~info->shown;
	if (!info->shown)
		gtk_widget_hide (info->child_box);
	else
		gtk_widget_show (info->child_box);
//	em_format_set_inline(info->puri.format, info->puri.part_id, info->shown);
	if (!info->rendered && info->child_box) {
		efwd_set_inline(info);
		info->rendered = TRUE;
	}

}

static void
efwd_attachment_button_show(GtkWidget *w, void *data)
{
	if (!efwd_can_process_attachment (w))
		return;

	efwd_attachment_show(NULL, NULL, data);
}

static void
efwd_image_fit(EPopup *ep, EPopupItem *item, void *data)
{
	struct _attach_puri *info = data;

	info->fit_width = ((GtkWidget *)((EMFormatWebKit *)info->puri.format)->body)->allocation.width - 12;
	gtk_image_set_from_pixbuf(info->image, em_icon_stream_get_image(info->puri.cid, info->fit_width, info->fit_height));
}

static void
efwd_image_unfit(EPopup *ep, EPopupItem *item, void *data)
{
	struct _attach_puri *info = data;

	info->fit_width = 0;
	gtk_image_set_from_pixbuf((GtkImage *)info->image, em_icon_stream_get_image(info->puri.cid, info->fit_width, info->fit_height));
}

static EPopupItem efwd_menu_items[] = {
	{ E_POPUP_BAR, "05.display", },
	{ E_POPUP_ITEM, "05.display.00", N_("_View Inline"), efwd_attachment_show },
	{ E_POPUP_ITEM, "05.display.00", N_("_Hide"), efwd_attachment_show },
	{ E_POPUP_ITEM, "05.display.01", N_("_Fit to Width"), efwd_image_fit, NULL, NULL, EM_POPUP_PART_IMAGE },
	{ E_POPUP_ITEM, "05.display.01", N_("Show _Original Size"), efwd_image_unfit, NULL, NULL, EM_POPUP_PART_IMAGE },
};

static void
efwd_menu_items_free(EPopup *ep, GSList *items, void *data)
{
	g_slist_free(items);
}

static void
efwd_popup_place_widget(GtkMenu *menu, int *x, int *y, gboolean *push_in, gpointer user_data)
{
	GtkWidget *w = user_data;

	gdk_window_get_origin(gtk_widget_get_parent_window(w), x, y);
	*x += w->allocation.x + w->allocation.width;
	*y += w->allocation.y;
}

static gboolean
efwd_attachment_popup(GtkWidget *w, GdkEventButton *event, struct _attach_puri *info)
{
	GtkMenu *menu;
	GSList *menus = NULL;
	EMPopup *emp;
	EMPopupTargetPart *target;

	d(printf("attachment popup, button %d\n", event->button));

	if (event && event->button != 1 && event->button != 3) {
		/* ?? gtk_propagate_event(GTK_WIDGET (user_data), (GdkEvent *)event);*/
		return FALSE;
	}

	if (!efwd_can_process_attachment (w))
		return FALSE;

	/** @HookPoint-EMPopup: Attachment Button Context Menu
	 * @Id: org.gnome.evolution.mail.formathtmldisplay.popup
	 * @Class: org.gnome.evolution.mail.popup:1.0
	 * @Target: EMPopupTargetPart
	 *
	 * This is the drop-down menu shown when a user clicks on the down arrow
	 * of the attachment button in inline mail content.
	 */
	emp = em_popup_new("org.gnome.evolution.mail.formathtmldisplay.popup");
	target = em_popup_target_new_part(emp, info->puri.part, info->handle?info->handle->mime_type:NULL);
	target->target.widget = w;

	/* add our local menus */
	if (info->handle) {
		/* show/hide menus, only if we have an inline handler */
		menus = g_slist_prepend(menus, &efwd_menu_items[0]);
		menus = g_slist_prepend(menus, &efwd_menu_items[info->shown?2:1]);
		if (info->shown && info->image) {
			if (info->fit_width != 0) {
				if (em_icon_stream_is_resized(info->puri.cid, info->fit_width, info->fit_height))
				    menus = g_slist_prepend(menus, &efwd_menu_items[4]);
			} else
				menus = g_slist_prepend(menus, &efwd_menu_items[3]);
		}
	}

	e_popup_add_items((EPopup *)emp, menus, NULL, efwd_menu_items_free, info);

	menu = e_popup_create_menu_once((EPopup *)emp, (EPopupTarget *)target, 0);
	if (event)
		gtk_menu_popup(menu, NULL, NULL, NULL, NULL, event->button, event->time);
	else
		gtk_menu_popup(menu, NULL, NULL, (GtkMenuPositionFunc)efwd_popup_place_widget, w, 0, gtk_get_current_event_time());

	return TRUE;
}

static gboolean
efwd_image_popup(GtkWidget *w, GdkEventButton *event, struct _attach_puri *info)
{
	if (event && event->button != 3)
		return FALSE;

	return efwd_attachment_popup(w, event, info);
}

static gboolean
efwd_attachment_popup_menu(GtkWidget *w, struct _attach_puri *info)
{
	return efwd_attachment_popup(w, NULL, info);
}

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

static void
efwd_drag_data_get(GtkWidget *w, GdkDragContext *drag, GtkSelectionData *data, guint info, guint time, EMFormatWebKitPObject *pobject)
{
	CamelMimePart *part = pobject->part;
	char *uri, *uri_crlf, *path;
	CamelStream *stream;

	switch (info) {
	case 0: /* mime/type request */
		stream = camel_stream_mem_new();
		/* TODO: shoudl format_format_text run on the content-object? */
		/* TODO: should we just do format_content? */
		if (camel_content_type_is (((CamelDataWrapper *)part)->mime_type, "text", "*")) {
			/* FIXME: this should be an em_utils method, it only needs a default charset param */
			em_format_format_text((EMFormat *)pobject->format, stream, (CamelDataWrapper *)part);
		} else {
			CamelDataWrapper *dw = camel_medium_get_content_object((CamelMedium *)part);

			camel_data_wrapper_decode_to_stream(dw, stream);
		}

		gtk_selection_data_set(data, data->target, 8,
				       ((CamelStreamMem *)stream)->buffer->data,
				       ((CamelStreamMem *)stream)->buffer->len);
		camel_object_unref(stream);
		break;
	case 1: /* text-uri-list request */
		/* Kludge around Nautilus requesting the same data many times */
		uri = g_object_get_data((GObject *)w, "e-drag-uri");
		if (uri) {
			gtk_selection_data_set(data, data->target, 8, (unsigned char *)uri, strlen(uri));
			return;
		}

		path = em_utils_temp_save_part(w, part, FALSE);
		if (path == NULL)
			return;

		uri = g_filename_to_uri(path, NULL, NULL);
		g_free(path);
		uri_crlf = g_strconcat(uri, "\r\n", NULL);
		g_free(uri);
		gtk_selection_data_set(data, data->target, 8, (unsigned char *)uri_crlf, strlen(uri_crlf));
		g_object_set_data_full((GObject *)w, "e-drag-uri", uri_crlf, g_free);
		break;
	default:
		abort();
	}
}

static void
efwd_drag_data_delete(GtkWidget *w, GdkDragContext *drag, EMFormatWebKitPObject *pobject)
{
	char *uri;

	uri = g_object_get_data((GObject *)w, "e-drag-uri");
	if (uri) {
		/* NB: this doesn't kill the dnd directory */
		/* NB: is this ever called? */
		/* NB even more: doesn't the e-drag-uri have \r\n
		 * appended? (see efwd_drag_data_get())
		 */
		char *filename = g_filename_from_uri (uri, NULL, NULL);
		g_unlink(filename);
		g_free(filename);
		g_object_set_data((GObject *)w, "e-drag-uri", NULL);
	}
}

static void
efwd_write_icon_job(struct _EMFormatWebKitJob *job, int cancelled)
{
	EMFormatWebKitPObject *pobject;
	CamelDataWrapper *dw;

	if (cancelled)
		return;

	pobject = job->u.data;
	dw = camel_medium_get_content_object((CamelMedium *)pobject->part);
	camel_data_wrapper_decode_to_stream(dw, job->stream);
	camel_stream_close(job->stream);
}

static void
efwd_image_resized(GtkWidget *w, GtkAllocation *event, struct _attach_puri *info)
{
	GdkPixbuf *pb;
	int width = 500;

	if (info->fit_width == 0)
		return;

#warning "fix image width"
	//width = ((GtkWidget *)((EMFormatWebKit *)info->puri.format)->html)->allocation.width - 12;
	if (info->fit_width == width)
		return;
	info->fit_width = width;

	pb = em_icon_stream_get_image(info->puri.cid, info->fit_width, info->fit_height);
	if (pb) {
		gtk_image_set_from_pixbuf(info->image, pb);
		g_object_unref(pb);
	}
}

static void
efwd_change_cursor(GtkWidget *w, GdkEventCrossing *event, struct _attach_puri *info)
{
	if (info->shown && info->image) {
		if (info->fit_width != 0) {
			if (em_icon_stream_is_resized(info->puri.cid, info->fit_width, info->fit_height))
			    	e_cursor_set(w->window, E_CURSOR_ZOOM_IN);

		}
	}
}

static void
efwd_image_fit_width(GtkWidget *widget, GdkEventButton *event, struct _attach_puri *info)
{
	int width=500;

#warning "fix image width"
	//width = ((GtkWidget *)((EMFormatWebKit *)info->puri.format)->html)->allocation.width - 12;

	if (info->shown && info->image) {
		if (info->fit_width != 0) {
			if (em_icon_stream_is_resized(info->puri.cid, info->fit_width, info->fit_height)) {
				if(info->fit_width != width) {
					info->fit_width = width;
					e_cursor_set (widget->window, E_CURSOR_ZOOM_IN);
				} else {
					info->fit_width = 0;
					e_cursor_set(widget->window, E_CURSOR_ZOOM_OUT);
				}
			}
		} else {
			info->fit_width = width;
			e_cursor_set (widget->window, E_CURSOR_ZOOM_IN);
		}
	}

	gtk_image_set_from_pixbuf(info->image, em_icon_stream_get_image(info->puri.cid, info->fit_width, info->fit_height));
}

/* When the puri gets freed in the formatter thread and if the image is resized, crash will happen
   See bug #333864 So while freeing the puri, we disconnect the image attach resize attached with
   the puri */

static void
efwd_image_unallocate (struct _EMFormatPURI * puri)
{
	struct _attach_puri *info = (struct _attach_puri *) puri;
	g_signal_handlers_disconnect_by_func(info->html, efwd_image_resized, info);

	g_signal_handlers_disconnect_by_func(info->event_box, efwd_image_popup, info);
	g_signal_handlers_disconnect_by_func(info->event_box, efwd_change_cursor, info);
	g_signal_handlers_disconnect_by_func(info->event_box, efwd_attachment_popup_menu, info);
	g_signal_handlers_disconnect_by_func(info->event_box, efwd_image_fit_width, info);
}

static GtkWidget *
efwd_attachment_image(EMFormatWebKit *efh, GtkWidget *eb, EMFormatWebKitPObject *pobject)
{
	GtkWidget *box;
	EMFormatWebKitJob *job;
	struct _attach_puri *info;
	GdkPixbuf *pixbuf;
	GtkTargetEntry drag_types[] = {
		{ NULL, 0, 0 },
		{ "text/uri-list", 0, 1 },
	};
	char *simple_type;

	info = (struct _attach_puri *)em_format_find_puri((EMFormat *)efh, pobject->classid);

	info->image = (GtkImage *)gtk_image_new();
	info->html = eb;
	info->puri.free = efwd_image_unallocate;

	pixbuf = em_icon_stream_get_image(pobject->classid, info->fit_width, info->fit_height);
	if (pixbuf) {
		gtk_image_set_from_pixbuf(info->image, pixbuf);
		g_object_unref(pixbuf);
	} else {
		job = em_format_webkit_job_new(efh, efwd_write_icon_job, pobject);
		job->stream = (CamelStream *)em_icon_stream_new((GtkImage *)info->image, pobject->classid, info->fit_width, info->fit_height, TRUE);
		//em_format_webkit_job_queue(efh, job);
		/* FIXME:SRINI: This happens on main thread*/

		CamelDataWrapper *dw;
		dw = camel_medium_get_content_object((CamelMedium *)pobject->part);
		camel_data_wrapper_decode_to_stream(dw, job->stream);
		camel_stream_close(job->stream);
	}

	box = gtk_event_box_new();
	info->event_box = box;
	gtk_container_add((GtkContainer *)box, (GtkWidget *)info->image);
	gtk_widget_show_all(box);
	gtk_box_pack_start ((GtkBox *)eb, box, FALSE, FALSE, 0);
//	gtk_container_add((GtkContainer *)eb, box);

	g_signal_connect(eb, "size_allocate", G_CALLBACK(efwd_image_resized), info);

	simple_type = camel_content_type_simple(((CamelDataWrapper *)pobject->part)->mime_type);
	camel_strdown(simple_type);

	drag_types[0].target = simple_type;
	gtk_drag_source_set(box, GDK_BUTTON1_MASK, drag_types, sizeof(drag_types)/sizeof(drag_types[0]), GDK_ACTION_COPY);
	g_free(simple_type);

	g_signal_connect(box, "drag-data-get", G_CALLBACK(efwd_drag_data_get), pobject);
	g_signal_connect (box, "drag-data-delete", G_CALLBACK(efwd_drag_data_delete), pobject);

	g_signal_connect(box, "button_press_event", G_CALLBACK(efwd_image_popup), info);
	g_signal_connect(box, "enter-notify-event", G_CALLBACK(efwd_change_cursor), info);
	g_signal_connect(box, "popup_menu", G_CALLBACK(efwd_attachment_popup_menu), info);
	g_signal_connect(box, "button-press-event", G_CALLBACK(efwd_image_fit_width), info);

	g_object_set_data (G_OBJECT (box), "efh", efh);

	return NULL;
}
//#if 0
/* attachment button callback */
static GtkWidget *
efwd_attachment_button(EMFormatWebKit *efh, GtkWidget*eb, EMFormatWebKitPObject *pobject)
{
	struct _attach_puri *info;
	GtkWidget *hbox, *w, *button, *mainbox, *topbox;
	char *simple_type;
	GtkTargetEntry drag_types[] = {
		{ NULL, 0, 0 },
		{ "text/uri-list", 0, 1 },
	};
	AtkObject *a11y;
	char *txt;

	/* FIXME: handle default shown case */
	d(printf("adding attachment button/content\n"));

	info = (struct _attach_puri *)em_format_find_puri((EMFormat *)efh, pobject->classid);

	if (!info || info->forward) {
		g_warning ("unable to expand the attachment\n");
		return NULL;
	}
#if 0
	if (efwd->priv->attachment_bar) {
		file = camel_mime_part_get_filename(info->puri.part);

		new = info->attachment;

		if (!file) {
			file = "attachment.dat";
			new->file_name = g_strdup(file);
		}

		tmp = g_hash_table_lookup (efwd->priv->files, file);
		if (tmp) {
			guint count = GPOINTER_TO_UINT(tmp);
			char *ext;
			char *tmp_file = g_strdup (file);

			if ((ext = strrchr(tmp_file, '.'))) {
				ext[0] = 0;
				new_file = g_strdup_printf("%s(%d).%s", tmp_file, count++, ext+1);
			} else {
				new_file = g_strdup_printf("%s(%d)", tmp_file, count++);
			}

			g_free (tmp_file);
			g_hash_table_insert (efwd->priv->files, g_strdup(file), GUINT_TO_POINTER(count));
			g_free (new->file_name);
			new->file_name = new_file;
		} else {
			g_hash_table_insert (efwd->priv->files, g_strdup(file), GUINT_TO_POINTER(1));
		}

		/* Store the status of encryption / signature on the attachment for emblem display
		 * FIXME: May not work well always
		 */
		new->sign = info->sign;
		new->encrypt = info->encrypt;

		/* Add the attachment to the bar.*/
		e_attachment_bar_add_attachment_silent (E_ATTACHMENT_BAR(efwd->priv->attachment_bar), new);
		efwd_attachment_bar_refresh(efwd);
	}
#endif
	txt = em_format_describe_part(info->puri.part, info->mime_type);
	

	mainbox = gtk_hbox_new(FALSE, 0);
	
	button = gtk_label_new (NULL);
	gtk_widget_show (button);
	gtk_box_pack_start((GtkBox *)mainbox, button, FALSE, FALSE, 6);

	button = gtk_button_new();

	if (info->handle) {
		g_signal_connect(button, "clicked", G_CALLBACK(efwd_attachment_button_show), info);
		g_object_set_data (G_OBJECT (button), "efh", efh);
		topbox = gtk_vbox_new (FALSE, 0);
		gtk_widget_hide(topbox);
		info->child_box = topbox;
	} else {
		gtk_widget_set_sensitive(button, FALSE);
		GTK_WIDGET_UNSET_FLAGS(button, GTK_CAN_FOCUS);
		info->child_box = NULL;
	}

	hbox = gtk_hbox_new(FALSE, 2);
	info->forward = gtk_image_new_from_stock(GTK_STOCK_GO_FORWARD, GTK_ICON_SIZE_BUTTON);
	gtk_box_pack_start((GtkBox *)hbox, info->forward, TRUE, TRUE, 0);
	if (info->handle) {
		info->down = gtk_image_new_from_stock(GTK_STOCK_GO_DOWN, GTK_ICON_SIZE_BUTTON);
		gtk_box_pack_start((GtkBox *)hbox, info->down, TRUE, TRUE, 0);
	}

	w = gtk_image_new();
	gtk_widget_set_size_request(w, 24, 24);
	gtk_box_pack_start((GtkBox *)hbox, w, TRUE, TRUE, 0);
	gtk_container_add((GtkContainer *)button, hbox);
	gtk_box_pack_start((GtkBox *)mainbox, button, FALSE, FALSE, 0);

	/* Check for snooped type to get the right icon/processing */
	if (info->snoop_mime_type)
		simple_type = g_strdup(info->snoop_mime_type);
	else
		simple_type = camel_content_type_simple (((CamelDataWrapper *)pobject->part)->mime_type);
	camel_strdown(simple_type);

	/* FIXME: offline parts, just get icon */
	if (camel_content_type_is(((CamelDataWrapper *)pobject->part)->mime_type, "image", "*")) {
		EMFormatWebKitJob *job;
		GdkPixbuf *mini;
		char *key;

		key = pobject->classid;
		mini = em_icon_stream_get_image(key, 24, 24);
		if (mini) {
			d(printf("got image from cache '%s'\n", key));
			gtk_image_set_from_pixbuf((GtkImage *)w, mini);
			g_object_unref(mini);
		} else {
			d(printf("need to create icon image '%s'\n", key));
			job = em_format_webkit_job_new(efh, efwd_write_icon_job, pobject);
			job->stream = (CamelStream *)em_icon_stream_new((GtkImage *)w, key, 24, 24, FALSE);
			//em_format_webkit_job_queue(efh, job);
			/* FIXME:SRINI: This happens on main thread*/
			CamelDataWrapper *dw;

			dw = camel_medium_get_content_object((CamelMedium *)pobject->part);
			camel_data_wrapper_decode_to_stream(dw, job->stream);
			camel_stream_close(job->stream);			
		}
	} else {
/*
		if ((pixbuf = e_icon_for_mime_type (simple_type, 24))) {
			if ((mini = e_icon_factory_pixbuf_scale (pixbuf, 24, 24))) {
				gtk_image_set_from_pixbuf ((GtkImage *) w, mini);
				g_object_unref (mini);
			}
			g_object_unref (pixbuf);
		}*/
	}

	drag_types[0].target = simple_type;
	gtk_drag_source_set(button, GDK_BUTTON1_MASK, drag_types, sizeof(drag_types)/sizeof(drag_types[0]), GDK_ACTION_COPY);
	g_signal_connect(button, "drag-data-get", G_CALLBACK(efwd_drag_data_get), pobject);
	g_signal_connect (button, "drag-data-delete", G_CALLBACK(efwd_drag_data_delete), pobject);
	g_free(simple_type);

	button = gtk_button_new();
	/*GTK_WIDGET_UNSET_FLAGS(button, GTK_CAN_FOCUS);*/
	gtk_container_add((GtkContainer *)button, gtk_arrow_new(GTK_ARROW_DOWN, GTK_SHADOW_NONE));

	a11y = gtk_widget_get_accessible (button);
	atk_object_set_name (a11y, _("Attachment"));

	g_signal_connect(button, "button_press_event", G_CALLBACK(efwd_attachment_popup), info);
	g_signal_connect(button, "popup_menu", G_CALLBACK(efwd_attachment_popup_menu), info);
	g_signal_connect(button, "clicked", G_CALLBACK(efwd_attachment_popup_menu), info);
	gtk_box_pack_start((GtkBox *)mainbox, button, FALSE, FALSE, 0);

	g_object_set_data (G_OBJECT (button), "efh", efh);

	gtk_widget_show_all(mainbox);

	if (info->shown)
		gtk_widget_hide(info->forward);
	else if (info->down)
		gtk_widget_hide(info->down);
	
	w = gtk_label_new (txt);
	gtk_widget_show (w);
	gtk_box_pack_start ((GtkBox *)mainbox, w, FALSE, FALSE, 6);
	gtk_box_pack_start ((GtkBox *)eb, mainbox, FALSE, FALSE, 0);
	if (info->child_box)
		gtk_box_pack_start ((GtkBox *)eb, info->child_box, FALSE, FALSE, 0);

	//gtk_container_add((GtkContainer *)eb, mainbox);

	return info->child_box;
}
//#endif
/* not used currently */
/* frame source callback */
static void
efwd_attachment_frame(EMFormat *emf, CamelStream *stream, EMFormatPURI *puri)
{
	struct _attach_puri *info = (struct _attach_puri *)puri;

	if (info->shown) {
		d(printf("writing to frame content, handler is '%s'\n", info->handle->mime_type));
		info->handle->handler(emf, stream, info->puri.part, info->handle);
		camel_stream_close(stream);
	} else {
		/* FIXME: this is leaked if the object is closed without showing it
		   NB: need a virtual puri_free method? */
		info->output = stream;
		camel_object_ref(stream);
	}
}

#ifdef NOT_USED
static void
attachment_bar_arrow_clicked(GtkWidget *w, EMFormatWebKitDisplay *efwd)
{

	efwd->priv->show_bar = !efwd->priv->show_bar;

	if (efwd->priv->show_bar) {
		gtk_widget_show(efwd->priv->attachment_box);
		gtk_widget_show(efwd->priv->down);
		gtk_widget_hide(efwd->priv->forward);
	} else {
		gtk_widget_hide(efwd->priv->attachment_box);
		gtk_widget_show(efwd->priv->forward);
		gtk_widget_hide(efwd->priv->down);
	}
}

static void
attachments_save_all_clicked (GtkWidget *widget, EMFormatWebKitDisplay *efwd)
{
	GSList *attachment_parts=NULL;
	guint n_attachment_parts;

	//attachment_parts = e_attachment_bar_get_parts (
		//E_ATTACHMENT_BAR (efwd->priv->attachment_bar));
	n_attachment_parts = g_slist_length (attachment_parts);
	g_return_if_fail (n_attachment_parts > 0);

	if (n_attachment_parts == 1)
		em_utils_save_part (
			widget, _("Save attachment as"),
			attachment_parts->data);
	else
		em_utils_save_parts (
			widget, _("Select folder to save all attachments"),
			attachment_parts);

        g_slist_free (attachment_parts);
}

static GdkPixbuf *
scale_pixbuf (GdkPixbuf *pixbuf)
{
	int ratio, width, height;

	if (!pixbuf)
		return NULL;

	width = gdk_pixbuf_get_width (pixbuf);
	height = gdk_pixbuf_get_height (pixbuf);
	if (width >= height) {
		if (width > 48) {
			ratio = width / 48;
			width = 48;
			height = height / ratio;
			if (height == 0)
				height = 1;
		}
	} else {
		if (height > 48) {
			ratio = height / 48;
			height = 48;
			width = width / ratio;
			if (width == 0)
				width = 1;
		}
	}

	return e_icon_factory_pixbuf_scale (pixbuf, width, height);
}
#endif
static void
efwd_create_attachment_cache (EAttachment *attachment)
{

	CamelContentType *content_type;

#ifdef EVOLUTION_2_26
	if (!attachment->body)
#else
	if (!e_attachment_get_mime_part(attachment))
#endif		
		return;

#ifdef EVOLUTION_2_26
	content_type = camel_mime_part_get_content_type (attachment->body);
#else
	content_type = camel_mime_part_get_content_type (e_attachment_get_mime_part(attachment));
#endif	
	if (camel_content_type_is(content_type, "image", "*")) {
		CamelDataWrapper *wrapper;
		CamelStreamMem *mstream;
		GdkPixbufLoader *loader;
		gboolean error = TRUE;
#ifdef EVOLUTION_2_26
		wrapper = camel_medium_get_content_object (CAMEL_MEDIUM (attachment->body));
#else
		wrapper = camel_medium_get_content_object (CAMEL_MEDIUM (e_attachment_get_mime_part(attachment)));
#endif		
		mstream = (CamelStreamMem *) camel_stream_mem_new ();

		camel_data_wrapper_decode_to_stream (wrapper, (CamelStream *) mstream);

		/* Stream image into pixbuf loader */
		loader = gdk_pixbuf_loader_new ();
		error = !gdk_pixbuf_loader_write (loader, mstream->buffer->data, mstream->buffer->len, NULL);
		gdk_pixbuf_loader_close (loader, NULL);
/*
		if (!error) {
			pixbuf = gdk_pixbuf_loader_get_pixbuf (loader);
			attachment->pixbuf_cache = scale_pixbuf (pixbuf);
			pixbuf = attachment->pixbuf_cache;
			g_object_ref(pixbuf);
		} else {
			attachment->pixbuf_cache = NULL;
			g_warning ("GdkPixbufLoader Error");
		}
*/
		/* Destroy everything */
		g_object_unref (loader);
		camel_object_unref (mstream);
	}
}


static void
efwd_format_attachment(EMFormat *emf, CamelStream *stream, CamelMimePart *part, const char *mime_type, const EMFormatHandler *handle)
{
	char *classid;
	struct _attach_puri *info;
	EMFormatWebKitPObject *pobj;

	classid = g_strdup_printf("attachment%s", emf->part_id->str);
	info = (struct _attach_puri *)em_format_add_puri(emf, sizeof(*info), classid, part, efwd_attachment_frame);
	info->handle = handle;
	info->shown = em_format_is_inline(emf, info->puri.part_id, info->puri.part, handle);
	info->snoop_mime_type = emf->snoop_mime_type;
	info->mime_type = g_strdup (mime_type);
#ifdef EVOLUTION_2_26	
	info->attachment = e_attachment_new_from_mime_part (info->puri.part);
#else
	info->attachment = e_attachment_new ();
	e_attachment_set_mime_part (info->attachment, info->puri.part);
#endif	
	efwd_create_attachment_cache (info->attachment);
	if (emf->valid) {
		info->sign = emf->valid->sign.status;
		info->encrypt = emf->valid->encrypt.status;
	}

	pobj = em_format_webkit_add_pobject((EMFormatWebKit *)emf, sizeof(EMFormatWebKitPObject), classid, part, efwd_attachment_button);
	info->pobject = pobj;
	pobj->body = mail_message_view_get_body (stream);
	efwd_draw_in_main_thread ((EMFormatWebKitDisplay *)emf, pobj);
/*
	camel_stream_write_string(stream,
				  EM_FORMAT_WEBKIT_VPAD
				  "<table cellspacing=0 cellpadding=0><tr><td>"
				  "<table width=10 cellspacing=0 cellpadding=0>"
				  "<tr><td></td></tr></table></td>");

	camel_stream_printf(stream, "<td><object classid=\"%s\"></object></td>", classid);

	camel_stream_write_string(stream,
				  "<td><table width=3 cellspacing=0 cellpadding=0>"
				  "<tr><td></td></tr></table></td><td><font size=-1>");
*/
	/* output some info about it */
	/* FIXME: should we look up mime_type from object again? */
	//text = em_format_describe_part(part, mime_type);
/*	html = camel_text_to_html(text, ((EMFormatWebKit *)emf)->text_html_flags & CAMEL_MIME_FILTER_TOHTML_CONVERT_URLS, 0);
	camel_stream_write_string(stream, html);
	g_free(html);
	g_free(text);

	camel_stream_write_string(stream,
				  "</font></td></tr><tr></table>\n"
				  EM_FORMAT_WEBKIT_VPAD);
*/
	if (handle && pobj->view) {
		if (info->shown) {
			info->rendered = 1;
			camel_stream_printf (pobj->stream, "<HTML> <HEAD> </HEAD> <BODY BGCOLOR=\"#FFFFFF\">");

			handle->handler(emf, pobj->stream, part, handle);
			camel_stream_printf (pobj->stream, "</BODY> </HTML>");
			camel_stream_close (pobj->stream);
			camel_object_unref(pobj->stream);
			pobj->stream = NULL;
		} else
			info->rendered = 0;
         } 

	g_free(classid);
}

/* UI Threading */



static void preview_message_exec (struct _preview_message_msg *m);

static void
preview_message_exec (struct _preview_message_msg *m)
{
	EMFormatWebKitPObject *pobj = m->pobject;
	pobj->view = (gpointer) pobj->func(pobj->format, (gpointer)pobj->body, pobj);
	if (pobj->view) {
		pobj->stream = mail_message_view_create_webstream (mail_message_view_create_webview(((EMFormatWebKit *)pobj->format)->msg_view, pobj->view), pobj->view);
		gtk_widget_show_all (pobj->view);
	}
	e_flag_set (m->done);
}

static void
preview_message_free (struct _preview_message_msg *m)
{
	e_flag_free (m->done);
}

static MailMsgInfo preview_message_info = {
	sizeof (struct _preview_message_msg),
	(MailMsgDescFunc) NULL,
	(MailMsgExecFunc) preview_message_exec,
	(MailMsgDoneFunc) NULL,
	(MailMsgFreeFunc) preview_message_free
};

static void
efwd_draw_in_main_thread (EMFormatWebKitDisplay *efwd, EMFormatWebKitPObject *pobject)
{
	struct _preview_message_msg *m;

	m = mail_msg_new (&preview_message_info);
	m->ismain = mail_in_main_thread ();
	m->done = e_flag_new ();
	m->allow_cancel = TRUE;
	m->pobject = pobject;
	mail_msg_ref (m);
	if (m->ismain)
		preview_message_exec (m);
	else
		mail_msg_main_loop_push (m);

	if (TRUE) {
		e_flag_wait (m->done);
		mail_msg_unref (m);
	}

	if (m->ismain)
		mail_msg_unref (m);

	return;
}
