some stuff around composing and forwarding messages
[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
102 #if USE_GPGME
103 #  include "rfc2015.h"
104 #endif
105
106 #include "quote_fmt.h"
107
108 typedef enum
109 {
110         COL_MIMETYPE = 0,
111         COL_SIZE     = 1,
112         COL_NAME     = 2
113 } AttachColumnPos;
114
115 #define N_ATTACH_COLS           3
116
117 #define B64_LINE_SIZE           57
118 #define B64_BUFFSIZE            77
119
120 #define MAX_REFERENCES_LEN      999
121
122 static GdkColor quote_color = {0, 0, 0, 0xbfff};
123
124 static GList *compose_list = NULL;
125
126 static Compose *compose_create                  (PrefsAccount   *account);
127 static void compose_toolbar_create              (Compose        *compose,
128                                                  GtkWidget      *container);
129 static GtkWidget *compose_account_option_menu_create
130                                                 (Compose        *compose);
131 static void compose_destroy                     (Compose        *compose);
132
133 static gint compose_parse_header                (Compose        *compose,
134                                                  MsgInfo        *msginfo);
135 static gchar *compose_parse_references          (const gchar    *ref,
136                                                  const gchar    *msgid);
137 static void compose_quote_file                  (Compose        *compose,
138                                                  MsgInfo        *msginfo,
139                                                  FILE           *fp);
140 static gchar *compose_quote_parse_fmt           (Compose        *compose,
141                                                  MsgInfo        *msginfo,
142                                                  const gchar    *fmt);
143 static void compose_reply_set_entry             (Compose        *compose,
144                                                  MsgInfo        *msginfo,
145                                                  gboolean        to_all,
146                                                  gboolean        to_sender);
147 static void compose_reedit_set_entry            (Compose        *compose,
148                                                  MsgInfo        *msginfo);
149 static void compose_insert_sig                  (Compose        *compose);
150 static void compose_insert_file                 (Compose        *compose,
151                                                  const gchar    *file);
152 static void compose_attach_append               (Compose        *compose,
153                                                  const gchar    *file,
154                                                  ContentType     cnttype);
155 static void compose_attach_append_with_type(Compose *compose,
156                                             const gchar *file,
157                                             const gchar *type,
158                                             ContentType cnttype);
159 static void compose_wrap_line                   (Compose        *compose);
160 static void compose_set_title                   (Compose        *compose);
161
162 static PrefsAccount *compose_current_mail_account(void);
163 /* static gint compose_send                     (Compose        *compose); */
164 static gint compose_write_to_file               (Compose        *compose,
165                                                  const gchar    *file,
166                                                  gboolean        is_draft);
167 static gint compose_write_body_to_file          (Compose        *compose,
168                                                  const gchar    *file);
169 static gint compose_save_to_outbox              (Compose        *compose,
170                                                  const gchar    *file);
171 static gint compose_queue                       (Compose        *compose,
172                                                  const gchar    *file);
173 static void compose_write_attach                (Compose        *compose,
174                                                  FILE           *fp);
175 static gint compose_write_headers               (Compose        *compose,
176                                                  FILE           *fp,
177                                                  const gchar    *charset,
178                                                  EncodingType    encoding,
179                                                  gboolean        is_draft);
180
181 static void compose_convert_header              (gchar          *dest,
182                                                  gint            len,
183                                                  gchar          *src,
184                                                  gint            header_len);
185 static void compose_generate_msgid              (Compose        *compose,
186                                                  gchar          *buf,
187                                                  gint            len);
188
189 static void compose_attach_info_free            (AttachInfo     *ainfo);
190 static void compose_attach_remove_selected      (Compose        *compose);
191
192 static void compose_attach_property             (Compose        *compose);
193 static void compose_attach_property_create      (gboolean       *cancelled);
194 static void attach_property_ok                  (GtkWidget      *widget,
195                                                  gboolean       *cancelled);
196 static void attach_property_cancel              (GtkWidget      *widget,
197                                                  gboolean       *cancelled);
198 static gint attach_property_delete_event        (GtkWidget      *widget,
199                                                  GdkEventAny    *event,
200                                                  gboolean       *cancelled);
201 static void attach_property_key_pressed         (GtkWidget      *widget,
202                                                  GdkEventKey    *event,
203                                                  gboolean       *cancelled);
204
205 static void compose_exec_ext_editor             (Compose           *compose);
206 static gint compose_exec_ext_editor_real        (const gchar       *file);
207 static gboolean compose_ext_editor_kill         (Compose           *compose);
208 static void compose_input_cb                    (gpointer           data,
209                                                  gint               source,
210                                                  GdkInputCondition  condition);
211 static void compose_set_ext_editor_sensitive    (Compose           *compose,
212                                                  gboolean           sensitive);
213
214 static gint calc_cursor_xpos    (GtkSText       *text,
215                                  gint            extra,
216                                  gint            char_width);
217
218 /* callback functions */
219
220 static gboolean compose_edit_size_alloc (GtkEditable    *widget,
221                                          GtkAllocation  *allocation,
222                                          GtkSHRuler     *shruler);
223
224 static void toolbar_send_cb             (GtkWidget      *widget,
225                                          gpointer        data);
226 static void toolbar_send_later_cb       (GtkWidget      *widget,
227                                          gpointer        data);
228 static void toolbar_draft_cb            (GtkWidget      *widget,
229                                          gpointer        data);
230 static void toolbar_insert_cb           (GtkWidget      *widget,
231                                          gpointer        data);
232 static void toolbar_attach_cb           (GtkWidget      *widget,
233                                          gpointer        data);
234 static void toolbar_sig_cb              (GtkWidget      *widget,
235                                          gpointer        data);
236 static void toolbar_ext_editor_cb       (GtkWidget      *widget,
237                                          gpointer        data);
238 static void toolbar_linewrap_cb         (GtkWidget      *widget,
239                                          gpointer        data);
240 static void toolbar_address_cb          (GtkWidget      *widget,
241                                          gpointer        data);
242
243 static void select_account(Compose * compose, PrefsAccount * ac);
244 static void account_activated           (GtkMenuItem    *menuitem,
245                                          gpointer        data);
246
247 static void attach_selected             (GtkCList       *clist,
248                                          gint            row,
249                                          gint            column,
250                                          GdkEvent       *event,
251                                          gpointer        data);
252 static void attach_button_pressed       (GtkWidget      *widget,
253                                          GdkEventButton *event,
254                                          gpointer        data);
255 static void attach_key_pressed          (GtkWidget      *widget,
256                                          GdkEventKey    *event,
257                                          gpointer        data);
258
259 static void compose_send_cb             (gpointer        data,
260                                          guint           action,
261                                          GtkWidget      *widget);
262 static void compose_send_later_cb       (gpointer        data,
263                                          guint           action,
264                                          GtkWidget      *widget);
265
266 static void compose_draft_cb            (gpointer        data,
267                                          guint           action,
268                                          GtkWidget      *widget);
269
270 static void compose_attach_cb           (gpointer        data,
271                                          guint           action,
272                                          GtkWidget      *widget);
273 static void compose_insert_file_cb      (gpointer        data,
274                                          guint           action,
275                                          GtkWidget      *widget);
276
277 static void compose_close_cb            (gpointer        data,
278                                          guint           action,
279                                          GtkWidget      *widget);
280 static void compose_address_cb          (gpointer        data,
281                                          guint           action,
282                                          GtkWidget      *widget);
283
284 static void compose_ext_editor_cb       (gpointer        data,
285                                          guint           action,
286                                          GtkWidget      *widget);
287
288 static gint compose_delete_cb           (GtkWidget      *widget,
289                                          GdkEventAny    *event,
290                                          gpointer        data);
291 static void compose_destroy_cb          (GtkWidget      *widget,
292                                          Compose        *compose);
293
294 static void compose_cut_cb              (Compose        *compose);
295 static void compose_copy_cb             (Compose        *compose);
296 static void compose_paste_cb            (Compose        *compose);
297 static void compose_allsel_cb           (Compose        *compose);
298
299 static void compose_grab_focus_cb       (GtkWidget      *widget,
300                                          Compose        *compose);
301
302 static void compose_changed_cb          (GtkEditable    *editable,
303                                          Compose        *compose);
304 static void compose_button_press_cb     (GtkWidget      *widget,
305                                          GdkEventButton *event,
306                                          Compose        *compose);
307 #if 0
308 static void compose_key_press_cb        (GtkWidget      *widget,
309                                          GdkEventKey    *event,
310                                          Compose        *compose);
311 #endif
312
313 static void compose_toggle_to_cb        (gpointer        data,
314                                          guint           action,
315                                          GtkWidget      *widget);
316 static void compose_toggle_cc_cb        (gpointer        data,
317                                          guint           action,
318                                          GtkWidget      *widget);
319 static void compose_toggle_bcc_cb       (gpointer        data,
320                                          guint           action,
321                                          GtkWidget      *widget);
322 static void compose_toggle_replyto_cb   (gpointer        data,
323                                          guint           action,
324                                          GtkWidget      *widget);
325 static void compose_toggle_followupto_cb(gpointer        data,
326                                          guint           action,
327                                          GtkWidget      *widget);
328 static void compose_toggle_attach_cb    (gpointer        data,
329                                          guint           action,
330                                          GtkWidget      *widget);
331 static void compose_toggle_ruler_cb     (gpointer        data,
332                                          guint           action,
333                                          GtkWidget      *widget);
334 #if USE_GPGME
335 static void compose_toggle_sign_cb      (gpointer        data,
336                                          guint           action,
337                                          GtkWidget      *widget);
338 static void compose_toggle_encrypt_cb   (gpointer        data,
339                                          guint           action,
340                                          GtkWidget      *widget);
341 #endif
342 static void compose_toggle_return_receipt_cb(gpointer data, guint action,
343                                              GtkWidget *widget);
344
345 static void compose_attach_drag_received_cb (GtkWidget          *widget,
346                                              GdkDragContext     *drag_context,
347                                              gint                x,
348                                              gint                y,
349                                              GtkSelectionData   *data,
350                                              guint               info,
351                                              guint               time,
352                                              gpointer            user_data);
353 static void compose_insert_drag_received_cb (GtkWidget          *widget,
354                                              GdkDragContext     *drag_context,
355                                              gint                x,
356                                              gint                y,
357                                              GtkSelectionData   *data,
358                                              guint               info,
359                                              guint               time,
360                                              gpointer            user_data);
361
362 static void to_activated                (GtkWidget      *widget,
363                                          Compose        *compose);
364 static void newsgroups_activated        (GtkWidget      *widget,
365                                          Compose        *compose);
366 static void subject_activated           (GtkWidget      *widget,
367                                          Compose        *compose);
368 static void cc_activated                (GtkWidget      *widget,
369                                          Compose        *compose);
370 static void bcc_activated               (GtkWidget      *widget,
371                                          Compose        *compose);
372 static void replyto_activated           (GtkWidget      *widget,
373                                          Compose        *compose);
374 static void followupto_activated        (GtkWidget      *widget,
375                                          Compose        *compose);
376 static void compose_attach_parts(Compose * compose,
377                                  MsgInfo * msginfo);
378
379 static gchar *compose_quote_fmt         (Compose        *compose,
380                                          MsgInfo        *msginfo,
381                                          const gchar    *fmt,
382                                          const gchar    * qmark);
383
384 static GtkItemFactoryEntry compose_popup_entries[] =
385 {
386         {N_("/_Add..."),        NULL, compose_attach_cb, 0, NULL},
387         {N_("/_Remove"),        NULL, compose_attach_remove_selected, 0, NULL},
388         {N_("/---"),            NULL, NULL, 0, "<Separator>"},
389         {N_("/_Property..."),   NULL, compose_attach_property, 0, NULL}
390 };
391
392 static GtkItemFactoryEntry compose_entries[] =
393 {
394         {N_("/_File"),                          NULL, NULL, 0, "<Branch>"},
395         {N_("/_File/_Attach file"),             "<control>M", compose_attach_cb, 0, NULL},
396         {N_("/_File/_Insert file"),             "<control>I", compose_insert_file_cb, 0, NULL},
397         {N_("/_File/Insert si_gnature"),        "<control>G", compose_insert_sig, 0, NULL},
398         {N_("/_File/---"),                      NULL, NULL, 0, "<Separator>"},
399         {N_("/_File/_Close"),                   "<alt>W", compose_close_cb, 0, NULL},
400
401         {N_("/_Edit"),             NULL,         NULL,  0, "<Branch>"},
402         {N_("/_Edit/_Undo"),       "<control>Z", NULL,  0, NULL},
403         {N_("/_Edit/_Redo"),       "<control>Y", NULL,  0, NULL},
404         {N_("/_Edit/---"),         NULL,         NULL,  0, "<Separator>"},
405         {N_("/_Edit/Cu_t"),        "<control>X", compose_cut_cb,    0, NULL},
406         {N_("/_Edit/_Copy"),       "<control>C", compose_copy_cb,   0, NULL},
407         {N_("/_Edit/_Paste"),      "<control>V", compose_paste_cb,  0, NULL},
408         {N_("/_Edit/Select _all"), "<control>A", compose_allsel_cb, 0, NULL},
409         {N_("/_Edit/---"),         NULL,         NULL,  0, "<Separator>"},
410         {N_("/_Edit/Wrap long _lines"), "<alt>L", compose_wrap_line, 0, NULL},
411         {N_("/_Edit/Edit with e_xternal editor"), "<alt>X",
412                                         compose_ext_editor_cb,  0, NULL},
413
414         {N_("/_Message"),               NULL,           NULL,   0, "<Branch>"},
415         {N_("/_Message/_Send"),         "<shift><control>S",
416                                         compose_send_cb, 0, NULL},
417         {N_("/_Message/Send _later"),   "<shift><alt>S",
418                                         compose_send_later_cb,  0, NULL},
419         {N_("/_Message/Save to _draft folder"),
420                                         "<alt>D",       compose_draft_cb, 0, NULL},
421         {N_("/_Message/---"),           NULL,           NULL,   0, "<Separator>"},
422         {N_("/_Message/_To"),           NULL, compose_toggle_to_cb, 0, "<ToggleItem>"},
423         {N_("/_Message/_Cc"),           NULL, compose_toggle_cc_cb, 0, "<ToggleItem>"},
424         {N_("/_Message/_Bcc"),          NULL, compose_toggle_bcc_cb, 0, "<ToggleItem>"},
425         {N_("/_Message/_Reply to"),     NULL, compose_toggle_replyto_cb, 0, "<ToggleItem>"},
426         {N_("/_Message/---"),           NULL,           NULL,   0, "<Separator>"},
427         {N_("/_Message/_Followup to"),  NULL, compose_toggle_followupto_cb, 0, "<ToggleItem>"},
428         {N_("/_Message/---"),           NULL,           NULL,   0, "<Separator>"},
429         {N_("/_Message/_Attach"),       NULL, compose_toggle_attach_cb, 0, "<ToggleItem>"},
430 #if USE_GPGME
431         {N_("/_Message/---"),           NULL,           NULL,   0, "<Separator>"},
432         {N_("/_Message/Si_gn"),         NULL, compose_toggle_sign_cb, 0, "<ToggleItem>"},
433         {N_("/_Message/_Encrypt"),      NULL, compose_toggle_encrypt_cb, 0, "<ToggleItem>"},
434 #endif /* USE_GPGME */
435         {N_("/_Message/---"),           NULL,           NULL,   0, "<Separator>"},
436         {N_("/_Message/_Request Return Receipt"),       NULL, compose_toggle_return_receipt_cb, 0, "<ToggleItem>"},
437         {N_("/_Tool"),                  NULL, NULL,     0, "<Branch>"},
438         {N_("/_Tool/Show _ruler"),      NULL, compose_toggle_ruler_cb,  0, "<ToggleItem>"},
439         {N_("/_Tool/_Address book"),    "<alt>A",       compose_address_cb, 0, NULL},
440         {N_("/_Help"),                  NULL, NULL,     0, "<LastBranch>"},
441         {N_("/_Help/_About"),           NULL,           about_show,     0, NULL}
442 };
443
444 static GtkTargetEntry compose_mime_types[] =
445 {
446         {"text/uri-list", 0, 0}
447 };
448
449 Compose * compose_new(PrefsAccount *account)
450 {
451         return compose_new_with_recipient(account, NULL);
452 }
453
454 Compose * compose_new_with_recipient(PrefsAccount *account, const gchar *to)
455 {
456         Compose *compose;
457
458         if (!account) account = cur_account;
459         g_return_val_if_fail(account != NULL, NULL);
460
461         compose = compose_create(account);
462         compose->mode = COMPOSE_NEW;
463
464         if (prefs_common.auto_sig)
465                 compose_insert_sig(compose);
466         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
467         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
468
469         if (account->protocol != A_NNTP) {
470                 if (to) {
471                         compose_entry_append(compose, to, COMPOSE_TO);
472                         gtk_widget_grab_focus(compose->subject_entry);
473                 } else
474                         gtk_widget_grab_focus(compose->to_entry);
475         } else {
476                 if (to) {
477                         compose_entry_append(compose, to, COMPOSE_NEWSGROUPS);
478                         gtk_widget_grab_focus(compose->subject_entry);
479                 } else
480                         gtk_widget_grab_focus(compose->newsgroups_entry);
481         }
482
483         return compose;
484 }
485
486 #define CHANGE_FLAGS(msginfo) \
487 { \
488 if (msginfo->folder->folder->change_flags != NULL) \
489 msginfo->folder->folder->change_flags(msginfo->folder->folder, \
490                                       msginfo->folder, \
491                                       msginfo); \
492 }
493
494 void compose_reply(MsgInfo *msginfo, gboolean quote, gboolean to_all,
495                    gboolean ignore_replyto)
496 {
497         Compose *compose;
498         PrefsAccount *account;
499         PrefsAccount *reply_account;
500         GtkSText *text;
501
502         g_return_if_fail(msginfo != NULL);
503         g_return_if_fail(msginfo->folder != NULL);
504
505         account = msginfo->folder->folder->account;
506         if (!account) account = cur_account;
507         g_return_if_fail(account != NULL);
508
509         if (ignore_replyto && account->protocol == A_NNTP) {
510                 reply_account =
511                         account_find_mail_from_address(account->address);
512                 if (!reply_account)
513                         reply_account = compose_current_mail_account();
514                 if (!reply_account)
515                         return;
516         } else
517                 reply_account = account;
518
519         MSG_UNSET_FLAGS(msginfo->flags, MSG_FORWARDED);
520         MSG_SET_FLAGS(msginfo->flags, MSG_REPLIED);
521
522         CHANGE_FLAGS(msginfo);
523
524         compose = compose_create(reply_account);
525         compose->mode = COMPOSE_REPLY;
526
527         if (compose_parse_header(compose, msginfo) < 0) return;
528         compose_reply_set_entry(compose, msginfo, to_all, ignore_replyto);
529
530         text = GTK_STEXT(compose->text);
531         gtk_stext_freeze(text);
532
533         if (quote) {
534                 FILE *fp;
535                 gchar *quote_str;
536
537                 if ((fp = procmime_get_text_part(msginfo)) == NULL)
538                         g_warning(_("Can't get text part\n"));
539                 else {
540                         gchar * qmark;
541
542                         if (prefs_common.quotemark && *prefs_common.quotemark)
543                                 qmark = prefs_common.quotemark;
544                         else
545                                 qmark = "> ";
546
547                         quote_str = compose_quote_fmt(compose, msginfo,
548                                                       prefs_common.quotefmt,
549                                                       qmark);
550
551                         /*
552                         quote_str = compose_quote_parse_fmt
553                                 (compose, msginfo, prefs_common.quotefmt);
554                         */
555
556                         if (quote_str != NULL)
557                                 gtk_stext_insert(text, NULL, NULL, NULL,
558                                                  quote_str, -1);
559                         /*                      g_free(quote_str); */
560                         /* compose_quote_file(compose, msginfo, fp); */
561                         fclose(fp);
562                 }
563         }
564
565         if (prefs_common.auto_sig)
566                 compose_insert_sig(compose);
567         gtk_editable_set_position(GTK_EDITABLE(text), 0);
568         gtk_stext_set_point(text, 0);
569
570         gtk_stext_thaw(text);
571         gtk_widget_grab_focus(compose->text);
572 }
573
574
575 static gchar *procmime_get_file_name(MimeInfo *mimeinfo)
576 {
577         gchar *base;
578         gchar *filename;
579
580         g_return_val_if_fail(mimeinfo != NULL, NULL);
581
582         base = mimeinfo->filename ? mimeinfo->filename
583                 : mimeinfo->name ? mimeinfo->name : NULL;
584
585         if (MIME_TEXT_HTML == mimeinfo->mime_type && base == NULL){
586                 filename = g_strdup_printf("%s%smimetmp%i.html",
587                                            get_mime_tmp_dir(),
588                                            G_DIR_SEPARATOR_S,
589                                            mimeinfo);
590                 return filename;
591         }
592         else {
593                 base = base ? base : "";
594                 base = g_basename(base);
595                 if (*base == '\0') {
596                         filename = g_strdup_printf("%s%smimetmp%i",
597                                                    get_mime_tmp_dir(),
598                                                    G_DIR_SEPARATOR_S,
599                                                    mimeinfo);
600                         return filename;
601                 }
602         }
603
604         filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
605                                base, NULL);
606
607         return filename;
608 }
609
610 static gchar * mime_extract_file(gchar * source, MimeInfo *partinfo)
611 {
612         gchar *filename;
613
614         if (!partinfo) return;
615
616         filename = procmime_get_file_name(partinfo);
617
618         if (procmime_get_part(filename, source, partinfo) < 0)
619                 alertpanel_error
620                         (_("Can't get the part of multipart message."));
621
622         return filename;
623 }
624
625 static void compose_attach_parts(Compose * compose,
626                                  MsgInfo * msginfo)
627 {
628
629         FILE *fp;
630         gchar *file;
631         MimeInfo *mimeinfo;
632         MsgInfo *tmpmsginfo;
633         gchar *p;
634         gchar *boundary;
635         gint boundary_len = 0;
636         gchar buf[BUFFSIZE];
637         glong fpos, prev_fpos;
638         gint npart;
639         gchar * source;
640         gchar * filename;
641
642         g_return_if_fail(msginfo != NULL);
643         
644 #if USE_GPGME
645         for (;;) {
646                 if ((fp = procmsg_open_message(msginfo)) == NULL) return;
647                 mimeinfo = procmime_scan_mime_header(fp);
648                 if (!mimeinfo) break;
649
650                 if (!MSG_IS_ENCRYPTED(msginfo->flags) &&
651                     rfc2015_is_encrypted(mimeinfo)) {
652                         MSG_SET_FLAGS(msginfo->flags, MSG_ENCRYPTED);
653                 }
654                 if (MSG_IS_ENCRYPTED(msginfo->flags) &&
655                     !msginfo->plaintext_file  &&
656                     !msginfo->decryption_failed) {
657                         rfc2015_decrypt_message(msginfo, mimeinfo, fp);
658                         if (msginfo->plaintext_file &&
659                             !msginfo->decryption_failed) {
660                                 fclose(fp);
661                                 continue;
662                         }
663                 }
664                 
665                 break;
666         }
667 #else /* !USE_GPGME */
668         if ((fp = procmsg_open_message(msginfo)) == NULL) return;
669         mimeinfo = procmime_scan_mime_header(fp);
670 #endif /* USE_GPGME */
671
672         fclose(fp);
673         if (!mimeinfo) return;
674         if (mimeinfo->mime_type == MIME_TEXT)
675                 return;
676
677         if ((fp = procmsg_open_message(msginfo)) == NULL) return;
678
679         g_return_if_fail(mimeinfo != NULL);
680         g_return_if_fail(mimeinfo->mime_type != MIME_TEXT);
681
682         if (mimeinfo->mime_type == MIME_MULTIPART) {
683                 g_return_if_fail(mimeinfo->boundary != NULL);
684                 g_return_if_fail(mimeinfo->sub == NULL);
685         }
686         g_return_if_fail(fp != NULL);
687
688         boundary = mimeinfo->boundary;
689
690         if (boundary) {
691                 boundary_len = strlen(boundary);
692
693                 /* look for first boundary */
694                 while ((p = fgets(buf, sizeof(buf), fp)) != NULL)
695                         if (IS_BOUNDARY(buf, boundary, boundary_len)) break;
696                 if (!p) {
697                         fclose(fp);
698                         return;
699                 }
700         }
701
702         if ((fpos = ftell(fp)) < 0) {
703                 perror("ftell");
704                 fclose(fp);
705                 return;
706         }
707
708         for (npart = 0;; npart++) {
709                 MimeInfo *partinfo;
710                 gboolean eom = FALSE;
711
712                 prev_fpos = fpos;
713
714                 partinfo = procmime_scan_mime_header(fp);
715                 if (!partinfo) break;
716
717                 if (npart != 0)
718                         procmime_mimeinfo_insert(mimeinfo, partinfo);
719                 else
720                         procmime_mimeinfo_free(partinfo);
721
722                 /* look for next boundary */
723                 buf[0] = '\0';
724                 while ((p = fgets(buf, sizeof(buf), fp)) != NULL) {
725                         if (IS_BOUNDARY(buf, boundary, boundary_len)) {
726                                 if (buf[2 + boundary_len]     == '-' &&
727                                     buf[2 + boundary_len + 1] == '-')
728                                         eom = TRUE;
729                                 break;
730                         }
731                 }
732                 if (p == NULL)
733                         eom = TRUE;     /* broken MIME message */
734                 fpos = ftell(fp);
735
736                 partinfo->size = fpos - prev_fpos - strlen(buf);
737
738                 if (eom) break;
739         }
740
741         source = procmsg_get_message_file_path(msginfo);
742
743         g_return_if_fail(mimeinfo != NULL);
744
745         if (!mimeinfo->main && mimeinfo->parent)
746                 {
747                         filename = mime_extract_file(source, mimeinfo);
748
749                         compose_attach_append_with_type(compose, filename,
750                                                         mimeinfo->content_type,
751                                                         mimeinfo->mime_type);
752
753                         g_free(filename);
754                 }
755
756         if (mimeinfo->sub && mimeinfo->sub->children)
757                 {
758                         filename = mime_extract_file(source, mimeinfo->sub);
759
760                         compose_attach_append_with_type(compose, filename,
761                                                         mimeinfo->content_type,
762                                                         mimeinfo->sub->mime_type);
763
764                         g_free(filename);
765                 }
766
767         if (mimeinfo->children) {
768                 MimeInfo *child;
769
770                 child = mimeinfo->children;
771                 while (child) {
772                         filename = mime_extract_file(source, child);
773
774                         compose_attach_append_with_type(compose, filename,
775                                                         child->content_type,
776                                                         child->mime_type);
777
778                         g_free(filename);
779
780                         child = child->next;
781                 }
782         }
783
784         fclose(fp);
785
786         procmime_mimeinfo_free_all(mimeinfo);
787 }
788
789
790 #define INSERT_FW_HEADER(var, hdr) \
791 if (msginfo->var && *msginfo->var) { \
792         gtk_stext_insert(text, NULL, NULL, NULL, hdr, -1); \
793         gtk_stext_insert(text, NULL, NULL, NULL, msginfo->var, -1); \
794         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1); \
795 }
796
797 Compose * compose_forward(PrefsAccount * account, MsgInfo *msginfo,
798                           gboolean as_attach)
799 {
800         Compose *compose;
801         /*      PrefsAccount *account; */
802         GtkSText *text;
803         FILE *fp;
804         gchar buf[BUFFSIZE];
805
806         g_return_val_if_fail(msginfo != NULL, NULL);
807         g_return_val_if_fail(msginfo->folder != NULL, NULL);
808
809         if (account == NULL) {
810                 account = cur_account;
811                 /*
812                 account = msginfo->folder->folder->account;
813                 if (!account) account = cur_account;
814                 */
815         }
816         g_return_val_if_fail(account != NULL, NULL);
817
818         MSG_UNSET_FLAGS(msginfo->flags, MSG_REPLIED);
819         MSG_SET_FLAGS(msginfo->flags, MSG_FORWARDED);
820
821         CHANGE_FLAGS(msginfo);
822
823         compose = compose_create(account);
824         compose->mode = COMPOSE_FORWARD;
825
826         if (msginfo->subject && *msginfo->subject) {
827                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), "Fw: ");
828                 gtk_entry_append_text(GTK_ENTRY(compose->subject_entry),
829                                       msginfo->subject);
830         }
831
832         text = GTK_STEXT(compose->text);
833         gtk_stext_freeze(text);
834
835         if (as_attach) {
836                 gchar *msgfile;
837
838                 msgfile = procmsg_get_message_file_path(msginfo);
839                 if (!is_file_exist(msgfile))
840                         g_warning(_("%s: file not exist\n"), msgfile);
841                 else
842                         compose_attach_append(compose, msgfile,
843                                               MIME_MESSAGE_RFC822);
844
845                 g_free(msgfile);
846         } else {
847                 FILE *fp;
848                 gchar *quote_str;
849
850                 if ((fp = procmime_get_text_part(msginfo)) == NULL)
851                         g_warning(_("Can't get text part\n"));
852                 else {
853                         gchar * qmark;
854
855                         if (prefs_common.fw_quotemark &&
856                             *prefs_common.fw_quotemark)
857                                 qmark = prefs_common.fw_quotemark;
858                         else
859                                 qmark = "> ";
860
861                         quote_str = compose_quote_fmt(compose, msginfo,
862                                                       prefs_common.fw_quotefmt,
863                                                       qmark);
864
865                         if (quote_str != NULL)
866                                 gtk_stext_insert(text, NULL, NULL, NULL,
867                                                  quote_str, -1);
868
869                         fclose(fp);
870                 }
871
872                 compose_attach_parts(compose, msginfo);
873         }
874
875         if (prefs_common.auto_sig)
876                 compose_insert_sig(compose);
877         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
878         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
879
880         gtk_stext_thaw(text);
881         if (account->protocol != A_NNTP)
882                 gtk_widget_grab_focus(compose->to_entry);
883         else
884                 gtk_widget_grab_focus(compose->newsgroups_entry);
885
886         return compose;
887 }
888
889 #undef INSERT_FW_HEADER
890
891 void compose_reedit(MsgInfo *msginfo)
892 {
893         Compose *compose;
894         PrefsAccount *account;
895         GtkSText *text;
896         FILE *fp;
897         gchar buf[BUFFSIZE];
898
899         g_return_if_fail(msginfo != NULL);
900         g_return_if_fail(msginfo->folder != NULL);
901
902         account = msginfo->folder->folder->account;
903         if (!account) account = cur_account;
904         g_return_if_fail(account != NULL);
905
906         compose = compose_create(account);
907         compose->mode = COMPOSE_REEDIT_DRAFT;
908         compose->targetinfo = procmsg_msginfo_copy(msginfo);
909
910         if (compose_parse_header(compose, msginfo) < 0) return;
911         compose_reedit_set_entry(compose, msginfo);
912
913         text = GTK_STEXT(compose->text);
914         gtk_stext_freeze(text);
915
916         if ((fp = procmime_get_text_part(msginfo)) == NULL)
917                 g_warning(_("Can't get text part\n"));
918         else {
919                 while (fgets(buf, sizeof(buf), fp) != NULL)
920                         gtk_stext_insert(text, NULL, NULL, NULL, buf, -1);
921                 fclose(fp);
922         }
923         compose_attach_parts(compose, msginfo);
924
925         gtk_stext_thaw(text);
926         gtk_widget_grab_focus(compose->text);
927 }
928
929 GList *compose_get_compose_list(void)
930 {
931         return compose_list;
932 }
933
934 void compose_entry_append(Compose *compose, const gchar *address,
935                           ComposeEntryType type)
936 {
937         GtkEntry *entry;
938         const gchar *text;
939
940         if (!address || *address == '\0') return;
941
942         switch (type) {
943         case COMPOSE_CC:
944                 entry = GTK_ENTRY(compose->cc_entry);
945                 break;
946         case COMPOSE_BCC:
947                 entry = GTK_ENTRY(compose->bcc_entry);
948                 break;
949         case COMPOSE_NEWSGROUPS:
950                 entry = GTK_ENTRY(compose->newsgroups_entry);
951                 break;
952         case COMPOSE_TO:
953         default:
954                 entry = GTK_ENTRY(compose->to_entry);
955                 break;
956         }
957
958         text = gtk_entry_get_text(entry);
959         if (*text != '\0')
960                 gtk_entry_append_text(entry, ", ");
961         gtk_entry_append_text(entry, address);
962 }
963
964 static gint compose_parse_header(Compose *compose, MsgInfo *msginfo)
965 {
966         static HeaderEntry hentry[] = {{"Reply-To:",    NULL, TRUE},
967                                        {"Cc:",          NULL, FALSE},
968                                        {"References:",  NULL, FALSE},
969                                        {"Bcc:",         NULL, FALSE},
970                                        {"Newsgroups:",  NULL, FALSE},
971                                        {"Followup-To:", NULL, FALSE},
972                                        {NULL,           NULL, FALSE}};
973
974         enum
975         {
976                 H_REPLY_TO      = 0,
977                 H_CC            = 1,
978                 H_REFERENCES    = 2,
979                 H_BCC           = 3,
980                 H_NEWSGROUPS    = 4,
981                 H_FOLLOWUP_TO   = 5
982         };
983
984         FILE *fp;
985
986         g_return_val_if_fail(msginfo != NULL, -1);
987
988         if ((fp = procmsg_open_message(msginfo)) == NULL) return -1;
989         procheader_get_header_fields(fp, hentry);
990         fclose(fp);
991
992         if (hentry[H_REPLY_TO].body != NULL) {
993                 conv_unmime_header_overwrite(hentry[H_REPLY_TO].body);
994                 compose->replyto = hentry[H_REPLY_TO].body;
995                 hentry[H_REPLY_TO].body = NULL;
996         }
997         if (hentry[H_CC].body != NULL) {
998                 conv_unmime_header_overwrite(hentry[H_CC].body);
999                 compose->cc = hentry[H_CC].body;
1000                 hentry[H_CC].body = NULL;
1001         }
1002         if (hentry[H_REFERENCES].body != NULL) {
1003                 if (compose->mode == COMPOSE_REEDIT_DRAFT)
1004                         compose->references = hentry[H_REFERENCES].body;
1005                 else {
1006                         compose->references = compose_parse_references
1007                                 (hentry[H_REFERENCES].body, msginfo->msgid);
1008                         g_free(hentry[H_REFERENCES].body);
1009                 }
1010                 hentry[H_REFERENCES].body = NULL;
1011         }
1012         if (hentry[H_BCC].body != NULL) {
1013                 if (compose->mode == COMPOSE_REEDIT_DRAFT) {
1014                         conv_unmime_header_overwrite(hentry[H_BCC].body);
1015                         compose->bcc = hentry[H_BCC].body;
1016                 } else
1017                         g_free(hentry[H_BCC].body);
1018                 hentry[H_BCC].body = NULL;
1019         }
1020         if (hentry[H_NEWSGROUPS].body != NULL) {
1021                 compose->newsgroups = hentry[H_NEWSGROUPS].body;
1022                 hentry[H_NEWSGROUPS].body = NULL;
1023         }
1024         if (hentry[H_FOLLOWUP_TO].body != NULL) {
1025                 conv_unmime_header_overwrite(hentry[H_FOLLOWUP_TO].body);
1026                 compose->followup_to = hentry[H_FOLLOWUP_TO].body;
1027                 hentry[H_FOLLOWUP_TO].body = NULL;
1028         }
1029
1030         if (compose->mode == COMPOSE_REEDIT_DRAFT && msginfo->inreplyto)
1031                 compose->inreplyto = g_strdup(msginfo->inreplyto);
1032         else if (compose->mode != COMPOSE_REEDIT_DRAFT &&
1033                  msginfo->msgid && *msginfo->msgid) {
1034                 compose->inreplyto = g_strdup(msginfo->msgid);
1035
1036                 if (!compose->references) {
1037                         if (msginfo->inreplyto && *msginfo->inreplyto)
1038                                 compose->references =
1039                                         g_strdup_printf("<%s>\n\t<%s>",
1040                                                         msginfo->inreplyto,
1041                                                         msginfo->msgid);
1042                         else
1043                                 compose->references =
1044                                         g_strconcat("<", msginfo->msgid, ">",
1045                                                     NULL);
1046                 }
1047         }
1048
1049         return 0;
1050 }
1051
1052 static gchar *compose_parse_references(const gchar *ref, const gchar *msgid)
1053 {
1054         GSList *ref_id_list, *cur;
1055         GString *new_ref;
1056         gchar *new_ref_str;
1057
1058         ref_id_list = references_list_append(NULL, ref);
1059         if (!ref_id_list) return NULL;
1060         if (msgid && *msgid)
1061                 ref_id_list = g_slist_append(ref_id_list, g_strdup(msgid));
1062
1063         for (;;) {
1064                 gint len = 0;
1065
1066                 for (cur = ref_id_list; cur != NULL; cur = cur->next)
1067                         /* "<" + Message-ID + ">" + CR+LF+TAB */
1068                         len += strlen((gchar *)cur->data) + 5;
1069
1070                 if (len > MAX_REFERENCES_LEN) {
1071                         /* remove second message-ID */
1072                         if (ref_id_list && ref_id_list->next &&
1073                             ref_id_list->next->next) {
1074                                 g_free(ref_id_list->next->data);
1075                                 ref_id_list = g_slist_remove
1076                                         (ref_id_list, ref_id_list->next->data);
1077                         } else {
1078                                 slist_free_strings(ref_id_list);
1079                                 g_slist_free(ref_id_list);
1080                                 return NULL;
1081                         }
1082                 } else
1083                         break;
1084         }
1085
1086         new_ref = g_string_new("");
1087         for (cur = ref_id_list; cur != NULL; cur = cur->next) {
1088                 if (new_ref->len > 0)
1089                         g_string_append(new_ref, "\n\t");
1090                 g_string_sprintfa(new_ref, "<%s>", (gchar *)cur->data);
1091         }
1092
1093         slist_free_strings(ref_id_list);
1094         g_slist_free(ref_id_list);
1095
1096         new_ref_str = new_ref->str;
1097         g_string_free(new_ref, FALSE);
1098
1099         return new_ref_str;
1100 }
1101
1102 /*
1103 static void compose_quote_file(Compose *compose, MsgInfo *msginfo, FILE *fp)
1104 {
1105         GtkSText *text = GTK_STEXT(compose->text);
1106         gchar *qmark;
1107         gchar *quote_str;
1108         GdkColor *qcolor = NULL;
1109         gchar buf[BUFFSIZE];
1110         gint qlen;
1111         gchar *linep, *cur, *leftp;
1112         gint line_len, cur_len;
1113         gint wrap_len;
1114         gint str_len;
1115         gint ch_len;
1116
1117         // if (prefs_common.enable_color) qcolor = &quote_color;
1118         if (prefs_common.quotemark && *prefs_common.quotemark)
1119                 qmark = prefs_common.quotemark;
1120         else
1121                 qmark = "> ";
1122         quote_str = compose_quote_parse_fmt(compose, msginfo, qmark);
1123         g_return_if_fail(quote_str != NULL);
1124         qlen = strlen(quote_str);
1125
1126         if (!prefs_common.linewrap_quote ||
1127             prefs_common.linewrap_len <= qlen) {
1128                 while (fgets(buf, sizeof(buf), fp) != NULL) {
1129                         gtk_stext_insert(text, NULL, qcolor, NULL,
1130                                         quote_str, -1);
1131                         gtk_stext_insert(text, NULL, qcolor, NULL, buf, -1);
1132                 }
1133                 g_free(quote_str);
1134                 return;
1135         }
1136
1137         wrap_len = prefs_common.linewrap_len - qlen;
1138
1139         while (fgets(buf, sizeof(buf), fp) != NULL) {
1140                 strretchomp(buf);
1141                 str_len = strlen(buf);
1142
1143                 if (str_len <= wrap_len) {
1144                         gtk_stext_insert(text, NULL, qcolor, NULL,
1145                                         quote_str, -1);
1146                         gtk_stext_insert(text, NULL, qcolor, NULL, buf, -1);
1147                         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1);
1148                         continue;
1149                 }
1150
1151                 linep = cur = leftp = buf;
1152                 line_len = cur_len = 0;
1153
1154                 while (*cur != '\0') {
1155                         ch_len = mblen(cur, MB_CUR_MAX);
1156                         if (ch_len < 0) ch_len = 1;
1157
1158                         if (ch_len == 1 && isspace(*cur)) {
1159                                 linep = cur + ch_len;
1160                                 line_len = cur_len + ch_len;
1161                         }
1162
1163                         if (cur_len + ch_len > wrap_len && line_len > 0) {
1164                                 gtk_stext_insert(text, NULL, qcolor, NULL,
1165                                                 quote_str, -1);
1166
1167                                 if (isspace(*(linep - 1)))
1168                                         gtk_stext_insert(text, NULL,
1169                                                         qcolor, NULL,
1170                                                         leftp, line_len - 1);
1171                                 else
1172                                         gtk_stext_insert(text, NULL,
1173                                                         qcolor, NULL,
1174                                                         leftp, line_len);
1175                                 gtk_stext_insert(text, NULL, NULL, NULL,
1176                                                 "\n", 1);
1177
1178                                 leftp = linep;
1179                                 cur_len = cur_len - line_len + ch_len;
1180                                 line_len = 0;
1181                                 cur += ch_len;
1182                                 continue;
1183                         }
1184
1185                         if (ch_len > 1) {
1186                                 linep = cur + ch_len;
1187                                 line_len = cur_len + ch_len;
1188                         }
1189                         cur_len += ch_len;
1190                         cur += ch_len;
1191                 }
1192
1193                 if (*leftp) {
1194                         gtk_stext_insert(text, NULL, qcolor, NULL,
1195                                         quote_str, -1);
1196                         gtk_stext_insert(text, NULL, qcolor, NULL, leftp, -1);
1197                         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1);
1198                 }
1199         }
1200
1201         g_free(quote_str);
1202 }
1203 */
1204
1205 /*
1206 static gchar *compose_quote_parse_fmt(Compose *compose, MsgInfo *msginfo,
1207                                       const gchar *fmt)
1208 {
1209         gchar *ext_str;
1210         size_t buf_len = 1024;
1211         size_t ext_len = 0;
1212         gchar *str;
1213         gchar *mbs;
1214         wchar_t *wcsfmt;
1215         wchar_t *sp;
1216         gchar tmp[3];
1217
1218         if (!fmt || *fmt == '\0') return 0;
1219
1220         Xalloca(mbs, sizeof(wchar_t) + 1, return 0);
1221         Xalloca(wcsfmt, (strlen(fmt) + 1) * sizeof(wchar_t), return 0);
1222         mbstowcs(wcsfmt, fmt, strlen(fmt) + 1);
1223         sp = wcsfmt;
1224
1225         ext_str = g_malloc(sizeof(gchar) * buf_len);
1226         g_return_val_if_fail(ext_str != NULL, NULL);
1227
1228         while (*sp) {
1229                 gint len;
1230
1231                 len = wctomb(mbs, *sp);
1232                 mbs[len] = '\0';
1233
1234                 if (*mbs == '%') {
1235                         gchar *p;
1236
1237                         wctomb(mbs, *(++sp));
1238                         str = NULL;
1239
1240                         switch (*mbs) {
1241                         case 'd':
1242                                 str = msginfo->date;
1243                                 sp++;
1244                                 break;
1245                         case 'f':
1246                                 str = msginfo->from;
1247                                 sp++;
1248                                 break;
1249                         case 'I':
1250                                 if (!msginfo->fromname) {sp++; break;}
1251                                 p = msginfo->fromname;
1252                                 tmp[0] = tmp[1] = tmp[2] = '\0';
1253
1254                                 if (*p && isalnum(*p))
1255                                         tmp[0] = toupper(*p);
1256                                 else {
1257                                         sp++;
1258                                         break;
1259                                 }
1260
1261                                 while (*p) {
1262                                         while (*p && !isspace(*p)) p++;
1263                                         while (*p && isspace(*p)) p++;
1264                                         if (*p && isalnum(*p))
1265                                                 tmp[1] = toupper(*p);
1266                                 }
1267
1268                                 if (tmp[1]) str = tmp;
1269                                 sp++;
1270                                 break;
1271                         case 'n':
1272                                 str = msginfo->fromname;
1273                                 sp++;
1274                                 break;
1275                         case 'N':
1276                                 if (!msginfo->fromname) {sp++; break;}
1277                                 Xstrdup_a(str, msginfo->fromname,
1278                                           {sp++; break;});
1279                                 p = str;
1280                                 while (*p && !isspace(*p)) p++;
1281                                 *p = '\0';
1282                                 sp++;
1283                                 break;
1284                         case 's':
1285                                 str = msginfo->subject;
1286                                 sp++;
1287                                 break;
1288                         case 't':
1289                                 str = msginfo->to;
1290                                 sp++;
1291                                 break;
1292                         case 'i':
1293                                 if (!msginfo->msgid) {sp++; break;}
1294                                 Xalloca(str, strlen(msginfo->msgid) + 3,
1295                                         {sp++; break;});
1296                                 g_snprintf(str, strlen(msginfo->msgid) + 3,
1297                                            "<%s>", msginfo->msgid);
1298                                 sp++;
1299                                 break;
1300                         case '%':
1301                                 str = "%";
1302                                 sp++;
1303                                 break;
1304                         default:
1305                                 break;
1306                         }
1307
1308                         if (str) {
1309                                 while (ext_len + strlen(str) + 1 > buf_len)
1310                                         buf_len += 1024;
1311                                 ext_str = g_realloc(ext_str,
1312                                                     sizeof(gchar) * buf_len);
1313                                 g_return_val_if_fail(ext_str != NULL, NULL);
1314                                 strcpy(ext_str + ext_len, str);
1315                                 ext_len += strlen(str);
1316                         }
1317                 } else if (*mbs == '\\') {
1318                         wctomb(mbs, *(++sp));
1319                         str = NULL;
1320
1321                         switch (*mbs) {
1322                         case 'n':
1323                                 str = "\n";
1324                                 break;
1325                         case 't':
1326                                 str = "\t";
1327                                 break;
1328                         case '\\':
1329                                 str = "\\";
1330                                 break;
1331                         default:
1332                                 break;
1333                         }
1334
1335                         if (str) {
1336                                 while (ext_len + strlen(str) + 1 > buf_len)
1337                                         buf_len += 1024;
1338                                 ext_str = g_realloc(ext_str,
1339                                                     sizeof(gchar) * buf_len);
1340                                 g_return_val_if_fail(ext_str != NULL, NULL);
1341                                 strcpy(ext_str + ext_len, str);
1342                                 ext_len += strlen(str);
1343                                 sp++;
1344                         }
1345                 } else {
1346                         while (ext_len + len + 1 > buf_len) buf_len += 1024;
1347                         ext_str = g_realloc(ext_str, sizeof(gchar) * buf_len);
1348                         g_return_val_if_fail(ext_str != NULL, NULL);
1349                         strcpy(ext_str + ext_len, mbs);
1350                         ext_len += len;
1351                         sp++;
1352                 }
1353         }
1354
1355         if (ext_str)
1356                 ext_str = g_realloc(ext_str, strlen(ext_str) + 1);
1357
1358         return ext_str;
1359 }
1360 */
1361
1362 static void compose_reply_set_entry(Compose *compose, MsgInfo *msginfo,
1363                                     gboolean to_all, gboolean ignore_replyto)
1364 {
1365         GSList *cc_list;
1366         GSList *cur;
1367         gchar *from;
1368         GHashTable *to_table;
1369
1370         g_return_if_fail(compose->account != NULL);
1371         g_return_if_fail(msginfo != NULL);
1372
1373         if (compose->account->protocol != A_NNTP)
1374                 gtk_entry_set_text(GTK_ENTRY(compose->to_entry),
1375                                    ( (compose->replyto && !ignore_replyto) 
1376                                      ? compose->replyto
1377                                      : msginfo->from ? msginfo->from : ""));
1378         if (compose->account->protocol == A_NNTP)
1379                 gtk_entry_set_text(GTK_ENTRY(compose->newsgroups_entry),
1380                                    compose->followup_to ? compose->followup_to
1381                                    : compose->newsgroups ? compose->newsgroups
1382                                    : "");
1383
1384         if (msginfo->subject && *msginfo->subject) {
1385                 gchar *buf, *buf2, *p;
1386
1387                 buf = g_strdup(msginfo->subject);
1388                 while (!strncasecmp(buf, "Re:", 3)) {
1389                         p = buf + 3;
1390                         while (isspace(*p)) p++;
1391                         memmove(buf, p, strlen(p) + 1);
1392                 }
1393
1394                 buf2 = g_strdup_printf("Re: %s", buf);
1395                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), buf2);
1396                 g_free(buf2);
1397                 g_free(buf);
1398         } else
1399                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), "Re: ");
1400
1401         if (!to_all || compose->account->protocol == A_NNTP) return;
1402
1403         from = g_strdup(compose->replyto ? compose->replyto :
1404                         msginfo->from ? msginfo->from : "");
1405         extract_address(from);
1406
1407         cc_list = address_list_append(NULL, msginfo->to);
1408         cc_list = address_list_append(cc_list, compose->cc);
1409
1410         to_table = g_hash_table_new(g_str_hash, g_str_equal);
1411         g_hash_table_insert(to_table, from, GINT_TO_POINTER(1));
1412         if (compose->account)
1413                 g_hash_table_insert(to_table, compose->account->address,
1414                                     GINT_TO_POINTER(1));
1415
1416         /* remove address on To: and that of current account */
1417         for (cur = cc_list; cur != NULL; ) {
1418                 GSList *next = cur->next;
1419
1420                 if (g_hash_table_lookup(to_table, cur->data) != NULL)
1421                         cc_list = g_slist_remove(cc_list, cur->data);
1422                 else
1423                         g_hash_table_insert(to_table, cur->data, cur);
1424
1425                 cur = next;
1426         }
1427         g_hash_table_destroy(to_table);
1428         g_free(from);
1429
1430         if (cc_list) {
1431                 for (cur = cc_list; cur != NULL; cur = cur->next)
1432                         compose_entry_append(compose, (gchar *)cur->data,
1433                                              COMPOSE_CC);
1434                 slist_free_strings(cc_list);
1435                 g_slist_free(cc_list);
1436         }
1437 }
1438
1439 #define SET_ENTRY(entry, str) \
1440 { \
1441         if (str && *str) \
1442                 gtk_entry_set_text(GTK_ENTRY(compose->entry), str); \
1443 }
1444
1445 static void compose_reedit_set_entry(Compose *compose, MsgInfo *msginfo)
1446 {
1447         g_return_if_fail(msginfo != NULL);
1448
1449         SET_ENTRY(to_entry, msginfo->to);
1450         SET_ENTRY(subject_entry, msginfo->subject);
1451         SET_ENTRY(cc_entry, compose->cc);
1452         SET_ENTRY(bcc_entry, compose->bcc);
1453         SET_ENTRY(reply_entry, compose->replyto);
1454
1455         if (compose->bcc) {
1456                 GtkItemFactory *ifactory;
1457                 GtkWidget *menuitem;
1458
1459                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1460                 menuitem = gtk_item_factory_get_item(ifactory, "/Message/Bcc");
1461                 gtk_check_menu_item_set_active
1462                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
1463         }
1464         if (compose->replyto) {
1465                 GtkItemFactory *ifactory;
1466                 GtkWidget *menuitem;
1467
1468                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1469                 menuitem = gtk_item_factory_get_item
1470                         (ifactory, "/Message/Reply to");
1471                 gtk_check_menu_item_set_active
1472                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
1473         }
1474 }
1475
1476 #undef SET_ENTRY
1477
1478 static void compose_insert_sig(Compose *compose)
1479 {
1480         gchar *sigfile;
1481
1482         if (compose->account && compose->account->sig_path)
1483                 sigfile = g_strdup(compose->account->sig_path);
1484         else {
1485                 sigfile = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1486                                       DEFAULT_SIGNATURE, NULL);
1487         }
1488
1489         if (!is_file_or_fifo_exist(sigfile)) {
1490                 g_free(sigfile);
1491                 return;
1492         }
1493
1494         gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, "\n\n", 2);
1495         if (prefs_common.sig_sep) {
1496                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL,
1497                                 prefs_common.sig_sep, -1);
1498                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL,
1499                                 "\n", 1);
1500         }
1501
1502         compose_insert_file(compose, sigfile);
1503         g_free(sigfile);
1504 }
1505
1506 static void compose_insert_file(Compose *compose, const gchar *file)
1507 {
1508         GtkSText *text = GTK_STEXT(compose->text);
1509         gchar buf[BUFFSIZE];
1510         FILE *fp;
1511
1512         g_return_if_fail(file != NULL);
1513
1514         if ((fp = fopen(file, "r")) == NULL) {
1515                 FILE_OP_ERROR(file, "fopen");
1516                 return;
1517         }
1518
1519         gtk_stext_freeze(text);
1520
1521         while (fgets(buf, sizeof(buf), fp) != NULL)
1522                 gtk_stext_insert(text, NULL, NULL, NULL, buf, -1);
1523
1524         gtk_stext_thaw(text);
1525
1526         fclose(fp);
1527 }
1528
1529 static void compose_attach_info(Compose * compose, AttachInfo * ainfo,
1530                                 ContentType cnttype)
1531 {
1532         gchar *text[N_ATTACH_COLS];
1533         gint row;
1534
1535         text[COL_MIMETYPE] = ainfo->content_type;
1536         text[COL_SIZE] = to_human_readable(ainfo->size);
1537         text[COL_NAME] = ainfo->name;
1538
1539         row = gtk_clist_append(GTK_CLIST(compose->attach_clist), text);
1540         gtk_clist_set_row_data(GTK_CLIST(compose->attach_clist), row, ainfo);
1541
1542         if (cnttype != MIME_MESSAGE_RFC822)
1543                 compose_changed_cb(NULL, compose);
1544 }
1545
1546 static void compose_attach_append_with_type(Compose *compose,
1547                                             const gchar *file,
1548                                             const gchar *type,
1549                                             ContentType cnttype)
1550 {
1551         AttachInfo *ainfo;
1552         off_t size;
1553
1554         if (!is_file_exist(file)) {
1555                 g_warning(_("File %s doesn't exist\n"), file);
1556                 return;
1557         }
1558         if ((size = get_file_size(file)) < 0) {
1559                 g_warning(_("Can't get file size of %s\n"), file);
1560                 return;
1561         }
1562         if (size == 0) {
1563                 alertpanel_notice(_("File %s is empty\n"), file);
1564                 return;
1565         }
1566
1567         if (!compose->use_attach) {
1568                 GtkItemFactory *ifactory;
1569                 GtkWidget *menuitem;
1570
1571                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1572                 menuitem = gtk_item_factory_get_item(ifactory,
1573                                                      "/Message/Attach");
1574                 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
1575                                                TRUE);
1576         }
1577
1578         ainfo = g_new0(AttachInfo, 1);
1579         ainfo->file = g_strdup(file);
1580
1581         if (cnttype == MIME_MESSAGE_RFC822) {
1582                 ainfo->encoding = ENC_7BIT;
1583                 ainfo->name = g_strdup_printf(_("Message: %s"),
1584                                               g_basename(file));
1585         } else {
1586                 ainfo->encoding = ENC_BASE64;
1587                 ainfo->name = g_strdup(g_basename(file));
1588         }
1589
1590         ainfo->content_type = g_strdup(type);
1591         ainfo->size = size;
1592
1593         compose_attach_info(compose, ainfo, cnttype);
1594 }
1595
1596 static void compose_attach_append(Compose *compose, const gchar *file,
1597                                   ContentType cnttype)
1598 {
1599         AttachInfo *ainfo;
1600         gchar *text[N_ATTACH_COLS];
1601         off_t size;
1602         gint row;
1603
1604         if (!is_file_exist(file)) {
1605                 g_warning(_("File %s doesn't exist\n"), file);
1606                 return;
1607         }
1608         if ((size = get_file_size(file)) < 0) {
1609                 g_warning(_("Can't get file size of %s\n"), file);
1610                 return;
1611         }
1612         if (size == 0) {
1613                 alertpanel_notice(_("File %s is empty\n"), file);
1614                 return;
1615         }
1616
1617         if (!compose->use_attach) {
1618                 GtkItemFactory *ifactory;
1619                 GtkWidget *menuitem;
1620
1621                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1622                 menuitem = gtk_item_factory_get_item(ifactory,
1623                                                      "/Message/Attach");
1624                 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
1625                                                TRUE);
1626         }
1627
1628         ainfo = g_new0(AttachInfo, 1);
1629         ainfo->file = g_strdup(file);
1630
1631         if (cnttype == MIME_MESSAGE_RFC822) {
1632                 ainfo->content_type = g_strdup("message/rfc822");
1633                 ainfo->encoding = ENC_7BIT;
1634                 ainfo->name = g_strdup_printf(_("Message: %s"),
1635                                               g_basename(file));
1636         } else {
1637                 ainfo->content_type = procmime_get_mime_type(file);
1638                 if (!ainfo->content_type)
1639                         ainfo->content_type =
1640                                 g_strdup("application/octet-stream");
1641                 ainfo->encoding = ENC_BASE64;
1642                 ainfo->name = g_strdup(g_basename(file));
1643         }
1644         ainfo->size = size;
1645
1646         compose_attach_info(compose, ainfo, cnttype);
1647 }
1648
1649 static void compose_wrap_line(Compose *compose)
1650 {
1651         GtkSText *text = GTK_STEXT(compose->text);
1652         guint text_len;
1653         guint line_pos = 0, cur_pos = 0;
1654         gint line_len = 0, cur_len = 0;
1655         gint ch_len;
1656         gchar cbuf[MB_CUR_MAX];
1657
1658         gtk_stext_freeze(text);
1659
1660         text_len = gtk_stext_get_length(text);
1661
1662         for (; cur_pos < text_len; cur_pos++) {
1663                 if (text->use_wchar)
1664                         ch_len = wctomb
1665                                 (cbuf, (wchar_t)GTK_STEXT_INDEX(text, cur_pos));
1666                 else {
1667                         cbuf[0] = GTK_STEXT_INDEX(text, cur_pos);
1668                         ch_len = 1;
1669                 }
1670
1671                 if (ch_len == 1 && *cbuf == '\n') {
1672                         line_pos = cur_pos + 1;
1673                         line_len = cur_len = 0;
1674                         continue;
1675                 }
1676
1677                 if (ch_len < 0) {
1678                         cbuf[0] = '\0';
1679                         ch_len = 1;
1680                 }
1681
1682                 if (ch_len == 1 && isspace(*cbuf)) {
1683                         line_pos = cur_pos + 1;
1684                         line_len = cur_len + ch_len;
1685                 }
1686
1687                 if (cur_len + ch_len > prefs_common.linewrap_len &&
1688                     line_len > 0) {
1689                         gint tlen;
1690
1691                         if (text->use_wchar)
1692                                 tlen = wctomb(cbuf, (wchar_t)GTK_STEXT_INDEX(text, line_pos - 1));
1693                         else {
1694                                 cbuf[0] = GTK_STEXT_INDEX(text, line_pos - 1);
1695                                 tlen = 1;
1696                         }
1697                         if (tlen == 1 && isspace(*cbuf)) {
1698                                 gtk_stext_set_point(text, line_pos);
1699                                 gtk_stext_backward_delete(text, 1);
1700                                 text_len--;
1701                                 cur_pos--;
1702                                 line_pos--;
1703                                 cur_len--;
1704                                 line_len--;
1705                         }
1706
1707                         gtk_stext_set_point(text, line_pos);
1708                         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1);
1709                         text_len++;
1710                         cur_pos++;
1711                         line_pos++;
1712                         cur_len = cur_len - line_len + ch_len;
1713                         line_len = 0;
1714                         continue;
1715                 }
1716
1717                 if (ch_len > 1) {
1718                         line_pos = cur_pos + 1;
1719                         line_len = cur_len + ch_len;
1720                 }
1721                 cur_len += ch_len;
1722         }
1723
1724         gtk_stext_thaw(text);
1725 }
1726
1727 static void compose_set_title(Compose *compose)
1728 {
1729         gchar *str;
1730         gchar *edited;
1731
1732         edited = compose->modified ? _(" [Edited]") : "";
1733         if (compose->account && compose->account->address)
1734                 str = g_strdup_printf(_("%s - Compose message%s"),
1735                                       compose->account->address, edited);
1736         else
1737                 str = g_strdup_printf(_("Compose message%s"), edited);
1738         gtk_window_set_title(GTK_WINDOW(compose->window), str);
1739         g_free(str);
1740 }
1741
1742 /**
1743  * compose_current_mail_account:
1744  * 
1745  * Find a current mail account (the currently selected account, or the
1746  * default account, if a news account is currently selected).  If a
1747  * mail account cannot be found, display an error message.
1748  * 
1749  * Return value: Mail account, or NULL if not found.
1750  **/
1751 static PrefsAccount *
1752 compose_current_mail_account(void)
1753 {
1754         PrefsAccount *ac;
1755
1756         if (cur_account && cur_account->protocol != A_NNTP)
1757                 ac = cur_account;
1758         else {
1759                 ac = account_get_default();
1760                 if (!ac || ac->protocol == A_NNTP) {
1761                         alertpanel_error(_("Account for sending mail is not specified.\n"
1762                                            "Please select a mail account before sending."));
1763                         return NULL;
1764                 }
1765         }
1766         return ac;
1767 }
1768
1769 gint compose_send(Compose *compose)
1770 {
1771         gchar tmp[MAXPATHLEN + 1];
1772         gchar *to, *newsgroups;
1773         gint ok = 0;
1774         static gboolean lock = FALSE;
1775
1776         if (lock) return 1;
1777
1778         g_return_val_if_fail(compose->account != NULL, -1);
1779         g_return_val_if_fail(compose->orig_account != NULL, -1);
1780
1781         lock = TRUE;
1782
1783         to = gtk_entry_get_text(GTK_ENTRY(compose->to_entry));
1784         newsgroups = gtk_entry_get_text(GTK_ENTRY(compose->newsgroups_entry));
1785         if (*to == '\0' && *newsgroups == '\0') {
1786                 alertpanel_error(_("Recipient is not specified."));
1787                 lock = FALSE;
1788                 return 1;
1789         }
1790
1791         /* write to temporary file */
1792         g_snprintf(tmp, sizeof(tmp), "%s%ctmpmsg%d",
1793                    get_rc_dir(), G_DIR_SEPARATOR, (gint)compose);
1794
1795         if (prefs_common.linewrap_at_send)
1796                 compose_wrap_line(compose);
1797
1798         if (compose_write_to_file(compose, tmp, FALSE) < 0) {
1799                 lock = FALSE;
1800                 return -1;
1801         }
1802
1803         if (!compose->to_list && !compose->newsgroup_list) {
1804                 g_warning(_("can't get recipient list."));
1805                 unlink(tmp);
1806                 lock = FALSE;
1807                 return -1;
1808         }
1809
1810         if (compose->to_list) {
1811                 PrefsAccount *ac;
1812
1813                 /*
1814                 if (compose->account->protocol != A_NNTP)
1815                         ac = compose->account;
1816                 else if (compose->orig_account->protocol != A_NNTP)
1817                         ac = compose->orig_account;
1818                 else {
1819                         ac = compose_current_mail_account();
1820                         if (!ac) {
1821                                 unlink(tmp);
1822                                 lock = FALSE;
1823                                 return -1;
1824                         }
1825                 }
1826                 */
1827                 ac = compose->account;
1828
1829                 ok = send_message(tmp, ac, compose->to_list);
1830                 statusbar_pop_all();
1831         }
1832
1833         if (ok == 0 && compose->newsgroup_list) {
1834                 Folder *folder;
1835
1836                 if (compose->account->protocol == A_NNTP)
1837                         folder = FOLDER(compose->account->folder);
1838                 else
1839                         folder = FOLDER(compose->orig_account->folder);
1840
1841                 ok = news_post(folder, tmp);
1842                 if (ok < 0) {
1843                         alertpanel_error(_("Error occurred while posting the message to %s ."),
1844                                          compose->account->nntp_server);
1845                         unlink(tmp);
1846                         lock = FALSE;
1847                         return -1;
1848                 }
1849         }
1850
1851         /* queue message if failed to send */
1852         if (ok < 0) {
1853                 if (prefs_common.queue_msg) {
1854                         AlertValue val;
1855
1856                         val = alertpanel
1857                                 (_("Queueing"),
1858                                  _("Error occurred while sending the message.\n"
1859                                    "Put this message into queue folder?"),
1860                                  _("OK"), _("Cancel"), NULL);
1861                         if (G_ALERTDEFAULT == val) {
1862                                 ok = compose_queue(compose, tmp);
1863                                 if (ok < 0)
1864                                         alertpanel_error(_("Can't queue the message."));
1865                         }
1866                 } else
1867                         alertpanel_error(_("Error occurred while sending the message."));
1868         }
1869
1870         /* save message to outbox */
1871         if (ok == 0 && prefs_common.savemsg) {
1872                 if (compose_save_to_outbox(compose, tmp) < 0)
1873                         alertpanel_error
1874                                 (_("Can't save the message to outbox."));
1875         }
1876
1877         unlink(tmp);
1878         lock = FALSE;
1879         return ok;
1880 }
1881
1882 static gint compose_write_to_file(Compose *compose, const gchar *file,
1883                                   gboolean is_draft)
1884 {
1885         FILE *fp;
1886         size_t len;
1887         gchar *chars;
1888         gchar *buf;
1889         const gchar *out_codeset;
1890         EncodingType encoding;
1891
1892         if ((fp = fopen(file, "w")) == NULL) {
1893                 FILE_OP_ERROR(file, "fopen");
1894                 return -1;
1895         }
1896
1897         /* chmod for security */
1898         if (change_file_mode_rw(fp, file) < 0) {
1899                 FILE_OP_ERROR(file, "chmod");
1900                 g_warning(_("can't change file mode\n"));
1901         }
1902
1903         /* get all composed text */
1904         chars = gtk_editable_get_chars(GTK_EDITABLE(compose->text), 0, -1);
1905         len = strlen(chars);
1906         if (is_ascii_str(chars)) {
1907                 buf = g_strdup(chars);
1908                 out_codeset = "US-ASCII";
1909                 encoding = ENC_7BIT;
1910         } else {
1911                 const gchar *src_codeset;
1912
1913                 out_codeset = conv_get_outgoing_charset_str();
1914                 if (!strcasecmp(out_codeset, "US-ASCII"))
1915                         out_codeset = "ISO-8859-1";
1916                 encoding = procmime_get_encoding_for_charset(out_codeset);
1917                 debug_print("charset = %s, encoding = %s\n",
1918                             out_codeset, procmime_get_encoding_str(encoding));
1919
1920                 src_codeset = conv_get_current_charset_str();
1921                 buf = conv_codeset_strdup(chars, src_codeset, out_codeset);
1922                 if (!buf) {
1923                         g_free(chars);
1924                         fclose(fp);
1925                         unlink(file);
1926                         alertpanel_error(_("Can't convert the codeset of the message."));
1927                         return -1;
1928                 }
1929         }
1930         g_free(chars);
1931
1932         /* write headers */
1933         if (compose_write_headers
1934                 (compose, fp, out_codeset, encoding, is_draft) < 0) {
1935                 g_warning(_("can't write headers\n"));
1936                 fclose(fp);
1937                 /* unlink(file); */
1938                 g_free(buf);
1939                 return -1;
1940         }
1941
1942         if (compose->use_attach) {
1943 #if USE_GPGME
1944             /* This prolog message is ignored by mime software and
1945              * because it would make our signing/encryption task
1946              * tougher, we don't emit it in that case */
1947             if (!compose->use_signing && !compose->use_encryption)
1948 #endif
1949                 fputs("This is a multi-part message in MIME format.\n", fp);
1950
1951                 fprintf(fp, "\n--%s\n", compose->boundary);
1952                 fprintf(fp, "Content-Type: text/plain; charset=%s\n",
1953                         out_codeset);
1954                 fprintf(fp, "Content-Transfer-Encoding: %s\n",
1955                         procmime_get_encoding_str(encoding));
1956                 fputc('\n', fp);
1957         }
1958
1959         /* write body */
1960         len = strlen(buf);
1961         if (encoding == ENC_BASE64) {
1962                 gchar outbuf[B64_BUFFSIZE];
1963                 gint i, l;
1964
1965                 for (i = 0; i < len; i += B64_LINE_SIZE) {
1966                         l = MIN(B64_LINE_SIZE, len - i);
1967                         to64frombits(outbuf, buf + i, l);
1968                         fputs(outbuf, fp);
1969                         fputc('\n', fp);
1970                 }
1971         } else if (fwrite(buf, sizeof(gchar), len, fp) != len) {
1972                 FILE_OP_ERROR(file, "fwrite");
1973                 fclose(fp);
1974                 unlink(file);
1975                 g_free(buf);
1976                 return -1;
1977         }
1978         g_free(buf);
1979
1980         if (compose->use_attach)
1981                 compose_write_attach(compose, fp);
1982
1983         if (fclose(fp) == EOF) {
1984                 FILE_OP_ERROR(file, "fclose");
1985                 unlink(file);
1986                 return -1;
1987         }
1988
1989 #if USE_GPGME
1990         if (compose->use_signing) {
1991                 if (rfc2015_sign(file, compose->account) < 0) {
1992                         unlink(file);
1993                         return -1;
1994                 }
1995         }
1996         if (compose->use_encryption) {
1997                 if (rfc2015_encrypt(file, compose->to_list) < 0) {
1998                         unlink(file);
1999                         return -1;
2000                 }
2001         }
2002 #endif /* USE_GPGME */
2003
2004         return 0;
2005 }
2006
2007 static gint compose_write_body_to_file(Compose *compose, const gchar *file)
2008 {
2009         FILE *fp;
2010         size_t len;
2011         gchar *chars;
2012
2013         if ((fp = fopen(file, "w")) == NULL) {
2014                 FILE_OP_ERROR(file, "fopen");
2015                 return -1;
2016         }
2017
2018         /* chmod for security */
2019         if (change_file_mode_rw(fp, file) < 0) {
2020                 FILE_OP_ERROR(file, "chmod");
2021                 g_warning(_("can't change file mode\n"));
2022         }
2023
2024         chars = gtk_editable_get_chars(GTK_EDITABLE(compose->text), 0, -1);
2025
2026         /* write body */
2027         len = strlen(chars);
2028         if (fwrite(chars, sizeof(gchar), len, fp) != len) {
2029                 FILE_OP_ERROR(file, "fwrite");
2030                 g_free(chars);
2031                 fclose(fp);
2032                 unlink(file);
2033                 return -1;
2034         }
2035
2036         g_free(chars);
2037
2038         if (fclose(fp) == EOF) {
2039                 FILE_OP_ERROR(file, "fclose");
2040                 unlink(file);
2041                 return -1;
2042         }
2043         return 0;
2044 }
2045
2046 static gint compose_save_to_outbox(Compose *compose, const gchar *file)
2047 {
2048         FolderItem *outbox;
2049         gchar *path;
2050         gint num;
2051         FILE *fp;
2052
2053         debug_print(_("saving sent message...\n"));
2054
2055         outbox = folder_get_default_outbox();
2056         path = folder_item_get_path(outbox);
2057         if (!is_dir_exist(path))
2058                 make_dir_hier(path);
2059
2060         folder_item_scan(outbox);
2061         if ((num = folder_item_add_msg(outbox, file, FALSE)) < 0) {
2062                 g_free(path);
2063                 g_warning(_("can't save message\n"));
2064                 return -1;
2065         }
2066
2067         if ((fp = procmsg_open_mark_file(path, TRUE)) == NULL)
2068                 g_warning(_("can't open mark file\n"));
2069         else {
2070                 MsgInfo newmsginfo;
2071
2072                 newmsginfo.msgnum = num;
2073                 newmsginfo.flags = 0;
2074                 procmsg_write_flags(&newmsginfo, fp);
2075                 fclose(fp);
2076         }
2077         g_free(path);
2078
2079         return 0;
2080 }
2081
2082 static gint compose_queue(Compose *compose, const gchar *file)
2083 {
2084         FolderItem *queue;
2085         gchar *tmp, *queue_path;
2086         FILE *fp, *src_fp;
2087         GSList *cur;
2088         gchar buf[BUFFSIZE];
2089         gint num;
2090
2091         debug_print(_("queueing message...\n"));
2092         g_return_val_if_fail(compose->to_list != NULL, -1);
2093         g_return_val_if_fail(compose->account != NULL, -1);
2094
2095         tmp = g_strdup_printf("%s%cqueue.%d", g_get_tmp_dir(),
2096                               G_DIR_SEPARATOR, (gint)compose);
2097         if ((fp = fopen(tmp, "w")) == NULL) {
2098                 FILE_OP_ERROR(tmp, "fopen");
2099                 g_free(tmp);
2100                 return -1;
2101         }
2102         if ((src_fp = fopen(file, "r")) == NULL) {
2103                 FILE_OP_ERROR(file, "fopen");
2104                 fclose(fp);
2105                 unlink(tmp);
2106                 g_free(tmp);
2107                 return -1;
2108         }
2109         if (change_file_mode_rw(fp, tmp) < 0) {
2110                 FILE_OP_ERROR(tmp, "chmod");
2111                 g_warning(_("can't change file mode\n"));
2112         }
2113
2114         /* queueing variables */
2115         fprintf(fp, "AF:\n");
2116         fprintf(fp, "NF:0\n");
2117         fprintf(fp, "PS:10\n");
2118         fprintf(fp, "SRH:1\n");
2119         fprintf(fp, "SFN:\n");
2120         fprintf(fp, "DSR:\n");
2121         if (compose->msgid)
2122                 fprintf(fp, "MID:<%s>\n", compose->msgid);
2123         else
2124                 fprintf(fp, "MID:\n");
2125         fprintf(fp, "CFG:\n");
2126         fprintf(fp, "PT:0\n");
2127         fprintf(fp, "S:%s\n", compose->account->address);
2128         fprintf(fp, "RQ:\n");
2129         if (compose->account->smtp_server)
2130                 fprintf(fp, "SSV:%s\n", compose->account->smtp_server);
2131         else
2132                 fprintf(fp, "SSV:\n");
2133         if (compose->account->nntp_server)
2134                 fprintf(fp, "NSV:%s\n", compose->account->nntp_server);
2135         else
2136                 fprintf(fp, "NSV:\n");
2137         fprintf(fp, "SSH:\n");
2138         fprintf(fp, "R:<%s>", (gchar *)compose->to_list->data);
2139         for (cur = compose->to_list->next; cur != NULL; cur = cur->next)
2140                 fprintf(fp, ",<%s>", (gchar *)cur->data);
2141         fprintf(fp, "\n");
2142         fprintf(fp, "\n");
2143
2144         while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2145                 if (fputs(buf, fp) == EOF) {
2146                         FILE_OP_ERROR(tmp, "fputs");
2147                         fclose(fp);
2148                         fclose(src_fp);
2149                         unlink(tmp);
2150                         g_free(tmp);
2151                         return -1;
2152                 }
2153         }
2154
2155         fclose(src_fp);
2156         if (fclose(fp) == EOF) {
2157                 FILE_OP_ERROR(tmp, "fclose");
2158                 unlink(tmp);
2159                 g_free(tmp);
2160                 return -1;
2161         }
2162
2163         queue = folder_get_default_queue();
2164         folder_item_scan(queue);
2165         queue_path = folder_item_get_path(queue);
2166         if (!is_dir_exist(queue_path))
2167                 make_dir_hier(queue_path);
2168         if ((num = folder_item_add_msg(queue, tmp, TRUE)) < 0) {
2169                 g_warning(_("can't queue the message\n"));
2170                 unlink(tmp);
2171                 g_free(tmp);
2172                 g_free(queue_path);
2173                 return -1;
2174         }
2175         g_free(tmp);
2176
2177         if ((fp = procmsg_open_mark_file(queue_path, TRUE)) == NULL)
2178                 g_warning(_("can't open mark file\n"));
2179         else {
2180                 MsgInfo newmsginfo;
2181
2182                 newmsginfo.msgnum = num;
2183                 newmsginfo.flags = 0;
2184                 procmsg_write_flags(&newmsginfo, fp);
2185                 fclose(fp);
2186         }
2187         g_free(queue_path);
2188
2189         folder_item_scan(queue);
2190         folderview_update_item(queue, TRUE);
2191
2192         return 0;
2193 }
2194
2195 static void compose_write_attach(Compose *compose, FILE *fp)
2196 {
2197         AttachInfo *ainfo;
2198         GtkCList *clist = GTK_CLIST(compose->attach_clist);
2199         gint row;
2200         FILE *attach_fp;
2201         gchar filename[BUFFSIZE];
2202         gint len;
2203
2204         for (row = 0; (ainfo = gtk_clist_get_row_data(clist, row)) != NULL;
2205              row++) {
2206                 if ((attach_fp = fopen(ainfo->file, "r")) == NULL) {
2207                         g_warning(_("Can't open file %s\n"), ainfo->file);
2208                         continue;
2209                 }
2210
2211                 fprintf(fp, "\n--%s\n", compose->boundary);
2212
2213                 if (!strcmp2(ainfo->content_type, "message/rfc822")) {
2214                         fprintf(fp, "Content-Type: %s\n", ainfo->content_type);
2215                         fprintf(fp, "Content-Disposition: inline\n");
2216                 } else {
2217                         conv_encode_header(filename, sizeof(filename),
2218                                            ainfo->name, 12);
2219                         fprintf(fp, "Content-Type: %s;\n"
2220                                     " name=\"%s\"\n",
2221                                 ainfo->content_type, filename);
2222                         fprintf(fp, "Content-Disposition: attachment;\n"
2223                                     " filename=\"%s\"\n", filename);
2224                 }
2225
2226                 fprintf(fp, "Content-Transfer-Encoding: %s\n\n",
2227                         procmime_get_encoding_str(ainfo->encoding));
2228
2229                 if (ainfo->encoding == ENC_7BIT) {
2230                         gchar buf[BUFFSIZE];
2231
2232                         while (fgets(buf, sizeof(buf), attach_fp) != NULL) {
2233                                 len = strlen(buf);
2234                                 if (len > 1 && buf[len - 1] == '\n' &&
2235                                     buf[len - 2] == '\r') {
2236                                         buf[len - 2] = '\n';
2237                                         buf[len - 1] = '\0';
2238                                 }
2239                                 fputs(buf, fp);
2240                         }
2241                 } else {
2242                         gchar inbuf[B64_LINE_SIZE], outbuf[B64_BUFFSIZE];
2243
2244                         while ((len = fread(inbuf, sizeof(gchar),
2245                                             B64_LINE_SIZE, attach_fp))
2246                                == B64_LINE_SIZE) {
2247                                 to64frombits(outbuf, inbuf, B64_LINE_SIZE);
2248                                 fputs(outbuf, fp);
2249                                 fputc('\n', fp);
2250                         }
2251                         if (len > 0 && feof(attach_fp)) {
2252                                 to64frombits(outbuf, inbuf, len);
2253                                 fputs(outbuf, fp);
2254                                 fputc('\n', fp);
2255                         }
2256                 }
2257
2258                 fclose(attach_fp);
2259         }
2260
2261         fprintf(fp, "\n--%s--\n", compose->boundary);
2262 }
2263
2264 #define IS_IN_CUSTOM_HEADER(header) \
2265         (compose->account->add_customhdr && \
2266          custom_header_find(compose->account->customhdr_list, header) != NULL)
2267
2268 static gint compose_write_headers(Compose *compose, FILE *fp,
2269                                   const gchar *charset, EncodingType encoding,
2270                                   gboolean is_draft)
2271 {
2272         gchar buf[BUFFSIZE];
2273         gchar *str;
2274         /* struct utsname utsbuf; */
2275
2276         g_return_val_if_fail(fp != NULL, -1);
2277         g_return_val_if_fail(charset != NULL, -1);
2278         g_return_val_if_fail(compose->account != NULL, -1);
2279         g_return_val_if_fail(compose->account->address != NULL, -1);
2280
2281         /* Date */
2282         if (compose->account->add_date) {
2283                 get_rfc822_date(buf, sizeof(buf));
2284                 fprintf(fp, "Date: %s\n", buf);
2285         }
2286         
2287         /* From */
2288         if (!IS_IN_CUSTOM_HEADER("From")) {
2289                 if (compose->account->name && *compose->account->name) {
2290                         compose_convert_header
2291                                 (buf, sizeof(buf), compose->account->name,
2292                                  strlen("From: "));
2293                         fprintf(fp, "From: %s <%s>\n",
2294                                 buf, compose->account->address);
2295                 } else
2296                         fprintf(fp, "From: %s\n", compose->account->address);
2297         }
2298         
2299         slist_free_strings(compose->to_list);
2300         g_slist_free(compose->to_list);
2301         compose->to_list = NULL;
2302
2303         /* To */
2304         if (compose->use_to) {
2305                 str = gtk_entry_get_text(GTK_ENTRY(compose->to_entry));
2306                 if (*str != '\0') {
2307                         Xstrdup_a(str, str, return -1);
2308                         g_strstrip(str);
2309                         if (*str != '\0') {
2310                                 compose->to_list = address_list_append
2311                                         (compose->to_list, str);
2312                                 if (!IS_IN_CUSTOM_HEADER("To")) {
2313                                         compose_convert_header
2314                                                 (buf, sizeof(buf), str,
2315                                                  strlen("To: "));
2316                                         fprintf(fp, "To: %s\n", buf);
2317                                 }
2318                         }
2319                 }
2320         }
2321         
2322         slist_free_strings(compose->newsgroup_list);
2323         g_slist_free(compose->newsgroup_list);
2324         compose->newsgroup_list = NULL;
2325
2326         /* Newsgroups */
2327         str = gtk_entry_get_text(GTK_ENTRY(compose->newsgroups_entry));
2328         if (*str != '\0') {
2329                 Xstrdup_a(str, str, return -1);
2330                 g_strstrip(str);
2331                 remove_space(str);
2332                 if (*str != '\0') {
2333                         compose->newsgroup_list =
2334                                 newsgroup_list_append(compose->newsgroup_list,
2335                                                       str);
2336                         if (!IS_IN_CUSTOM_HEADER("Newsgroups")) {
2337                                 compose_convert_header(buf, sizeof(buf), str,
2338                                                        strlen("Newsgroups: "));
2339                                 fprintf(fp, "Newsgroups: %s\n", buf);
2340                         }
2341                 }
2342         }
2343
2344         if (!is_draft && !compose->to_list && !compose->newsgroup_list)
2345                 return -1;
2346
2347         /* Cc */
2348         if (compose->use_cc) {
2349                 str = gtk_entry_get_text(GTK_ENTRY(compose->cc_entry));
2350                 if (*str != '\0') {
2351                         Xstrdup_a(str, str, return -1);
2352                         g_strstrip(str);
2353                         if (*str != '\0') {
2354                                 compose->to_list = address_list_append
2355                                         (compose->to_list, str);
2356                                 if (!IS_IN_CUSTOM_HEADER("Cc")) {
2357                                         compose_convert_header
2358                                                 (buf, sizeof(buf), str,
2359                                                  strlen("Cc: "));
2360                                         fprintf(fp, "Cc: %s\n", buf);
2361                                 }
2362                         }
2363                 }
2364         }
2365         
2366         /* Bcc */
2367         if (compose->use_bcc) {
2368                 str = gtk_entry_get_text(GTK_ENTRY(compose->bcc_entry));
2369                 if (*str != '\0') {
2370                         Xstrdup_a(str, str, return -1);
2371                         g_strstrip(str);
2372                         if (*str != '\0') {
2373                                 compose->to_list = address_list_append
2374                                         (compose->to_list, str);
2375                                 if (is_draft) {
2376                                         compose_convert_header
2377                                                 (buf, sizeof(buf), str,
2378                                                  strlen("Bcc: "));
2379                                         fprintf(fp, "Bcc: %s\n", buf);
2380                                 }
2381                         }
2382                 }
2383         }
2384
2385         /* Subject */
2386         str = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
2387         if (*str != '\0' && !IS_IN_CUSTOM_HEADER("Subject")) {
2388                 Xstrdup_a(str, str, return -1);
2389                 g_strstrip(str);
2390                 if (*str != '\0') {
2391                         compose_convert_header(buf, sizeof(buf), str,
2392                                                strlen("Subject: "));
2393                         fprintf(fp, "Subject: %s\n", buf);
2394                 }
2395         }
2396
2397         /* Message-ID */
2398         if (compose->account->gen_msgid) {
2399                 compose_generate_msgid(compose, buf, sizeof(buf));
2400                 fprintf(fp, "Message-Id: <%s>\n", buf);
2401                 compose->msgid = g_strdup(buf);
2402         }
2403
2404         /* In-Reply-To */
2405         if (compose->inreplyto && compose->to_list)
2406                 fprintf(fp, "In-Reply-To: <%s>\n", compose->inreplyto);
2407
2408         /* References */
2409         if (compose->references)
2410                 fprintf(fp, "References: %s\n", compose->references);
2411
2412         /* Followup-To */
2413         if (compose->use_followupto && !IS_IN_CUSTOM_HEADER("Followup-To")) {
2414                 str = gtk_entry_get_text(GTK_ENTRY(compose->followup_entry));
2415                 if (*str != '\0') {
2416                         Xstrdup_a(str, str, return -1);
2417                         g_strstrip(str);
2418                         remove_space(str);
2419                         if (*str != '\0') {
2420                                 compose_convert_header(buf, sizeof(buf), str,
2421                                                        strlen("Followup-To: "));
2422                                 fprintf(fp, "Followup-To: %s\n", buf);
2423                         }
2424                 }
2425         }
2426
2427         /* Reply-To */
2428         if (compose->use_replyto && !IS_IN_CUSTOM_HEADER("Reply-To")) {
2429                 str = gtk_entry_get_text(GTK_ENTRY(compose->reply_entry));
2430                 if (*str != '\0') {
2431                         Xstrdup_a(str, str, return -1);
2432                         g_strstrip(str);
2433                         if (*str != '\0') {
2434                                 compose_convert_header(buf, sizeof(buf), str,
2435                                                        strlen("Reply-To: "));
2436                                 fprintf(fp, "Reply-To: %s\n", buf);
2437                         }
2438                 }
2439         }
2440
2441         /* Organization */
2442         if (compose->account->organization &&
2443             !IS_IN_CUSTOM_HEADER("Organization")) {
2444                 compose_convert_header(buf, sizeof(buf),
2445                                        compose->account->organization,
2446                                        strlen("Organization: "));
2447                 fprintf(fp, "Organization: %s\n", buf);
2448         }
2449
2450         /* Program version and system info */
2451         /* uname(&utsbuf); */
2452         str = gtk_entry_get_text(GTK_ENTRY(compose->to_entry));
2453         if (*str != '\0' && !IS_IN_CUSTOM_HEADER("X-Mailer")) {
2454                 fprintf(fp, "X-Mailer: %s (GTK+ %d.%d.%d; %s)\n",
2455                         prog_version,
2456                         gtk_major_version, gtk_minor_version, gtk_micro_version,
2457                         HOST_ALIAS);
2458                         /* utsbuf.sysname, utsbuf.release, utsbuf.machine); */
2459         }
2460         str = gtk_entry_get_text(GTK_ENTRY(compose->newsgroups_entry));
2461         if (*str != '\0' && !IS_IN_CUSTOM_HEADER("X-Newsreader")) {
2462                 fprintf(fp, "X-Newsreader: %s (GTK+ %d.%d.%d; %s)\n",
2463                         prog_version,
2464                         gtk_major_version, gtk_minor_version, gtk_micro_version,
2465                         HOST_ALIAS);
2466                         /* utsbuf.sysname, utsbuf.release, utsbuf.machine); */
2467         }
2468
2469         /* custom headers */
2470         if (compose->account->add_customhdr) {
2471                 GSList *cur;
2472
2473                 for (cur = compose->account->customhdr_list; cur != NULL;
2474                      cur = cur->next) {
2475                         CustomHeader *chdr = (CustomHeader *)cur->data;
2476
2477                         if (strcasecmp(chdr->name, "Date")         != 0 &&
2478                             strcasecmp(chdr->name, "From")         != 0 &&
2479                             strcasecmp(chdr->name, "To")           != 0 &&
2480                             strcasecmp(chdr->name, "Sender")       != 0 &&
2481                             strcasecmp(chdr->name, "Message-Id")   != 0 &&
2482                             strcasecmp(chdr->name, "In-Reply-To")  != 0 &&
2483                             strcasecmp(chdr->name, "References")   != 0 &&
2484                             strcasecmp(chdr->name, "Mime-Version") != 0 &&
2485                             strcasecmp(chdr->name, "Content-Type") != 0 &&
2486                             strcasecmp(chdr->name, "Content-Transfer-Encoding")
2487                             != 0)
2488                                 compose_convert_header
2489                                         (buf, sizeof(buf),
2490                                          chdr->value ? chdr->value : "",
2491                                          strlen(chdr->name) + 2);
2492                                 fprintf(fp, "%s: %s\n", chdr->name, buf);
2493                 }
2494         }
2495         
2496         /* MIME */
2497         fprintf(fp, "Mime-Version: 1.0\n");
2498         if (compose->use_attach) {
2499                 get_rfc822_date(buf, sizeof(buf));
2500                 subst_char(buf, ' ', '_');
2501                 subst_char(buf, ',', '_');
2502                 compose->boundary = g_strdup_printf("Multipart_%s_%08x",
2503                                                     buf, (guint)compose);
2504                 fprintf(fp,
2505                         "Content-Type: multipart/mixed;\n"
2506                         " boundary=\"%s\"\n", compose->boundary);
2507         } else {
2508                 fprintf(fp, "Content-Type: text/plain; charset=%s\n", charset);
2509                 fprintf(fp, "Content-Transfer-Encoding: %s\n",
2510                         procmime_get_encoding_str(encoding));
2511         }
2512
2513         /* Request Return Receipt */
2514         if (!IS_IN_CUSTOM_HEADER("Disposition-Notification-To")) {
2515                 if (compose->return_receipt) {
2516                         if (compose->account->name
2517                             && *compose->account->name) {
2518                                 compose_convert_header(buf, sizeof(buf), compose->account->name, strlen("Disposition-Notification-To: "));
2519                                 fprintf(fp, "Disposition-Notification-To: %s <%s>\n", buf, compose->account->address);
2520                         } else
2521                                 fprintf(fp, "Disposition-Notification-To: %s\n", compose->account->address);
2522                 }
2523         }
2524
2525         /* separator between header and body */
2526         fputs("\n", fp);
2527
2528         return 0;
2529 }
2530
2531 #undef IS_IN_CUSTOM_HEADER
2532
2533 static void compose_convert_header(gchar *dest, gint len, gchar *src,
2534                                    gint header_len)
2535 {
2536         g_return_if_fail(src != NULL);
2537         g_return_if_fail(dest != NULL);
2538
2539         if (len < 1) return;
2540
2541         remove_return(src);
2542
2543         if (is_ascii_str(src)) {
2544                 strncpy2(dest, src, len);
2545                 dest[len - 1] = '\0';
2546                 return;
2547         } else
2548                 conv_encode_header(dest, len, src, header_len);
2549 }
2550
2551 static void compose_generate_msgid(Compose *compose, gchar *buf, gint len)
2552 {
2553         struct tm *lt;
2554         time_t t;
2555         gchar *addr;
2556
2557         t = time(NULL);
2558         lt = localtime(&t);
2559
2560         if (compose->account && compose->account->address &&
2561             *compose->account->address) {
2562                 if (strchr(compose->account->address, '@'))
2563                         addr = g_strdup(compose->account->address);
2564                 else
2565                         addr = g_strconcat(compose->account->address, "@",
2566                                            get_domain_name(), NULL);
2567         } else
2568                 addr = g_strconcat(g_get_user_name(), "@", get_domain_name(),
2569                                    NULL);
2570
2571         g_snprintf(buf, len, "%04d%02d%02d%02d%02d%02d.%08x.%s",
2572                    lt->tm_year + 1900, lt->tm_mon + 1,
2573                    lt->tm_mday, lt->tm_hour,
2574                    lt->tm_min, lt->tm_sec,
2575                    (guint)random(), addr);
2576
2577         debug_print(_("generated Message-ID: %s\n"), buf);
2578
2579         g_free(addr);
2580 }
2581
2582 static void compose_add_entry_field(GtkWidget *table, GtkWidget **hbox,
2583                                     GtkWidget **entry, gint *count,
2584                                     const gchar *label_str,
2585                                     gboolean is_addr_entry)
2586 {
2587         GtkWidget *label;
2588
2589         if (GTK_TABLE(table)->nrows < (*count) + 1)
2590                 gtk_table_resize(GTK_TABLE(table), (*count) + 1, 2);
2591
2592         *hbox = gtk_hbox_new(FALSE, 0);
2593         label = gtk_label_new
2594                 (prefs_common.trans_hdr ? gettext(label_str) : label_str);
2595         gtk_box_pack_end(GTK_BOX(*hbox), label, FALSE, FALSE, 0);
2596         gtk_table_attach(GTK_TABLE(table), *hbox, 0, 1, *count, (*count) + 1,
2597                          GTK_FILL, 0, 2, 0);
2598         *entry = gtk_entry_new();
2599         gtk_table_attach_defaults
2600                 (GTK_TABLE(table), *entry, 1, 2, *count, (*count) + 1);
2601         if (GTK_TABLE(table)->nrows > (*count) + 1)
2602                 gtk_table_set_row_spacing(GTK_TABLE(table), *count, 4);
2603
2604         if (is_addr_entry)
2605                 address_completion_register_entry(GTK_ENTRY(*entry));
2606
2607         (*count)++;
2608 }
2609
2610 static Compose *compose_create(PrefsAccount *account)
2611 {
2612         Compose   *compose;
2613         GtkWidget *window;
2614         GtkWidget *vbox;
2615         GtkWidget *menubar;
2616         GtkWidget *handlebox;
2617
2618         GtkWidget *vbox2;
2619
2620         GtkWidget *table_vbox;
2621         GtkWidget *label;
2622         GtkWidget *from_optmenu_hbox;
2623         GtkWidget *to_entry;
2624         GtkWidget *to_hbox;
2625         GtkWidget *newsgroups_entry;
2626         GtkWidget *newsgroups_hbox;
2627         GtkWidget *subject_entry;
2628         GtkWidget *cc_entry;
2629         GtkWidget *cc_hbox;
2630         GtkWidget *bcc_entry;
2631         GtkWidget *bcc_hbox;
2632         GtkWidget *reply_entry;
2633         GtkWidget *reply_hbox;
2634         GtkWidget *followup_entry;
2635         GtkWidget *followup_hbox;
2636
2637         GtkWidget *paned;
2638
2639         GtkWidget *attach_scrwin;
2640         GtkWidget *attach_clist;
2641
2642         GtkWidget *edit_vbox;
2643         GtkWidget *ruler_hbox;
2644         GtkWidget *ruler;
2645         GtkWidget *scrolledwin;
2646         GtkWidget *text;
2647
2648         GtkWidget *table;
2649         GtkWidget *hbox;
2650
2651         gchar *titles[] = {_("MIME type"), _("Size"), _("Name")};
2652         guint n_menu_entries;
2653         GtkStyle  *style, *new_style;
2654         GdkColormap *cmap;
2655         GdkColor color[1];
2656         gboolean success[1];
2657         GdkFont   *font;
2658         GtkWidget *popupmenu;
2659         GtkWidget *menuitem;
2660         GtkItemFactory *popupfactory;
2661         GtkItemFactory *ifactory;
2662         gint n_entries;
2663         gint count = 0;
2664         gint i;
2665
2666         g_return_val_if_fail(account != NULL, NULL);
2667
2668         debug_print(_("Creating compose window...\n"));
2669         compose = g_new0(Compose, 1);
2670
2671         compose->account = account;
2672         compose->orig_account = account;
2673
2674         window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
2675         gtk_window_set_policy(GTK_WINDOW(window), TRUE, TRUE, FALSE);
2676         gtk_widget_set_usize(window, -1, prefs_common.compose_height);
2677         gtk_signal_connect(GTK_OBJECT(window), "delete_event",
2678                            GTK_SIGNAL_FUNC(compose_delete_cb), compose);
2679         gtk_signal_connect(GTK_OBJECT(window), "destroy",
2680                            GTK_SIGNAL_FUNC(compose_destroy_cb), compose);
2681         gtk_signal_connect(GTK_OBJECT(window), "focus_in_event",
2682                            GTK_SIGNAL_FUNC(manage_window_focus_in), NULL);
2683         gtk_signal_connect(GTK_OBJECT(window), "focus_out_event",
2684                            GTK_SIGNAL_FUNC(manage_window_focus_out), NULL);
2685         gtk_widget_realize(window);
2686
2687         vbox = gtk_vbox_new(FALSE, 0);
2688         gtk_container_add(GTK_CONTAINER(window), vbox);
2689
2690         n_menu_entries = sizeof(compose_entries) / sizeof(compose_entries[0]);
2691         menubar = menubar_create(window, compose_entries,
2692                                  n_menu_entries, "<Compose>", compose);
2693         gtk_box_pack_start(GTK_BOX(vbox), menubar, FALSE, TRUE, 0);
2694
2695         handlebox = gtk_handle_box_new();
2696         gtk_box_pack_start(GTK_BOX(vbox), handlebox, FALSE, FALSE, 0);
2697
2698         compose_toolbar_create(compose, handlebox);
2699
2700         vbox2 = gtk_vbox_new(FALSE, 2);
2701         gtk_box_pack_start(GTK_BOX(vbox), vbox2, TRUE, TRUE, 0);
2702         gtk_container_set_border_width(GTK_CONTAINER(vbox2), BORDER_WIDTH);
2703
2704         table_vbox = gtk_vbox_new(FALSE, 0);
2705         gtk_box_pack_start(GTK_BOX(vbox2), table_vbox, FALSE, TRUE, 0);
2706         gtk_container_set_border_width(GTK_CONTAINER(table_vbox),
2707                                        BORDER_WIDTH * 2);
2708
2709         table = gtk_table_new(8, 2, FALSE);
2710         gtk_box_pack_start(GTK_BOX(table_vbox), table, FALSE, TRUE, 0);
2711
2712         /* option menu for selecting accounts */
2713         hbox = gtk_hbox_new(FALSE, 0);
2714         label = gtk_label_new(prefs_common.trans_hdr ? _("From:") : "From:");
2715         gtk_box_pack_end(GTK_BOX(hbox), label, FALSE, FALSE, 0);
2716         gtk_table_attach(GTK_TABLE(table), hbox, 0, 1, count, count + 1,
2717                          GTK_FILL, 0, 2, 0);
2718         from_optmenu_hbox = compose_account_option_menu_create(compose);
2719         gtk_table_attach_defaults(GTK_TABLE(table), from_optmenu_hbox,
2720                                   1, 2, count, count + 1);
2721         gtk_table_set_row_spacing(GTK_TABLE(table), 0, 4);
2722         count++;
2723
2724         /* header labels and entries */
2725         compose_add_entry_field(table, &to_hbox, &to_entry, &count,
2726                                 "To:", TRUE); 
2727         gtk_table_set_row_spacing(GTK_TABLE(table), 0, 4);
2728         compose_add_entry_field(table, &newsgroups_hbox, &newsgroups_entry,
2729                                 &count, "Newsgroups:", FALSE);
2730         gtk_table_set_row_spacing(GTK_TABLE(table), 1, 4);
2731         compose_add_entry_field(table, &hbox, &subject_entry, &count,
2732                                 "Subject:", FALSE);
2733         gtk_table_set_row_spacing(GTK_TABLE(table), 2, 4);
2734         compose_add_entry_field(table, &cc_hbox, &cc_entry, &count,
2735                                 "Cc:", TRUE);
2736         gtk_table_set_row_spacing(GTK_TABLE(table), 3, 4);
2737         compose_add_entry_field(table, &bcc_hbox, &bcc_entry, &count,
2738                                 "Bcc:", TRUE);
2739         gtk_table_set_row_spacing(GTK_TABLE(table), 4, 4);
2740         compose_add_entry_field(table, &reply_hbox, &reply_entry, &count,
2741                                 "Reply-To:", TRUE);
2742         gtk_table_set_row_spacing(GTK_TABLE(table), 5, 4);
2743         compose_add_entry_field(table, &followup_hbox, &followup_entry, &count,
2744                                 "Followup-To:", FALSE);
2745         gtk_table_set_row_spacing(GTK_TABLE(table), 6, 4);
2746
2747         gtk_table_set_col_spacings(GTK_TABLE(table), 4);
2748
2749         gtk_signal_connect(GTK_OBJECT(to_entry), "activate",
2750                            GTK_SIGNAL_FUNC(to_activated), compose);
2751         gtk_signal_connect(GTK_OBJECT(newsgroups_entry), "activate",
2752                            GTK_SIGNAL_FUNC(newsgroups_activated), compose);
2753         gtk_signal_connect(GTK_OBJECT(subject_entry), "activate",
2754                            GTK_SIGNAL_FUNC(subject_activated), compose);
2755         gtk_signal_connect(GTK_OBJECT(cc_entry), "activate",
2756                            GTK_SIGNAL_FUNC(cc_activated), compose);
2757         gtk_signal_connect(GTK_OBJECT(bcc_entry), "activate",
2758                            GTK_SIGNAL_FUNC(bcc_activated), compose);
2759         gtk_signal_connect(GTK_OBJECT(reply_entry), "activate",
2760                            GTK_SIGNAL_FUNC(replyto_activated), compose);
2761         gtk_signal_connect(GTK_OBJECT(followup_entry), "activate",
2762                            GTK_SIGNAL_FUNC(followupto_activated), compose);
2763
2764         gtk_signal_connect(GTK_OBJECT(subject_entry), "grab_focus",
2765                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
2766         gtk_signal_connect(GTK_OBJECT(to_entry), "grab_focus",
2767                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
2768         gtk_signal_connect(GTK_OBJECT(newsgroups_entry), "grab_focus",
2769                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
2770         gtk_signal_connect(GTK_OBJECT(cc_entry), "grab_focus",
2771                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
2772         gtk_signal_connect(GTK_OBJECT(bcc_entry), "grab_focus",
2773                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
2774         gtk_signal_connect(GTK_OBJECT(reply_entry), "grab_focus",
2775                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
2776         gtk_signal_connect(GTK_OBJECT(followup_entry), "grab_focus",
2777                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
2778
2779         /* attachment list */
2780         attach_scrwin = gtk_scrolled_window_new(NULL, NULL);
2781         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(attach_scrwin),
2782                                        GTK_POLICY_AUTOMATIC,
2783                                        GTK_POLICY_ALWAYS);
2784         gtk_widget_set_usize(attach_scrwin, -1, 80);
2785
2786         attach_clist = gtk_clist_new_with_titles(N_ATTACH_COLS, titles);
2787         gtk_clist_set_column_justification(GTK_CLIST(attach_clist), COL_SIZE,
2788                                            GTK_JUSTIFY_RIGHT);
2789         gtk_clist_set_column_width(GTK_CLIST(attach_clist), COL_MIMETYPE, 240);
2790         gtk_clist_set_column_width(GTK_CLIST(attach_clist), COL_SIZE, 64);
2791         gtk_clist_set_selection_mode(GTK_CLIST(attach_clist),
2792                                      GTK_SELECTION_EXTENDED);
2793         for (i = 0; i < N_ATTACH_COLS; i++)
2794                 GTK_WIDGET_UNSET_FLAGS
2795                         (GTK_CLIST(attach_clist)->column[i].button,
2796                          GTK_CAN_FOCUS);
2797         gtk_container_add(GTK_CONTAINER(attach_scrwin), attach_clist);
2798
2799         gtk_signal_connect(GTK_OBJECT(attach_clist), "select_row",
2800                            GTK_SIGNAL_FUNC(attach_selected), compose);
2801         gtk_signal_connect(GTK_OBJECT(attach_clist), "button_press_event",
2802                            GTK_SIGNAL_FUNC(attach_button_pressed), compose);
2803         gtk_signal_connect(GTK_OBJECT(attach_clist), "key_press_event",
2804                            GTK_SIGNAL_FUNC(attach_key_pressed), compose);
2805
2806         /* drag and drop */
2807         gtk_drag_dest_set(attach_clist,
2808                           GTK_DEST_DEFAULT_ALL, compose_mime_types, 1,
2809                           GDK_ACTION_COPY);
2810         gtk_signal_connect(GTK_OBJECT(attach_clist), "drag_data_received",
2811                            GTK_SIGNAL_FUNC(compose_attach_drag_received_cb),
2812                            compose);
2813
2814         /* pane between attach clist and text */
2815         paned = gtk_vpaned_new();
2816         gtk_paned_add1(GTK_PANED(paned), attach_scrwin);
2817         gtk_widget_ref(paned);
2818         gtk_widget_show_all(paned);
2819
2820         edit_vbox = gtk_vbox_new(FALSE, 0);
2821         gtk_box_pack_start(GTK_BOX(vbox2), edit_vbox, TRUE, TRUE, 0);
2822
2823         /* ruler */
2824         ruler_hbox = gtk_hbox_new(FALSE, 0);
2825         gtk_box_pack_start(GTK_BOX(edit_vbox), ruler_hbox, FALSE, FALSE, 0);
2826
2827         ruler = gtk_shruler_new();
2828         gtk_ruler_set_range(GTK_RULER(ruler), 0.0, 100.0, 1.0, 100.0);
2829         gtk_box_pack_start(GTK_BOX(ruler_hbox), ruler, TRUE, TRUE,
2830                            BORDER_WIDTH + 1);
2831         gtk_widget_set_usize(ruler_hbox, 1, -1);
2832
2833         /* text widget */
2834         scrolledwin = gtk_scrolled_window_new(NULL, NULL);
2835         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin),
2836                                        GTK_POLICY_NEVER, GTK_POLICY_ALWAYS);
2837         gtk_box_pack_start(GTK_BOX(edit_vbox), scrolledwin, TRUE, TRUE, 0);
2838         gtk_widget_set_usize(scrolledwin, prefs_common.compose_width, -1);
2839
2840         text = gtk_stext_new(gtk_scrolled_window_get_hadjustment
2841                             (GTK_SCROLLED_WINDOW(scrolledwin)),
2842                             gtk_scrolled_window_get_vadjustment
2843                             (GTK_SCROLLED_WINDOW(scrolledwin)));
2844         gtk_stext_set_editable(GTK_STEXT(text), TRUE);
2845         gtk_stext_set_word_wrap(GTK_STEXT(text), TRUE);
2846         gtk_stext_set_wrap_rmargin(GTK_STEXT(text), prefs_common.linewrap_len);
2847
2848         gtk_container_add(GTK_CONTAINER(scrolledwin), text);
2849
2850         gtk_signal_connect(GTK_OBJECT(text), "changed",
2851                            GTK_SIGNAL_FUNC(compose_changed_cb), compose);
2852         gtk_signal_connect(GTK_OBJECT(text), "grab_focus",
2853                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
2854         gtk_signal_connect_after(GTK_OBJECT(text), "button_press_event",
2855                                  GTK_SIGNAL_FUNC(compose_button_press_cb),
2856                                  compose);
2857 #if 0
2858         gtk_signal_connect_after(GTK_OBJECT(text), "key_press_event",
2859                                  GTK_SIGNAL_FUNC(compose_key_press_cb),
2860                                  compose);
2861 #endif
2862         gtk_signal_connect_after(GTK_OBJECT(text), "size_allocate",
2863                                  GTK_SIGNAL_FUNC(compose_edit_size_alloc),
2864                                  ruler);
2865
2866         /* drag and drop */
2867         gtk_drag_dest_set(text, GTK_DEST_DEFAULT_ALL, compose_mime_types, 1,
2868                           GDK_ACTION_COPY);
2869         gtk_signal_connect(GTK_OBJECT(text), "drag_data_received",
2870                            GTK_SIGNAL_FUNC(compose_insert_drag_received_cb),
2871                            compose);
2872
2873         gtk_widget_show_all(vbox);
2874
2875         style = gtk_widget_get_style(text);
2876
2877         /* workaround for the slow down of GtkSText when using Pixmap theme */
2878         if (style->engine) {
2879                 GtkThemeEngine *engine;
2880
2881                 engine = style->engine;
2882                 style->engine = NULL;
2883                 new_style = gtk_style_copy(style);
2884                 style->engine = engine;
2885         } else
2886                 new_style = gtk_style_copy(style);
2887
2888         if (prefs_common.textfont) {
2889                 CharSet charset;
2890
2891                 charset = conv_get_current_charset();
2892                 if (MB_CUR_MAX == 1) {
2893                         gchar *fontstr, *p;
2894
2895                         Xstrdup_a(fontstr, prefs_common.textfont, );
2896                         if (fontstr && (p = strchr(fontstr, ',')) != NULL)
2897                                 *p = '\0';
2898                         font = gdk_font_load(fontstr);
2899                 } else
2900                         font = gdk_fontset_load(prefs_common.textfont);
2901                 if (font) {
2902                         gdk_font_unref(new_style->font);
2903                         new_style->font = font;
2904                 }
2905         }
2906
2907         gtk_widget_set_style(text, new_style);
2908
2909         color[0] = quote_color;
2910         cmap = gdk_window_get_colormap(window->window);
2911         gdk_colormap_alloc_colors(cmap, color, 1, FALSE, TRUE, success);
2912         if (success[0] == FALSE) {
2913                 g_warning("Compose: color allocation failed.\n");
2914                 style = gtk_widget_get_style(text);
2915                 quote_color = style->black;
2916         }
2917
2918         n_entries = sizeof(compose_popup_entries) /
2919                 sizeof(compose_popup_entries[0]);
2920         popupmenu = menu_create_items(compose_popup_entries, n_entries,
2921                                       "<Compose>", &popupfactory,
2922                                       compose);
2923
2924         ifactory = gtk_item_factory_from_widget(menubar);
2925         menu_set_sensitive(ifactory, "/Edit/Undo", FALSE);
2926         menu_set_sensitive(ifactory, "/Edit/Redo", FALSE);
2927
2928         /*
2929         if (account->protocol == A_NNTP) {
2930                 gtk_widget_hide(to_hbox);
2931                 gtk_widget_hide(to_entry);
2932                 gtk_widget_hide(cc_hbox);
2933                 gtk_widget_hide(cc_entry);
2934                 gtk_table_set_row_spacing(GTK_TABLE(table), 1, 0);
2935                 gtk_table_set_row_spacing(GTK_TABLE(table), 3, 0);
2936         } else {
2937                 gtk_widget_hide(newsgroups_hbox);
2938                 gtk_widget_hide(newsgroups_entry);
2939                 gtk_table_set_row_spacing(GTK_TABLE(table), 2, 0);
2940
2941                 menu_set_sensitive(ifactory, "/Message/Followup to", FALSE);
2942         }
2943         */
2944
2945         switch (prefs_common.toolbar_style) {
2946         case TOOLBAR_NONE:
2947                 gtk_widget_hide(handlebox);
2948                 break;
2949         case TOOLBAR_ICON:
2950                 gtk_toolbar_set_style(GTK_TOOLBAR(compose->toolbar),
2951                                       GTK_TOOLBAR_ICONS);
2952                 break;
2953         case TOOLBAR_TEXT:
2954                 gtk_toolbar_set_style(GTK_TOOLBAR(compose->toolbar),
2955                                       GTK_TOOLBAR_TEXT);
2956                 break;
2957         case TOOLBAR_BOTH:
2958                 gtk_toolbar_set_style(GTK_TOOLBAR(compose->toolbar),
2959                                       GTK_TOOLBAR_BOTH);
2960                 break;
2961         }
2962
2963         gtk_widget_show(window);
2964
2965         address_completion_start(window);
2966
2967         compose->window        = window;
2968         compose->vbox          = vbox;
2969         compose->menubar       = menubar;
2970         compose->handlebox     = handlebox;
2971
2972         compose->vbox2         = vbox2;
2973
2974         compose->table_vbox       = table_vbox;
2975         compose->table            = table;
2976         compose->to_hbox          = to_hbox;
2977         compose->to_entry         = to_entry;
2978         compose->newsgroups_hbox  = newsgroups_hbox;
2979         compose->newsgroups_entry = newsgroups_entry;
2980         compose->subject_entry    = subject_entry;
2981         compose->cc_hbox          = cc_hbox;
2982         compose->cc_entry         = cc_entry;
2983         compose->bcc_hbox         = bcc_hbox;
2984         compose->bcc_entry        = bcc_entry;
2985         compose->reply_hbox       = reply_hbox;
2986         compose->reply_entry      = reply_entry;
2987         compose->followup_hbox    = followup_hbox;
2988         compose->followup_entry   = followup_entry;
2989
2990         compose->paned = paned;
2991
2992         compose->attach_scrwin = attach_scrwin;
2993         compose->attach_clist  = attach_clist;
2994
2995         compose->edit_vbox     = edit_vbox;
2996         compose->ruler_hbox    = ruler_hbox;
2997         compose->ruler         = ruler;
2998         compose->scrolledwin   = scrolledwin;
2999         compose->text          = text;
3000
3001         compose->focused_editable = NULL;
3002
3003         compose->popupmenu    = popupmenu;
3004         compose->popupfactory = popupfactory;
3005
3006         compose->mode = COMPOSE_NEW;
3007
3008         compose->replyto     = NULL;
3009         compose->cc          = NULL;
3010         compose->bcc         = NULL;
3011         compose->followup_to = NULL;
3012         compose->inreplyto   = NULL;
3013         compose->references  = NULL;
3014         compose->msgid       = NULL;
3015         compose->boundary    = NULL;
3016
3017 #if USE_GPGME
3018         compose->use_signing    = FALSE;
3019         compose->use_encryption = FALSE;
3020 #endif /* USE_GPGME */
3021
3022         compose->modified = FALSE;
3023
3024         compose->return_receipt = FALSE;
3025
3026         compose->to_list        = NULL;
3027         compose->newsgroup_list = NULL;
3028
3029         compose->exteditor_file    = NULL;
3030         compose->exteditor_pid     = -1;
3031         compose->exteditor_readdes = -1;
3032         compose->exteditor_tag     = -1;
3033
3034         compose_set_title(compose);
3035
3036         /*
3037         if (account->protocol != A_NNTP) {
3038                 menuitem = gtk_item_factory_get_item(ifactory, "/Message/To");
3039                 gtk_check_menu_item_set_active
3040                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
3041                 gtk_widget_set_sensitive(menuitem, FALSE);
3042                 menuitem = gtk_item_factory_get_item(ifactory, "/Message/Cc");
3043                 gtk_check_menu_item_set_active
3044                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
3045                 gtk_widget_set_sensitive(menuitem, FALSE);
3046         }
3047         */
3048         if (account->set_autocc && account->auto_cc) {
3049                 gtk_entry_set_text(GTK_ENTRY(cc_entry), account->auto_cc);
3050                 menuitem = gtk_item_factory_get_item(ifactory, "/Message/Cc");
3051                 gtk_check_menu_item_set_active
3052                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
3053         }
3054
3055         if (account->set_autobcc) {
3056                 menuitem = gtk_item_factory_get_item(ifactory, "/Message/Bcc");
3057                 gtk_check_menu_item_set_active
3058                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
3059                 if (account->auto_bcc)
3060                         gtk_entry_set_text(GTK_ENTRY(bcc_entry),
3061                                            account->auto_bcc);
3062         }
3063         if (account->set_autoreplyto) {
3064                 menuitem = gtk_item_factory_get_item(ifactory,
3065                                                      "/Message/Reply to");
3066                 gtk_check_menu_item_set_active
3067                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
3068                 if (account->auto_replyto)
3069                         gtk_entry_set_text(GTK_ENTRY(reply_entry),
3070                                            account->auto_replyto);
3071         }
3072
3073         menuitem = gtk_item_factory_get_item(ifactory, "/Tool/Show ruler");
3074         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
3075                                        prefs_common.show_ruler);
3076
3077 #if USE_GPGME
3078         menuitem = gtk_item_factory_get_item(ifactory, "/Message/Sign");
3079         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
3080                                        prefs_common.default_sign);
3081         menuitem = gtk_item_factory_get_item(ifactory, "/Message/Encrypt");
3082         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
3083                                        prefs_common.default_encrypt);
3084 #endif /* USE_GPGME */
3085
3086         addressbook_set_target_compose(compose);
3087
3088         compose_list = g_list_append(compose_list, compose);
3089
3090         /*
3091         compose->use_to         = FALSE;
3092         compose->use_cc         = FALSE;
3093         */
3094         compose->use_attach     = FALSE;
3095
3096         compose->use_bcc        = FALSE;
3097         compose->use_replyto    = FALSE;
3098         compose->use_followupto = FALSE;
3099         gtk_widget_hide(bcc_hbox);
3100         gtk_widget_hide(bcc_entry);
3101         gtk_widget_hide(reply_hbox);
3102         gtk_widget_hide(reply_entry);
3103         gtk_widget_hide(followup_hbox);
3104         gtk_widget_hide(followup_entry);
3105         gtk_widget_hide(ruler_hbox);
3106         gtk_table_set_row_spacing(GTK_TABLE(table), 4, 0);
3107         gtk_table_set_row_spacing(GTK_TABLE(table), 5, 0);
3108         gtk_table_set_row_spacing(GTK_TABLE(table), 6, 0);
3109
3110
3111         select_account(compose, account);
3112
3113         return compose;
3114 }
3115
3116 #include "pixmaps/stock_mail_send.xpm"
3117 #include "pixmaps/stock_mail.xpm"
3118 #include "pixmaps/stock_paste.xpm"
3119 #include "pixmaps/stock_mail_attach.xpm"
3120 #include "pixmaps/stock_mail_compose.xpm"
3121 #include "pixmaps/linewrap.xpm"
3122 //#include "pixmaps/tb_mail_queue_send.xpm"
3123 #include "pixmaps/tb_address_book.xpm"
3124
3125 #define CREATE_TOOLBAR_ICON(xpm_d) \
3126 { \
3127         icon = gdk_pixmap_create_from_xpm_d(container->window, &mask, \
3128                                             &container->style->white, \
3129                                             xpm_d); \
3130         icon_wid = gtk_pixmap_new(icon, mask); \
3131 }
3132
3133 static void compose_toolbar_create(Compose *compose, GtkWidget *container)
3134 {
3135         GtkWidget *toolbar;
3136         GdkPixmap *icon;
3137         GdkBitmap *mask;
3138         GtkWidget *icon_wid;
3139         GtkWidget *send_btn;
3140         GtkWidget *sendl_btn;
3141         GtkWidget *draft_btn;
3142         GtkWidget *insert_btn;
3143         GtkWidget *attach_btn;
3144         GtkWidget *sig_btn;
3145         GtkWidget *exteditor_btn;
3146         GtkWidget *linewrap_btn;
3147         GtkWidget *addrbook_btn;
3148
3149         toolbar = gtk_toolbar_new(GTK_ORIENTATION_HORIZONTAL,
3150                                   GTK_TOOLBAR_BOTH);
3151         gtk_container_add(GTK_CONTAINER(container), toolbar);
3152         gtk_container_set_border_width(GTK_CONTAINER(container), 2);
3153         gtk_toolbar_set_button_relief(GTK_TOOLBAR(toolbar), GTK_RELIEF_NONE);
3154         gtk_toolbar_set_space_style(GTK_TOOLBAR(toolbar),
3155                                     GTK_TOOLBAR_SPACE_LINE);
3156
3157         CREATE_TOOLBAR_ICON(stock_mail_send_xpm);
3158         send_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
3159                                            _("Send"),
3160                                            _("Send message"),
3161                                            "Send",
3162                                            icon_wid, toolbar_send_cb, compose);
3163
3164         CREATE_TOOLBAR_ICON(stock_mail_send_xpm);
3165         //CREATE_TOOLBAR_ICON(tb_mail_queue_send_xpm);
3166         sendl_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
3167                                            _("Send later"),
3168                                            _("Put into queue folder and send later"),
3169                                            "Send later",
3170                                            icon_wid, toolbar_send_later_cb,
3171                                            compose);
3172
3173         CREATE_TOOLBAR_ICON(stock_mail_xpm);
3174         draft_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
3175                                             _("Draft"),
3176                                             _("Save to draft folder"),
3177                                             "Draft",
3178                                             icon_wid, toolbar_draft_cb,
3179                                             compose);
3180
3181         gtk_toolbar_append_space(GTK_TOOLBAR(toolbar));
3182
3183         CREATE_TOOLBAR_ICON(stock_paste_xpm);
3184         insert_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
3185                                              _("Insert"),
3186                                              _("Insert file"),
3187                                              "Insert",
3188                                              icon_wid, toolbar_insert_cb,
3189                                              compose);
3190
3191         CREATE_TOOLBAR_ICON(stock_mail_attach_xpm);
3192         attach_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
3193                                              _("Attach"),
3194                                              _("Attach file"),
3195                                              "Attach",
3196                                              icon_wid, toolbar_attach_cb,
3197                                              compose);
3198
3199         gtk_toolbar_append_space(GTK_TOOLBAR(toolbar));
3200
3201         CREATE_TOOLBAR_ICON(stock_mail_xpm);
3202         sig_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
3203                                           _("Signature"),
3204                                           _("Insert signature"),
3205                                           "Signature",
3206                                           icon_wid, toolbar_sig_cb, compose);
3207
3208         gtk_toolbar_append_space(GTK_TOOLBAR(toolbar));
3209
3210         CREATE_TOOLBAR_ICON(stock_mail_compose_xpm);
3211         exteditor_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
3212                                                 _("Editor"),
3213                                                 _("Edit with external editor"),
3214                                                 "Editor",
3215                                                 icon_wid,
3216                                                 toolbar_ext_editor_cb,
3217                                                 compose);
3218
3219         CREATE_TOOLBAR_ICON(linewrap_xpm);
3220         linewrap_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
3221                                                _("Linewrap"),
3222                                                _("Wrap long lines"),
3223                                                "Linewrap",
3224                                                icon_wid,
3225                                                toolbar_linewrap_cb,
3226                                                compose);
3227
3228         gtk_toolbar_append_space(GTK_TOOLBAR(toolbar));
3229
3230         CREATE_TOOLBAR_ICON(tb_address_book_xpm);
3231         addrbook_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
3232                                                _("Address"),
3233                                                _("Address book"),
3234                                                "Address",
3235                                                icon_wid, toolbar_address_cb,
3236                                                compose);
3237
3238         compose->toolbar       = toolbar;
3239         compose->send_btn      = send_btn;
3240         compose->sendl_btn     = sendl_btn;
3241         compose->draft_btn     = draft_btn;
3242         compose->insert_btn    = insert_btn;
3243         compose->attach_btn    = attach_btn;
3244         compose->sig_btn       = sig_btn;
3245         compose->exteditor_btn = exteditor_btn;
3246         compose->linewrap_btn  = linewrap_btn;
3247         compose->addrbook_btn  = addrbook_btn;
3248
3249         gtk_widget_show_all(toolbar);
3250 }
3251
3252 #undef CREATE_TOOLBAR_ICON
3253
3254 static GtkWidget *compose_account_option_menu_create(Compose *compose)
3255 {
3256         GList *accounts;
3257         GtkWidget *hbox;
3258         GtkWidget *optmenu;
3259         GtkWidget *menu;
3260         gint num = 0, def_menu = 0;
3261
3262         accounts = account_get_list();
3263         g_return_val_if_fail(accounts != NULL, NULL);
3264
3265         hbox = gtk_hbox_new(FALSE, 0);
3266         optmenu = gtk_option_menu_new();
3267         gtk_box_pack_start(GTK_BOX(hbox), optmenu, FALSE, FALSE, 0);
3268         menu = gtk_menu_new();
3269
3270         for (; accounts != NULL; accounts = accounts->next, num++) {
3271                 PrefsAccount *ac = (PrefsAccount *)accounts->data;
3272                 GtkWidget *menuitem;
3273                 gchar *name;
3274
3275                 if (ac == compose->account) def_menu = num;
3276
3277                 name = g_strdup_printf("%s <%s> (%s)",
3278                                        ac->name, ac->address, ac->account_name);
3279                 MENUITEM_ADD(menu, menuitem, name, ac);
3280                 g_free(name);
3281                 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
3282                                    GTK_SIGNAL_FUNC(account_activated),
3283                                    compose);
3284         }
3285
3286         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), menu);
3287         gtk_option_menu_set_history(GTK_OPTION_MENU(optmenu), def_menu);
3288
3289         return hbox;
3290 }
3291
3292 static void compose_destroy(Compose *compose)
3293 {
3294         gint row;
3295         GtkCList *clist = GTK_CLIST(compose->attach_clist);
3296         AttachInfo *ainfo;
3297
3298         /* NOTE: address_completion_end() does nothing with the window
3299          * however this may change. */
3300         address_completion_end(compose->window);
3301
3302         slist_free_strings(compose->to_list);
3303         g_slist_free(compose->to_list);
3304         slist_free_strings(compose->newsgroup_list);
3305         g_slist_free(compose->newsgroup_list);
3306
3307         procmsg_msginfo_free(compose->targetinfo);
3308
3309         g_free(compose->replyto);
3310         g_free(compose->cc);
3311         g_free(compose->bcc);
3312         g_free(compose->newsgroups);
3313         g_free(compose->followup_to);
3314
3315         g_free(compose->inreplyto);
3316         g_free(compose->references);
3317         g_free(compose->msgid);
3318         g_free(compose->boundary);
3319
3320         g_free(compose->exteditor_file);
3321
3322         for (row = 0; (ainfo = gtk_clist_get_row_data(clist, row)) != NULL;
3323              row++)
3324                 compose_attach_info_free(ainfo);
3325
3326         if (addressbook_get_target_compose() == compose)
3327                 addressbook_set_target_compose(NULL);
3328
3329         prefs_common.compose_width = compose->scrolledwin->allocation.width;
3330         prefs_common.compose_height = compose->window->allocation.height;
3331
3332         gtk_widget_destroy(compose->paned);
3333
3334         g_free(compose);
3335
3336         compose_list = g_list_remove(compose_list, compose);
3337 }
3338
3339 static void compose_attach_info_free(AttachInfo *ainfo)
3340 {
3341         g_free(ainfo->file);
3342         g_free(ainfo->content_type);
3343         g_free(ainfo->name);
3344         g_free(ainfo);
3345 }
3346
3347 static void compose_attach_remove_selected(Compose *compose)
3348 {
3349         GtkCList *clist = GTK_CLIST(compose->attach_clist);
3350         AttachInfo *ainfo;
3351         gint row;
3352
3353         while (clist->selection != NULL) {
3354                 row = GPOINTER_TO_INT(clist->selection->data);
3355                 ainfo = gtk_clist_get_row_data(clist, row);
3356                 compose_attach_info_free(ainfo);
3357                 gtk_clist_remove(clist, row);
3358         }
3359 }
3360
3361 static struct _AttachProperty
3362 {
3363         GtkWidget *window;
3364         GtkWidget *mimetype_entry;
3365         GtkWidget *encoding_optmenu;
3366         GtkWidget *path_entry;
3367         GtkWidget *filename_entry;
3368         GtkWidget *ok_btn;
3369         GtkWidget *cancel_btn;
3370 } attach_prop;
3371
3372 static void compose_attach_property(Compose *compose)
3373 {
3374         GtkCList *clist = GTK_CLIST(compose->attach_clist);
3375         AttachInfo *ainfo;
3376         gint row;
3377         gboolean cancelled;
3378         GtkOptionMenu *optmenu;
3379
3380         if (!clist->selection) return;
3381         row = GPOINTER_TO_INT(clist->selection->data);
3382
3383         ainfo = gtk_clist_get_row_data(clist, row);
3384         if (!ainfo) return;
3385
3386         if (!attach_prop.window)
3387                 compose_attach_property_create(&cancelled);
3388         gtk_widget_grab_focus(attach_prop.ok_btn);
3389         gtk_widget_show(attach_prop.window);
3390         manage_window_set_transient(GTK_WINDOW(attach_prop.window));
3391
3392         optmenu = GTK_OPTION_MENU(attach_prop.encoding_optmenu);
3393         if (ainfo->encoding == ENC_UNKNOWN)
3394                 gtk_option_menu_set_history(optmenu, ENC_BASE64);
3395         else
3396                 gtk_option_menu_set_history(optmenu, ainfo->encoding);
3397
3398         gtk_entry_set_text(GTK_ENTRY(attach_prop.mimetype_entry),
3399                            ainfo->content_type ? ainfo->content_type : "");
3400         gtk_entry_set_text(GTK_ENTRY(attach_prop.path_entry),
3401                            ainfo->file ? ainfo->file : "");
3402         gtk_entry_set_text(GTK_ENTRY(attach_prop.filename_entry),
3403                            ainfo->name ? ainfo->name : "");
3404
3405         for (;;) {
3406                 gchar *text;
3407                 gchar *cnttype = NULL;
3408                 gchar *file = NULL;
3409                 off_t size = 0;
3410                 GtkWidget *menu;
3411                 GtkWidget *menuitem;
3412
3413                 gtk_main();
3414
3415                 if (cancelled == TRUE) {
3416                         gtk_widget_hide(attach_prop.window);
3417                         break;
3418                 }
3419
3420                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.mimetype_entry));
3421                 if (*text != '\0') {
3422                         gchar *p;
3423
3424                         text = g_strstrip(g_strdup(text));
3425                         if ((p = strchr(text, '/')) && !strchr(p + 1, '/')) {
3426                                 cnttype = g_strdup(text);
3427                                 g_free(text);
3428                         } else {
3429                                 alertpanel_error(_("Invalid MIME type."));
3430                                 g_free(text);
3431                                 continue;
3432                         }
3433                 }
3434
3435                 menu = gtk_option_menu_get_menu(optmenu);
3436                 menuitem = gtk_menu_get_active(GTK_MENU(menu));
3437                 ainfo->encoding = GPOINTER_TO_INT
3438                         (gtk_object_get_user_data(GTK_OBJECT(menuitem)));
3439
3440                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.path_entry));
3441                 if (*text != '\0') {
3442                         if (is_file_exist(text) &&
3443                             (size = get_file_size(text)) > 0)
3444                                 file = g_strdup(text);
3445                         else {
3446                                 alertpanel_error
3447                                         (_("File doesn't exist or is empty."));
3448                                 g_free(cnttype);
3449                                 continue;
3450                         }
3451                 }
3452
3453                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.filename_entry));
3454                 if (*text != '\0') {
3455                         g_free(ainfo->name);
3456                         ainfo->name = g_strdup(text);
3457                 }
3458
3459                 if (cnttype) {
3460                         g_free(ainfo->content_type);
3461                         ainfo->content_type = cnttype;
3462                 }
3463                 if (file) {
3464                         g_free(ainfo->file);
3465                         ainfo->file = file;
3466                 }
3467                 if (size)
3468                         ainfo->size = size;
3469
3470                 gtk_clist_set_text(clist, row, COL_MIMETYPE,
3471                                    ainfo->content_type);
3472                 gtk_clist_set_text(clist, row, COL_SIZE,
3473                                    to_human_readable(ainfo->size));
3474                 gtk_clist_set_text(clist, row, COL_NAME, ainfo->name);
3475
3476                 gtk_widget_hide(attach_prop.window);
3477                 break;
3478         }
3479 }
3480
3481 #define SET_LABEL_AND_ENTRY(str, entry, top) \
3482 { \
3483         label = gtk_label_new(str); \
3484         gtk_table_attach(GTK_TABLE(table), label, 0, 1, top, (top + 1), \
3485                          GTK_FILL, 0, 0, 0); \
3486         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); \
3487  \
3488         entry = gtk_entry_new(); \
3489         gtk_table_attach(GTK_TABLE(table), entry, 1, 2, top, (top + 1), \
3490                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0); \
3491 }
3492
3493 static void compose_attach_property_create(gboolean *cancelled)
3494 {
3495         GtkWidget *window;
3496         GtkWidget *vbox;
3497         GtkWidget *table;
3498         GtkWidget *label;
3499         GtkWidget *mimetype_entry;
3500         GtkWidget *hbox;
3501         GtkWidget *optmenu;
3502         GtkWidget *optmenu_menu;
3503         GtkWidget *menuitem;
3504         GtkWidget *path_entry;
3505         GtkWidget *filename_entry;
3506         GtkWidget *hbbox;
3507         GtkWidget *ok_btn;
3508         GtkWidget *cancel_btn;
3509
3510         debug_print("Creating attach_property window...\n");
3511
3512         window = gtk_window_new(GTK_WINDOW_DIALOG);
3513         gtk_widget_set_usize(window, 480, -1);
3514         gtk_container_set_border_width(GTK_CONTAINER(window), 8);
3515         gtk_window_set_title(GTK_WINDOW(window), _("Property"));
3516         gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
3517         gtk_window_set_modal(GTK_WINDOW(window), TRUE);
3518         gtk_signal_connect(GTK_OBJECT(window), "delete_event",
3519                            GTK_SIGNAL_FUNC(attach_property_delete_event),
3520                            cancelled);
3521         gtk_signal_connect(GTK_OBJECT(window), "key_press_event",
3522                            GTK_SIGNAL_FUNC(attach_property_key_pressed),
3523                            cancelled);
3524
3525         vbox = gtk_vbox_new(FALSE, 8);
3526         gtk_container_add(GTK_CONTAINER(window), vbox);
3527
3528         table = gtk_table_new(4, 2, FALSE);
3529         gtk_box_pack_start(GTK_BOX(vbox), table, FALSE, FALSE, 0);
3530         gtk_table_set_row_spacings(GTK_TABLE(table), 8);
3531         gtk_table_set_col_spacings(GTK_TABLE(table), 8);
3532
3533         SET_LABEL_AND_ENTRY(_("MIME type"), mimetype_entry, 0);
3534
3535         label = gtk_label_new(_("Encoding"));
3536         gtk_table_attach(GTK_TABLE(table), label, 0, 1, 1, 2,
3537                          GTK_FILL, 0, 0, 0);
3538         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5);
3539
3540         hbox = gtk_hbox_new(FALSE, 0);
3541         gtk_table_attach(GTK_TABLE(table), hbox, 1, 2, 1, 2,
3542                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0);
3543
3544         optmenu = gtk_option_menu_new();
3545         gtk_box_pack_start(GTK_BOX(hbox), optmenu, FALSE, FALSE, 0);
3546
3547         optmenu_menu = gtk_menu_new();
3548         MENUITEM_ADD(optmenu_menu, menuitem, "7bit", ENC_7BIT);
3549         gtk_widget_set_sensitive(menuitem, FALSE);
3550         MENUITEM_ADD(optmenu_menu, menuitem, "8bit", ENC_8BIT);
3551         gtk_widget_set_sensitive(menuitem, FALSE);
3552         MENUITEM_ADD(optmenu_menu, menuitem, "quoted-printable", ENC_QUOTED_PRINTABLE);
3553         gtk_widget_set_sensitive(menuitem, FALSE);
3554         MENUITEM_ADD(optmenu_menu, menuitem, "base64", ENC_BASE64);
3555
3556         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
3557
3558         SET_LABEL_AND_ENTRY(_("Path"),      path_entry,     2);
3559         SET_LABEL_AND_ENTRY(_("File name"), filename_entry, 3);
3560
3561         gtkut_button_set_create(&hbbox, &ok_btn, _("OK"),
3562                                 &cancel_btn, _("Cancel"), NULL, NULL);
3563         gtk_box_pack_end(GTK_BOX(vbox), hbbox, FALSE, FALSE, 0);
3564         gtk_widget_grab_default(ok_btn);
3565
3566         gtk_signal_connect(GTK_OBJECT(ok_btn), "clicked",
3567                            GTK_SIGNAL_FUNC(attach_property_ok),
3568                            cancelled);
3569         gtk_signal_connect(GTK_OBJECT(cancel_btn), "clicked",
3570                            GTK_SIGNAL_FUNC(attach_property_cancel),
3571                            cancelled);
3572
3573         gtk_widget_show_all(vbox);
3574
3575         attach_prop.window           = window;
3576         attach_prop.mimetype_entry   = mimetype_entry;
3577         attach_prop.encoding_optmenu = optmenu;
3578         attach_prop.path_entry       = path_entry;
3579         attach_prop.filename_entry   = filename_entry;
3580         attach_prop.ok_btn           = ok_btn;
3581         attach_prop.cancel_btn       = cancel_btn;
3582 }
3583
3584 #undef SET_LABEL_AND_ENTRY
3585
3586 static void attach_property_ok(GtkWidget *widget, gboolean *cancelled)
3587 {
3588         *cancelled = FALSE;
3589         gtk_main_quit();
3590 }
3591
3592 static void attach_property_cancel(GtkWidget *widget, gboolean *cancelled)
3593 {
3594         *cancelled = TRUE;
3595         gtk_main_quit();
3596 }
3597
3598 static gint attach_property_delete_event(GtkWidget *widget, GdkEventAny *event,
3599                                          gboolean *cancelled)
3600 {
3601         *cancelled = TRUE;
3602         gtk_main_quit();
3603
3604         return TRUE;
3605 }
3606
3607 static void attach_property_key_pressed(GtkWidget *widget, GdkEventKey *event,
3608                                         gboolean *cancelled)
3609 {
3610         if (event && event->keyval == GDK_Escape) {
3611                 *cancelled = TRUE;
3612                 gtk_main_quit();
3613         }
3614 }
3615
3616 static void compose_exec_ext_editor(Compose *compose)
3617 {
3618         gchar tmp[64];
3619         pid_t pid;
3620         gint pipe_fds[2];
3621
3622         g_snprintf(tmp, sizeof(tmp), "%s%ctmpmsg.%08x",
3623                    g_get_tmp_dir(), G_DIR_SEPARATOR, (gint)compose);
3624
3625         if (pipe(pipe_fds) < 0) {
3626                 perror("pipe");
3627                 return;
3628         }
3629
3630         if ((pid = fork()) < 0) {
3631                 perror("fork");
3632                 return;
3633         }
3634
3635         if (pid != 0) {
3636                 /* close the write side of the pipe */
3637                 close(pipe_fds[1]);
3638
3639                 compose->exteditor_file    = g_strdup(tmp);
3640                 compose->exteditor_pid     = pid;
3641                 compose->exteditor_readdes = pipe_fds[0];
3642
3643                 compose_set_ext_editor_sensitive(compose, FALSE);
3644
3645                 compose->exteditor_tag =
3646                         gdk_input_add(pipe_fds[0], GDK_INPUT_READ,
3647                                       compose_input_cb, compose);
3648         } else {        /* process-monitoring process */
3649                 pid_t pid_ed;
3650
3651                 if (setpgid(0, 0))
3652                         perror("setpgid");
3653
3654                 /* close the read side of the pipe */
3655                 close(pipe_fds[0]);
3656
3657                 if (compose_write_body_to_file(compose, tmp) < 0) {
3658                         fd_write(pipe_fds[1], "2\n", 2);
3659                         _exit(1);
3660                 }
3661
3662                 pid_ed = compose_exec_ext_editor_real(tmp);
3663                 if (pid_ed < 0) {
3664                         fd_write(pipe_fds[1], "1\n", 2);
3665                         _exit(1);
3666                 }
3667
3668                 /* wait until editor is terminated */
3669                 waitpid(pid_ed, NULL, 0);
3670
3671                 fd_write(pipe_fds[1], "0\n", 2);
3672
3673                 close(pipe_fds[1]);
3674                 _exit(0);
3675         }
3676 }
3677
3678 static gint compose_exec_ext_editor_real(const gchar *file)
3679 {
3680         static gchar *def_cmd = "emacs %s";
3681         gchar buf[1024];
3682         gchar *p;
3683         gchar **cmdline;
3684         pid_t pid;
3685
3686         g_return_val_if_fail(file != NULL, -1);
3687
3688         if ((pid = fork()) < 0) {
3689                 perror("fork");
3690                 return -1;
3691         }
3692
3693         if (pid != 0) return pid;
3694
3695         /* grandchild process */
3696
3697         if (setpgid(0, getppid()))
3698                 perror("setpgid");
3699
3700         if (prefs_common.ext_editor_cmd &&
3701             (p = strchr(prefs_common.ext_editor_cmd, '%')) &&
3702             *(p + 1) == 's' && !strchr(p + 2, '%')) {
3703                 g_snprintf(buf, sizeof(buf), prefs_common.ext_editor_cmd, file);
3704         } else {
3705                 if (prefs_common.ext_editor_cmd)
3706                         g_warning(_("External editor command line is invalid: `%s'\n"),
3707                                   prefs_common.ext_editor_cmd);
3708                 g_snprintf(buf, sizeof(buf), def_cmd, file);
3709         }
3710
3711         cmdline = g_strsplit(buf, " ", 1024);
3712         execvp(cmdline[0], cmdline);
3713
3714         perror("execvp");
3715         g_strfreev(cmdline);
3716
3717         _exit(1);
3718 }
3719
3720 static gboolean compose_ext_editor_kill(Compose *compose)
3721 {
3722         pid_t pgid = compose->exteditor_pid * -1;
3723         gint ret;
3724
3725         ret = kill(pgid, 0);
3726
3727         if (ret == 0 || (ret == -1 && EPERM == errno)) {
3728                 AlertValue val;
3729                 gchar *msg;
3730
3731                 msg = g_strdup_printf
3732                         (_("The external editor is still working.\n"
3733                            "Force terminating the process?\n"
3734                            "process group id: %d"), -pgid);
3735                 val = alertpanel(_("Notice"), msg, _("Yes"), _("+No"), NULL);
3736                 g_free(msg);
3737
3738                 if (val == G_ALERTDEFAULT) {
3739                         gdk_input_remove(compose->exteditor_tag);
3740                         close(compose->exteditor_readdes);
3741
3742                         if (kill(pgid, SIGTERM) < 0) perror("kill");
3743                         waitpid(compose->exteditor_pid, NULL, 0);
3744
3745                         g_warning(_("Terminated process group id: %d"), -pgid);
3746                         g_warning(_("Temporary file: %s"),
3747                                   compose->exteditor_file);
3748
3749                         compose_set_ext_editor_sensitive(compose, TRUE);
3750
3751                         g_free(compose->exteditor_file);
3752                         compose->exteditor_file    = NULL;
3753                         compose->exteditor_pid     = -1;
3754                         compose->exteditor_readdes = -1;
3755                         compose->exteditor_tag     = -1;
3756                 } else
3757                         return FALSE;
3758         }
3759
3760         return TRUE;
3761 }
3762
3763 static void compose_input_cb(gpointer data, gint source,
3764                              GdkInputCondition condition)
3765 {
3766         gchar buf[3];
3767         Compose *compose = (Compose *)data;
3768         gint i = 0;
3769
3770         debug_print(_("Compose: input from monitoring process\n"));
3771
3772         gdk_input_remove(compose->exteditor_tag);
3773
3774         for (;;) {
3775                 if (read(source, &buf[i], 1) < 1) {
3776                         buf[0] = '3';
3777                         break;
3778                 }
3779                 if (buf[i] == '\n') {
3780                         buf[i] = '\0';
3781                         break;
3782                 }
3783                 i++;
3784                 if (i == sizeof(buf) - 1)
3785                         break;
3786         }
3787
3788         waitpid(compose->exteditor_pid, NULL, 0);
3789
3790         if (buf[0] == '0') {            /* success */
3791                 GtkSText *text = GTK_STEXT(compose->text);
3792
3793                 gtk_stext_freeze(text);
3794                 gtk_stext_set_point(text, 0);
3795                 gtk_stext_forward_delete(text, gtk_stext_get_length(text));
3796                 compose_insert_file(compose, compose->exteditor_file);
3797                 compose_changed_cb(NULL, compose);
3798                 gtk_stext_thaw(text);
3799
3800                 if (unlink(compose->exteditor_file) < 0)
3801                         FILE_OP_ERROR(compose->exteditor_file, "unlink");
3802         } else if (buf[0] == '1') {     /* failed */
3803                 g_warning(_("Couldn't exec external editor\n"));
3804                 if (unlink(compose->exteditor_file) < 0)
3805                         FILE_OP_ERROR(compose->exteditor_file, "unlink");
3806         } else if (buf[0] == '2') {
3807                 g_warning(_("Couldn't write to file\n"));
3808         } else if (buf[0] == '3') {
3809                 g_warning(_("Pipe read failed\n"));
3810         }
3811
3812         close(source);
3813
3814         compose_set_ext_editor_sensitive(compose, TRUE);
3815
3816         g_free(compose->exteditor_file);
3817         compose->exteditor_file    = NULL;
3818         compose->exteditor_pid     = -1;
3819         compose->exteditor_readdes = -1;
3820         compose->exteditor_tag     = -1;
3821 }
3822
3823 static void compose_set_ext_editor_sensitive(Compose *compose,
3824                                              gboolean sensitive)
3825 {
3826         GtkItemFactory *ifactory;
3827
3828         ifactory = gtk_item_factory_from_widget(compose->menubar);
3829
3830         menu_set_sensitive(ifactory, "/Message/Send", sensitive);
3831         menu_set_sensitive(ifactory, "/Message/Send later", sensitive);
3832         menu_set_sensitive(ifactory, "/Message/Save to draft folder",
3833                            sensitive);
3834         menu_set_sensitive(ifactory, "/File/Insert file", sensitive);
3835         menu_set_sensitive(ifactory, "/File/Insert signature", sensitive);
3836         menu_set_sensitive(ifactory, "/Edit/Wrap long lines", sensitive);
3837         menu_set_sensitive(ifactory, "/Edit/Edit with external editor",
3838                            sensitive);
3839
3840         gtk_widget_set_sensitive(compose->text,          sensitive);
3841         gtk_widget_set_sensitive(compose->send_btn,      sensitive);
3842         gtk_widget_set_sensitive(compose->sendl_btn,     sensitive);
3843         gtk_widget_set_sensitive(compose->draft_btn,     sensitive);
3844         gtk_widget_set_sensitive(compose->insert_btn,    sensitive);
3845         gtk_widget_set_sensitive(compose->sig_btn,       sensitive);
3846         gtk_widget_set_sensitive(compose->exteditor_btn, sensitive);
3847         gtk_widget_set_sensitive(compose->linewrap_btn,  sensitive);
3848 }
3849
3850 static gint calc_cursor_xpos(GtkSText *text, gint extra, gint char_width)
3851 {
3852         gint cursor_pos;
3853
3854         cursor_pos = (text->cursor_pos_x - extra) / char_width;
3855         cursor_pos = MAX(cursor_pos, 0);
3856
3857         return cursor_pos;
3858 }
3859
3860 /* callback functions */
3861
3862 /* compose_edit_size_alloc() - called when resized. don't know whether Gtk
3863  * includes "non-client" (windows-izm) in calculation, so this calculation
3864  * may not be accurate.
3865  */
3866 static gboolean compose_edit_size_alloc(GtkEditable *widget,
3867                                         GtkAllocation *allocation,
3868                                         GtkSHRuler *shruler)
3869 {
3870         if (prefs_common.show_ruler) {
3871                 gint char_width;
3872                 gint line_width_in_chars;
3873
3874                 char_width = gtkut_get_font_width
3875                         (GTK_WIDGET(widget)->style->font);
3876                 line_width_in_chars =
3877                         (allocation->width - allocation->x) / char_width;
3878
3879                 /* got the maximum */
3880                 gtk_ruler_set_range(GTK_RULER(shruler),
3881                                     0.0, line_width_in_chars,
3882                                     calc_cursor_xpos(GTK_STEXT(widget),
3883                                                      allocation->x,
3884                                                      char_width),
3885                                     /*line_width_in_chars*/ char_width);
3886         }
3887
3888         return TRUE;
3889 }
3890
3891 static void toolbar_send_cb(GtkWidget *widget, gpointer data)
3892 {
3893         compose_send_cb(data, 0, NULL);
3894 }
3895
3896 static void toolbar_send_later_cb(GtkWidget *widget, gpointer data)
3897 {
3898         compose_send_later_cb(data, 0, NULL);
3899 }
3900
3901 static void toolbar_draft_cb(GtkWidget *widget, gpointer data)
3902 {
3903         compose_draft_cb(data, 0, NULL);
3904 }
3905
3906 static void toolbar_insert_cb(GtkWidget *widget, gpointer data)
3907 {
3908         compose_insert_file_cb(data, 0, NULL);
3909 }
3910
3911 static void toolbar_attach_cb(GtkWidget *widget, gpointer data)
3912 {
3913         compose_attach_cb(data, 0, NULL);
3914 }
3915
3916 static void toolbar_sig_cb(GtkWidget *widget, gpointer data)
3917 {
3918         Compose *compose = (Compose *)data;
3919
3920         compose_insert_sig(compose);
3921 }
3922
3923 static void toolbar_ext_editor_cb(GtkWidget *widget, gpointer data)
3924 {
3925         Compose *compose = (Compose *)data;
3926
3927         compose_exec_ext_editor(compose);
3928 }
3929
3930 static void toolbar_linewrap_cb(GtkWidget *widget, gpointer data)
3931 {
3932         Compose *compose = (Compose *)data;
3933
3934         compose_wrap_line(compose);
3935 }
3936
3937 static void toolbar_address_cb(GtkWidget *widget, gpointer data)
3938 {
3939         compose_address_cb(data, 0, NULL);
3940 }
3941
3942 static void select_account(Compose * compose, PrefsAccount * ac)
3943 {
3944                 compose->account = ac;
3945                 compose_set_title(compose);
3946
3947                 if (ac->protocol == A_NNTP) {
3948                         GtkItemFactory *ifactory;
3949                         GtkWidget *menuitem;
3950
3951                         ifactory = gtk_item_factory_from_widget(compose->menubar);
3952                         menu_set_sensitive(ifactory,
3953                                            "/Message/Followup to", TRUE);
3954
3955                         gtk_widget_show(compose->newsgroups_hbox);
3956                         gtk_widget_show(compose->newsgroups_entry);
3957                         gtk_table_set_row_spacing(GTK_TABLE(compose->table),
3958                                                   1, 4);
3959
3960                         compose->use_to = FALSE;
3961                         compose->use_cc = FALSE;
3962
3963                         menuitem = gtk_item_factory_get_item(ifactory, "/Message/To");
3964                         gtk_check_menu_item_set_active
3965                                 (GTK_CHECK_MENU_ITEM(menuitem), FALSE);
3966                         menu_set_sensitive(ifactory,
3967                                            "/Message/To", TRUE);
3968                         menuitem = gtk_item_factory_get_item(ifactory, "/Message/Cc");
3969                         gtk_check_menu_item_set_active
3970                                 (GTK_CHECK_MENU_ITEM(menuitem), FALSE);
3971
3972                         gtk_widget_hide(compose->to_hbox);
3973                         gtk_widget_hide(compose->to_entry);
3974                         gtk_widget_hide(compose->cc_hbox);
3975                         gtk_widget_hide(compose->cc_entry);
3976
3977                         gtk_table_set_row_spacing(GTK_TABLE(compose->table),
3978                                                   0, 0);
3979                         gtk_table_set_row_spacing(GTK_TABLE(compose->table),
3980                                                   3, 0);
3981                 }
3982                 else {
3983                         GtkItemFactory *ifactory;
3984                         GtkWidget *menuitem;
3985
3986                         ifactory = gtk_item_factory_from_widget(compose->menubar);
3987                         menu_set_sensitive(ifactory,
3988                                            "/Message/Followup to", FALSE);
3989
3990                         gtk_entry_set_text(GTK_ENTRY(compose->newsgroups_entry), "");
3991                         gtk_widget_hide(compose->newsgroups_hbox);
3992                         gtk_widget_hide(compose->newsgroups_entry);
3993                         gtk_table_set_row_spacing(GTK_TABLE(compose->table),
3994                                                   1, 0);
3995
3996                         compose->use_to = TRUE;
3997                         compose->use_cc = TRUE;
3998
3999                         menuitem = gtk_item_factory_get_item(ifactory, "/Message/To");
4000                         gtk_check_menu_item_set_active
4001                                 (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
4002                         menu_set_sensitive(ifactory,
4003                                            "/Message/To", FALSE);
4004                         menuitem = gtk_item_factory_get_item(ifactory, "/Message/Cc");
4005                         gtk_check_menu_item_set_active
4006                                 (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
4007
4008                         gtk_widget_show(compose->to_hbox);
4009                         gtk_widget_show(compose->to_entry);
4010                         gtk_widget_show(compose->cc_hbox);
4011                         gtk_widget_show(compose->cc_entry);
4012
4013                         gtk_table_set_row_spacing(GTK_TABLE(compose->table),
4014                                                   0, 4);
4015                         gtk_table_set_row_spacing(GTK_TABLE(compose->table),
4016                                                   3, 4);
4017                 }
4018                 gtk_widget_queue_resize(compose->table_vbox);
4019 }
4020
4021 static void account_activated(GtkMenuItem *menuitem, gpointer data)
4022 {
4023         Compose *compose = (Compose *)data;
4024
4025         PrefsAccount *ac;
4026
4027         ac = (PrefsAccount *)gtk_object_get_user_data(GTK_OBJECT(menuitem));
4028         g_return_if_fail(ac != NULL);
4029
4030         if (ac != compose->account)
4031                 select_account(compose, ac);
4032 }
4033
4034 static void attach_selected(GtkCList *clist, gint row, gint column,
4035                             GdkEvent *event, gpointer data)
4036 {
4037         Compose *compose = (Compose *)data;
4038
4039         if (event && event->type == GDK_2BUTTON_PRESS)
4040                 compose_attach_property(compose);
4041 }
4042
4043 static void attach_button_pressed(GtkWidget *widget, GdkEventButton *event,
4044                                   gpointer data)
4045 {
4046         Compose *compose = (Compose *)data;
4047         GtkCList *clist = GTK_CLIST(compose->attach_clist);
4048         gint row, column;
4049
4050         if (!event) return;
4051
4052         if (event->button == 3) {
4053                 if ((clist->selection && !clist->selection->next) ||
4054                     !clist->selection) {
4055                         gtk_clist_unselect_all(clist);
4056                         if (gtk_clist_get_selection_info(clist,
4057                                                          event->x, event->y,
4058                                                          &row, &column)) {
4059                                 gtk_clist_select_row(clist, row, column);
4060                                 gtkut_clist_set_focus_row(clist, row);
4061                         }
4062                 }
4063                 gtk_menu_popup(GTK_MENU(compose->popupmenu), NULL, NULL,
4064                                NULL, NULL, event->button, event->time);
4065         }
4066 }
4067
4068 static void attach_key_pressed(GtkWidget *widget, GdkEventKey *event,
4069                                gpointer data)
4070 {
4071         Compose *compose = (Compose *)data;
4072
4073         if (!event) return;
4074
4075         switch (event->keyval) {
4076         case GDK_Delete:
4077                 compose_attach_remove_selected(compose);
4078                 break;
4079         }
4080 }
4081
4082 static void compose_send_cb(gpointer data, guint action, GtkWidget *widget)
4083 {
4084         Compose *compose = (Compose *)data;
4085         gint val;
4086
4087         val = compose_send(compose);
4088
4089         if (val == 0) gtk_widget_destroy(compose->window);
4090 }
4091
4092 static void compose_send_later_cb(gpointer data, guint action,
4093                                   GtkWidget *widget)
4094 {
4095         Compose *compose = (Compose *)data;
4096         gchar tmp[22];
4097         gchar *to, *newsgroups;
4098
4099         to = gtk_entry_get_text(GTK_ENTRY(compose->to_entry));
4100         newsgroups = gtk_entry_get_text(GTK_ENTRY(compose->newsgroups_entry));
4101         if (*to == '\0' && *newsgroups == '\0') {
4102                 alertpanel_error(_("Recipient is not specified."));
4103                 return;
4104         }
4105
4106         g_snprintf(tmp, 22, "%s%ctmpmsg%d",
4107                    g_get_tmp_dir(), G_DIR_SEPARATOR, (gint)compose);
4108
4109         if (prefs_common.linewrap_at_send)
4110                 compose_wrap_line(compose);
4111
4112         if (compose_write_to_file(compose, tmp, FALSE) < 0 ||
4113             compose_queue(compose, tmp) < 0) {
4114                 alertpanel_error(_("Can't queue the message."));
4115                 return;
4116         }
4117
4118         if (prefs_common.savemsg) {
4119                 if (compose_save_to_outbox(compose, tmp) < 0)
4120                         alertpanel_error
4121                                 (_("Can't save the message to outbox."));
4122         }
4123
4124         if (unlink(tmp) < 0)
4125                 FILE_OP_ERROR(tmp, "unlink");
4126
4127         gtk_widget_destroy(compose->window);
4128 }
4129
4130 static void compose_draft_cb(gpointer data, guint action, GtkWidget *widget)
4131 {
4132         Compose *compose = (Compose *)data;
4133         FolderItem *draft;
4134         gchar *tmp;
4135
4136         draft = folder_get_default_draft();
4137         folder_item_scan(draft);
4138
4139         if (procmsg_msg_exist(compose->targetinfo) &&
4140             compose->targetinfo->folder == draft) {
4141                 if (folder_item_remove_msg(draft,
4142                                            compose->targetinfo->msgnum) < 0)
4143                         g_warning(_("can't remove the old draft message\n"));
4144         }
4145         tmp = g_strdup_printf("%s%cdraft.%d", g_get_tmp_dir(),
4146                               G_DIR_SEPARATOR, (gint)compose);
4147
4148         if (compose_write_to_file(compose, tmp, TRUE) < 0) {
4149                 g_free(tmp);
4150                 return;
4151         }
4152
4153         if (folder_item_add_msg(draft, tmp, TRUE) < 0) {
4154                 unlink(tmp);
4155                 g_free(tmp);
4156                 return;
4157         }
4158
4159         g_free(tmp);
4160
4161         //folderview_scan_folder_a(DRAFT_DIR, TRUE);
4162
4163         gtk_widget_destroy(compose->window);
4164 }
4165
4166 static void compose_attach_cb(gpointer data, guint action, GtkWidget *widget)
4167 {
4168         Compose *compose = (Compose *)data;
4169         gchar *file;
4170
4171         file = filesel_select_file(_("Select file"), NULL);
4172
4173         if (file)
4174                 compose_attach_append(compose, file, MIME_UNKNOWN);
4175 }
4176
4177 static void compose_insert_file_cb(gpointer data, guint action,
4178                                    GtkWidget *widget)
4179 {
4180         Compose *compose = (Compose *)data;
4181         gchar *file;
4182
4183         file = filesel_select_file(_("Select file"), NULL);
4184
4185         if (file)
4186                 compose_insert_file(compose, file);
4187 }
4188
4189 static gint compose_delete_cb(GtkWidget *widget, GdkEventAny *event,
4190                               gpointer data)
4191 {
4192         compose_close_cb(data, 0, NULL);
4193         return TRUE;
4194 }
4195
4196 static void compose_close_cb(gpointer data, guint action, GtkWidget *widget)
4197 {
4198         Compose *compose = (Compose *)data;
4199         AlertValue val;
4200
4201         if (compose->exteditor_tag != -1) {
4202                 if (!compose_ext_editor_kill(compose))
4203                         return;
4204         }
4205
4206         if (compose->modified) {
4207                 val = alertpanel(_("Discard message"),
4208                                  _("This message has been modified. discard it?"),
4209                                  _("Discard"), _("to Draft"), _("Cancel"));
4210
4211                 switch (val) {
4212                 case G_ALERTDEFAULT:
4213                         break;
4214                 case G_ALERTALTERNATE:
4215                         compose_draft_cb(data, 0, NULL);
4216                         return;
4217                 default:
4218                         return;
4219                 }
4220         }
4221
4222         gtk_widget_destroy(compose->window);
4223 }
4224
4225 static void compose_address_cb(gpointer data, guint action, GtkWidget *widget)
4226 {
4227         Compose *compose = (Compose *)data;
4228
4229         addressbook_open(compose);
4230 }
4231
4232 static void compose_ext_editor_cb(gpointer data, guint action,
4233                                   GtkWidget *widget)
4234 {
4235         Compose *compose = (Compose *)data;
4236
4237         compose_exec_ext_editor(compose);
4238 }
4239
4240 static void compose_destroy_cb(GtkWidget *widget, Compose *compose)
4241 {
4242         compose_destroy(compose);
4243 }
4244
4245 static void compose_cut_cb(Compose *compose)
4246 {
4247         if (compose->focused_editable &&
4248             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
4249                 gtk_editable_cut_clipboard
4250                         (GTK_EDITABLE(compose->focused_editable));
4251 }
4252
4253 static void compose_copy_cb(Compose *compose)
4254 {
4255         if (compose->focused_editable &&
4256             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
4257                 gtk_editable_copy_clipboard
4258                         (GTK_EDITABLE(compose->focused_editable));
4259 }
4260
4261 static void compose_paste_cb(Compose *compose)
4262 {
4263         if (compose->focused_editable &&
4264             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
4265                 gtk_editable_paste_clipboard
4266                         (GTK_EDITABLE(compose->focused_editable));
4267 }
4268
4269 static void compose_allsel_cb(Compose *compose)
4270 {
4271         if (compose->focused_editable &&
4272             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
4273                 gtk_editable_select_region
4274                         (GTK_EDITABLE(compose->focused_editable), 0, -1);
4275 }
4276
4277 static void compose_grab_focus_cb(GtkWidget *widget, Compose *compose)
4278 {
4279         if (GTK_IS_EDITABLE(widget))
4280                 compose->focused_editable = widget;
4281 }
4282
4283 static void compose_changed_cb(GtkEditable *editable, Compose *compose)
4284 {
4285         if (compose->modified == FALSE) {
4286                 compose->modified = TRUE;
4287                 compose_set_title(compose);
4288         }
4289 }
4290
4291 static void compose_button_press_cb(GtkWidget *widget, GdkEventButton *event,
4292                                     Compose *compose)
4293 {
4294         gtk_stext_set_point(GTK_STEXT(widget),
4295                            gtk_editable_get_position(GTK_EDITABLE(widget)));
4296 }
4297
4298 #if 0
4299 static void compose_key_press_cb(GtkWidget *widget, GdkEventKey *event,
4300                                  Compose *compose)
4301 {
4302         gtk_stext_set_point(GTK_STEXT(widget),
4303                            gtk_editable_get_position(GTK_EDITABLE(widget)));
4304 }
4305 #endif
4306
4307 static void compose_toggle_to_cb(gpointer data, guint action,
4308                                  GtkWidget *widget)
4309 {
4310         Compose *compose = (Compose *)data;
4311
4312         if (GTK_CHECK_MENU_ITEM(widget)->active) {
4313                 gtk_widget_show(compose->to_hbox);
4314                 gtk_widget_show(compose->to_entry);
4315                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 1, 4);
4316                 compose->use_to = TRUE;
4317         } else {
4318                 gtk_widget_hide(compose->to_hbox);
4319                 gtk_widget_hide(compose->to_entry);
4320                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 1, 0);
4321                 gtk_widget_queue_resize(compose->table_vbox);
4322                 compose->use_to = FALSE;
4323         }
4324
4325         if (addressbook_get_target_compose() == compose)
4326                 addressbook_set_target_compose(compose);
4327 }
4328
4329 static void compose_toggle_cc_cb(gpointer data, guint action,
4330                                  GtkWidget *widget)
4331 {
4332         Compose *compose = (Compose *)data;
4333
4334         if (GTK_CHECK_MENU_ITEM(widget)->active) {
4335                 gtk_widget_show(compose->cc_hbox);
4336                 gtk_widget_show(compose->cc_entry);
4337                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 3, 4);
4338                 compose->use_cc = TRUE;
4339         } else {
4340                 gtk_widget_hide(compose->cc_hbox);
4341                 gtk_widget_hide(compose->cc_entry);
4342                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 3, 0);
4343                 gtk_widget_queue_resize(compose->table_vbox);
4344                 compose->use_cc = FALSE;
4345         }
4346
4347         if (addressbook_get_target_compose() == compose)
4348                 addressbook_set_target_compose(compose);
4349 }
4350
4351 static void compose_toggle_bcc_cb(gpointer data, guint action,
4352                                   GtkWidget *widget)
4353 {
4354         Compose *compose = (Compose *)data;
4355
4356         if (GTK_CHECK_MENU_ITEM(widget)->active) {
4357                 gtk_widget_show(compose->bcc_hbox);
4358                 gtk_widget_show(compose->bcc_entry);
4359                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 4, 4);
4360                 compose->use_bcc = TRUE;
4361         } else {
4362                 gtk_widget_hide(compose->bcc_hbox);
4363                 gtk_widget_hide(compose->bcc_entry);
4364                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 4, 0);
4365                 gtk_widget_queue_resize(compose->table_vbox);
4366                 compose->use_bcc = FALSE;
4367         }
4368
4369         if (addressbook_get_target_compose() == compose)
4370                 addressbook_set_target_compose(compose);
4371 }
4372
4373 static void compose_toggle_replyto_cb(gpointer data, guint action,
4374                                       GtkWidget *widget)
4375 {
4376         Compose *compose = (Compose *)data;
4377
4378         if (GTK_CHECK_MENU_ITEM(widget)->active) {
4379                 gtk_widget_show(compose->reply_hbox);
4380                 gtk_widget_show(compose->reply_entry);
4381                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 5, 4);
4382                 compose->use_replyto = TRUE;
4383         } else {
4384                 gtk_widget_hide(compose->reply_hbox);
4385                 gtk_widget_hide(compose->reply_entry);
4386                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 5, 0);
4387                 gtk_widget_queue_resize(compose->table_vbox);
4388                 compose->use_replyto = FALSE;
4389         }
4390 }
4391
4392 static void compose_toggle_followupto_cb(gpointer data, guint action,
4393                                          GtkWidget *widget)
4394 {
4395         Compose *compose = (Compose *)data;
4396
4397         if (GTK_CHECK_MENU_ITEM(widget)->active) {
4398                 gtk_widget_show(compose->followup_hbox);
4399                 gtk_widget_show(compose->followup_entry);
4400                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 6, 4);
4401                 compose->use_followupto = TRUE;
4402         } else {
4403                 gtk_widget_hide(compose->followup_hbox);
4404                 gtk_widget_hide(compose->followup_entry);
4405                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 6, 0);
4406                 gtk_widget_queue_resize(compose->table_vbox);
4407                 compose->use_followupto = FALSE;
4408         }
4409 }
4410
4411 static void compose_toggle_attach_cb(gpointer data, guint action,
4412                                      GtkWidget *widget)
4413 {
4414         Compose *compose = (Compose *)data;
4415
4416         if (GTK_CHECK_MENU_ITEM(widget)->active) {
4417                 gtk_widget_ref(compose->edit_vbox);
4418
4419                 gtk_container_remove(GTK_CONTAINER(compose->vbox2),
4420                                      compose->edit_vbox);
4421                 gtk_paned_add2(GTK_PANED(compose->paned), compose->edit_vbox);
4422                 gtk_box_pack_start(GTK_BOX(compose->vbox2), compose->paned,
4423                                    TRUE, TRUE, 0);
4424                 gtk_widget_show(compose->paned);
4425
4426                 gtk_widget_unref(compose->edit_vbox);
4427                 gtk_widget_unref(compose->paned);
4428
4429                 compose->use_attach = TRUE;
4430         } else {
4431                 gtk_widget_ref(compose->paned);
4432                 gtk_widget_ref(compose->edit_vbox);
4433
4434                 gtk_container_remove(GTK_CONTAINER(compose->vbox2),
4435                                      compose->paned);
4436                 gtk_container_remove(GTK_CONTAINER(compose->paned),
4437                                      compose->edit_vbox);
4438                 gtk_box_pack_start(GTK_BOX(compose->vbox2),
4439                                    compose->edit_vbox, TRUE, TRUE, 0);
4440
4441                 gtk_widget_unref(compose->edit_vbox);
4442
4443                 compose->use_attach = FALSE;
4444         }
4445 }
4446
4447 #if USE_GPGME
4448 static void compose_toggle_sign_cb(gpointer data, guint action,
4449                                    GtkWidget *widget)
4450 {
4451         Compose *compose = (Compose *)data;
4452
4453         if (GTK_CHECK_MENU_ITEM(widget)->active)
4454                 compose->use_signing = TRUE;
4455         else
4456                 compose->use_signing = FALSE;
4457 }
4458
4459 static void compose_toggle_encrypt_cb(gpointer data, guint action,
4460                                       GtkWidget *widget)
4461 {
4462         Compose *compose = (Compose *)data;
4463
4464         if (GTK_CHECK_MENU_ITEM(widget)->active)
4465                 compose->use_encryption = TRUE;
4466         else
4467                 compose->use_encryption = FALSE;
4468 }
4469 #endif /* USE_GPGME */
4470
4471 static void compose_toggle_ruler_cb(gpointer data, guint action,
4472                                     GtkWidget *widget)
4473 {
4474         Compose *compose = (Compose *)data;
4475
4476         if (GTK_CHECK_MENU_ITEM(widget)->active) {
4477                 gtk_widget_show(compose->ruler_hbox);
4478                 prefs_common.show_ruler = TRUE;
4479         } else {
4480                 gtk_widget_hide(compose->ruler_hbox);
4481                 gtk_widget_queue_resize(compose->edit_vbox);
4482                 prefs_common.show_ruler = FALSE;
4483         }
4484 }
4485
4486 static void compose_attach_drag_received_cb (GtkWidget          *widget,
4487                                              GdkDragContext     *drag_context,
4488                                              gint                x,
4489                                              gint                y,
4490                                              GtkSelectionData   *data,
4491                                              guint               info,
4492                                              guint               time,
4493                                              gpointer            user_data)
4494 {
4495         Compose *compose = (Compose *)user_data;
4496         GList *list, *tmp;
4497
4498         list = uri_list_extract_filenames((const gchar *)data->data);
4499         for (tmp = list; tmp != NULL; tmp = tmp->next)
4500                 compose_attach_append(compose, (const gchar *)tmp->data,
4501                                       MIME_UNKNOWN);
4502         list_free_strings(list);
4503         g_list_free(list);
4504 }
4505
4506 static void compose_insert_drag_received_cb (GtkWidget          *widget,
4507                                              GdkDragContext     *drag_context,
4508                                              gint                x,
4509                                              gint                y,
4510                                              GtkSelectionData   *data,
4511                                              guint               info,
4512                                              guint               time,
4513                                              gpointer            user_data)
4514 {
4515         Compose *compose = (Compose *)user_data;
4516         GList *list, *tmp;
4517
4518         list = uri_list_extract_filenames((const gchar *)data->data);
4519         for (tmp = list; tmp != NULL; tmp = tmp->next)
4520                 compose_insert_file(compose, (const gchar *)tmp->data);
4521         list_free_strings(list);
4522         g_list_free(list);
4523 }
4524
4525 static void to_activated(GtkWidget *widget, Compose *compose)
4526 {
4527         if (GTK_WIDGET_VISIBLE(compose->newsgroups_entry))
4528                 gtk_widget_grab_focus(compose->newsgroups_entry);
4529         else
4530                 gtk_widget_grab_focus(compose->subject_entry);
4531 }
4532
4533 static void newsgroups_activated(GtkWidget *widget, Compose *compose)
4534 {
4535         gtk_widget_grab_focus(compose->subject_entry);
4536 }
4537
4538 static void subject_activated(GtkWidget *widget, Compose *compose)
4539 {
4540         if (GTK_WIDGET_VISIBLE(compose->cc_entry))
4541                 gtk_widget_grab_focus(compose->cc_entry);
4542         else if (GTK_WIDGET_VISIBLE(compose->bcc_entry))
4543                 gtk_widget_grab_focus(compose->bcc_entry);
4544         else if (GTK_WIDGET_VISIBLE(compose->reply_entry))
4545                 gtk_widget_grab_focus(compose->reply_entry);
4546         else if (GTK_WIDGET_VISIBLE(compose->followup_entry))
4547                 gtk_widget_grab_focus(compose->followup_entry);
4548         else
4549                 gtk_widget_grab_focus(compose->text);
4550 }
4551
4552 static void cc_activated(GtkWidget *widget, Compose *compose)
4553 {
4554         if (GTK_WIDGET_VISIBLE(compose->bcc_entry))
4555                 gtk_widget_grab_focus(compose->bcc_entry);
4556         else if (GTK_WIDGET_VISIBLE(compose->reply_entry))
4557                 gtk_widget_grab_focus(compose->reply_entry);
4558         else if (GTK_WIDGET_VISIBLE(compose->followup_entry))
4559                 gtk_widget_grab_focus(compose->followup_entry);
4560         else
4561                 gtk_widget_grab_focus(compose->text);
4562 }
4563
4564 static void bcc_activated(GtkWidget *widget, Compose *compose)
4565 {
4566         if (GTK_WIDGET_VISIBLE(compose->reply_entry))
4567                 gtk_widget_grab_focus(compose->reply_entry);
4568         else if (GTK_WIDGET_VISIBLE(compose->followup_entry))
4569                 gtk_widget_grab_focus(compose->followup_entry);
4570         else
4571                 gtk_widget_grab_focus(compose->text);
4572 }
4573
4574 static void replyto_activated(GtkWidget *widget, Compose *compose)
4575 {
4576         if (GTK_WIDGET_VISIBLE(compose->followup_entry))
4577                 gtk_widget_grab_focus(compose->followup_entry);
4578         else
4579                 gtk_widget_grab_focus(compose->text);
4580 }
4581
4582 static void followupto_activated(GtkWidget *widget, Compose *compose)
4583 {
4584         gtk_widget_grab_focus(compose->text);
4585 }
4586
4587 static void compose_toggle_return_receipt_cb(gpointer data, guint action,
4588                                              GtkWidget *widget)
4589 {
4590         Compose *compose = (Compose *)data;
4591
4592         if (GTK_CHECK_MENU_ITEM(widget)->active)
4593                 compose->return_receipt = TRUE;
4594         else
4595                 compose->return_receipt = FALSE;
4596 }
4597
4598 static gchar *compose_quote_fmt         (Compose        *compose,
4599                                          MsgInfo        *msginfo,
4600                                          const gchar    *fmt,
4601                                          const gchar    *qmark)
4602 {
4603         gchar * quote_str = NULL;
4604
4605         if (qmark != NULL) {
4606                 gchar * p;
4607
4608                 quote_fmt_init(msginfo, NULL);
4609                 quote_fmt_scan_string(qmark);
4610                 quote_fmtparse();
4611
4612                 p = quote_fmt_get_buffer();
4613                 if (p == NULL) {
4614                         alertpanel_error
4615                                 (_("Quote mark format error."));
4616                 }
4617                 else {
4618                         quote_str = alloca(strlen(p) + 1);
4619                         strcpy(quote_str, p);
4620                 }
4621         }
4622
4623         quote_fmt_init(msginfo, quote_str);
4624         quote_fmt_scan_string(fmt);
4625         quote_fmtparse();
4626
4627         if (quote_fmt_get_buffer() == NULL)
4628                 alertpanel_error
4629                         (_("Message reply/forward format error."));
4630
4631         return quote_fmt_get_buffer();
4632 }