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