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