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