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