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