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