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