7ad82fe14260d54537d46ff753a69456ebec2714
[claws.git] / src / compose.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2001 Hiroyuki Yamamoto
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include "defs.h"
25
26 #include <glib.h>
27 #include <gdk/gdkkeysyms.h>
28 #include <gtk/gtkmain.h>
29 #include <gtk/gtkmenu.h>
30 #include <gtk/gtkmenuitem.h>
31 #include <gtk/gtkitemfactory.h>
32 #include <gtk/gtkcheckmenuitem.h>
33 #include <gtk/gtkoptionmenu.h>
34 #include <gtk/gtkwidget.h>
35 #include <gtk/gtkclist.h>
36 #include <gtk/gtkctree.h>
37 #include <gtk/gtkvpaned.h>
38 #include <gtk/gtkentry.h>
39 #include <gtk/gtkeditable.h>
40 #include <gtk/gtkwindow.h>
41 #include <gtk/gtksignal.h>
42 #include <gtk/gtkvbox.h>
43 #include <gtk/gtkcontainer.h>
44 #include <gtk/gtkhandlebox.h>
45 #include <gtk/gtktoolbar.h>
46 #include <gtk/gtktable.h>
47 #include <gtk/gtkhbox.h>
48 #include <gtk/gtklabel.h>
49 #include <gtk/gtkscrolledwindow.h>
50 #include <gtk/gtkthemes.h>
51 #include <gtk/gtkdnd.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <ctype.h>
56 #include <unistd.h>
57 #include <time.h>
58 /* #include <sys/utsname.h> */
59 #include <stdlib.h>
60 #include <sys/wait.h>
61 #include <signal.h>
62 #include <errno.h>
63
64 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
65 #  include <wchar.h>
66 #  include <wctype.h>
67 #endif
68
69
70 #include "gtkstext.h"
71
72 #include "intl.h"
73 #include "main.h"
74 #include "mainwindow.h"
75 #include "compose.h"
76 #include "addressbook.h"
77 #include "folderview.h"
78 #include "procmsg.h"
79 #include "menu.h"
80 #include "stock_pixmap.h"
81 #include "send.h"
82 #include "imap.h"
83 #include "news.h"
84 #include "customheader.h"
85 #include "prefs_common.h"
86 #include "prefs_account.h"
87 #include "account.h"
88 #include "filesel.h"
89 #include "procheader.h"
90 #include "procmime.h"
91 #include "statusbar.h"
92 #include "about.h"
93 #include "base64.h"
94 #include "codeconv.h"
95 #include "utils.h"
96 #include "gtkutils.h"
97 #include "socket.h"
98 #include "alertpanel.h"
99 #include "manage_window.h"
100 #include "gtkshruler.h"
101 #include "folder.h"
102 #include "addr_compl.h"
103 #include "quote_fmt.h"
104 #include "template.h"
105 #include "undo.h"
106 #include "foldersel.h"
107
108 #if USE_GPGME
109 #  include "rfc2015.h"
110 #endif
111
112 typedef enum
113 {
114         COL_MIMETYPE = 0,
115         COL_SIZE     = 1,
116         COL_NAME     = 2
117 } AttachColumnPos;
118
119 #define N_ATTACH_COLS           3
120
121 #define B64_LINE_SIZE           57
122 #define B64_BUFFSIZE            77
123
124 #define MAX_REFERENCES_LEN      999
125
126 static GdkColor quote_color = {0, 0, 0, 0xbfff};
127
128 static GList *compose_list = NULL;
129
130 Compose *compose_generic_new                    (PrefsAccount   *account,
131                                                  const gchar    *to,
132                                                  FolderItem     *item);
133
134 static Compose *compose_create                  (PrefsAccount   *account,
135                                                  ComposeMode     mode);
136 static void compose_toolbar_create              (Compose        *compose,
137                                                  GtkWidget      *container);
138 static GtkWidget *compose_account_option_menu_create
139                                                 (Compose        *compose);
140 static void compose_set_template_menu           (Compose        *compose);
141 static void compose_template_apply              (Compose        *compose,
142                                                  Template       *tmpl);
143 static void compose_destroy                     (Compose        *compose);
144
145 static void compose_entries_set                 (Compose        *compose,
146                                                  const gchar    *mailto);
147 static gint compose_parse_header                (Compose        *compose,
148                                                  MsgInfo        *msginfo);
149 static gchar *compose_parse_references          (const gchar    *ref,
150                                                  const gchar    *msgid);
151
152 static gchar *compose_quote_fmt                 (Compose        *compose,
153                                                  MsgInfo        *msginfo,
154                                                  const gchar    *fmt,
155                                                  const gchar    *qmark);
156
157 static void compose_reply_set_entry             (Compose        *compose,
158                                                  MsgInfo        *msginfo,
159                                                  gboolean        to_all,
160                                                  gboolean        to_sender,
161                                                  gboolean
162                                                  followup_and_reply_to);
163 static void compose_reedit_set_entry            (Compose        *compose,
164                                                  MsgInfo        *msginfo);
165 static void compose_insert_sig                  (Compose        *compose);
166 static void compose_insert_file                 (Compose        *compose,
167                                                  const gchar    *file);
168 static void compose_attach_append               (Compose        *compose,
169                                                  const gchar    *file,
170                                                  ContentType     cnttype);
171 static void compose_attach_append_with_type(Compose *compose,
172                                             const gchar *file,
173                                             const gchar *type,
174                                             ContentType cnttype);
175 static void compose_wrap_line                   (Compose        *compose);
176 static void compose_wrap_line_all               (Compose        *compose);
177 static void compose_set_title                   (Compose        *compose);
178
179 static PrefsAccount *compose_current_mail_account(void);
180 /* static gint compose_send                     (Compose        *compose); */
181 static gint compose_write_to_file               (Compose        *compose,
182                                                  const gchar    *file,
183                                                  gboolean        is_draft);
184 static gint compose_write_body_to_file          (Compose        *compose,
185                                                  const gchar    *file);
186 static gint compose_save_to_outbox              (Compose        *compose,
187                                                  const gchar    *file);
188 static gint compose_remove_reedit_target        (Compose        *compose);
189 static gint compose_queue                       (Compose        *compose,
190                                                  gint           *msgnum,
191                                                  FolderItem     **item);
192 static void compose_write_attach                (Compose        *compose,
193                                                  FILE           *fp);
194 static gint compose_write_headers               (Compose        *compose,
195                                                  FILE           *fp,
196                                                  const gchar    *charset,
197                                                  EncodingType    encoding,
198                                                  gboolean        is_draft);
199
200 static void compose_convert_header              (gchar          *dest,
201                                                  gint            len,
202                                                  gchar          *src,
203                                                  gint            header_len);
204 static void compose_generate_msgid              (Compose        *compose,
205                                                  gchar          *buf,
206                                                  gint            len);
207
208 static void compose_attach_info_free            (AttachInfo     *ainfo);
209 static void compose_attach_remove_selected      (Compose        *compose);
210
211 static void compose_attach_property             (Compose        *compose);
212 static void compose_attach_property_create      (gboolean       *cancelled);
213 static void attach_property_ok                  (GtkWidget      *widget,
214                                                  gboolean       *cancelled);
215 static void attach_property_cancel              (GtkWidget      *widget,
216                                                  gboolean       *cancelled);
217 static gint attach_property_delete_event        (GtkWidget      *widget,
218                                                  GdkEventAny    *event,
219                                                  gboolean       *cancelled);
220 static void attach_property_key_pressed         (GtkWidget      *widget,
221                                                  GdkEventKey    *event,
222                                                  gboolean       *cancelled);
223
224 static void compose_exec_ext_editor             (Compose           *compose);
225 static gint compose_exec_ext_editor_real        (const gchar       *file);
226 static gboolean compose_ext_editor_kill         (Compose           *compose);
227 static void compose_input_cb                    (gpointer           data,
228                                                  gint               source,
229                                                  GdkInputCondition  condition);
230 static void compose_set_ext_editor_sensitive    (Compose           *compose,
231                                                  gboolean           sensitive);
232
233 static void compose_undo_state_changed          (UndoMain       *undostruct,
234                                                  gint            undo_state,
235                                                  gint            redo_state,
236                                                  gpointer        data);
237
238 static gint calc_cursor_xpos    (GtkSText       *text,
239                                  gint            extra,
240                                  gint            char_width);
241
242 static void compose_create_header_entry (Compose *compose);
243 static void compose_add_header_entry    (Compose *compose, gchar *header, gchar *text);
244
245 /* callback functions */
246
247 static gboolean compose_edit_size_alloc (GtkEditable    *widget,
248                                          GtkAllocation  *allocation,
249                                          GtkSHRuler     *shruler);
250
251 static void toolbar_send_cb             (GtkWidget      *widget,
252                                          gpointer        data);
253 static void toolbar_send_later_cb       (GtkWidget      *widget,
254                                          gpointer        data);
255 static void toolbar_draft_cb            (GtkWidget      *widget,
256                                          gpointer        data);
257 static void toolbar_insert_cb           (GtkWidget      *widget,
258                                          gpointer        data);
259 static void toolbar_attach_cb           (GtkWidget      *widget,
260                                          gpointer        data);
261 static void toolbar_sig_cb              (GtkWidget      *widget,
262                                          gpointer        data);
263 static void toolbar_ext_editor_cb       (GtkWidget      *widget,
264                                          gpointer        data);
265 static void toolbar_linewrap_cb         (GtkWidget      *widget,
266                                          gpointer        data);
267 static void toolbar_address_cb          (GtkWidget      *widget,
268                                          gpointer        data);
269
270 static void select_account              (Compose        *compose,
271                                          PrefsAccount   *ac);
272
273 static void account_activated           (GtkMenuItem    *menuitem,
274                                          gpointer        data);
275
276 static void attach_selected             (GtkCList       *clist,
277                                          gint            row,
278                                          gint            column,
279                                          GdkEvent       *event,
280                                          gpointer        data);
281 static void attach_button_pressed       (GtkWidget      *widget,
282                                          GdkEventButton *event,
283                                          gpointer        data);
284 static void attach_key_pressed          (GtkWidget      *widget,
285                                          GdkEventKey    *event,
286                                          gpointer        data);
287
288 static void compose_send_cb             (gpointer        data,
289                                          guint           action,
290                                          GtkWidget      *widget);
291 static void compose_send_later_cb       (gpointer        data,
292                                          guint           action,
293                                          GtkWidget      *widget);
294
295 static void compose_draft_cb            (gpointer        data,
296                                          guint           action,
297                                          GtkWidget      *widget);
298
299 static void compose_attach_cb           (gpointer        data,
300                                          guint           action,
301                                          GtkWidget      *widget);
302 static void compose_insert_file_cb      (gpointer        data,
303                                          guint           action,
304                                          GtkWidget      *widget);
305
306 static void compose_close_cb            (gpointer        data,
307                                          guint           action,
308                                          GtkWidget      *widget);
309
310 static void compose_address_cb          (gpointer        data,
311                                          guint           action,
312                                          GtkWidget      *widget);
313 static void compose_template_activate_cb(GtkWidget      *widget,
314                                          gpointer        data);
315
316 static void compose_ext_editor_cb       (gpointer        data,
317                                          guint           action,
318                                          GtkWidget      *widget);
319
320 static gint compose_delete_cb           (GtkWidget      *widget,
321                                          GdkEventAny    *event,
322                                          gpointer        data);
323 static void compose_destroy_cb          (GtkWidget      *widget,
324                                          Compose        *compose);
325
326 static void compose_undo_cb             (Compose        *compose);
327 static void compose_redo_cb             (Compose        *compose);
328 static void compose_cut_cb              (Compose        *compose);
329 static void compose_copy_cb             (Compose        *compose);
330 static void compose_paste_cb            (Compose        *compose);
331 static void compose_allsel_cb           (Compose        *compose);
332
333 static void compose_grab_focus_cb       (GtkWidget      *widget,
334                                          Compose        *compose);
335
336 static void compose_changed_cb          (GtkEditable    *editable,
337                                          Compose        *compose);
338 static void compose_button_press_cb     (GtkWidget      *widget,
339                                          GdkEventButton *event,
340                                          Compose        *compose);
341 #if 0
342 static void compose_key_press_cb        (GtkWidget      *widget,
343                                          GdkEventKey    *event,
344                                          Compose        *compose);
345 #endif
346
347 #if 0
348 static void compose_toggle_to_cb        (gpointer        data,
349                                          guint           action,
350                                          GtkWidget      *widget);
351 static void compose_toggle_cc_cb        (gpointer        data,
352                                          guint           action,
353                                          GtkWidget      *widget);
354 static void compose_toggle_bcc_cb       (gpointer        data,
355                                          guint           action,
356                                          GtkWidget      *widget);
357 static void compose_toggle_replyto_cb   (gpointer        data,
358                                          guint           action,
359                                          GtkWidget      *widget);
360 static void compose_toggle_followupto_cb(gpointer        data,
361                                          guint           action,
362                                          GtkWidget      *widget);
363 static void compose_toggle_attach_cb    (gpointer        data,
364                                          guint           action,
365                                          GtkWidget      *widget);
366 #endif
367 static void compose_toggle_ruler_cb     (gpointer        data,
368                                          guint           action,
369                                          GtkWidget      *widget);
370 #if USE_GPGME
371 static void compose_toggle_sign_cb      (gpointer        data,
372                                          guint           action,
373                                          GtkWidget      *widget);
374 static void compose_toggle_encrypt_cb   (gpointer        data,
375                                          guint           action,
376                                          GtkWidget      *widget);
377 #endif
378 static void compose_toggle_return_receipt_cb(gpointer data, guint action,
379                                              GtkWidget *widget);
380
381 static void compose_attach_drag_received_cb (GtkWidget          *widget,
382                                              GdkDragContext     *drag_context,
383                                              gint                x,
384                                              gint                y,
385                                              GtkSelectionData   *data,
386                                              guint               info,
387                                              guint               time,
388                                              gpointer            user_data);
389 static void compose_insert_drag_received_cb (GtkWidget          *widget,
390                                              GdkDragContext     *drag_context,
391                                              gint                x,
392                                              gint                y,
393                                              GtkSelectionData   *data,
394                                              guint               info,
395                                              guint               time,
396                                              gpointer            user_data);
397
398 #if 0
399 static void to_activated                (GtkWidget      *widget,
400                                          Compose        *compose);
401 static void newsgroups_activated        (GtkWidget      *widget,
402                                          Compose        *compose);
403 static void subject_activated           (GtkWidget      *widget,
404                                          Compose        *compose);
405 static void cc_activated                (GtkWidget      *widget,
406                                          Compose        *compose);
407 static void bcc_activated               (GtkWidget      *widget,
408                                          Compose        *compose);
409 static void replyto_activated           (GtkWidget      *widget,
410                                          Compose        *compose);
411 static void followupto_activated        (GtkWidget      *widget,
412                                          Compose        *compose);
413 #endif
414
415 static void compose_attach_parts        (Compose        *compose,
416                                          MsgInfo        *msginfo);
417
418 static void compose_generic_reply(MsgInfo *msginfo, gboolean quote,
419                                   gboolean to_all,
420                                   gboolean ignore_replyto,
421                                   gboolean followup_and_reply_to);
422
423 void compose_headerentry_changed_cb        (GtkWidget          *entry,
424                                             ComposeHeaderEntry *headerentry);
425 void compose_headerentry_key_press_event_cb(GtkWidget          *entry,
426                                             GdkEventKey        *event,
427                                             ComposeHeaderEntry *headerentry);
428
429 static void compose_show_first_last_header (Compose *compose, gboolean show_first);
430
431 static void compose_ctl_enter_send_shortcut_cb(GtkWidget *w, Compose *compose);
432
433 static GtkItemFactoryEntry compose_popup_entries[] =
434 {
435         {N_("/_Add..."),        NULL, compose_attach_cb, 0, NULL},
436         {N_("/_Remove"),        NULL, compose_attach_remove_selected, 0, NULL},
437         {N_("/---"),            NULL, NULL, 0, "<Separator>"},
438         {N_("/_Property..."),   NULL, compose_attach_property, 0, NULL}
439 };
440
441 static GtkItemFactoryEntry compose_entries[] =
442 {
443         {N_("/_File"),                          NULL, NULL, 0, "<Branch>"},
444         {N_("/_File/_Attach file"),             "<control>M", compose_attach_cb,      0, NULL},
445         {N_("/_File/_Insert file"),             "<control>I", compose_insert_file_cb, 0, NULL},
446         {N_("/_File/Insert si_gnature"),        "<control>G", compose_insert_sig,     0, NULL},
447         {N_("/_File/---"),                      NULL, NULL, 0, "<Separator>"},
448         {N_("/_File/_Close"),                   "<alt>W", compose_close_cb, 0, NULL},
449
450         {N_("/_Edit"),             NULL, NULL, 0, "<Branch>"},
451         {N_("/_Edit/_Undo"),       "<control>Z", compose_undo_cb, 0, NULL},
452         {N_("/_Edit/_Redo"),       "<control>Y", compose_redo_cb, 0, NULL},
453         {N_("/_Edit/---"),         NULL, NULL, 0, "<Separator>"},
454         {N_("/_Edit/Cu_t"),        "<control>X", compose_cut_cb,    0, NULL},
455         {N_("/_Edit/_Copy"),       "<control>C", compose_copy_cb,   0, NULL},
456         {N_("/_Edit/_Paste"),      "<control>V", compose_paste_cb,  0, NULL},
457         {N_("/_Edit/Select _all"), "<control>A", compose_allsel_cb, 0, NULL},
458         {N_("/_Edit/---"),         NULL, NULL, 0, "<Separator>"},
459         {N_("/_Edit/_Wrap current paragraph"), "<alt>L", compose_wrap_line, 0, NULL},
460         {N_("/_Edit/Wrap all long _lines"),
461                         "<shift><alt>L", compose_wrap_line_all, 0, NULL},
462         {N_("/_Edit/Edit with e_xternal editor"),
463                         "<alt>X", compose_ext_editor_cb, 0, NULL},
464
465         {N_("/_Message"),               NULL, NULL, 0, "<Branch>"},
466         {N_("/_Message/_Send"),         "<control>Return",
467                                         compose_send_cb, 0, NULL},
468         {N_("/_Message/Send _later"),   "<shift><alt>S",
469                                         compose_send_later_cb,  0, NULL},
470         {N_("/_Message/Save to _draft folder"),
471                                         "<alt>D", compose_draft_cb, 0, NULL},
472 #if 0 /* NEW COMPOSE GUI */
473         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
474         {N_("/_Message/_To"),           NULL, compose_toggle_to_cb     , 0, "<ToggleItem>"},
475         {N_("/_Message/_Cc"),           NULL, compose_toggle_cc_cb     , 0, "<ToggleItem>"},
476         {N_("/_Message/_Bcc"),          NULL, compose_toggle_bcc_cb    , 0, "<ToggleItem>"},
477         {N_("/_Message/_Reply to"),     NULL, compose_toggle_replyto_cb, 0, "<ToggleItem>"},
478         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
479         {N_("/_Message/_Followup to"),  NULL, compose_toggle_followupto_cb, 0, "<ToggleItem>"},
480         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
481         {N_("/_Message/_Attach"),       NULL, compose_toggle_attach_cb, 0, "<ToggleItem>"},
482 #endif
483 #if USE_GPGME
484         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
485         {N_("/_Message/Si_gn"),         NULL, compose_toggle_sign_cb   , 0, "<ToggleItem>"},
486         {N_("/_Message/_Encrypt"),      NULL, compose_toggle_encrypt_cb, 0, "<ToggleItem>"},
487 #endif /* USE_GPGME */
488         {N_("/_Message/---"),           NULL,           NULL,   0, "<Separator>"},
489         {N_("/_Message/_Request Return Receipt"),       NULL, compose_toggle_return_receipt_cb, 0, "<ToggleItem>"},
490         {N_("/_Tool"),                  NULL, NULL, 0, "<Branch>"},
491         {N_("/_Tool/Show _ruler"),      NULL, compose_toggle_ruler_cb, 0, "<ToggleItem>"},
492         {N_("/_Tool/_Address book"),    "<alt>A", compose_address_cb , 0, NULL},
493         {N_("/_Tool/_Template"),        NULL, NULL, 0, "<Branch>"},
494         {N_("/_Help"),                  NULL, NULL, 0, "<LastBranch>"},
495         {N_("/_Help/_About"),           NULL, about_show, 0, NULL}
496 };
497
498 static GtkTargetEntry compose_mime_types[] =
499 {
500         {"text/uri-list", 0, 0}
501 };
502
503 Compose *compose_new(PrefsAccount *account)
504 {
505         return compose_generic_new(account, NULL, NULL);
506 }
507
508 Compose *compose_bounce(PrefsAccount *account, MsgInfo *msginfo)
509 {
510         Compose *c;
511         gchar *filename;
512         GtkItemFactory *ifactory;
513         
514         c = compose_generic_new(account, NULL, NULL);
515
516         filename = procmsg_get_message_file(msginfo);
517         if (filename == NULL)
518                 return NULL;
519
520         c->bounce_filename = filename;
521
522         if (msginfo->subject)
523                 gtk_entry_set_text(GTK_ENTRY(c->subject_entry),
524                                    msginfo->subject);
525         gtk_editable_set_editable(GTK_EDITABLE(c->subject_entry), FALSE);
526
527         compose_quote_fmt(c, msginfo, "%M", NULL);
528         gtk_editable_set_editable(GTK_EDITABLE(c->text), FALSE);
529
530         ifactory = gtk_item_factory_from_widget(c->popupmenu);
531         menu_set_sensitive(ifactory, "/Add...", FALSE);
532         menu_set_sensitive(ifactory, "/Remove", FALSE);
533         menu_set_sensitive(ifactory, "/Property...", FALSE);
534
535         ifactory = gtk_item_factory_from_widget(c->menubar);
536         menu_set_sensitive(ifactory, "/File/Insert file", FALSE);
537         menu_set_sensitive(ifactory, "/File/Attach file", FALSE);
538         menu_set_sensitive(ifactory, "/File/Insert signature", FALSE);
539         menu_set_sensitive(ifactory, "/Edit/Paste", FALSE);
540         menu_set_sensitive(ifactory, "/Edit/Wrap current paragraph", FALSE);
541         menu_set_sensitive(ifactory, "/Edit/Wrap all long lines", FALSE);
542         menu_set_sensitive(ifactory, "/Edit/Edit with external editor", FALSE);
543         menu_set_sensitive(ifactory, "/Message/Attach", FALSE);
544 #if USE_GPGME
545         menu_set_sensitive(ifactory, "/Message/Sign", FALSE);
546         menu_set_sensitive(ifactory, "/Message/Encrypt", FALSE);
547 #endif
548         menu_set_sensitive(ifactory, "/Message/Request Return Receipt", FALSE);
549         menu_set_sensitive(ifactory, "/Tool/Template", FALSE);
550         
551         gtk_widget_set_sensitive(c->insert_btn, FALSE);
552         gtk_widget_set_sensitive(c->attach_btn, FALSE);
553         gtk_widget_set_sensitive(c->sig_btn, FALSE);
554         gtk_widget_set_sensitive(c->exteditor_btn, FALSE);
555         gtk_widget_set_sensitive(c->linewrap_btn, FALSE);
556
557         return c;
558 }
559
560 Compose *compose_new_with_recipient(PrefsAccount *account, const gchar *mailto)
561 {
562         return compose_generic_new(account, mailto, NULL);
563 }
564
565 Compose *compose_new_with_folderitem(PrefsAccount *account, FolderItem *item)
566 {
567         return compose_generic_new(account, NULL, item);
568 }
569
570 Compose *compose_generic_new(PrefsAccount *account, const gchar *mailto, FolderItem *item)
571 {
572         Compose *compose;
573
574         if (item && item->prefs && item->prefs->enable_default_account)
575                 account = account_find_from_id(item->prefs->default_account);
576
577         if (!account) account = cur_account;
578         g_return_val_if_fail(account != NULL, NULL);
579
580         compose = compose_create(account, COMPOSE_NEW);
581         compose->replyinfo = NULL;
582
583         if (prefs_common.auto_sig)
584                 compose_insert_sig(compose);
585         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
586         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
587
588         if (account->protocol != A_NNTP) {
589                 if (mailto) {
590                         compose_entries_set(compose, mailto);
591
592                 } else if(item && item->prefs->enable_default_to) {
593                         compose_entry_append(compose, item->prefs->default_to, COMPOSE_TO);
594                 }
595                 if (item && item->ret_rcpt) {
596                         GtkItemFactory *ifactory;
597                 
598                         ifactory = gtk_item_factory_from_widget(compose->menubar);
599                         menu_set_toggle(ifactory, "/Message/Request Return Receipt", TRUE);
600                 }
601         } else {
602                 if (mailto) {
603                         compose_entry_append(compose, mailto, COMPOSE_NEWSGROUPS);
604                 }
605         }
606         compose_show_first_last_header(compose, TRUE);
607
608         /* Set save folder */
609         if(item && item->prefs && item->prefs->save_copy_to_folder) {
610                 gchar *folderidentifier;
611
612                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), prefs_common.savemsg);
613                 folderidentifier = folder_item_get_identifier(item);
614                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
615                 g_free(folderidentifier);
616         }
617
618         gtk_widget_grab_focus(compose->header_last->entry);
619
620         if (prefs_common.auto_exteditor)
621                 compose_exec_ext_editor(compose);
622
623         return compose;
624 }
625
626 #define CHANGE_FLAGS(msginfo) \
627 { \
628 if (msginfo->folder->folder->change_flags != NULL) \
629 msginfo->folder->folder->change_flags(msginfo->folder->folder, \
630                                       msginfo->folder, \
631                                       msginfo); \
632 }
633
634 /*
635 Compose *compose_new_followup_and_replyto(PrefsAccount *account,
636                                            const gchar *followupto, gchar * to)
637 {
638         Compose *compose;
639
640         if (!account) account = cur_account;
641         g_return_val_if_fail(account != NULL, NULL);
642         g_return_val_if_fail(account->protocol != A_NNTP, NULL);
643
644         compose = compose_create(account, COMPOSE_NEW);
645
646         if (prefs_common.auto_sig)
647                 compose_insert_sig(compose);
648         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
649         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
650
651         compose_entry_append(compose, to, COMPOSE_TO);
652         compose_entry_append(compose, followupto, COMPOSE_NEWSGROUPS);
653         gtk_widget_grab_focus(compose->subject_entry);
654
655         return compose;
656 }
657 */
658
659 void compose_reply(MsgInfo *msginfo, gboolean quote, gboolean to_all,
660                    gboolean ignore_replyto)
661 {
662         compose_generic_reply(msginfo, quote, to_all, ignore_replyto, FALSE);
663 }
664
665 void compose_followup_and_reply_to(MsgInfo *msginfo, gboolean quote,
666                                    gboolean to_all,
667                                    gboolean ignore_replyto)
668 {
669         compose_generic_reply(msginfo, quote, to_all, ignore_replyto, TRUE);
670 }
671
672 static void compose_generic_reply(MsgInfo *msginfo, gboolean quote,
673                                   gboolean to_all,
674                                   gboolean ignore_replyto,
675                                   gboolean followup_and_reply_to)
676 {
677         Compose *compose;
678         PrefsAccount *account;
679         PrefsAccount *reply_account;
680         GtkSText *text;
681
682         g_return_if_fail(msginfo != NULL);
683         g_return_if_fail(msginfo->folder != NULL);
684
685         account = NULL;
686         /* select the account set in folderitem's property (if enabled) */
687         if (msginfo->folder->prefs && msginfo->folder->prefs->enable_default_account)
688                 account = account_find_from_id(msginfo->folder->prefs->default_account);
689         
690         /* select the account for the whole folder (IMAP / NNTP) */
691         if (!account)
692                 /* FIXME: this is not right, because folder may be nested. we should
693                  * ascend the tree until we find a parent with proper account 
694                  * information */
695                 account = msginfo->folder->folder->account;
696
697         /* select account by to: and cc: header if enabled */
698         if (prefs_common.reply_account_autosel) {
699                 if (!account && msginfo->to) {
700                         gchar *to;
701                         Xstrdup_a(to, msginfo->to, return);
702                         extract_address(to);
703                         account = account_find_from_address(to);
704                 }
705                 if (!account) {
706                         gchar cc[BUFFSIZE];
707                         if(!get_header_from_msginfo(msginfo, cc, sizeof(cc), "CC:")) { /* Found a CC header */
708                                 extract_address(cc);
709                                 account = account_find_from_address(cc);
710                         }        
711                 }
712         }
713
714         /* select current account */
715         if (!account) account = cur_account;
716         g_return_if_fail(account != NULL);
717
718         if (ignore_replyto && account->protocol == A_NNTP &&
719             !followup_and_reply_to) {
720                 reply_account =
721                         account_find_from_address(account->address);
722                 if (!reply_account)
723                         reply_account = compose_current_mail_account();
724                 if (!reply_account)
725                         return;
726         } else
727                 reply_account = account;
728
729         MSG_UNSET_PERM_FLAGS(msginfo->flags, MSG_FORWARDED);
730         MSG_SET_PERM_FLAGS(msginfo->flags, MSG_REPLIED);
731         if (MSG_IS_IMAP(msginfo->flags))
732                 imap_msg_set_perm_flags(msginfo, MSG_REPLIED);
733         CHANGE_FLAGS(msginfo);
734
735         compose = compose_create(account, COMPOSE_REPLY);
736         compose->replyinfo = procmsg_msginfo_copy(msginfo);
737
738 #if 0 /* NEW COMPOSE GUI */
739         if (followup_and_reply_to) {
740                 gtk_widget_show(compose->to_hbox);
741                 gtk_widget_show(compose->to_entry);
742                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 1, 4);
743                 compose->use_to = TRUE;
744         }
745 #endif
746         if (msginfo->folder && msginfo->folder->ret_rcpt) {
747                 GtkItemFactory *ifactory;
748         
749                 ifactory = gtk_item_factory_from_widget(compose->menubar);
750                 menu_set_toggle(ifactory, "/Message/Request Return Receipt", TRUE);
751         }
752
753         /* Set save folder */
754         if(msginfo->folder && msginfo->folder->prefs && msginfo->folder->prefs->save_copy_to_folder) {
755                 gchar *folderidentifier;
756
757                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), TRUE);
758                 folderidentifier = folder_item_get_identifier(msginfo->folder);
759                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
760                 g_free(folderidentifier);
761         }
762
763         if (compose_parse_header(compose, msginfo) < 0) return;
764         compose_reply_set_entry(compose, msginfo, to_all, ignore_replyto,
765                                 followup_and_reply_to);
766         compose_show_first_last_header(compose, TRUE);
767
768         text = GTK_STEXT(compose->text);
769         gtk_stext_freeze(text);
770
771         if (quote) {
772                 gchar *qmark;
773                 gchar *quote_str;
774
775                 if (prefs_common.quotemark && *prefs_common.quotemark)
776                         qmark = prefs_common.quotemark;
777                 else
778                         qmark = "> ";
779
780                 quote_str = compose_quote_fmt(compose, msginfo,
781                                               prefs_common.quotefmt,
782                                               qmark);
783         }
784
785         if (prefs_common.auto_sig)
786                 compose_insert_sig(compose);
787
788         if (quote && prefs_common.linewrap_quote)
789                 compose_wrap_line_all(compose);
790
791         gtk_editable_set_position(GTK_EDITABLE(text), 0);
792         gtk_stext_set_point(text, 0);
793
794         gtk_stext_thaw(text);
795         gtk_widget_grab_focus(compose->text);
796
797         if (prefs_common.auto_exteditor)
798                 compose_exec_ext_editor(compose);
799 }
800
801
802 static gchar *procmime_get_file_name(MimeInfo *mimeinfo)
803 {
804         gchar *base;
805         gchar *filename;
806
807         g_return_val_if_fail(mimeinfo != NULL, NULL);
808
809         base = mimeinfo->filename ? mimeinfo->filename
810                 : mimeinfo->name ? mimeinfo->name : NULL;
811
812         if (MIME_TEXT_HTML == mimeinfo->mime_type && base == NULL){
813                 filename = g_strdup_printf("%s%smimetmp.%08x.html",
814                                            get_mime_tmp_dir(),
815                                            G_DIR_SEPARATOR_S,
816                                            (gint)mimeinfo);
817                 return filename;
818         }
819         else {
820                 base = base ? base : "";
821                 base = g_basename(base);
822                 if (*base == '\0') {
823                         filename = g_strdup_printf("%s%smimetmp.%08x",
824                                                    get_mime_tmp_dir(),
825                                                    G_DIR_SEPARATOR_S,
826                                                    (gint)mimeinfo);
827                         return filename;
828                 }
829         }
830
831         filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
832                                base, NULL);
833
834         return filename;
835 }
836
837 static gchar *mime_extract_file(gchar *source, MimeInfo *partinfo)
838 {
839         gchar *filename;
840
841         if (!partinfo) return NULL;
842
843         filename = procmime_get_file_name(partinfo);
844
845         if (procmime_get_part(filename, source, partinfo) < 0)
846                 alertpanel_error
847                         (_("Can't get the part of multipart message."));
848
849         return filename;
850 }
851
852 static void compose_attach_parts(Compose *compose, MsgInfo *msginfo)
853 {
854         FILE *fp;
855         gchar *file;
856         MimeInfo *mimeinfo;
857         MsgInfo *tmpmsginfo;
858         gchar *p;
859         gchar *boundary;
860         gint boundary_len = 0;
861         gchar buf[BUFFSIZE];
862         glong fpos, prev_fpos;
863         gint npart;
864         gchar *source;
865         gchar *filename;
866
867         g_return_if_fail(msginfo != NULL);
868         
869 #if USE_GPGME
870         for (;;) {
871                 if ((fp = procmsg_open_message(msginfo)) == NULL) return;
872                 mimeinfo = procmime_scan_mime_header(fp, MIME_TEXT);
873                 if (!mimeinfo) break;
874
875                 if (!MSG_IS_ENCRYPTED(msginfo->flags) &&
876                     rfc2015_is_encrypted(mimeinfo)) {
877                         MSG_SET_TMP_FLAGS(msginfo->flags, MSG_ENCRYPTED);
878                 }
879                 if (MSG_IS_ENCRYPTED(msginfo->flags) &&
880                     !msginfo->plaintext_file  &&
881                     !msginfo->decryption_failed) {
882                         rfc2015_decrypt_message(msginfo, mimeinfo, fp);
883                         if (msginfo->plaintext_file &&
884                             !msginfo->decryption_failed) {
885                                 fclose(fp);
886                                 continue;
887                         }
888                 }
889                 
890                 break;
891         }
892 #else /* !USE_GPGME */
893         if ((fp = procmsg_open_message(msginfo)) == NULL) return;
894         mimeinfo = procmime_scan_mime_header(fp, MIME_TEXT);
895 #endif /* USE_GPGME */
896
897         fclose(fp);
898         if (!mimeinfo) return;
899         if (mimeinfo->mime_type == MIME_TEXT)
900                 return;
901
902         if ((fp = procmsg_open_message(msginfo)) == NULL) return;
903
904         g_return_if_fail(mimeinfo != NULL);
905         g_return_if_fail(mimeinfo->mime_type != MIME_TEXT);
906
907         if (mimeinfo->mime_type == MIME_MULTIPART) {
908                 g_return_if_fail(mimeinfo->boundary != NULL);
909                 g_return_if_fail(mimeinfo->sub == NULL);
910         }
911         g_return_if_fail(fp != NULL);
912
913         boundary = mimeinfo->boundary;
914
915         if (boundary) {
916                 boundary_len = strlen(boundary);
917
918                 /* look for first boundary */
919                 while ((p = fgets(buf, sizeof(buf), fp)) != NULL)
920                         if (IS_BOUNDARY(buf, boundary, boundary_len)) break;
921                 if (!p) {
922                         fclose(fp);
923                         return;
924                 }
925         }
926
927         if ((fpos = ftell(fp)) < 0) {
928                 perror("ftell");
929                 fclose(fp);
930                 return;
931         }
932
933         for (npart = 0;; npart++) {
934                 MimeInfo *partinfo;
935                 gboolean eom = FALSE;
936
937                 prev_fpos = fpos;
938
939                 partinfo = procmime_scan_mime_header(fp, MIME_TEXT);
940                 if (!partinfo) break;
941
942                 if (npart != 0)
943                         procmime_mimeinfo_insert(mimeinfo, partinfo);
944                 else
945                         procmime_mimeinfo_free(partinfo);
946
947                 /* look for next boundary */
948                 buf[0] = '\0';
949                 while ((p = fgets(buf, sizeof(buf), fp)) != NULL) {
950                         if (IS_BOUNDARY(buf, boundary, boundary_len)) {
951                                 if (buf[2 + boundary_len]     == '-' &&
952                                     buf[2 + boundary_len + 1] == '-')
953                                         eom = TRUE;
954                                 break;
955                         }
956                 }
957                 if (p == NULL)
958                         eom = TRUE;     /* broken MIME message */
959                 fpos = ftell(fp);
960
961                 partinfo->size = fpos - prev_fpos - strlen(buf);
962
963                 if (eom) break;
964         }
965
966         source = procmsg_get_message_file_path(msginfo);
967
968         g_return_if_fail(mimeinfo != NULL);
969
970         if (!mimeinfo->main && mimeinfo->parent)
971                 {
972                         filename = mime_extract_file(source, mimeinfo);
973
974                         compose_attach_append_with_type(compose, filename,
975                                                         mimeinfo->content_type,
976                                                         mimeinfo->mime_type);
977
978                         g_free(filename);
979                 }
980
981         if (mimeinfo->sub && mimeinfo->sub->children)
982                 {
983                         filename = mime_extract_file(source, mimeinfo->sub);
984
985                         compose_attach_append_with_type(compose, filename,
986                                                         mimeinfo->content_type,
987                                                         mimeinfo->sub->mime_type);
988
989                         g_free(filename);
990                 }
991
992         if (mimeinfo->children) {
993                 MimeInfo *child;
994
995                 child = mimeinfo->children;
996                 while (child) {
997                         filename = mime_extract_file(source, child);
998
999                         compose_attach_append_with_type(compose, filename,
1000                                                         child->content_type,
1001                                                         child->mime_type);
1002
1003                         g_free(filename);
1004
1005                         child = child->next;
1006                 }
1007         }
1008
1009         fclose(fp);
1010
1011         procmime_mimeinfo_free_all(mimeinfo);
1012 }
1013
1014
1015 #define INSERT_FW_HEADER(var, hdr) \
1016 if (msginfo->var && *msginfo->var) { \
1017         gtk_stext_insert(text, NULL, NULL, NULL, hdr, -1); \
1018         gtk_stext_insert(text, NULL, NULL, NULL, msginfo->var, -1); \
1019         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1); \
1020 }
1021
1022 Compose *compose_forward(PrefsAccount *account, MsgInfo *msginfo,
1023                          gboolean as_attach)
1024 {
1025         Compose *compose;
1026         /*      PrefsAccount *account; */
1027         GtkSText *text;
1028
1029         g_return_val_if_fail(msginfo != NULL, NULL);
1030         g_return_val_if_fail(msginfo->folder != NULL, NULL);
1031
1032         account = msginfo->folder->folder->account;
1033         if (!account && msginfo->to && prefs_common.forward_account_autosel) {
1034                 gchar *to;
1035                 Xstrdup_a(to, msginfo->to, return NULL);
1036                 extract_address(to);
1037                 account = account_find_from_address(to);
1038         }
1039
1040         if(!account && prefs_common.forward_account_autosel) {
1041                 gchar cc[BUFFSIZE];
1042                 if(!get_header_from_msginfo(msginfo,cc,sizeof(cc),"CC:")){ /* Found a CC header */
1043                         extract_address(cc);
1044                         account = account_find_from_address(cc);
1045                 }
1046         }
1047
1048         if (account == NULL) {
1049                 account = cur_account;
1050                 /*
1051                 account = msginfo->folder->folder->account;
1052                 if (!account) account = cur_account;
1053                 */
1054         }
1055         g_return_val_if_fail(account != NULL, NULL);
1056
1057         MSG_UNSET_PERM_FLAGS(msginfo->flags, MSG_REPLIED);
1058         MSG_SET_PERM_FLAGS(msginfo->flags, MSG_FORWARDED);
1059         if (MSG_IS_IMAP(msginfo->flags))
1060                 imap_msg_unset_perm_flags(msginfo, MSG_REPLIED);
1061         CHANGE_FLAGS(msginfo);
1062
1063         compose = compose_create(account, COMPOSE_FORWARD);
1064
1065         if (msginfo->subject && *msginfo->subject) {
1066                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), "Fw: ");
1067                 gtk_entry_append_text(GTK_ENTRY(compose->subject_entry),
1068                                       msginfo->subject);
1069         }
1070
1071         text = GTK_STEXT(compose->text);
1072         gtk_stext_freeze(text);
1073
1074         if (as_attach) {
1075                 gchar *msgfile;
1076
1077                 msgfile = procmsg_get_message_file_path(msginfo);
1078                 if (!is_file_exist(msgfile))
1079                         g_warning(_("%s: file not exist\n"), msgfile);
1080                 else
1081                         compose_attach_append(compose, msgfile,
1082                                               MIME_MESSAGE_RFC822);
1083
1084                 g_free(msgfile);
1085         } else {
1086                 gchar *qmark;
1087                 gchar *quote_str;
1088
1089                 if (prefs_common.fw_quotemark && *prefs_common.fw_quotemark)
1090                         qmark = prefs_common.fw_quotemark;
1091                 else
1092                         qmark = "> ";
1093
1094                 quote_str = compose_quote_fmt(compose, msginfo,
1095                                               prefs_common.fw_quotefmt, qmark);
1096                 compose_attach_parts(compose, msginfo);
1097         }
1098
1099         if (prefs_common.auto_sig)
1100                 compose_insert_sig(compose);
1101
1102         if (prefs_common.linewrap_quote)
1103                 compose_wrap_line_all(compose);
1104
1105         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
1106         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
1107
1108         gtk_stext_thaw(text);
1109 #if 0 /* NEW COMPOSE GUI */
1110         if (account->protocol != A_NNTP)
1111                 gtk_widget_grab_focus(compose->to_entry);
1112         else
1113                 gtk_widget_grab_focus(compose->newsgroups_entry);
1114 #endif
1115         gtk_widget_grab_focus(compose->header_last->entry);
1116
1117         if (prefs_common.auto_exteditor)
1118                 compose_exec_ext_editor(compose);
1119
1120         return compose;
1121 }
1122
1123 #undef INSERT_FW_HEADER
1124
1125 Compose *compose_forward_multiple(PrefsAccount *account, GSList *msginfo_list)
1126 {
1127         Compose *compose;
1128         GtkSText *text;
1129         GSList *msginfo;
1130         gchar *msgfile;
1131
1132         g_return_val_if_fail(msginfo_list != NULL, NULL);
1133         
1134         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1135                 if ( ((MsgInfo *)msginfo->data)->folder == NULL )
1136                         return NULL;
1137         }
1138
1139         if (account == NULL) {
1140                 account = cur_account;
1141                 /*
1142                 account = msginfo->folder->folder->account;
1143                 if (!account) account = cur_account;
1144                 */
1145         }
1146         g_return_val_if_fail(account != NULL, NULL);
1147
1148         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1149                 MSG_UNSET_PERM_FLAGS(((MsgInfo *)msginfo->data)->flags, MSG_REPLIED);
1150                 MSG_SET_PERM_FLAGS(((MsgInfo *)msginfo->data)->flags, MSG_FORWARDED);
1151                 CHANGE_FLAGS(((MsgInfo *)msginfo->data));
1152         }
1153
1154         compose = compose_create(account, COMPOSE_FORWARD);
1155
1156         text = GTK_STEXT(compose->text);
1157         gtk_stext_freeze(text);
1158
1159         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1160                 msgfile = procmsg_get_message_file_path((MsgInfo *)msginfo->data);
1161                 if (!is_file_exist(msgfile))
1162                         g_warning(_("%s: file not exist\n"), msgfile);
1163                 else
1164                         compose_attach_append(compose, msgfile,
1165                                 MIME_MESSAGE_RFC822);
1166                 g_free(msgfile);
1167         }
1168
1169         if (prefs_common.auto_sig)
1170                 compose_insert_sig(compose);
1171
1172         if (prefs_common.linewrap_quote)
1173                 compose_wrap_line_all(compose);
1174
1175         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
1176         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
1177
1178         gtk_stext_thaw(text);
1179 #if 0 /* NEW COMPOSE GUI */
1180         if (account->protocol != A_NNTP)
1181                 gtk_widget_grab_focus(compose->to_entry);
1182         else
1183                 gtk_widget_grab_focus(compose->newsgroups_entry);
1184 #endif
1185
1186         return compose;
1187 }
1188
1189 void compose_reedit(MsgInfo *msginfo)
1190 {
1191         Compose *compose;
1192         PrefsAccount *account;
1193         GtkSText *text;
1194         FILE *fp;
1195         gchar buf[BUFFSIZE];
1196
1197         g_return_if_fail(msginfo != NULL);
1198         g_return_if_fail(msginfo->folder != NULL);
1199
1200         if (msginfo->folder->stype == F_QUEUE) {
1201                 gchar account_address[BUFFSIZE];
1202                 if (!get_header_from_msginfo(msginfo, account_address, sizeof(account_address), "S:")) {
1203                         account = account_find_from_address(account_address);
1204                 }
1205         } else 
1206                 account = msginfo->folder->folder->account;
1207
1208         if (!account && prefs_common.reedit_account_autosel) {
1209                 gchar from[BUFFSIZE];
1210                 if (!get_header_from_msginfo(msginfo, from, sizeof(from), "FROM:")){
1211                         extract_address(from);
1212                         account = account_find_from_address(from);
1213                 }
1214         }
1215         if (!account) account = cur_account;
1216         g_return_if_fail(account != NULL);
1217
1218         compose = compose_create(account, COMPOSE_REEDIT);
1219         compose->targetinfo = procmsg_msginfo_copy(msginfo);
1220
1221         if (compose_parse_header(compose, msginfo) < 0) return;
1222         compose_reedit_set_entry(compose, msginfo);
1223
1224         text = GTK_STEXT(compose->text);
1225         gtk_stext_freeze(text);
1226
1227         if ((fp = procmime_get_first_text_content(msginfo)) == NULL)
1228                 g_warning(_("Can't get text part\n"));
1229         else {
1230                 while (fgets(buf, sizeof(buf), fp) != NULL)
1231                         gtk_stext_insert(text, NULL, NULL, NULL, buf, -1);
1232                 fclose(fp);
1233         }
1234         compose_attach_parts(compose, msginfo);
1235
1236         gtk_stext_thaw(text);
1237         gtk_widget_grab_focus(compose->text);
1238
1239         if (prefs_common.auto_exteditor)
1240                 compose_exec_ext_editor(compose);
1241 }
1242
1243 GList *compose_get_compose_list(void)
1244 {
1245         return compose_list;
1246 }
1247
1248 void compose_entry_append(Compose *compose, const gchar *address,
1249                           ComposeEntryType type)
1250 {
1251         GtkEntry *entry;
1252         const gchar *text;
1253         gchar *header;
1254
1255         if (!address || *address == '\0') return;
1256
1257 #if 0 /* NEW COMPOSE GUI */
1258         switch (type) {
1259         case COMPOSE_CC:
1260                 entry = GTK_ENTRY(compose->cc_entry);
1261                 break;
1262         case COMPOSE_BCC:
1263                 entry = GTK_ENTRY(compose->bcc_entry);
1264                 break;
1265         case COMPOSE_NEWSGROUPS:
1266                 entry = GTK_ENTRY(compose->newsgroups_entry);
1267                 break;
1268         case COMPOSE_TO:
1269         default:
1270                 entry = GTK_ENTRY(compose->to_entry);
1271                 break;
1272         }
1273
1274         text = gtk_entry_get_text(entry);
1275         if (*text != '\0')
1276                 gtk_entry_append_text(entry, ", ");
1277         gtk_entry_append_text(entry, address);
1278 #endif
1279
1280         switch (type) {
1281         case COMPOSE_CC:
1282                 header = N_("Cc:");
1283                 break;
1284         case COMPOSE_BCC:
1285                 header = N_("Bcc:");
1286                 break;
1287         case COMPOSE_REPLYTO:
1288                 header = N_("Reply-To:");
1289                 break;
1290         case COMPOSE_NEWSGROUPS:
1291                 header = N_("Newsgroups:");
1292                 break;
1293         case COMPOSE_FOLLOWUPTO:
1294                 header = N_( "Followup-To:");
1295                 break;
1296         case COMPOSE_TO:
1297         default:
1298                 header = N_("To:");
1299                 break;
1300         }
1301         header = prefs_common.trans_hdr ? gettext(header) : header;
1302
1303         compose_add_header_entry(compose, header, (gchar *)address);
1304 }
1305
1306 static void compose_entries_set(Compose *compose, const gchar *mailto)
1307 {
1308         gchar *subject = NULL;
1309         gchar *to = NULL;
1310         gchar *cc = NULL;
1311         gchar *bcc = NULL;
1312         gchar *body = NULL;
1313         gchar *p;
1314         gchar *tmp_mailto;
1315
1316         Xstrdup_a(tmp_mailto, mailto, return);
1317
1318         to = tmp_mailto;
1319
1320         p = strchr(tmp_mailto, '?');
1321         if (p) {
1322                 *p = '\0';
1323                 p++;
1324         }
1325
1326         while (p) {
1327                 gchar *field, *value;
1328
1329                 field = p;
1330
1331                 p = strchr(p, '=');
1332                 if (!p) break;
1333                 *p = '\0';
1334                 p++;
1335
1336                 value = p;
1337
1338                 p = strchr(p, '&');
1339                 if (p) {
1340                         *p = '\0';
1341                         p++;
1342                 }
1343
1344                 if (*value == '\0') continue;
1345
1346                 if (!g_strcasecmp(field, "subject")) {
1347                         Xalloca(subject, strlen(value) + 1, return);
1348                         decode_uri(subject, value);
1349                 } else if (!g_strcasecmp(field, "cc")) {
1350                         cc = value;
1351                 } else if (!g_strcasecmp(field, "bcc")) {
1352                         bcc = value;
1353                 } else if (!g_strcasecmp(field, "body")) {
1354                         Xalloca(body, strlen(value) + 1, return);
1355                         decode_uri(body, value);
1356                 }
1357         }
1358
1359         if (to)
1360                 compose_entry_append(compose, to, COMPOSE_TO);
1361         if (subject)
1362                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), subject);
1363         if (cc)
1364                 compose_entry_append(compose, cc, COMPOSE_CC);
1365         if (bcc)
1366                 compose_entry_append(compose, bcc, COMPOSE_BCC);
1367         if (body) {
1368                 gtk_stext_insert(GTK_STEXT(compose->text),
1369                                 NULL, NULL, NULL, body, -1);
1370                 gtk_stext_insert(GTK_STEXT(compose->text),
1371                                 NULL, NULL, NULL, "\n", 1);
1372         }
1373 }
1374
1375 static gint compose_parse_header(Compose *compose, MsgInfo *msginfo)
1376 {
1377         static HeaderEntry hentry[] = {{"Reply-To:",       NULL, TRUE},
1378                                        {"Cc:",             NULL, FALSE},
1379                                        {"References:",     NULL, FALSE},
1380                                        {"Bcc:",            NULL, FALSE},
1381                                        {"Newsgroups:",     NULL, FALSE},
1382                                        {"Followup-To:",    NULL, FALSE},
1383                                        {"X-Mailing-List:", NULL, FALSE},
1384                                        {"X-BeenThere:",    NULL, FALSE},
1385                                        {NULL,              NULL, FALSE}};
1386
1387         enum
1388         {
1389                 H_REPLY_TO       = 0,
1390                 H_CC             = 1,
1391                 H_REFERENCES     = 2,
1392                 H_BCC            = 3,
1393                 H_NEWSGROUPS     = 4,
1394                 H_FOLLOWUP_TO    = 5,
1395                 H_X_MAILING_LIST = 6,
1396                 H_X_BEENTHERE    = 7
1397         };
1398
1399         FILE *fp;
1400
1401         g_return_val_if_fail(msginfo != NULL, -1);
1402
1403         if ((fp = procmsg_open_message(msginfo)) == NULL) return -1;
1404         procheader_get_header_fields(fp, hentry);
1405         fclose(fp);
1406
1407         if (hentry[H_REPLY_TO].body != NULL) {
1408                 conv_unmime_header_overwrite(hentry[H_REPLY_TO].body);
1409                 compose->replyto = hentry[H_REPLY_TO].body;
1410                 hentry[H_REPLY_TO].body = NULL;
1411         }
1412         if (hentry[H_CC].body != NULL) {
1413                 conv_unmime_header_overwrite(hentry[H_CC].body);
1414                 compose->cc = hentry[H_CC].body;
1415                 hentry[H_CC].body = NULL;
1416         }
1417         if (hentry[H_X_MAILING_LIST].body != NULL) {
1418                 /* this is good enough to parse debian-devel */
1419                 gchar *buf = g_malloc(strlen(hentry[H_X_MAILING_LIST].body) + 1);
1420                 g_return_val_if_fail(buf != NULL, -1 );
1421                 if (1 == sscanf(hentry[H_X_MAILING_LIST].body, "<%[^>]>", buf))
1422                         compose->mailinglist = g_strdup(buf);
1423                 g_free(buf);
1424                 g_free(hentry[H_X_MAILING_LIST].body);
1425                 hentry[H_X_MAILING_LIST].body = NULL ;
1426         }
1427         if (hentry[H_X_BEENTHERE].body != NULL) {
1428                 /* this is good enough to parse the sylpheed-claws lists */
1429                 gchar *buf = g_malloc(strlen(hentry[H_X_BEENTHERE].body) + 1);
1430                 g_return_val_if_fail(buf != NULL, -1 );
1431                 if (1 == sscanf(hentry[H_X_BEENTHERE].body, "%[^>]", buf))
1432                         compose->mailinglist = g_strdup(buf);
1433                 g_free(buf);
1434                 g_free(hentry[H_X_BEENTHERE].body);
1435                 hentry[H_X_BEENTHERE].body = NULL ;
1436         }
1437         if (hentry[H_REFERENCES].body != NULL) {
1438                 if (compose->mode == COMPOSE_REEDIT)
1439                         compose->references = hentry[H_REFERENCES].body;
1440                 else {
1441                         compose->references = compose_parse_references
1442                                 (hentry[H_REFERENCES].body, msginfo->msgid);
1443                         g_free(hentry[H_REFERENCES].body);
1444                 }
1445                 hentry[H_REFERENCES].body = NULL;
1446         }
1447         if (hentry[H_BCC].body != NULL) {
1448                 if (compose->mode == COMPOSE_REEDIT) {
1449                         conv_unmime_header_overwrite(hentry[H_BCC].body);
1450                         compose->bcc = hentry[H_BCC].body;
1451                 } else
1452                         g_free(hentry[H_BCC].body);
1453                 hentry[H_BCC].body = NULL;
1454         }
1455         if (hentry[H_NEWSGROUPS].body != NULL) {
1456                 compose->newsgroups = hentry[H_NEWSGROUPS].body;
1457                 hentry[H_NEWSGROUPS].body = NULL;
1458         }
1459         if (hentry[H_FOLLOWUP_TO].body != NULL) {
1460                 conv_unmime_header_overwrite(hentry[H_FOLLOWUP_TO].body);
1461                 compose->followup_to = hentry[H_FOLLOWUP_TO].body;
1462                 hentry[H_FOLLOWUP_TO].body = NULL;
1463         }
1464
1465         if (compose->mode == COMPOSE_REEDIT && msginfo->inreplyto)
1466                 compose->inreplyto = g_strdup(msginfo->inreplyto);
1467         else if (compose->mode != COMPOSE_REEDIT &&
1468                  msginfo->msgid && *msginfo->msgid) {
1469                 compose->inreplyto = g_strdup(msginfo->msgid);
1470
1471                 if (!compose->references) {
1472                         if (msginfo->inreplyto && *msginfo->inreplyto)
1473                                 compose->references =
1474                                         g_strdup_printf("<%s>\n\t<%s>",
1475                                                         msginfo->inreplyto,
1476                                                         msginfo->msgid);
1477                         else
1478                                 compose->references =
1479                                         g_strconcat("<", msginfo->msgid, ">",
1480                                                     NULL);
1481                 }
1482         }
1483
1484         return 0;
1485 }
1486
1487 static gchar *compose_parse_references(const gchar *ref, const gchar *msgid)
1488 {
1489         GSList *ref_id_list, *cur;
1490         GString *new_ref;
1491         gchar *new_ref_str;
1492
1493         ref_id_list = references_list_append(NULL, ref);
1494         if (!ref_id_list) return NULL;
1495         if (msgid && *msgid)
1496                 ref_id_list = g_slist_append(ref_id_list, g_strdup(msgid));
1497
1498         for (;;) {
1499                 gint len = 0;
1500
1501                 for (cur = ref_id_list; cur != NULL; cur = cur->next)
1502                         /* "<" + Message-ID + ">" + CR+LF+TAB */
1503                         len += strlen((gchar *)cur->data) + 5;
1504
1505                 if (len > MAX_REFERENCES_LEN) {
1506                         /* remove second message-ID */
1507                         if (ref_id_list && ref_id_list->next &&
1508                             ref_id_list->next->next) {
1509                                 g_free(ref_id_list->next->data);
1510                                 ref_id_list = g_slist_remove
1511                                         (ref_id_list, ref_id_list->next->data);
1512                         } else {
1513                                 slist_free_strings(ref_id_list);
1514                                 g_slist_free(ref_id_list);
1515                                 return NULL;
1516                         }
1517                 } else
1518                         break;
1519         }
1520
1521         new_ref = g_string_new("");
1522         for (cur = ref_id_list; cur != NULL; cur = cur->next) {
1523                 if (new_ref->len > 0)
1524                         g_string_append(new_ref, "\n\t");
1525                 g_string_sprintfa(new_ref, "<%s>", (gchar *)cur->data);
1526         }
1527
1528         slist_free_strings(ref_id_list);
1529         g_slist_free(ref_id_list);
1530
1531         new_ref_str = new_ref->str;
1532         g_string_free(new_ref, FALSE);
1533
1534         return new_ref_str;
1535 }
1536
1537 static gchar *compose_quote_fmt(Compose *compose, MsgInfo *msginfo,
1538                                 const gchar *fmt, const gchar *qmark)
1539 {
1540         GtkSText *text = GTK_STEXT(compose->text);
1541         gchar *quote_str = NULL;
1542         gchar *buf;
1543         gchar *p, *lastp;
1544         gint len;
1545
1546         if (qmark != NULL) {
1547                 quote_fmt_init(msginfo, NULL);
1548                 quote_fmt_scan_string(qmark);
1549                 quote_fmt_parse();
1550
1551                 buf = quote_fmt_get_buffer();
1552                 if (buf == NULL)
1553                         alertpanel_error(_("Quote mark format error."));
1554                 else
1555                         Xstrdup_a(quote_str, buf, return NULL)
1556         }
1557
1558         if (fmt && *fmt != '\0') {
1559                 quote_fmt_init(msginfo, quote_str);
1560                 quote_fmt_scan_string(fmt);
1561                 quote_fmt_parse();
1562
1563                 buf = quote_fmt_get_buffer();
1564                 if (buf == NULL) {
1565                         alertpanel_error(_("Message reply/forward format error."));
1566                         return NULL;
1567                 }
1568         } else
1569                 buf = "";
1570
1571         gtk_stext_freeze(text);
1572         gtk_stext_set_point(text, 0);
1573         gtk_stext_forward_delete(text, gtk_stext_get_length(text));
1574
1575         for (p = buf; *p != '\0'; ) {
1576                 lastp = strchr(p, '\n');
1577                 len = lastp ? lastp - p + 1 : -1;
1578                 gtk_stext_insert(text, NULL, NULL, NULL, p, len);
1579                 if (lastp)
1580                         p = lastp + 1;
1581                 else
1582                         break;
1583         }
1584
1585         gtk_stext_thaw(text);
1586
1587         return buf;
1588 }
1589
1590 static void compose_reply_set_entry(Compose *compose, MsgInfo *msginfo,
1591                                     gboolean to_all, gboolean ignore_replyto,
1592                                     gboolean followup_and_reply_to)
1593 {
1594         GSList *cc_list;
1595         GSList *cur;
1596         gchar *from;
1597         GHashTable *to_table;
1598
1599         g_return_if_fail(compose->account != NULL);
1600         g_return_if_fail(msginfo != NULL);
1601
1602         if ((compose->account->protocol != A_NNTP) || followup_and_reply_to)
1603                 compose_entry_append(compose,
1604                                     ((compose->replyto && !ignore_replyto)
1605                                      ? compose->replyto
1606                                      : (compose->mailinglist && !ignore_replyto)
1607                                      ? compose->mailinglist
1608                                      : msginfo->from ? msginfo->from : ""),
1609                                      COMPOSE_TO);
1610         if (compose->account->protocol == A_NNTP) {
1611                 if (ignore_replyto)
1612                         compose_entry_append
1613                                 (compose, msginfo->from ? msginfo->from : "",
1614                                  COMPOSE_TO);
1615                 else
1616                         compose_entry_append
1617                                 (compose,
1618                                  compose->followup_to ? compose->followup_to
1619                                  : compose->newsgroups ? compose->newsgroups
1620                                  : "",
1621                                  COMPOSE_NEWSGROUPS);
1622         }
1623
1624         if (msginfo->subject && *msginfo->subject) {
1625                 gchar *buf, *buf2, *p;
1626
1627                 buf = g_strdup(msginfo->subject);
1628                 while (!strncasecmp(buf, "Re:", 3)) {
1629                         p = buf + 3;
1630                         while (isspace(*p)) p++;
1631                         memmove(buf, p, strlen(p) + 1);
1632                 }
1633
1634                 buf2 = g_strdup_printf("Re: %s", buf);
1635                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), buf2);
1636                 g_free(buf2);
1637                 g_free(buf);
1638         } else
1639                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), "Re: ");
1640
1641         if (!to_all || compose->account->protocol == A_NNTP) return;
1642
1643         from = g_strdup(compose->replyto ? compose->replyto :
1644                         msginfo->from ? msginfo->from : "");
1645         extract_address(from);
1646
1647         cc_list = address_list_append(NULL, msginfo->to);
1648         cc_list = address_list_append(cc_list, compose->cc);
1649
1650         to_table = g_hash_table_new(g_str_hash, g_str_equal);
1651         g_hash_table_insert(to_table, from, GINT_TO_POINTER(1));
1652         if (compose->account)
1653                 g_hash_table_insert(to_table, compose->account->address,
1654                                     GINT_TO_POINTER(1));
1655
1656         /* remove address on To: and that of current account */
1657         for (cur = cc_list; cur != NULL; ) {
1658                 GSList *next = cur->next;
1659
1660                 if (g_hash_table_lookup(to_table, cur->data) != NULL)
1661                         cc_list = g_slist_remove(cc_list, cur->data);
1662                 else
1663                         g_hash_table_insert(to_table, cur->data, cur);
1664
1665                 cur = next;
1666         }
1667         g_hash_table_destroy(to_table);
1668         g_free(from);
1669
1670         if (cc_list) {
1671                 for (cur = cc_list; cur != NULL; cur = cur->next)
1672                         compose_entry_append(compose, (gchar *)cur->data,
1673                                              COMPOSE_CC);
1674                 slist_free_strings(cc_list);
1675                 g_slist_free(cc_list);
1676         }
1677 }
1678
1679 #define SET_ENTRY(entry, str) \
1680 { \
1681         if (str && *str) \
1682                 gtk_entry_set_text(GTK_ENTRY(compose->entry), str); \
1683 }
1684
1685 #define SET_ADDRESS(type, str) \
1686 { \
1687         if (str && *str) \
1688                 compose_entry_append(compose, str, type); \
1689 }
1690
1691 static void compose_reedit_set_entry(Compose *compose, MsgInfo *msginfo)
1692 {
1693         g_return_if_fail(msginfo != NULL);
1694
1695         SET_ENTRY(subject_entry, msginfo->subject);
1696         SET_ADDRESS(COMPOSE_TO, msginfo->to);
1697         SET_ADDRESS(COMPOSE_CC, compose->cc);
1698         SET_ADDRESS(COMPOSE_BCC, compose->bcc);
1699         SET_ADDRESS(COMPOSE_REPLYTO, compose->replyto);
1700
1701         compose_show_first_last_header(compose, TRUE);
1702
1703 #if 0 /* NEW COMPOSE GUI */
1704         if (compose->bcc) {
1705                 GtkItemFactory *ifactory;
1706                 GtkWidget *menuitem;
1707
1708                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1709                 menuitem = gtk_item_factory_get_item(ifactory, "/Message/Bcc");
1710                 gtk_check_menu_item_set_active
1711                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
1712         }
1713         if (compose->replyto) {
1714                 GtkItemFactory *ifactory;
1715                 GtkWidget *menuitem;
1716
1717                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1718                 menuitem = gtk_item_factory_get_item
1719                         (ifactory, "/Message/Reply to");
1720                 gtk_check_menu_item_set_active
1721                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
1722         }
1723 #endif
1724 }
1725
1726 #undef SET_ENTRY
1727 #undef SET_ADDRESS
1728
1729 static void compose_exec_sig(Compose *compose, gchar *sigfile)
1730 {
1731         FILE *tmpfp;
1732         pid_t thepid;
1733         gchar *sigtext;
1734         FILE  *sigprg;
1735         gchar  *buf;
1736         size_t buf_len = 128;
1737  
1738         if (strlen(sigfile) < 2)
1739           return;
1740  
1741         sigprg = popen(sigfile+1, "r");
1742         if (sigprg) {
1743
1744                 buf = g_malloc(buf_len);
1745
1746                 if (!buf) {
1747                         gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, \
1748                         "Unable to insert signature (malloc failed)\n", -1);
1749
1750                         pclose(sigprg);
1751                         return;
1752                 }
1753
1754                 while (!feof(sigprg)) {
1755                         bzero(buf, buf_len);
1756                         fread(buf, buf_len-1, 1, sigprg);
1757                         gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, buf, -1);
1758                 }
1759
1760                 g_free(buf);
1761                 pclose(sigprg);
1762         }
1763         else
1764         {
1765                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, \
1766                 "Can't exec file: ", -1);
1767                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, \
1768                 sigfile+1, -1);
1769         }
1770 }
1771
1772 static void compose_insert_sig(Compose *compose)
1773 {
1774         gchar *sigfile;
1775
1776         if (compose->account && compose->account->sig_path)
1777                 sigfile = g_strdup(compose->account->sig_path);
1778         else {
1779                 sigfile = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1780                                       DEFAULT_SIGNATURE, NULL);
1781         }
1782
1783         if (!is_file_or_fifo_exist(sigfile) & (sigfile[0] != '|')) {
1784                 g_free(sigfile);
1785                 return;
1786         }
1787
1788         gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, "\n\n", 2);
1789         if (prefs_common.sig_sep) {
1790                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL,
1791                                 prefs_common.sig_sep, -1);
1792                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL,
1793                                 "\n", 1);
1794         }
1795
1796         if (sigfile[0] == '|')
1797         {
1798                 compose_exec_sig(compose, sigfile);
1799         }
1800         else
1801         {
1802                 compose_insert_file(compose, sigfile);
1803         }
1804         g_free(sigfile);
1805 }
1806
1807 static void compose_insert_file(Compose *compose, const gchar *file)
1808 {
1809         GtkSText *text = GTK_STEXT(compose->text);
1810         gchar buf[BUFFSIZE];
1811         gint len;
1812         FILE *fp;
1813
1814         g_return_if_fail(file != NULL);
1815
1816         if ((fp = fopen(file, "r")) == NULL) {
1817                 FILE_OP_ERROR(file, "fopen");
1818                 return;
1819         }
1820
1821         gtk_stext_freeze(text);
1822
1823         while (fgets(buf, sizeof(buf), fp) != NULL) {
1824                 /* strip <CR> if DOS/Windows file,
1825                    replace <CR> with <LF> if Macintosh file. */
1826                 strcrchomp(buf);
1827                 len = strlen(buf);
1828                 if (len > 0 && buf[len - 1] != '\n') {
1829                         while (--len >= 0)
1830                                 if (buf[len] == '\r') buf[len] = '\n';
1831                 }
1832
1833                 gtk_stext_insert(text, NULL, NULL, NULL, buf, -1);
1834         }
1835
1836         gtk_stext_thaw(text);
1837
1838         fclose(fp);
1839 }
1840
1841 static void compose_attach_info(Compose * compose, AttachInfo * ainfo,
1842                                 ContentType cnttype)
1843 {
1844         gchar *text[N_ATTACH_COLS];
1845         gint row;
1846
1847         text[COL_MIMETYPE] = ainfo->content_type;
1848         text[COL_SIZE] = to_human_readable(ainfo->size);
1849         text[COL_NAME] = ainfo->name;
1850
1851         row = gtk_clist_append(GTK_CLIST(compose->attach_clist), text);
1852         gtk_clist_set_row_data(GTK_CLIST(compose->attach_clist), row, ainfo);
1853
1854         if (cnttype != MIME_MESSAGE_RFC822)
1855                 compose_changed_cb(NULL, compose);
1856 }
1857
1858 static void compose_attach_append_with_type(Compose *compose,
1859                                             const gchar *file,
1860                                             const gchar *type,
1861                                             ContentType cnttype)
1862 {
1863         AttachInfo *ainfo;
1864         off_t size;
1865
1866         if (!is_file_exist(file)) {
1867                 g_warning(_("File %s doesn't exist\n"), file);
1868                 return;
1869         }
1870         if ((size = get_file_size(file)) < 0) {
1871                 g_warning(_("Can't get file size of %s\n"), file);
1872                 return;
1873         }
1874         if (size == 0) {
1875                 alertpanel_notice(_("File %s is empty\n"), file);
1876                 return;
1877         }
1878 #if 0 /* NEW COMPOSE GUI */
1879         if (!compose->use_attach) {
1880                 GtkItemFactory *ifactory;
1881                 GtkWidget *menuitem;
1882
1883                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1884                 menuitem = gtk_item_factory_get_item(ifactory,
1885                                                      "/Message/Attach");
1886                 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
1887                                                TRUE);
1888         }
1889 #endif
1890         ainfo = g_new0(AttachInfo, 1);
1891         ainfo->file = g_strdup(file);
1892
1893         if (cnttype == MIME_MESSAGE_RFC822) {
1894                 ainfo->encoding = ENC_7BIT;
1895                 ainfo->name = g_strdup_printf(_("Message: %s"),
1896                                               g_basename(file));
1897         } else {
1898                 ainfo->encoding = ENC_BASE64;
1899                 ainfo->name = g_strdup(g_basename(file));
1900         }
1901
1902         ainfo->content_type = g_strdup(type);
1903         ainfo->size = size;
1904
1905         compose_attach_info(compose, ainfo, cnttype);
1906 }
1907
1908 static void compose_attach_append(Compose *compose, const gchar *file,
1909                                   ContentType cnttype)
1910 {
1911         AttachInfo *ainfo;
1912         gchar *text[N_ATTACH_COLS];
1913         off_t size;
1914         gint row;
1915
1916         if (!is_file_exist(file)) {
1917                 g_warning(_("File %s doesn't exist\n"), file);
1918                 return;
1919         }
1920         if ((size = get_file_size(file)) < 0) {
1921                 g_warning(_("Can't get file size of %s\n"), file);
1922                 return;
1923         }
1924         if (size == 0) {
1925                 alertpanel_notice(_("File %s is empty\n"), file);
1926                 return;
1927         }
1928 #if 0 /* NEW COMPOSE GUI */
1929         if (!compose->use_attach) {
1930                 GtkItemFactory *ifactory;
1931                 GtkWidget *menuitem;
1932
1933                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1934                 menuitem = gtk_item_factory_get_item(ifactory,
1935                                                      "/Message/Attach");
1936                 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
1937                                                TRUE);
1938         }
1939 #endif
1940         ainfo = g_new0(AttachInfo, 1);
1941         ainfo->file = g_strdup(file);
1942
1943         if (cnttype == MIME_MESSAGE_RFC822) {
1944                 ainfo->content_type = g_strdup("message/rfc822");
1945                 ainfo->encoding = ENC_7BIT;
1946                 ainfo->name = g_strdup_printf(_("Message: %s"),
1947                                               g_basename(file));
1948         } else {
1949                 ainfo->content_type = procmime_get_mime_type(file);
1950                 if (!ainfo->content_type)
1951                         ainfo->content_type =
1952                                 g_strdup("application/octet-stream");
1953                 ainfo->encoding = ENC_BASE64;
1954                 ainfo->name = g_strdup(g_basename(file));
1955         }
1956         ainfo->size = size;
1957
1958         compose_attach_info(compose, ainfo, cnttype);
1959 }
1960
1961 #define GET_CHAR(pos, buf, len)                                              \
1962 {                                                                            \
1963         if (text->use_wchar)                                                 \
1964                 len = wctomb(buf, (wchar_t)GTK_STEXT_INDEX(text, (pos)));     \
1965         else {                                                               \
1966                 buf[0] = GTK_STEXT_INDEX(text, (pos));                       \
1967                 len = 1;                                                     \
1968         }                                                                    \
1969 }
1970
1971 static void compose_wrap_line(Compose *compose)
1972 {
1973         GtkSText *text = GTK_STEXT(compose->text);
1974         gint ch_len, last_ch_len;
1975         gchar cbuf[MB_LEN_MAX], last_ch;
1976         guint text_len;
1977         guint line_end;
1978         guint quoted;
1979         gint p_start, p_end;
1980         gint line_pos, cur_pos;
1981         gint line_len, cur_len;
1982
1983
1984         gtk_stext_freeze(text);
1985
1986         text_len = gtk_stext_get_length(text);
1987
1988         /* check to see if the point is on the paragraph mark (empty line). */
1989         cur_pos = gtk_stext_get_point(text);
1990         GET_CHAR(cur_pos, cbuf, ch_len);
1991         if ((ch_len == 1 && *cbuf == '\n') || cur_pos == text_len) {
1992                 if (cur_pos == 0)
1993                         goto compose_end; /* on the paragraph mark */
1994                 GET_CHAR(cur_pos - 1, cbuf, ch_len);
1995                 if (ch_len == 1 && *cbuf == '\n')
1996                         goto compose_end; /* on the paragraph mark */
1997         }
1998
1999         /* find paragraph start. */
2000         line_end = quoted = 0;
2001         for (p_start = cur_pos; p_start >= 0; --p_start) {
2002                 GET_CHAR(p_start, cbuf, ch_len);
2003                 if (ch_len == 1 && *cbuf == '\n') {
2004                         if (quoted)
2005                                 goto compose_end; /* quoted part */
2006                         if (line_end) {
2007                                 p_start += 2;
2008                                 break;
2009                         }
2010                         line_end = 1;
2011                 } else {
2012                         if (ch_len == 1 && strchr(">:#", *cbuf))
2013                                 quoted = 1;
2014                         else if (ch_len != 1 || !isspace(*cbuf))
2015                                 quoted = 0;
2016
2017                         line_end = 0;
2018                 }
2019         }
2020         if (p_start < 0)
2021                 p_start = 0;
2022
2023         /* find paragraph end. */
2024         line_end = 0;
2025         for (p_end = cur_pos; p_end < text_len; p_end++) {
2026                 GET_CHAR(p_end, cbuf, ch_len);
2027                 if (ch_len == 1 && *cbuf == '\n') {
2028                         if (line_end) {
2029                                 p_end -= 1;
2030                                 break;
2031                         }
2032                         line_end = 1;
2033                 } else {
2034                         if (line_end && ch_len == 1 && strchr(">:#", *cbuf))
2035                                 goto compose_end; /* quoted part */
2036
2037                         line_end = 0;
2038                 }
2039         }
2040         if (p_end >= text_len)
2041                 p_end = text_len;
2042
2043         if (p_start >= p_end)
2044                 goto compose_end;
2045
2046         line_len = cur_len = 0;
2047         last_ch_len = 0;
2048         last_ch = '\0';
2049         line_pos = p_start;
2050         for (cur_pos = p_start; cur_pos < p_end; cur_pos++) {
2051                 guint space = 0;
2052
2053                 GET_CHAR(cur_pos, cbuf, ch_len);
2054
2055                 if (ch_len < 0) {
2056                         cbuf[0] = '\0';
2057                         ch_len = 1;
2058                 }
2059
2060                 if (ch_len == 1 && isspace(*cbuf))
2061                         space = 1;
2062
2063                 if (ch_len == 1 && *cbuf == '\n') {
2064                         guint replace = 0;
2065                         if (last_ch_len == 1 && !isspace(last_ch)) {
2066                                 if (cur_pos + 1 < p_end) {
2067                                         GET_CHAR(cur_pos + 1, cbuf, ch_len);
2068                                         if (ch_len == 1 && !isspace(*cbuf))
2069                                                 replace = 1;
2070                                 }
2071                         }
2072                         gtk_stext_set_point(text, cur_pos + 1);
2073                         gtk_stext_backward_delete(text, 1);
2074                         if (replace) {
2075                                 gtk_stext_set_point(text, cur_pos);
2076                                 gtk_stext_insert(text, NULL, NULL, NULL, " ", 1);
2077                                 space = 1;
2078                         }
2079                         else {
2080                                 p_end--;
2081                                 cur_pos--;
2082                                 continue;
2083                         }
2084                 }
2085
2086                 last_ch_len = ch_len;
2087                 last_ch = *cbuf;
2088
2089                 if (space) {
2090                         line_pos = cur_pos + 1;
2091                         line_len = cur_len + ch_len;
2092                 }
2093
2094                 if (cur_len + ch_len > prefs_common.linewrap_len &&
2095                     line_len > 0) {
2096                         gint tlen = ch_len;
2097
2098                         GET_CHAR(line_pos - 1, cbuf, ch_len);
2099                         if (ch_len == 1 && isspace(*cbuf)) {
2100                                 gtk_stext_set_point(text, line_pos);
2101                                 gtk_stext_backward_delete(text, 1);
2102                                 p_end--;
2103                                 cur_pos--;
2104                                 line_pos--;
2105                                 cur_len--;
2106                                 line_len--;
2107                         }
2108                         ch_len = tlen;
2109
2110                         gtk_stext_set_point(text, line_pos);
2111                         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1);
2112                         p_end++;
2113                         cur_pos++;
2114                         line_pos++;
2115                         cur_len = cur_len - line_len + ch_len;
2116                         line_len = 0;
2117                         continue;
2118                 }
2119
2120                 if (ch_len > 1) {
2121                         line_pos = cur_pos + 1;
2122                         line_len = cur_len + ch_len;
2123                 }
2124                 cur_len += ch_len;
2125         }
2126
2127 compose_end:
2128         gtk_stext_thaw(text);
2129 }
2130
2131 /* return indent length */
2132 static guint get_indent_length(GtkSText *text, guint start_pos, guint text_len)
2133 {
2134         gint indent_len = 0;
2135         gint i, ch_len;
2136         gchar cbuf[MB_LEN_MAX];
2137
2138         for (i = start_pos; i < text_len; i++) {
2139                 GET_CHAR(i, cbuf, ch_len);
2140                 if (ch_len > 1)
2141                         break;
2142                 /* allow space, tab, > or | */
2143                 if (cbuf[0] != ' ' && cbuf[0] != '\t' &&
2144                     cbuf[0] != '>' && cbuf[0] != '|')
2145                         break;
2146                 indent_len++;
2147         }
2148
2149         return indent_len;
2150 }
2151
2152 /* insert quotation string when line was wrapped */
2153 static guint ins_quote(GtkSText *text, guint quote_len, guint indent_len,
2154                        guint prev_line_pos, guint text_len,
2155                        gchar *quote_fmt)
2156 {
2157         guint i, ins_len;
2158         gchar ch;
2159
2160         if (indent_len) {
2161                 for (i = 0; i < indent_len; i++) {
2162                         ch = GTK_STEXT_INDEX(text, prev_line_pos + i);
2163                         gtk_stext_insert(text, NULL, NULL, NULL, &ch, 1);
2164                 }
2165                 ins_len = indent_len;
2166         } else {
2167                 gtk_stext_insert(text, NULL, NULL, NULL, quote_fmt, quote_len);
2168                 ins_len = quote_len;
2169         }
2170
2171         return ins_len;
2172 }
2173
2174 #undef WRAP_DEBUG
2175 #ifdef WRAP_DEBUG
2176 /* Darko: used when I debug wrapping */
2177 void dump_text(GtkSText *text, int pos, int tlen, int breakoncr)
2178 {
2179         gint i;
2180         gchar ch;
2181
2182         printf("%d [", pos);
2183         for (i = pos; i < tlen; i++) {
2184                 ch = GTK_STEXT_INDEX(text, i);
2185                 if (breakoncr && ch == '\n')
2186                         break;
2187                 printf("%c", ch);
2188         }
2189         printf("]\n");
2190 }
2191 #endif
2192
2193 static void compose_wrap_line_all(Compose *compose)
2194 {
2195         GtkSText *text = GTK_STEXT(compose->text);
2196         guint tlen;
2197         guint line_pos = 0, cur_pos = 0, p_pos = 0;
2198         gint line_len = 0, cur_len = 0;
2199         gint ch_len;
2200         gboolean is_new_line = TRUE, do_delete = FALSE;
2201         guint qlen = 0, i_len = 0;
2202         guint linewrap_quote = prefs_common.linewrap_quote;
2203         guint linewrap_len = prefs_common.linewrap_len;
2204         gchar *qfmt = prefs_common.quotemark;
2205         gchar cbuf[MB_LEN_MAX];
2206
2207         gtk_stext_freeze(text);
2208
2209         /* make text buffer contiguous */
2210         /* gtk_stext_compact_buffer(text); */
2211
2212         tlen = gtk_stext_get_length(text);
2213
2214         for (; cur_pos < tlen; cur_pos++) {
2215                 /* mark position of new line - needed for quotation wrap */
2216                 if (is_new_line) {
2217                         if (linewrap_quote) {
2218                                 qlen = gtkut_text_str_compare
2219                                         (text, cur_pos, tlen, qfmt);
2220                                 if (qlen)
2221                                         i_len = get_indent_length
2222                                                 (text, cur_pos, tlen);
2223                                 else
2224                                         i_len = 0;
2225                         }
2226                         is_new_line = FALSE;
2227                         p_pos = cur_pos;
2228 #ifdef WRAP_DEBUG
2229                         printf("new line i_len=%d qlen=%d p_pos=", i_len, qlen);
2230                         dump_text(text, p_pos, tlen, 1);
2231 #endif
2232                 }
2233
2234                 GET_CHAR(cur_pos, cbuf, ch_len);
2235
2236                 /* fix line length for tabs */
2237                 if (ch_len == 1 && *cbuf == '\t') {
2238                         guint tab_width = text->default_tab_width;
2239                         guint tab_offset = line_len % tab_width;
2240
2241 #ifdef WRAP_DEBUG
2242                         printf("found tab at pos=%d line_len=%d ", cur_pos,
2243                                 line_len);
2244 #endif
2245                         if (tab_offset) {
2246                                 line_len += tab_width - tab_offset - 1;
2247                                 cur_len = line_len;
2248                         }
2249 #ifdef WRAP_DEBUG
2250                         printf("new_len=%d\n", line_len);
2251 #endif
2252                 }
2253
2254                 /* we have encountered line break */
2255                 if (ch_len == 1 && *cbuf == '\n') {
2256                         gint clen;
2257                         guint ilen;
2258                         gchar cb[MB_CUR_MAX];
2259
2260 #ifdef WRAP_DEBUG
2261                         printf("found CR at %d next line is ", cur_pos);
2262                         dump_text(text, cur_pos + 1, tlen, 1);
2263 #endif
2264                         /* if it's just quotation + newline skip it */
2265                         if (i_len && (cur_pos + 1 < tlen)) {
2266                                 /* check if text at new line matches indent */
2267                                 ilen =  gtkut_text_str_compare_n
2268                                         (text, cur_pos + 1, p_pos, i_len, tlen);
2269                                 if (cur_pos + ilen < tlen) {
2270                                         GET_CHAR(cur_pos + ilen + 1, cb, clen);
2271                                         /* no need to join the lines */
2272                                         if (clen == 1 && cb[0] == '\n')
2273                                                 do_delete = FALSE;
2274                                 }
2275                         /* if it's just newline skip it */
2276                         } else if (do_delete && (cur_pos + 1 < tlen)) {
2277                                 GET_CHAR(cur_pos + 1, cb, clen);
2278                                 /* no need to join the lines */
2279                                 if (clen == 1 && cb[0] == '\n')
2280                                         do_delete = FALSE;
2281                         }
2282
2283 #ifdef WRAP_DEBUG
2284                         printf("qlen=%d l_len=%d wrap_len=%d do_del=%d\n",
2285                                 qlen, line_len, linewrap_len, do_delete);
2286 #endif
2287                         /* should we delete to perform smart wrapping */
2288                         if (line_len < linewrap_len && do_delete) {
2289                                 /* get rid of newline */
2290                                 gtk_stext_set_point(text, cur_pos);
2291                                 gtk_stext_forward_delete(text, 1);
2292                                 tlen--;
2293
2294                                 /* if text starts with quote fmt or with
2295                                    indent string, delete them */
2296                                 if (i_len) {
2297                                         ilen =  gtkut_text_str_compare_n
2298                                                 (text, cur_pos, p_pos, i_len,
2299                                                  tlen);
2300                                         if (ilen) {
2301                                                 gtk_stext_forward_delete(text,
2302                                                                          ilen);
2303                                                 tlen -= ilen;
2304                                         }
2305                                 } else if (qlen) {
2306                                         if (gtkut_text_str_compare
2307                                             (text, cur_pos, tlen, qfmt)) {
2308                                                 gtk_stext_forward_delete
2309                                                         (text, qlen);
2310                                                 tlen -= qlen;
2311                                         }
2312                                 }
2313
2314                                 GET_CHAR(cur_pos, cb, clen);
2315
2316                                 /* insert space if it's alphanumeric */
2317                                 if ((cur_pos != line_pos) &&
2318                                     ((clen > 1) || isalnum(cb[0]))) {
2319                                         gtk_stext_insert(text, NULL, NULL,
2320                                                         NULL, " ", 1);
2321                                         /* gtk_text_compact_buffer(text); */
2322                                         tlen++;
2323                                 }
2324
2325                                 /* and start over with current line */
2326                                 cur_pos = p_pos - 1;
2327                                 line_pos = cur_pos;
2328                                 line_len = cur_len = 0;
2329                                 qlen = 0;
2330                                 do_delete = FALSE;
2331                                 is_new_line = TRUE;
2332 #ifdef WRAP_DEBUG
2333                                 printf("after delete l_pos=");
2334                                 dump_text(text, line_pos, tlen, 1);
2335 #endif
2336                                 continue;
2337                         }
2338
2339                         /* mark new line beginning */
2340                         line_pos = cur_pos + 1;
2341                         line_len = cur_len = 0;
2342                         qlen = 0;
2343                         do_delete = FALSE;
2344                         is_new_line = TRUE;
2345                         continue;
2346                 }
2347
2348                 if (ch_len < 0) {
2349                         cbuf[0] = '\0';
2350                         ch_len = 1;
2351                 }
2352
2353                 /* possible line break */
2354                 if (ch_len == 1 && isspace(*cbuf)) {
2355                         line_pos = cur_pos + 1;
2356                         line_len = cur_len + ch_len;
2357                 }
2358
2359                 /* are we over wrapping length set in preferences ? */
2360                 if (cur_len + ch_len > linewrap_len) {
2361                         gint clen;
2362
2363 #ifdef WRAP_DEBUG
2364                         printf("should wrap cur_pos=%d ", cur_pos);
2365                         dump_text(text, p_pos, tlen, 1);
2366                         dump_text(text, line_pos, tlen, 1);
2367 #endif
2368                         /* force wrapping if it is one long word but not URL */
2369                         if (p_pos + i_len == line_pos)
2370                                 if (!gtkut_text_is_uri_string
2371                                     (text, line_pos, tlen))
2372                                         line_pos = cur_pos - 1;
2373 #ifdef WRAP_DEBUG
2374                         printf("new line_pos=%d\n", line_pos);
2375 #endif
2376
2377                         GET_CHAR(line_pos - 1, cbuf, clen);
2378
2379                         /* if next character is space delete it */
2380                         if (clen == 1 && isspace(*cbuf)) {
2381                                 if (p_pos + i_len != line_pos ||
2382                                     !gtkut_text_is_uri_string
2383                                         (text, line_pos, tlen)) {
2384                                         gtk_stext_set_point(text, line_pos);
2385                                         gtk_stext_backward_delete(text, 1);
2386                                         tlen--;
2387                                         cur_pos--;
2388                                         line_pos--;
2389                                         cur_len--;
2390                                         line_len--;
2391                                 }
2392                         }
2393
2394                         /* if it is URL at beginning of line don't wrap */
2395                         if (p_pos + i_len == line_pos &&
2396                             gtkut_text_is_uri_string(text, line_pos, tlen)) {
2397 #ifdef WRAP_DEBUG
2398                                 printf("found URL at ");
2399                                 dump_text(text, line_pos, tlen, 1);
2400 #endif
2401                                 continue;
2402                         }
2403
2404                         /* insert CR */
2405                         gtk_stext_set_point(text, line_pos);
2406                         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1);
2407                         /* gtk_stext_compact_buffer(text); */
2408                         tlen++;
2409                         line_pos++;
2410                         /* for loop will increase it */
2411                         cur_pos = line_pos - 1;
2412                         /* start over with current line */
2413                         is_new_line = TRUE;
2414                         line_len = 0;
2415                         cur_len = 0;
2416                         do_delete = TRUE;
2417 #ifdef WRAP_DEBUG
2418                         printf("after CR insert ");
2419                         dump_text(text, line_pos, tlen, 1);
2420                         dump_text(text, cur_pos, tlen, 1);
2421 #endif
2422
2423                         /* should we insert quotation ? */
2424                         if (linewrap_quote && qlen) {
2425                                 /* only if line is not already quoted  */
2426                                 if (!gtkut_text_str_compare
2427                                         (text, line_pos, tlen, qfmt)) {
2428                                         guint ins_len;
2429
2430                                         if (line_pos - p_pos > i_len) {
2431                                                 ins_len = ins_quote
2432                                                         (text, qlen, i_len,
2433                                                          p_pos, tlen, qfmt);
2434
2435                                                 /* gtk_stext_compact_buffer(text); */
2436                                                 tlen += ins_len;
2437                                         }
2438 #ifdef WRAP_DEBUG
2439                                         printf("after quote insert ");
2440                                         dump_text(text, line_pos, tlen, 1);
2441 #endif
2442                                 }
2443                         }
2444                         continue;
2445                 }
2446
2447                 if (ch_len > 1) {
2448                         line_pos = cur_pos + 1;
2449                         line_len = cur_len + ch_len;
2450                 }
2451                 /* advance to next character in buffer */
2452                 cur_len += ch_len;
2453         }
2454
2455         gtk_stext_thaw(text);
2456 }
2457 #undef GET_CHAR
2458
2459 static void compose_set_title(Compose *compose)
2460 {
2461         gchar *str;
2462         gchar *edited;
2463
2464         edited = compose->modified ? _(" [Edited]") : "";
2465         if (compose->account && compose->account->address)
2466                 str = g_strdup_printf(_("%s - Compose message%s"),
2467                                       compose->account->address, edited);
2468         else
2469                 str = g_strdup_printf(_("Compose message%s"), edited);
2470         gtk_window_set_title(GTK_WINDOW(compose->window), str);
2471         g_free(str);
2472 }
2473
2474 /**
2475  * compose_current_mail_account:
2476  * 
2477  * Find a current mail account (the currently selected account, or the
2478  * default account, if a news account is currently selected).  If a
2479  * mail account cannot be found, display an error message.
2480  * 
2481  * Return value: Mail account, or NULL if not found.
2482  **/
2483 static PrefsAccount *
2484 compose_current_mail_account(void)
2485 {
2486         PrefsAccount *ac;
2487
2488         if (cur_account && cur_account->protocol != A_NNTP)
2489                 ac = cur_account;
2490         else {
2491                 ac = account_get_default();
2492                 if (!ac || ac->protocol == A_NNTP) {
2493                         alertpanel_error(_("Account for sending mail is not specified.\n"
2494                                            "Please select a mail account before sending."));
2495                         return NULL;
2496                 }
2497         }
2498         return ac;
2499 }
2500
2501 gboolean compose_check_for_valid_recipient(Compose *compose) {
2502         gchar *recipient_headers_mail[] = {"To:", "Cc:", "Bcc:", NULL};
2503         gchar *recipient_headers_news[] = {"Newsgroups:", NULL};
2504         gboolean recipient_found = FALSE;
2505         GSList *list;
2506         gchar **strptr;
2507
2508         /* free to and newsgroup list */
2509         slist_free_strings(compose->to_list);
2510         g_slist_free(compose->to_list);
2511         compose->to_list = NULL;
2512                         
2513         slist_free_strings(compose->newsgroup_list);
2514         g_slist_free(compose->newsgroup_list);
2515         compose->newsgroup_list = NULL;
2516
2517         /* search header entries for to and newsgroup entries */
2518         for(list = compose->header_list; list; list = list->next) {
2519                 gchar *header;
2520                 gchar *entry;
2521                 header = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(((ComposeHeaderEntry *)list->data)->combo)->entry));
2522                 entry = gtk_editable_get_chars(GTK_EDITABLE(((ComposeHeaderEntry *)list->data)->entry), 0, -1);
2523                 g_strstrip(entry);
2524                 if(entry[0] != '\0') {
2525                         for(strptr = recipient_headers_mail; *strptr != NULL; strptr++) {
2526                                 if(!strcmp(header, (prefs_common.trans_hdr ? gettext(*strptr) : *strptr))) {
2527                                         compose->to_list = address_list_append(compose->to_list, entry);
2528                                         recipient_found = TRUE;
2529                                 }
2530                         }
2531                         for(strptr = recipient_headers_news; *strptr != NULL; strptr++) {
2532                                 if(!strcmp(header, (prefs_common.trans_hdr ? gettext(*strptr) : *strptr))) {
2533                                         compose->newsgroup_list = newsgroup_list_append(compose->newsgroup_list, entry);
2534                                         recipient_found = TRUE;
2535                                 }
2536                         }
2537                 }
2538                 g_free(entry);
2539         }
2540         return recipient_found;
2541 }
2542
2543 gint compose_send(Compose *compose)
2544 {
2545         gint msgnum;
2546         FolderItem *folder;
2547         gint val;
2548
2549         val = compose_queue(compose, &msgnum, &folder);
2550         if (val) {
2551                 alertpanel_error(_("Could not queue message for sending"));
2552                 return -1;
2553         }
2554         
2555         val = procmsg_send_message_queue(folder_item_fetch_msg(folder, msgnum));
2556         if(!val) {
2557                 folder_item_remove_msg(folder, msgnum);
2558                 folderview_update_item(folder, TRUE);
2559         }
2560
2561         return val;
2562 }
2563
2564 #if 0 /* compose restructure */
2565 gint compose_send(Compose *compose)
2566 {
2567         gchar tmp[MAXPATHLEN + 1];
2568         gint ok = 0;
2569         static gboolean lock = FALSE;
2570
2571         if (lock) return 1;
2572
2573         g_return_val_if_fail(compose->account != NULL, -1);
2574         g_return_val_if_fail(compose->orig_account != NULL, -1);
2575
2576         lock = TRUE;
2577
2578         if(!compose_check_for_valid_recipient(compose)) {
2579                 alertpanel_error(_("Recipient is not specified."));
2580                 lock = FALSE;
2581                 return 1;
2582         }
2583
2584         /* write to temporary file */
2585         g_snprintf(tmp, sizeof(tmp), "%s%ctmpmsg%d",
2586                    get_rc_dir(), G_DIR_SEPARATOR, (gint)compose);
2587
2588         if (prefs_common.linewrap_at_send)
2589                 compose_wrap_line_all(compose);
2590
2591         if (compose_write_to_file(compose, tmp, FALSE) < 0) {
2592                 lock = FALSE;
2593                 return -1;
2594         }
2595
2596         if (!compose->to_list && !compose->newsgroup_list) {
2597                 g_warning(_("can't get recipient list."));
2598                 unlink(tmp);
2599                 lock = FALSE;
2600                 return -1;
2601         }
2602
2603         if (compose->to_list) {
2604                 PrefsAccount *ac;
2605
2606 #if 0 /* NEW COMPOSE GUI */
2607                 if (compose->account->protocol != A_NNTP)
2608                         ac = compose->account;
2609                 else if (compose->orig_account->protocol != A_NNTP)
2610                         ac = compose->orig_account;
2611                 else if (cur_account && cur_account->protocol != A_NNTP)
2612                         ac = cur_account;
2613                 else {
2614                         ac = compose_current_mail_account();
2615                         if (!ac) {
2616                                 unlink(tmp);
2617                                 lock = FALSE;
2618                                 return -1;
2619                         }
2620                 }
2621 #endif
2622                 ac = compose->account;
2623
2624                 ok = send_message(tmp, ac, compose->to_list);
2625                 statusbar_pop_all();
2626         }
2627
2628         if (ok == 0 && compose->newsgroup_list) {
2629                 Folder *folder;
2630
2631                 if (compose->account->protocol == A_NNTP)
2632                         folder = FOLDER(compose->account->folder);
2633                 else
2634                         folder = FOLDER(compose->orig_account->folder);
2635
2636                 ok = news_post(folder, tmp);
2637                 if (ok < 0) {
2638                         alertpanel_error(_("Error occurred while posting the message to %s ."),
2639                                          compose->account->nntp_server);
2640                         unlink(tmp);
2641                         lock = FALSE;
2642                         return -1;
2643                 }
2644         }
2645
2646         /* queue message if failed to send */
2647         if (ok < 0) {
2648                 if (prefs_common.queue_msg) {
2649                         AlertValue val;
2650
2651                         val = alertpanel
2652                                 (_("Queueing"),
2653                                  _("Error occurred while sending the message.\n"
2654                                    "Put this message into queue folder?"),
2655                                  _("OK"), _("Cancel"), NULL);
2656                         if (G_ALERTDEFAULT == val) {
2657                                 ok = compose_queue(compose, tmp);
2658                                 if (ok < 0)
2659                                         alertpanel_error(_("Can't queue the message."));
2660                         }
2661                 } else
2662                         alertpanel_error(_("Error occurred while sending the message."));
2663         } else {
2664                 if (compose->mode == COMPOSE_REEDIT) {
2665                         compose_remove_reedit_target(compose);
2666                         if (compose->targetinfo)
2667                                 folderview_update_item
2668                                         (compose->targetinfo->folder, TRUE);
2669                 }
2670         }
2671
2672         /* save message to outbox */
2673         if (ok == 0 && prefs_common.savemsg) {
2674                 if (compose_save_to_outbox(compose, tmp) < 0)
2675                         alertpanel_error
2676                                 (_("Can't save the message to outbox."));
2677         }
2678
2679         unlink(tmp);
2680         lock = FALSE;
2681         return ok;
2682 }
2683 #endif
2684
2685 static gboolean compose_use_attach(Compose *compose) {
2686     return(gtk_clist_get_row_data(GTK_CLIST(compose->attach_clist), 0) != NULL);
2687 }
2688
2689 static gint compose_bounce_write_headers_from_headerlist(Compose *compose, 
2690                                                          FILE *fp)
2691 {
2692         gchar buf[BUFFSIZE];
2693         gchar *str;
2694         gboolean first_address;
2695         GSList *list;
2696         ComposeHeaderEntry *headerentry;
2697         gchar *headerentryname;
2698         gchar *header_w_colon;
2699         gchar *cc_hdr;
2700         gchar *to_hdr;
2701
2702         debug_print(_("Writing bounce header\n"));
2703
2704         header_w_colon = g_strconcat("To:", NULL);
2705         to_hdr = (prefs_common.trans_hdr ? gettext(header_w_colon) : header_w_colon);
2706         header_w_colon = g_strconcat("Cc:", NULL);
2707         cc_hdr = (prefs_common.trans_hdr ? gettext(header_w_colon) : header_w_colon);
2708         
2709         first_address = TRUE;
2710         for(list = compose->header_list; list; list = list->next) {
2711                 headerentry = ((ComposeHeaderEntry *)list->data);
2712                 headerentryname = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry));
2713
2714                 if(g_strcasecmp(headerentryname, cc_hdr) == 0 
2715                    || g_strcasecmp(headerentryname, to_hdr) == 0) {
2716                         str = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
2717                         Xstrdup_a(str, str, return -1);
2718                         g_strstrip(str);
2719                         if(str[0] != '\0') {
2720                                 compose_convert_header
2721                                         (buf, sizeof(buf), str,
2722                                         strlen("Resent-To") + 2);
2723                                 if(first_address) {
2724                                         fprintf(fp, "Resent-To: ");
2725                                         first_address = FALSE;
2726                                 } else {
2727                                         fprintf(fp, ",");
2728                                 }
2729                                 fprintf(fp, "%s", buf);
2730                         }
2731                 }
2732         }
2733         /* if(!first_address) { */
2734         fprintf(fp, "\n");
2735         /* } */
2736
2737         return(0);
2738 }
2739
2740 static gint compose_bounce_write_headers(Compose *compose, FILE *fp)
2741 {
2742         gchar buf[BUFFSIZE];
2743         gchar *str;
2744         /* struct utsname utsbuf; */
2745
2746         g_return_val_if_fail(fp != NULL, -1);
2747         g_return_val_if_fail(compose->account != NULL, -1);
2748         g_return_val_if_fail(compose->account->address != NULL, -1);
2749
2750         /* Date */
2751         get_rfc822_date(buf, sizeof(buf));
2752         fprintf(fp, "Resent-Date: %s\n", buf);
2753
2754         /* From */
2755         if (compose->account->name && *compose->account->name) {
2756                 compose_convert_header
2757                         (buf, sizeof(buf), compose->account->name,
2758                          strlen("From: "));
2759                 fprintf(fp, "Resent-From: %s <%s>\n",
2760                         buf, compose->account->address);
2761         } else
2762                 fprintf(fp, "Resent-From: %s\n", compose->account->address);
2763
2764         /* To */
2765         compose_bounce_write_headers_from_headerlist(compose, fp);
2766
2767         /* separator between header and body */
2768         fputs("\n", fp);
2769
2770         return 0;
2771 }
2772
2773 static gint compose_bounce_write_to_file(Compose *compose, const gchar *file)
2774 {
2775         FILE *fp;
2776         FILE *fdest;
2777         size_t len;
2778         gchar buf[BUFFSIZE];
2779
2780         if ((fp = fopen(compose->bounce_filename, "r")) == NULL) {
2781                 FILE_OP_ERROR(file, "fopen");
2782                 return -1;
2783         }
2784
2785         if ((fdest = fopen(file, "w")) == NULL) {
2786                 FILE_OP_ERROR(file, "fopen");
2787                 fclose(fp);
2788                 return -1;
2789         }
2790
2791         /* chmod for security */
2792         if (change_file_mode_rw(fdest, file) < 0) {
2793                 FILE_OP_ERROR(file, "chmod");
2794                 g_warning(_("can't change file mode\n"));
2795         }
2796
2797         while (procheader_get_unfolded_line(buf, sizeof(buf), fp)) {
2798                 /* should filter returnpath, delivered-to */
2799                 if ((g_strncasecmp(buf, "Return-Path:",
2800                                    strlen("Return-Path:")) == 0)
2801                     || (g_strncasecmp(buf, "Delivered-To:",
2802                                       strlen("Delivered-To:")) == 0))
2803                         continue;
2804
2805                 if (fputs(buf, fdest) == -1)
2806                         goto error;
2807
2808                 if (g_strncasecmp(buf, "From:", strlen("From:")) == 0) {
2809                         fputs(" (by way of ", fdest);
2810                         if (compose->account->name
2811                             && *compose->account->name) {
2812                                 compose_convert_header
2813                                         (buf, sizeof(buf),
2814                                          compose->account->name,
2815                                          strlen("From: "));
2816                                 fprintf(fdest, "%s <%s>",
2817                                         buf, compose->account->address);
2818                         } else
2819                                 fprintf(fdest, "%s",
2820                                         compose->account->address);
2821                         fputs(")", fdest);
2822                 }
2823
2824                 if (fputs("\n", fdest) == -1)
2825                         goto error;
2826         }
2827
2828         compose_bounce_write_headers(compose, fdest);
2829
2830         while ((len = fread(buf, sizeof(gchar), BUFFSIZE, fp)) > 0) {
2831                 if (fwrite(buf, sizeof(gchar), len, fdest) == -1)
2832                         goto error;
2833         }
2834
2835         fclose(fdest);
2836         fclose(fp);
2837
2838         return 0;
2839  error:
2840         fclose(fdest);
2841         fclose(fp);
2842
2843         return -1;
2844 }
2845
2846 static gint compose_write_to_file(Compose *compose, const gchar *file,
2847                                   gboolean is_draft)
2848 {
2849         FILE *fp;
2850         size_t len;
2851         gchar *chars;
2852         gchar *buf;
2853         const gchar *out_codeset;
2854         EncodingType encoding;
2855
2856         if ((fp = fopen(file, "w")) == NULL) {
2857                 FILE_OP_ERROR(file, "fopen");
2858                 return -1;
2859         }
2860
2861         /* chmod for security */
2862         if (change_file_mode_rw(fp, file) < 0) {
2863                 FILE_OP_ERROR(file, "chmod");
2864                 g_warning(_("can't change file mode\n"));
2865         }
2866
2867         /* get all composed text */
2868         chars = gtk_editable_get_chars(GTK_EDITABLE(compose->text), 0, -1);
2869         len = strlen(chars);
2870         if (is_ascii_str(chars)) {
2871                 buf = g_strdup(chars);
2872                 out_codeset = CS_US_ASCII;
2873                 encoding = ENC_7BIT;
2874         } else {
2875                 const gchar *src_codeset;
2876
2877                 out_codeset = conv_get_outgoing_charset_str();
2878                 if (!strcasecmp(out_codeset, CS_US_ASCII))
2879                         out_codeset = CS_ISO_8859_1;
2880                 encoding = procmime_get_encoding_for_charset(out_codeset);
2881
2882                 src_codeset = conv_get_current_charset_str();
2883                 /* if current encoding is US-ASCII, set it the same as
2884                    outgoing one to prevent code conversion failure */
2885                 if (!strcasecmp(src_codeset, CS_US_ASCII))
2886                         src_codeset = out_codeset;
2887
2888                 debug_print("src encoding = %s, out encoding = %s, transfer encoding = %s\n",
2889                             src_codeset, out_codeset, procmime_get_encoding_str(encoding));
2890
2891                 buf = conv_codeset_strdup(chars, src_codeset, out_codeset);
2892                 if (!buf) {
2893                         g_free(chars);
2894                         fclose(fp);
2895                         unlink(file);
2896                         alertpanel_error(_("Can't convert the codeset of the message."));
2897                         return -1;
2898                 }
2899         }
2900         g_free(chars);
2901
2902         /* write headers */
2903         if (compose_write_headers
2904                 (compose, fp, out_codeset, encoding, is_draft) < 0) {
2905                 g_warning(_("can't write headers\n"));
2906                 fclose(fp);
2907                 /* unlink(file); */
2908                 g_free(buf);
2909                 return -1;
2910         }
2911
2912         if (compose_use_attach(compose)) {
2913 #if USE_GPGME
2914             /* This prolog message is ignored by mime software and
2915              * because it would make our signing/encryption task
2916              * tougher, we don't emit it in that case */
2917             if (!compose->use_signing && !compose->use_encryption)
2918 #endif
2919                 fputs("This is a multi-part message in MIME format.\n", fp);
2920
2921                 fprintf(fp, "\n--%s\n", compose->boundary);
2922                 fprintf(fp, "Content-Type: text/plain; charset=%s\n",
2923                         out_codeset);
2924                 fprintf(fp, "Content-Transfer-Encoding: %s\n",
2925                         procmime_get_encoding_str(encoding));
2926                 fputc('\n', fp);
2927         }
2928
2929         /* write body */
2930         len = strlen(buf);
2931         if (encoding == ENC_BASE64) {
2932                 gchar outbuf[B64_BUFFSIZE];
2933                 gint i, l;
2934
2935                 for (i = 0; i < len; i += B64_LINE_SIZE) {
2936                         l = MIN(B64_LINE_SIZE, len - i);
2937                         to64frombits(outbuf, buf + i, l);
2938                         fputs(outbuf, fp);
2939                         fputc('\n', fp);
2940                 }
2941         } else if (fwrite(buf, sizeof(gchar), len, fp) != len) {
2942                 FILE_OP_ERROR(file, "fwrite");
2943                 fclose(fp);
2944                 unlink(file);
2945                 g_free(buf);
2946                 return -1;
2947         }
2948         g_free(buf);
2949
2950         if (compose_use_attach(compose))
2951                 compose_write_attach(compose, fp);
2952
2953         if (fclose(fp) == EOF) {
2954                 FILE_OP_ERROR(file, "fclose");
2955                 unlink(file);
2956                 return -1;
2957         }
2958
2959 #if USE_GPGME
2960         if (compose->use_signing) {
2961                 if (rfc2015_sign(file, compose->account) < 0) {
2962                         unlink(file);
2963                         return -1;
2964                 }
2965         }
2966         if (compose->use_encryption) {
2967                 if (rfc2015_encrypt(file, compose->to_list) < 0) {
2968                         unlink(file);
2969                         return -1;
2970                 }
2971         }
2972 #endif /* USE_GPGME */
2973
2974         return 0;
2975 }
2976
2977 static gint compose_write_body_to_file(Compose *compose, const gchar *file)
2978 {
2979         FILE *fp;
2980         size_t len;
2981         gchar *chars;
2982
2983         if ((fp = fopen(file, "w")) == NULL) {
2984                 FILE_OP_ERROR(file, "fopen");
2985                 return -1;
2986         }
2987
2988         /* chmod for security */
2989         if (change_file_mode_rw(fp, file) < 0) {
2990                 FILE_OP_ERROR(file, "chmod");
2991                 g_warning(_("can't change file mode\n"));
2992         }
2993
2994         chars = gtk_editable_get_chars(GTK_EDITABLE(compose->text), 0, -1);
2995
2996         /* write body */
2997         len = strlen(chars);
2998         if (fwrite(chars, sizeof(gchar), len, fp) != len) {
2999                 FILE_OP_ERROR(file, "fwrite");
3000                 g_free(chars);
3001                 fclose(fp);
3002                 unlink(file);
3003                 return -1;
3004         }
3005
3006         g_free(chars);
3007
3008         if (fclose(fp) == EOF) {
3009                 FILE_OP_ERROR(file, "fclose");
3010                 unlink(file);
3011                 return -1;
3012         }
3013         return 0;
3014 }
3015
3016 static gint compose_save_to_outbox(Compose *compose, const gchar *file)
3017 {
3018         FolderItem *outbox;
3019         gchar *path;
3020         gint num;
3021         FILE *fp;
3022
3023         debug_print(_("saving sent message...\n"));
3024
3025         outbox = folder_get_default_outbox();
3026         path = folder_item_get_path(outbox);
3027         if (!is_dir_exist(path))
3028                 make_dir_hier(path);
3029
3030         folder_item_scan(outbox);
3031         if ((num = folder_item_add_msg(outbox, file, FALSE)) < 0) {
3032                 g_free(path);
3033                 g_warning(_("can't save message\n"));
3034                 return -1;
3035         }
3036
3037         if ((fp = procmsg_open_mark_file(path, TRUE)) == NULL)
3038                 g_warning(_("can't open mark file\n"));
3039         else {
3040                 MsgInfo newmsginfo;
3041
3042                 newmsginfo.msgnum = num;
3043                 newmsginfo.flags.perm_flags = 0;
3044                 newmsginfo.flags.tmp_flags = 0;
3045                 procmsg_write_flags(&newmsginfo, fp);
3046                 fclose(fp);
3047         }
3048         g_free(path);
3049
3050         return 0;
3051 }
3052
3053 static gint compose_remove_reedit_target(Compose *compose)
3054 {
3055         FolderItem *item;
3056         MsgInfo *msginfo = compose->targetinfo;
3057
3058         g_return_val_if_fail(compose->mode == COMPOSE_REEDIT, -1);
3059         if (!msginfo) return -1;
3060
3061         item = msginfo->folder;
3062         g_return_val_if_fail(item != NULL, -1);
3063
3064         folder_item_scan(item);
3065         if (procmsg_msg_exist(msginfo) &&
3066             (item->stype == F_DRAFT || item->stype == F_QUEUE)) {
3067                 if (folder_item_remove_msg(item, msginfo->msgnum) < 0) {
3068                         g_warning(_("can't remove the old message\n"));
3069                         return -1;
3070                 }
3071         }
3072
3073         return 0;
3074 }
3075
3076
3077 static gint compose_queue(Compose *compose, gint *msgnum, FolderItem **item)
3078 {
3079         FolderItem *queue;
3080         gchar *tmp, *tmp2, *queue_path;
3081         FILE *fp, *src_fp;
3082         GSList *cur;
3083         gchar buf[BUFFSIZE];
3084         gint num;
3085         static gboolean lock = FALSE;
3086         PrefsAccount *mailac = NULL, *newsac = NULL;
3087         
3088         debug_print(_("queueing message...\n"));
3089         g_return_val_if_fail(compose->account != NULL, -1);
3090         g_return_val_if_fail(compose->orig_account != NULL, -1);
3091
3092         lock = TRUE;
3093         
3094         if(!compose_check_for_valid_recipient(compose)) {
3095                 alertpanel_error(_("Recipient is not specified."));
3096                 lock = FALSE;
3097                 return -1;
3098         }
3099                                                                         
3100         if (!compose->to_list && !compose->newsgroup_list) {
3101                 g_warning(_("can't get recipient list."));
3102                 lock = FALSE;
3103                 return -1;
3104         }
3105
3106         if(compose->to_list) {
3107                 if (compose->account->protocol != A_NNTP)
3108                         mailac = compose->account;
3109                 else if (compose->orig_account->protocol != A_NNTP)
3110                         mailac = compose->orig_account;
3111                 else if (cur_account && cur_account->protocol != A_NNTP)
3112                         mailac = cur_account;
3113                 else if (!(mailac = compose_current_mail_account())) {
3114                         lock = FALSE;
3115                         alertpanel_error(_("No account for sending mails available!"));
3116                         return -1;
3117                 }
3118         }
3119
3120         if(compose->newsgroup_list) {
3121                 if (compose->account->protocol == A_NNTP)
3122                         newsac = compose->account;
3123                 else if(!(newsac = compose->orig_account) || (newsac->protocol != A_NNTP)) {
3124                         lock = FALSE;
3125                         alertpanel_error(_("No account for posting news available!"));
3126                         return -1;
3127                 }                       
3128         }
3129
3130         if (prefs_common.linewrap_at_send)
3131                 compose_wrap_line_all(compose);
3132                         
3133         /* write to temporary file */
3134         tmp2 = g_strdup_printf("%s%ctmp%d", g_get_tmp_dir(),
3135                                       G_DIR_SEPARATOR, (gint)compose);
3136
3137         if (compose->bounce_filename != NULL) {
3138                 if (compose_bounce_write_to_file(compose, tmp2) < 0) {
3139                         unlink(tmp2);
3140                         lock = FALSE;
3141                         return -1;
3142                 }
3143         }
3144         else {
3145                 if (compose_write_to_file(compose, tmp2, FALSE) < 0) {
3146                         unlink(tmp2);
3147                         lock = FALSE;
3148                         return -1;
3149                 }
3150         }
3151
3152         /* add queue header */
3153         tmp = g_strdup_printf("%s%cqueue.%d", g_get_tmp_dir(),
3154                                       G_DIR_SEPARATOR, (gint)compose);
3155         if ((fp = fopen(tmp, "w")) == NULL) {
3156                 FILE_OP_ERROR(tmp, "fopen");
3157                 g_free(tmp);
3158                 return -1;
3159         }
3160         if ((src_fp = fopen(tmp2, "r")) == NULL) {
3161                 FILE_OP_ERROR(tmp2, "fopen");
3162                 fclose(fp);
3163                 unlink(tmp);
3164                 g_free(tmp);
3165                 unlink(tmp2);
3166                 g_free(tmp2);
3167                 return -1;
3168         }
3169         if (change_file_mode_rw(fp, tmp) < 0) {
3170                 FILE_OP_ERROR(tmp, "chmod");
3171                 g_warning(_("can't change file mode\n"));
3172         }
3173
3174         /* queueing variables */
3175         fprintf(fp, "AF:\n");
3176         fprintf(fp, "NF:0\n");
3177         fprintf(fp, "PS:10\n");
3178         fprintf(fp, "SRH:1\n");
3179         fprintf(fp, "SFN:\n");
3180         fprintf(fp, "DSR:\n");
3181         if (compose->msgid)
3182                 fprintf(fp, "MID:<%s>\n", compose->msgid);
3183         else
3184                 fprintf(fp, "MID:\n");
3185         fprintf(fp, "CFG:\n");
3186         fprintf(fp, "PT:0\n");
3187         fprintf(fp, "S:%s\n", compose->account->address);
3188         fprintf(fp, "RQ:\n");
3189         if (mailac)
3190                 fprintf(fp, "SSV:%s\n", mailac->smtp_server);
3191         else
3192                 fprintf(fp, "SSV:\n");
3193         if (newsac)
3194                 fprintf(fp, "NSV:%s\n", newsac->nntp_server);
3195         else
3196                 fprintf(fp, "NSV:\n");
3197         fprintf(fp, "SSH:\n");
3198         /* write recepient list */
3199         fprintf(fp, "R:");
3200         if(compose->to_list) {
3201                 fprintf(fp, "<%s>", (gchar *)compose->to_list->data);
3202                 for (cur = compose->to_list->next; cur != NULL; cur = cur->next)
3203                         fprintf(fp, ",<%s>", (gchar *)cur->data);
3204         }
3205         fprintf(fp, "\n");
3206         /* write newsgroup list */
3207         fprintf(fp, "NG:");
3208         if(compose->newsgroup_list) {
3209                 fprintf(fp, "%s", (gchar *)compose->newsgroup_list->data);
3210                 for (cur = compose->newsgroup_list->next; cur != NULL; cur = cur->next)
3211                         fprintf(fp, ",%s", (gchar *)cur->data);
3212         }
3213         fprintf(fp, "\n");
3214         /* Sylpheed account IDs */
3215         if(mailac) {
3216                 fprintf(fp, "MAID:%d\n", mailac->account_id);
3217         }
3218         if(newsac) {
3219                 fprintf(fp, "NAID:%d\n", newsac->account_id);
3220         }
3221         /* Save copy folder */
3222         if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn))) {
3223                 gchar *str;
3224                 
3225                 str = gtk_editable_get_chars(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
3226                 fprintf(fp, "SCF:%s\n", str);
3227                 g_free(str);
3228         }
3229         fprintf(fp, "\n");
3230
3231         while (fgets(buf, sizeof(buf), src_fp) != NULL) {
3232                 if (fputs(buf, fp) == EOF) {
3233                         FILE_OP_ERROR(tmp, "fputs");
3234                         fclose(fp);
3235                         fclose(src_fp);
3236                         unlink(tmp);
3237                         g_free(tmp);
3238                         unlink(tmp2);
3239                         g_free(tmp2);
3240                         return -1;
3241                 }
3242         }
3243         fclose(src_fp);
3244         if (fclose(fp) == EOF) {
3245                 FILE_OP_ERROR(tmp, "fclose");
3246                 unlink(tmp);
3247                 g_free(tmp);
3248                 unlink(tmp2);
3249                 g_free(tmp2);
3250                 return -1;
3251         }
3252                                                 
3253         /* queue message */
3254         queue = folder_get_default_queue();
3255
3256         folder_item_scan(queue);
3257         queue_path = folder_item_get_path(queue);
3258         if (!is_dir_exist(queue_path))
3259                 make_dir_hier(queue_path);
3260         if ((num = folder_item_add_msg(queue, tmp, TRUE)) < 0) {
3261                 g_warning(_("can't queue the message\n"));
3262                 unlink(tmp);
3263                 g_free(tmp);
3264                 g_free(queue_path);
3265                 return -1;
3266         }
3267         unlink(tmp);
3268         g_free(tmp);
3269         unlink(tmp2);
3270         g_free(tmp2);
3271
3272         if (compose->mode == COMPOSE_REEDIT) {
3273                 compose_remove_reedit_target(compose);
3274                 if (compose->targetinfo &&
3275                     compose->targetinfo->folder != queue)
3276                         folderview_update_item
3277                                 (compose->targetinfo->folder, TRUE);
3278         }
3279
3280         if ((fp = procmsg_open_mark_file(queue_path, TRUE)) == NULL)
3281                 g_warning(_("can't open mark file\n"));
3282         else {
3283                 MsgInfo newmsginfo;
3284
3285                 newmsginfo.msgnum = num;
3286                 newmsginfo.flags.perm_flags = 0;
3287                 newmsginfo.flags.tmp_flags = 0;
3288                 procmsg_write_flags(&newmsginfo, fp);
3289                 fclose(fp);
3290         }
3291         g_free(queue_path);
3292
3293         folder_item_scan(queue);
3294         folderview_update_item(queue, TRUE);
3295
3296         if((msgnum != NULL) && (item != NULL)) {
3297                 *msgnum = num;
3298                 *item = queue;
3299         }
3300
3301         return 0;
3302 }
3303
3304 static void compose_write_attach(Compose *compose, FILE *fp)
3305 {
3306         AttachInfo *ainfo;
3307         GtkCList *clist = GTK_CLIST(compose->attach_clist);
3308         gint row;
3309         FILE *attach_fp;
3310         gchar filename[BUFFSIZE];
3311         gint len;
3312
3313         for (row = 0; (ainfo = gtk_clist_get_row_data(clist, row)) != NULL;
3314              row++) {
3315                 if ((attach_fp = fopen(ainfo->file, "r")) == NULL) {
3316                         g_warning(_("Can't open file %s\n"), ainfo->file);
3317                         continue;
3318                 }
3319
3320                 fprintf(fp, "\n--%s\n", compose->boundary);
3321
3322                 if (!strcmp2(ainfo->content_type, "message/rfc822")) {
3323                         fprintf(fp, "Content-Type: %s\n", ainfo->content_type);
3324                         fprintf(fp, "Content-Disposition: inline\n");
3325                 } else {
3326                         conv_encode_header(filename, sizeof(filename),
3327                                            ainfo->name, 12);
3328                         fprintf(fp, "Content-Type: %s;\n"
3329                                     " name=\"%s\"\n",
3330                                 ainfo->content_type, filename);
3331                         fprintf(fp, "Content-Disposition: attachment;\n"
3332                                     " filename=\"%s\"\n", filename);
3333                 }
3334
3335                 fprintf(fp, "Content-Transfer-Encoding: %s\n\n",
3336                         procmime_get_encoding_str(ainfo->encoding));
3337
3338                 if (ainfo->encoding == ENC_7BIT) {
3339                         gchar buf[BUFFSIZE];
3340
3341                         while (fgets(buf, sizeof(buf), attach_fp) != NULL) {
3342                                 strcrchomp(buf);
3343                                 fputs(buf, fp);
3344                         }
3345                 } else {
3346                         gchar inbuf[B64_LINE_SIZE], outbuf[B64_BUFFSIZE];
3347
3348                         while ((len = fread(inbuf, sizeof(gchar),
3349                                             B64_LINE_SIZE, attach_fp))
3350                                == B64_LINE_SIZE) {
3351                                 to64frombits(outbuf, inbuf, B64_LINE_SIZE);
3352                                 fputs(outbuf, fp);
3353                                 fputc('\n', fp);
3354                         }
3355                         if (len > 0 && feof(attach_fp)) {
3356                                 to64frombits(outbuf, inbuf, len);
3357                                 fputs(outbuf, fp);
3358                                 fputc('\n', fp);
3359                         }
3360                 }
3361
3362                 fclose(attach_fp);
3363         }
3364
3365         fprintf(fp, "\n--%s--\n", compose->boundary);
3366 }
3367
3368 #define IS_IN_CUSTOM_HEADER(header) \
3369         (compose->account->add_customhdr && \
3370          custom_header_find(compose->account->customhdr_list, header) != NULL)
3371
3372 static gint compose_write_headers_from_headerlist(Compose *compose, 
3373                                                   FILE *fp, 
3374                                                   gchar *header)
3375 {
3376         gchar buf[BUFFSIZE];
3377         gchar *str, *header_w_colon, *trans_hdr;
3378         gboolean first_address;
3379         GSList *list;
3380         ComposeHeaderEntry *headerentry;
3381         gchar * headerentryname;
3382
3383         if (IS_IN_CUSTOM_HEADER(header)) {
3384                 return 0;
3385         }
3386
3387         debug_print(_("Writing %s-header\n"), header);
3388
3389         header_w_colon = g_strconcat(header, ":", NULL);
3390         trans_hdr = (prefs_common.trans_hdr ? gettext(header_w_colon) : header_w_colon);
3391
3392         first_address = TRUE;
3393         for(list = compose->header_list; list; list = list->next) {
3394                 headerentry = ((ComposeHeaderEntry *)list->data);
3395                 headerentryname = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry));
3396
3397                 if(!g_strcasecmp(trans_hdr, headerentryname)) {
3398                         str = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
3399                         Xstrdup_a(str, str, return -1);
3400                         g_strstrip(str);
3401                         if(str[0] != '\0') {
3402                                 compose_convert_header
3403                                         (buf, sizeof(buf), str,
3404                                         strlen(header) + 2);
3405                                 if(first_address) {
3406                                         fprintf(fp, "%s: ", header);
3407                                         first_address = FALSE;
3408                                 } else {
3409                                         fprintf(fp, ",");
3410                                 }
3411                                 fprintf(fp, "%s", buf);
3412                         }
3413                 }
3414         }
3415         if(!first_address) {
3416                 fprintf(fp, "\n");
3417         }
3418
3419         g_free(header_w_colon);
3420
3421         return(0);
3422 }
3423
3424 static gint compose_write_headers(Compose *compose, FILE *fp,
3425                                   const gchar *charset, EncodingType encoding,
3426                                   gboolean is_draft)
3427 {
3428         gchar buf[BUFFSIZE];
3429         gchar *str;
3430         /* struct utsname utsbuf; */
3431
3432         g_return_val_if_fail(fp != NULL, -1);
3433         g_return_val_if_fail(charset != NULL, -1);
3434         g_return_val_if_fail(compose->account != NULL, -1);
3435         g_return_val_if_fail(compose->account->address != NULL, -1);
3436
3437         /* Date */
3438         if (compose->account->add_date) {
3439                 get_rfc822_date(buf, sizeof(buf));
3440                 fprintf(fp, "Date: %s\n", buf);
3441         }
3442
3443         /* From */
3444         if (!IS_IN_CUSTOM_HEADER("From")) {
3445                 if (compose->account->name && *compose->account->name) {
3446                         compose_convert_header
3447                                 (buf, sizeof(buf), compose->account->name,
3448                                  strlen("From: "));
3449                         fprintf(fp, "From: %s <%s>\n",
3450                                 buf, compose->account->address);
3451                 } else
3452                         fprintf(fp, "From: %s\n", compose->account->address);
3453         }
3454         
3455         /* To */
3456         compose_write_headers_from_headerlist(compose, fp, "To");
3457 #if 0 /* NEW COMPOSE GUI */
3458         if (compose->use_to) {
3459                 str = gtk_entry_get_text(GTK_ENTRY(compose->to_entry));
3460                 if (*str != '\0') {
3461                         Xstrdup_a(str, str, return -1);
3462                         g_strstrip(str);
3463                         if (*str != '\0') {
3464                                 compose->to_list = address_list_append
3465                                         (compose->to_list, str);
3466                                 if (!IS_IN_CUSTOM_HEADER("To")) {
3467                                         compose_convert_header
3468                                                 (buf, sizeof(buf), str,
3469                                                  strlen("To: "));
3470                                         fprintf(fp, "To: %s\n", buf);
3471                                 }
3472                         }
3473                 }
3474         }
3475 #endif
3476
3477         /* Newsgroups */
3478         compose_write_headers_from_headerlist(compose, fp, "Newsgroups");
3479 #if 0 /* NEW COMPOSE GUI */
3480         str = gtk_entry_get_text(GTK_ENTRY(compose->newsgroups_entry));
3481         if (*str != '\0') {
3482                 Xstrdup_a(str, str, return -1);
3483                 g_strstrip(str);
3484                 remove_space(str);
3485                 if (*str != '\0') {
3486                         compose->newsgroup_list =
3487                                 newsgroup_list_append(compose->newsgroup_list,
3488                                                       str);
3489                         if (!IS_IN_CUSTOM_HEADER("Newsgroups")) {
3490                                 compose_convert_header(buf, sizeof(buf), str,
3491                                                        strlen("Newsgroups: "));
3492                                 fprintf(fp, "Newsgroups: %s\n", buf);
3493                         }
3494                 }
3495         }
3496 #endif
3497         /* Cc */
3498         compose_write_headers_from_headerlist(compose, fp, "Cc");
3499 #if 0 /* NEW COMPOSE GUI */
3500         if (compose->use_cc) {
3501                 str = gtk_entry_get_text(GTK_ENTRY(compose->cc_entry));
3502                 if (*str != '\0') {
3503                         Xstrdup_a(str, str, return -1);
3504                         g_strstrip(str);
3505                         if (*str != '\0') {
3506                                 compose->to_list = address_list_append
3507                                         (compose->to_list, str);
3508                                 if (!IS_IN_CUSTOM_HEADER("Cc")) {
3509                                         compose_convert_header
3510                                                 (buf, sizeof(buf), str,
3511                                                  strlen("Cc: "));
3512                                         fprintf(fp, "Cc: %s\n", buf);
3513                                 }
3514                         }
3515                 }
3516         }
3517 #endif
3518         /* Bcc */
3519         compose_write_headers_from_headerlist(compose, fp, "Bcc");
3520 #if 0 /* NEW COMPOSE GUI */
3521         if (compose->use_bcc) {
3522                 str = gtk_entry_get_text(GTK_ENTRY(compose->bcc_entry));
3523                 if (*str != '\0') {
3524                         Xstrdup_a(str, str, return -1);
3525                         g_strstrip(str);
3526                         if (*str != '\0') {
3527                                 compose->to_list = address_list_append
3528                                         (compose->to_list, str);
3529                                 compose_convert_header(buf, sizeof(buf), str,
3530                                                        strlen("Bcc: "));
3531                                 fprintf(fp, "Bcc: %s\n", buf);
3532                         }
3533                 }
3534         }
3535 #endif
3536
3537         /* Subject */
3538         str = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
3539         if (*str != '\0' && !IS_IN_CUSTOM_HEADER("Subject")) {
3540                 Xstrdup_a(str, str, return -1);
3541                 g_strstrip(str);
3542                 if (*str != '\0') {
3543                         compose_convert_header(buf, sizeof(buf), str,
3544                                                strlen("Subject: "));
3545                         fprintf(fp, "Subject: %s\n", buf);
3546                 }
3547         }
3548
3549         /* Message-ID */
3550         if (compose->account->gen_msgid) {
3551                 compose_generate_msgid(compose, buf, sizeof(buf));
3552                 fprintf(fp, "Message-Id: <%s>\n", buf);
3553                 compose->msgid = g_strdup(buf);
3554         }
3555
3556         /* In-Reply-To */
3557         if (compose->inreplyto && compose->to_list)
3558                 fprintf(fp, "In-Reply-To: <%s>\n", compose->inreplyto);
3559
3560         /* References */
3561         if (compose->references)
3562                 fprintf(fp, "References: %s\n", compose->references);
3563
3564         /* Followup-To */
3565         compose_write_headers_from_headerlist(compose, fp, "Followup-To");
3566 #if 0 /* NEW COMPOSE GUI */
3567         if (compose->use_followupto && !IS_IN_CUSTOM_HEADER("Followup-To")) {
3568                 str = gtk_entry_get_text(GTK_ENTRY(compose->followup_entry));
3569                 if (*str != '\0') {
3570                         Xstrdup_a(str, str, return -1);
3571                         g_strstrip(str);
3572                         remove_space(str);
3573                         if (*str != '\0') {
3574                                 compose_convert_header(buf, sizeof(buf), str,
3575                                                        strlen("Followup-To: "));
3576                                 fprintf(fp, "Followup-To: %s\n", buf);
3577                         }
3578                 }
3579         }
3580 #endif
3581         /* Reply-To */
3582         compose_write_headers_from_headerlist(compose, fp, "Reply-To");
3583 #if 0 /* NEW COMPOSE GUI */
3584         if (compose->use_replyto && !IS_IN_CUSTOM_HEADER("Reply-To")) {
3585                 str = gtk_entry_get_text(GTK_ENTRY(compose->reply_entry));
3586                 if (*str != '\0') {
3587                         Xstrdup_a(str, str, return -1);
3588                         g_strstrip(str);
3589                         if (*str != '\0') {
3590                                 compose_convert_header(buf, sizeof(buf), str,
3591                                                        strlen("Reply-To: "));
3592                                 fprintf(fp, "Reply-To: %s\n", buf);
3593                         }
3594                 }
3595         }
3596 #endif
3597         /* Organization */
3598         if (compose->account->organization &&
3599             !IS_IN_CUSTOM_HEADER("Organization")) {
3600                 compose_convert_header(buf, sizeof(buf),
3601                                        compose->account->organization,
3602                                        strlen("Organization: "));
3603                 fprintf(fp, "Organization: %s\n", buf);
3604         }
3605
3606         /* Program version and system info */
3607         /* uname(&utsbuf); */
3608         if (g_slist_length(compose->to_list) && !IS_IN_CUSTOM_HEADER("X-Mailer")) {
3609                 fprintf(fp, "X-Mailer: %s (GTK+ %d.%d.%d; %s)\n",
3610                         prog_version,
3611                         gtk_major_version, gtk_minor_version, gtk_micro_version,
3612                         HOST_ALIAS);
3613                         /* utsbuf.sysname, utsbuf.release, utsbuf.machine); */
3614         }
3615         if (g_slist_length(compose->newsgroup_list) && !IS_IN_CUSTOM_HEADER("X-Newsreader")) {
3616                 fprintf(fp, "X-Newsreader: %s (GTK+ %d.%d.%d; %s)\n",
3617                         prog_version,
3618                         gtk_major_version, gtk_minor_version, gtk_micro_version,
3619                         HOST_ALIAS);
3620                         /* utsbuf.sysname, utsbuf.release, utsbuf.machine); */
3621         }
3622
3623         /* custom headers */
3624         if (compose->account->add_customhdr) {
3625                 GSList *cur;
3626
3627                 for (cur = compose->account->customhdr_list; cur != NULL;
3628                      cur = cur->next) {
3629                         CustomHeader *chdr = (CustomHeader *)cur->data;
3630
3631                         if (strcasecmp(chdr->name, "Date")         != 0 &&
3632                             strcasecmp(chdr->name, "From")         != 0 &&
3633                             strcasecmp(chdr->name, "To")           != 0 &&
3634                          /* strcasecmp(chdr->name, "Sender")       != 0 && */
3635                             strcasecmp(chdr->name, "Message-Id")   != 0 &&
3636                             strcasecmp(chdr->name, "In-Reply-To")  != 0 &&
3637                             strcasecmp(chdr->name, "References")   != 0 &&
3638                             strcasecmp(chdr->name, "Mime-Version") != 0 &&
3639                             strcasecmp(chdr->name, "Content-Type") != 0 &&
3640                             strcasecmp(chdr->name, "Content-Transfer-Encoding")
3641                             != 0) {
3642                                 compose_convert_header
3643                                         (buf, sizeof(buf),
3644                                          chdr->value ? chdr->value : "",
3645                                          strlen(chdr->name) + 2);
3646                                 fprintf(fp, "%s: %s\n", chdr->name, buf);
3647                         }
3648                 }
3649         }
3650
3651         /* MIME */
3652         fprintf(fp, "Mime-Version: 1.0\n");
3653         if (compose_use_attach(compose)) {
3654                 get_rfc822_date(buf, sizeof(buf));
3655                 subst_char(buf, ' ', '_');
3656                 subst_char(buf, ',', '_');
3657                 compose->boundary = g_strdup_printf("Multipart_%s_%08x",
3658                                                     buf, (guint)compose);
3659                 fprintf(fp,
3660                         "Content-Type: multipart/mixed;\n"
3661                         " boundary=\"%s\"\n", compose->boundary);
3662         } else {
3663                 fprintf(fp, "Content-Type: text/plain; charset=%s\n", charset);
3664                 fprintf(fp, "Content-Transfer-Encoding: %s\n",
3665                         procmime_get_encoding_str(encoding));
3666         }
3667
3668         /* Request Return Receipt */
3669         if (!IS_IN_CUSTOM_HEADER("Disposition-Notification-To")) {
3670                 if (compose->return_receipt) {
3671                         if (compose->account->name
3672                             && *compose->account->name) {
3673                                 compose_convert_header(buf, sizeof(buf), compose->account->name, strlen("Disposition-Notification-To: "));
3674                                 fprintf(fp, "Disposition-Notification-To: %s <%s>\n", buf, compose->account->address);
3675                         } else
3676                                 fprintf(fp, "Disposition-Notification-To: %s\n", compose->account->address);
3677                 }
3678         }
3679
3680         /* separator between header and body */
3681         fputs("\n", fp);
3682
3683         return 0;
3684 }
3685
3686 #undef IS_IN_CUSTOM_HEADER
3687
3688 static void compose_convert_header(gchar *dest, gint len, gchar *src,
3689                                    gint header_len)
3690 {
3691         g_return_if_fail(src != NULL);
3692         g_return_if_fail(dest != NULL);
3693
3694         if (len < 1) return;
3695
3696         remove_return(src);
3697
3698         if (is_ascii_str(src)) {
3699                 strncpy2(dest, src, len);
3700                 dest[len - 1] = '\0';
3701                 return;
3702         } else
3703                 conv_encode_header(dest, len, src, header_len);
3704 }
3705
3706 static void compose_generate_msgid(Compose *compose, gchar *buf, gint len)
3707 {
3708         struct tm *lt;
3709         time_t t;
3710         gchar *addr;
3711
3712         t = time(NULL);
3713         lt = localtime(&t);
3714
3715         if (compose->account && compose->account->address &&
3716             *compose->account->address) {
3717                 if (strchr(compose->account->address, '@'))
3718                         addr = g_strdup(compose->account->address);
3719                 else
3720                         addr = g_strconcat(compose->account->address, "@",
3721                                            get_domain_name(), NULL);
3722         } else
3723                 addr = g_strconcat(g_get_user_name(), "@", get_domain_name(),
3724                                    NULL);
3725
3726         g_snprintf(buf, len, "%04d%02d%02d%02d%02d%02d.%08x.%s",
3727                    lt->tm_year + 1900, lt->tm_mon + 1,
3728                    lt->tm_mday, lt->tm_hour,
3729                    lt->tm_min, lt->tm_sec,
3730                    (guint)random(), addr);
3731
3732         debug_print(_("generated Message-ID: %s\n"), buf);
3733
3734         g_free(addr);
3735 }
3736
3737
3738 static void compose_add_entry_field(GtkWidget *table, GtkWidget **hbox,
3739                                     GtkWidget **entry, gint *count,
3740                                     const gchar *label_str,
3741                                     gboolean is_addr_entry)
3742 {
3743         GtkWidget *label;
3744
3745         if (GTK_TABLE(table)->nrows < (*count) + 1)
3746                 gtk_table_resize(GTK_TABLE(table), (*count) + 1, 2);
3747
3748         *hbox = gtk_hbox_new(FALSE, 0);
3749         label = gtk_label_new
3750                 (prefs_common.trans_hdr ? gettext(label_str) : label_str);
3751         gtk_box_pack_end(GTK_BOX(*hbox), label, FALSE, FALSE, 0);
3752         gtk_table_attach(GTK_TABLE(table), *hbox, 0, 1, *count, (*count) + 1,
3753                          GTK_FILL, 0, 2, 0);
3754         *entry = gtk_entry_new_with_max_length(MAX_ENTRY_LENGTH);
3755         gtk_table_attach
3756                 (GTK_TABLE(table), *entry, 1, 2, *count, (*count) + 1, GTK_FILL | GTK_EXPAND, GTK_SHRINK, 0, 0);
3757 #if 0 /* NEW COMPOSE GUI */
3758         if (GTK_TABLE(table)->nrows > (*count) + 1)
3759                 gtk_table_set_row_spacing(GTK_TABLE(table), *count, 4);
3760 #endif
3761
3762         if (is_addr_entry)
3763                 address_completion_register_entry(GTK_ENTRY(*entry));
3764
3765         (*count)++;
3766 }
3767
3768 static void compose_create_header_entry(Compose *compose) 
3769 {
3770         gchar *headers[] = {"To:", "Cc:", "Bcc:", "Newsgroups:", "Reply-To:", "Followup-To:", NULL};
3771
3772         GtkWidget *combo;
3773         GtkWidget *entry;
3774         GList *combo_list = NULL;
3775         gchar **string, *header;
3776         ComposeHeaderEntry *headerentry;
3777
3778         headerentry = g_new0(ComposeHeaderEntry, 1);
3779
3780         /* Combo box */
3781         combo = gtk_combo_new();
3782         string = headers; 
3783         while(*string != NULL) {
3784             combo_list = g_list_append(combo_list, (prefs_common.trans_hdr ? gettext(*string) : *string));
3785             string++;
3786         }
3787         gtk_combo_set_popdown_strings(GTK_COMBO(combo), combo_list);
3788         g_list_free(combo_list);
3789         gtk_editable_set_editable(GTK_EDITABLE(GTK_COMBO(combo)->entry), FALSE);
3790         gtk_widget_show(combo);
3791         gtk_table_attach(GTK_TABLE(compose->header_table), combo, 0, 1, compose->header_nextrow, compose->header_nextrow+1, GTK_SHRINK, GTK_FILL, 0, 0);
3792         if(compose->header_last) {      
3793                 header = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry));
3794         } else {
3795                 switch(compose->account->protocol) {
3796                         case A_NNTP:
3797                                 header = prefs_common.trans_hdr ? _("Newsgroups:") : "Newsgroups:";
3798                                 break;
3799                         default:
3800                                 header = prefs_common.trans_hdr ? _("To:") : "To:";
3801                                 break;
3802                 }                                                                   
3803         }
3804         gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(combo)->entry), header);
3805
3806         /* Entry field */
3807         entry = gtk_entry_new(); 
3808         gtk_widget_show(entry);
3809         gtk_table_attach(GTK_TABLE(compose->header_table), entry, 1, 2, compose->header_nextrow, compose->header_nextrow+1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
3810
3811         gtk_signal_connect(GTK_OBJECT(entry), "key-press-event", GTK_SIGNAL_FUNC(compose_headerentry_key_press_event_cb), headerentry);
3812         gtk_signal_connect(GTK_OBJECT(entry), "changed", GTK_SIGNAL_FUNC(compose_headerentry_changed_cb), headerentry);
3813         gtk_signal_connect(GTK_OBJECT(entry), "activate", GTK_SIGNAL_FUNC(compose_ctl_enter_send_shortcut_cb), compose);
3814
3815         address_completion_register_entry(GTK_ENTRY(entry));
3816
3817         headerentry->compose = compose;
3818         headerentry->combo = combo;
3819         headerentry->entry = entry;
3820         headerentry->headernum = compose->header_nextrow;
3821
3822         compose->header_nextrow++;
3823         compose->header_last = headerentry;
3824 }
3825
3826 static void compose_add_header_entry(Compose *compose, gchar *header, gchar *text) 
3827 {
3828         ComposeHeaderEntry *last_header;
3829         
3830         last_header = compose->header_last;
3831         
3832         gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(last_header->combo)->entry), header);
3833         gtk_entry_set_text(GTK_ENTRY(last_header->entry), text);
3834 }
3835
3836 static GtkWidget *compose_create_header(Compose *compose) 
3837 {
3838         GtkWidget *label;
3839         GtkWidget *hbox;
3840         GtkWidget *from_optmenu_hbox;
3841 #if 0 /* NEW COMPOSE GUI */
3842         GtkWidget *to_entry;
3843         GtkWidget *to_hbox;
3844         GtkWidget *newsgroups_entry;
3845         GtkWidget *newsgroups_hbox;
3846 #endif
3847         GtkWidget *header_scrolledwin;
3848         GtkWidget *header_table;
3849 #if 0 /* NEW COMPOSE GUI */
3850         GtkWidget *cc_entry;
3851         GtkWidget *cc_hbox;
3852         GtkWidget *bcc_entry;
3853         GtkWidget *bcc_hbox;
3854         GtkWidget *reply_entry;
3855         GtkWidget *reply_hbox;
3856         GtkWidget *followup_entry;
3857         GtkWidget *followup_hbox;
3858 #endif
3859
3860         gint count = 0;
3861
3862         /* header labels and entries */
3863         header_scrolledwin = gtk_scrolled_window_new(NULL, NULL);
3864         gtk_widget_show(header_scrolledwin);
3865         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(header_scrolledwin), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
3866
3867         header_table = gtk_table_new(2, 2, FALSE);
3868         gtk_widget_show(header_table);
3869         gtk_container_set_border_width(GTK_CONTAINER(header_table), 2);
3870         gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(header_scrolledwin), header_table);
3871         gtk_viewport_set_shadow_type(GTK_VIEWPORT(GTK_BIN(header_scrolledwin)->child), GTK_SHADOW_ETCHED_IN);
3872         count = 0;
3873
3874         /* option menu for selecting accounts */
3875         hbox = gtk_hbox_new(FALSE, 0);
3876         label = gtk_label_new(prefs_common.trans_hdr ? _("From:") : "From:");
3877         gtk_box_pack_end(GTK_BOX(hbox), label, FALSE, FALSE, 0);
3878         gtk_table_attach(GTK_TABLE(header_table), hbox, 0, 1, count, count + 1,
3879                          GTK_FILL, 0, 2, 0);
3880         from_optmenu_hbox = compose_account_option_menu_create(compose);
3881         gtk_table_attach(GTK_TABLE(header_table), from_optmenu_hbox,
3882                                   1, 2, count, count + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
3883 #if 0 /* NEW COMPOSE GUI */
3884         gtk_table_set_row_spacing(GTK_TABLE(table), 0, 4);
3885 #endif
3886         count++;
3887
3888         compose->header_table = header_table;
3889         compose->header_list = NULL;
3890         compose->header_nextrow = count;
3891
3892         compose_create_header_entry(compose);
3893
3894 #if 0 /* NEW COMPOSE GUI */
3895         compose_add_entry_field(table, &to_hbox, &to_entry, &count,
3896                                 "To:", TRUE); 
3897         gtk_table_set_row_spacing(GTK_TABLE(table), 0, 4);
3898         compose_add_entry_field(table, &newsgroups_hbox, &newsgroups_entry,
3899                                 &count, "Newsgroups:", FALSE);
3900         gtk_table_set_row_spacing(GTK_TABLE(table), 1, 4);
3901
3902         gtk_table_set_row_spacing(GTK_TABLE(table), 2, 4);
3903
3904         compose_add_entry_field(table, &cc_hbox, &cc_entry, &count,
3905                                 "Cc:", TRUE);
3906         gtk_table_set_row_spacing(GTK_TABLE(table), 3, 4);
3907         compose_add_entry_field(table, &bcc_hbox, &bcc_entry, &count,
3908                                 "Bcc:", TRUE);
3909         gtk_table_set_row_spacing(GTK_TABLE(table), 4, 4);
3910         compose_add_entry_field(table, &reply_hbox, &reply_entry, &count,
3911                                 "Reply-To:", TRUE);
3912         gtk_table_set_row_spacing(GTK_TABLE(table), 5, 4);
3913         compose_add_entry_field(table, &followup_hbox, &followup_entry, &count,
3914                                 "Followup-To:", FALSE);
3915         gtk_table_set_row_spacing(GTK_TABLE(table), 6, 4);
3916
3917         gtk_table_set_col_spacings(GTK_TABLE(table), 4);
3918
3919         gtk_signal_connect(GTK_OBJECT(to_entry), "activate",
3920                            GTK_SIGNAL_FUNC(to_activated), compose);
3921         gtk_signal_connect(GTK_OBJECT(newsgroups_entry), "activate",
3922                            GTK_SIGNAL_FUNC(newsgroups_activated), compose);
3923         gtk_signal_connect(GTK_OBJECT(subject_entry), "activate",
3924                            GTK_SIGNAL_FUNC(subject_activated), compose);
3925         gtk_signal_connect(GTK_OBJECT(cc_entry), "activate",
3926                            GTK_SIGNAL_FUNC(cc_activated), compose);
3927         gtk_signal_connect(GTK_OBJECT(bcc_entry), "activate",
3928                            GTK_SIGNAL_FUNC(bcc_activated), compose);
3929         gtk_signal_connect(GTK_OBJECT(reply_entry), "activate",
3930                            GTK_SIGNAL_FUNC(replyto_activated), compose);
3931         gtk_signal_connect(GTK_OBJECT(followup_entry), "activate",
3932                            GTK_SIGNAL_FUNC(followupto_activated), compose);
3933
3934         gtk_signal_connect(GTK_OBJECT(subject_entry), "grab_focus",
3935                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
3936         gtk_signal_connect(GTK_OBJECT(to_entry), "grab_focus",
3937                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
3938         gtk_signal_connect(GTK_OBJECT(newsgroups_entry), "grab_focus",
3939                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
3940         gtk_signal_connect(GTK_OBJECT(cc_entry), "grab_focus",
3941                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
3942         gtk_signal_connect(GTK_OBJECT(bcc_entry), "grab_focus",
3943                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
3944         gtk_signal_connect(GTK_OBJECT(reply_entry), "grab_focus",
3945                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
3946         gtk_signal_connect(GTK_OBJECT(followup_entry), "grab_focus",
3947                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
3948 #endif
3949
3950         compose->table            = NULL;
3951 #if 0 /* NEW COMPOSE GUI */
3952         compose->table            = table;
3953         compose->to_hbox          = to_hbox;
3954         compose->to_entry         = to_entry;
3955         compose->newsgroups_hbox  = newsgroups_hbox;
3956         compose->newsgroups_entry = newsgroups_entry;
3957 #endif
3958 #if 0 /* NEW COMPOSE GUI */
3959         compose->cc_hbox          = cc_hbox;
3960         compose->cc_entry         = cc_entry;
3961         compose->bcc_hbox         = bcc_hbox;
3962         compose->bcc_entry        = bcc_entry;
3963         compose->reply_hbox       = reply_hbox;
3964         compose->reply_entry      = reply_entry;
3965         compose->followup_hbox    = followup_hbox;
3966         compose->followup_entry   = followup_entry;
3967 #endif
3968
3969         return header_scrolledwin ;
3970 }
3971
3972 GtkWidget *compose_create_attach(Compose *compose)
3973 {
3974         gchar *titles[] = {_("MIME type"), _("Size"), _("Name")};
3975         gint i;
3976
3977         GtkWidget *attach_scrwin;
3978         GtkWidget *attach_clist;
3979
3980         /* attachment list */
3981         attach_scrwin = gtk_scrolled_window_new(NULL, NULL);
3982         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(attach_scrwin),
3983                                        GTK_POLICY_AUTOMATIC,
3984                                        GTK_POLICY_ALWAYS);
3985         gtk_widget_set_usize(attach_scrwin, -1, 80);
3986
3987         attach_clist = gtk_clist_new_with_titles(N_ATTACH_COLS, titles);
3988         gtk_clist_set_column_justification(GTK_CLIST(attach_clist), COL_SIZE,
3989                                            GTK_JUSTIFY_RIGHT);
3990         gtk_clist_set_column_width(GTK_CLIST(attach_clist), COL_MIMETYPE, 240);
3991         gtk_clist_set_column_width(GTK_CLIST(attach_clist), COL_SIZE, 64);
3992         gtk_clist_set_selection_mode(GTK_CLIST(attach_clist),
3993                                      GTK_SELECTION_EXTENDED);
3994         for (i = 0; i < N_ATTACH_COLS; i++)
3995                 GTK_WIDGET_UNSET_FLAGS
3996                         (GTK_CLIST(attach_clist)->column[i].button,
3997                          GTK_CAN_FOCUS);
3998         gtk_container_add(GTK_CONTAINER(attach_scrwin), attach_clist);
3999
4000         gtk_signal_connect(GTK_OBJECT(attach_clist), "select_row",
4001                            GTK_SIGNAL_FUNC(attach_selected), compose);
4002         gtk_signal_connect(GTK_OBJECT(attach_clist), "button_press_event",
4003                            GTK_SIGNAL_FUNC(attach_button_pressed), compose);
4004         gtk_signal_connect(GTK_OBJECT(attach_clist), "key_press_event",
4005                            GTK_SIGNAL_FUNC(attach_key_pressed), compose);
4006
4007         /* drag and drop */
4008         gtk_drag_dest_set(attach_clist,
4009                           GTK_DEST_DEFAULT_ALL, compose_mime_types, 1,
4010                           GDK_ACTION_COPY);
4011         gtk_signal_connect(GTK_OBJECT(attach_clist), "drag_data_received",
4012                            GTK_SIGNAL_FUNC(compose_attach_drag_received_cb),
4013                            compose);
4014
4015         compose->attach_scrwin = attach_scrwin;
4016         compose->attach_clist  = attach_clist;
4017
4018         return attach_scrwin;
4019 }
4020
4021 static void compose_savemsg_checkbtn_cb(GtkWidget *widget, Compose *compose);
4022 static void compose_savemsg_select_cb(GtkWidget *widget, Compose *compose);
4023
4024 static GtkWidget *compose_create_others(Compose *compose)
4025 {
4026         GtkWidget *table;
4027         GtkWidget *savemsg_checkbtn;
4028         GtkWidget *savemsg_entry;
4029         GtkWidget *savemsg_select;
4030         
4031         guint rowcount = 0;
4032         gchar *folderidentifier;
4033
4034         /* Table for settings */
4035         table = gtk_table_new(3, 1, FALSE);
4036         gtk_widget_show(table);
4037         gtk_table_set_row_spacings(GTK_TABLE(table), VSPACING_NARROW);
4038         rowcount = 0;
4039
4040         /* Save Message to folder */
4041         savemsg_checkbtn = gtk_check_button_new_with_label(_("Save Message to "));
4042         gtk_widget_show(savemsg_checkbtn);
4043         gtk_table_attach(GTK_TABLE(table), savemsg_checkbtn, 0, 1, rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
4044         if(folder_get_default_outbox()) {
4045                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(savemsg_checkbtn), prefs_common.savemsg);
4046         }
4047         gtk_signal_connect(GTK_OBJECT(savemsg_checkbtn), "toggled",
4048                             GTK_SIGNAL_FUNC(compose_savemsg_checkbtn_cb), compose);
4049
4050         savemsg_entry = gtk_entry_new();
4051         gtk_widget_show(savemsg_entry);
4052         gtk_table_attach_defaults(GTK_TABLE(table), savemsg_entry, 1, 2, rowcount, rowcount + 1);
4053         gtk_editable_set_editable(GTK_EDITABLE(savemsg_entry), prefs_common.savemsg);
4054         if(folder_get_default_outbox()) {
4055                 folderidentifier = folder_item_get_identifier(folder_get_default_outbox());
4056                 gtk_entry_set_text(GTK_ENTRY(savemsg_entry), folderidentifier);
4057                 g_free(folderidentifier);
4058         }
4059
4060         savemsg_select = gtk_button_new_with_label (_("Select ..."));
4061         gtk_widget_show (savemsg_select);
4062         gtk_table_attach(GTK_TABLE(table), savemsg_select, 2, 3, rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
4063         gtk_signal_connect (GTK_OBJECT (savemsg_select), "clicked",
4064                             GTK_SIGNAL_FUNC (compose_savemsg_select_cb),
4065                             compose);
4066
4067         rowcount++;
4068
4069         compose->savemsg_checkbtn = savemsg_checkbtn;
4070         compose->savemsg_entry = savemsg_entry;
4071
4072         return table;   
4073 }
4074
4075 static void compose_savemsg_checkbtn_cb(GtkWidget *widget, Compose *compose) 
4076 {
4077         gtk_editable_set_editable(GTK_EDITABLE(compose->savemsg_entry),
4078                 gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn)));
4079 }
4080
4081 static void compose_savemsg_select_cb(GtkWidget *widget, Compose *compose)
4082 {
4083         FolderItem *dest;
4084         gchar * path;
4085
4086         dest = foldersel_folder_sel(NULL, NULL);
4087         if (!dest) return;
4088
4089         path = folder_item_get_identifier(dest);
4090
4091         gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), path);
4092         g_free(path);
4093 }
4094
4095 static Compose *compose_create(PrefsAccount *account, ComposeMode mode)
4096 {
4097         Compose   *compose;
4098         GtkWidget *window;
4099         GtkWidget *vbox;
4100         GtkWidget *menubar;
4101         GtkWidget *handlebox;
4102
4103         GtkWidget *notebook;
4104
4105         GtkWidget *vbox2;
4106
4107         GtkWidget *label;
4108         GtkWidget *subject_hbox;
4109         GtkWidget *subject_frame;
4110         GtkWidget *subject_entry;
4111         GtkWidget *subject;
4112         GtkWidget *paned;
4113
4114         GtkWidget *edit_vbox;
4115         GtkWidget *ruler_hbox;
4116         GtkWidget *ruler;
4117         GtkWidget *scrolledwin;
4118         GtkWidget *text;
4119
4120         GtkWidget *table;
4121
4122         UndoMain *undostruct;
4123
4124         guint n_menu_entries;
4125         GtkStyle  *style, *new_style;
4126         GdkColormap *cmap;
4127         GdkColor color[1];
4128         gboolean success[1];
4129         GdkFont   *font;
4130         GtkWidget *popupmenu;
4131         GtkWidget *menuitem;
4132         GtkItemFactory *popupfactory;
4133         GtkItemFactory *ifactory;
4134         GtkWidget *tmpl_menu;
4135         gint n_entries;
4136
4137 #if USE_PSPELL
4138         GtkPspell * gtkpspell = NULL;
4139 #endif
4140
4141         g_return_val_if_fail(account != NULL, NULL);
4142
4143         debug_print(_("Creating compose window...\n"));
4144         compose = g_new0(Compose, 1);
4145
4146         compose->account = account;
4147         compose->orig_account = account;
4148
4149         window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
4150         gtk_window_set_policy(GTK_WINDOW(window), TRUE, TRUE, FALSE);
4151         gtk_widget_set_usize(window, -1, prefs_common.compose_height);
4152         gtk_window_set_wmclass(GTK_WINDOW(window), "compose window", "Sylpheed");
4153         gtk_signal_connect(GTK_OBJECT(window), "delete_event",
4154                            GTK_SIGNAL_FUNC(compose_delete_cb), compose);
4155         gtk_signal_connect(GTK_OBJECT(window), "destroy",
4156                            GTK_SIGNAL_FUNC(compose_destroy_cb), compose);
4157         gtk_signal_connect(GTK_OBJECT(window), "focus_in_event",
4158                            GTK_SIGNAL_FUNC(manage_window_focus_in), NULL);
4159         gtk_signal_connect(GTK_OBJECT(window), "focus_out_event",
4160                            GTK_SIGNAL_FUNC(manage_window_focus_out), NULL);
4161         gtk_widget_realize(window);
4162
4163         gtkut_widget_set_composer_icon(window);
4164
4165         vbox = gtk_vbox_new(FALSE, 0);
4166         gtk_container_add(GTK_CONTAINER(window), vbox);
4167
4168         n_menu_entries = sizeof(compose_entries) / sizeof(compose_entries[0]);
4169         menubar = menubar_create(window, compose_entries,
4170                                  n_menu_entries, "<Compose>", compose);
4171         gtk_box_pack_start(GTK_BOX(vbox), menubar, FALSE, TRUE, 0);
4172
4173         handlebox = gtk_handle_box_new();
4174         gtk_box_pack_start(GTK_BOX(vbox), handlebox, FALSE, FALSE, 0);
4175
4176         compose_toolbar_create(compose, handlebox);
4177
4178         vbox2 = gtk_vbox_new(FALSE, 2);
4179         gtk_box_pack_start(GTK_BOX(vbox), vbox2, TRUE, TRUE, 0);
4180         gtk_container_set_border_width(GTK_CONTAINER(vbox2), BORDER_WIDTH);
4181         
4182         /* Notebook */
4183         notebook = gtk_notebook_new();
4184         gtk_widget_set_usize(notebook, -1, 130);
4185         gtk_widget_show(notebook);
4186
4187         /* header labels and entries */
4188         gtk_notebook_append_page(GTK_NOTEBOOK(notebook), compose_create_header(compose), gtk_label_new(_("Header")));
4189         /* attachment list */
4190         gtk_notebook_append_page(GTK_NOTEBOOK(notebook), compose_create_attach(compose), gtk_label_new(_("Attachments")));
4191         /* Others Tab */
4192         gtk_notebook_append_page(GTK_NOTEBOOK(notebook), compose_create_others(compose), gtk_label_new(_("Others")));
4193
4194         /* Subject */
4195         subject_hbox = gtk_hbox_new(FALSE, 0);
4196         gtk_widget_show(subject_hbox);
4197
4198         subject_frame = gtk_frame_new(NULL);
4199         gtk_frame_set_shadow_type(GTK_FRAME(subject_frame), GTK_SHADOW_OUT);
4200         gtk_box_pack_start(GTK_BOX(subject_hbox), subject_frame, TRUE, TRUE, BORDER_WIDTH+1);
4201         gtk_widget_show(subject_frame);
4202
4203         subject = gtk_hbox_new(FALSE, 0);
4204         gtk_container_set_border_width(GTK_CONTAINER(subject), BORDER_WIDTH);
4205         gtk_widget_show(subject);
4206
4207         label = gtk_label_new(_("Subject:"));
4208         gtk_box_pack_start(GTK_BOX(subject), label, FALSE, FALSE, 4);
4209         gtk_widget_show(label);
4210
4211         subject_entry = gtk_entry_new();
4212         gtk_box_pack_start(GTK_BOX(subject), subject_entry, TRUE, TRUE, 2);
4213         gtk_signal_connect(GTK_OBJECT(subject_entry), "activate", GTK_SIGNAL_FUNC(compose_ctl_enter_send_shortcut_cb), compose);
4214         gtk_widget_show(subject_entry);
4215         compose->subject_entry = subject_entry;
4216         gtk_container_add(GTK_CONTAINER(subject_frame), subject);
4217         
4218         edit_vbox = gtk_vbox_new(FALSE, 0);
4219 #if 0 /* NEW COMPOSE GUI */
4220         gtk_box_pack_start(GTK_BOX(vbox2), edit_vbox, TRUE, TRUE, 0);
4221 #endif
4222
4223         gtk_box_pack_start(GTK_BOX(edit_vbox), subject_hbox, FALSE, FALSE, 0);
4224
4225         /* ruler */
4226         ruler_hbox = gtk_hbox_new(FALSE, 0);
4227         gtk_box_pack_start(GTK_BOX(edit_vbox), ruler_hbox, FALSE, FALSE, 0);
4228
4229         ruler = gtk_shruler_new();
4230         gtk_ruler_set_range(GTK_RULER(ruler), 0.0, 100.0, 1.0, 100.0);
4231         gtk_box_pack_start(GTK_BOX(ruler_hbox), ruler, TRUE, TRUE,
4232                            BORDER_WIDTH + 1);
4233         gtk_widget_set_usize(ruler_hbox, 1, -1);
4234
4235         /* text widget */
4236         scrolledwin = gtk_scrolled_window_new(NULL, NULL);
4237         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin),
4238                                        GTK_POLICY_NEVER, GTK_POLICY_ALWAYS);
4239         gtk_box_pack_start(GTK_BOX(edit_vbox), scrolledwin, TRUE, TRUE, 0);
4240         gtk_widget_set_usize(scrolledwin, prefs_common.compose_width, -1);
4241
4242         text = gtk_stext_new(gtk_scrolled_window_get_hadjustment
4243                             (GTK_SCROLLED_WINDOW(scrolledwin)),
4244                             gtk_scrolled_window_get_vadjustment
4245                             (GTK_SCROLLED_WINDOW(scrolledwin)));
4246         GTK_STEXT(text)->default_tab_width = 8;
4247         gtk_stext_set_editable(GTK_STEXT(text), TRUE);
4248
4249         if (prefs_common.block_cursor) {
4250                 GTK_STEXT(text)->cursor_type = STEXT_CURSOR_BLOCK;
4251         }
4252         
4253         if (prefs_common.smart_wrapping) {      
4254                 gtk_stext_set_word_wrap(GTK_STEXT(text), TRUE);
4255                 gtk_stext_set_wrap_rmargin(GTK_STEXT(text), prefs_common.linewrap_len);
4256         }               
4257
4258         gtk_container_add(GTK_CONTAINER(scrolledwin), text);
4259
4260         gtk_signal_connect(GTK_OBJECT(text), "changed",
4261                            GTK_SIGNAL_FUNC(compose_changed_cb), compose);
4262         gtk_signal_connect(GTK_OBJECT(text), "grab_focus",
4263                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4264         gtk_signal_connect(GTK_OBJECT(text), "activate",
4265                            GTK_SIGNAL_FUNC(compose_ctl_enter_send_shortcut_cb), compose);
4266         gtk_signal_connect_after(GTK_OBJECT(text), "button_press_event",
4267                                  GTK_SIGNAL_FUNC(compose_button_press_cb),
4268                                  edit_vbox);
4269 #if 0
4270         gtk_signal_connect_after(GTK_OBJECT(text), "key_press_event",
4271                                  GTK_SIGNAL_FUNC(compose_key_press_cb),
4272                                  compose);
4273 #endif
4274         gtk_signal_connect_after(GTK_OBJECT(text), "size_allocate",
4275                                  GTK_SIGNAL_FUNC(compose_edit_size_alloc),
4276                                  ruler);
4277
4278         /* drag and drop */
4279         gtk_drag_dest_set(text, GTK_DEST_DEFAULT_ALL, compose_mime_types, 1,
4280                           GDK_ACTION_COPY);
4281         gtk_signal_connect(GTK_OBJECT(text), "drag_data_received",
4282                            GTK_SIGNAL_FUNC(compose_insert_drag_received_cb),
4283                            compose);
4284 #if USE_PSPELL
4285         if (prefs_common.enable_pspell) {
4286                 gtkpspell = gtkpspell_new_with_config(gtkpspellconfig,
4287                                                       prefs_common.pspell_path,
4288                                                       prefs_common.dictionary,
4289                                                       prefs_common.pspell_sugmode,
4290                                                       conv_get_current_charset_str());
4291                 if (gtkpspell == NULL)
4292                         prefs_common.enable_pspell = FALSE;
4293                 else
4294                         gtkpspell_attach(gtkpspell, GTK_STEXT(text));
4295         }
4296 #endif
4297         gtk_widget_show_all(vbox);
4298
4299         /* pane between attach clist and text */
4300         paned = gtk_vpaned_new();
4301         gtk_paned_set_gutter_size(GTK_PANED(paned), 12);
4302         gtk_paned_set_handle_size(GTK_PANED(paned), 12);
4303         gtk_container_add(GTK_CONTAINER(vbox2), paned);
4304         gtk_paned_add1(GTK_PANED(paned), notebook);
4305         gtk_paned_add2(GTK_PANED(paned), edit_vbox);
4306         gtk_widget_show_all(paned);
4307
4308         style = gtk_widget_get_style(text);
4309
4310         /* workaround for the slow down of GtkText when using Pixmap theme */
4311         if (style->engine) {
4312                 GtkThemeEngine *engine;
4313
4314                 engine = style->engine;
4315                 style->engine = NULL;
4316                 new_style = gtk_style_copy(style);
4317                 style->engine = engine;
4318         } else
4319                 new_style = gtk_style_copy(style);
4320
4321         if (prefs_common.textfont) {
4322                 CharSet charset;
4323
4324                 charset = conv_get_current_charset();
4325                 if (MB_CUR_MAX == 1) {
4326                         gchar *fontstr, *p;
4327
4328                         Xstrdup_a(fontstr, prefs_common.textfont, );
4329                         if (fontstr && (p = strchr(fontstr, ',')) != NULL)
4330                                 *p = '\0';
4331                         font = gdk_font_load(fontstr);
4332                 } else
4333                         font = gdk_fontset_load(prefs_common.textfont);
4334                 if (font) {
4335                         gdk_font_unref(new_style->font);
4336                         new_style->font = font;
4337                 }
4338         }
4339
4340         gtk_widget_set_style(text, new_style);
4341
4342         color[0] = quote_color;
4343         cmap = gdk_window_get_colormap(window->window);
4344         gdk_colormap_alloc_colors(cmap, color, 1, FALSE, TRUE, success);
4345         if (success[0] == FALSE) {
4346                 g_warning("Compose: color allocation failed.\n");
4347                 style = gtk_widget_get_style(text);
4348                 quote_color = style->black;
4349         }
4350
4351         n_entries = sizeof(compose_popup_entries) /
4352                 sizeof(compose_popup_entries[0]);
4353         popupmenu = menu_create_items(compose_popup_entries, n_entries,
4354                                       "<Compose>", &popupfactory,
4355                                       compose);
4356
4357         ifactory = gtk_item_factory_from_widget(menubar);
4358         menu_set_sensitive(ifactory, "/Edit/Undo", FALSE);
4359         menu_set_sensitive(ifactory, "/Edit/Redo", FALSE);
4360
4361         tmpl_menu = gtk_item_factory_get_item(ifactory, "/Tool/Template");
4362 #if 0 /* NEW COMPOSE GUI */
4363         if (account->protocol == A_NNTP) {
4364                 gtk_widget_hide(to_hbox);
4365                 gtk_widget_hide(to_entry);
4366                 gtk_widget_hide(cc_hbox);
4367                 gtk_widget_hide(cc_entry);
4368                 gtk_table_set_row_spacing(GTK_TABLE(table), 1, 0);
4369                 gtk_table_set_row_spacing(GTK_TABLE(table), 3, 0);
4370         } else {
4371                 gtk_widget_hide(newsgroups_hbox);
4372                 gtk_widget_hide(newsgroups_entry);
4373                 gtk_table_set_row_spacing(GTK_TABLE(table), 2, 0);
4374
4375                 menu_set_sensitive(ifactory, "/Message/Followup to", FALSE);
4376         }
4377 #endif
4378
4379         switch (prefs_common.toolbar_style) {
4380         case TOOLBAR_NONE:
4381                 gtk_widget_hide(handlebox);
4382                 break;
4383         case TOOLBAR_ICON:
4384                 gtk_toolbar_set_style(GTK_TOOLBAR(compose->toolbar),
4385                                       GTK_TOOLBAR_ICONS);
4386                 break;
4387         case TOOLBAR_TEXT:
4388                 gtk_toolbar_set_style(GTK_TOOLBAR(compose->toolbar),
4389                                       GTK_TOOLBAR_TEXT);
4390                 break;
4391         case TOOLBAR_BOTH:
4392                 gtk_toolbar_set_style(GTK_TOOLBAR(compose->toolbar),
4393                                       GTK_TOOLBAR_BOTH);
4394                 break;
4395         }
4396
4397         undostruct = undo_init(text);
4398         undo_set_change_state_func(undostruct, &compose_undo_state_changed,
4399                                    menubar);
4400
4401         gtk_widget_show(window);
4402
4403         address_completion_start(window);
4404
4405         compose->window        = window;
4406         compose->vbox          = vbox;
4407         compose->menubar       = menubar;
4408         compose->handlebox     = handlebox;
4409
4410         compose->vbox2         = vbox2;
4411
4412         compose->paned = paned;
4413
4414         compose->edit_vbox     = edit_vbox;
4415         compose->ruler_hbox    = ruler_hbox;
4416         compose->ruler         = ruler;
4417         compose->scrolledwin   = scrolledwin;
4418         compose->text          = text;
4419
4420         compose->focused_editable = NULL;
4421
4422         compose->popupmenu    = popupmenu;
4423         compose->popupfactory = popupfactory;
4424
4425         compose->tmpl_menu = tmpl_menu;
4426
4427         compose->mode = mode;
4428
4429         compose->targetinfo = NULL;
4430         compose->replyinfo  = NULL;
4431
4432         compose->replyto     = NULL;
4433         compose->mailinglist = NULL;
4434         compose->cc          = NULL;
4435         compose->bcc         = NULL;
4436         compose->followup_to = NULL;
4437         compose->inreplyto   = NULL;
4438         compose->references  = NULL;
4439         compose->msgid       = NULL;
4440         compose->boundary    = NULL;
4441
4442 #if USE_GPGME
4443         compose->use_signing    = FALSE;
4444         compose->use_encryption = FALSE;
4445 #endif /* USE_GPGME */
4446
4447         compose->modified = FALSE;
4448
4449         compose->return_receipt = FALSE;
4450
4451         compose->to_list        = NULL;
4452         compose->newsgroup_list = NULL;
4453
4454         compose->exteditor_file    = NULL;
4455         compose->exteditor_pid     = -1;
4456         compose->exteditor_readdes = -1;
4457         compose->exteditor_tag     = -1;
4458
4459         compose->bounce_filename = NULL;
4460         compose->undostruct = undostruct;
4461
4462         compose_set_title(compose);
4463
4464 #if 0 /* NEW COMPOSE GUI */
4465         compose->use_bcc        = FALSE;
4466         compose->use_replyto    = FALSE;
4467         compose->use_followupto = FALSE;
4468 #endif
4469
4470 #if USE_PSPELL
4471         compose->gtkpspell      = gtkpspell;
4472 #endif
4473
4474 #if 0 /* NEW COMPOSE GUI */
4475         if (account->protocol != A_NNTP) {
4476                 menuitem = gtk_item_factory_get_item(ifactory, "/Message/To");
4477                 gtk_check_menu_item_set_active
4478                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
4479                 gtk_widget_set_sensitive(menuitem, FALSE);
4480                 menuitem = gtk_item_factory_get_item(ifactory, "/Message/Cc");
4481                 gtk_check_menu_item_set_active
4482                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
4483                 gtk_widget_set_sensitive(menuitem, FALSE);
4484         }
4485 #endif
4486         if (account->set_autocc && account->auto_cc && mode != COMPOSE_REEDIT) {
4487                 compose_entry_append(compose, account->auto_cc, COMPOSE_CC);
4488 #if 0 /* NEW COMPOSE GUI */
4489                 compose->use_cc = TRUE;
4490                 gtk_entry_set_text(GTK_ENTRY(cc_entry), account->auto_cc);
4491                 menuitem = gtk_item_factory_get_item(ifactory, "/Message/Cc");
4492                 gtk_check_menu_item_set_active
4493                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
4494 #endif
4495         }
4496         if (account->set_autobcc) {
4497                 compose_entry_append(compose, account->auto_bcc, COMPOSE_BCC);
4498 #if 0 /* NEW COMPOSE GUI */
4499                 compose->use_bcc = TRUE;
4500                 menuitem = gtk_item_factory_get_item(ifactory, "/Message/Bcc");
4501                 gtk_check_menu_item_set_active
4502                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
4503                 if (account->auto_bcc && mode != COMPOSE_REEDIT)
4504                         gtk_entry_set_text(GTK_ENTRY(bcc_entry),
4505                                            account->auto_bcc);
4506 #endif
4507         }
4508         if (account->set_autoreplyto && account->auto_replyto && mode != COMPOSE_REEDIT) {
4509                 compose_entry_append(compose, account->auto_replyto, COMPOSE_REPLYTO);
4510 #if 0 /* NEW COMPOSE GUI */
4511                 compose->use_replyto = TRUE;
4512                 menuitem = gtk_item_factory_get_item(ifactory,
4513                                                      "/Message/Reply to");
4514                 gtk_check_menu_item_set_active
4515                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
4516                 gtk_entry_set_text(GTK_ENTRY(reply_entry),
4517                                    account->auto_replyto);
4518 #endif
4519         }
4520
4521         if (account->protocol != A_NNTP) {
4522                 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry), prefs_common.trans_hdr ? _("To:") : "To:");
4523         } else {
4524                 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry), prefs_common.trans_hdr ? _("Newsgroups:") : "Newsgroups:");
4525         }
4526
4527         menuitem = gtk_item_factory_get_item(ifactory, "/Tool/Show ruler");
4528         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
4529                                        prefs_common.show_ruler);
4530
4531 #if USE_GPGME
4532         menuitem = gtk_item_factory_get_item(ifactory, "/Message/Sign");
4533         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
4534                                        prefs_common.default_sign);
4535         menuitem = gtk_item_factory_get_item(ifactory, "/Message/Encrypt");
4536         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
4537                                        prefs_common.default_encrypt);
4538 #endif /* USE_GPGME */
4539
4540         addressbook_set_target_compose(compose);
4541         compose_set_template_menu(compose);
4542
4543         compose_list = g_list_append(compose_list, compose);
4544
4545 #if 0 /* NEW COMPOSE GUI */
4546         compose->use_to         = FALSE;
4547         compose->use_cc         = FALSE;
4548         compose->use_attach     = TRUE;
4549 #endif
4550
4551 #if 0 /* NEW COMPOSE GUI */
4552         if (!compose->use_bcc) {
4553                 gtk_widget_hide(bcc_hbox);
4554                 gtk_widget_hide(bcc_entry);
4555                 gtk_table_set_row_spacing(GTK_TABLE(table), 4, 0);
4556         }
4557         if (!compose->use_replyto) {
4558                 gtk_widget_hide(reply_hbox);
4559                 gtk_widget_hide(reply_entry);
4560                 gtk_table_set_row_spacing(GTK_TABLE(table), 5, 0);
4561         }
4562         if (!compose->use_followupto) {
4563                 gtk_widget_hide(followup_hbox);
4564                 gtk_widget_hide(followup_entry);
4565                 gtk_table_set_row_spacing(GTK_TABLE(table), 6, 0);
4566         }
4567 #endif
4568         if (!prefs_common.show_ruler)
4569                 gtk_widget_hide(ruler_hbox);
4570
4571         select_account(compose, account);
4572
4573         return compose;
4574 }
4575
4576 #include "pixmaps/stock_mail_send.xpm"
4577 #include "pixmaps/stock_mail_send_queue.xpm"
4578 #include "pixmaps/stock_mail.xpm"
4579 #include "pixmaps/stock_paste.xpm"
4580 #include "pixmaps/stock_mail_attach.xpm"
4581 #include "pixmaps/stock_mail_compose.xpm"
4582 #include "pixmaps/linewrap.xpm"
4583 #include "pixmaps/tb_address_book.xpm"
4584
4585 #define CREATE_TOOLBAR_ICON(xpm_d) \
4586 { \
4587         icon = gdk_pixmap_create_from_xpm_d(container->window, &mask, \
4588                                             &container->style->white, \
4589                                             xpm_d); \
4590         icon_wid = gtk_pixmap_new(icon, mask); \
4591 }
4592
4593 static void compose_toolbar_create(Compose *compose, GtkWidget *container)
4594 {
4595         GtkWidget *toolbar;
4596         GtkWidget *icon_wid;
4597         GtkWidget *send_btn;
4598         GtkWidget *sendl_btn;
4599         GtkWidget *draft_btn;
4600         GtkWidget *insert_btn;
4601         GtkWidget *attach_btn;
4602         GtkWidget *sig_btn;
4603         GtkWidget *exteditor_btn;
4604         GtkWidget *linewrap_btn;
4605         GtkWidget *addrbook_btn;
4606
4607         toolbar = gtk_toolbar_new(GTK_ORIENTATION_HORIZONTAL,
4608                                   GTK_TOOLBAR_BOTH);
4609         gtk_container_add(GTK_CONTAINER(container), toolbar);
4610         gtk_container_set_border_width(GTK_CONTAINER(container), 2);
4611         gtk_toolbar_set_button_relief(GTK_TOOLBAR(toolbar), GTK_RELIEF_NONE);
4612         gtk_toolbar_set_space_style(GTK_TOOLBAR(toolbar),
4613                                     GTK_TOOLBAR_SPACE_LINE);
4614
4615         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_MAIL_SEND);
4616         send_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4617                                            _("Send"),
4618                                            _("Send message"),
4619                                            "Send",
4620                                            icon_wid, toolbar_send_cb, compose);
4621
4622         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_MAIL_SEND_QUEUE);
4623         sendl_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4624                                            _("Send later"),
4625                                            _("Put into queue folder and send later"),
4626                                            "Send later",
4627                                            icon_wid, toolbar_send_later_cb,
4628                                            compose);
4629
4630         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_MAIL);
4631         draft_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4632                                             _("Draft"),
4633                                             _("Save to draft folder"),
4634                                             "Draft",
4635                                             icon_wid, toolbar_draft_cb,
4636                                             compose);
4637
4638         gtk_toolbar_append_space(GTK_TOOLBAR(toolbar));
4639
4640         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_PASTE);
4641         insert_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4642                                              _("Insert"),
4643                                              _("Insert file"),
4644                                              "Insert",
4645                                              icon_wid, toolbar_insert_cb,
4646                                              compose);
4647
4648         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_MAIL_ATTACH);
4649         attach_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4650                                              _("Attach"),
4651                                              _("Attach file"),
4652                                              "Attach",
4653                                              icon_wid, toolbar_attach_cb,
4654                                              compose);
4655
4656         gtk_toolbar_append_space(GTK_TOOLBAR(toolbar));
4657
4658         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_MAIL);
4659         sig_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4660                                           _("Signature"),
4661                                           _("Insert signature"),
4662                                           "Signature",
4663                                           icon_wid, toolbar_sig_cb, compose);
4664
4665         gtk_toolbar_append_space(GTK_TOOLBAR(toolbar));
4666
4667         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_MAIL_COMPOSE);
4668         exteditor_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4669                                                 _("Editor"),
4670                                                 _("Edit with external editor"),
4671                                                 "Editor",
4672                                                 icon_wid,
4673                                                 toolbar_ext_editor_cb,
4674                                                 compose);
4675
4676         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_LINEWRAP);
4677         linewrap_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4678                                                _("Linewrap"),
4679                                                _("Wrap all long lines"),
4680                                                "Linewrap",
4681                                                icon_wid,
4682                                                toolbar_linewrap_cb,
4683                                                compose);
4684
4685         gtk_toolbar_append_space(GTK_TOOLBAR(toolbar));
4686
4687         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_ADDRESS_BOOK);
4688         addrbook_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4689                                                _("Address"),
4690                                                _("Address book"),
4691                                                "Address",
4692                                                icon_wid, toolbar_address_cb,
4693                                                compose);
4694
4695         compose->toolbar       = toolbar;
4696         compose->send_btn      = send_btn;
4697         compose->sendl_btn     = sendl_btn;
4698         compose->draft_btn     = draft_btn;
4699         compose->insert_btn    = insert_btn;
4700         compose->attach_btn    = attach_btn;
4701         compose->sig_btn       = sig_btn;
4702         compose->exteditor_btn = exteditor_btn;
4703         compose->linewrap_btn  = linewrap_btn;
4704         compose->addrbook_btn  = addrbook_btn;
4705
4706         gtk_widget_show_all(toolbar);
4707 }
4708
4709 static GtkWidget *compose_account_option_menu_create(Compose *compose)
4710 {
4711         GList *accounts;
4712         GtkWidget *hbox;
4713         GtkWidget *optmenu;
4714         GtkWidget *menu;
4715         gint num = 0, def_menu = 0;
4716
4717         accounts = account_get_list();
4718         g_return_val_if_fail(accounts != NULL, NULL);
4719
4720         hbox = gtk_hbox_new(FALSE, 0);
4721         optmenu = gtk_option_menu_new();
4722         gtk_box_pack_start(GTK_BOX(hbox), optmenu, FALSE, FALSE, 0);
4723         menu = gtk_menu_new();
4724
4725         for (; accounts != NULL; accounts = accounts->next, num++) {
4726                 PrefsAccount *ac = (PrefsAccount *)accounts->data;
4727                 GtkWidget *menuitem;
4728                 gchar *name;
4729
4730                 if (ac == compose->account) def_menu = num;
4731
4732                 name = g_strdup_printf("%s: %s <%s>",
4733                                        ac->account_name, ac->name, ac->address);
4734                 MENUITEM_ADD(menu, menuitem, name, ac);
4735                 g_free(name);
4736                 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
4737                                    GTK_SIGNAL_FUNC(account_activated),
4738                                    compose);
4739         }
4740
4741         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), menu);
4742         gtk_option_menu_set_history(GTK_OPTION_MENU(optmenu), def_menu);
4743
4744         return hbox;
4745 }
4746
4747 static void compose_set_template_menu(Compose *compose)
4748 {
4749         GSList *tmpl_list, *cur;
4750         GtkWidget *menu;
4751         GtkWidget *item;
4752
4753         tmpl_list = template_get_config();
4754
4755         menu = gtk_menu_new();
4756
4757         for (cur = tmpl_list; cur != NULL; cur = cur->next) {
4758                 Template *tmpl = (Template *)cur->data;
4759
4760                 item = gtk_menu_item_new_with_label(tmpl->name);
4761                 gtk_menu_append(GTK_MENU(menu), item);
4762                 gtk_signal_connect(GTK_OBJECT(item), "activate",
4763                                    GTK_SIGNAL_FUNC(compose_template_activate_cb),
4764                                    compose);
4765                 gtk_object_set_data(GTK_OBJECT(item), "template", tmpl);
4766                 gtk_widget_show(item);
4767         }
4768
4769         gtk_widget_show(menu);
4770         gtk_menu_item_set_submenu(GTK_MENU_ITEM(compose->tmpl_menu), menu);
4771 }
4772
4773 void compose_reflect_prefs_all(void)
4774 {
4775         GList *cur;
4776         Compose *compose;
4777
4778         for (cur = compose_list; cur != NULL; cur = cur->next) {
4779                 compose = (Compose *)cur->data;
4780                 compose_set_template_menu(compose);
4781         }
4782 }
4783
4784 static void compose_template_apply(Compose *compose, Template *tmpl)
4785 {
4786         gchar *qmark;
4787         gchar *parsed_str;
4788
4789         if (!tmpl || !tmpl->value) return;
4790
4791         gtk_stext_freeze(GTK_STEXT(compose->text));
4792         
4793         if (tmpl->subject && *tmpl->subject != '\0')
4794                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry),
4795                                    tmpl->subject);
4796         if (tmpl->to && *tmpl->to != '\0')
4797                 compose_entry_append(compose, tmpl->to, COMPOSE_TO);
4798
4799         if (compose->replyinfo == NULL) {
4800                 MsgInfo dummyinfo;
4801
4802                 memset(&dummyinfo, 0, sizeof(MsgInfo));
4803                 parsed_str = compose_quote_fmt(compose, &dummyinfo,
4804                                                tmpl->value, NULL);
4805         } else {
4806                 if (prefs_common.quotemark && *prefs_common.quotemark)
4807                         qmark = prefs_common.quotemark;
4808                 else
4809                         qmark = "> ";
4810
4811                 parsed_str = compose_quote_fmt(compose, compose->replyinfo,
4812                                                tmpl->value, qmark);
4813         }
4814
4815         if (parsed_str && prefs_common.auto_sig)
4816                 compose_insert_sig(compose);
4817
4818         gtk_stext_thaw(GTK_STEXT(compose->text));
4819 }
4820
4821 static void compose_destroy(Compose *compose)
4822 {
4823         gint row;
4824         GtkCList *clist = GTK_CLIST(compose->attach_clist);
4825         AttachInfo *ainfo;
4826
4827         /* NOTE: address_completion_end() does nothing with the window
4828          * however this may change. */
4829         address_completion_end(compose->window);
4830
4831         slist_free_strings(compose->to_list);
4832         g_slist_free(compose->to_list);
4833         slist_free_strings(compose->newsgroup_list);
4834         g_slist_free(compose->newsgroup_list);
4835         slist_free_strings(compose->header_list);
4836         g_slist_free(compose->header_list);
4837
4838         procmsg_msginfo_free(compose->targetinfo);
4839         procmsg_msginfo_free(compose->replyinfo);
4840
4841         g_free(compose->replyto);
4842         g_free(compose->cc);
4843         g_free(compose->bcc);
4844         g_free(compose->newsgroups);
4845         g_free(compose->followup_to);
4846
4847         g_free(compose->inreplyto);
4848         g_free(compose->references);
4849         g_free(compose->msgid);
4850         g_free(compose->boundary);
4851
4852         if (compose->bounce_filename)
4853                 g_free(compose->bounce_filename);
4854
4855         g_free(compose->exteditor_file);
4856
4857         for (row = 0; (ainfo = gtk_clist_get_row_data(clist, row)) != NULL;
4858              row++)
4859                 compose_attach_info_free(ainfo);
4860
4861         if (addressbook_get_target_compose() == compose)
4862                 addressbook_set_target_compose(NULL);
4863
4864         prefs_common.compose_width = compose->scrolledwin->allocation.width;
4865         prefs_common.compose_height = compose->window->allocation.height;
4866
4867         gtk_widget_destroy(compose->paned);
4868
4869         g_free(compose);
4870
4871         compose_list = g_list_remove(compose_list, compose);
4872 }
4873
4874 static void compose_attach_info_free(AttachInfo *ainfo)
4875 {
4876         g_free(ainfo->file);
4877         g_free(ainfo->content_type);
4878         g_free(ainfo->name);
4879         g_free(ainfo);
4880 }
4881
4882 static void compose_attach_remove_selected(Compose *compose)
4883 {
4884         GtkCList *clist = GTK_CLIST(compose->attach_clist);
4885         AttachInfo *ainfo;
4886         gint row;
4887
4888         while (clist->selection != NULL) {
4889                 row = GPOINTER_TO_INT(clist->selection->data);
4890                 ainfo = gtk_clist_get_row_data(clist, row);
4891                 compose_attach_info_free(ainfo);
4892                 gtk_clist_remove(clist, row);
4893         }
4894 }
4895
4896 static struct _AttachProperty
4897 {
4898         GtkWidget *window;
4899         GtkWidget *mimetype_entry;
4900         GtkWidget *encoding_optmenu;
4901         GtkWidget *path_entry;
4902         GtkWidget *filename_entry;
4903         GtkWidget *ok_btn;
4904         GtkWidget *cancel_btn;
4905 } attach_prop;
4906
4907 static void compose_attach_property(Compose *compose)
4908 {
4909         GtkCList *clist = GTK_CLIST(compose->attach_clist);
4910         AttachInfo *ainfo;
4911         gint row;
4912         GtkOptionMenu *optmenu;
4913         static gboolean cancelled;
4914
4915         if (!clist->selection) return;
4916         row = GPOINTER_TO_INT(clist->selection->data);
4917
4918         ainfo = gtk_clist_get_row_data(clist, row);
4919         if (!ainfo) return;
4920
4921         if (!attach_prop.window)
4922                 compose_attach_property_create(&cancelled);
4923         gtk_widget_grab_focus(attach_prop.ok_btn);
4924         gtk_widget_show(attach_prop.window);
4925         manage_window_set_transient(GTK_WINDOW(attach_prop.window));
4926
4927         optmenu = GTK_OPTION_MENU(attach_prop.encoding_optmenu);
4928         if (ainfo->encoding == ENC_UNKNOWN)
4929                 gtk_option_menu_set_history(optmenu, ENC_BASE64);
4930         else
4931                 gtk_option_menu_set_history(optmenu, ainfo->encoding);
4932
4933         gtk_entry_set_text(GTK_ENTRY(attach_prop.mimetype_entry),
4934                            ainfo->content_type ? ainfo->content_type : "");
4935         gtk_entry_set_text(GTK_ENTRY(attach_prop.path_entry),
4936                            ainfo->file ? ainfo->file : "");
4937         gtk_entry_set_text(GTK_ENTRY(attach_prop.filename_entry),
4938                            ainfo->name ? ainfo->name : "");
4939
4940         for (;;) {
4941                 gchar *text;
4942                 gchar *cnttype = NULL;
4943                 gchar *file = NULL;
4944                 off_t size = 0;
4945                 GtkWidget *menu;
4946                 GtkWidget *menuitem;
4947
4948                 cancelled = FALSE;
4949                 gtk_main();
4950
4951                 if (cancelled == TRUE) {
4952                         gtk_widget_hide(attach_prop.window);
4953                         break;
4954                 }
4955
4956                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.mimetype_entry));
4957                 if (*text != '\0') {
4958                         gchar *p;
4959
4960                         text = g_strstrip(g_strdup(text));
4961                         if ((p = strchr(text, '/')) && !strchr(p + 1, '/')) {
4962                                 cnttype = g_strdup(text);
4963                                 g_free(text);
4964                         } else {
4965                                 alertpanel_error(_("Invalid MIME type."));
4966                                 g_free(text);
4967                                 continue;
4968                         }
4969                 }
4970
4971                 menu = gtk_option_menu_get_menu(optmenu);
4972                 menuitem = gtk_menu_get_active(GTK_MENU(menu));
4973                 ainfo->encoding = GPOINTER_TO_INT
4974                         (gtk_object_get_user_data(GTK_OBJECT(menuitem)));
4975
4976                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.path_entry));
4977                 if (*text != '\0') {
4978                         if (is_file_exist(text) &&
4979                             (size = get_file_size(text)) > 0)
4980                                 file = g_strdup(text);
4981                         else {
4982                                 alertpanel_error
4983                                         (_("File doesn't exist or is empty."));
4984                                 g_free(cnttype);
4985                                 continue;
4986                         }
4987                 }
4988
4989                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.filename_entry));
4990                 if (*text != '\0') {
4991                         g_free(ainfo->name);
4992                         ainfo->name = g_strdup(text);
4993                 }
4994
4995                 if (cnttype) {
4996                         g_free(ainfo->content_type);
4997                         ainfo->content_type = cnttype;
4998                 }
4999                 if (file) {
5000                         g_free(ainfo->file);
5001                         ainfo->file = file;
5002                 }
5003                 if (size)
5004                         ainfo->size = size;
5005
5006                 gtk_clist_set_text(clist, row, COL_MIMETYPE,
5007                                    ainfo->content_type);
5008                 gtk_clist_set_text(clist, row, COL_SIZE,
5009                                    to_human_readable(ainfo->size));
5010                 gtk_clist_set_text(clist, row, COL_NAME, ainfo->name);
5011
5012                 gtk_widget_hide(attach_prop.window);
5013                 break;
5014         }
5015 }
5016
5017 #define SET_LABEL_AND_ENTRY(str, entry, top) \
5018 { \
5019         label = gtk_label_new(str); \
5020         gtk_table_attach(GTK_TABLE(table), label, 0, 1, top, (top + 1), \
5021                          GTK_FILL, 0, 0, 0); \
5022         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); \
5023  \
5024         entry = gtk_entry_new(); \
5025         gtk_table_attach(GTK_TABLE(table), entry, 1, 2, top, (top + 1), \
5026                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0); \
5027 }
5028
5029 static void compose_attach_property_create(gboolean *cancelled)
5030 {
5031         GtkWidget *window;
5032         GtkWidget *vbox;
5033         GtkWidget *table;
5034         GtkWidget *label;
5035         GtkWidget *mimetype_entry;
5036         GtkWidget *hbox;
5037         GtkWidget *optmenu;
5038         GtkWidget *optmenu_menu;
5039         GtkWidget *menuitem;
5040         GtkWidget *path_entry;
5041         GtkWidget *filename_entry;
5042         GtkWidget *hbbox;
5043         GtkWidget *ok_btn;
5044         GtkWidget *cancel_btn;
5045         GList     *mime_type_list, *strlist;
5046
5047         debug_print("Creating attach_property window...\n");
5048
5049         window = gtk_window_new(GTK_WINDOW_DIALOG);
5050         gtk_widget_set_usize(window, 480, -1);
5051         gtk_container_set_border_width(GTK_CONTAINER(window), 8);
5052         gtk_window_set_title(GTK_WINDOW(window), _("Property"));
5053         gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
5054         gtk_window_set_modal(GTK_WINDOW(window), TRUE);
5055         gtk_signal_connect(GTK_OBJECT(window), "delete_event",
5056                            GTK_SIGNAL_FUNC(attach_property_delete_event),
5057                            cancelled);
5058         gtk_signal_connect(GTK_OBJECT(window), "key_press_event",
5059                            GTK_SIGNAL_FUNC(attach_property_key_pressed),
5060                            cancelled);
5061
5062         vbox = gtk_vbox_new(FALSE, 8);
5063         gtk_container_add(GTK_CONTAINER(window), vbox);
5064
5065         table = gtk_table_new(4, 2, FALSE);
5066         gtk_box_pack_start(GTK_BOX(vbox), table, FALSE, FALSE, 0);
5067         gtk_table_set_row_spacings(GTK_TABLE(table), 8);
5068         gtk_table_set_col_spacings(GTK_TABLE(table), 8);
5069
5070         label = gtk_label_new(_("MIME type")); 
5071         gtk_table_attach(GTK_TABLE(table), label, 0, 1, 0, (0 + 1), 
5072                          GTK_FILL, 0, 0, 0); 
5073         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); 
5074         mimetype_entry = gtk_combo_new(); 
5075         gtk_table_attach(GTK_TABLE(table), mimetype_entry, 1, 2, 0, (0 + 1), 
5076                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0);
5077                          
5078         /* stuff with list */
5079         mime_type_list = procmime_get_mime_type_list();
5080         strlist = NULL;
5081         for (; mime_type_list != NULL; mime_type_list = mime_type_list->next) {
5082                 MimeType *type = (MimeType *) mime_type_list->data;
5083                 strlist = g_list_append(strlist, 
5084                                 g_strdup_printf("%s/%s",
5085                                         type->type, type->sub_type));
5086         }
5087         
5088         gtk_combo_set_popdown_strings(GTK_COMBO(mimetype_entry), strlist);
5089
5090         for (mime_type_list = strlist; mime_type_list != NULL; 
5091                 mime_type_list = mime_type_list->next)
5092                 g_free(mime_type_list->data);
5093         g_list_free(strlist);
5094                          
5095         mimetype_entry = GTK_COMBO(mimetype_entry)->entry;                       
5096
5097         label = gtk_label_new(_("Encoding"));
5098         gtk_table_attach(GTK_TABLE(table), label, 0, 1, 1, 2,
5099                          GTK_FILL, 0, 0, 0);
5100         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5);
5101
5102         hbox = gtk_hbox_new(FALSE, 0);
5103         gtk_table_attach(GTK_TABLE(table), hbox, 1, 2, 1, 2,
5104                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0);
5105
5106         optmenu = gtk_option_menu_new();
5107         gtk_box_pack_start(GTK_BOX(hbox), optmenu, FALSE, FALSE, 0);
5108
5109         optmenu_menu = gtk_menu_new();
5110         MENUITEM_ADD(optmenu_menu, menuitem, "7bit", ENC_7BIT);
5111         gtk_widget_set_sensitive(menuitem, FALSE);
5112         MENUITEM_ADD(optmenu_menu, menuitem, "8bit", ENC_8BIT);
5113         gtk_widget_set_sensitive(menuitem, FALSE);
5114         MENUITEM_ADD(optmenu_menu, menuitem, "quoted-printable", ENC_QUOTED_PRINTABLE);
5115         gtk_widget_set_sensitive(menuitem, FALSE);
5116         MENUITEM_ADD(optmenu_menu, menuitem, "base64", ENC_BASE64);
5117
5118         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
5119
5120         SET_LABEL_AND_ENTRY(_("Path"),      path_entry,     2);
5121         SET_LABEL_AND_ENTRY(_("File name"), filename_entry, 3);
5122
5123         gtkut_button_set_create(&hbbox, &ok_btn, _("OK"),
5124                                 &cancel_btn, _("Cancel"), NULL, NULL);
5125         gtk_box_pack_end(GTK_BOX(vbox), hbbox, FALSE, FALSE, 0);
5126         gtk_widget_grab_default(ok_btn);
5127
5128         gtk_signal_connect(GTK_OBJECT(ok_btn), "clicked",
5129                            GTK_SIGNAL_FUNC(attach_property_ok),
5130                            cancelled);
5131         gtk_signal_connect(GTK_OBJECT(cancel_btn), "clicked",
5132                            GTK_SIGNAL_FUNC(attach_property_cancel),
5133                            cancelled);
5134
5135         gtk_widget_show_all(vbox);
5136
5137         attach_prop.window           = window;
5138         attach_prop.mimetype_entry   = mimetype_entry;
5139         attach_prop.encoding_optmenu = optmenu;
5140         attach_prop.path_entry       = path_entry;
5141         attach_prop.filename_entry   = filename_entry;
5142         attach_prop.ok_btn           = ok_btn;
5143         attach_prop.cancel_btn       = cancel_btn;
5144 }
5145
5146 #undef SET_LABEL_AND_ENTRY
5147
5148 static void attach_property_ok(GtkWidget *widget, gboolean *cancelled)
5149 {
5150         *cancelled = FALSE;
5151         gtk_main_quit();
5152 }
5153
5154 static void attach_property_cancel(GtkWidget *widget, gboolean *cancelled)
5155 {
5156         *cancelled = TRUE;
5157         gtk_main_quit();
5158 }
5159
5160 static gint attach_property_delete_event(GtkWidget *widget, GdkEventAny *event,
5161                                          gboolean *cancelled)
5162 {
5163         *cancelled = TRUE;
5164         gtk_main_quit();
5165
5166         return TRUE;
5167 }
5168
5169 static void attach_property_key_pressed(GtkWidget *widget, GdkEventKey *event,
5170                                         gboolean *cancelled)
5171 {
5172         if (event && event->keyval == GDK_Escape) {
5173                 *cancelled = TRUE;
5174                 gtk_main_quit();
5175         }
5176 }
5177
5178 static void compose_exec_ext_editor(Compose *compose)
5179 {
5180         gchar tmp[64];
5181         pid_t pid;
5182         gint pipe_fds[2];
5183
5184         g_snprintf(tmp, sizeof(tmp), "%s%ctmpmsg.%08x",
5185                    g_get_tmp_dir(), G_DIR_SEPARATOR, (gint)compose);
5186
5187         if (pipe(pipe_fds) < 0) {
5188                 perror("pipe");
5189                 return;
5190         }
5191
5192         if ((pid = fork()) < 0) {
5193                 perror("fork");
5194                 return;
5195         }
5196
5197         if (pid != 0) {
5198                 /* close the write side of the pipe */
5199                 close(pipe_fds[1]);
5200
5201                 compose->exteditor_file    = g_strdup(tmp);
5202                 compose->exteditor_pid     = pid;
5203                 compose->exteditor_readdes = pipe_fds[0];
5204
5205                 compose_set_ext_editor_sensitive(compose, FALSE);
5206
5207                 compose->exteditor_tag =
5208                         gdk_input_add(pipe_fds[0], GDK_INPUT_READ,
5209                                       compose_input_cb, compose);
5210         } else {        /* process-monitoring process */
5211                 pid_t pid_ed;
5212
5213                 if (setpgid(0, 0))
5214                         perror("setpgid");
5215
5216                 /* close the read side of the pipe */
5217                 close(pipe_fds[0]);
5218
5219                 if (compose_write_body_to_file(compose, tmp) < 0) {
5220                         fd_write(pipe_fds[1], "2\n", 2);
5221                         _exit(1);
5222                 }
5223
5224                 pid_ed = compose_exec_ext_editor_real(tmp);
5225                 if (pid_ed < 0) {
5226                         fd_write(pipe_fds[1], "1\n", 2);
5227                         _exit(1);
5228                 }
5229
5230                 /* wait until editor is terminated */
5231                 waitpid(pid_ed, NULL, 0);
5232
5233                 fd_write(pipe_fds[1], "0\n", 2);
5234
5235                 close(pipe_fds[1]);
5236                 _exit(0);
5237         }
5238 }
5239
5240 static gint compose_exec_ext_editor_real(const gchar *file)
5241 {
5242         static gchar *def_cmd = "emacs %s";
5243         gchar buf[1024];
5244         gchar *p;
5245         gchar **cmdline;
5246         pid_t pid;
5247
5248         g_return_val_if_fail(file != NULL, -1);
5249
5250         if ((pid = fork()) < 0) {
5251                 perror("fork");
5252                 return -1;
5253         }
5254
5255         if (pid != 0) return pid;
5256
5257         /* grandchild process */
5258
5259         if (setpgid(0, getppid()))
5260                 perror("setpgid");
5261
5262         if (prefs_common.ext_editor_cmd &&
5263             (p = strchr(prefs_common.ext_editor_cmd, '%')) &&
5264             *(p + 1) == 's' && !strchr(p + 2, '%')) {
5265                 g_snprintf(buf, sizeof(buf), prefs_common.ext_editor_cmd, file);
5266         } else {
5267                 if (prefs_common.ext_editor_cmd)
5268                         g_warning(_("External editor command line is invalid: `%s'\n"),
5269                                   prefs_common.ext_editor_cmd);
5270                 g_snprintf(buf, sizeof(buf), def_cmd, file);
5271         }
5272
5273         cmdline = g_strsplit(buf, " ", 1024);
5274         execvp(cmdline[0], cmdline);
5275
5276         perror("execvp");
5277         g_strfreev(cmdline);
5278
5279         _exit(1);
5280 }
5281
5282 static gboolean compose_ext_editor_kill(Compose *compose)
5283 {
5284         pid_t pgid = compose->exteditor_pid * -1;
5285         gint ret;
5286
5287         ret = kill(pgid, 0);
5288
5289         if (ret == 0 || (ret == -1 && EPERM == errno)) {
5290                 AlertValue val;
5291                 gchar *msg;
5292
5293                 msg = g_strdup_printf
5294                         (_("The external editor is still working.\n"
5295                            "Force terminating the process?\n"
5296                            "process group id: %d"), -pgid);
5297                 val = alertpanel(_("Notice"), msg, _("Yes"), _("+No"), NULL);
5298                 g_free(msg);
5299
5300                 if (val == G_ALERTDEFAULT) {
5301                         gdk_input_remove(compose->exteditor_tag);
5302                         close(compose->exteditor_readdes);
5303
5304                         if (kill(pgid, SIGTERM) < 0) perror("kill");
5305                         waitpid(compose->exteditor_pid, NULL, 0);
5306
5307                         g_warning(_("Terminated process group id: %d"), -pgid);
5308                         g_warning(_("Temporary file: %s"),
5309                                   compose->exteditor_file);
5310
5311                         compose_set_ext_editor_sensitive(compose, TRUE);
5312
5313                         g_free(compose->exteditor_file);
5314                         compose->exteditor_file    = NULL;
5315                         compose->exteditor_pid     = -1;
5316                         compose->exteditor_readdes = -1;
5317                         compose->exteditor_tag     = -1;
5318                 } else
5319                         return FALSE;
5320         }
5321
5322         return TRUE;
5323 }
5324
5325 static void compose_input_cb(gpointer data, gint source,
5326                              GdkInputCondition condition)
5327 {
5328         gchar buf[3];
5329         Compose *compose = (Compose *)data;
5330         gint i = 0;
5331
5332         debug_print(_("Compose: input from monitoring process\n"));
5333
5334         gdk_input_remove(compose->exteditor_tag);
5335
5336         for (;;) {
5337                 if (read(source, &buf[i], 1) < 1) {
5338                         buf[0] = '3';
5339                         break;
5340                 }
5341                 if (buf[i] == '\n') {
5342                         buf[i] = '\0';
5343                         break;
5344                 }
5345                 i++;
5346                 if (i == sizeof(buf) - 1)
5347                         break;
5348         }
5349
5350         waitpid(compose->exteditor_pid, NULL, 0);
5351
5352         if (buf[0] == '0') {            /* success */
5353                 GtkSText *text = GTK_STEXT(compose->text);
5354
5355                 gtk_stext_freeze(text);
5356                 gtk_stext_set_point(text, 0);
5357                 gtk_stext_forward_delete(text, gtk_stext_get_length(text));
5358                 compose_insert_file(compose, compose->exteditor_file);
5359                 compose_changed_cb(NULL, compose);
5360                 gtk_stext_thaw(text);
5361
5362                 if (unlink(compose->exteditor_file) < 0)
5363                         FILE_OP_ERROR(compose->exteditor_file, "unlink");
5364         } else if (buf[0] == '1') {     /* failed */
5365                 g_warning(_("Couldn't exec external editor\n"));
5366                 if (unlink(compose->exteditor_file) < 0)
5367                         FILE_OP_ERROR(compose->exteditor_file, "unlink");
5368         } else if (buf[0] == '2') {
5369                 g_warning(_("Couldn't write to file\n"));
5370         } else if (buf[0] == '3') {
5371                 g_warning(_("Pipe read failed\n"));
5372         }
5373
5374         close(source);
5375
5376         compose_set_ext_editor_sensitive(compose, TRUE);
5377
5378         g_free(compose->exteditor_file);
5379         compose->exteditor_file    = NULL;
5380         compose->exteditor_pid     = -1;
5381         compose->exteditor_readdes = -1;
5382         compose->exteditor_tag     = -1;
5383 }
5384
5385 static void compose_set_ext_editor_sensitive(Compose *compose,
5386                                              gboolean sensitive)
5387 {
5388         GtkItemFactory *ifactory;
5389
5390         ifactory = gtk_item_factory_from_widget(compose->menubar);
5391
5392         menu_set_sensitive(ifactory, "/Message/Send", sensitive);
5393         menu_set_sensitive(ifactory, "/Message/Send later", sensitive);
5394         menu_set_sensitive(ifactory, "/Message/Save to draft folder",
5395                            sensitive);
5396         menu_set_sensitive(ifactory, "/File/Insert file", sensitive);
5397         menu_set_sensitive(ifactory, "/File/Insert signature", sensitive);
5398         menu_set_sensitive(ifactory, "/Edit/Wrap current paragraph", sensitive);
5399         menu_set_sensitive(ifactory, "/Edit/Wrap all long lines", sensitive);
5400         menu_set_sensitive(ifactory, "/Edit/Edit with external editor",
5401                            sensitive);
5402
5403         gtk_widget_set_sensitive(compose->text,          sensitive);
5404         gtk_widget_set_sensitive(compose->send_btn,      sensitive);
5405         gtk_widget_set_sensitive(compose->sendl_btn,     sensitive);
5406         gtk_widget_set_sensitive(compose->draft_btn,     sensitive);
5407         gtk_widget_set_sensitive(compose->insert_btn,    sensitive);
5408         gtk_widget_set_sensitive(compose->sig_btn,       sensitive);
5409         gtk_widget_set_sensitive(compose->exteditor_btn, sensitive);
5410         gtk_widget_set_sensitive(compose->linewrap_btn,  sensitive);
5411 }
5412
5413 /**
5414  * compose_undo_state_changed:
5415  *
5416  * Change the sensivity of the menuentries undo and redo
5417  **/
5418 static void compose_undo_state_changed(UndoMain *undostruct, gint undo_state,
5419                                        gint redo_state, gpointer data)
5420 {
5421         GtkWidget *widget = GTK_WIDGET(data);
5422         GtkItemFactory *ifactory;
5423
5424         g_return_if_fail(widget != NULL);
5425
5426         debug_print("Set_undo.  UNDO:%i  REDO:%i\n", undo_state, redo_state);
5427
5428         ifactory = gtk_item_factory_from_widget(widget);
5429
5430         switch (undo_state) {
5431         case UNDO_STATE_TRUE:
5432                 if (!undostruct->undo_state) {
5433                         debug_print ("Set_undo - Testpoint\n");
5434                         undostruct->undo_state = TRUE;
5435                         menu_set_sensitive(ifactory, "/Edit/Undo", TRUE);
5436                 }
5437                 break;
5438         case UNDO_STATE_FALSE:
5439                 if (undostruct->undo_state) {
5440                         undostruct->undo_state = FALSE;
5441                         menu_set_sensitive(ifactory, "/Edit/Undo", FALSE);
5442                 }
5443                 break;
5444         case UNDO_STATE_UNCHANGED:
5445                 break;
5446         case UNDO_STATE_REFRESH:
5447                 menu_set_sensitive(ifactory, "/Edit/Undo",
5448                                    undostruct->undo_state);
5449                 break;
5450         default:
5451                 g_warning("Undo state not recognized");
5452                 break;
5453         }
5454
5455         switch (redo_state) {
5456         case UNDO_STATE_TRUE:
5457                 if (!undostruct->redo_state) {
5458                         undostruct->redo_state = TRUE;
5459                         menu_set_sensitive(ifactory, "/Edit/Redo", TRUE);
5460                 }
5461                 break;
5462         case UNDO_STATE_FALSE:
5463                 if (undostruct->redo_state) {
5464                         undostruct->redo_state = FALSE;
5465                         menu_set_sensitive(ifactory, "/Edit/Redo", FALSE);
5466                 }
5467                 break;
5468         case UNDO_STATE_UNCHANGED:
5469                 break;
5470         case UNDO_STATE_REFRESH:
5471                 menu_set_sensitive(ifactory, "/Edit/Redo",
5472                                    undostruct->redo_state);
5473                 break;
5474         default:
5475                 g_warning("Redo state not recognized");
5476                 break;
5477         }
5478 }
5479
5480 static gint calc_cursor_xpos(GtkSText *text, gint extra, gint char_width)
5481 {
5482         gint cursor_pos;
5483
5484         cursor_pos = (text->cursor_pos_x - extra) / char_width;
5485         cursor_pos = MAX(cursor_pos, 0);
5486
5487         return cursor_pos;
5488 }
5489
5490 /* callback functions */
5491
5492 /* compose_edit_size_alloc() - called when resized. don't know whether Gtk
5493  * includes "non-client" (windows-izm) in calculation, so this calculation
5494  * may not be accurate.
5495  */
5496 static gboolean compose_edit_size_alloc(GtkEditable *widget,
5497                                         GtkAllocation *allocation,
5498                                         GtkSHRuler *shruler)
5499 {
5500         if (prefs_common.show_ruler) {
5501                 gint char_width;
5502                 gint line_width_in_chars;
5503
5504                 char_width = gtkut_get_font_width
5505                         (GTK_WIDGET(widget)->style->font);
5506                 line_width_in_chars =
5507                         (allocation->width - allocation->x) / char_width;
5508
5509                 /* got the maximum */
5510                 gtk_ruler_set_range(GTK_RULER(shruler),
5511                                     0.0, line_width_in_chars,
5512                                     calc_cursor_xpos(GTK_STEXT(widget),
5513                                                      allocation->x,
5514                                                      char_width),
5515                                     /*line_width_in_chars*/ char_width);
5516         }
5517
5518         return TRUE;
5519 }
5520
5521 static void toolbar_send_cb(GtkWidget *widget, gpointer data)
5522 {
5523         compose_send_cb(data, 0, NULL);
5524 }
5525
5526 static void toolbar_send_later_cb(GtkWidget *widget, gpointer data)
5527 {
5528         compose_send_later_cb(data, 0, NULL);
5529 }
5530
5531 static void toolbar_draft_cb(GtkWidget *widget, gpointer data)
5532 {
5533         compose_draft_cb(data, 0, NULL);
5534 }
5535
5536 static void toolbar_insert_cb(GtkWidget *widget, gpointer data)
5537 {
5538         compose_insert_file_cb(data, 0, NULL);
5539 }
5540
5541 static void toolbar_attach_cb(GtkWidget *widget, gpointer data)
5542 {
5543         compose_attach_cb(data, 0, NULL);
5544 }
5545
5546 static void toolbar_sig_cb(GtkWidget *widget, gpointer data)
5547 {
5548         Compose *compose = (Compose *)data;
5549
5550         compose_insert_sig(compose);
5551 }
5552
5553 static void toolbar_ext_editor_cb(GtkWidget *widget, gpointer data)
5554 {
5555         Compose *compose = (Compose *)data;
5556
5557         compose_exec_ext_editor(compose);
5558 }
5559
5560 static void toolbar_linewrap_cb(GtkWidget *widget, gpointer data)
5561 {
5562         Compose *compose = (Compose *)data;
5563
5564         compose_wrap_line(compose);
5565 }
5566
5567 static void toolbar_address_cb(GtkWidget *widget, gpointer data)
5568 {
5569         compose_address_cb(data, 0, NULL);
5570 }
5571
5572 static void select_account(Compose * compose, PrefsAccount * ac)
5573 {
5574         compose->account = ac;
5575         compose_set_title(compose);
5576
5577 #if 0 /* NEW COMPOSE GUI */
5578                 if (ac->protocol == A_NNTP) {
5579                         GtkItemFactory *ifactory;
5580                         GtkWidget *menuitem;
5581
5582                         ifactory = gtk_item_factory_from_widget(compose->menubar);
5583                         menu_set_sensitive(ifactory,
5584                                            "/Message/Followup to", TRUE);
5585                         gtk_widget_show(compose->newsgroups_hbox);
5586                         gtk_widget_show(compose->newsgroups_entry);
5587                         gtk_table_set_row_spacing(GTK_TABLE(compose->table),
5588                                                   1, 4);
5589
5590                         compose->use_to = FALSE;
5591                         compose->use_cc = FALSE;
5592
5593                         menuitem = gtk_item_factory_get_item(ifactory, "/Message/To");
5594                         gtk_check_menu_item_set_active
5595                                 (GTK_CHECK_MENU_ITEM(menuitem), FALSE);
5596
5597                         menu_set_sensitive(ifactory,
5598                                            "/Message/To", TRUE);
5599                         menuitem = gtk_item_factory_get_item(ifactory, "/Message/Cc");
5600                         gtk_check_menu_item_set_active
5601                                 (GTK_CHECK_MENU_ITEM(menuitem), FALSE);
5602
5603                         gtk_widget_hide(compose->to_hbox);
5604                         gtk_widget_hide(compose->to_entry);
5605                         gtk_widget_hide(compose->cc_hbox);
5606                         gtk_widget_hide(compose->cc_entry);
5607                         gtk_table_set_row_spacing(GTK_TABLE(compose->table),
5608                                                   0, 0);
5609                         gtk_table_set_row_spacing(GTK_TABLE(compose->table),
5610                                                   3, 0);
5611                 }
5612                 else {
5613                         GtkItemFactory *ifactory;
5614                         GtkWidget *menuitem;
5615
5616                         ifactory = gtk_item_factory_from_widget(compose->menubar);
5617                         menu_set_sensitive(ifactory,
5618                                            "/Message/Followup to", FALSE);
5619                         gtk_entry_set_text(GTK_ENTRY(compose->newsgroups_entry), "");
5620                         gtk_widget_hide(compose->newsgroups_hbox);
5621                         gtk_widget_hide(compose->newsgroups_entry);
5622                         gtk_table_set_row_spacing(GTK_TABLE(compose->table),
5623                                                   1, 0);
5624
5625                         compose->use_to = TRUE;
5626                         compose->use_cc = TRUE;
5627
5628                         menuitem = gtk_item_factory_get_item(ifactory, "/Message/To");
5629                         gtk_check_menu_item_set_active
5630                                 (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
5631                         menu_set_sensitive(ifactory,
5632                                            "/Message/To", FALSE);
5633                         menuitem = gtk_item_factory_get_item(ifactory, "/Message/Cc");
5634                         gtk_check_menu_item_set_active
5635                                 (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
5636                         gtk_widget_show(compose->to_hbox);
5637                         gtk_widget_show(compose->to_entry);
5638                         gtk_widget_show(compose->cc_hbox);
5639                         gtk_widget_show(compose->cc_entry);
5640
5641                         gtk_table_set_row_spacing(GTK_TABLE(compose->table),
5642                                                   0, 4);
5643                         gtk_table_set_row_spacing(GTK_TABLE(compose->table),
5644                                                   3, 4);
5645                 }
5646                 gtk_widget_queue_resize(compose->table_vbox);
5647 #endif
5648 }
5649
5650 static void account_activated(GtkMenuItem *menuitem, gpointer data)
5651 {
5652         Compose *compose = (Compose *)data;
5653
5654         PrefsAccount *ac;
5655
5656         ac = (PrefsAccount *)gtk_object_get_user_data(GTK_OBJECT(menuitem));
5657         g_return_if_fail(ac != NULL);
5658
5659         if (ac != compose->account)
5660                 select_account(compose, ac);
5661 }
5662
5663 static void attach_selected(GtkCList *clist, gint row, gint column,
5664                             GdkEvent *event, gpointer data)
5665 {
5666         Compose *compose = (Compose *)data;
5667
5668         if (event && event->type == GDK_2BUTTON_PRESS)
5669                 compose_attach_property(compose);
5670 }
5671
5672 static void attach_button_pressed(GtkWidget *widget, GdkEventButton *event,
5673                                   gpointer data)
5674 {
5675         Compose *compose = (Compose *)data;
5676         GtkCList *clist = GTK_CLIST(compose->attach_clist);
5677         gint row, column;
5678
5679         if (!event) return;
5680
5681         if (event->button == 3) {
5682                 if ((clist->selection && !clist->selection->next) ||
5683                     !clist->selection) {
5684                         gtk_clist_unselect_all(clist);
5685                         if (gtk_clist_get_selection_info(clist,
5686                                                          event->x, event->y,
5687                                                          &row, &column)) {
5688                                 gtk_clist_select_row(clist, row, column);
5689                                 gtkut_clist_set_focus_row(clist, row);
5690                         }
5691                 }
5692                 gtk_menu_popup(GTK_MENU(compose->popupmenu), NULL, NULL,
5693                                NULL, NULL, event->button, event->time);
5694         }
5695 }
5696
5697 static void attach_key_pressed(GtkWidget *widget, GdkEventKey *event,
5698                                gpointer data)
5699 {
5700         Compose *compose = (Compose *)data;
5701
5702         if (!event) return;
5703
5704         switch (event->keyval) {
5705         case GDK_Delete:
5706                 compose_attach_remove_selected(compose);
5707                 break;
5708         }
5709 }
5710
5711 static void compose_send_cb(gpointer data, guint action, GtkWidget *widget)
5712 {
5713         Compose *compose = (Compose *)data;
5714         gint val;
5715
5716         val = compose_send(compose);
5717         if (val == 0) gtk_widget_destroy(compose->window);
5718 }
5719
5720 static void compose_send_later_cb(gpointer data, guint action,
5721                                   GtkWidget *widget)
5722 {
5723         Compose *compose = (Compose *)data;
5724         gint val;
5725
5726         val = compose_queue(compose, NULL, NULL);
5727         if (!val) gtk_widget_destroy(compose->window);
5728 }
5729
5730 static void compose_draft_cb(gpointer data, guint action, GtkWidget *widget)
5731 {
5732         Compose *compose = (Compose *)data;
5733         FolderItem *draft;
5734         gchar *tmp;
5735
5736         draft = folder_get_default_draft();
5737
5738         tmp = g_strdup_printf("%s%cdraft.%d", g_get_tmp_dir(),
5739                               G_DIR_SEPARATOR, (gint)compose);
5740
5741         if (compose_write_to_file(compose, tmp, TRUE) < 0) {
5742                 g_free(tmp);
5743                 return;
5744         }
5745
5746         folder_item_scan(draft);
5747         if (folder_item_add_msg(draft, tmp, TRUE) < 0) {
5748                 unlink(tmp);
5749                 g_free(tmp);
5750                 return;
5751         }
5752         g_free(tmp);
5753
5754         if (compose->mode == COMPOSE_REEDIT) {
5755                 compose_remove_reedit_target(compose);
5756                 if (compose->targetinfo &&
5757                     compose->targetinfo->folder != draft)
5758                         folderview_update_item(compose->targetinfo->folder,
5759                                                TRUE);
5760         }
5761
5762         folder_item_scan(draft);
5763         folderview_update_item(draft, TRUE);
5764
5765         gtk_widget_destroy(compose->window);
5766 }
5767
5768 static void compose_attach_cb(gpointer data, guint action, GtkWidget *widget)
5769 {
5770         Compose *compose = (Compose *)data;
5771         GList *file_list;
5772
5773         if (compose->bounce_filename != NULL)
5774                 return;
5775
5776         file_list = filesel_select_multiple_files(_("Select file"), NULL);
5777
5778         if (file_list) {
5779                 GList *tmp;
5780
5781                 for ( tmp = file_list; tmp; tmp = tmp->next) {
5782                         gchar *file = (gchar *) tmp->data;
5783                         compose_attach_append(compose, file, MIME_UNKNOWN);
5784                         g_free(file);
5785                 }
5786                 g_list_free(file_list);
5787         }               
5788 }
5789
5790 static void compose_insert_file_cb(gpointer data, guint action,
5791                                    GtkWidget *widget)
5792 {
5793         Compose *compose = (Compose *)data;
5794         GList *file_list;
5795
5796         file_list = filesel_select_multiple_files(_("Select file"), NULL);
5797
5798         if (file_list) {
5799                 GList *tmp;
5800
5801                 for ( tmp = file_list; tmp; tmp = tmp->next) {
5802                         gchar *file = (gchar *) tmp->data;
5803                         compose_insert_file(compose, file);
5804                         g_free(file);
5805                 }
5806                 g_list_free(file_list);
5807         }
5808 }
5809
5810 static gint compose_delete_cb(GtkWidget *widget, GdkEventAny *event,
5811                               gpointer data)
5812 {
5813         compose_close_cb(data, 0, NULL);
5814         return TRUE;
5815 }
5816
5817 static void compose_close_cb(gpointer data, guint action, GtkWidget *widget)
5818 {
5819         Compose *compose = (Compose *)data;
5820         AlertValue val;
5821
5822         if (compose->exteditor_tag != -1) {
5823                 if (!compose_ext_editor_kill(compose))
5824                         return;
5825         }
5826
5827         if (compose->modified) {
5828                 val = alertpanel(_("Discard message"),
5829                                  _("This message has been modified. discard it?"),
5830                                  _("Discard"), _("to Draft"), _("Cancel"));
5831
5832                 switch (val) {
5833                 case G_ALERTDEFAULT:
5834                         break;
5835                 case G_ALERTALTERNATE:
5836                         compose_draft_cb(data, 0, NULL);
5837                         return;
5838                 default:
5839                         return;
5840                 }
5841         }
5842 #if USE_PSPELL
5843         if (compose->gtkpspell) {
5844                 gtkpspell_detach(compose->gtkpspell);
5845                 compose->gtkpspell = gtkpspell_delete(compose->gtkpspell);
5846         }
5847 #endif
5848         gtk_widget_destroy(compose->window);
5849 }
5850
5851 static void compose_address_cb(gpointer data, guint action, GtkWidget *widget)
5852 {
5853         Compose *compose = (Compose *)data;
5854
5855         addressbook_open(compose);
5856 }
5857
5858 static void compose_template_activate_cb(GtkWidget *widget, gpointer data)
5859 {
5860         Compose *compose = (Compose *)data;
5861         Template *tmpl;
5862
5863         tmpl = gtk_object_get_data(GTK_OBJECT(widget), "template");
5864         g_return_if_fail(tmpl != NULL);
5865
5866         compose_template_apply(compose, tmpl);
5867 }
5868
5869 static void compose_ext_editor_cb(gpointer data, guint action,
5870                                   GtkWidget *widget)
5871 {
5872         Compose *compose = (Compose *)data;
5873
5874         compose_exec_ext_editor(compose);
5875 }
5876
5877 static void compose_destroy_cb(GtkWidget *widget, Compose *compose)
5878 {
5879         compose_destroy(compose);
5880 }
5881
5882 static void compose_undo_cb(Compose *compose)
5883 {
5884         undo_undo(compose->undostruct);
5885 }
5886
5887 static void compose_redo_cb(Compose *compose)
5888 {
5889         undo_redo(compose->undostruct);
5890 }
5891
5892 static void compose_cut_cb(Compose *compose)
5893 {
5894         if (compose->focused_editable &&
5895             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
5896                 gtk_editable_cut_clipboard
5897                         (GTK_EDITABLE(compose->focused_editable));
5898 }
5899
5900 static void compose_copy_cb(Compose *compose)
5901 {
5902         if (compose->focused_editable &&
5903             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
5904                 gtk_editable_copy_clipboard
5905                         (GTK_EDITABLE(compose->focused_editable));
5906 }
5907
5908 static void compose_paste_cb(Compose *compose)
5909 {
5910         if (compose->focused_editable &&
5911             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
5912                 gtk_editable_paste_clipboard
5913                         (GTK_EDITABLE(compose->focused_editable));
5914 }
5915
5916 static void compose_allsel_cb(Compose *compose)
5917 {
5918         if (compose->focused_editable &&
5919             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
5920                 gtk_editable_select_region
5921                         (GTK_EDITABLE(compose->focused_editable), 0, -1);
5922 }
5923
5924 static void compose_grab_focus_cb(GtkWidget *widget, Compose *compose)
5925 {
5926         if (GTK_IS_EDITABLE(widget))
5927                 compose->focused_editable = widget;
5928 }
5929
5930 static void compose_changed_cb(GtkEditable *editable, Compose *compose)
5931 {
5932         if (compose->modified == FALSE) {
5933                 compose->modified = TRUE;
5934                 compose_set_title(compose);
5935         }
5936 }
5937
5938 static void compose_button_press_cb(GtkWidget *widget, GdkEventButton *event,
5939                                     Compose *compose)
5940 {
5941         gtk_stext_set_point(GTK_STEXT(widget),
5942                            gtk_editable_get_position(GTK_EDITABLE(widget)));
5943 }
5944
5945 #if 0
5946 static void compose_key_press_cb(GtkWidget *widget, GdkEventKey *event,
5947                                  Compose *compose)
5948 {
5949         gtk_stext_set_point(GTK_STEXT(widget),
5950                            gtk_editable_get_position(GTK_EDITABLE(widget)));
5951 }
5952 #endif
5953
5954 #if 0 /* NEW COMPOSE GUI */
5955 static void compose_toggle_to_cb(gpointer data, guint action,
5956                                  GtkWidget *widget)
5957 {
5958         Compose *compose = (Compose *)data;
5959
5960         if (GTK_CHECK_MENU_ITEM(widget)->active) {
5961                 gtk_widget_show(compose->to_hbox);
5962                 gtk_widget_show(compose->to_entry);
5963                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 1, 4);
5964                 compose->use_to = TRUE;
5965         } else {
5966                 gtk_widget_hide(compose->to_hbox);
5967                 gtk_widget_hide(compose->to_entry);
5968                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 1, 0);
5969                 gtk_widget_queue_resize(compose->table_vbox);
5970                 compose->use_to = FALSE;
5971         }
5972
5973         if (addressbook_get_target_compose() == compose)
5974                 addressbook_set_target_compose(compose);
5975 }
5976
5977 static void compose_toggle_cc_cb(gpointer data, guint action,
5978                                  GtkWidget *widget)
5979 {
5980         Compose *compose = (Compose *)data;
5981
5982         if (GTK_CHECK_MENU_ITEM(widget)->active) {
5983                 gtk_widget_show(compose->cc_hbox);
5984                 gtk_widget_show(compose->cc_entry);
5985                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 3, 4);
5986                 compose->use_cc = TRUE;
5987         } else {
5988                 gtk_widget_hide(compose->cc_hbox);
5989                 gtk_widget_hide(compose->cc_entry);
5990                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 3, 0);
5991                 gtk_widget_queue_resize(compose->table_vbox);
5992                 compose->use_cc = FALSE;
5993         }
5994
5995         if (addressbook_get_target_compose() == compose)
5996                 addressbook_set_target_compose(compose);
5997 }
5998
5999 static void compose_toggle_bcc_cb(gpointer data, guint action,
6000                                   GtkWidget *widget)
6001 {
6002         Compose *compose = (Compose *)data;
6003
6004         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6005                 gtk_widget_show(compose->bcc_hbox);
6006                 gtk_widget_show(compose->bcc_entry);
6007                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 4, 4);
6008                 compose->use_bcc = TRUE;
6009         } else {
6010                 gtk_widget_hide(compose->bcc_hbox);
6011                 gtk_widget_hide(compose->bcc_entry);
6012                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 4, 0);
6013                 gtk_widget_queue_resize(compose->table_vbox);
6014                 compose->use_bcc = FALSE;
6015         }
6016
6017         if (addressbook_get_target_compose() == compose)
6018                 addressbook_set_target_compose(compose);
6019 }
6020
6021 static void compose_toggle_replyto_cb(gpointer data, guint action,
6022                                       GtkWidget *widget)
6023 {
6024         Compose *compose = (Compose *)data;
6025
6026         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6027                 gtk_widget_show(compose->reply_hbox);
6028                 gtk_widget_show(compose->reply_entry);
6029                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 5, 4);
6030                 compose->use_replyto = TRUE;
6031         } else {
6032                 gtk_widget_hide(compose->reply_hbox);
6033                 gtk_widget_hide(compose->reply_entry);
6034                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 5, 0);
6035                 gtk_widget_queue_resize(compose->table_vbox);
6036                 compose->use_replyto = FALSE;
6037         }
6038 }
6039
6040 static void compose_toggle_followupto_cb(gpointer data, guint action,
6041                                          GtkWidget *widget)
6042 {
6043         Compose *compose = (Compose *)data;
6044
6045         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6046                 gtk_widget_show(compose->followup_hbox);
6047                 gtk_widget_show(compose->followup_entry);
6048                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 6, 4);
6049                 compose->use_followupto = TRUE;
6050         } else {
6051                 gtk_widget_hide(compose->followup_hbox);
6052                 gtk_widget_hide(compose->followup_entry);
6053                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 6, 0);
6054                 gtk_widget_queue_resize(compose->table_vbox);
6055                 compose->use_followupto = FALSE;
6056         }
6057 }
6058
6059 static void compose_toggle_attach_cb(gpointer data, guint action,
6060                                      GtkWidget *widget)
6061 {
6062         Compose *compose = (Compose *)data;
6063
6064         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6065                 gtk_widget_ref(compose->edit_vbox);
6066
6067                 gtkut_container_remove(GTK_CONTAINER(compose->vbox2),
6068                                        compose->edit_vbox);
6069                 gtk_paned_add2(GTK_PANED(compose->paned), compose->edit_vbox);
6070                 gtk_box_pack_start(GTK_BOX(compose->vbox2), compose->paned,
6071                                    TRUE, TRUE, 0);
6072                 gtk_widget_show(compose->paned);
6073
6074                 gtk_widget_unref(compose->edit_vbox);
6075                 gtk_widget_unref(compose->paned);
6076
6077                 compose->use_attach = TRUE;
6078         } else {
6079                 gtk_widget_ref(compose->paned);
6080                 gtk_widget_ref(compose->edit_vbox);
6081
6082                 gtkut_container_remove(GTK_CONTAINER(compose->vbox2),
6083                                        compose->paned);
6084                 gtkut_container_remove(GTK_CONTAINER(compose->paned),
6085                                        compose->edit_vbox);
6086                 gtk_box_pack_start(GTK_BOX(compose->vbox2),
6087                                    compose->edit_vbox, TRUE, TRUE, 0);
6088
6089                 gtk_widget_unref(compose->edit_vbox);
6090
6091                 compose->use_attach = FALSE;
6092         }
6093 }
6094 #endif
6095
6096 #if USE_GPGME
6097 static void compose_toggle_sign_cb(gpointer data, guint action,
6098                                    GtkWidget *widget)
6099 {
6100         Compose *compose = (Compose *)data;
6101
6102         if (GTK_CHECK_MENU_ITEM(widget)->active)
6103                 compose->use_signing = TRUE;
6104         else
6105                 compose->use_signing = FALSE;
6106 }
6107
6108 static void compose_toggle_encrypt_cb(gpointer data, guint action,
6109                                       GtkWidget *widget)
6110 {
6111         Compose *compose = (Compose *)data;
6112
6113         if (GTK_CHECK_MENU_ITEM(widget)->active)
6114                 compose->use_encryption = TRUE;
6115         else
6116                 compose->use_encryption = FALSE;
6117 }
6118 #endif /* USE_GPGME */
6119
6120 static void compose_toggle_ruler_cb(gpointer data, guint action,
6121                                     GtkWidget *widget)
6122 {
6123         Compose *compose = (Compose *)data;
6124
6125         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6126                 gtk_widget_show(compose->ruler_hbox);
6127                 prefs_common.show_ruler = TRUE;
6128         } else {
6129                 gtk_widget_hide(compose->ruler_hbox);
6130                 gtk_widget_queue_resize(compose->edit_vbox);
6131                 prefs_common.show_ruler = FALSE;
6132         }
6133 }
6134
6135 static void compose_attach_drag_received_cb (GtkWidget          *widget,
6136                                              GdkDragContext     *drag_context,
6137                                              gint                x,
6138                                              gint                y,
6139                                              GtkSelectionData   *data,
6140                                              guint               info,
6141                                              guint               time,
6142                                              gpointer            user_data)
6143 {
6144         Compose *compose = (Compose *)user_data;
6145         GList *list, *tmp;
6146
6147         list = uri_list_extract_filenames((const gchar *)data->data);
6148         for (tmp = list; tmp != NULL; tmp = tmp->next)
6149                 compose_attach_append(compose, (const gchar *)tmp->data,
6150                                       MIME_UNKNOWN);
6151         list_free_strings(list);
6152         g_list_free(list);
6153 }
6154
6155 static void compose_insert_drag_received_cb (GtkWidget          *widget,
6156                                              GdkDragContext     *drag_context,
6157                                              gint                x,
6158                                              gint                y,
6159                                              GtkSelectionData   *data,
6160                                              guint               info,
6161                                              guint               time,
6162                                              gpointer            user_data)
6163 {
6164         Compose *compose = (Compose *)user_data;
6165         GList *list, *tmp;
6166
6167         list = uri_list_extract_filenames((const gchar *)data->data);
6168         for (tmp = list; tmp != NULL; tmp = tmp->next)
6169                 compose_insert_file(compose, (const gchar *)tmp->data);
6170         list_free_strings(list);
6171         g_list_free(list);
6172 }
6173
6174 #if 0 /* NEW COMPOSE GUI */
6175 static void to_activated(GtkWidget *widget, Compose *compose)
6176 {
6177         if (GTK_WIDGET_VISIBLE(compose->newsgroups_entry))
6178                 gtk_widget_grab_focus(compose->newsgroups_entry);
6179         else
6180                 gtk_widget_grab_focus(compose->subject_entry);
6181 }
6182
6183 static void newsgroups_activated(GtkWidget *widget, Compose *compose)
6184 {
6185         gtk_widget_grab_focus(compose->subject_entry);
6186 }
6187
6188 static void subject_activated(GtkWidget *widget, Compose *compose)
6189 {
6190         if (GTK_WIDGET_VISIBLE(compose->cc_entry))
6191                 gtk_widget_grab_focus(compose->cc_entry);
6192         else if (GTK_WIDGET_VISIBLE(compose->bcc_entry))
6193                 gtk_widget_grab_focus(compose->bcc_entry);
6194         else if (GTK_WIDGET_VISIBLE(compose->reply_entry))
6195                 gtk_widget_grab_focus(compose->reply_entry);
6196         else if (GTK_WIDGET_VISIBLE(compose->followup_entry))
6197                 gtk_widget_grab_focus(compose->followup_entry);
6198         else
6199                 gtk_widget_grab_focus(compose->text);
6200 }
6201
6202 static void cc_activated(GtkWidget *widget, Compose *compose)
6203 {
6204         if (GTK_WIDGET_VISIBLE(compose->bcc_entry))
6205                 gtk_widget_grab_focus(compose->bcc_entry);
6206         else if (GTK_WIDGET_VISIBLE(compose->reply_entry))
6207                 gtk_widget_grab_focus(compose->reply_entry);
6208         else if (GTK_WIDGET_VISIBLE(compose->followup_entry))
6209                 gtk_widget_grab_focus(compose->followup_entry);
6210         else
6211                 gtk_widget_grab_focus(compose->text);
6212 }
6213
6214 static void bcc_activated(GtkWidget *widget, Compose *compose)
6215 {
6216         if (GTK_WIDGET_VISIBLE(compose->reply_entry))
6217                 gtk_widget_grab_focus(compose->reply_entry);
6218         else if (GTK_WIDGET_VISIBLE(compose->followup_entry))
6219                 gtk_widget_grab_focus(compose->followup_entry);
6220         else
6221                 gtk_widget_grab_focus(compose->text);
6222 }
6223
6224 static void replyto_activated(GtkWidget *widget, Compose *compose)
6225 {
6226         if (GTK_WIDGET_VISIBLE(compose->followup_entry))
6227                 gtk_widget_grab_focus(compose->followup_entry);
6228         else
6229                 gtk_widget_grab_focus(compose->text);
6230 }
6231
6232 static void followupto_activated(GtkWidget *widget, Compose *compose)
6233 {
6234         gtk_widget_grab_focus(compose->text);
6235 }
6236 #endif
6237
6238 static void compose_toggle_return_receipt_cb(gpointer data, guint action,
6239                                              GtkWidget *widget)
6240 {
6241         Compose *compose = (Compose *)data;
6242
6243         if (GTK_CHECK_MENU_ITEM(widget)->active)
6244                 compose->return_receipt = TRUE;
6245         else
6246                 compose->return_receipt = FALSE;
6247 }
6248
6249 void compose_headerentry_key_press_event_cb(GtkWidget *entry,
6250                                             GdkEventKey *event,
6251                                             ComposeHeaderEntry *headerentry)
6252 {
6253         if ((g_slist_length(headerentry->compose->header_list) > 0) &&
6254             ((headerentry->headernum + 1) != headerentry->compose->header_nextrow) &&
6255             !(event->state & GDK_MODIFIER_MASK) &&
6256             (event->keyval == GDK_BackSpace) &&
6257             (strlen(gtk_entry_get_text(GTK_ENTRY(entry))) == 0)) {
6258                 gtk_container_remove
6259                         (GTK_CONTAINER(headerentry->compose->header_table),
6260                          headerentry->combo);
6261                 gtk_container_remove
6262                         (GTK_CONTAINER(headerentry->compose->header_table),
6263                          headerentry->entry);
6264                 headerentry->compose->header_list =
6265                         g_slist_remove(headerentry->compose->header_list,
6266                                        headerentry);
6267                 g_free(headerentry);
6268         } else  if (event->keyval == GDK_Tab) {
6269                 if (headerentry->compose->header_last == headerentry) {
6270                         /* Override default next focus, and give it to subject_entry
6271                          * instead of notebook tabs
6272                          */
6273                         gtk_signal_emit_stop_by_name(GTK_OBJECT(entry), "key-press-event"); 
6274                         gtk_widget_grab_focus(headerentry->compose->subject_entry);
6275                 }
6276         }
6277
6278 }
6279
6280 void compose_headerentry_changed_cb(GtkWidget *entry,
6281                                     ComposeHeaderEntry *headerentry)
6282 {
6283         if (strlen(gtk_entry_get_text(GTK_ENTRY(entry))) != 0) {
6284                 headerentry->compose->header_list =
6285                         g_slist_append(headerentry->compose->header_list,
6286                                        headerentry);
6287                 compose_create_header_entry(headerentry->compose);
6288                 gtk_signal_disconnect_by_func
6289                         (GTK_OBJECT(entry),
6290                          GTK_SIGNAL_FUNC(compose_headerentry_changed_cb),
6291                          headerentry);
6292                 /* Automatically scroll down */
6293                 compose_show_first_last_header(headerentry->compose, FALSE);
6294                 
6295         }
6296 }
6297
6298 static void compose_show_first_last_header(Compose *compose, gboolean show_first)
6299 {
6300         GtkAdjustment *vadj;
6301
6302         g_return_if_fail(compose);
6303         g_return_if_fail(GTK_IS_WIDGET(compose->header_table));
6304         g_return_if_fail(GTK_IS_VIEWPORT(compose->header_table->parent));
6305
6306         vadj = gtk_viewport_get_vadjustment(GTK_VIEWPORT(compose->header_table->parent));
6307         gtk_adjustment_set_value(vadj, (show_first ? vadj->lower : vadj->upper));
6308 }
6309
6310 static void compose_ctl_enter_send_shortcut_cb(GtkWidget *w, Compose *compose)
6311 {
6312         GtkItemFactory *ifactory;
6313         GtkAccelEntry  *accel;
6314         GtkWidget      *send_button;
6315         GSList *list;
6316         GdkEvent *e= gtk_get_current_event();
6317         
6318         if (e->type != GDK_KEY_PRESS || 
6319             !( ((GdkEventKey *)e)->state & GDK_CONTROL_MASK) )
6320                 return;
6321
6322         ifactory = gtk_item_factory_from_widget(compose->menubar);
6323         send_button = gtk_item_factory_get_widget(ifactory, "/Message/Send");
6324         list = gtk_accel_group_entries_from_object(GTK_OBJECT(send_button));
6325         accel = (GtkAccelEntry *) list->data;
6326         if (accel->accelerator_key == GDK_Return && 
6327             accel->accelerator_mods == GDK_CONTROL_MASK)
6328                 compose_send_cb(compose, 0, NULL);
6329 }