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