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