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