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