c8ebea65e56a195e515bc36285496da2e43476c0
[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 "send.h"
81 #include "news.h"
82 #include "customheader.h"
83 #include "prefs_common.h"
84 #include "prefs_account.h"
85 #include "account.h"
86 #include "filesel.h"
87 #include "procheader.h"
88 #include "procmime.h"
89 #include "statusbar.h"
90 #include "about.h"
91 #include "base64.h"
92 #include "codeconv.h"
93 #include "utils.h"
94 #include "gtkutils.h"
95 #include "socket.h"
96 #include "alertpanel.h"
97 #include "manage_window.h"
98 #include "gtkshruler.h"
99 #include "folder.h"
100 #include "addr_compl.h"
101 #include "quote_fmt.h"
102 #include "template.h"
103 #include "undo.h"
104 #include "foldersel.h"
105
106 #if USE_GPGME
107 #  include "rfc2015.h"
108 #endif
109
110 typedef enum
111 {
112         COL_MIMETYPE = 0,
113         COL_SIZE     = 1,
114         COL_NAME     = 2
115 } AttachColumnPos;
116
117 #define N_ATTACH_COLS           3
118
119 #define B64_LINE_SIZE           57
120 #define B64_BUFFSIZE            77
121
122 #define MAX_REFERENCES_LEN      999
123
124 static GdkColor quote_color = {0, 0, 0, 0xbfff};
125
126 static GList *compose_list = NULL;
127
128 static void compose_set_undo                    (UndoMain       *undostruct, 
129                                                  gint            undo_state, 
130                                                  gint            redo_state, 
131                                                  GtkWidget      *changewidget);
132 Compose *compose_generic_new                    (PrefsAccount   *account,
133                                                  const gchar    *to,
134                                                  FolderItem     *item);
135
136 static Compose *compose_create                  (PrefsAccount   *account,
137                                                  ComposeMode     mode);
138 static void compose_toolbar_create              (Compose        *compose,
139                                                  GtkWidget      *container);
140 static GtkWidget *compose_account_option_menu_create
141                                                 (Compose        *compose);
142 static void compose_set_template_menu           (Compose        *compose);
143 static void compose_template_apply              (Compose        *compose,
144                                                  Template       *tmpl);
145 static void compose_destroy                     (Compose        *compose);
146
147 static void compose_entries_set                 (Compose        *compose,
148                                                  const gchar    *mailto);
149 static gint compose_parse_header                (Compose        *compose,
150                                                  MsgInfo        *msginfo);
151 static gchar *compose_parse_references          (const gchar    *ref,
152                                                  const gchar    *msgid);
153
154 static gchar *compose_quote_fmt                 (Compose        *compose,
155                                                  MsgInfo        *msginfo,
156                                                  const gchar    *fmt,
157                                                  const gchar    *qmark);
158
159 static void compose_reply_set_entry             (Compose        *compose,
160                                                  MsgInfo        *msginfo,
161                                                  gboolean        to_all,
162                                                  gboolean        to_sender,
163                                                  gboolean
164                                                  followup_and_reply_to);
165 static void compose_reedit_set_entry            (Compose        *compose,
166                                                  MsgInfo        *msginfo);
167 static void compose_insert_sig                  (Compose        *compose);
168 static void compose_insert_file                 (Compose        *compose,
169                                                  const gchar    *file);
170 static void compose_attach_append               (Compose        *compose,
171                                                  const gchar    *file,
172                                                  ContentType     cnttype);
173 static void compose_attach_append_with_type(Compose *compose,
174                                             const gchar *file,
175                                             const gchar *type,
176                                             ContentType cnttype);
177 static void compose_wrap_line                   (Compose        *compose);
178 static void compose_wrap_line_all               (Compose        *compose);
179 static void compose_set_title                   (Compose        *compose);
180
181 static PrefsAccount *compose_current_mail_account(void);
182 /* static gint compose_send                     (Compose        *compose); */
183 static gint compose_write_to_file               (Compose        *compose,
184                                                  const gchar    *file,
185                                                  gboolean        is_draft);
186 static gint compose_write_body_to_file          (Compose        *compose,
187                                                  const gchar    *file);
188 static gint compose_save_to_outbox              (Compose        *compose,
189                                                  const gchar    *file);
190 static gint compose_remove_reedit_target        (Compose        *compose);
191 static gint compose_queue                       (Compose        *compose,
192                                                  gint           *msgnum,
193                                                  FolderItem     **item);
194 static void compose_write_attach                (Compose        *compose,
195                                                  FILE           *fp);
196 static gint compose_write_headers               (Compose        *compose,
197                                                  FILE           *fp,
198                                                  const gchar    *charset,
199                                                  EncodingType    encoding,
200                                                  gboolean        is_draft);
201
202 static void compose_convert_header              (gchar          *dest,
203                                                  gint            len,
204                                                  gchar          *src,
205                                                  gint            header_len);
206 static void compose_generate_msgid              (Compose        *compose,
207                                                  gchar          *buf,
208                                                  gint            len);
209
210 static void compose_attach_info_free            (AttachInfo     *ainfo);
211 static void compose_attach_remove_selected      (Compose        *compose);
212
213 static void compose_attach_property             (Compose        *compose);
214 static void compose_attach_property_create      (gboolean       *cancelled);
215 static void attach_property_ok                  (GtkWidget      *widget,
216                                                  gboolean       *cancelled);
217 static void attach_property_cancel              (GtkWidget      *widget,
218                                                  gboolean       *cancelled);
219 static gint attach_property_delete_event        (GtkWidget      *widget,
220                                                  GdkEventAny    *event,
221                                                  gboolean       *cancelled);
222 static void attach_property_key_pressed         (GtkWidget      *widget,
223                                                  GdkEventKey    *event,
224                                                  gboolean       *cancelled);
225
226 static void compose_exec_ext_editor             (Compose           *compose);
227 static gint compose_exec_ext_editor_real        (const gchar       *file);
228 static gboolean compose_ext_editor_kill         (Compose           *compose);
229 static void compose_input_cb                    (gpointer           data,
230                                                  gint               source,
231                                                  GdkInputCondition  condition);
232 static void compose_set_ext_editor_sensitive    (Compose           *compose,
233                                                  gboolean           sensitive);
234
235 static gint calc_cursor_xpos    (GtkSText       *text,
236                                  gint            extra,
237                                  gint            char_width);
238
239 static void compose_create_header_entry (Compose *compose);
240 static void compose_add_header_entry    (Compose *compose, gchar *header, gchar *text);
241
242 /* callback functions */
243
244 static gboolean compose_edit_size_alloc (GtkEditable    *widget,
245                                          GtkAllocation  *allocation,
246                                          GtkSHRuler     *shruler);
247
248 static void toolbar_send_cb             (GtkWidget      *widget,
249                                          gpointer        data);
250 static void toolbar_send_later_cb       (GtkWidget      *widget,
251                                          gpointer        data);
252 static void toolbar_draft_cb            (GtkWidget      *widget,
253                                          gpointer        data);
254 static void toolbar_insert_cb           (GtkWidget      *widget,
255                                          gpointer        data);
256 static void toolbar_attach_cb           (GtkWidget      *widget,
257                                          gpointer        data);
258 static void toolbar_sig_cb              (GtkWidget      *widget,
259                                          gpointer        data);
260 static void toolbar_ext_editor_cb       (GtkWidget      *widget,
261                                          gpointer        data);
262 static void toolbar_linewrap_cb         (GtkWidget      *widget,
263                                          gpointer        data);
264 static void toolbar_address_cb          (GtkWidget      *widget,
265                                          gpointer        data);
266
267 static void select_account              (Compose        *compose,
268                                          PrefsAccount   *ac);
269
270 static void account_activated           (GtkMenuItem    *menuitem,
271                                          gpointer        data);
272
273 static void attach_selected             (GtkCList       *clist,
274                                          gint            row,
275                                          gint            column,
276                                          GdkEvent       *event,
277                                          gpointer        data);
278 static void attach_button_pressed       (GtkWidget      *widget,
279                                          GdkEventButton *event,
280                                          gpointer        data);
281 static void attach_key_pressed          (GtkWidget      *widget,
282                                          GdkEventKey    *event,
283                                          gpointer        data);
284
285 static void compose_send_cb             (gpointer        data,
286                                          guint           action,
287                                          GtkWidget      *widget);
288 static void compose_send_later_cb       (gpointer        data,
289                                          guint           action,
290                                          GtkWidget      *widget);
291
292 static void compose_draft_cb            (gpointer        data,
293                                          guint           action,
294                                          GtkWidget      *widget);
295
296 static void compose_attach_cb           (gpointer        data,
297                                          guint           action,
298                                          GtkWidget      *widget);
299 static void compose_insert_file_cb      (gpointer        data,
300                                          guint           action,
301                                          GtkWidget      *widget);
302
303 static void compose_close_cb            (gpointer        data,
304                                          guint           action,
305                                          GtkWidget      *widget);
306
307 static void compose_address_cb          (gpointer        data,
308                                          guint           action,
309                                          GtkWidget      *widget);
310 static void compose_template_activate_cb(GtkWidget      *widget,
311                                          gpointer        data);
312
313 static void compose_ext_editor_cb       (gpointer        data,
314                                          guint           action,
315                                          GtkWidget      *widget);
316
317 static gint compose_delete_cb           (GtkWidget      *widget,
318                                          GdkEventAny    *event,
319                                          gpointer        data);
320 static void compose_destroy_cb          (GtkWidget      *widget,
321                                          Compose        *compose);
322
323 static void compose_undo_cb             (Compose *compose);
324 static void compose_redo_cb             (Compose *compose);
325 static void compose_cut_cb              (Compose        *compose);
326 static void compose_copy_cb             (Compose        *compose);
327 static void compose_paste_cb            (Compose        *compose);
328 static void compose_allsel_cb           (Compose        *compose);
329
330 static void compose_grab_focus_cb       (GtkWidget      *widget,
331                                          Compose        *compose);
332
333 static void compose_changed_cb          (GtkEditable    *editable,
334                                          Compose        *compose);
335 static void compose_button_press_cb     (GtkWidget      *widget,
336                                          GdkEventButton *event,
337                                          Compose        *compose);
338 #if 0
339 static void compose_key_press_cb        (GtkWidget      *widget,
340                                          GdkEventKey    *event,
341                                          Compose        *compose);
342 #endif
343
344 #if 0
345 static void compose_toggle_to_cb        (gpointer        data,
346                                          guint           action,
347                                          GtkWidget      *widget);
348 static void compose_toggle_cc_cb        (gpointer        data,
349                                          guint           action,
350                                          GtkWidget      *widget);
351 static void compose_toggle_bcc_cb       (gpointer        data,
352                                          guint           action,
353                                          GtkWidget      *widget);
354 static void compose_toggle_replyto_cb   (gpointer        data,
355                                          guint           action,
356                                          GtkWidget      *widget);
357 static void compose_toggle_followupto_cb(gpointer        data,
358                                          guint           action,
359                                          GtkWidget      *widget);
360 static void compose_toggle_attach_cb    (gpointer        data,
361                                          guint           action,
362                                          GtkWidget      *widget);
363 #endif
364 static void compose_toggle_ruler_cb     (gpointer        data,
365                                          guint           action,
366                                          GtkWidget      *widget);
367 #if USE_GPGME
368 static void compose_toggle_sign_cb      (gpointer        data,
369                                          guint           action,
370                                          GtkWidget      *widget);
371 static void compose_toggle_encrypt_cb   (gpointer        data,
372                                          guint           action,
373                                          GtkWidget      *widget);
374 #endif
375 static void compose_toggle_return_receipt_cb(gpointer data, guint action,
376                                              GtkWidget *widget);
377
378 static void compose_attach_drag_received_cb (GtkWidget          *widget,
379                                              GdkDragContext     *drag_context,
380                                              gint                x,
381                                              gint                y,
382                                              GtkSelectionData   *data,
383                                              guint               info,
384                                              guint               time,
385                                              gpointer            user_data);
386 static void compose_insert_drag_received_cb (GtkWidget          *widget,
387                                              GdkDragContext     *drag_context,
388                                              gint                x,
389                                              gint                y,
390                                              GtkSelectionData   *data,
391                                              guint               info,
392                                              guint               time,
393                                              gpointer            user_data);
394
395 #if 0
396 static void to_activated                (GtkWidget      *widget,
397                                          Compose        *compose);
398 static void newsgroups_activated        (GtkWidget      *widget,
399                                          Compose        *compose);
400 static void subject_activated           (GtkWidget      *widget,
401                                          Compose        *compose);
402 static void cc_activated                (GtkWidget      *widget,
403                                          Compose        *compose);
404 static void bcc_activated               (GtkWidget      *widget,
405                                          Compose        *compose);
406 static void replyto_activated           (GtkWidget      *widget,
407                                          Compose        *compose);
408 static void followupto_activated        (GtkWidget      *widget,
409                                          Compose        *compose);
410 #endif
411
412 static void compose_attach_parts        (Compose        *compose,
413                                          MsgInfo        *msginfo);
414
415 static void compose_generic_reply(MsgInfo *msginfo, gboolean quote,
416                                   gboolean to_all,
417                                   gboolean ignore_replyto,
418                                   gboolean followup_and_reply_to);
419
420 void compose_headerentry_changed_cb        (GtkWidget          *entry,
421                                             ComposeHeaderEntry *headerentry);
422 void compose_headerentry_key_press_event_cb(GtkWidget          *entry,
423                                             GdkEventKey        *event,
424                                             ComposeHeaderEntry *headerentry);
425
426 static GtkItemFactoryEntry compose_popup_entries[] =
427 {
428         {N_("/_Add..."),        NULL, compose_attach_cb, 0, NULL},
429         {N_("/_Remove"),        NULL, compose_attach_remove_selected, 0, NULL},
430         {N_("/---"),            NULL, NULL, 0, "<Separator>"},
431         {N_("/_Property..."),   NULL, compose_attach_property, 0, NULL}
432 };
433
434 static GtkItemFactoryEntry compose_entries[] =
435 {
436         {N_("/_File"),                          NULL, NULL, 0, "<Branch>"},
437         {N_("/_File/_Attach file"),             "<control>M", compose_attach_cb,      0, NULL},
438         {N_("/_File/_Insert file"),             "<control>I", compose_insert_file_cb, 0, NULL},
439         {N_("/_File/Insert si_gnature"),        "<control>G", compose_insert_sig,     0, NULL},
440         {N_("/_File/---"),                      NULL, NULL, 0, "<Separator>"},
441         {N_("/_File/_Close"),                   "<alt>W", compose_close_cb, 0, NULL},
442
443         {N_("/_Edit"),             NULL, NULL, 0, "<Branch>"},
444         {N_("/_Edit/_Undo"),       "<control>Z", compose_undo_cb, 0, NULL},
445         {N_("/_Edit/_Redo"),       "<control>Y", compose_redo_cb, 0, NULL},
446         {N_("/_Edit/---"),         NULL, NULL, 0, "<Separator>"},
447         {N_("/_Edit/Cu_t"),        "<control>X", compose_cut_cb,    0, NULL},
448         {N_("/_Edit/_Copy"),       "<control>C", compose_copy_cb,   0, NULL},
449         {N_("/_Edit/_Paste"),      "<control>V", compose_paste_cb,  0, NULL},
450         {N_("/_Edit/Select _all"), "<control>A", compose_allsel_cb, 0, NULL},
451         {N_("/_Edit/---"),         NULL, NULL, 0, "<Separator>"},
452         {N_("/_Edit/_Wrap current paragraph"), "<alt>L", compose_wrap_line, 0, NULL},
453         {N_("/_Edit/Wrap all long _lines"),
454                         "<shift><alt>L", compose_wrap_line_all, 0, NULL},
455         {N_("/_Edit/Edit with e_xternal editor"),
456                         "<alt>X", compose_ext_editor_cb, 0, NULL},
457
458         {N_("/_Message"),               NULL, NULL, 0, "<Branch>"},
459         {N_("/_Message/_Send"),         "<control>Return",
460                                         compose_send_cb, 0, NULL},
461         {N_("/_Message/Send _later"),   "<shift><alt>S",
462                                         compose_send_later_cb,  0, NULL},
463         {N_("/_Message/Save to _draft folder"),
464                                         "<alt>D", compose_draft_cb, 0, NULL},
465 #if 0 /* NEW COMPOSE GUI */
466         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
467         {N_("/_Message/_To"),           NULL, compose_toggle_to_cb     , 0, "<ToggleItem>"},
468         {N_("/_Message/_Cc"),           NULL, compose_toggle_cc_cb     , 0, "<ToggleItem>"},
469         {N_("/_Message/_Bcc"),          NULL, compose_toggle_bcc_cb    , 0, "<ToggleItem>"},
470         {N_("/_Message/_Reply to"),     NULL, compose_toggle_replyto_cb, 0, "<ToggleItem>"},
471         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
472         {N_("/_Message/_Followup to"),  NULL, compose_toggle_followupto_cb, 0, "<ToggleItem>"},
473         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
474         {N_("/_Message/_Attach"),       NULL, compose_toggle_attach_cb, 0, "<ToggleItem>"},
475 #endif
476 #if USE_GPGME
477         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
478         {N_("/_Message/Si_gn"),         NULL, compose_toggle_sign_cb   , 0, "<ToggleItem>"},
479         {N_("/_Message/_Encrypt"),      NULL, compose_toggle_encrypt_cb, 0, "<ToggleItem>"},
480 #endif /* USE_GPGME */
481         {N_("/_Message/---"),           NULL,           NULL,   0, "<Separator>"},
482         {N_("/_Message/_Request Return Receipt"),       NULL, compose_toggle_return_receipt_cb, 0, "<ToggleItem>"},
483         {N_("/_Tool"),                  NULL, NULL, 0, "<Branch>"},
484         {N_("/_Tool/Show _ruler"),      NULL, compose_toggle_ruler_cb, 0, "<ToggleItem>"},
485         {N_("/_Tool/_Address book"),    "<alt>A", compose_address_cb , 0, NULL},
486         {N_("/_Tool/_Template"),        NULL, NULL, 0, "<Branch>"},
487         {N_("/_Help"),                  NULL, NULL, 0, "<LastBranch>"},
488         {N_("/_Help/_About"),           NULL, about_show, 0, NULL}
489 };
490
491 static GtkTargetEntry compose_mime_types[] =
492 {
493         {"text/uri-list", 0, 0}
494 };
495
496 Compose *compose_new(PrefsAccount *account)
497 {
498         return compose_generic_new(account, NULL, NULL);
499 }
500
501 Compose *compose_bounce(PrefsAccount *account, MsgInfo *msginfo)
502 {
503         Compose *c;
504         gchar *filename;
505         GtkItemFactory *ifactory;
506         
507         c = compose_generic_new(account, NULL, NULL);
508
509         filename = procmsg_get_message_file(msginfo);
510         if (filename == NULL)
511                 return NULL;
512
513         c->bounce_filename = filename;
514
515         if (msginfo->subject)
516                 gtk_entry_set_text(GTK_ENTRY(c->subject_entry),
517                                    msginfo->subject);
518         gtk_editable_set_editable(GTK_EDITABLE(c->subject_entry), FALSE);
519
520         compose_quote_fmt(c, msginfo, "%M", NULL);
521         gtk_editable_set_editable(GTK_EDITABLE(c->text), FALSE);
522
523         ifactory = gtk_item_factory_from_widget(c->popupmenu);
524         menu_set_sensitive(ifactory, "/Add...", FALSE);
525         menu_set_sensitive(ifactory, "/Remove", FALSE);
526         menu_set_sensitive(ifactory, "/Property...", FALSE);
527
528         ifactory = gtk_item_factory_from_widget(c->menubar);
529         menu_set_sensitive(ifactory, "/File/Insert file", FALSE);
530         menu_set_sensitive(ifactory, "/File/Attach file", FALSE);
531         menu_set_sensitive(ifactory, "/File/Insert signature", FALSE);
532         menu_set_sensitive(ifactory, "/Edit/Paste", FALSE);
533         menu_set_sensitive(ifactory, "/Edit/Wrap current paragraph", FALSE);
534         menu_set_sensitive(ifactory, "/Edit/Wrap all long lines", FALSE);
535         menu_set_sensitive(ifactory, "/Edit/Edit with external editor", FALSE);
536         menu_set_sensitive(ifactory, "/Message/Attach", FALSE);
537 #if USE_GPGME
538         menu_set_sensitive(ifactory, "/Message/Sign", FALSE);
539         menu_set_sensitive(ifactory, "/Message/Encrypt", FALSE);
540 #endif
541         menu_set_sensitive(ifactory, "/Message/Request Return Receipt", FALSE);
542         menu_set_sensitive(ifactory, "/Tool/Template", FALSE);
543         
544         gtk_widget_set_sensitive(c->insert_btn, FALSE);
545         gtk_widget_set_sensitive(c->attach_btn, FALSE);
546         gtk_widget_set_sensitive(c->sig_btn, FALSE);
547         gtk_widget_set_sensitive(c->exteditor_btn, FALSE);
548         gtk_widget_set_sensitive(c->linewrap_btn, FALSE);
549
550         return c;
551 }
552
553 Compose *compose_new_with_recipient(PrefsAccount *account, const gchar *mailto)
554 {
555         return compose_generic_new(account, mailto, NULL);
556 }
557
558 Compose *compose_new_with_folderitem(PrefsAccount *account, FolderItem *item)
559 {
560         return compose_generic_new(account, NULL, item);
561 }
562
563 Compose *compose_generic_new(PrefsAccount *account, const gchar *mailto, FolderItem *item)
564 {
565         Compose *compose;
566
567         if (item && item->prefs && item->prefs->enable_default_account)
568                 account = account_find_from_id(item->prefs->default_account);
569
570         if (!account) account = cur_account;
571         g_return_val_if_fail(account != NULL, NULL);
572
573         compose = compose_create(account, COMPOSE_NEW);
574         compose->replyinfo = NULL;
575
576         if (prefs_common.auto_sig)
577                 compose_insert_sig(compose);
578         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
579         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
580
581         if (account->protocol != A_NNTP) {
582                 if (mailto) {
583                         compose_entries_set(compose, mailto);
584
585                 } else if(item && item->prefs->enable_default_to) {
586                         compose_entry_append(compose, item->prefs->default_to, COMPOSE_TO);
587                 }
588                 if (item && item->ret_rcpt) {
589                         GtkItemFactory *ifactory;
590                 
591                         ifactory = gtk_item_factory_from_widget(compose->menubar);
592                         menu_set_toggle(ifactory, "/Message/Request Return Receipt", TRUE);
593                 }
594         } else {
595                 if (mailto) {
596                         compose_entry_append(compose, mailto, COMPOSE_NEWSGROUPS);
597                 }
598         }
599         gtk_widget_grab_focus(compose->subject_entry);
600
601         if (prefs_common.auto_exteditor)
602                 compose_exec_ext_editor(compose);
603
604         return compose;
605 }
606
607 #define CHANGE_FLAGS(msginfo) \
608 { \
609 if (msginfo->folder->folder->change_flags != NULL) \
610 msginfo->folder->folder->change_flags(msginfo->folder->folder, \
611                                       msginfo->folder, \
612                                       msginfo); \
613 }
614
615 /*
616 Compose *compose_new_followup_and_replyto(PrefsAccount *account,
617                                            const gchar *followupto, gchar * to)
618 {
619         Compose *compose;
620
621         if (!account) account = cur_account;
622         g_return_val_if_fail(account != NULL, NULL);
623         g_return_val_if_fail(account->protocol != A_NNTP, NULL);
624
625         compose = compose_create(account, COMPOSE_NEW);
626
627         if (prefs_common.auto_sig)
628                 compose_insert_sig(compose);
629         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
630         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
631
632         compose_entry_append(compose, to, COMPOSE_TO);
633         compose_entry_append(compose, followupto, COMPOSE_NEWSGROUPS);
634         gtk_widget_grab_focus(compose->subject_entry);
635
636         return compose;
637 }
638 */
639
640 void compose_reply(MsgInfo *msginfo, gboolean quote, gboolean to_all,
641                    gboolean ignore_replyto)
642 {
643         compose_generic_reply(msginfo, quote, to_all, ignore_replyto, FALSE);
644 }
645
646 void compose_followup_and_reply_to(MsgInfo *msginfo, gboolean quote,
647                                    gboolean to_all,
648                                    gboolean ignore_replyto)
649 {
650         compose_generic_reply(msginfo, quote, to_all, ignore_replyto, TRUE);
651 }
652
653 static void compose_generic_reply(MsgInfo *msginfo, gboolean quote,
654                                   gboolean to_all,
655                                   gboolean ignore_replyto,
656                                   gboolean followup_and_reply_to)
657 {
658         Compose *compose;
659         PrefsAccount *account;
660         PrefsAccount *reply_account;
661         GtkSText *text;
662
663         g_return_if_fail(msginfo != NULL);
664         g_return_if_fail(msginfo->folder != NULL);
665
666         account = NULL;
667         /* select the account set in folderitem's property (if enabled) */
668         if (msginfo->folder->prefs && msginfo->folder->prefs->enable_default_account)
669                 account = account_find_from_id(msginfo->folder->prefs->default_account);
670         
671         /* select the account for the whole folder (IMAP / NNTP) */
672         if (!account)
673                 account = msginfo->folder->folder->account;
674
675         /* select account by to: and cc: header if enabled */
676         if (prefs_common.reply_account_autosel) {
677                 if (!account && msginfo->to) {
678                         gchar *to;
679                         Xstrdup_a(to, msginfo->to, return);
680                         extract_address(to);
681                         account = account_find_from_address(to);
682                 }
683                 if (!account) {
684                         gchar cc[BUFFSIZE];
685                         if(!get_header_from_msginfo(msginfo, cc, sizeof(cc), "CC:")) { /* Found a CC header */
686                                 extract_address(cc);
687                                 account = account_find_from_address(cc);
688                         }        
689                 }
690         }
691
692         /* select current account */
693         if (!account) account = cur_account;
694         g_return_if_fail(account != NULL);
695
696         if (ignore_replyto && account->protocol == A_NNTP &&
697             !followup_and_reply_to) {
698                 reply_account =
699                         account_find_from_address(account->address);
700                 if (!reply_account)
701                         reply_account = compose_current_mail_account();
702                 if (!reply_account)
703                         return;
704         } else
705                 reply_account = account;
706
707         MSG_UNSET_PERM_FLAGS(msginfo->flags, MSG_FORWARDED);
708         MSG_SET_PERM_FLAGS(msginfo->flags, MSG_REPLIED);
709         imap_do_reply(msginfo);
710
711         CHANGE_FLAGS(msginfo);
712
713         compose = compose_create(account, COMPOSE_REPLY);
714         compose->replyinfo = procmsg_msginfo_copy(msginfo);
715
716 #if 0 /* NEW COMPOSE GUI */
717         if (followup_and_reply_to) {
718                 gtk_widget_show(compose->to_hbox);
719                 gtk_widget_show(compose->to_entry);
720                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 1, 4);
721                 compose->use_to = TRUE;
722         }
723 #endif
724         if (msginfo->folder && msginfo->folder->ret_rcpt) {
725                 GtkItemFactory *ifactory;
726         
727                 ifactory = gtk_item_factory_from_widget(compose->menubar);
728                 menu_set_toggle(ifactory, "/Message/Request Return Receipt", TRUE);
729         }
730
731         if (compose_parse_header(compose, msginfo) < 0) return;
732         compose_reply_set_entry(compose, msginfo, to_all, ignore_replyto,
733                                 followup_and_reply_to);
734
735         text = GTK_STEXT(compose->text);
736         gtk_stext_freeze(text);
737
738         if (quote) {
739                 gchar *qmark;
740                 gchar *quote_str;
741
742                 if (prefs_common.quotemark && *prefs_common.quotemark)
743                         qmark = prefs_common.quotemark;
744                 else
745                         qmark = "> ";
746
747                 quote_str = compose_quote_fmt(compose, msginfo,
748                                               prefs_common.quotefmt,
749                                               qmark);
750         }
751
752         if (prefs_common.auto_sig)
753                 compose_insert_sig(compose);
754
755         if (quote && prefs_common.linewrap_quote)
756                 compose_wrap_line_all(compose);
757
758         gtk_editable_set_position(GTK_EDITABLE(text), 0);
759         gtk_stext_set_point(text, 0);
760
761         gtk_stext_thaw(text);
762         gtk_widget_grab_focus(compose->text);
763
764         if (prefs_common.auto_exteditor)
765                 compose_exec_ext_editor(compose);
766 }
767
768
769 static gchar *procmime_get_file_name(MimeInfo *mimeinfo)
770 {
771         gchar *base;
772         gchar *filename;
773
774         g_return_val_if_fail(mimeinfo != NULL, NULL);
775
776         base = mimeinfo->filename ? mimeinfo->filename
777                 : mimeinfo->name ? mimeinfo->name : NULL;
778
779         if (MIME_TEXT_HTML == mimeinfo->mime_type && base == NULL){
780                 filename = g_strdup_printf("%s%smimetmp.%08x.html",
781                                            get_mime_tmp_dir(),
782                                            G_DIR_SEPARATOR_S,
783                                            (gint)mimeinfo);
784                 return filename;
785         }
786         else {
787                 base = base ? base : "";
788                 base = g_basename(base);
789                 if (*base == '\0') {
790                         filename = g_strdup_printf("%s%smimetmp.%08x",
791                                                    get_mime_tmp_dir(),
792                                                    G_DIR_SEPARATOR_S,
793                                                    (gint)mimeinfo);
794                         return filename;
795                 }
796         }
797
798         filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
799                                base, NULL);
800
801         return filename;
802 }
803
804 static gchar *mime_extract_file(gchar *source, MimeInfo *partinfo)
805 {
806         gchar *filename;
807
808         if (!partinfo) return NULL;
809
810         filename = procmime_get_file_name(partinfo);
811
812         if (procmime_get_part(filename, source, partinfo) < 0)
813                 alertpanel_error
814                         (_("Can't get the part of multipart message."));
815
816         return filename;
817 }
818
819 static void compose_attach_parts(Compose *compose, MsgInfo *msginfo)
820 {
821         FILE *fp;
822         gchar *file;
823         MimeInfo *mimeinfo;
824         MsgInfo *tmpmsginfo;
825         gchar *p;
826         gchar *boundary;
827         gint boundary_len = 0;
828         gchar buf[BUFFSIZE];
829         glong fpos, prev_fpos;
830         gint npart;
831         gchar *source;
832         gchar *filename;
833
834         g_return_if_fail(msginfo != NULL);
835         
836 #if USE_GPGME
837         for (;;) {
838                 if ((fp = procmsg_open_message(msginfo)) == NULL) return;
839                 mimeinfo = procmime_scan_mime_header(fp);
840                 if (!mimeinfo) break;
841
842                 if (!MSG_IS_ENCRYPTED(msginfo->flags) &&
843                     rfc2015_is_encrypted(mimeinfo)) {
844                         MSG_SET_TMP_FLAGS(msginfo->flags, MSG_ENCRYPTED);
845                 }
846                 if (MSG_IS_ENCRYPTED(msginfo->flags) &&
847                     !msginfo->plaintext_file  &&
848                     !msginfo->decryption_failed) {
849                         rfc2015_decrypt_message(msginfo, mimeinfo, fp);
850                         if (msginfo->plaintext_file &&
851                             !msginfo->decryption_failed) {
852                                 fclose(fp);
853                                 continue;
854                         }
855                 }
856                 
857                 break;
858         }
859 #else /* !USE_GPGME */
860         if ((fp = procmsg_open_message(msginfo)) == NULL) return;
861         mimeinfo = procmime_scan_mime_header(fp);
862 #endif /* USE_GPGME */
863
864         fclose(fp);
865         if (!mimeinfo) return;
866         if (mimeinfo->mime_type == MIME_TEXT)
867                 return;
868
869         if ((fp = procmsg_open_message(msginfo)) == NULL) return;
870
871         g_return_if_fail(mimeinfo != NULL);
872         g_return_if_fail(mimeinfo->mime_type != MIME_TEXT);
873
874         if (mimeinfo->mime_type == MIME_MULTIPART) {
875                 g_return_if_fail(mimeinfo->boundary != NULL);
876                 g_return_if_fail(mimeinfo->sub == NULL);
877         }
878         g_return_if_fail(fp != NULL);
879
880         boundary = mimeinfo->boundary;
881
882         if (boundary) {
883                 boundary_len = strlen(boundary);
884
885                 /* look for first boundary */
886                 while ((p = fgets(buf, sizeof(buf), fp)) != NULL)
887                         if (IS_BOUNDARY(buf, boundary, boundary_len)) break;
888                 if (!p) {
889                         fclose(fp);
890                         return;
891                 }
892         }
893
894         if ((fpos = ftell(fp)) < 0) {
895                 perror("ftell");
896                 fclose(fp);
897                 return;
898         }
899
900         for (npart = 0;; npart++) {
901                 MimeInfo *partinfo;
902                 gboolean eom = FALSE;
903
904                 prev_fpos = fpos;
905
906                 partinfo = procmime_scan_mime_header(fp);
907                 if (!partinfo) break;
908
909                 if (npart != 0)
910                         procmime_mimeinfo_insert(mimeinfo, partinfo);
911                 else
912                         procmime_mimeinfo_free(partinfo);
913
914                 /* look for next boundary */
915                 buf[0] = '\0';
916                 while ((p = fgets(buf, sizeof(buf), fp)) != NULL) {
917                         if (IS_BOUNDARY(buf, boundary, boundary_len)) {
918                                 if (buf[2 + boundary_len]     == '-' &&
919                                     buf[2 + boundary_len + 1] == '-')
920                                         eom = TRUE;
921                                 break;
922                         }
923                 }
924                 if (p == NULL)
925                         eom = TRUE;     /* broken MIME message */
926                 fpos = ftell(fp);
927
928                 partinfo->size = fpos - prev_fpos - strlen(buf);
929
930                 if (eom) break;
931         }
932
933         source = procmsg_get_message_file_path(msginfo);
934
935         g_return_if_fail(mimeinfo != NULL);
936
937         if (!mimeinfo->main && mimeinfo->parent)
938                 {
939                         filename = mime_extract_file(source, mimeinfo);
940
941                         compose_attach_append_with_type(compose, filename,
942                                                         mimeinfo->content_type,
943                                                         mimeinfo->mime_type);
944
945                         g_free(filename);
946                 }
947
948         if (mimeinfo->sub && mimeinfo->sub->children)
949                 {
950                         filename = mime_extract_file(source, mimeinfo->sub);
951
952                         compose_attach_append_with_type(compose, filename,
953                                                         mimeinfo->content_type,
954                                                         mimeinfo->sub->mime_type);
955
956                         g_free(filename);
957                 }
958
959         if (mimeinfo->children) {
960                 MimeInfo *child;
961
962                 child = mimeinfo->children;
963                 while (child) {
964                         filename = mime_extract_file(source, child);
965
966                         compose_attach_append_with_type(compose, filename,
967                                                         child->content_type,
968                                                         child->mime_type);
969
970                         g_free(filename);
971
972                         child = child->next;
973                 }
974         }
975
976         fclose(fp);
977
978         procmime_mimeinfo_free_all(mimeinfo);
979 }
980
981
982 #define INSERT_FW_HEADER(var, hdr) \
983 if (msginfo->var && *msginfo->var) { \
984         gtk_stext_insert(text, NULL, NULL, NULL, hdr, -1); \
985         gtk_stext_insert(text, NULL, NULL, NULL, msginfo->var, -1); \
986         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1); \
987 }
988
989 Compose *compose_forward(PrefsAccount *account, MsgInfo *msginfo,
990                          gboolean as_attach)
991 {
992         Compose *compose;
993         /*      PrefsAccount *account; */
994         GtkSText *text;
995
996         g_return_val_if_fail(msginfo != NULL, NULL);
997         g_return_val_if_fail(msginfo->folder != NULL, NULL);
998
999         account = msginfo->folder->folder->account;
1000         if (!account && msginfo->to && prefs_common.forward_account_autosel) {
1001                 gchar *to;
1002                 Xstrdup_a(to, msginfo->to, return NULL);
1003                 extract_address(to);
1004                 account = account_find_from_address(to);
1005         }
1006
1007         if(!account && prefs_common.forward_account_autosel) {
1008                 gchar cc[BUFFSIZE];
1009                 if(!get_header_from_msginfo(msginfo,cc,sizeof(cc),"CC:")){ /* Found a CC header */
1010                         extract_address(cc);
1011                         account = account_find_from_address(cc);
1012                 }
1013         }
1014
1015         if (account == NULL) {
1016                 account = cur_account;
1017                 /*
1018                 account = msginfo->folder->folder->account;
1019                 if (!account) account = cur_account;
1020                 */
1021         }
1022         g_return_val_if_fail(account != NULL, NULL);
1023
1024         MSG_UNSET_PERM_FLAGS(msginfo->flags, MSG_REPLIED);
1025         MSG_SET_PERM_FLAGS(msginfo->flags, MSG_FORWARDED);
1026         CHANGE_FLAGS(msginfo);
1027
1028         compose = compose_create(account, COMPOSE_FORWARD);
1029
1030         if (msginfo->subject && *msginfo->subject) {
1031                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), "Fw: ");
1032                 gtk_entry_append_text(GTK_ENTRY(compose->subject_entry),
1033                                       msginfo->subject);
1034         }
1035
1036         text = GTK_STEXT(compose->text);
1037         gtk_stext_freeze(text);
1038
1039         if (as_attach) {
1040                 gchar *msgfile;
1041
1042                 msgfile = procmsg_get_message_file_path(msginfo);
1043                 if (!is_file_exist(msgfile))
1044                         g_warning(_("%s: file not exist\n"), msgfile);
1045                 else
1046                         compose_attach_append(compose, msgfile,
1047                                               MIME_MESSAGE_RFC822);
1048
1049                 g_free(msgfile);
1050         } else {
1051                 gchar *qmark;
1052                 gchar *quote_str;
1053
1054                 if (prefs_common.fw_quotemark && *prefs_common.fw_quotemark)
1055                         qmark = prefs_common.fw_quotemark;
1056                 else
1057                         qmark = "> ";
1058
1059                 quote_str = compose_quote_fmt(compose, msginfo,
1060                                               prefs_common.fw_quotefmt, qmark);
1061                 compose_attach_parts(compose, msginfo);
1062         }
1063
1064         if (prefs_common.auto_sig)
1065                 compose_insert_sig(compose);
1066
1067         if (prefs_common.linewrap_quote)
1068                 compose_wrap_line_all(compose);
1069
1070         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
1071         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
1072
1073         gtk_stext_thaw(text);
1074 #if 0 /* NEW COMPOSE GUI */
1075         if (account->protocol != A_NNTP)
1076                 gtk_widget_grab_focus(compose->to_entry);
1077         else
1078                 gtk_widget_grab_focus(compose->newsgroups_entry);
1079 #endif
1080         gtk_widget_grab_focus(compose->header_last->entry);
1081
1082         if (prefs_common.auto_exteditor)
1083                 compose_exec_ext_editor(compose);
1084
1085         return compose;
1086 }
1087
1088 #undef INSERT_FW_HEADER
1089
1090 Compose *compose_forward_multiple(PrefsAccount *account, GSList *msginfo_list)
1091 {
1092         Compose *compose;
1093         GtkSText *text;
1094         GSList *msginfo;
1095         gchar *msgfile;
1096
1097         g_return_val_if_fail(msginfo_list != NULL, NULL);
1098         
1099         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1100                 if ( ((MsgInfo *)msginfo->data)->folder == NULL )
1101                         return NULL;
1102         }
1103
1104         if (account == NULL) {
1105                 account = cur_account;
1106                 /*
1107                 account = msginfo->folder->folder->account;
1108                 if (!account) account = cur_account;
1109                 */
1110         }
1111         g_return_val_if_fail(account != NULL, NULL);
1112
1113         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1114                 MSG_UNSET_PERM_FLAGS(((MsgInfo *)msginfo->data)->flags, MSG_REPLIED);
1115                 MSG_SET_PERM_FLAGS(((MsgInfo *)msginfo->data)->flags, MSG_FORWARDED);
1116                 CHANGE_FLAGS(((MsgInfo *)msginfo->data));
1117         }
1118
1119         compose = compose_create(account, COMPOSE_FORWARD);
1120
1121         text = GTK_STEXT(compose->text);
1122         gtk_stext_freeze(text);
1123
1124         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1125                 msgfile = procmsg_get_message_file_path((MsgInfo *)msginfo->data);
1126                 if (!is_file_exist(msgfile))
1127                         g_warning(_("%s: file not exist\n"), msgfile);
1128                 else
1129                         compose_attach_append(compose, msgfile,
1130                                 MIME_MESSAGE_RFC822);
1131                 g_free(msgfile);
1132         }
1133
1134         if (prefs_common.auto_sig)
1135                 compose_insert_sig(compose);
1136
1137         if (prefs_common.linewrap_quote)
1138                 compose_wrap_line_all(compose);
1139
1140         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
1141         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
1142
1143         gtk_stext_thaw(text);
1144 #if 0 /* NEW COMPOSE GUI */
1145         if (account->protocol != A_NNTP)
1146                 gtk_widget_grab_focus(compose->to_entry);
1147         else
1148                 gtk_widget_grab_focus(compose->newsgroups_entry);
1149 #endif
1150
1151         return compose;
1152 }
1153
1154 void compose_reedit(MsgInfo *msginfo)
1155 {
1156         Compose *compose;
1157         PrefsAccount *account;
1158         GtkSText *text;
1159         FILE *fp;
1160         gchar buf[BUFFSIZE];
1161
1162         g_return_if_fail(msginfo != NULL);
1163         g_return_if_fail(msginfo->folder != NULL);
1164
1165         if (msginfo->folder->stype == F_QUEUE) {
1166                 gchar account_address[BUFFSIZE];
1167                 if (!get_header_from_msginfo(msginfo, account_address, sizeof(account_address), "S:")) {
1168                         account = account_find_from_address(account_address);
1169                 }
1170         } else 
1171                 account = msginfo->folder->folder->account;
1172
1173         if (!account && prefs_common.reedit_account_autosel) {
1174                 gchar from[BUFFSIZE];
1175                 if (!get_header_from_msginfo(msginfo, from, sizeof(from), "FROM:")){
1176                         extract_address(from);
1177                         account = account_find_from_address(from);
1178                 }
1179         }
1180         if (!account) account = cur_account;
1181         g_return_if_fail(account != NULL);
1182
1183         compose = compose_create(account, COMPOSE_REEDIT);
1184         compose->targetinfo = procmsg_msginfo_copy(msginfo);
1185
1186         if (compose_parse_header(compose, msginfo) < 0) return;
1187         compose_reedit_set_entry(compose, msginfo);
1188
1189         text = GTK_STEXT(compose->text);
1190         gtk_stext_freeze(text);
1191
1192         if ((fp = procmime_get_first_text_content(msginfo)) == NULL)
1193                 g_warning(_("Can't get text part\n"));
1194         else {
1195                 while (fgets(buf, sizeof(buf), fp) != NULL)
1196                         gtk_stext_insert(text, NULL, NULL, NULL, buf, -1);
1197                 fclose(fp);
1198         }
1199         compose_attach_parts(compose, msginfo);
1200
1201         gtk_stext_thaw(text);
1202         gtk_widget_grab_focus(compose->text);
1203
1204         if (prefs_common.auto_exteditor)
1205                 compose_exec_ext_editor(compose);
1206 }
1207
1208 GList *compose_get_compose_list(void)
1209 {
1210         return compose_list;
1211 }
1212
1213 void compose_entry_append(Compose *compose, const gchar *address,
1214                           ComposeEntryType type)
1215 {
1216         GtkEntry *entry;
1217         const gchar *text;
1218         gchar *header;
1219
1220         if (!address || *address == '\0') return;
1221
1222 #if 0 /* NEW COMPOSE GUI */
1223         switch (type) {
1224         case COMPOSE_CC:
1225                 entry = GTK_ENTRY(compose->cc_entry);
1226                 break;
1227         case COMPOSE_BCC:
1228                 entry = GTK_ENTRY(compose->bcc_entry);
1229                 break;
1230         case COMPOSE_NEWSGROUPS:
1231                 entry = GTK_ENTRY(compose->newsgroups_entry);
1232                 break;
1233         case COMPOSE_TO:
1234         default:
1235                 entry = GTK_ENTRY(compose->to_entry);
1236                 break;
1237         }
1238
1239         text = gtk_entry_get_text(entry);
1240         if (*text != '\0')
1241                 gtk_entry_append_text(entry, ", ");
1242         gtk_entry_append_text(entry, address);
1243 #endif
1244
1245         switch (type) {
1246         case COMPOSE_CC:
1247                 header = N_("Cc:");
1248                 break;
1249         case COMPOSE_BCC:
1250                 header = N_("Bcc:");
1251                 break;
1252         case COMPOSE_REPLYTO:
1253                 header = N_("Reply-To:");
1254                 break;
1255         case COMPOSE_NEWSGROUPS:
1256                 header = N_("Newsgroups:");
1257                 break;
1258         case COMPOSE_FOLLOWUPTO:
1259                 header = N_( "Followup-To:");
1260                 break;
1261         case COMPOSE_TO:
1262         default:
1263                 header = N_("To:");
1264                 break;
1265         }
1266         header = prefs_common.trans_hdr ? gettext(header) : header;
1267
1268         compose_add_header_entry(compose, header, (gchar *)address);
1269 }
1270
1271 static void compose_entries_set(Compose *compose, const gchar *mailto)
1272 {
1273         gchar *subject = NULL;
1274         gchar *to = NULL;
1275         gchar *cc = NULL;
1276         gchar *bcc = NULL;
1277         gchar *body = NULL;
1278         gchar *p;
1279         gchar *tmp_mailto;
1280
1281         Xstrdup_a(tmp_mailto, mailto, return);
1282
1283         to = tmp_mailto;
1284
1285         p = strchr(tmp_mailto, '?');
1286         if (p) {
1287                 *p = '\0';
1288                 p++;
1289         }
1290
1291         while (p) {
1292                 gchar *field, *value;
1293
1294                 field = p;
1295
1296                 p = strchr(p, '=');
1297                 if (!p) break;
1298                 *p = '\0';
1299                 p++;
1300
1301                 value = p;
1302
1303                 p = strchr(p, '&');
1304                 if (p) {
1305                         *p = '\0';
1306                         p++;
1307                 }
1308
1309                 if (*value == '\0') continue;
1310
1311                 if (!g_strcasecmp(field, "subject")) {
1312                         Xalloca(subject, strlen(value) + 1, return);
1313                         decode_uri(subject, value);
1314                 } else if (!g_strcasecmp(field, "cc")) {
1315                         cc = value;
1316                 } else if (!g_strcasecmp(field, "bcc")) {
1317                         bcc = value;
1318                 } else if (!g_strcasecmp(field, "body")) {
1319                         Xalloca(body, strlen(value) + 1, return);
1320                         decode_uri(body, value);
1321                 }
1322         }
1323
1324         if (to)
1325                 compose_entry_append(compose, to, COMPOSE_TO);
1326         if (subject)
1327                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), subject);
1328         if (cc)
1329                 compose_entry_append(compose, cc, COMPOSE_CC);
1330         if (bcc)
1331                 compose_entry_append(compose, bcc, COMPOSE_BCC);
1332         if (body) {
1333                 gtk_stext_insert(GTK_STEXT(compose->text),
1334                                 NULL, NULL, NULL, body, -1);
1335                 gtk_stext_insert(GTK_STEXT(compose->text),
1336                                 NULL, NULL, NULL, "\n", 1);
1337         }
1338 }
1339
1340 static gint compose_parse_header(Compose *compose, MsgInfo *msginfo)
1341 {
1342         static HeaderEntry hentry[] = {{"Reply-To:",       NULL, TRUE},
1343                                        {"Cc:",             NULL, FALSE},
1344                                        {"References:",     NULL, FALSE},
1345                                        {"Bcc:",            NULL, FALSE},
1346                                        {"Newsgroups:",     NULL, FALSE},
1347                                        {"Followup-To:",    NULL, FALSE},
1348                                        {"X-Mailing-List:", NULL, FALSE},
1349                                        {"X-BeenThere:",    NULL, FALSE},
1350                                        {NULL,              NULL, FALSE}};
1351
1352         enum
1353         {
1354                 H_REPLY_TO       = 0,
1355                 H_CC             = 1,
1356                 H_REFERENCES     = 2,
1357                 H_BCC            = 3,
1358                 H_NEWSGROUPS     = 4,
1359                 H_FOLLOWUP_TO    = 5,
1360                 H_X_MAILING_LIST = 6,
1361                 H_X_BEENTHERE    = 7
1362         };
1363
1364         FILE *fp;
1365
1366         g_return_val_if_fail(msginfo != NULL, -1);
1367
1368         if ((fp = procmsg_open_message(msginfo)) == NULL) return -1;
1369         procheader_get_header_fields(fp, hentry);
1370         fclose(fp);
1371
1372         if (hentry[H_REPLY_TO].body != NULL) {
1373                 conv_unmime_header_overwrite(hentry[H_REPLY_TO].body);
1374                 compose->replyto = hentry[H_REPLY_TO].body;
1375                 hentry[H_REPLY_TO].body = NULL;
1376         }
1377         if (hentry[H_CC].body != NULL) {
1378                 conv_unmime_header_overwrite(hentry[H_CC].body);
1379                 compose->cc = hentry[H_CC].body;
1380                 hentry[H_CC].body = NULL;
1381         }
1382         if (hentry[H_X_MAILING_LIST].body != NULL) {
1383                 /* this is good enough to parse debian-devel */
1384                 gchar *buf = g_malloc(strlen(hentry[H_X_MAILING_LIST].body) + 1);
1385                 g_return_val_if_fail(buf != NULL, -1 );
1386                 if (1 == sscanf(hentry[H_X_MAILING_LIST].body, "<%[^>]>", buf))
1387                         compose->mailinglist = g_strdup(buf);
1388                 g_free(buf);
1389                 g_free(hentry[H_X_MAILING_LIST].body);
1390                 hentry[H_X_MAILING_LIST].body = NULL ;
1391         }
1392         if (hentry[H_X_BEENTHERE].body != NULL) {
1393                 /* this is good enough to parse the sylpheed-claws lists */
1394                 gchar *buf = g_malloc(strlen(hentry[H_X_BEENTHERE].body) + 1);
1395                 g_return_val_if_fail(buf != NULL, -1 );
1396                 if (1 == sscanf(hentry[H_X_BEENTHERE].body, "%[^>]", buf))
1397                         compose->mailinglist = g_strdup(buf);
1398                 g_free(buf);
1399                 g_free(hentry[H_X_BEENTHERE].body);
1400                 hentry[H_X_BEENTHERE].body = NULL ;
1401         }
1402         if (hentry[H_REFERENCES].body != NULL) {
1403                 if (compose->mode == COMPOSE_REEDIT)
1404                         compose->references = hentry[H_REFERENCES].body;
1405                 else {
1406                         compose->references = compose_parse_references
1407                                 (hentry[H_REFERENCES].body, msginfo->msgid);
1408                         g_free(hentry[H_REFERENCES].body);
1409                 }
1410                 hentry[H_REFERENCES].body = NULL;
1411         }
1412         if (hentry[H_BCC].body != NULL) {
1413                 if (compose->mode == COMPOSE_REEDIT) {
1414                         conv_unmime_header_overwrite(hentry[H_BCC].body);
1415                         compose->bcc = hentry[H_BCC].body;
1416                 } else
1417                         g_free(hentry[H_BCC].body);
1418                 hentry[H_BCC].body = NULL;
1419         }
1420         if (hentry[H_NEWSGROUPS].body != NULL) {
1421                 compose->newsgroups = hentry[H_NEWSGROUPS].body;
1422                 hentry[H_NEWSGROUPS].body = NULL;
1423         }
1424         if (hentry[H_FOLLOWUP_TO].body != NULL) {
1425                 conv_unmime_header_overwrite(hentry[H_FOLLOWUP_TO].body);
1426                 compose->followup_to = hentry[H_FOLLOWUP_TO].body;
1427                 hentry[H_FOLLOWUP_TO].body = NULL;
1428         }
1429
1430         if (compose->mode == COMPOSE_REEDIT && msginfo->inreplyto)
1431                 compose->inreplyto = g_strdup(msginfo->inreplyto);
1432         else if (compose->mode != COMPOSE_REEDIT &&
1433                  msginfo->msgid && *msginfo->msgid) {
1434                 compose->inreplyto = g_strdup(msginfo->msgid);
1435
1436                 if (!compose->references) {
1437                         if (msginfo->inreplyto && *msginfo->inreplyto)
1438                                 compose->references =
1439                                         g_strdup_printf("<%s>\n\t<%s>",
1440                                                         msginfo->inreplyto,
1441                                                         msginfo->msgid);
1442                         else
1443                                 compose->references =
1444                                         g_strconcat("<", msginfo->msgid, ">",
1445                                                     NULL);
1446                 }
1447         }
1448
1449         return 0;
1450 }
1451
1452 static gchar *compose_parse_references(const gchar *ref, const gchar *msgid)
1453 {
1454         GSList *ref_id_list, *cur;
1455         GString *new_ref;
1456         gchar *new_ref_str;
1457
1458         ref_id_list = references_list_append(NULL, ref);
1459         if (!ref_id_list) return NULL;
1460         if (msgid && *msgid)
1461                 ref_id_list = g_slist_append(ref_id_list, g_strdup(msgid));
1462
1463         for (;;) {
1464                 gint len = 0;
1465
1466                 for (cur = ref_id_list; cur != NULL; cur = cur->next)
1467                         /* "<" + Message-ID + ">" + CR+LF+TAB */
1468                         len += strlen((gchar *)cur->data) + 5;
1469
1470                 if (len > MAX_REFERENCES_LEN) {
1471                         /* remove second message-ID */
1472                         if (ref_id_list && ref_id_list->next &&
1473                             ref_id_list->next->next) {
1474                                 g_free(ref_id_list->next->data);
1475                                 ref_id_list = g_slist_remove
1476                                         (ref_id_list, ref_id_list->next->data);
1477                         } else {
1478                                 slist_free_strings(ref_id_list);
1479                                 g_slist_free(ref_id_list);
1480                                 return NULL;
1481                         }
1482                 } else
1483                         break;
1484         }
1485
1486         new_ref = g_string_new("");
1487         for (cur = ref_id_list; cur != NULL; cur = cur->next) {
1488                 if (new_ref->len > 0)
1489                         g_string_append(new_ref, "\n\t");
1490                 g_string_sprintfa(new_ref, "<%s>", (gchar *)cur->data);
1491         }
1492
1493         slist_free_strings(ref_id_list);
1494         g_slist_free(ref_id_list);
1495
1496         new_ref_str = new_ref->str;
1497         g_string_free(new_ref, FALSE);
1498
1499         return new_ref_str;
1500 }
1501
1502 static gchar *compose_quote_fmt(Compose *compose, MsgInfo *msginfo,
1503                                 const gchar *fmt, const gchar *qmark)
1504 {
1505         GtkSText *text = GTK_STEXT(compose->text);
1506         gchar *quote_str = NULL;
1507         gchar *buf;
1508         gchar *p, *lastp;
1509         gint len;
1510
1511         if (qmark != NULL) {
1512                 quote_fmt_init(msginfo, NULL);
1513                 quote_fmt_scan_string(qmark);
1514                 quote_fmt_parse();
1515
1516                 buf = quote_fmt_get_buffer();
1517                 if (buf == NULL)
1518                         alertpanel_error(_("Quote mark format error."));
1519                 else
1520                         Xstrdup_a(quote_str, buf, return NULL)
1521         }
1522
1523         if (fmt && *fmt != '\0') {
1524                 quote_fmt_init(msginfo, quote_str);
1525                 quote_fmt_scan_string(fmt);
1526                 quote_fmt_parse();
1527
1528                 buf = quote_fmt_get_buffer();
1529                 if (buf == NULL) {
1530                         alertpanel_error(_("Message reply/forward format error."));
1531                         return NULL;
1532                 }
1533         } else
1534                 buf = "";
1535
1536         gtk_stext_freeze(text);
1537         gtk_stext_set_point(text, 0);
1538         gtk_stext_forward_delete(text, gtk_stext_get_length(text));
1539
1540         for (p = buf; *p != '\0'; ) {
1541                 lastp = strchr(p, '\n');
1542                 len = lastp ? lastp - p + 1 : -1;
1543                 gtk_stext_insert(text, NULL, NULL, NULL, p, len);
1544                 if (lastp)
1545                         p = lastp + 1;
1546                 else
1547                         break;
1548         }
1549
1550         gtk_stext_thaw(text);
1551
1552         return buf;
1553 }
1554
1555 static void compose_reply_set_entry(Compose *compose, MsgInfo *msginfo,
1556                                     gboolean to_all, gboolean ignore_replyto,
1557                                     gboolean followup_and_reply_to)
1558 {
1559         GSList *cc_list;
1560         GSList *cur;
1561         gchar *from;
1562         GHashTable *to_table;
1563
1564         g_return_if_fail(compose->account != NULL);
1565         g_return_if_fail(msginfo != NULL);
1566
1567         if ((compose->account->protocol != A_NNTP) || followup_and_reply_to)
1568                 compose_entry_append(compose,
1569                                     ((compose->replyto && !ignore_replyto)
1570                                      ? compose->replyto
1571                                      : (compose->mailinglist && !ignore_replyto)
1572                                      ? compose->mailinglist
1573                                      : msginfo->from ? msginfo->from : ""),
1574                                      COMPOSE_TO);
1575         if (compose->account->protocol == A_NNTP) {
1576                 if (ignore_replyto)
1577                         compose_entry_append
1578                                 (compose, msginfo->from ? msginfo->from : "",
1579                                  COMPOSE_TO);
1580                 else
1581                         compose_entry_append
1582                                 (compose,
1583                                  compose->followup_to ? compose->followup_to
1584                                  : compose->newsgroups ? compose->newsgroups
1585                                  : "",
1586                                  COMPOSE_NEWSGROUPS);
1587         }
1588
1589         if (msginfo->subject && *msginfo->subject) {
1590                 gchar *buf, *buf2, *p;
1591
1592                 buf = g_strdup(msginfo->subject);
1593                 while (!strncasecmp(buf, "Re:", 3)) {
1594                         p = buf + 3;
1595                         while (isspace(*p)) p++;
1596                         memmove(buf, p, strlen(p) + 1);
1597                 }
1598
1599                 buf2 = g_strdup_printf("Re: %s", buf);
1600                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), buf2);
1601                 g_free(buf2);
1602                 g_free(buf);
1603         } else
1604                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), "Re: ");
1605
1606         if (!to_all || compose->account->protocol == A_NNTP) return;
1607
1608         from = g_strdup(compose->replyto ? compose->replyto :
1609                         msginfo->from ? msginfo->from : "");
1610         extract_address(from);
1611
1612         cc_list = address_list_append(NULL, msginfo->to);
1613         cc_list = address_list_append(cc_list, compose->cc);
1614
1615         to_table = g_hash_table_new(g_str_hash, g_str_equal);
1616         g_hash_table_insert(to_table, from, GINT_TO_POINTER(1));
1617         if (compose->account)
1618                 g_hash_table_insert(to_table, compose->account->address,
1619                                     GINT_TO_POINTER(1));
1620
1621         /* remove address on To: and that of current account */
1622         for (cur = cc_list; cur != NULL; ) {
1623                 GSList *next = cur->next;
1624
1625                 if (g_hash_table_lookup(to_table, cur->data) != NULL)
1626                         cc_list = g_slist_remove(cc_list, cur->data);
1627                 else
1628                         g_hash_table_insert(to_table, cur->data, cur);
1629
1630                 cur = next;
1631         }
1632         g_hash_table_destroy(to_table);
1633         g_free(from);
1634
1635         if (cc_list) {
1636                 for (cur = cc_list; cur != NULL; cur = cur->next)
1637                         compose_entry_append(compose, (gchar *)cur->data,
1638                                              COMPOSE_CC);
1639                 slist_free_strings(cc_list);
1640                 g_slist_free(cc_list);
1641         }
1642 }
1643
1644 #define SET_ENTRY(entry, str) \
1645 { \
1646         if (str && *str) \
1647                 gtk_entry_set_text(GTK_ENTRY(compose->entry), str); \
1648 }
1649
1650 #define SET_ADDRESS(type, str) \
1651 { \
1652         if (str && *str) \
1653                 compose_entry_append(compose, str, type); \
1654 }
1655
1656 static void compose_reedit_set_entry(Compose *compose, MsgInfo *msginfo)
1657 {
1658         g_return_if_fail(msginfo != NULL);
1659
1660         SET_ENTRY(subject_entry, msginfo->subject);
1661         SET_ADDRESS(COMPOSE_TO, msginfo->to);
1662         SET_ADDRESS(COMPOSE_CC, compose->cc);
1663         SET_ADDRESS(COMPOSE_BCC, compose->bcc);
1664         SET_ADDRESS(COMPOSE_REPLYTO, compose->replyto);
1665
1666 #if 0 /* NEW COMPOSE GUI */
1667         if (compose->bcc) {
1668                 GtkItemFactory *ifactory;
1669                 GtkWidget *menuitem;
1670
1671                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1672                 menuitem = gtk_item_factory_get_item(ifactory, "/Message/Bcc");
1673                 gtk_check_menu_item_set_active
1674                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
1675         }
1676         if (compose->replyto) {
1677                 GtkItemFactory *ifactory;
1678                 GtkWidget *menuitem;
1679
1680                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1681                 menuitem = gtk_item_factory_get_item
1682                         (ifactory, "/Message/Reply to");
1683                 gtk_check_menu_item_set_active
1684                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
1685         }
1686 #endif
1687 }
1688
1689 #undef SET_ENTRY
1690 #undef SET_ADDRESS
1691
1692 static void compose_exec_sig(Compose *compose, gchar *sigfile)
1693 {
1694         FILE *tmpfp;
1695         pid_t thepid;
1696         gchar *sigtext;
1697         FILE  *sigprg;
1698         gchar  *buf;
1699         size_t buf_len = 128;
1700  
1701         if (strlen(sigfile) < 2)
1702           return;
1703  
1704         sigprg = popen(sigfile+1, "r");
1705         if (sigprg) {
1706
1707                 buf = g_malloc(buf_len);
1708
1709                 if (!buf) {
1710                         gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, \
1711                         "Unable to insert signature (malloc failed)\n", -1);
1712
1713                         pclose(sigprg);
1714                         return;
1715                 }
1716
1717                 while (!feof(sigprg)) {
1718                         bzero(buf, buf_len);
1719                         fread(buf, buf_len-1, 1, sigprg);
1720                         gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, buf, -1);
1721                 }
1722
1723                 g_free(buf);
1724                 pclose(sigprg);
1725         }
1726         else
1727         {
1728                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, \
1729                 "Can't exec file: ", -1);
1730                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, \
1731                 sigfile+1, -1);
1732         }
1733 }
1734
1735 static void compose_insert_sig(Compose *compose)
1736 {
1737         gchar *sigfile;
1738
1739         if (compose->account && compose->account->sig_path)
1740                 sigfile = g_strdup(compose->account->sig_path);
1741         else {
1742                 sigfile = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1743                                       DEFAULT_SIGNATURE, NULL);
1744         }
1745
1746         if (!is_file_or_fifo_exist(sigfile) & (sigfile[0] != '|')) {
1747                 g_free(sigfile);
1748                 return;
1749         }
1750
1751         gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, "\n\n", 2);
1752         if (prefs_common.sig_sep) {
1753                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL,
1754                                 prefs_common.sig_sep, -1);
1755                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL,
1756                                 "\n", 1);
1757         }
1758
1759         if (sigfile[0] == '|')
1760         {
1761                 compose_exec_sig(compose, sigfile);
1762         }
1763         else
1764         {
1765                 compose_insert_file(compose, sigfile);
1766         }
1767         g_free(sigfile);
1768 }
1769
1770 static void compose_insert_file(Compose *compose, const gchar *file)
1771 {
1772         GtkSText *text = GTK_STEXT(compose->text);
1773         gchar buf[BUFFSIZE];
1774         gint len;
1775         FILE *fp;
1776
1777         g_return_if_fail(file != NULL);
1778
1779         if ((fp = fopen(file, "r")) == NULL) {
1780                 FILE_OP_ERROR(file, "fopen");
1781                 return;
1782         }
1783
1784         gtk_stext_freeze(text);
1785
1786         while (fgets(buf, sizeof(buf), fp) != NULL) {
1787                 /* Strip <CR> if DOS/Windoze file, replace <CR> with <LF> if MAC file */
1788                 len = strlen(buf);
1789                 if (len > 1 && buf[len - 2] == '\r' && buf[len - 1] == '\n') {
1790                         buf[len - 2] = '\n';
1791                         buf[len - 1] = '\0';
1792                 } else {
1793                         while (--len > 0)
1794                                 if (buf[len] == '\r')
1795                                         buf[len] = '\n';
1796                 }
1797
1798                 gtk_stext_insert(text, NULL, NULL, NULL, buf, -1);
1799         }
1800
1801         gtk_stext_thaw(text);
1802
1803         fclose(fp);
1804 }
1805
1806 static void compose_attach_info(Compose * compose, AttachInfo * ainfo,
1807                                 ContentType cnttype)
1808 {
1809         gchar *text[N_ATTACH_COLS];
1810         gint row;
1811
1812         text[COL_MIMETYPE] = ainfo->content_type;
1813         text[COL_SIZE] = to_human_readable(ainfo->size);
1814         text[COL_NAME] = ainfo->name;
1815
1816         row = gtk_clist_append(GTK_CLIST(compose->attach_clist), text);
1817         gtk_clist_set_row_data(GTK_CLIST(compose->attach_clist), row, ainfo);
1818
1819         if (cnttype != MIME_MESSAGE_RFC822)
1820                 compose_changed_cb(NULL, compose);
1821 }
1822
1823 static void compose_attach_append_with_type(Compose *compose,
1824                                             const gchar *file,
1825                                             const gchar *type,
1826                                             ContentType cnttype)
1827 {
1828         AttachInfo *ainfo;
1829         off_t size;
1830
1831         if (!is_file_exist(file)) {
1832                 g_warning(_("File %s doesn't exist\n"), file);
1833                 return;
1834         }
1835         if ((size = get_file_size(file)) < 0) {
1836                 g_warning(_("Can't get file size of %s\n"), file);
1837                 return;
1838         }
1839         if (size == 0) {
1840                 alertpanel_notice(_("File %s is empty\n"), file);
1841                 return;
1842         }
1843 #if 0 /* NEW COMPOSE GUI */
1844         if (!compose->use_attach) {
1845                 GtkItemFactory *ifactory;
1846                 GtkWidget *menuitem;
1847
1848                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1849                 menuitem = gtk_item_factory_get_item(ifactory,
1850                                                      "/Message/Attach");
1851                 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
1852                                                TRUE);
1853         }
1854 #endif
1855         ainfo = g_new0(AttachInfo, 1);
1856         ainfo->file = g_strdup(file);
1857
1858         if (cnttype == MIME_MESSAGE_RFC822) {
1859                 ainfo->encoding = ENC_7BIT;
1860                 ainfo->name = g_strdup_printf(_("Message: %s"),
1861                                               g_basename(file));
1862         } else {
1863                 ainfo->encoding = ENC_BASE64;
1864                 ainfo->name = g_strdup(g_basename(file));
1865         }
1866
1867         ainfo->content_type = g_strdup(type);
1868         ainfo->size = size;
1869
1870         compose_attach_info(compose, ainfo, cnttype);
1871 }
1872
1873 static void compose_attach_append(Compose *compose, const gchar *file,
1874                                   ContentType cnttype)
1875 {
1876         AttachInfo *ainfo;
1877         gchar *text[N_ATTACH_COLS];
1878         off_t size;
1879         gint row;
1880
1881         if (!is_file_exist(file)) {
1882                 g_warning(_("File %s doesn't exist\n"), file);
1883                 return;
1884         }
1885         if ((size = get_file_size(file)) < 0) {
1886                 g_warning(_("Can't get file size of %s\n"), file);
1887                 return;
1888         }
1889         if (size == 0) {
1890                 alertpanel_notice(_("File %s is empty\n"), file);
1891                 return;
1892         }
1893 #if 0 /* NEW COMPOSE GUI */
1894         if (!compose->use_attach) {
1895                 GtkItemFactory *ifactory;
1896                 GtkWidget *menuitem;
1897
1898                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1899                 menuitem = gtk_item_factory_get_item(ifactory,
1900                                                      "/Message/Attach");
1901                 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
1902                                                TRUE);
1903         }
1904 #endif
1905         ainfo = g_new0(AttachInfo, 1);
1906         ainfo->file = g_strdup(file);
1907
1908         if (cnttype == MIME_MESSAGE_RFC822) {
1909                 ainfo->content_type = g_strdup("message/rfc822");
1910                 ainfo->encoding = ENC_7BIT;
1911                 ainfo->name = g_strdup_printf(_("Message: %s"),
1912                                               g_basename(file));
1913         } else {
1914                 ainfo->content_type = procmime_get_mime_type(file);
1915                 if (!ainfo->content_type)
1916                         ainfo->content_type =
1917                                 g_strdup("application/octet-stream");
1918                 ainfo->encoding = ENC_BASE64;
1919                 ainfo->name = g_strdup(g_basename(file));
1920         }
1921         ainfo->size = size;
1922
1923         compose_attach_info(compose, ainfo, cnttype);
1924 }
1925
1926 #define GET_CHAR(pos, buf, len)                                              \
1927 {                                                                            \
1928         if (text->use_wchar)                                                 \
1929                 len = wctomb(buf, (wchar_t)GTK_STEXT_INDEX(text, (pos)));     \
1930         else {                                                               \
1931                 buf[0] = GTK_STEXT_INDEX(text, (pos));                       \
1932                 len = 1;                                                     \
1933         }                                                                    \
1934 }
1935
1936 static void compose_wrap_line(Compose *compose)
1937 {
1938         GtkSText *text = GTK_STEXT(compose->text);
1939         gint ch_len, last_ch_len;
1940         gchar cbuf[MB_LEN_MAX], last_ch;
1941         guint text_len;
1942         guint line_end;
1943         guint quoted;
1944         gint p_start, p_end;
1945         gint line_pos, cur_pos;
1946         gint line_len, cur_len;
1947
1948
1949         gtk_stext_freeze(text);
1950
1951         text_len = gtk_stext_get_length(text);
1952
1953         /* check to see if the point is on the paragraph mark (empty line). */
1954         cur_pos = gtk_stext_get_point(text);
1955         GET_CHAR(cur_pos, cbuf, ch_len);
1956         if ((ch_len == 1 && *cbuf == '\n') || cur_pos == text_len) {
1957                 if (cur_pos == 0)
1958                         goto compose_end; /* on the paragraph mark */
1959                 GET_CHAR(cur_pos - 1, cbuf, ch_len);
1960                 if (ch_len == 1 && *cbuf == '\n')
1961                         goto compose_end; /* on the paragraph mark */
1962         }
1963
1964         /* find paragraph start. */
1965         line_end = quoted = 0;
1966         for (p_start = cur_pos; p_start >= 0; --p_start) {
1967                 GET_CHAR(p_start, cbuf, ch_len);
1968                 if (ch_len == 1 && *cbuf == '\n') {
1969                         if (quoted)
1970                                 goto compose_end; /* quoted part */
1971                         if (line_end) {
1972                                 p_start += 2;
1973                                 break;
1974                         }
1975                         line_end = 1;
1976                 } else {
1977                         if (ch_len == 1 && strchr(">:#", *cbuf))
1978                                 quoted = 1;
1979                         else if (ch_len != 1 || !isspace(*cbuf))
1980                                 quoted = 0;
1981
1982                         line_end = 0;
1983                 }
1984         }
1985         if (p_start < 0)
1986                 p_start = 0;
1987
1988         /* find paragraph end. */
1989         line_end = 0;
1990         for (p_end = cur_pos; p_end < text_len; p_end++) {
1991                 GET_CHAR(p_end, cbuf, ch_len);
1992                 if (ch_len == 1 && *cbuf == '\n') {
1993                         if (line_end) {
1994                                 p_end -= 1;
1995                                 break;
1996                         }
1997                         line_end = 1;
1998                 } else {
1999                         if (line_end && ch_len == 1 && strchr(">:#", *cbuf))
2000                                 goto compose_end; /* quoted part */
2001
2002                         line_end = 0;
2003                 }
2004         }
2005         if (p_end >= text_len)
2006                 p_end = text_len;
2007
2008         if (p_start >= p_end)
2009                 goto compose_end;
2010
2011         line_len = cur_len = 0;
2012         last_ch_len = 0;
2013         last_ch = '\0';
2014         line_pos = p_start;
2015         for (cur_pos = p_start; cur_pos < p_end; cur_pos++) {
2016                 guint space = 0;
2017
2018                 GET_CHAR(cur_pos, cbuf, ch_len);
2019
2020                 if (ch_len < 0) {
2021                         cbuf[0] = '\0';
2022                         ch_len = 1;
2023                 }
2024
2025                 if (ch_len == 1 && isspace(*cbuf))
2026                         space = 1;
2027
2028                 if (ch_len == 1 && *cbuf == '\n') {
2029                         guint replace = 0;
2030                         if (last_ch_len == 1 && !isspace(last_ch)) {
2031                                 if (cur_pos + 1 < p_end) {
2032                                         GET_CHAR(cur_pos + 1, cbuf, ch_len);
2033                                         if (ch_len == 1 && !isspace(*cbuf))
2034                                                 replace = 1;
2035                                 }
2036                         }
2037                         gtk_stext_set_point(text, cur_pos + 1);
2038                         gtk_stext_backward_delete(text, 1);
2039                         if (replace) {
2040                                 gtk_stext_set_point(text, cur_pos);
2041                                 gtk_stext_insert(text, NULL, NULL, NULL, " ", 1);
2042                                 space = 1;
2043                         }
2044                         else {
2045                                 p_end--;
2046                                 cur_pos--;
2047                                 continue;
2048                         }
2049                 }
2050
2051                 last_ch_len = ch_len;
2052                 last_ch = *cbuf;
2053
2054                 if (space) {
2055                         line_pos = cur_pos + 1;
2056                         line_len = cur_len + ch_len;
2057                 }
2058
2059                 if (cur_len + ch_len > prefs_common.linewrap_len &&
2060                     line_len > 0) {
2061                         gint tlen = ch_len;
2062
2063                         GET_CHAR(line_pos - 1, cbuf, ch_len);
2064                         if (ch_len == 1 && isspace(*cbuf)) {
2065                                 gtk_stext_set_point(text, line_pos);
2066                                 gtk_stext_backward_delete(text, 1);
2067                                 p_end--;
2068                                 cur_pos--;
2069                                 line_pos--;
2070                                 cur_len--;
2071                                 line_len--;
2072                         }
2073                         ch_len = tlen;
2074
2075                         gtk_stext_set_point(text, line_pos);
2076                         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1);
2077                         p_end++;
2078                         cur_pos++;
2079                         line_pos++;
2080                         cur_len = cur_len - line_len + ch_len;
2081                         line_len = 0;
2082                         continue;
2083                 }
2084
2085                 if (ch_len > 1) {
2086                         line_pos = cur_pos + 1;
2087                         line_len = cur_len + ch_len;
2088                 }
2089                 cur_len += ch_len;
2090         }
2091
2092 compose_end:
2093         gtk_stext_thaw(text);
2094 }
2095
2096 /* return indent length */
2097 static guint get_indent_length(GtkSText *text, guint start_pos, guint text_len)
2098 {
2099         gint indent_len = 0;
2100         gint i, ch_len;
2101         gchar cbuf[MB_LEN_MAX];
2102
2103         for (i = start_pos; i < text_len; i++) {
2104                 GET_CHAR(i, cbuf, ch_len);
2105                 if (ch_len > 1)
2106                         break;
2107                 /* allow space, tab, > or | */
2108                 if (cbuf[0] != ' ' && cbuf[0] != '\t' &&
2109                     cbuf[0] != '>' && cbuf[0] != '|')
2110                         break;
2111                 indent_len++;
2112         }
2113
2114         return indent_len;
2115 }
2116
2117 /* insert quotation string when line was wrapped */
2118 static guint ins_quote(GtkSText *text, guint quote_len, guint indent_len,
2119                        guint prev_line_pos, guint text_len,
2120                        gchar *quote_fmt)
2121 {
2122         guint i, ins_len;
2123         gchar ch;
2124
2125         if (indent_len) {
2126                 for (i = 0; i < indent_len; i++) {
2127                         ch = GTK_STEXT_INDEX(text, prev_line_pos + i);
2128                         gtk_stext_insert(text, NULL, NULL, NULL, &ch, 1);
2129                 }
2130                 ins_len = indent_len;
2131         } else {
2132                 gtk_stext_insert(text, NULL, NULL, NULL, quote_fmt, quote_len);
2133                 ins_len = quote_len;
2134         }
2135
2136         return ins_len;
2137 }
2138
2139 #undef WRAP_DEBUG
2140 #ifdef WRAP_DEBUG
2141 /* Darko: used when I debug wrapping */
2142 void dump_text(GtkSText *text, int pos, int tlen, int breakoncr)
2143 {
2144         gint i;
2145         gchar ch;
2146
2147         printf("%d [", pos);
2148         for (i = pos; i < tlen; i++) {
2149                 ch = GTK_STEXT_INDEX(text, i);
2150                 if (breakoncr && ch == '\n')
2151                         break;
2152                 printf("%c", ch);
2153         }
2154         printf("]\n");
2155 }
2156 #endif
2157
2158 static void compose_wrap_line_all(Compose *compose)
2159 {
2160         GtkSText *text = GTK_STEXT(compose->text);
2161         guint tlen;
2162         guint line_pos = 0, cur_pos = 0, p_pos = 0;
2163         gint line_len = 0, cur_len = 0;
2164         gint ch_len;
2165         gboolean is_new_line = TRUE, do_delete = FALSE;
2166         guint qlen = 0, i_len = 0;
2167         guint linewrap_quote = prefs_common.linewrap_quote;
2168         guint linewrap_len = prefs_common.linewrap_len;
2169         gchar *qfmt = prefs_common.quotemark;
2170         gchar cbuf[MB_LEN_MAX];
2171
2172         gtk_stext_freeze(text);
2173
2174         /* make text buffer contiguous */
2175         /* gtk_stext_compact_buffer(text); */
2176
2177         tlen = gtk_stext_get_length(text);
2178
2179         for (; cur_pos < tlen; cur_pos++) {
2180                 /* mark position of new line - needed for quotation wrap */
2181                 if (is_new_line) {
2182                         if (linewrap_quote && is_new_line) {
2183                                 qlen = gtkut_text_str_compare
2184                                         (text, cur_pos, tlen, qfmt);
2185                                 if (qlen)
2186                                         i_len = get_indent_length(text, cur_pos, tlen);
2187                                 else
2188                                         i_len = 0;
2189                         }
2190                         is_new_line = FALSE;
2191                         p_pos = cur_pos;
2192 #ifdef WRAP_DEBUG
2193                         printf("new line i_len=%d qlen=%d p_pos=", i_len, qlen);
2194                         dump_text(text, p_pos, tlen, 1);
2195 #endif
2196                 }
2197
2198                 GET_CHAR(cur_pos, cbuf, ch_len);
2199
2200                 /* fix line length for tabs */
2201                 if (ch_len == 1 && *cbuf == '\t') {
2202                         guint tab_width = text->default_tab_width;
2203                         guint tab_offset = line_len % tab_width;
2204
2205 #ifdef WRAP_DEBUG
2206                         printf("found tab at pos=%d line_len=%d ", cur_pos,
2207                                 line_len);
2208 #endif
2209                         if (tab_offset) {
2210                                 line_len += tab_width - tab_offset - 1;
2211                                 cur_len = line_len;
2212                         }
2213 #ifdef WRAP_DEBUG
2214                         printf("new_len=%d\n", line_len);
2215 #endif
2216                 }
2217
2218                 /* we have encountered line break */
2219                 if (ch_len == 1 && *cbuf == '\n') {
2220                         gint clen;
2221                         guint ilen;
2222                         gchar cb[MB_CUR_MAX];
2223
2224 #ifdef WRAP_DEBUG
2225                         printf("found CR at %d next line is ", cur_pos);
2226                         dump_text(text, cur_pos + 1, tlen, 1);
2227 #endif
2228                         /* if it's just quotation + newline skip it */
2229                         if (i_len && (cur_pos + 1 < tlen)) {
2230                                 /* check if text at new line matches indent */
2231                                 ilen =  gtkut_text_str_compare_n
2232                                         (text, cur_pos + 1, p_pos, i_len, tlen);
2233                                 if (cur_pos + ilen < tlen) {
2234                                         GET_CHAR(cur_pos + ilen + 1, cb, clen);
2235                                         /* no need to join the lines */
2236                                         if (clen == 1 && cb[0] == '\n')
2237                                                 do_delete = FALSE;
2238                                 }
2239                         /* if it's just newline skip it */
2240                         } else if (do_delete && (cur_pos + 1 < tlen)) {
2241                                 GET_CHAR(cur_pos + 1, cb, clen);
2242                                 /* no need to join the lines */
2243                                 if (clen == 1 && cb[0] == '\n')
2244                                         do_delete = FALSE;
2245                         }
2246
2247 #ifdef WRAP_DEBUG
2248                         printf("qlen=%d l_len=%d wrap_len=%d do_del=%d\n",
2249                                 qlen, line_len, linewrap_len, do_delete);
2250 #endif
2251                         /* should we delete to perform smart wrapping */
2252                         if (line_len < linewrap_len && do_delete) {
2253                                 /* get rid of newline */
2254                                 gtk_stext_set_point(text, cur_pos);
2255                                 gtk_stext_forward_delete(text, 1);
2256                                 tlen--;
2257
2258                                 /* if text starts with quote fmt or with
2259                                    indent string, delete them */
2260                                 if (i_len) {
2261                                         ilen =  gtkut_text_str_compare_n
2262                                                 (text, cur_pos, p_pos, i_len,
2263                                                  tlen);
2264                                         if (ilen) {
2265                                                 gtk_stext_forward_delete(text,
2266                                                                          ilen);
2267                                                 tlen -= ilen;
2268                                         }
2269                                 } else if (qlen) {
2270                                         if (gtkut_text_str_compare
2271                                             (text, cur_pos, tlen, qfmt)) {
2272                                                 gtk_stext_forward_delete
2273                                                         (text, qlen);
2274                                                 tlen -= qlen;
2275                                         }
2276                                 }
2277
2278                                 GET_CHAR(cur_pos, cb, clen);
2279
2280                                 /* insert space if it's alphanumeric */
2281                                 if ((cur_pos != line_pos) &&
2282                                     ((clen > 1) || isalnum(cb[0]))) {
2283                                         gtk_stext_insert(text, NULL, NULL,
2284                                                         NULL, " ", 1);
2285                                         /* gtk_text_compact_buffer(text); */
2286                                         tlen++;
2287                                 }
2288
2289                                 /* and start over with current line */
2290                                 cur_pos = p_pos - 1;
2291                                 line_pos = cur_pos;
2292                                 line_len = cur_len = 0;
2293                                 qlen = 0;
2294                                 do_delete = FALSE;
2295                                 is_new_line = TRUE;
2296 #ifdef WRAP_DEBUG
2297                                 printf("after delete l_pos=");
2298                                 dump_text(text, line_pos, tlen, 1);
2299 #endif
2300                                 continue;
2301                         }
2302
2303                         /* mark new line beginning */
2304                         line_pos = cur_pos + 1;
2305                         line_len = cur_len = 0;
2306                         qlen = 0;
2307                         do_delete = FALSE;
2308                         is_new_line = TRUE;
2309                         continue;
2310                 }
2311
2312                 if (ch_len < 0) {
2313                         cbuf[0] = '\0';
2314                         ch_len = 1;
2315                 }
2316
2317                 /* possible line break */
2318                 if (ch_len == 1 && isspace(*cbuf)) {
2319                         line_pos = cur_pos + 1;
2320                         line_len = cur_len + ch_len;
2321                 }
2322
2323                 /* are we over wrapping length set in preferences ? */
2324                 if (cur_len + ch_len > linewrap_len) {
2325                         gint clen;
2326
2327 #ifdef WRAP_DEBUG
2328                         printf("should wrap cur_pos=%d ", cur_pos);
2329                         dump_text(text, p_pos, tlen, 1);
2330                         dump_text(text, line_pos, tlen, 1);
2331 #endif
2332                         /* force wrapping if it is one long word but not URL */
2333                         if (p_pos + i_len == line_pos)
2334                                 if (!gtkut_text_is_uri_string
2335                                     (text, line_pos, tlen))
2336                                         line_pos = cur_pos - 1;
2337 #ifdef WRAP_DEBUG
2338                         printf("new line_pos=%d\n", line_pos);
2339 #endif
2340
2341                         GET_CHAR(line_pos - 1, cbuf, clen);
2342
2343                         /* if next character is space delete it */
2344                         if (clen == 1 && isspace(*cbuf)) {
2345                                 if (p_pos + i_len != line_pos ||
2346                                     !gtkut_text_is_uri_string
2347                                         (text, line_pos, tlen)) {
2348                                         gtk_stext_set_point(text, line_pos);
2349                                         gtk_stext_backward_delete(text, 1);
2350                                         tlen--;
2351                                         cur_pos--;
2352                                         line_pos--;
2353                                         cur_len--;
2354                                         line_len--;
2355                                 }
2356                         }
2357
2358                         /* if it is URL at beginning of line don't wrap */
2359                         if (p_pos + i_len == line_pos &&
2360                             gtkut_text_is_uri_string(text, line_pos, tlen)) {
2361 #ifdef WRAP_DEBUG
2362                                 printf("found URL at ");
2363                                 dump_text(text, line_pos, tlen, 1);
2364 #endif
2365                                 continue;
2366                         }
2367
2368                         /* insert CR */
2369                         gtk_stext_set_point(text, line_pos);
2370                         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1);
2371                         /* gtk_stext_compact_buffer(text); */
2372                         tlen++;
2373                         line_pos++;
2374                         /* for loop will increase it */
2375                         cur_pos = line_pos - 1;
2376                         /* start over with current line */
2377                         is_new_line = TRUE;
2378                         line_len = 0;
2379                         cur_len = 0;
2380                         do_delete = TRUE;
2381 #ifdef WRAP_DEBUG
2382                         printf("after CR insert ");
2383                         dump_text(text, line_pos, tlen, 1);
2384                         dump_text(text, cur_pos, tlen, 1);
2385 #endif
2386
2387                         /* should we insert quotation ? */
2388                         if (linewrap_quote && qlen) {
2389                                 /* only if line is not already quoted  */
2390                                 if (!gtkut_text_str_compare
2391                                         (text, line_pos, tlen, qfmt)) {
2392                                         guint ins_len;
2393
2394                                         if (line_pos - p_pos > i_len) {
2395                                                 ins_len = ins_quote
2396                                                         (text, qlen, i_len,
2397                                                          p_pos, tlen, qfmt);
2398
2399                                                 /* gtk_stext_compact_buffer(text); */
2400                                                 tlen += ins_len;
2401                                         }
2402 #ifdef WRAP_DEBUG
2403                                         printf("after quote insert ");
2404                                         dump_text(text, line_pos, tlen, 1);
2405 #endif
2406                                 }
2407                         }
2408                         continue;
2409                 }
2410
2411                 if (ch_len > 1) {
2412                         line_pos = cur_pos + 1;
2413                         line_len = cur_len + ch_len;
2414                 }
2415                 /* advance to next character in buffer */
2416                 cur_len += ch_len;
2417         }
2418
2419         gtk_stext_thaw(text);
2420 }
2421 #undef GET_CHAR
2422
2423 static void compose_set_title(Compose *compose)
2424 {
2425         gchar *str;
2426         gchar *edited;
2427
2428         edited = compose->modified ? _(" [Edited]") : "";
2429         if (compose->account && compose->account->address)
2430                 str = g_strdup_printf(_("%s - Compose message%s"),
2431                                       compose->account->address, edited);
2432         else
2433                 str = g_strdup_printf(_("Compose message%s"), edited);
2434         gtk_window_set_title(GTK_WINDOW(compose->window), str);
2435         g_free(str);
2436 }
2437
2438 /**
2439  * compose_current_mail_account:
2440  * 
2441  * Find a current mail account (the currently selected account, or the
2442  * default account, if a news account is currently selected).  If a
2443  * mail account cannot be found, display an error message.
2444  * 
2445  * Return value: Mail account, or NULL if not found.
2446  **/
2447 static PrefsAccount *
2448 compose_current_mail_account(void)
2449 {
2450         PrefsAccount *ac;
2451
2452         if (cur_account && cur_account->protocol != A_NNTP)
2453                 ac = cur_account;
2454         else {
2455                 ac = account_get_default();
2456                 if (!ac || ac->protocol == A_NNTP) {
2457                         alertpanel_error(_("Account for sending mail is not specified.\n"
2458                                            "Please select a mail account before sending."));
2459                         return NULL;
2460                 }
2461         }
2462         return ac;
2463 }
2464
2465 gboolean compose_check_for_valid_recipient(Compose *compose) {
2466         gchar *recipient_headers_mail[] = {"To:", "Cc:", "Bcc:", NULL};
2467         gchar *recipient_headers_news[] = {"Newsgroups:", NULL};
2468         gboolean recipient_found = FALSE;
2469         GSList *list;
2470         gchar **strptr;
2471
2472         /* free to and newsgroup list */
2473         slist_free_strings(compose->to_list);
2474         g_slist_free(compose->to_list);
2475         compose->to_list = NULL;
2476                         
2477         slist_free_strings(compose->newsgroup_list);
2478         g_slist_free(compose->newsgroup_list);
2479         compose->newsgroup_list = NULL;
2480
2481         /* search header entries for to and newsgroup entries */
2482         for(list = compose->header_list; list; list = list->next) {
2483                 gchar *header;
2484                 gchar *entry;
2485                 header = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(((ComposeHeaderEntry *)list->data)->combo)->entry));
2486                 entry = gtk_editable_get_chars(GTK_EDITABLE(((ComposeHeaderEntry *)list->data)->entry), 0, -1);
2487                 g_strstrip(entry);
2488                 if(entry[0] != '\0') {
2489                         for(strptr = recipient_headers_mail; *strptr != NULL; strptr++) {
2490                                 if(!strcmp(header, (prefs_common.trans_hdr ? gettext(*strptr) : *strptr))) {
2491                                         compose->to_list = address_list_append(compose->to_list, entry);
2492                                         recipient_found = TRUE;
2493                                 }
2494                         }
2495                         for(strptr = recipient_headers_news; *strptr != NULL; strptr++) {
2496                                 if(!strcmp(header, (prefs_common.trans_hdr ? gettext(*strptr) : *strptr))) {
2497                                         compose->newsgroup_list = newsgroup_list_append(compose->newsgroup_list, entry);
2498                                         recipient_found = TRUE;
2499                                 }
2500                         }
2501                 }
2502                 g_free(entry);
2503         }
2504         return recipient_found;
2505 }
2506
2507 gint compose_send(Compose *compose)
2508 {
2509         gint msgnum;
2510         FolderItem *folder;
2511         gint val;
2512
2513         val = compose_queue(compose, &msgnum, &folder);
2514         if (val) {
2515                 alertpanel_error(_("Could not queue message for sending"));
2516                 return -1;
2517         }
2518         
2519         val = procmsg_send_message_queue(folder_item_fetch_msg(folder, msgnum));
2520         if(!val) {
2521                 folder_item_remove_msg(folder, msgnum);
2522                 folderview_update_item(folder, TRUE);
2523         }
2524
2525         return val;
2526 }
2527
2528 #if 0 /* compose restructure */
2529 gint compose_send(Compose *compose)
2530 {
2531         gchar tmp[MAXPATHLEN + 1];
2532         gint ok = 0;
2533         static gboolean lock = FALSE;
2534
2535         if (lock) return 1;
2536
2537         g_return_val_if_fail(compose->account != NULL, -1);
2538         g_return_val_if_fail(compose->orig_account != NULL, -1);
2539
2540         lock = TRUE;
2541
2542         if(!compose_check_for_valid_recipient(compose)) {
2543                 alertpanel_error(_("Recipient is not specified."));
2544                 lock = FALSE;
2545                 return 1;
2546         }
2547
2548         /* write to temporary file */
2549         g_snprintf(tmp, sizeof(tmp), "%s%ctmpmsg%d",
2550                    get_rc_dir(), G_DIR_SEPARATOR, (gint)compose);
2551
2552         if (prefs_common.linewrap_at_send)
2553                 compose_wrap_line_all(compose);
2554
2555         if (compose_write_to_file(compose, tmp, FALSE) < 0) {
2556                 lock = FALSE;
2557                 return -1;
2558         }
2559
2560         if (!compose->to_list && !compose->newsgroup_list) {
2561                 g_warning(_("can't get recipient list."));
2562                 unlink(tmp);
2563                 lock = FALSE;
2564                 return -1;
2565         }
2566
2567         if (compose->to_list) {
2568                 PrefsAccount *ac;
2569
2570 #if 0 /* NEW COMPOSE GUI */
2571                 if (compose->account->protocol != A_NNTP)
2572                         ac = compose->account;
2573                 else if (compose->orig_account->protocol != A_NNTP)
2574                         ac = compose->orig_account;
2575                 else if (cur_account && cur_account->protocol != A_NNTP)
2576                         ac = cur_account;
2577                 else {
2578                         ac = compose_current_mail_account();
2579                         if (!ac) {
2580                                 unlink(tmp);
2581                                 lock = FALSE;
2582                                 return -1;
2583                         }
2584                 }
2585 #endif
2586                 ac = compose->account;
2587
2588                 ok = send_message(tmp, ac, compose->to_list);
2589                 statusbar_pop_all();
2590         }
2591
2592         if (ok == 0 && compose->newsgroup_list) {
2593                 Folder *folder;
2594
2595                 if (compose->account->protocol == A_NNTP)
2596                         folder = FOLDER(compose->account->folder);
2597                 else
2598                         folder = FOLDER(compose->orig_account->folder);
2599
2600                 ok = news_post(folder, tmp);
2601                 if (ok < 0) {
2602                         alertpanel_error(_("Error occurred while posting the message to %s ."),
2603                                          compose->account->nntp_server);
2604                         unlink(tmp);
2605                         lock = FALSE;
2606                         return -1;
2607                 }
2608         }
2609
2610         /* queue message if failed to send */
2611         if (ok < 0) {
2612                 if (prefs_common.queue_msg) {
2613                         AlertValue val;
2614
2615                         val = alertpanel
2616                                 (_("Queueing"),
2617                                  _("Error occurred while sending the message.\n"
2618                                    "Put this message into queue folder?"),
2619                                  _("OK"), _("Cancel"), NULL);
2620                         if (G_ALERTDEFAULT == val) {
2621                                 ok = compose_queue(compose, tmp);
2622                                 if (ok < 0)
2623                                         alertpanel_error(_("Can't queue the message."));
2624                         }
2625                 } else
2626                         alertpanel_error(_("Error occurred while sending the message."));
2627         } else {
2628                 if (compose->mode == COMPOSE_REEDIT) {
2629                         compose_remove_reedit_target(compose);
2630                         if (compose->targetinfo)
2631                                 folderview_update_item
2632                                         (compose->targetinfo->folder, TRUE);
2633                 }
2634         }
2635
2636         /* save message to outbox */
2637         if (ok == 0 && prefs_common.savemsg) {
2638                 if (compose_save_to_outbox(compose, tmp) < 0)
2639                         alertpanel_error
2640                                 (_("Can't save the message to outbox."));
2641         }
2642
2643         unlink(tmp);
2644         lock = FALSE;
2645         return ok;
2646 }
2647 #endif
2648
2649 static gboolean compose_use_attach(Compose *compose) {
2650     return(gtk_clist_get_row_data(GTK_CLIST(compose->attach_clist), 0) != NULL);
2651 }
2652
2653 static gint compose_bounce_write_headers_from_headerlist(Compose *compose, 
2654                                                          FILE *fp)
2655 {
2656         gchar buf[BUFFSIZE];
2657         gchar *str;
2658         gboolean first_address;
2659         GSList *list;
2660         ComposeHeaderEntry *headerentry;
2661         gchar *headerentryname;
2662         gchar *header_w_colon;
2663         gchar *cc_hdr;
2664         gchar *to_hdr;
2665
2666         debug_print(_("Writing bounce header\n"));
2667
2668         header_w_colon = g_strconcat("To:", NULL);
2669         to_hdr = (prefs_common.trans_hdr ? gettext(header_w_colon) : header_w_colon);
2670         header_w_colon = g_strconcat("Cc:", NULL);
2671         cc_hdr = (prefs_common.trans_hdr ? gettext(header_w_colon) : header_w_colon);
2672         
2673         first_address = TRUE;
2674         for(list = compose->header_list; list; list = list->next) {
2675                 headerentry = ((ComposeHeaderEntry *)list->data);
2676                 headerentryname = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry));
2677
2678                 if(g_strcasecmp(headerentryname, cc_hdr) == 0 
2679                    || g_strcasecmp(headerentryname, to_hdr) == 0) {
2680                         str = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
2681                         Xstrdup_a(str, str, return -1);
2682                         g_strstrip(str);
2683                         if(str[0] != '\0') {
2684                                 compose_convert_header
2685                                         (buf, sizeof(buf), str,
2686                                         strlen("Resent-To") + 2);
2687                                 if(first_address) {
2688                                         fprintf(fp, "Resent-To: ");
2689                                         first_address = FALSE;
2690                                 } else {
2691                                         fprintf(fp, ",");
2692                                 }
2693                                 fprintf(fp, "%s", buf);
2694                         }
2695                 }
2696         }
2697         /* if(!first_address) { */
2698         fprintf(fp, "\n");
2699         /* } */
2700
2701         return(0);
2702 }
2703
2704 static gint compose_bounce_write_headers(Compose *compose, FILE *fp)
2705 {
2706         gchar buf[BUFFSIZE];
2707         gchar *str;
2708         /* struct utsname utsbuf; */
2709
2710         g_return_val_if_fail(fp != NULL, -1);
2711         g_return_val_if_fail(compose->account != NULL, -1);
2712         g_return_val_if_fail(compose->account->address != NULL, -1);
2713
2714         /* Date */
2715         get_rfc822_date(buf, sizeof(buf));
2716         fprintf(fp, "Resent-Date: %s\n", buf);
2717
2718         /* From */
2719         if (compose->account->name && *compose->account->name) {
2720                 compose_convert_header
2721                         (buf, sizeof(buf), compose->account->name,
2722                          strlen("From: "));
2723                 fprintf(fp, "Resent-From: %s <%s>\n",
2724                         buf, compose->account->address);
2725         } else
2726                 fprintf(fp, "Resent-From: %s\n", compose->account->address);
2727
2728         /* To */
2729         compose_bounce_write_headers_from_headerlist(compose, fp);
2730
2731         /* separator between header and body */
2732         fputs("\n", fp);
2733
2734         return 0;
2735 }
2736
2737 static gint compose_bounce_write_to_file(Compose *compose, const gchar *file)
2738 {
2739         FILE *fp;
2740         FILE *fdest;
2741         size_t len;
2742         gchar buf[BUFFSIZE];
2743
2744         if ((fp = fopen(compose->bounce_filename, "r")) == NULL) {
2745                 FILE_OP_ERROR(file, "fopen");
2746                 return -1;
2747         }
2748
2749         if ((fdest = fopen(file, "w")) == NULL) {
2750                 FILE_OP_ERROR(file, "fopen");
2751                 fclose(fp);
2752                 return -1;
2753         }
2754
2755         /* chmod for security */
2756         if (change_file_mode_rw(fdest, file) < 0) {
2757                 FILE_OP_ERROR(file, "chmod");
2758                 g_warning(_("can't change file mode\n"));
2759         }
2760
2761         while (procheader_get_unfolded_line(buf, sizeof(buf), fp)) {
2762                 /* should filter returnpath, delivered-to */
2763                 if ((g_strncasecmp(buf, "Return-Path:",
2764                                    strlen("Return-Path:")) == 0)
2765                     || (g_strncasecmp(buf, "Delivered-To:",
2766                                       strlen("Delivered-To:")) == 0))
2767                         continue;
2768
2769                 if (fputs(buf, fdest) == -1)
2770                         goto error;
2771
2772                 if (g_strncasecmp(buf, "From:", strlen("From:")) == 0) {
2773                         fputs(" (by way of ", fdest);
2774                         if (compose->account->name
2775                             && *compose->account->name) {
2776                                 compose_convert_header
2777                                         (buf, sizeof(buf),
2778                                          compose->account->name,
2779                                          strlen("From: "));
2780                                 fprintf(fdest, "%s <%s>",
2781                                         buf, compose->account->address);
2782                         } else
2783                                 fprintf(fdest, "%s",
2784                                         compose->account->address);
2785                         fputs(")", fdest);
2786                 }
2787
2788                 if (fputs("\n", fdest) == -1)
2789                         goto error;
2790         }
2791
2792         compose_bounce_write_headers(compose, fdest);
2793
2794         while ((len = fread(buf, sizeof(gchar), BUFFSIZE, fp)) > 0) {
2795                 if (fwrite(buf, sizeof(gchar), len, fdest) == -1)
2796                         goto error;
2797         }
2798
2799         fclose(fdest);
2800         fclose(fp);
2801
2802         return 0;
2803  error:
2804         fclose(fdest);
2805         fclose(fp);
2806
2807         return -1;
2808 }
2809
2810 static gint compose_write_to_file(Compose *compose, const gchar *file,
2811                                   gboolean is_draft)
2812 {
2813         FILE *fp;
2814         size_t len;
2815         gchar *chars;
2816         gchar *buf;
2817         const gchar *out_codeset;
2818         EncodingType encoding;
2819
2820         if ((fp = fopen(file, "w")) == NULL) {
2821                 FILE_OP_ERROR(file, "fopen");
2822                 return -1;
2823         }
2824
2825         /* chmod for security */
2826         if (change_file_mode_rw(fp, file) < 0) {
2827                 FILE_OP_ERROR(file, "chmod");
2828                 g_warning(_("can't change file mode\n"));
2829         }
2830
2831         /* get all composed text */
2832         chars = gtk_editable_get_chars(GTK_EDITABLE(compose->text), 0, -1);
2833         len = strlen(chars);
2834         if (is_ascii_str(chars)) {
2835                 buf = g_strdup(chars);
2836                 out_codeset = CS_US_ASCII;
2837                 encoding = ENC_7BIT;
2838         } else {
2839                 const gchar *src_codeset;
2840
2841                 out_codeset = conv_get_outgoing_charset_str();
2842                 if (!strcasecmp(out_codeset, CS_US_ASCII))
2843                         out_codeset = CS_ISO_8859_1;
2844                 encoding = procmime_get_encoding_for_charset(out_codeset);
2845
2846                 src_codeset = conv_get_current_charset_str();
2847                 /* if current encoding is US-ASCII, set it the same as
2848                    outgoing one to prevent code conversion failure */
2849                 if (!strcasecmp(src_codeset, CS_US_ASCII))
2850                         src_codeset = out_codeset;
2851
2852                 debug_print("src encoding = %s, out encoding = %s, transfer encoding = %s\n",
2853                             src_codeset, out_codeset, procmime_get_encoding_str(encoding));
2854
2855                 buf = conv_codeset_strdup(chars, src_codeset, out_codeset);
2856                 if (!buf) {
2857                         g_free(chars);
2858                         fclose(fp);
2859                         unlink(file);
2860                         alertpanel_error(_("Can't convert the codeset of the message."));
2861                         return -1;
2862                 }
2863         }
2864         g_free(chars);
2865
2866         /* write headers */
2867         if (compose_write_headers
2868                 (compose, fp, out_codeset, encoding, is_draft) < 0) {
2869                 g_warning(_("can't write headers\n"));
2870                 fclose(fp);
2871                 /* unlink(file); */
2872                 g_free(buf);
2873                 return -1;
2874         }
2875
2876         if (compose_use_attach(compose)) {
2877 #if USE_GPGME
2878             /* This prolog message is ignored by mime software and
2879              * because it would make our signing/encryption task
2880              * tougher, we don't emit it in that case */
2881             if (!compose->use_signing && !compose->use_encryption)
2882 #endif
2883                 fputs("This is a multi-part message in MIME format.\n", fp);
2884
2885                 fprintf(fp, "\n--%s\n", compose->boundary);
2886                 fprintf(fp, "Content-Type: text/plain; charset=%s\n",
2887                         out_codeset);
2888                 fprintf(fp, "Content-Transfer-Encoding: %s\n",
2889                         procmime_get_encoding_str(encoding));
2890                 fputc('\n', fp);
2891         }
2892
2893         /* write body */
2894         len = strlen(buf);
2895         if (encoding == ENC_BASE64) {
2896                 gchar outbuf[B64_BUFFSIZE];
2897                 gint i, l;
2898
2899                 for (i = 0; i < len; i += B64_LINE_SIZE) {
2900                         l = MIN(B64_LINE_SIZE, len - i);
2901                         to64frombits(outbuf, buf + i, l);
2902                         fputs(outbuf, fp);
2903                         fputc('\n', fp);
2904                 }
2905         } else if (fwrite(buf, sizeof(gchar), len, fp) != len) {
2906                 FILE_OP_ERROR(file, "fwrite");
2907                 fclose(fp);
2908                 unlink(file);
2909                 g_free(buf);
2910                 return -1;
2911         }
2912         g_free(buf);
2913
2914         if (compose_use_attach(compose))
2915                 compose_write_attach(compose, fp);
2916
2917         if (fclose(fp) == EOF) {
2918                 FILE_OP_ERROR(file, "fclose");
2919                 unlink(file);
2920                 return -1;
2921         }
2922
2923 #if USE_GPGME
2924         if (compose->use_signing) {
2925                 if (rfc2015_sign(file, compose->account) < 0) {
2926                         unlink(file);
2927                         return -1;
2928                 }
2929         }
2930         if (compose->use_encryption) {
2931                 if (rfc2015_encrypt(file, compose->to_list) < 0) {
2932                         unlink(file);
2933                         return -1;
2934                 }
2935         }
2936 #endif /* USE_GPGME */
2937
2938         return 0;
2939 }
2940
2941 static gint compose_write_body_to_file(Compose *compose, const gchar *file)
2942 {
2943         FILE *fp;
2944         size_t len;
2945         gchar *chars;
2946
2947         if ((fp = fopen(file, "w")) == NULL) {
2948                 FILE_OP_ERROR(file, "fopen");
2949                 return -1;
2950         }
2951
2952         /* chmod for security */
2953         if (change_file_mode_rw(fp, file) < 0) {
2954                 FILE_OP_ERROR(file, "chmod");
2955                 g_warning(_("can't change file mode\n"));
2956         }
2957
2958         chars = gtk_editable_get_chars(GTK_EDITABLE(compose->text), 0, -1);
2959
2960         /* write body */
2961         len = strlen(chars);
2962         if (fwrite(chars, sizeof(gchar), len, fp) != len) {
2963                 FILE_OP_ERROR(file, "fwrite");
2964                 g_free(chars);
2965                 fclose(fp);
2966                 unlink(file);
2967                 return -1;
2968         }
2969
2970         g_free(chars);
2971
2972         if (fclose(fp) == EOF) {
2973                 FILE_OP_ERROR(file, "fclose");
2974                 unlink(file);
2975                 return -1;
2976         }
2977         return 0;
2978 }
2979
2980 static gint compose_save_to_outbox(Compose *compose, const gchar *file)
2981 {
2982         FolderItem *outbox;
2983         gchar *path;
2984         gint num;
2985         FILE *fp;
2986
2987         debug_print(_("saving sent message...\n"));
2988
2989         outbox = folder_get_default_outbox();
2990         path = folder_item_get_path(outbox);
2991         if (!is_dir_exist(path))
2992                 make_dir_hier(path);
2993
2994         folder_item_scan(outbox);
2995         if ((num = folder_item_add_msg(outbox, file, FALSE)) < 0) {
2996                 g_free(path);
2997                 g_warning(_("can't save message\n"));
2998                 return -1;
2999         }
3000
3001         if ((fp = procmsg_open_mark_file(path, TRUE)) == NULL)
3002                 g_warning(_("can't open mark file\n"));
3003         else {
3004                 MsgInfo newmsginfo;
3005
3006                 newmsginfo.msgnum = num;
3007                 newmsginfo.flags.perm_flags = 0;
3008                 newmsginfo.flags.tmp_flags = 0;
3009                 procmsg_write_flags(&newmsginfo, fp);
3010                 fclose(fp);
3011         }
3012         g_free(path);
3013
3014         return 0;
3015 }
3016
3017 static gint compose_remove_reedit_target(Compose *compose)
3018 {
3019         FolderItem *item;
3020         MsgInfo *msginfo = compose->targetinfo;
3021
3022         g_return_val_if_fail(compose->mode == COMPOSE_REEDIT, -1);
3023         if (!msginfo) return -1;
3024
3025         item = msginfo->folder;
3026         g_return_val_if_fail(item != NULL, -1);
3027
3028         folder_item_scan(item);
3029         if (procmsg_msg_exist(msginfo) &&
3030             (item->stype == F_DRAFT || item->stype == F_QUEUE)) {
3031                 if (folder_item_remove_msg(item, msginfo->msgnum) < 0) {
3032                         g_warning(_("can't remove the old message\n"));
3033                         return -1;
3034                 }
3035         }
3036
3037         return 0;
3038 }
3039
3040
3041 static gint compose_queue(Compose *compose, gint *msgnum, FolderItem **item)
3042 {
3043         FolderItem *queue;
3044         gchar *tmp, *tmp2, *queue_path;
3045         FILE *fp, *src_fp;
3046         GSList *cur;
3047         gchar buf[BUFFSIZE];
3048         gint num;
3049         static gboolean lock = FALSE;
3050         PrefsAccount *mailac = NULL, *newsac = NULL;
3051         
3052         debug_print(_("queueing message...\n"));
3053         g_return_val_if_fail(compose->account != NULL, -1);
3054         g_return_val_if_fail(compose->orig_account != NULL, -1);
3055
3056         lock = TRUE;
3057         
3058         if(!compose_check_for_valid_recipient(compose)) {
3059                 alertpanel_error(_("Recipient is not specified."));
3060                 lock = FALSE;
3061                 return -1;
3062         }
3063                                                                         
3064         if (!compose->to_list && !compose->newsgroup_list) {
3065                 g_warning(_("can't get recipient list."));
3066                 lock = FALSE;
3067                 return -1;
3068         }
3069
3070         if(compose->to_list) {
3071                 if (compose->account->protocol != A_NNTP)
3072                         mailac = compose->account;
3073                 else if (compose->orig_account->protocol != A_NNTP)
3074                         mailac = compose->orig_account;
3075                 else if (cur_account && cur_account->protocol != A_NNTP)
3076                         mailac = cur_account;
3077                 else if (!(mailac = compose_current_mail_account())) {
3078                         lock = FALSE;
3079                         alertpanel_error(_("No account for sending mails available!"));
3080                         return -1;
3081                 }
3082         }
3083
3084         if(compose->newsgroup_list) {
3085                 if (compose->account->protocol == A_NNTP)
3086                         newsac = compose->account;
3087                 else if(!(newsac = compose->orig_account) || (newsac->protocol != A_NNTP)) {
3088                         lock = FALSE;
3089                         alertpanel_error(_("No account for posting news available!"));
3090                         return -1;
3091                 }                       
3092         }
3093
3094         if (prefs_common.linewrap_at_send)
3095                 compose_wrap_line_all(compose);
3096                         
3097         /* write to temporary file */
3098         tmp2 = g_strdup_printf("%s%ctmp%d", g_get_tmp_dir(),
3099                                       G_DIR_SEPARATOR, (gint)compose);
3100
3101         if (compose->bounce_filename != NULL) {
3102                 if (compose_bounce_write_to_file(compose, tmp2) < 0) {
3103                         unlink(tmp2);
3104                         lock = FALSE;
3105                         return -1;
3106                 }
3107         }
3108         else {
3109                 if (compose_write_to_file(compose, tmp2, FALSE) < 0) {
3110                         unlink(tmp2);
3111                         lock = FALSE;
3112                         return -1;
3113                 }
3114         }
3115
3116         /* add queue header */
3117         tmp = g_strdup_printf("%s%cqueue.%d", g_get_tmp_dir(),
3118                                       G_DIR_SEPARATOR, (gint)compose);
3119         if ((fp = fopen(tmp, "w")) == NULL) {
3120                 FILE_OP_ERROR(tmp, "fopen");
3121                 g_free(tmp);
3122                 return -1;
3123         }
3124         if ((src_fp = fopen(tmp2, "r")) == NULL) {
3125                 FILE_OP_ERROR(tmp2, "fopen");
3126                 fclose(fp);
3127                 unlink(tmp);
3128                 g_free(tmp);
3129                 unlink(tmp2);
3130                 g_free(tmp2);
3131                 return -1;
3132         }
3133         if (change_file_mode_rw(fp, tmp) < 0) {
3134                 FILE_OP_ERROR(tmp, "chmod");
3135                 g_warning(_("can't change file mode\n"));
3136         }
3137
3138         /* queueing variables */
3139         fprintf(fp, "AF:\n");
3140         fprintf(fp, "NF:0\n");
3141         fprintf(fp, "PS:10\n");
3142         fprintf(fp, "SRH:1\n");
3143         fprintf(fp, "SFN:\n");
3144         fprintf(fp, "DSR:\n");
3145         if (compose->msgid)
3146                 fprintf(fp, "MID:<%s>\n", compose->msgid);
3147         else
3148                 fprintf(fp, "MID:\n");
3149         fprintf(fp, "CFG:\n");
3150         fprintf(fp, "PT:0\n");
3151         fprintf(fp, "S:%s\n", compose->account->address);
3152         fprintf(fp, "RQ:\n");
3153         if (mailac)
3154                 fprintf(fp, "SSV:%s\n", mailac->smtp_server);
3155         else
3156                 fprintf(fp, "SSV:\n");
3157         if (newsac)
3158                 fprintf(fp, "NSV:%s\n", newsac->nntp_server);
3159         else
3160                 fprintf(fp, "NSV:\n");
3161         fprintf(fp, "SSH:\n");
3162         /* write recepient list */
3163         fprintf(fp, "R:");
3164         if(compose->to_list) {
3165                 fprintf(fp, "<%s>", (gchar *)compose->to_list->data);
3166                 for (cur = compose->to_list->next; cur != NULL; cur = cur->next)
3167                         fprintf(fp, ",<%s>", (gchar *)cur->data);
3168         }
3169         fprintf(fp, "\n");
3170         /* write newsgroup list */
3171         fprintf(fp, "NG:");
3172         if(compose->newsgroup_list) {
3173                 fprintf(fp, "%s", (gchar *)compose->newsgroup_list->data);
3174                 for (cur = compose->newsgroup_list->next; cur != NULL; cur = cur->next)
3175                         fprintf(fp, ",%s", (gchar *)cur->data);
3176         }
3177         fprintf(fp, "\n");
3178         /* Sylpheed account IDs */
3179         if(mailac) {
3180                 fprintf(fp, "MAID:%d\n", mailac->account_id);
3181         }
3182         if(newsac) {
3183                 fprintf(fp, "NAID:%d\n", newsac->account_id);
3184         }
3185         /* Save copy folder */
3186         if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn))) {
3187                 gchar *str;
3188                 
3189                 str = gtk_editable_get_chars(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
3190                 fprintf(fp, "SCF:%s\n", str);
3191                 g_free(str);
3192         }
3193         fprintf(fp, "\n");
3194
3195         while (fgets(buf, sizeof(buf), src_fp) != NULL) {
3196                 if (fputs(buf, fp) == EOF) {
3197                         FILE_OP_ERROR(tmp, "fputs");
3198                         fclose(fp);
3199                         fclose(src_fp);
3200                         unlink(tmp);
3201                         g_free(tmp);
3202                         unlink(tmp2);
3203                         g_free(tmp2);
3204                         return -1;
3205                 }
3206         }
3207         fclose(src_fp);
3208         if (fclose(fp) == EOF) {
3209                 FILE_OP_ERROR(tmp, "fclose");
3210                 unlink(tmp);
3211                 g_free(tmp);
3212                 unlink(tmp2);
3213                 g_free(tmp2);
3214                 return -1;
3215         }
3216                                                 
3217         /* queue message */
3218         queue = folder_get_default_queue();
3219
3220         folder_item_scan(queue);
3221         queue_path = folder_item_get_path(queue);
3222         if (!is_dir_exist(queue_path))
3223                 make_dir_hier(queue_path);
3224         if ((num = folder_item_add_msg(queue, tmp, TRUE)) < 0) {
3225                 g_warning(_("can't queue the message\n"));
3226                 unlink(tmp);
3227                 g_free(tmp);
3228                 g_free(queue_path);
3229                 return -1;
3230         }
3231         unlink(tmp);
3232         g_free(tmp);
3233         unlink(tmp2);
3234         g_free(tmp2);
3235
3236         if (compose->mode == COMPOSE_REEDIT) {
3237                 compose_remove_reedit_target(compose);
3238                 if (compose->targetinfo &&
3239                     compose->targetinfo->folder != queue)
3240                         folderview_update_item
3241                                 (compose->targetinfo->folder, TRUE);
3242         }
3243
3244         if ((fp = procmsg_open_mark_file(queue_path, TRUE)) == NULL)
3245                 g_warning(_("can't open mark file\n"));
3246         else {
3247                 MsgInfo newmsginfo;
3248
3249                 newmsginfo.msgnum = num;
3250                 newmsginfo.flags.perm_flags = 0;
3251                 newmsginfo.flags.tmp_flags = 0;
3252                 procmsg_write_flags(&newmsginfo, fp);
3253                 fclose(fp);
3254         }
3255         g_free(queue_path);
3256
3257         folder_item_scan(queue);
3258         folderview_update_item(queue, TRUE);
3259
3260         if((msgnum != NULL) && (item != NULL)) {
3261                 *msgnum = num;
3262                 *item = queue;
3263         }
3264
3265         return 0;
3266 }
3267
3268 static void compose_write_attach(Compose *compose, FILE *fp)
3269 {
3270         AttachInfo *ainfo;
3271         GtkCList *clist = GTK_CLIST(compose->attach_clist);
3272         gint row;
3273         FILE *attach_fp;
3274         gchar filename[BUFFSIZE];
3275         gint len;
3276
3277         for (row = 0; (ainfo = gtk_clist_get_row_data(clist, row)) != NULL;
3278              row++) {
3279                 if ((attach_fp = fopen(ainfo->file, "r")) == NULL) {
3280                         g_warning(_("Can't open file %s\n"), ainfo->file);
3281                         continue;
3282                 }
3283
3284                 fprintf(fp, "\n--%s\n", compose->boundary);
3285
3286                 if (!strcmp2(ainfo->content_type, "message/rfc822")) {
3287                         fprintf(fp, "Content-Type: %s\n", ainfo->content_type);
3288                         fprintf(fp, "Content-Disposition: inline\n");
3289                 } else {
3290                         conv_encode_header(filename, sizeof(filename),
3291                                            ainfo->name, 12);
3292                         fprintf(fp, "Content-Type: %s;\n"
3293                                     " name=\"%s\"\n",
3294                                 ainfo->content_type, filename);
3295                         fprintf(fp, "Content-Disposition: attachment;\n"
3296                                     " filename=\"%s\"\n", filename);
3297                 }
3298
3299                 fprintf(fp, "Content-Transfer-Encoding: %s\n\n",
3300                         procmime_get_encoding_str(ainfo->encoding));
3301
3302                 if (ainfo->encoding == ENC_7BIT) {
3303                         gchar buf[BUFFSIZE];
3304
3305                         while (fgets(buf, sizeof(buf), attach_fp) != NULL) {
3306                                 strcrchomp(buf);
3307                                 fputs(buf, fp);
3308                         }
3309                 } else {
3310                         gchar inbuf[B64_LINE_SIZE], outbuf[B64_BUFFSIZE];
3311
3312                         while ((len = fread(inbuf, sizeof(gchar),
3313                                             B64_LINE_SIZE, attach_fp))
3314                                == B64_LINE_SIZE) {
3315                                 to64frombits(outbuf, inbuf, B64_LINE_SIZE);
3316                                 fputs(outbuf, fp);
3317                                 fputc('\n', fp);
3318                         }
3319                         if (len > 0 && feof(attach_fp)) {
3320                                 to64frombits(outbuf, inbuf, len);
3321                                 fputs(outbuf, fp);
3322                                 fputc('\n', fp);
3323                         }
3324                 }
3325
3326                 fclose(attach_fp);
3327         }
3328
3329         fprintf(fp, "\n--%s--\n", compose->boundary);
3330 }
3331
3332 #define IS_IN_CUSTOM_HEADER(header) \
3333         (compose->account->add_customhdr && \
3334          custom_header_find(compose->account->customhdr_list, header) != NULL)
3335
3336 static gint compose_write_headers_from_headerlist(Compose *compose, 
3337                                                   FILE *fp, 
3338                                                   gchar *header)
3339 {
3340         gchar buf[BUFFSIZE];
3341         gchar *str, *header_w_colon, *trans_hdr;
3342         gboolean first_address;
3343         GSList *list;
3344         ComposeHeaderEntry *headerentry;
3345         gchar * headerentryname;
3346
3347         if (IS_IN_CUSTOM_HEADER(header)) {
3348                 return 0;
3349         }
3350
3351         debug_print(_("Writing %s-header\n"), header);
3352
3353         header_w_colon = g_strconcat(header, ":", NULL);
3354         trans_hdr = (prefs_common.trans_hdr ? gettext(header_w_colon) : header_w_colon);
3355
3356         first_address = TRUE;
3357         for(list = compose->header_list; list; list = list->next) {
3358                 headerentry = ((ComposeHeaderEntry *)list->data);
3359                 headerentryname = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry));
3360
3361                 if(!g_strcasecmp(trans_hdr, headerentryname)) {
3362                         str = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
3363                         Xstrdup_a(str, str, return -1);
3364                         g_strstrip(str);
3365                         if(str[0] != '\0') {
3366                                 compose_convert_header
3367                                         (buf, sizeof(buf), str,
3368                                         strlen(header) + 2);
3369                                 if(first_address) {
3370                                         fprintf(fp, "%s: ", header);
3371                                         first_address = FALSE;
3372                                 } else {
3373                                         fprintf(fp, ",");
3374                                 }
3375                                 fprintf(fp, "%s", buf);
3376                         }
3377                 }
3378         }
3379         if(!first_address) {
3380                 fprintf(fp, "\n");
3381         }
3382
3383         g_free(header_w_colon);
3384
3385         return(0);
3386 }
3387
3388 static gint compose_write_headers(Compose *compose, FILE *fp,
3389                                   const gchar *charset, EncodingType encoding,
3390                                   gboolean is_draft)
3391 {
3392         gchar buf[BUFFSIZE];
3393         gchar *str;
3394         /* struct utsname utsbuf; */
3395
3396         g_return_val_if_fail(fp != NULL, -1);
3397         g_return_val_if_fail(charset != NULL, -1);
3398         g_return_val_if_fail(compose->account != NULL, -1);
3399         g_return_val_if_fail(compose->account->address != NULL, -1);
3400
3401         /* Date */
3402         if (compose->account->add_date) {
3403                 get_rfc822_date(buf, sizeof(buf));
3404                 fprintf(fp, "Date: %s\n", buf);
3405         }
3406
3407         /* From */
3408         if (!IS_IN_CUSTOM_HEADER("From")) {
3409                 if (compose->account->name && *compose->account->name) {
3410                         compose_convert_header
3411                                 (buf, sizeof(buf), compose->account->name,
3412                                  strlen("From: "));
3413                         fprintf(fp, "From: %s <%s>\n",
3414                                 buf, compose->account->address);
3415                 } else
3416                         fprintf(fp, "From: %s\n", compose->account->address);
3417         }
3418         
3419         /* To */
3420         compose_write_headers_from_headerlist(compose, fp, "To");
3421 #if 0 /* NEW COMPOSE GUI */
3422         if (compose->use_to) {
3423                 str = gtk_entry_get_text(GTK_ENTRY(compose->to_entry));
3424                 if (*str != '\0') {
3425                         Xstrdup_a(str, str, return -1);
3426                         g_strstrip(str);
3427                         if (*str != '\0') {
3428                                 compose->to_list = address_list_append
3429                                         (compose->to_list, str);
3430                                 if (!IS_IN_CUSTOM_HEADER("To")) {
3431                                         compose_convert_header
3432                                                 (buf, sizeof(buf), str,
3433                                                  strlen("To: "));
3434                                         fprintf(fp, "To: %s\n", buf);
3435                                 }
3436                         }
3437                 }
3438         }
3439 #endif
3440
3441         /* Newsgroups */
3442         compose_write_headers_from_headerlist(compose, fp, "Newsgroups");
3443 #if 0 /* NEW COMPOSE GUI */
3444         str = gtk_entry_get_text(GTK_ENTRY(compose->newsgroups_entry));
3445         if (*str != '\0') {
3446                 Xstrdup_a(str, str, return -1);
3447                 g_strstrip(str);
3448                 remove_space(str);
3449                 if (*str != '\0') {
3450                         compose->newsgroup_list =
3451                                 newsgroup_list_append(compose->newsgroup_list,
3452                                                       str);
3453                         if (!IS_IN_CUSTOM_HEADER("Newsgroups")) {
3454                                 compose_convert_header(buf, sizeof(buf), str,
3455                                                        strlen("Newsgroups: "));
3456                                 fprintf(fp, "Newsgroups: %s\n", buf);
3457                         }
3458                 }
3459         }
3460 #endif
3461         /* Cc */
3462         compose_write_headers_from_headerlist(compose, fp, "Cc");
3463 #if 0 /* NEW COMPOSE GUI */
3464         if (compose->use_cc) {
3465                 str = gtk_entry_get_text(GTK_ENTRY(compose->cc_entry));
3466                 if (*str != '\0') {
3467                         Xstrdup_a(str, str, return -1);
3468                         g_strstrip(str);
3469                         if (*str != '\0') {
3470                                 compose->to_list = address_list_append
3471                                         (compose->to_list, str);
3472                                 if (!IS_IN_CUSTOM_HEADER("Cc")) {
3473                                         compose_convert_header
3474                                                 (buf, sizeof(buf), str,
3475                                                  strlen("Cc: "));
3476                                         fprintf(fp, "Cc: %s\n", buf);
3477                                 }
3478                         }
3479                 }
3480         }
3481 #endif
3482         /* Bcc */
3483         compose_write_headers_from_headerlist(compose, fp, "Bcc");
3484 #if 0 /* NEW COMPOSE GUI */
3485         if (compose->use_bcc) {
3486                 str = gtk_entry_get_text(GTK_ENTRY(compose->bcc_entry));
3487                 if (*str != '\0') {
3488                         Xstrdup_a(str, str, return -1);
3489                         g_strstrip(str);
3490                         if (*str != '\0') {
3491                                 compose->to_list = address_list_append
3492                                         (compose->to_list, str);
3493                                 compose_convert_header(buf, sizeof(buf), str,
3494                                                        strlen("Bcc: "));
3495                                 fprintf(fp, "Bcc: %s\n", buf);
3496                         }
3497                 }
3498         }
3499 #endif
3500
3501         /* Subject */
3502         str = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
3503         if (*str != '\0' && !IS_IN_CUSTOM_HEADER("Subject")) {
3504                 Xstrdup_a(str, str, return -1);
3505                 g_strstrip(str);
3506                 if (*str != '\0') {
3507                         compose_convert_header(buf, sizeof(buf), str,
3508                                                strlen("Subject: "));
3509                         fprintf(fp, "Subject: %s\n", buf);
3510                 }
3511         }
3512
3513         /* Message-ID */
3514         if (compose->account->gen_msgid) {
3515                 compose_generate_msgid(compose, buf, sizeof(buf));
3516                 fprintf(fp, "Message-Id: <%s>\n", buf);
3517                 compose->msgid = g_strdup(buf);
3518         }
3519
3520         /* In-Reply-To */
3521         if (compose->inreplyto && compose->to_list)
3522                 fprintf(fp, "In-Reply-To: <%s>\n", compose->inreplyto);
3523
3524         /* References */
3525         if (compose->references)
3526                 fprintf(fp, "References: %s\n", compose->references);
3527
3528         /* Followup-To */
3529         compose_write_headers_from_headerlist(compose, fp, "Followup-To");
3530 #if 0 /* NEW COMPOSE GUI */
3531         if (compose->use_followupto && !IS_IN_CUSTOM_HEADER("Followup-To")) {
3532                 str = gtk_entry_get_text(GTK_ENTRY(compose->followup_entry));
3533                 if (*str != '\0') {
3534                         Xstrdup_a(str, str, return -1);
3535                         g_strstrip(str);
3536                         remove_space(str);
3537                         if (*str != '\0') {
3538                                 compose_convert_header(buf, sizeof(buf), str,
3539                                                        strlen("Followup-To: "));
3540                                 fprintf(fp, "Followup-To: %s\n", buf);
3541                         }
3542                 }
3543         }
3544 #endif
3545         /* Reply-To */
3546         compose_write_headers_from_headerlist(compose, fp, "Reply-To");
3547 #if 0 /* NEW COMPOSE GUI */
3548         if (compose->use_replyto && !IS_IN_CUSTOM_HEADER("Reply-To")) {
3549                 str = gtk_entry_get_text(GTK_ENTRY(compose->reply_entry));
3550                 if (*str != '\0') {
3551                         Xstrdup_a(str, str, return -1);
3552                         g_strstrip(str);
3553                         if (*str != '\0') {
3554                                 compose_convert_header(buf, sizeof(buf), str,
3555                                                        strlen("Reply-To: "));
3556                                 fprintf(fp, "Reply-To: %s\n", buf);
3557                         }
3558                 }
3559         }
3560 #endif
3561         /* Organization */
3562         if (compose->account->organization &&
3563             !IS_IN_CUSTOM_HEADER("Organization")) {
3564                 compose_convert_header(buf, sizeof(buf),
3565                                        compose->account->organization,
3566                                        strlen("Organization: "));
3567                 fprintf(fp, "Organization: %s\n", buf);
3568         }
3569
3570         /* Program version and system info */
3571         /* uname(&utsbuf); */
3572         if (g_slist_length(compose->to_list) && !IS_IN_CUSTOM_HEADER("X-Mailer")) {
3573                 fprintf(fp, "X-Mailer: %s (GTK+ %d.%d.%d; %s)\n",
3574                         prog_version,
3575                         gtk_major_version, gtk_minor_version, gtk_micro_version,
3576                         HOST_ALIAS);
3577                         /* utsbuf.sysname, utsbuf.release, utsbuf.machine); */
3578         }
3579         if (g_slist_length(compose->newsgroup_list) && !IS_IN_CUSTOM_HEADER("X-Newsreader")) {
3580                 fprintf(fp, "X-Newsreader: %s (GTK+ %d.%d.%d; %s)\n",
3581                         prog_version,
3582                         gtk_major_version, gtk_minor_version, gtk_micro_version,
3583                         HOST_ALIAS);
3584                         /* utsbuf.sysname, utsbuf.release, utsbuf.machine); */
3585         }
3586
3587         /* custom headers */
3588         if (compose->account->add_customhdr) {
3589                 GSList *cur;
3590
3591                 for (cur = compose->account->customhdr_list; cur != NULL;
3592                      cur = cur->next) {
3593                         CustomHeader *chdr = (CustomHeader *)cur->data;
3594
3595                         if (strcasecmp(chdr->name, "Date")         != 0 &&
3596                             strcasecmp(chdr->name, "From")         != 0 &&
3597                             strcasecmp(chdr->name, "To")           != 0 &&
3598                          /* strcasecmp(chdr->name, "Sender")       != 0 && */
3599                             strcasecmp(chdr->name, "Message-Id")   != 0 &&
3600                             strcasecmp(chdr->name, "In-Reply-To")  != 0 &&
3601                             strcasecmp(chdr->name, "References")   != 0 &&
3602                             strcasecmp(chdr->name, "Mime-Version") != 0 &&
3603                             strcasecmp(chdr->name, "Content-Type") != 0 &&
3604                             strcasecmp(chdr->name, "Content-Transfer-Encoding")
3605                             != 0) {
3606                                 compose_convert_header
3607                                         (buf, sizeof(buf),
3608                                          chdr->value ? chdr->value : "",
3609                                          strlen(chdr->name) + 2);
3610                                 fprintf(fp, "%s: %s\n", chdr->name, buf);
3611                         }
3612                 }
3613         }
3614
3615         /* MIME */
3616         fprintf(fp, "Mime-Version: 1.0\n");
3617         if (compose_use_attach(compose)) {
3618                 get_rfc822_date(buf, sizeof(buf));
3619                 subst_char(buf, ' ', '_');
3620                 subst_char(buf, ',', '_');
3621                 compose->boundary = g_strdup_printf("Multipart_%s_%08x",
3622                                                     buf, (guint)compose);
3623                 fprintf(fp,
3624                         "Content-Type: multipart/mixed;\n"
3625                         " boundary=\"%s\"\n", compose->boundary);
3626         } else {
3627                 fprintf(fp, "Content-Type: text/plain; charset=%s\n", charset);
3628                 fprintf(fp, "Content-Transfer-Encoding: %s\n",
3629                         procmime_get_encoding_str(encoding));
3630         }
3631
3632         /* Request Return Receipt */
3633         if (!IS_IN_CUSTOM_HEADER("Disposition-Notification-To")) {
3634                 if (compose->return_receipt) {
3635                         if (compose->account->name
3636                             && *compose->account->name) {
3637                                 compose_convert_header(buf, sizeof(buf), compose->account->name, strlen("Disposition-Notification-To: "));
3638                                 fprintf(fp, "Disposition-Notification-To: %s <%s>\n", buf, compose->account->address);
3639                         } else
3640                                 fprintf(fp, "Disposition-Notification-To: %s\n", compose->account->address);
3641                 }
3642         }
3643
3644         /* separator between header and body */
3645         fputs("\n", fp);
3646
3647         return 0;
3648 }
3649
3650 #undef IS_IN_CUSTOM_HEADER
3651
3652 static void compose_convert_header(gchar *dest, gint len, gchar *src,
3653                                    gint header_len)
3654 {
3655         g_return_if_fail(src != NULL);
3656         g_return_if_fail(dest != NULL);
3657
3658         if (len < 1) return;
3659
3660         remove_return(src);
3661
3662         if (is_ascii_str(src)) {
3663                 strncpy2(dest, src, len);
3664                 dest[len - 1] = '\0';
3665                 return;
3666         } else
3667                 conv_encode_header(dest, len, src, header_len);
3668 }
3669
3670 static void compose_generate_msgid(Compose *compose, gchar *buf, gint len)
3671 {
3672         struct tm *lt;
3673         time_t t;
3674         gchar *addr;
3675
3676         t = time(NULL);
3677         lt = localtime(&t);
3678
3679         if (compose->account && compose->account->address &&
3680             *compose->account->address) {
3681                 if (strchr(compose->account->address, '@'))
3682                         addr = g_strdup(compose->account->address);
3683                 else
3684                         addr = g_strconcat(compose->account->address, "@",
3685                                            get_domain_name(), NULL);
3686         } else
3687                 addr = g_strconcat(g_get_user_name(), "@", get_domain_name(),
3688                                    NULL);
3689
3690         g_snprintf(buf, len, "%04d%02d%02d%02d%02d%02d.%08x.%s",
3691                    lt->tm_year + 1900, lt->tm_mon + 1,
3692                    lt->tm_mday, lt->tm_hour,
3693                    lt->tm_min, lt->tm_sec,
3694                    (guint)random(), addr);
3695
3696         debug_print(_("generated Message-ID: %s\n"), buf);
3697
3698         g_free(addr);
3699 }
3700
3701
3702 static void compose_add_entry_field(GtkWidget *table, GtkWidget **hbox,
3703                                     GtkWidget **entry, gint *count,
3704                                     const gchar *label_str,
3705                                     gboolean is_addr_entry)
3706 {
3707         GtkWidget *label;
3708
3709         if (GTK_TABLE(table)->nrows < (*count) + 1)
3710                 gtk_table_resize(GTK_TABLE(table), (*count) + 1, 2);
3711
3712         *hbox = gtk_hbox_new(FALSE, 0);
3713         label = gtk_label_new
3714                 (prefs_common.trans_hdr ? gettext(label_str) : label_str);
3715         gtk_box_pack_end(GTK_BOX(*hbox), label, FALSE, FALSE, 0);
3716         gtk_table_attach(GTK_TABLE(table), *hbox, 0, 1, *count, (*count) + 1,
3717                          GTK_FILL, 0, 2, 0);
3718         *entry = gtk_entry_new_with_max_length(MAX_ENTRY_LENGTH);
3719         gtk_table_attach
3720                 (GTK_TABLE(table), *entry, 1, 2, *count, (*count) + 1, GTK_FILL | GTK_EXPAND, GTK_SHRINK, 0, 0);
3721 #if 0 /* NEW COMPOSE GUI */
3722         if (GTK_TABLE(table)->nrows > (*count) + 1)
3723                 gtk_table_set_row_spacing(GTK_TABLE(table), *count, 4);
3724 #endif
3725
3726         if (is_addr_entry)
3727                 address_completion_register_entry(GTK_ENTRY(*entry));
3728
3729         (*count)++;
3730 }
3731
3732 static void compose_create_header_entry(Compose *compose) 
3733 {
3734         gchar *headers[] = {"To:", "Cc:", "Bcc:", "Newsgroups:", "Reply-To:", "Followup-To:", NULL};
3735
3736         GtkWidget *combo;
3737         GtkWidget *entry;
3738         GList *combo_list = NULL;
3739         gchar **string, *header;
3740         ComposeHeaderEntry *headerentry;
3741
3742         headerentry = g_new0(ComposeHeaderEntry, 1);
3743
3744         /* Combo box */
3745         combo = gtk_combo_new();
3746         string = headers; 
3747         while(*string != NULL) {
3748             combo_list = g_list_append(combo_list, (prefs_common.trans_hdr ? gettext(*string) : *string));
3749             string++;
3750         }
3751         gtk_combo_set_popdown_strings(GTK_COMBO(combo), combo_list);
3752         g_list_free(combo_list);
3753         gtk_editable_set_editable(GTK_EDITABLE(GTK_COMBO(combo)->entry), FALSE);
3754         gtk_widget_show(combo);
3755         gtk_table_attach(GTK_TABLE(compose->header_table), combo, 0, 1, compose->header_nextrow, compose->header_nextrow+1, GTK_SHRINK, GTK_FILL, 0, 0);
3756         if(compose->header_last) {      
3757                 header = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry));
3758         } else {
3759                 switch(compose->account->protocol) {
3760                         case A_NNTP:
3761                                 header = prefs_common.trans_hdr ? _("Newsgroups:") : "Newsgroups:";
3762                                 break;
3763                         default:
3764                                 header = prefs_common.trans_hdr ? _("To:") : "To:";
3765                                 break;
3766                 }                                                                   
3767         }
3768         gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(combo)->entry), header);
3769
3770         /* Entry field */
3771         entry = gtk_entry_new(); 
3772         gtk_widget_show(entry);
3773         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);
3774
3775         gtk_signal_connect(GTK_OBJECT(entry), "key-press-event", GTK_SIGNAL_FUNC(compose_headerentry_key_press_event_cb), headerentry);
3776         gtk_signal_connect(GTK_OBJECT(entry), "changed", GTK_SIGNAL_FUNC(compose_headerentry_changed_cb), headerentry);
3777
3778         address_completion_register_entry(GTK_ENTRY(entry));
3779
3780         headerentry->compose = compose;
3781         headerentry->combo = combo;
3782         headerentry->entry = entry;
3783         headerentry->headernum = compose->header_nextrow;
3784
3785         compose->header_nextrow++;
3786         compose->header_last = headerentry;
3787 }
3788
3789 static void compose_add_header_entry(Compose *compose, gchar *header, gchar *text) 
3790 {
3791         ComposeHeaderEntry *last_header;
3792         
3793         last_header = compose->header_last;
3794         
3795         gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(last_header->combo)->entry), header);
3796         gtk_entry_set_text(GTK_ENTRY(last_header->entry), text);
3797 }
3798
3799 static GtkWidget *compose_create_header(Compose *compose) 
3800 {
3801         GtkWidget *label;
3802         GtkWidget *from_optmenu_hbox;
3803 #if 0 /* NEW COMPOSE GUI */
3804         GtkWidget *to_entry;
3805         GtkWidget *to_hbox;
3806         GtkWidget *newsgroups_entry;
3807         GtkWidget *newsgroups_hbox;
3808 #endif