sync with sylpheed 0.7.0 release
[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 <sys/types.h>
57 #include <sys/stat.h>
58 #include <unistd.h>
59 #include <time.h>
60 /* #include <sys/utsname.h> */
61 #include <stdlib.h>
62 #include <sys/wait.h>
63 #include <signal.h>
64 #include <errno.h>
65
66 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
67 #  include <wchar.h>
68 #  include <wctype.h>
69 #endif
70
71 #include "intl.h"
72 #include "main.h"
73 #include "mainwindow.h"
74 #include "compose.h"
75 #include "gtkstext.h"
76 #include "addressbook.h"
77 #include "folderview.h"
78 #include "procmsg.h"
79 #include "menu.h"
80 #include "stock_pixmap.h"
81 #include "send.h"
82 #include "imap.h"
83 #include "news.h"
84 #include "customheader.h"
85 #include "prefs_common.h"
86 #include "prefs_account.h"
87 #include "account.h"
88 #include "filesel.h"
89 #include "procheader.h"
90 #include "procmime.h"
91 #include "statusbar.h"
92 #include "about.h"
93 #include "base64.h"
94 #include "codeconv.h"
95 #include "utils.h"
96 #include "gtkutils.h"
97 #include "socket.h"
98 #include "alertpanel.h"
99 #include "manage_window.h"
100 #include "gtkshruler.h"
101 #include "folder.h"
102 #include "addr_compl.h"
103 #include "quote_fmt.h"
104 #include "template.h"
105 #include "undo.h"
106 #include "foldersel.h"
107
108 #if USE_GPGME
109 #  include "rfc2015.h"
110 #endif
111
112 typedef enum
113 {
114         COL_MIMETYPE = 0,
115         COL_SIZE     = 1,
116         COL_NAME     = 2
117 } AttachColumnPos;
118
119 #define N_ATTACH_COLS           3
120
121 #define B64_LINE_SIZE           57
122 #define B64_BUFFSIZE            77
123
124 #define MAX_REFERENCES_LEN      999
125
126 static GdkColor quote_color = {0, 0, 0, 0xbfff};
127
128 static GList *compose_list = NULL;
129
130 Compose *compose_generic_new                    (PrefsAccount   *account,
131                                                  const gchar    *to,
132                                                  FolderItem     *item);
133
134 static Compose *compose_create                  (PrefsAccount   *account,
135                                                  ComposeMode     mode);
136 static void compose_toolbar_create              (Compose        *compose,
137                                                  GtkWidget      *container);
138 static GtkWidget *compose_account_option_menu_create
139                                                 (Compose        *compose);
140 static void compose_set_template_menu           (Compose        *compose);
141 static void compose_template_apply              (Compose        *compose,
142                                                  Template       *tmpl);
143 static void compose_destroy                     (Compose        *compose);
144
145 static void compose_entries_set                 (Compose        *compose,
146                                                  const gchar    *mailto);
147 static gint compose_parse_header                (Compose        *compose,
148                                                  MsgInfo        *msginfo);
149 static gchar *compose_parse_references          (const gchar    *ref,
150                                                  const gchar    *msgid);
151
152 static gchar *compose_quote_fmt                 (Compose        *compose,
153                                                  MsgInfo        *msginfo,
154                                                  const gchar    *fmt,
155                                                  const gchar    *qmark);
156
157 static void compose_reply_set_entry             (Compose        *compose,
158                                                  MsgInfo        *msginfo,
159                                                  gboolean        to_all,
160                                                  gboolean        to_sender,
161                                                  gboolean
162                                                  followup_and_reply_to);
163 static void compose_reedit_set_entry            (Compose        *compose,
164                                                  MsgInfo        *msginfo);
165 static void compose_insert_sig                  (Compose        *compose);
166 static void compose_insert_file                 (Compose        *compose,
167                                                  const gchar    *file);
168 static void compose_attach_append               (Compose        *compose,
169                                                  const gchar    *file,
170                                                  ContentType     cnttype);
171 static void compose_attach_append_with_type(Compose *compose,
172                                             const gchar *file,
173                                             const gchar *type,
174                                             ContentType cnttype);
175 static void compose_wrap_line                   (Compose        *compose);
176 static void compose_wrap_line_all               (Compose        *compose);
177 static void compose_set_title                   (Compose        *compose);
178
179 static PrefsAccount *compose_current_mail_account(void);
180 /* static gint compose_send                     (Compose        *compose); */
181 static gint compose_write_to_file               (Compose        *compose,
182                                                  const gchar    *file,
183                                                  gboolean        is_draft);
184 static gint compose_write_body_to_file          (Compose        *compose,
185                                                  const gchar    *file);
186 static gint compose_save_to_outbox              (Compose        *compose,
187                                                  const gchar    *file);
188 static gint compose_remove_reedit_target        (Compose        *compose);
189 static gint compose_queue                       (Compose        *compose,
190                                                  gint           *msgnum,
191                                                  FolderItem     **item);
192 static void compose_write_attach                (Compose        *compose,
193                                                  FILE           *fp);
194 static gint compose_write_headers               (Compose        *compose,
195                                                  FILE           *fp,
196                                                  const gchar    *charset,
197                                                  EncodingType    encoding,
198                                                  gboolean        is_draft);
199
200 static void compose_convert_header              (gchar          *dest,
201                                                  gint            len,
202                                                  gchar          *src,
203                                                  gint            header_len);
204 static void compose_generate_msgid              (Compose        *compose,
205                                                  gchar          *buf,
206                                                  gint            len);
207
208 static void compose_attach_info_free            (AttachInfo     *ainfo);
209 static void compose_attach_remove_selected      (Compose        *compose);
210
211 static void compose_attach_property             (Compose        *compose);
212 static void compose_attach_property_create      (gboolean       *cancelled);
213 static void attach_property_ok                  (GtkWidget      *widget,
214                                                  gboolean       *cancelled);
215 static void attach_property_cancel              (GtkWidget      *widget,
216                                                  gboolean       *cancelled);
217 static gint attach_property_delete_event        (GtkWidget      *widget,
218                                                  GdkEventAny    *event,
219                                                  gboolean       *cancelled);
220 static void attach_property_key_pressed         (GtkWidget      *widget,
221                                                  GdkEventKey    *event,
222                                                  gboolean       *cancelled);
223
224 static void compose_exec_ext_editor             (Compose           *compose);
225 static gint compose_exec_ext_editor_real        (const gchar       *file);
226 static gboolean compose_ext_editor_kill         (Compose           *compose);
227 static void compose_input_cb                    (gpointer           data,
228                                                  gint               source,
229                                                  GdkInputCondition  condition);
230 static void compose_set_ext_editor_sensitive    (Compose           *compose,
231                                                  gboolean           sensitive);
232
233 static void compose_undo_state_changed          (UndoMain       *undostruct,
234                                                  gint            undo_state,
235                                                  gint            redo_state,
236                                                  gpointer        data);
237
238 static gint calc_cursor_xpos    (GtkSText       *text,
239                                  gint            extra,
240                                  gint            char_width);
241
242 static void compose_create_header_entry (Compose *compose);
243 static void compose_add_header_entry    (Compose *compose, gchar *header, gchar *text);
244
245 /* callback functions */
246
247 static gboolean compose_edit_size_alloc (GtkEditable    *widget,
248                                          GtkAllocation  *allocation,
249                                          GtkSHRuler     *shruler);
250
251 static void toolbar_send_cb             (GtkWidget      *widget,
252                                          gpointer        data);
253 static void toolbar_send_later_cb       (GtkWidget      *widget,
254                                          gpointer        data);
255 static void toolbar_draft_cb            (GtkWidget      *widget,
256                                          gpointer        data);
257 static void toolbar_insert_cb           (GtkWidget      *widget,
258                                          gpointer        data);
259 static void toolbar_attach_cb           (GtkWidget      *widget,
260                                          gpointer        data);
261 static void toolbar_sig_cb              (GtkWidget      *widget,
262                                          gpointer        data);
263 static void toolbar_ext_editor_cb       (GtkWidget      *widget,
264                                          gpointer        data);
265 static void toolbar_linewrap_cb         (GtkWidget      *widget,
266                                          gpointer        data);
267 static void toolbar_address_cb          (GtkWidget      *widget,
268                                          gpointer        data);
269
270 static void select_account              (Compose        *compose,
271                                          PrefsAccount   *ac);
272
273 static void account_activated           (GtkMenuItem    *menuitem,
274                                          gpointer        data);
275
276 static void attach_selected             (GtkCList       *clist,
277                                          gint            row,
278                                          gint            column,
279                                          GdkEvent       *event,
280                                          gpointer        data);
281 static void attach_button_pressed       (GtkWidget      *widget,
282                                          GdkEventButton *event,
283                                          gpointer        data);
284 static void attach_key_pressed          (GtkWidget      *widget,
285                                          GdkEventKey    *event,
286                                          gpointer        data);
287
288 static void compose_send_cb             (gpointer        data,
289                                          guint           action,
290                                          GtkWidget      *widget);
291 static void compose_send_later_cb       (gpointer        data,
292                                          guint           action,
293                                          GtkWidget      *widget);
294
295 static void compose_draft_cb            (gpointer        data,
296                                          guint           action,
297                                          GtkWidget      *widget);
298
299 static void compose_attach_cb           (gpointer        data,
300                                          guint           action,
301                                          GtkWidget      *widget);
302 static void compose_insert_file_cb      (gpointer        data,
303                                          guint           action,
304                                          GtkWidget      *widget);
305
306 static void compose_close_cb            (gpointer        data,
307                                          guint           action,
308                                          GtkWidget      *widget);
309
310 static void compose_address_cb          (gpointer        data,
311                                          guint           action,
312                                          GtkWidget      *widget);
313 static void compose_template_activate_cb(GtkWidget      *widget,
314                                          gpointer        data);
315
316 static void compose_ext_editor_cb       (gpointer        data,
317                                          guint           action,
318                                          GtkWidget      *widget);
319
320 static gint compose_delete_cb           (GtkWidget      *widget,
321                                          GdkEventAny    *event,
322                                          gpointer        data);
323 static void compose_destroy_cb          (GtkWidget      *widget,
324                                          Compose        *compose);
325
326 static void compose_undo_cb             (Compose        *compose);
327 static void compose_redo_cb             (Compose        *compose);
328 static void compose_cut_cb              (Compose        *compose);
329 static void compose_copy_cb             (Compose        *compose);
330 static void compose_paste_cb            (Compose        *compose);
331 static void compose_allsel_cb           (Compose        *compose);
332
333 static void compose_grab_focus_cb       (GtkWidget      *widget,
334                                          Compose        *compose);
335
336 static void compose_changed_cb          (GtkEditable    *editable,
337                                          Compose        *compose);
338 static void compose_button_press_cb     (GtkWidget      *widget,
339                                          GdkEventButton *event,
340                                          Compose        *compose);
341 #if 0
342 static void compose_key_press_cb        (GtkWidget      *widget,
343                                          GdkEventKey    *event,
344                                          Compose        *compose);
345 #endif
346
347 #if 0
348 static void compose_toggle_to_cb        (gpointer        data,
349                                          guint           action,
350                                          GtkWidget      *widget);
351 static void compose_toggle_cc_cb        (gpointer        data,
352                                          guint           action,
353                                          GtkWidget      *widget);
354 static void compose_toggle_bcc_cb       (gpointer        data,
355                                          guint           action,
356                                          GtkWidget      *widget);
357 static void compose_toggle_replyto_cb   (gpointer        data,
358                                          guint           action,
359                                          GtkWidget      *widget);
360 static void compose_toggle_followupto_cb(gpointer        data,
361                                          guint           action,
362                                          GtkWidget      *widget);
363 static void compose_toggle_attach_cb    (gpointer        data,
364                                          guint           action,
365                                          GtkWidget      *widget);
366 #endif
367 static void compose_toggle_ruler_cb     (gpointer        data,
368                                          guint           action,
369                                          GtkWidget      *widget);
370 #if USE_GPGME
371 static void compose_toggle_sign_cb      (gpointer        data,
372                                          guint           action,
373                                          GtkWidget      *widget);
374 static void compose_toggle_encrypt_cb   (gpointer        data,
375                                          guint           action,
376                                          GtkWidget      *widget);
377 #endif
378 static void compose_toggle_return_receipt_cb(gpointer data, guint action,
379                                              GtkWidget *widget);
380
381 static void compose_attach_drag_received_cb (GtkWidget          *widget,
382                                              GdkDragContext     *drag_context,
383                                              gint                x,
384                                              gint                y,
385                                              GtkSelectionData   *data,
386                                              guint               info,
387                                              guint               time,
388                                              gpointer            user_data);
389 static void compose_insert_drag_received_cb (GtkWidget          *widget,
390                                              GdkDragContext     *drag_context,
391                                              gint                x,
392                                              gint                y,
393                                              GtkSelectionData   *data,
394                                              guint               info,
395                                              guint               time,
396                                              gpointer            user_data);
397
398 #if 0
399 static void to_activated                (GtkWidget      *widget,
400                                          Compose        *compose);
401 static void newsgroups_activated        (GtkWidget      *widget,
402                                          Compose        *compose);
403 static void subject_activated           (GtkWidget      *widget,
404                                          Compose        *compose);
405 static void cc_activated                (GtkWidget      *widget,
406                                          Compose        *compose);
407 static void bcc_activated               (GtkWidget      *widget,
408                                          Compose        *compose);
409 static void replyto_activated           (GtkWidget      *widget,
410                                          Compose        *compose);
411 static void followupto_activated        (GtkWidget      *widget,
412                                          Compose        *compose);
413 #endif
414
415 static void compose_attach_parts        (Compose        *compose,
416                                          MsgInfo        *msginfo);
417
418 static void compose_generic_reply(MsgInfo *msginfo, gboolean quote,
419                                   gboolean to_all,
420                                   gboolean ignore_replyto,
421                                   gboolean followup_and_reply_to);
422
423 void compose_headerentry_changed_cb        (GtkWidget          *entry,
424                                             ComposeHeaderEntry *headerentry);
425 void compose_headerentry_key_press_event_cb(GtkWidget          *entry,
426                                             GdkEventKey        *event,
427                                             ComposeHeaderEntry *headerentry);
428
429 static void compose_show_first_last_header (Compose *compose, gboolean show_first);
430
431 static void compose_ctl_enter_send_shortcut_cb(GtkWidget *w, Compose *compose);
432
433 static GtkItemFactoryEntry compose_popup_entries[] =
434 {
435         {N_("/_Add..."),        NULL, compose_attach_cb, 0, NULL},
436         {N_("/_Remove"),        NULL, compose_attach_remove_selected, 0, NULL},
437         {N_("/---"),            NULL, NULL, 0, "<Separator>"},
438         {N_("/_Property..."),   NULL, compose_attach_property, 0, NULL}
439 };
440
441 static GtkItemFactoryEntry compose_entries[] =
442 {
443         {N_("/_File"),                          NULL, NULL, 0, "<Branch>"},
444         {N_("/_File/_Attach file"),             "<control>M", compose_attach_cb,      0, NULL},
445         {N_("/_File/_Insert file"),             "<control>I", compose_insert_file_cb, 0, NULL},
446         {N_("/_File/Insert si_gnature"),        "<control>G", compose_insert_sig,     0, NULL},
447         {N_("/_File/---"),                      NULL, NULL, 0, "<Separator>"},
448         {N_("/_File/_Close"),                   "<alt>W", compose_close_cb, 0, NULL},
449
450         {N_("/_Edit"),                  NULL, NULL, 0, "<Branch>"},
451         {N_("/_Edit/_Undo"),            "<control>Z", compose_undo_cb, 0, NULL},
452         {N_("/_Edit/_Redo"),            "<control>Y", compose_redo_cb, 0, NULL},
453         {N_("/_Edit/---"),              NULL, NULL, 0, "<Separator>"},
454         {N_("/_Edit/Cu_t"),             "<control>X", compose_cut_cb,    0, NULL},
455         {N_("/_Edit/_Copy"),            "<control>C", compose_copy_cb,   0, NULL},
456         {N_("/_Edit/_Paste"),           "<control>V", compose_paste_cb,  0, NULL},
457         {N_("/_Edit/Select _all"),      "<control>A", compose_allsel_cb, 0, NULL},
458         {N_("/_Edit/---"),              NULL, NULL, 0, "<Separator>"},
459         {N_("/_Edit/_Wrap current paragraph"),
460                                         "<alt>L", compose_wrap_line, 0, NULL},
461         {N_("/_Edit/Wrap all long _lines"),
462                                         "<shift><alt>L", compose_wrap_line_all, 0, NULL},
463         {N_("/_Edit/Edit with e_xternal editor"),
464                                         "<alt>X", compose_ext_editor_cb, 0, NULL},
465 #if 0 /* NEW COMPOSE GUI */
466         {N_("/_View"),                  NULL, NULL, 0, "<Branch>"},
467         {N_("/_View/_To"),              NULL, compose_toggle_to_cb     , 0, "<ToggleItem>"},
468         {N_("/_View/_Cc"),              NULL, compose_toggle_cc_cb     , 0, "<ToggleItem>"},
469         {N_("/_View/_Bcc"),             NULL, compose_toggle_bcc_cb    , 0, "<ToggleItem>"},
470         {N_("/_View/_Reply to"),        NULL, compose_toggle_replyto_cb, 0, "<ToggleItem>"},
471         {N_("/_View/---"),              NULL, NULL, 0, "<Separator>"},
472         {N_("/_View/_Followup to"),     NULL, compose_toggle_followupto_cb, 0, "<ToggleItem>"},
473         {N_("/_View/---"),              NULL, NULL, 0, "<Separator>"},
474         {N_("/_View/R_uler"),           NULL, compose_toggle_ruler_cb, 0, "<ToggleItem>"},
475         {N_("/_View/---"),              NULL, NULL, 0, "<Separator>"},
476         {N_("/_View/_Attachment"),      NULL, compose_toggle_attach_cb, 0, "<ToggleItem>"},
477 #endif
478         {N_("/_Message"),               NULL, NULL, 0, "<Branch>"},
479         {N_("/_Message/_Send"),         "<control>Return",
480                                         compose_send_cb, 0, NULL},
481         {N_("/_Message/Send _later"),   "<shift><alt>S",
482                                         compose_send_later_cb,  0, NULL},
483         {N_("/_Message/Save to _draft folder"),
484                                         "<alt>D", compose_draft_cb, 0, NULL},
485         {N_("/_Message/Save and _keep editing"),
486                                         "<control>S", compose_draft_cb, 1, NULL},
487 #if 0 /* NEW COMPOSE GUI */
488         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
489         {N_("/_Message/_To"),           NULL, compose_toggle_to_cb     , 0, "<ToggleItem>"},
490         {N_("/_Message/_Cc"),           NULL, compose_toggle_cc_cb     , 0, "<ToggleItem>"},
491         {N_("/_Message/_Bcc"),          NULL, compose_toggle_bcc_cb    , 0, "<ToggleItem>"},
492         {N_("/_Message/_Reply to"),     NULL, compose_toggle_replyto_cb, 0, "<ToggleItem>"},
493         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
494         {N_("/_Message/_Followup to"),  NULL, compose_toggle_followupto_cb, 0, "<ToggleItem>"},
495         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
496         {N_("/_Message/_Attach"),       NULL, compose_toggle_attach_cb, 0, "<ToggleItem>"},
497 #endif
498 #if USE_GPGME
499         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
500         {N_("/_Message/Si_gn"),         NULL, compose_toggle_sign_cb   , 0, "<ToggleItem>"},
501         {N_("/_Message/_Encrypt"),      NULL, compose_toggle_encrypt_cb, 0, "<ToggleItem>"},
502 #endif /* USE_GPGME */
503         {N_("/_Message/---"),           NULL,           NULL,   0, "<Separator>"},
504         {N_("/_Message/_Request Return Receipt"),       NULL, compose_toggle_return_receipt_cb, 0, "<ToggleItem>"},
505         {N_("/_Tool"),                  NULL, NULL, 0, "<Branch>"},
506         {N_("/_Tool/Show _ruler"),      NULL, compose_toggle_ruler_cb, 0, "<ToggleItem>"},
507         {N_("/_Tool/_Address book"),    "<alt>A", compose_address_cb , 0, NULL},
508         {N_("/_Tool/_Template"),        NULL, NULL, 0, "<Branch>"},
509         {N_("/_Help"),                  NULL, NULL, 0, "<Branch>"},
510         {N_("/_Help/_About"),           NULL, about_show, 0, NULL}
511 };
512
513 static GtkTargetEntry compose_mime_types[] =
514 {
515         {"text/uri-list", 0, 0}
516 };
517
518 Compose *compose_new(PrefsAccount *account)
519 {
520         return compose_generic_new(account, NULL, NULL);
521 }
522
523 Compose *compose_bounce(PrefsAccount *account, MsgInfo *msginfo)
524 {
525         Compose *c;
526         gchar *filename;
527         GtkItemFactory *ifactory;
528         
529         c = compose_generic_new(account, NULL, NULL);
530
531         filename = procmsg_get_message_file(msginfo);
532         if (filename == NULL)
533                 return NULL;
534
535         c->bounce_filename = filename;
536
537         if (msginfo->subject)
538                 gtk_entry_set_text(GTK_ENTRY(c->subject_entry),
539                                    msginfo->subject);
540         gtk_editable_set_editable(GTK_EDITABLE(c->subject_entry), FALSE);
541
542         compose_quote_fmt(c, msginfo, "%M", NULL);
543         gtk_editable_set_editable(GTK_EDITABLE(c->text), FALSE);
544
545         ifactory = gtk_item_factory_from_widget(c->popupmenu);
546         menu_set_sensitive(ifactory, "/Add...", FALSE);
547         menu_set_sensitive(ifactory, "/Remove", FALSE);
548         menu_set_sensitive(ifactory, "/Property...", FALSE);
549
550         ifactory = gtk_item_factory_from_widget(c->menubar);
551         menu_set_sensitive(ifactory, "/File/Insert file", FALSE);
552         menu_set_sensitive(ifactory, "/File/Attach file", FALSE);
553         menu_set_sensitive(ifactory, "/File/Insert signature", FALSE);
554         menu_set_sensitive(ifactory, "/Edit/Paste", FALSE);
555         menu_set_sensitive(ifactory, "/Edit/Wrap current paragraph", FALSE);
556         menu_set_sensitive(ifactory, "/Edit/Wrap all long lines", FALSE);
557         menu_set_sensitive(ifactory, "/Edit/Edit with external editor", FALSE);
558         menu_set_sensitive(ifactory, "/Message/Attach", FALSE);
559 #if USE_GPGME
560         menu_set_sensitive(ifactory, "/Message/Sign", FALSE);
561         menu_set_sensitive(ifactory, "/Message/Encrypt", FALSE);
562 #endif
563         menu_set_sensitive(ifactory, "/Message/Request Return Receipt", FALSE);
564         menu_set_sensitive(ifactory, "/Tool/Template", FALSE);
565         
566         gtk_widget_set_sensitive(c->insert_btn, FALSE);
567         gtk_widget_set_sensitive(c->attach_btn, FALSE);
568         gtk_widget_set_sensitive(c->sig_btn, FALSE);
569         gtk_widget_set_sensitive(c->exteditor_btn, FALSE);
570         gtk_widget_set_sensitive(c->linewrap_btn, FALSE);
571
572         return c;
573 }
574
575 Compose *compose_new_with_recipient(PrefsAccount *account, const gchar *mailto)
576 {
577         return compose_generic_new(account, mailto, NULL);
578 }
579
580 Compose *compose_new_with_folderitem(PrefsAccount *account, FolderItem *item)
581 {
582         return compose_generic_new(account, NULL, item);
583 }
584
585 Compose *compose_generic_new(PrefsAccount *account, const gchar *mailto, FolderItem *item)
586 {
587         Compose *compose;
588
589         if (item && item->prefs && item->prefs->enable_default_account)
590                 account = account_find_from_id(item->prefs->default_account);
591
592         if (!account) account = cur_account;
593         g_return_val_if_fail(account != NULL, NULL);
594
595         compose = compose_create(account, COMPOSE_NEW);
596         compose->replyinfo = NULL;
597
598         if (prefs_common.auto_sig)
599                 compose_insert_sig(compose);
600         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
601         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
602
603         if (account->protocol != A_NNTP) {
604                 if (mailto) {
605                         compose_entries_set(compose, mailto);
606
607                 } else if(item && item->prefs->enable_default_to) {
608                         compose_entry_append(compose, item->prefs->default_to, COMPOSE_TO);
609                 }
610                 if (item && item->ret_rcpt) {
611                         GtkItemFactory *ifactory;
612                 
613                         ifactory = gtk_item_factory_from_widget(compose->menubar);
614                         menu_set_toggle(ifactory, "/Message/Request Return Receipt", TRUE);
615                 }
616         } else {
617                 if (mailto) {
618                         compose_entry_append(compose, mailto, COMPOSE_NEWSGROUPS);
619                 }
620         }
621         compose_show_first_last_header(compose, TRUE);
622
623         /* Set save folder */
624         if(item && item->prefs && item->prefs->save_copy_to_folder) {
625                 gchar *folderidentifier;
626
627                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), prefs_common.savemsg);
628                 folderidentifier = folder_item_get_identifier(item);
629                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
630                 g_free(folderidentifier);
631         }
632
633         gtk_widget_grab_focus(compose->header_last->entry);
634
635         if (prefs_common.auto_exteditor)
636                 compose_exec_ext_editor(compose);
637
638         return compose;
639 }
640
641 #define CHANGE_FLAGS(msginfo) \
642 { \
643 if (msginfo->folder->folder->change_flags != NULL) \
644 msginfo->folder->folder->change_flags(msginfo->folder->folder, \
645                                       msginfo->folder, \
646                                       msginfo); \
647 }
648
649 /*
650 Compose *compose_new_followup_and_replyto(PrefsAccount *account,
651                                            const gchar *followupto, gchar * to)
652 {
653         Compose *compose;
654
655         if (!account) account = cur_account;
656         g_return_val_if_fail(account != NULL, NULL);
657         g_return_val_if_fail(account->protocol != A_NNTP, NULL);
658
659         compose = compose_create(account, COMPOSE_NEW);
660
661         if (prefs_common.auto_sig)
662                 compose_insert_sig(compose);
663         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
664         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
665
666         compose_entry_append(compose, to, COMPOSE_TO);
667         compose_entry_append(compose, followupto, COMPOSE_NEWSGROUPS);
668         gtk_widget_grab_focus(compose->subject_entry);
669
670         return compose;
671 }
672 */
673
674 void compose_reply(MsgInfo *msginfo, gboolean quote, gboolean to_all,
675                    gboolean ignore_replyto)
676 {
677         compose_generic_reply(msginfo, quote, to_all, ignore_replyto, FALSE);
678 }
679
680 void compose_followup_and_reply_to(MsgInfo *msginfo, gboolean quote,
681                                    gboolean to_all,
682                                    gboolean ignore_replyto)
683 {
684         compose_generic_reply(msginfo, quote, to_all, ignore_replyto, TRUE);
685 }
686
687 static void compose_generic_reply(MsgInfo *msginfo, gboolean quote,
688                                   gboolean to_all,
689                                   gboolean ignore_replyto,
690                                   gboolean followup_and_reply_to)
691 {
692         Compose *compose;
693         PrefsAccount *account;
694         PrefsAccount *reply_account;
695         GtkSText *text;
696
697         g_return_if_fail(msginfo != NULL);
698         g_return_if_fail(msginfo->folder != NULL);
699
700         account = NULL;
701         /* select the account set in folderitem's property (if enabled) */
702         if (msginfo->folder->prefs && msginfo->folder->prefs->enable_default_account)
703                 account = account_find_from_id(msginfo->folder->prefs->default_account);
704         
705         /* select the account for the whole folder (IMAP / NNTP) */
706         if (!account)
707                 /* FIXME: this is not right, because folder may be nested. we should
708                  * ascend the tree until we find a parent with proper account 
709                  * information */
710                 account = msginfo->folder->folder->account;
711
712         /* select account by to: and cc: header if enabled */
713         if (prefs_common.reply_account_autosel) {
714                 if (!account && msginfo->to) {
715                         gchar *to;
716                         Xstrdup_a(to, msginfo->to, return);
717                         extract_address(to);
718                         account = account_find_from_address(to);
719                 }
720                 if (!account) {
721                         gchar cc[BUFFSIZE];
722                         if(!get_header_from_msginfo(msginfo, cc, sizeof(cc), "CC:")) { /* Found a CC header */
723                                 extract_address(cc);
724                                 account = account_find_from_address(cc);
725                         }        
726                 }
727         }
728
729         /* select current account */
730         if (!account) account = cur_account;
731         g_return_if_fail(account != NULL);
732
733         if (ignore_replyto && account->protocol == A_NNTP &&
734             !followup_and_reply_to) {
735                 reply_account =
736                         account_find_from_address(account->address);
737                 if (!reply_account)
738                         reply_account = compose_current_mail_account();
739                 if (!reply_account)
740                         return;
741         } else
742                 reply_account = account;
743
744         MSG_UNSET_PERM_FLAGS(msginfo->flags, MSG_FORWARDED);
745         MSG_SET_PERM_FLAGS(msginfo->flags, MSG_REPLIED);
746         if (MSG_IS_IMAP(msginfo->flags))
747                 imap_msg_set_perm_flags(msginfo, MSG_REPLIED);
748         CHANGE_FLAGS(msginfo);
749
750         compose = compose_create(account, COMPOSE_REPLY);
751         compose->replyinfo = procmsg_msginfo_copy(msginfo);
752
753 #if 0 /* NEW COMPOSE GUI */
754         if (followup_and_reply_to) {
755                 gtk_widget_show(compose->to_hbox);
756                 gtk_widget_show(compose->to_entry);
757                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 1, 4);
758                 compose->use_to = TRUE;
759         }
760 #endif
761         if (msginfo->folder && msginfo->folder->ret_rcpt) {
762                 GtkItemFactory *ifactory;
763         
764                 ifactory = gtk_item_factory_from_widget(compose->menubar);
765                 menu_set_toggle(ifactory, "/Message/Request Return Receipt", TRUE);
766         }
767
768         /* Set save folder */
769         if(msginfo->folder && msginfo->folder->prefs && msginfo->folder->prefs->save_copy_to_folder) {
770                 gchar *folderidentifier;
771
772                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), TRUE);
773                 folderidentifier = folder_item_get_identifier(msginfo->folder);
774                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
775                 g_free(folderidentifier);
776         }
777
778         if (compose_parse_header(compose, msginfo) < 0) return;
779         compose_reply_set_entry(compose, msginfo, to_all, ignore_replyto,
780                                 followup_and_reply_to);
781         compose_show_first_last_header(compose, TRUE);
782
783         text = GTK_STEXT(compose->text);
784         gtk_stext_freeze(text);
785
786         if (quote) {
787                 gchar *qmark;
788                 gchar *quote_str;
789
790                 if (prefs_common.quotemark && *prefs_common.quotemark)
791                         qmark = prefs_common.quotemark;
792                 else
793                         qmark = "> ";
794
795                 quote_str = compose_quote_fmt(compose, msginfo,
796                                               prefs_common.quotefmt,
797                                               qmark);
798         }
799
800         if (prefs_common.auto_sig)
801                 compose_insert_sig(compose);
802
803         if (quote && prefs_common.linewrap_quote)
804                 compose_wrap_line_all(compose);
805
806         gtk_editable_set_position(GTK_EDITABLE(text), 0);
807         gtk_stext_set_point(text, 0);
808
809         gtk_stext_thaw(text);
810         gtk_widget_grab_focus(compose->text);
811
812         if (prefs_common.auto_exteditor)
813                 compose_exec_ext_editor(compose);
814 }
815
816
817 static gchar *procmime_get_file_name(MimeInfo *mimeinfo)
818 {
819         gchar *base;
820         gchar *filename;
821
822         g_return_val_if_fail(mimeinfo != NULL, NULL);
823
824         base = mimeinfo->filename ? mimeinfo->filename
825                 : mimeinfo->name ? mimeinfo->name : NULL;
826
827         if (MIME_TEXT_HTML == mimeinfo->mime_type && base == NULL){
828                 filename = g_strdup_printf("%s%smimetmp.%08x.html",
829                                            get_mime_tmp_dir(),
830                                            G_DIR_SEPARATOR_S,
831                                            (gint)mimeinfo);
832                 return filename;
833         }
834         else {
835                 base = base ? base : "";
836                 base = g_basename(base);
837                 if (*base == '\0') {
838                         filename = g_strdup_printf("%s%smimetmp.%08x",
839                                                    get_mime_tmp_dir(),
840                                                    G_DIR_SEPARATOR_S,
841                                                    (gint)mimeinfo);
842                         return filename;
843                 }
844         }
845
846         filename = g_strconcat(get_mime_tmp_dir(), G_DIR_SEPARATOR_S,
847                                base, NULL);
848
849         return filename;
850 }
851
852 static gchar *mime_extract_file(gchar *source, MimeInfo *partinfo)
853 {
854         gchar *filename;
855
856         if (!partinfo) return NULL;
857
858         filename = procmime_get_file_name(partinfo);
859
860         if (procmime_get_part(filename, source, partinfo) < 0)
861                 alertpanel_error
862                         (_("Can't get the part of multipart message."));
863
864         return filename;
865 }
866
867 static void compose_attach_parts(Compose *compose, MsgInfo *msginfo)
868 {
869         FILE *fp;
870         gchar *file;
871         MimeInfo *mimeinfo;
872         MsgInfo *tmpmsginfo;
873         gchar *p;
874         gchar *boundary;
875         gint boundary_len = 0;
876         gchar buf[BUFFSIZE];
877         glong fpos, prev_fpos;
878         gint npart;
879         gchar *source;
880         gchar *filename;
881
882         g_return_if_fail(msginfo != NULL);
883         
884 #if USE_GPGME
885         for (;;) {
886                 if ((fp = procmsg_open_message(msginfo)) == NULL) return;
887                 mimeinfo = procmime_scan_mime_header(fp, MIME_TEXT);
888                 if (!mimeinfo) break;
889
890                 if (!MSG_IS_ENCRYPTED(msginfo->flags) &&
891                     rfc2015_is_encrypted(mimeinfo)) {
892                         MSG_SET_TMP_FLAGS(msginfo->flags, MSG_ENCRYPTED);
893                 }
894                 if (MSG_IS_ENCRYPTED(msginfo->flags) &&
895                     !msginfo->plaintext_file  &&
896                     !msginfo->decryption_failed) {
897                         rfc2015_decrypt_message(msginfo, mimeinfo, fp);
898                         if (msginfo->plaintext_file &&
899                             !msginfo->decryption_failed) {
900                                 fclose(fp);
901                                 continue;
902                         }
903                 }
904                 
905                 break;
906         }
907 #else /* !USE_GPGME */
908         if ((fp = procmsg_open_message(msginfo)) == NULL) return;
909         mimeinfo = procmime_scan_mime_header(fp, MIME_TEXT);
910 #endif /* USE_GPGME */
911
912         fclose(fp);
913         if (!mimeinfo) return;
914         if (mimeinfo->mime_type == MIME_TEXT)
915                 return;
916
917         if ((fp = procmsg_open_message(msginfo)) == NULL) return;
918
919         g_return_if_fail(mimeinfo != NULL);
920         g_return_if_fail(mimeinfo->mime_type != MIME_TEXT);
921
922         if (mimeinfo->mime_type == MIME_MULTIPART) {
923                 g_return_if_fail(mimeinfo->boundary != NULL);
924                 g_return_if_fail(mimeinfo->sub == NULL);
925         }
926         g_return_if_fail(fp != NULL);
927
928         boundary = mimeinfo->boundary;
929
930         if (boundary) {
931                 boundary_len = strlen(boundary);
932
933                 /* look for first boundary */
934                 while ((p = fgets(buf, sizeof(buf), fp)) != NULL)
935                         if (IS_BOUNDARY(buf, boundary, boundary_len)) break;
936                 if (!p) {
937                         fclose(fp);
938                         return;
939                 }
940         }
941
942         if ((fpos = ftell(fp)) < 0) {
943                 perror("ftell");
944                 fclose(fp);
945                 return;
946         }
947
948         for (npart = 0;; npart++) {
949                 MimeInfo *partinfo;
950                 gboolean eom = FALSE;
951
952                 prev_fpos = fpos;
953
954                 partinfo = procmime_scan_mime_header(fp, MIME_TEXT);
955                 if (!partinfo) break;
956
957                 if (npart != 0)
958                         procmime_mimeinfo_insert(mimeinfo, partinfo);
959                 else
960                         procmime_mimeinfo_free(partinfo);
961
962                 /* look for next boundary */
963                 buf[0] = '\0';
964                 while ((p = fgets(buf, sizeof(buf), fp)) != NULL) {
965                         if (IS_BOUNDARY(buf, boundary, boundary_len)) {
966                                 if (buf[2 + boundary_len]     == '-' &&
967                                     buf[2 + boundary_len + 1] == '-')
968                                         eom = TRUE;
969                                 break;
970                         }
971                 }
972                 if (p == NULL)
973                         eom = TRUE;     /* broken MIME message */
974                 fpos = ftell(fp);
975
976                 partinfo->size = fpos - prev_fpos - strlen(buf);
977
978                 if (eom) break;
979         }
980
981         source = procmsg_get_message_file_path(msginfo);
982
983         g_return_if_fail(mimeinfo != NULL);
984
985         if (!mimeinfo->main && mimeinfo->parent)
986                 {
987                         filename = mime_extract_file(source, mimeinfo);
988
989                         compose_attach_append_with_type(compose, filename,
990                                                         mimeinfo->content_type,
991                                                         mimeinfo->mime_type);
992
993                         g_free(filename);
994                 }
995
996         if (mimeinfo->sub && mimeinfo->sub->children)
997                 {
998                         filename = mime_extract_file(source, mimeinfo->sub);
999
1000                         compose_attach_append_with_type(compose, filename,
1001                                                         mimeinfo->content_type,
1002                                                         mimeinfo->sub->mime_type);
1003
1004                         g_free(filename);
1005                 }
1006
1007         if (mimeinfo->children) {
1008                 MimeInfo *child;
1009
1010                 child = mimeinfo->children;
1011                 while (child) {
1012                         filename = mime_extract_file(source, child);
1013
1014                         compose_attach_append_with_type(compose, filename,
1015                                                         child->content_type,
1016                                                         child->mime_type);
1017
1018                         g_free(filename);
1019
1020                         child = child->next;
1021                 }
1022         }
1023
1024         fclose(fp);
1025
1026         procmime_mimeinfo_free_all(mimeinfo);
1027 }
1028
1029
1030 #define INSERT_FW_HEADER(var, hdr) \
1031 if (msginfo->var && *msginfo->var) { \
1032         gtk_stext_insert(text, NULL, NULL, NULL, hdr, -1); \
1033         gtk_stext_insert(text, NULL, NULL, NULL, msginfo->var, -1); \
1034         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1); \
1035 }
1036
1037 Compose *compose_forward(PrefsAccount *account, MsgInfo *msginfo,
1038                          gboolean as_attach)
1039 {
1040         Compose *compose;
1041         /*      PrefsAccount *account; */
1042         GtkSText *text;
1043
1044         g_return_val_if_fail(msginfo != NULL, NULL);
1045         g_return_val_if_fail(msginfo->folder != NULL, NULL);
1046
1047         account = msginfo->folder->folder->account;
1048         if (!account && msginfo->to && prefs_common.forward_account_autosel) {
1049                 gchar *to;
1050                 Xstrdup_a(to, msginfo->to, return NULL);
1051                 extract_address(to);
1052                 account = account_find_from_address(to);
1053         }
1054
1055         if(!account && prefs_common.forward_account_autosel) {
1056                 gchar cc[BUFFSIZE];
1057                 if(!get_header_from_msginfo(msginfo,cc,sizeof(cc),"CC:")){ /* Found a CC header */
1058                         extract_address(cc);
1059                         account = account_find_from_address(cc);
1060                 }
1061         }
1062
1063         if (account == NULL) {
1064                 account = cur_account;
1065                 /*
1066                 account = msginfo->folder->folder->account;
1067                 if (!account) account = cur_account;
1068                 */
1069         }
1070         g_return_val_if_fail(account != NULL, NULL);
1071
1072         MSG_UNSET_PERM_FLAGS(msginfo->flags, MSG_REPLIED);
1073         MSG_SET_PERM_FLAGS(msginfo->flags, MSG_FORWARDED);
1074         if (MSG_IS_IMAP(msginfo->flags))
1075                 imap_msg_unset_perm_flags(msginfo, MSG_REPLIED);
1076         CHANGE_FLAGS(msginfo);
1077
1078         compose = compose_create(account, COMPOSE_FORWARD);
1079
1080         if (msginfo->subject && *msginfo->subject) {
1081                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), "Fw: ");
1082                 gtk_entry_append_text(GTK_ENTRY(compose->subject_entry),
1083                                       msginfo->subject);
1084         }
1085
1086         text = GTK_STEXT(compose->text);
1087         gtk_stext_freeze(text);
1088
1089         if (as_attach) {
1090                 gchar *msgfile;
1091
1092                 msgfile = procmsg_get_message_file_path(msginfo);
1093                 if (!is_file_exist(msgfile))
1094                         g_warning(_("%s: file not exist\n"), msgfile);
1095                 else
1096                         compose_attach_append(compose, msgfile,
1097                                               MIME_MESSAGE_RFC822);
1098
1099                 g_free(msgfile);
1100         } else {
1101                 gchar *qmark;
1102                 gchar *quote_str;
1103
1104                 if (prefs_common.fw_quotemark && *prefs_common.fw_quotemark)
1105                         qmark = prefs_common.fw_quotemark;
1106                 else
1107                         qmark = "> ";
1108
1109                 quote_str = compose_quote_fmt(compose, msginfo,
1110                                               prefs_common.fw_quotefmt, qmark);
1111                 compose_attach_parts(compose, msginfo);
1112         }
1113
1114         if (prefs_common.auto_sig)
1115                 compose_insert_sig(compose);
1116
1117         if (prefs_common.linewrap_quote)
1118                 compose_wrap_line_all(compose);
1119
1120         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
1121         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
1122
1123         gtk_stext_thaw(text);
1124 #if 0 /* NEW COMPOSE GUI */
1125         if (account->protocol != A_NNTP)
1126                 gtk_widget_grab_focus(compose->to_entry);
1127         else
1128                 gtk_widget_grab_focus(compose->newsgroups_entry);
1129 #endif
1130         gtk_widget_grab_focus(compose->header_last->entry);
1131
1132         if (prefs_common.auto_exteditor)
1133                 compose_exec_ext_editor(compose);
1134
1135         return compose;
1136 }
1137
1138 #undef INSERT_FW_HEADER
1139
1140 Compose *compose_forward_multiple(PrefsAccount *account, GSList *msginfo_list)
1141 {
1142         Compose *compose;
1143         GtkSText *text;
1144         GSList *msginfo;
1145         gchar *msgfile;
1146
1147         g_return_val_if_fail(msginfo_list != NULL, NULL);
1148         
1149         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1150                 if ( ((MsgInfo *)msginfo->data)->folder == NULL )
1151                         return NULL;
1152         }
1153
1154         if (account == NULL) {
1155                 account = cur_account;
1156                 /*
1157                 account = msginfo->folder->folder->account;
1158                 if (!account) account = cur_account;
1159                 */
1160         }
1161         g_return_val_if_fail(account != NULL, NULL);
1162
1163         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1164                 MSG_UNSET_PERM_FLAGS(((MsgInfo *)msginfo->data)->flags, MSG_REPLIED);
1165                 MSG_SET_PERM_FLAGS(((MsgInfo *)msginfo->data)->flags, MSG_FORWARDED);
1166                 CHANGE_FLAGS(((MsgInfo *)msginfo->data));
1167         }
1168
1169         compose = compose_create(account, COMPOSE_FORWARD);
1170
1171         text = GTK_STEXT(compose->text);
1172         gtk_stext_freeze(text);
1173
1174         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1175                 msgfile = procmsg_get_message_file_path((MsgInfo *)msginfo->data);
1176                 if (!is_file_exist(msgfile))
1177                         g_warning(_("%s: file not exist\n"), msgfile);
1178                 else
1179                         compose_attach_append(compose, msgfile,
1180                                 MIME_MESSAGE_RFC822);
1181                 g_free(msgfile);
1182         }
1183
1184         if (prefs_common.auto_sig)
1185                 compose_insert_sig(compose);
1186
1187         if (prefs_common.linewrap_quote)
1188                 compose_wrap_line_all(compose);
1189
1190         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
1191         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
1192
1193         gtk_stext_thaw(text);
1194 #if 0 /* NEW COMPOSE GUI */
1195         if (account->protocol != A_NNTP)
1196                 gtk_widget_grab_focus(compose->to_entry);
1197         else
1198                 gtk_widget_grab_focus(compose->newsgroups_entry);
1199 #endif
1200
1201         return compose;
1202 }
1203
1204 void compose_reedit(MsgInfo *msginfo)
1205 {
1206         Compose *compose;
1207         PrefsAccount *account;
1208         GtkSText *text;
1209         FILE *fp;
1210         gchar buf[BUFFSIZE];
1211
1212         g_return_if_fail(msginfo != NULL);
1213         g_return_if_fail(msginfo->folder != NULL);
1214
1215         if (msginfo->folder->stype == F_QUEUE) {
1216                 gchar account_address[BUFFSIZE];
1217                 if (!get_header_from_msginfo(msginfo, account_address, sizeof(account_address), "S:")) {
1218                         account = account_find_from_address(account_address);
1219                 }
1220         } else 
1221                 account = msginfo->folder->folder->account;
1222
1223         if (!account && prefs_common.reedit_account_autosel) {
1224                 gchar from[BUFFSIZE];
1225                 if (!get_header_from_msginfo(msginfo, from, sizeof(from), "FROM:")){
1226                         extract_address(from);
1227                         account = account_find_from_address(from);
1228                 }
1229         }
1230         if (!account) account = cur_account;
1231         g_return_if_fail(account != NULL);
1232
1233         compose = compose_create(account, COMPOSE_REEDIT);
1234         compose->targetinfo = procmsg_msginfo_copy(msginfo);
1235
1236         if (compose_parse_header(compose, msginfo) < 0) return;
1237         compose_reedit_set_entry(compose, msginfo);
1238
1239         text = GTK_STEXT(compose->text);
1240         gtk_stext_freeze(text);
1241
1242         if ((fp = procmime_get_first_text_content(msginfo)) == NULL)
1243                 g_warning(_("Can't get text part\n"));
1244         else {
1245                 while (fgets(buf, sizeof(buf), fp) != NULL)
1246                         gtk_stext_insert(text, NULL, NULL, NULL, buf, -1);
1247                 fclose(fp);
1248         }
1249         compose_attach_parts(compose, msginfo);
1250
1251         gtk_stext_thaw(text);
1252         gtk_widget_grab_focus(compose->text);
1253
1254         if (prefs_common.auto_exteditor)
1255                 compose_exec_ext_editor(compose);
1256 }
1257
1258 GList *compose_get_compose_list(void)
1259 {
1260         return compose_list;
1261 }
1262
1263 void compose_entry_append(Compose *compose, const gchar *address,
1264                           ComposeEntryType type)
1265 {
1266         GtkEntry *entry;
1267         const gchar *text;
1268         gchar *header;
1269
1270         if (!address || *address == '\0') return;
1271
1272 #if 0 /* NEW COMPOSE GUI */
1273         switch (type) {
1274         case COMPOSE_CC:
1275                 entry = GTK_ENTRY(compose->cc_entry);
1276                 break;
1277         case COMPOSE_BCC:
1278                 entry = GTK_ENTRY(compose->bcc_entry);
1279                 break;
1280         case COMPOSE_NEWSGROUPS:
1281                 entry = GTK_ENTRY(compose->newsgroups_entry);
1282                 break;
1283         case COMPOSE_TO:
1284         default:
1285                 entry = GTK_ENTRY(compose->to_entry);
1286                 break;
1287         }
1288
1289         text = gtk_entry_get_text(entry);
1290         if (*text != '\0')
1291                 gtk_entry_append_text(entry, ", ");
1292         gtk_entry_append_text(entry, address);
1293 #endif
1294
1295         switch (type) {
1296         case COMPOSE_CC:
1297                 header = N_("Cc:");
1298                 break;
1299         case COMPOSE_BCC:
1300                 header = N_("Bcc:");
1301                 break;
1302         case COMPOSE_REPLYTO:
1303                 header = N_("Reply-To:");
1304                 break;
1305         case COMPOSE_NEWSGROUPS:
1306                 header = N_("Newsgroups:");
1307                 break;
1308         case COMPOSE_FOLLOWUPTO:
1309                 header = N_( "Followup-To:");
1310                 break;
1311         case COMPOSE_TO:
1312         default:
1313                 header = N_("To:");
1314                 break;
1315         }
1316         header = prefs_common.trans_hdr ? gettext(header) : header;
1317
1318         compose_add_header_entry(compose, header, (gchar *)address);
1319 }
1320
1321 static void compose_entries_set(Compose *compose, const gchar *mailto)
1322 {
1323         gchar *subject = NULL;
1324         gchar *to = NULL;
1325         gchar *cc = NULL;
1326         gchar *bcc = NULL;
1327         gchar *body = NULL;
1328         gchar *p;
1329         gchar *tmp_mailto;
1330
1331         Xstrdup_a(tmp_mailto, mailto, return);
1332
1333         to = tmp_mailto;
1334
1335         p = strchr(tmp_mailto, '?');
1336         if (p) {
1337                 *p = '\0';
1338                 p++;
1339         }
1340
1341         while (p) {
1342                 gchar *field, *value;
1343
1344                 field = p;
1345
1346                 p = strchr(p, '=');
1347                 if (!p) break;
1348                 *p = '\0';
1349                 p++;
1350
1351                 value = p;
1352
1353                 p = strchr(p, '&');
1354                 if (p) {
1355                         *p = '\0';
1356                         p++;
1357                 }
1358
1359                 if (*value == '\0') continue;
1360
1361                 if (!g_strcasecmp(field, "subject")) {
1362                         Xalloca(subject, strlen(value) + 1, return);
1363                         decode_uri(subject, value);
1364                 } else if (!g_strcasecmp(field, "cc")) {
1365                         cc = value;
1366                 } else if (!g_strcasecmp(field, "bcc")) {
1367                         bcc = value;
1368                 } else if (!g_strcasecmp(field, "body")) {
1369                         Xalloca(body, strlen(value) + 1, return);
1370                         decode_uri(body, value);
1371                 }
1372         }
1373
1374         if (to)
1375                 compose_entry_append(compose, to, COMPOSE_TO);
1376         if (subject)
1377                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), subject);
1378         if (cc)
1379                 compose_entry_append(compose, cc, COMPOSE_CC);
1380         if (bcc)
1381                 compose_entry_append(compose, bcc, COMPOSE_BCC);
1382         if (body) {
1383                 gtk_stext_insert(GTK_STEXT(compose->text),
1384                                 NULL, NULL, NULL, body, -1);
1385                 gtk_stext_insert(GTK_STEXT(compose->text),
1386                                 NULL, NULL, NULL, "\n", 1);
1387         }
1388 }
1389
1390 static gint compose_parse_header(Compose *compose, MsgInfo *msginfo)
1391 {
1392         static HeaderEntry hentry[] = {{"Reply-To:",       NULL, TRUE},
1393                                        {"Cc:",             NULL, FALSE},
1394                                        {"References:",     NULL, FALSE},
1395                                        {"Bcc:",            NULL, FALSE},
1396                                        {"Newsgroups:",     NULL, FALSE},
1397                                        {"Followup-To:",    NULL, FALSE},
1398                                        {"X-Mailing-List:", NULL, FALSE},
1399                                        {"X-BeenThere:",    NULL, FALSE},
1400                                        {NULL,              NULL, FALSE}};
1401
1402         enum
1403         {
1404                 H_REPLY_TO       = 0,
1405                 H_CC             = 1,
1406                 H_REFERENCES     = 2,
1407                 H_BCC            = 3,
1408                 H_NEWSGROUPS     = 4,
1409                 H_FOLLOWUP_TO    = 5,
1410                 H_X_MAILING_LIST = 6,
1411                 H_X_BEENTHERE    = 7
1412         };
1413
1414         FILE *fp;
1415
1416         g_return_val_if_fail(msginfo != NULL, -1);
1417
1418         if ((fp = procmsg_open_message(msginfo)) == NULL) return -1;
1419         procheader_get_header_fields(fp, hentry);
1420         fclose(fp);
1421
1422         if (hentry[H_REPLY_TO].body != NULL) {
1423                 conv_unmime_header_overwrite(hentry[H_REPLY_TO].body);
1424                 compose->replyto = hentry[H_REPLY_TO].body;
1425                 hentry[H_REPLY_TO].body = NULL;
1426         }
1427         if (hentry[H_CC].body != NULL) {
1428                 conv_unmime_header_overwrite(hentry[H_CC].body);
1429                 compose->cc = hentry[H_CC].body;
1430                 hentry[H_CC].body = NULL;
1431         }
1432         if (hentry[H_X_MAILING_LIST].body != NULL) {
1433                 /* this is good enough to parse debian-devel */
1434                 gchar *buf = g_malloc(strlen(hentry[H_X_MAILING_LIST].body) + 1);
1435                 g_return_val_if_fail(buf != NULL, -1 );
1436                 if (1 == sscanf(hentry[H_X_MAILING_LIST].body, "<%[^>]>", buf))
1437                         compose->mailinglist = g_strdup(buf);
1438                 g_free(buf);
1439                 g_free(hentry[H_X_MAILING_LIST].body);
1440                 hentry[H_X_MAILING_LIST].body = NULL ;
1441         }
1442         if (hentry[H_X_BEENTHERE].body != NULL) {
1443                 /* this is good enough to parse the sylpheed-claws lists */
1444                 gchar *buf = g_malloc(strlen(hentry[H_X_BEENTHERE].body) + 1);
1445                 g_return_val_if_fail(buf != NULL, -1 );
1446                 if (1 == sscanf(hentry[H_X_BEENTHERE].body, "%[^>]", buf))
1447                         compose->mailinglist = g_strdup(buf);
1448                 g_free(buf);
1449                 g_free(hentry[H_X_BEENTHERE].body);
1450                 hentry[H_X_BEENTHERE].body = NULL ;
1451         }
1452         if (hentry[H_REFERENCES].body != NULL) {
1453                 if (compose->mode == COMPOSE_REEDIT)
1454                         compose->references = hentry[H_REFERENCES].body;
1455                 else {
1456                         compose->references = compose_parse_references
1457                                 (hentry[H_REFERENCES].body, msginfo->msgid);
1458                         g_free(hentry[H_REFERENCES].body);
1459                 }
1460                 hentry[H_REFERENCES].body = NULL;
1461         }
1462         if (hentry[H_BCC].body != NULL) {
1463                 if (compose->mode == COMPOSE_REEDIT) {
1464                         conv_unmime_header_overwrite(hentry[H_BCC].body);
1465                         compose->bcc = hentry[H_BCC].body;
1466                 } else
1467                         g_free(hentry[H_BCC].body);
1468                 hentry[H_BCC].body = NULL;
1469         }
1470         if (hentry[H_NEWSGROUPS].body != NULL) {
1471                 compose->newsgroups = hentry[H_NEWSGROUPS].body;
1472                 hentry[H_NEWSGROUPS].body = NULL;
1473         }
1474         if (hentry[H_FOLLOWUP_TO].body != NULL) {
1475                 conv_unmime_header_overwrite(hentry[H_FOLLOWUP_TO].body);
1476                 compose->followup_to = hentry[H_FOLLOWUP_TO].body;
1477                 hentry[H_FOLLOWUP_TO].body = NULL;
1478         }
1479
1480         if (compose->mode == COMPOSE_REEDIT && msginfo->inreplyto)
1481                 compose->inreplyto = g_strdup(msginfo->inreplyto);
1482         else if (compose->mode != COMPOSE_REEDIT &&
1483                  msginfo->msgid && *msginfo->msgid) {
1484                 compose->inreplyto = g_strdup(msginfo->msgid);
1485
1486                 if (!compose->references) {
1487                         if (msginfo->inreplyto && *msginfo->inreplyto)
1488                                 compose->references =
1489                                         g_strdup_printf("<%s>\n\t<%s>",
1490                                                         msginfo->inreplyto,
1491                                                         msginfo->msgid);
1492                         else
1493                                 compose->references =
1494                                         g_strconcat("<", msginfo->msgid, ">",
1495                                                     NULL);
1496                 }
1497         }
1498
1499         return 0;
1500 }
1501
1502 static gchar *compose_parse_references(const gchar *ref, const gchar *msgid)
1503 {
1504         GSList *ref_id_list, *cur;
1505         GString *new_ref;
1506         gchar *new_ref_str;
1507
1508         ref_id_list = references_list_append(NULL, ref);
1509         if (!ref_id_list) return NULL;
1510         if (msgid && *msgid)
1511                 ref_id_list = g_slist_append(ref_id_list, g_strdup(msgid));
1512
1513         for (;;) {
1514                 gint len = 0;
1515
1516                 for (cur = ref_id_list; cur != NULL; cur = cur->next)
1517                         /* "<" + Message-ID + ">" + CR+LF+TAB */
1518                         len += strlen((gchar *)cur->data) + 5;
1519
1520                 if (len > MAX_REFERENCES_LEN) {
1521                         /* remove second message-ID */
1522                         if (ref_id_list && ref_id_list->next &&
1523                             ref_id_list->next->next) {
1524                                 g_free(ref_id_list->next->data);
1525                                 ref_id_list = g_slist_remove
1526                                         (ref_id_list, ref_id_list->next->data);
1527                         } else {
1528                                 slist_free_strings(ref_id_list);
1529                                 g_slist_free(ref_id_list);
1530                                 return NULL;
1531                         }
1532                 } else
1533                         break;
1534         }
1535
1536         new_ref = g_string_new("");
1537         for (cur = ref_id_list; cur != NULL; cur = cur->next) {
1538                 if (new_ref->len > 0)
1539                         g_string_append(new_ref, "\n\t");
1540                 g_string_sprintfa(new_ref, "<%s>", (gchar *)cur->data);
1541         }
1542
1543         slist_free_strings(ref_id_list);
1544         g_slist_free(ref_id_list);
1545
1546         new_ref_str = new_ref->str;
1547         g_string_free(new_ref, FALSE);
1548
1549         return new_ref_str;
1550 }
1551
1552 static gchar *compose_quote_fmt(Compose *compose, MsgInfo *msginfo,
1553                                 const gchar *fmt, const gchar *qmark)
1554 {
1555         GtkSText *text = GTK_STEXT(compose->text);
1556         gchar *quote_str = NULL;
1557         gchar *buf;
1558         gchar *p, *lastp;
1559         gint len;
1560
1561         if (qmark != NULL) {
1562                 quote_fmt_init(msginfo, NULL);
1563                 quote_fmt_scan_string(qmark);
1564                 quote_fmt_parse();
1565
1566                 buf = quote_fmt_get_buffer();
1567                 if (buf == NULL)
1568                         alertpanel_error(_("Quote mark format error."));
1569                 else
1570                         Xstrdup_a(quote_str, buf, return NULL)
1571         }
1572
1573         if (fmt && *fmt != '\0') {
1574                 quote_fmt_init(msginfo, quote_str);
1575                 quote_fmt_scan_string(fmt);
1576                 quote_fmt_parse();
1577
1578                 buf = quote_fmt_get_buffer();
1579                 if (buf == NULL) {
1580                         alertpanel_error(_("Message reply/forward format error."));
1581                         return NULL;
1582                 }
1583         } else
1584                 buf = "";
1585
1586         gtk_stext_freeze(text);
1587         gtk_stext_set_point(text, 0);
1588         gtk_stext_forward_delete(text, gtk_stext_get_length(text));
1589
1590         for (p = buf; *p != '\0'; ) {
1591                 lastp = strchr(p, '\n');
1592                 len = lastp ? lastp - p + 1 : -1;
1593                 gtk_stext_insert(text, NULL, NULL, NULL, p, len);
1594                 if (lastp)
1595                         p = lastp + 1;
1596                 else
1597                         break;
1598         }
1599
1600         gtk_stext_thaw(text);
1601
1602         return buf;
1603 }
1604
1605 static void compose_reply_set_entry(Compose *compose, MsgInfo *msginfo,
1606                                     gboolean to_all, gboolean ignore_replyto,
1607                                     gboolean followup_and_reply_to)
1608 {
1609         GSList *cc_list;
1610         GSList *cur;
1611         gchar *from;
1612         GHashTable *to_table;
1613
1614         g_return_if_fail(compose->account != NULL);
1615         g_return_if_fail(msginfo != NULL);
1616
1617         if ((compose->account->protocol != A_NNTP) || followup_and_reply_to)
1618                 compose_entry_append(compose,
1619                                     ((compose->replyto && !ignore_replyto)
1620                                      ? compose->replyto
1621                                      : (compose->mailinglist && !ignore_replyto)
1622                                      ? compose->mailinglist
1623                                      : msginfo->from ? msginfo->from : ""),
1624                                      COMPOSE_TO);
1625         if (compose->account->protocol == A_NNTP) {
1626                 if (ignore_replyto)
1627                         compose_entry_append
1628                                 (compose, msginfo->from ? msginfo->from : "",
1629                                  COMPOSE_TO);
1630                 else
1631                         compose_entry_append
1632                                 (compose,
1633                                  compose->followup_to ? compose->followup_to
1634                                  : compose->newsgroups ? compose->newsgroups
1635                                  : "",
1636                                  COMPOSE_NEWSGROUPS);
1637         }
1638
1639         if (msginfo->subject && *msginfo->subject) {
1640                 gchar *buf, *buf2, *p;
1641
1642                 buf = g_strdup(msginfo->subject);
1643                 while (!strncasecmp(buf, "Re:", 3)) {
1644                         p = buf + 3;
1645                         while (isspace(*p)) p++;
1646                         memmove(buf, p, strlen(p) + 1);
1647                 }
1648
1649                 buf2 = g_strdup_printf("Re: %s", buf);
1650                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), buf2);
1651                 g_free(buf2);
1652                 g_free(buf);
1653         } else
1654                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), "Re: ");
1655
1656         if (!to_all || compose->account->protocol == A_NNTP) return;
1657
1658         from = g_strdup(compose->replyto ? compose->replyto :
1659                         msginfo->from ? msginfo->from : "");
1660         extract_address(from);
1661
1662         cc_list = address_list_append(NULL, msginfo->to);
1663         cc_list = address_list_append(cc_list, compose->cc);
1664
1665         to_table = g_hash_table_new(g_str_hash, g_str_equal);
1666         g_hash_table_insert(to_table, from, GINT_TO_POINTER(1));
1667         if (compose->account)
1668                 g_hash_table_insert(to_table, compose->account->address,
1669                                     GINT_TO_POINTER(1));
1670
1671         /* remove address on To: and that of current account */
1672         for (cur = cc_list; cur != NULL; ) {
1673                 GSList *next = cur->next;
1674
1675                 if (g_hash_table_lookup(to_table, cur->data) != NULL)
1676                         cc_list = g_slist_remove(cc_list, cur->data);
1677                 else
1678                         g_hash_table_insert(to_table, cur->data, cur);
1679
1680                 cur = next;
1681         }
1682         g_hash_table_destroy(to_table);
1683         g_free(from);
1684
1685         if (cc_list) {
1686                 for (cur = cc_list; cur != NULL; cur = cur->next)
1687                         compose_entry_append(compose, (gchar *)cur->data,
1688                                              COMPOSE_CC);
1689                 slist_free_strings(cc_list);
1690                 g_slist_free(cc_list);
1691         }
1692 }
1693
1694 #define SET_ENTRY(entry, str) \
1695 { \
1696         if (str && *str) \
1697                 gtk_entry_set_text(GTK_ENTRY(compose->entry), str); \
1698 }
1699
1700 #define SET_ADDRESS(type, str) \
1701 { \
1702         if (str && *str) \
1703                 compose_entry_append(compose, str, type); \
1704 }
1705
1706 static void compose_reedit_set_entry(Compose *compose, MsgInfo *msginfo)
1707 {
1708         g_return_if_fail(msginfo != NULL);
1709
1710         SET_ENTRY(subject_entry, msginfo->subject);
1711         SET_ADDRESS(COMPOSE_TO, msginfo->to);
1712         SET_ADDRESS(COMPOSE_CC, compose->cc);
1713         SET_ADDRESS(COMPOSE_BCC, compose->bcc);
1714         SET_ADDRESS(COMPOSE_REPLYTO, compose->replyto);
1715
1716         compose_show_first_last_header(compose, TRUE);
1717
1718 #if 0 /* NEW COMPOSE GUI */
1719         if (compose->bcc) {
1720                 GtkItemFactory *ifactory;
1721                 GtkWidget *menuitem;
1722
1723                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1724                 menuitem = gtk_item_factory_get_item(ifactory, "/View/Bcc");
1725                 gtk_check_menu_item_set_active
1726                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
1727         }
1728         if (compose->replyto) {
1729                 GtkItemFactory *ifactory;
1730                 GtkWidget *menuitem;
1731
1732                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1733                 menuitem = gtk_item_factory_get_item
1734                         (ifactory, "/View/Reply to");
1735                 gtk_check_menu_item_set_active
1736                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
1737         }
1738 #endif
1739 }
1740
1741 #undef SET_ENTRY
1742 #undef SET_ADDRESS
1743
1744 static void compose_exec_sig(Compose *compose, gchar *sigfile)
1745 {
1746         FILE *tmpfp;
1747         pid_t thepid;
1748         gchar *sigtext;
1749         FILE  *sigprg;
1750         gchar  *buf;
1751         size_t buf_len = 128;
1752  
1753         if (strlen(sigfile) < 2)
1754           return;
1755  
1756         sigprg = popen(sigfile+1, "r");
1757         if (sigprg) {
1758
1759                 buf = g_malloc(buf_len);
1760
1761                 if (!buf) {
1762                         gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, \
1763                         "Unable to insert signature (malloc failed)\n", -1);
1764
1765                         pclose(sigprg);
1766                         return;
1767                 }
1768
1769                 while (!feof(sigprg)) {
1770                         bzero(buf, buf_len);
1771                         fread(buf, buf_len-1, 1, sigprg);
1772                         gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, buf, -1);
1773                 }
1774
1775                 g_free(buf);
1776                 pclose(sigprg);
1777         }
1778         else
1779         {
1780                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, \
1781                 "Can't exec file: ", -1);
1782                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, \
1783                 sigfile+1, -1);
1784         }
1785 }
1786
1787 static void compose_insert_sig(Compose *compose)
1788 {
1789         gchar *sigfile;
1790
1791         if (compose->account && compose->account->sig_path)
1792                 sigfile = g_strdup(compose->account->sig_path);
1793         else {
1794                 sigfile = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1795                                       DEFAULT_SIGNATURE, NULL);
1796         }
1797
1798         if (!is_file_or_fifo_exist(sigfile) & (sigfile[0] != '|')) {
1799                 g_free(sigfile);
1800                 return;
1801         }
1802
1803         gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, "\n\n", 2);
1804         if (prefs_common.sig_sep) {
1805                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL,
1806                                 prefs_common.sig_sep, -1);
1807                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL,
1808                                 "\n", 1);
1809         }
1810
1811         if (sigfile[0] == '|')
1812         {
1813                 compose_exec_sig(compose, sigfile);
1814         }
1815         else
1816         {
1817                 compose_insert_file(compose, sigfile);
1818         }
1819         g_free(sigfile);
1820 }
1821
1822 static void compose_insert_file(Compose *compose, const gchar *file)
1823 {
1824         GtkSText *text = GTK_STEXT(compose->text);
1825         gchar buf[BUFFSIZE];
1826         gint len;
1827         FILE *fp;
1828
1829         g_return_if_fail(file != NULL);
1830
1831         if ((fp = fopen(file, "r")) == NULL) {
1832                 FILE_OP_ERROR(file, "fopen");
1833                 return;
1834         }
1835
1836         gtk_stext_freeze(text);
1837
1838         while (fgets(buf, sizeof(buf), fp) != NULL) {
1839                 /* strip <CR> if DOS/Windows file,
1840                    replace <CR> with <LF> if Macintosh file. */
1841                 strcrchomp(buf);
1842                 len = strlen(buf);
1843                 if (len > 0 && buf[len - 1] != '\n') {
1844                         while (--len >= 0)
1845                                 if (buf[len] == '\r') buf[len] = '\n';
1846                 }
1847                 gtk_stext_insert(text, NULL, NULL, NULL, buf, -1);
1848         }
1849
1850         gtk_stext_thaw(text);
1851
1852         fclose(fp);
1853 }
1854
1855 static void compose_attach_info(Compose * compose, AttachInfo * ainfo,
1856                                 ContentType cnttype)
1857 {
1858         gchar *text[N_ATTACH_COLS];
1859         gint row;
1860
1861         text[COL_MIMETYPE] = ainfo->content_type;
1862         text[COL_SIZE] = to_human_readable(ainfo->size);
1863         text[COL_NAME] = ainfo->name;
1864
1865         row = gtk_clist_append(GTK_CLIST(compose->attach_clist), text);
1866         gtk_clist_set_row_data(GTK_CLIST(compose->attach_clist), row, ainfo);
1867
1868         if (cnttype != MIME_MESSAGE_RFC822)
1869                 compose_changed_cb(NULL, compose);
1870 }
1871
1872 static void compose_attach_append_with_type(Compose *compose,
1873                                             const gchar *file,
1874                                             const gchar *type,
1875                                             ContentType cnttype)
1876 {
1877         AttachInfo *ainfo;
1878         off_t size;
1879
1880         if (!is_file_exist(file)) {
1881                 g_warning(_("File %s doesn't exist\n"), file);
1882                 return;
1883         }
1884         if ((size = get_file_size(file)) < 0) {
1885                 g_warning(_("Can't get file size of %s\n"), file);
1886                 return;
1887         }
1888         if (size == 0) {
1889                 alertpanel_notice(_("File %s is empty\n"), file);
1890                 return;
1891         }
1892 #if 0 /* NEW COMPOSE GUI */
1893         if (!compose->use_attach) {
1894                 GtkItemFactory *ifactory;
1895                 GtkWidget *menuitem;
1896
1897                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1898                 menuitem = gtk_item_factory_get_item(ifactory,
1899                                                      "/Message/Attach");
1900                 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
1901                                                TRUE);
1902         }
1903 #endif
1904         ainfo = g_new0(AttachInfo, 1);
1905         ainfo->file = g_strdup(file);
1906
1907         if (cnttype == MIME_MESSAGE_RFC822) {
1908                 ainfo->encoding = ENC_7BIT;
1909                 ainfo->name = g_strdup_printf(_("Message: %s"),
1910                                               g_basename(file));
1911         } else {
1912                 ainfo->encoding = ENC_BASE64;
1913                 ainfo->name = g_strdup(g_basename(file));
1914         }
1915
1916         ainfo->content_type = g_strdup(type);
1917         ainfo->size = size;
1918
1919         compose_attach_info(compose, ainfo, cnttype);
1920 }
1921
1922 static void compose_attach_append(Compose *compose, const gchar *file,
1923                                   ContentType cnttype)
1924 {
1925         AttachInfo *ainfo;
1926         gchar *text[N_ATTACH_COLS];
1927         off_t size;
1928         gint row;
1929
1930         if (!is_file_exist(file)) {
1931                 g_warning(_("File %s doesn't exist\n"), file);
1932                 return;
1933         }
1934         if ((size = get_file_size(file)) < 0) {
1935                 g_warning(_("Can't get file size of %s\n"), file);
1936                 return;
1937         }
1938         if (size == 0) {
1939                 alertpanel_notice(_("File %s is empty\n"), file);
1940                 return;
1941         }
1942 #if 0 /* NEW COMPOSE GUI */
1943         if (!compose->use_attach) {
1944                 GtkItemFactory *ifactory;
1945                 GtkWidget *menuitem;
1946
1947                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1948                 menuitem = gtk_item_factory_get_item(ifactory,
1949                                                      "/View/Attachment");
1950                 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
1951                                                TRUE);
1952         }
1953 #endif
1954         ainfo = g_new0(AttachInfo, 1);
1955         ainfo->file = g_strdup(file);
1956
1957         if (cnttype == MIME_MESSAGE_RFC822) {
1958                 ainfo->content_type = g_strdup("message/rfc822");
1959                 ainfo->encoding = ENC_7BIT;
1960                 ainfo->name = g_strdup_printf(_("Message: %s"),
1961                                               g_basename(file));
1962         } else {
1963                 ainfo->content_type = procmime_get_mime_type(file);
1964                 if (!ainfo->content_type)
1965                         ainfo->content_type =
1966                                 g_strdup("application/octet-stream");
1967                 ainfo->encoding = ENC_BASE64;
1968                 ainfo->name = g_strdup(g_basename(file));
1969         }
1970         ainfo->size = size;
1971
1972         compose_attach_info(compose, ainfo, cnttype);
1973 }
1974
1975 #define GET_CHAR(pos, buf, len)                                              \
1976 {                                                                            \
1977         if (text->use_wchar)                                                 \
1978                 len = wctomb(buf, (wchar_t)GTK_STEXT_INDEX(text, (pos)));    \
1979         else {                                                               \
1980                 buf[0] = GTK_STEXT_INDEX(text, (pos));                       \
1981                 len = 1;                                                     \
1982         }                                                                    \
1983 }
1984
1985 static void compose_wrap_line(Compose *compose)
1986 {
1987         GtkSText *text = GTK_STEXT(compose->text);
1988         gint ch_len, last_ch_len;
1989         gchar cbuf[MB_LEN_MAX], last_ch;
1990         guint text_len;
1991         guint line_end;
1992         guint quoted;
1993         gint p_start, p_end;
1994         gint line_pos, cur_pos;
1995         gint line_len, cur_len;
1996
1997         gtk_stext_freeze(text);
1998
1999         text_len = gtk_stext_get_length(text);
2000
2001         /* check to see if the point is on the paragraph mark (empty line). */
2002         cur_pos = gtk_stext_get_point(text);
2003         GET_CHAR(cur_pos, cbuf, ch_len);
2004         if ((ch_len == 1 && *cbuf == '\n') || cur_pos == text_len) {
2005                 if (cur_pos == 0)
2006                         goto compose_end; /* on the paragraph mark */
2007                 GET_CHAR(cur_pos - 1, cbuf, ch_len);
2008                 if (ch_len == 1 && *cbuf == '\n')
2009                         goto compose_end; /* on the paragraph mark */
2010         }
2011
2012         /* find paragraph start. */
2013         line_end = quoted = 0;
2014         for (p_start = cur_pos; p_start >= 0; --p_start) {
2015                 GET_CHAR(p_start, cbuf, ch_len);
2016                 if (ch_len == 1 && *cbuf == '\n') {
2017                         if (quoted)
2018                                 goto compose_end; /* quoted part */
2019                         if (line_end) {
2020                                 p_start += 2;
2021                                 break;
2022                         }
2023                         line_end = 1;
2024                 } else {
2025                         if (ch_len == 1 && strchr(">:#", *cbuf))
2026                                 quoted = 1;
2027                         else if (ch_len != 1 || !isspace(*cbuf))
2028                                 quoted = 0;
2029
2030                         line_end = 0;
2031                 }
2032         }
2033         if (p_start < 0)
2034                 p_start = 0;
2035
2036         /* find paragraph end. */
2037         line_end = 0;
2038         for (p_end = cur_pos; p_end < text_len; p_end++) {
2039                 GET_CHAR(p_end, cbuf, ch_len);
2040                 if (ch_len == 1 && *cbuf == '\n') {
2041                         if (line_end) {
2042                                 p_end -= 1;
2043                                 break;
2044                         }
2045                         line_end = 1;
2046                 } else {
2047                         if (line_end && ch_len == 1 && strchr(">:#", *cbuf))
2048                                 goto compose_end; /* quoted part */
2049
2050                         line_end = 0;
2051                 }
2052         }
2053         if (p_end >= text_len)
2054                 p_end = text_len;
2055
2056         if (p_start >= p_end)
2057                 goto compose_end;
2058
2059         line_len = cur_len = 0;
2060         last_ch_len = 0;
2061         last_ch = '\0';
2062         line_pos = p_start;
2063         for (cur_pos = p_start; cur_pos < p_end; cur_pos++) {
2064                 guint space = 0;
2065
2066                 GET_CHAR(cur_pos, cbuf, ch_len);
2067
2068                 if (ch_len < 0) {
2069                         cbuf[0] = '\0';
2070                         ch_len = 1;
2071                 }
2072
2073                 if (ch_len == 1 && isspace(*cbuf))
2074                         space = 1;
2075
2076                 if (ch_len == 1 && *cbuf == '\n') {
2077                         guint replace = 0;
2078                         if (last_ch_len == 1 && !isspace(last_ch)) {
2079                                 if (cur_pos + 1 < p_end) {
2080                                         GET_CHAR(cur_pos + 1, cbuf, ch_len);
2081                                         if (ch_len == 1 && !isspace(*cbuf))
2082                                                 replace = 1;
2083                                 }
2084                         }
2085                         gtk_stext_set_point(text, cur_pos + 1);
2086                         gtk_stext_backward_delete(text, 1);
2087                         if (replace) {
2088                                 gtk_stext_set_point(text, cur_pos);
2089                                 gtk_stext_insert(text, NULL, NULL, NULL, " ", 1);
2090                                 space = 1;
2091                         }
2092                         else {
2093                                 p_end--;
2094                                 cur_pos--;
2095                                 continue;
2096                         }
2097                 }
2098
2099                 last_ch_len = ch_len;
2100                 last_ch = *cbuf;
2101
2102                 if (space) {
2103                         line_pos = cur_pos + 1;
2104                         line_len = cur_len + ch_len;
2105                 }
2106
2107                 if (cur_len + ch_len > prefs_common.linewrap_len &&
2108                     line_len > 0) {
2109                         gint tlen = ch_len;
2110
2111                         GET_CHAR(line_pos - 1, cbuf, ch_len);
2112                         if (ch_len == 1 && isspace(*cbuf)) {
2113                                 gtk_stext_set_point(text, line_pos);
2114                                 gtk_stext_backward_delete(text, 1);
2115                                 p_end--;
2116                                 cur_pos--;
2117                                 line_pos--;
2118                                 cur_len--;
2119                                 line_len--;
2120                         }
2121                         ch_len = tlen;
2122
2123                         gtk_stext_set_point(text, line_pos);
2124                         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1);
2125                         p_end++;
2126                         cur_pos++;
2127                         line_pos++;
2128                         cur_len = cur_len - line_len + ch_len;
2129                         line_len = 0;
2130                         continue;
2131                 }
2132
2133                 if (ch_len > 1) {
2134                         line_pos = cur_pos + 1;
2135                         line_len = cur_len + ch_len;
2136                 }
2137                 cur_len += ch_len;
2138         }
2139
2140 compose_end:
2141         gtk_stext_thaw(text);
2142 }
2143
2144 /* return indent length */
2145 static guint get_indent_length(GtkSText *text, guint start_pos, guint text_len)
2146 {
2147         gint indent_len = 0;
2148         gint i, ch_len;
2149         gchar cbuf[MB_LEN_MAX];
2150
2151         for (i = start_pos; i < text_len; i++) {
2152                 GET_CHAR(i, cbuf, ch_len);
2153                 if (ch_len > 1)
2154                         break;
2155                 /* allow space, tab, > or | */
2156                 if (cbuf[0] != ' ' && cbuf[0] != '\t' &&
2157                     cbuf[0] != '>' && cbuf[0] != '|')
2158                         break;
2159                 indent_len++;
2160         }
2161
2162         return indent_len;
2163 }
2164
2165 /* insert quotation string when line was wrapped */
2166 static guint ins_quote(GtkSText *text, guint quote_len, guint indent_len,
2167                        guint prev_line_pos, guint text_len,
2168                        gchar *quote_fmt)
2169 {
2170         guint i, ins_len;
2171         gchar ch;
2172
2173         if (indent_len) {
2174                 for (i = 0; i < indent_len; i++) {
2175                         ch = GTK_STEXT_INDEX(text, prev_line_pos + i);
2176                         gtk_stext_insert(text, NULL, NULL, NULL, &ch, 1);
2177                 }
2178                 ins_len = indent_len;
2179         } else {
2180                 gtk_stext_insert(text, NULL, NULL, NULL, quote_fmt, quote_len);
2181                 ins_len = quote_len;
2182         }
2183
2184         return ins_len;
2185 }
2186
2187 #undef WRAP_DEBUG
2188 #ifdef WRAP_DEBUG
2189 /* Darko: used when I debug wrapping */
2190 void dump_text(GtkSText *text, int pos, int tlen, int breakoncr)
2191 {
2192         gint i;
2193         gchar ch;
2194
2195         printf("%d [", pos);
2196         for (i = pos; i < tlen; i++) {
2197                 ch = GTK_STEXT_INDEX(text, i);
2198                 if (breakoncr && ch == '\n')
2199                         break;
2200                 printf("%c", ch);
2201         }
2202         printf("]\n");
2203 }
2204 #endif
2205
2206 static void compose_wrap_line_all(Compose *compose)
2207 {
2208         GtkSText *text = GTK_STEXT(compose->text);
2209         guint tlen;
2210         guint line_pos = 0, cur_pos = 0, p_pos = 0;
2211         gint line_len = 0, cur_len = 0;
2212         gint ch_len;
2213         gboolean is_new_line = TRUE, do_delete = FALSE;
2214         guint qlen = 0, i_len = 0;
2215         guint linewrap_quote = prefs_common.linewrap_quote;
2216         guint linewrap_len = prefs_common.linewrap_len;
2217         gchar *qfmt = prefs_common.quotemark;
2218         gchar cbuf[MB_LEN_MAX];
2219
2220         gtk_stext_freeze(text);
2221
2222         /* make text buffer contiguous */
2223         /* gtk_stext_compact_buffer(text); */
2224
2225         tlen = gtk_stext_get_length(text);
2226
2227         for (; cur_pos < tlen; cur_pos++) {
2228                 /* mark position of new line - needed for quotation wrap */
2229                 if (is_new_line) {
2230                         if (linewrap_quote) {
2231                                 qlen = gtkut_stext_str_compare
2232                                         (text, cur_pos, tlen, qfmt);
2233                                 if (qlen)
2234                                         i_len = get_indent_length
2235                                                 (text, cur_pos, tlen);
2236                                 else
2237                                         i_len = 0;
2238                         }
2239                         is_new_line = FALSE;
2240                         p_pos = cur_pos;
2241 #ifdef WRAP_DEBUG
2242                         printf("new line i_len=%d qlen=%d p_pos=", i_len, qlen);
2243                         dump_text(text, p_pos, tlen, 1);
2244 #endif
2245                 }
2246
2247                 GET_CHAR(cur_pos, cbuf, ch_len);
2248
2249                 /* fix line length for tabs */
2250                 if (ch_len == 1 && *cbuf == '\t') {
2251                         guint tab_width = text->default_tab_width;
2252                         guint tab_offset = line_len % tab_width;
2253
2254 #ifdef WRAP_DEBUG
2255                         printf("found tab at pos=%d line_len=%d ", cur_pos,
2256                                 line_len);
2257 #endif
2258                         if (tab_offset) {
2259                                 line_len += tab_width - tab_offset - 1;
2260                                 cur_len = line_len;
2261                         }
2262 #ifdef WRAP_DEBUG
2263                         printf("new_len=%d\n", line_len);
2264 #endif
2265                 }
2266
2267                 /* we have encountered line break */
2268                 if (ch_len == 1 && *cbuf == '\n') {
2269                         gint clen;
2270                         guint ilen;
2271                         gchar cb[MB_CUR_MAX];
2272
2273 #ifdef WRAP_DEBUG
2274                         printf("found CR at %d next line is ", cur_pos);
2275                         dump_text(text, cur_pos + 1, tlen, 1);
2276 #endif
2277                         /* if it's just quotation + newline skip it */
2278                         if (i_len && (cur_pos + 1 < tlen)) {
2279                                 /* check if text at new line matches indent */
2280                                 ilen =  gtkut_stext_str_compare_n
2281                                         (text, cur_pos + 1, p_pos, i_len, tlen);
2282                                 if (cur_pos + ilen < tlen) {
2283                                         GET_CHAR(cur_pos + ilen + 1, cb, clen);
2284                                         /* no need to join the lines */
2285                                         if (clen == 1 && cb[0] == '\n')
2286                                                 do_delete = FALSE;
2287                                 }
2288                         /* if it's just newline skip it */
2289                         } else if (do_delete && (cur_pos + 1 < tlen)) {
2290                                 GET_CHAR(cur_pos + 1, cb, clen);
2291                                 /* no need to join the lines */
2292                                 if (clen == 1 && cb[0] == '\n')
2293                                         do_delete = FALSE;
2294                         }
2295
2296 #ifdef WRAP_DEBUG
2297                         printf("qlen=%d l_len=%d wrap_len=%d do_del=%d\n",
2298                                 qlen, line_len, linewrap_len, do_delete);
2299 #endif
2300                         /* should we delete to perform smart wrapping */
2301                         if (line_len < linewrap_len && do_delete) {
2302                                 /* get rid of newline */
2303                                 gtk_stext_set_point(text, cur_pos);
2304                                 gtk_stext_forward_delete(text, 1);
2305                                 tlen--;
2306
2307                                 /* if text starts with quote fmt or with
2308                                    indent string, delete them */
2309                                 if (i_len) {
2310                                         ilen =  gtkut_stext_str_compare_n
2311                                                 (text, cur_pos, p_pos, i_len,
2312                                                  tlen);
2313                                         if (ilen) {
2314                                                 gtk_stext_forward_delete
2315                                                         (text, ilen);
2316                                                 tlen -= ilen;
2317                                         }
2318                                 } else if (qlen) {
2319                                         if (gtkut_stext_str_compare
2320                                             (text, cur_pos, tlen, qfmt)) {
2321                                                 gtk_stext_forward_delete
2322                                                         (text, qlen);
2323                                                 tlen -= qlen;
2324                                         }
2325                                 }
2326
2327                                 GET_CHAR(cur_pos, cb, clen);
2328
2329                                 /* insert space if it's alphanumeric */
2330                                 if ((cur_pos != line_pos) &&
2331                                     ((clen > 1) || isalnum(cb[0]))) {
2332                                         gtk_stext_insert(text, NULL, NULL,
2333                                                         NULL, " ", 1);
2334                                         /* gtk_stext_compact_buffer(text); */
2335                                         tlen++;
2336                                 }
2337
2338                                 /* and start over with current line */
2339                                 cur_pos = p_pos - 1;
2340                                 line_pos = cur_pos;
2341                                 line_len = cur_len = 0;
2342                                 qlen = 0;
2343                                 do_delete = FALSE;
2344                                 is_new_line = TRUE;
2345 #ifdef WRAP_DEBUG
2346                                 printf("after delete l_pos=");
2347                                 dump_text(text, line_pos, tlen, 1);
2348 #endif
2349                                 continue;
2350                         }
2351
2352                         /* mark new line beginning */
2353                         line_pos = cur_pos + 1;
2354                         line_len = cur_len = 0;
2355                         qlen = 0;
2356                         do_delete = FALSE;
2357                         is_new_line = TRUE;
2358                         continue;
2359                 }
2360
2361                 if (ch_len < 0) {
2362                         cbuf[0] = '\0';
2363                         ch_len = 1;
2364                 }
2365
2366                 /* possible line break */
2367                 if (ch_len == 1 && isspace(*cbuf)) {
2368                         line_pos = cur_pos + 1;
2369                         line_len = cur_len + ch_len;
2370                 }
2371
2372                 /* are we over wrapping length set in preferences ? */
2373                 if (cur_len + ch_len > linewrap_len) {
2374                         gint clen;
2375
2376 #ifdef WRAP_DEBUG
2377                         printf("should wrap cur_pos=%d ", cur_pos);
2378                         dump_text(text, p_pos, tlen, 1);
2379                         dump_text(text, line_pos, tlen, 1);
2380 #endif
2381                         /* force wrapping if it is one long word but not URL */
2382                         if (line_pos - p_pos <= i_len)
2383                                 if (!gtkut_stext_is_uri_string
2384                                     (text, line_pos, tlen))
2385                                         line_pos = cur_pos - 1;
2386 #ifdef WRAP_DEBUG
2387                         printf("new line_pos=%d\n", line_pos);
2388 #endif
2389
2390                         GET_CHAR(line_pos - 1, cbuf, clen);
2391
2392                         /* if next character is space delete it */
2393                         if (clen == 1 && isspace(*cbuf)) {
2394                                 if (p_pos + i_len != line_pos ||
2395                                     !gtkut_stext_is_uri_string
2396                                         (text, line_pos, tlen)) {
2397                                         gtk_stext_set_point(text, line_pos);
2398                                         gtk_stext_backward_delete(text, 1);
2399                                         tlen--;
2400                                         cur_pos--;
2401                                         line_pos--;
2402                                         cur_len--;
2403                                         line_len--;
2404                                 }
2405                         }
2406
2407                         /* if it is URL at beginning of line don't wrap */
2408                         if (p_pos + i_len == line_pos &&
2409                             gtkut_stext_is_uri_string(text, line_pos, tlen)) {
2410 #ifdef WRAP_DEBUG
2411                                 printf("found URL at ");
2412                                 dump_text(text, line_pos, tlen, 1);
2413 #endif
2414                                 continue;
2415                         }
2416
2417                         /* insert CR */
2418                         gtk_stext_set_point(text, line_pos);
2419                         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1);
2420                         /* gtk_stext_compact_buffer(text); */
2421                         tlen++;
2422                         line_pos++;
2423                         /* for loop will increase it */
2424                         cur_pos = line_pos - 1;
2425                         /* start over with current line */
2426                         is_new_line = TRUE;
2427                         line_len = 0;
2428                         cur_len = 0;
2429                         do_delete = TRUE;
2430 #ifdef WRAP_DEBUG
2431                         printf("after CR insert ");
2432                         dump_text(text, line_pos, tlen, 1);
2433                         dump_text(text, cur_pos, tlen, 1);
2434 #endif
2435
2436                         /* should we insert quotation ? */
2437                         if (linewrap_quote && qlen) {
2438                                 /* only if line is not already quoted  */
2439                                 if (!gtkut_stext_str_compare
2440                                         (text, line_pos, tlen, qfmt)) {
2441                                         guint ins_len;
2442
2443                                         if (line_pos - p_pos > i_len) {
2444                                                 ins_len = ins_quote
2445                                                         (text, qlen, i_len,
2446                                                          p_pos, tlen, qfmt);
2447
2448                                                 /* gtk_stext_compact_buffer(text); */
2449                                                 tlen += ins_len;
2450                                         }
2451 #ifdef WRAP_DEBUG
2452                                         printf("after quote insert ");
2453                                         dump_text(text, line_pos, tlen, 1);
2454 #endif
2455                                 }
2456                         }
2457                         continue;
2458                 }
2459
2460                 if (ch_len > 1) {
2461                         line_pos = cur_pos + 1;
2462                         line_len = cur_len + ch_len;
2463                 }
2464                 /* advance to next character in buffer */
2465                 cur_len += ch_len;
2466         }
2467
2468         gtk_stext_thaw(text);
2469 }
2470
2471 #undef GET_CHAR
2472
2473 static void compose_set_title(Compose *compose)
2474 {
2475         gchar *str;
2476         gchar *edited;
2477
2478         edited = compose->modified ? _(" [Edited]") : "";
2479         if (compose->account && compose->account->address)
2480                 str = g_strdup_printf(_("%s - Compose message%s"),
2481                                       compose->account->address, edited);
2482         else
2483                 str = g_strdup_printf(_("Compose message%s"), edited);
2484         gtk_window_set_title(GTK_WINDOW(compose->window), str);
2485         g_free(str);
2486 }
2487
2488 /**
2489  * compose_current_mail_account:
2490  * 
2491  * Find a current mail account (the currently selected account, or the
2492  * default account, if a news account is currently selected).  If a
2493  * mail account cannot be found, display an error message.
2494  * 
2495  * Return value: Mail account, or NULL if not found.
2496  **/
2497 static PrefsAccount *
2498 compose_current_mail_account(void)
2499 {
2500         PrefsAccount *ac;
2501
2502         if (cur_account && cur_account->protocol != A_NNTP)
2503                 ac = cur_account;
2504         else {
2505                 ac = account_get_default();
2506                 if (!ac || ac->protocol == A_NNTP) {
2507                         alertpanel_error(_("Account for sending mail is not specified.\n"
2508                                            "Please select a mail account before sending."));
2509                         return NULL;
2510                 }
2511         }
2512         return ac;
2513 }
2514
2515 gboolean compose_check_for_valid_recipient(Compose *compose) {
2516         gchar *recipient_headers_mail[] = {"To:", "Cc:", "Bcc:", NULL};
2517         gchar *recipient_headers_news[] = {"Newsgroups:", NULL};
2518         gboolean recipient_found = FALSE;
2519         GSList *list;
2520         gchar **strptr;
2521
2522         /* free to and newsgroup list */
2523         slist_free_strings(compose->to_list);
2524         g_slist_free(compose->to_list);
2525         compose->to_list = NULL;
2526                         
2527         slist_free_strings(compose->newsgroup_list);
2528         g_slist_free(compose->newsgroup_list);
2529         compose->newsgroup_list = NULL;
2530
2531         /* search header entries for to and newsgroup entries */
2532         for(list = compose->header_list; list; list = list->next) {
2533                 gchar *header;
2534                 gchar *entry;
2535                 header = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(((ComposeHeaderEntry *)list->data)->combo)->entry));
2536                 entry = gtk_editable_get_chars(GTK_EDITABLE(((ComposeHeaderEntry *)list->data)->entry), 0, -1);
2537                 g_strstrip(entry);
2538                 if(entry[0] != '\0') {
2539                         for(strptr = recipient_headers_mail; *strptr != NULL; strptr++) {
2540                                 if(!strcmp(header, (prefs_common.trans_hdr ? gettext(*strptr) : *strptr))) {
2541                                         compose->to_list = address_list_append(compose->to_list, entry);
2542                                         recipient_found = TRUE;
2543                                 }
2544                         }
2545                         for(strptr = recipient_headers_news; *strptr != NULL; strptr++) {
2546                                 if(!strcmp(header, (prefs_common.trans_hdr ? gettext(*strptr) : *strptr))) {
2547                                         compose->newsgroup_list = newsgroup_list_append(compose->newsgroup_list, entry);
2548                                         recipient_found = TRUE;
2549                                 }
2550                         }
2551                 }
2552                 g_free(entry);
2553         }
2554         return recipient_found;
2555 }
2556
2557 gint compose_send(Compose *compose)
2558 {
2559         gint msgnum;
2560         FolderItem *folder;
2561         gint val;
2562
2563         val = compose_queue(compose, &msgnum, &folder);
2564         if (val) {
2565                 alertpanel_error(_("Could not queue message for sending"));
2566                 return -1;
2567         }
2568         
2569         val = procmsg_send_message_queue(folder_item_fetch_msg(folder, msgnum));
2570         if(!val) {
2571                 folder_item_remove_msg(folder, msgnum);
2572                 folderview_update_item(folder, TRUE);
2573         }
2574
2575         return val;
2576 }
2577
2578 #if 0 /* compose restructure */
2579 gint compose_send(Compose *compose)
2580 {
2581         gchar tmp[MAXPATHLEN + 1];
2582         gint ok = 0;
2583         static gboolean lock = FALSE;
2584
2585         if (lock) return 1;
2586
2587         g_return_val_if_fail(compose->account != NULL, -1);
2588         g_return_val_if_fail(compose->orig_account != NULL, -1);
2589
2590         lock = TRUE;
2591
2592         if(!compose_check_for_valid_recipient(compose)) {
2593                 alertpanel_error(_("Recipient is not specified."));
2594                 lock = FALSE;
2595                 return 1;
2596         }
2597
2598         /* write to temporary file */
2599         g_snprintf(tmp, sizeof(tmp), "%s%ctmpmsg%d",
2600                    get_rc_dir(), G_DIR_SEPARATOR, (gint)compose);
2601
2602         if (prefs_common.linewrap_at_send)
2603                 compose_wrap_line_all(compose);
2604
2605         if (compose_write_to_file(compose, tmp, FALSE) < 0) {
2606                 lock = FALSE;
2607                 return -1;
2608         }
2609
2610         if (!compose->to_list && !compose->newsgroup_list) {
2611                 g_warning(_("can't get recipient list."));
2612                 unlink(tmp);
2613                 lock = FALSE;
2614                 return -1;
2615         }
2616
2617         if (compose->to_list) {
2618                 PrefsAccount *ac;
2619
2620 #if 0 /* NEW COMPOSE GUI */
2621                 if (compose->account->protocol != A_NNTP)
2622                         ac = compose->account;
2623                 else if (compose->orig_account->protocol != A_NNTP)
2624                         ac = compose->orig_account;
2625                 else if (cur_account && cur_account->protocol != A_NNTP)
2626                         ac = cur_account;
2627                 else {
2628                         ac = compose_current_mail_account();
2629                         if (!ac) {
2630                                 unlink(tmp);
2631                                 lock = FALSE;
2632                                 return -1;
2633                         }
2634                 }
2635 #endif
2636                 ac = compose->account;
2637
2638                 ok = send_message(tmp, ac, compose->to_list);
2639                 statusbar_pop_all();
2640         }
2641
2642         if (ok == 0 && compose->newsgroup_list) {
2643                 Folder *folder;
2644
2645                 if (compose->account->protocol == A_NNTP)
2646                         folder = FOLDER(compose->account->folder);
2647                 else
2648                         folder = FOLDER(compose->orig_account->folder);
2649
2650                 ok = news_post(folder, tmp);
2651                 if (ok < 0) {
2652                         alertpanel_error(_("Error occurred while posting the message to %s ."),
2653                                          compose->account->nntp_server);
2654                         unlink(tmp);
2655                         lock = FALSE;
2656                         return -1;
2657                 }
2658         }
2659
2660         /* queue message if failed to send */
2661         if (ok < 0) {
2662                 if (prefs_common.queue_msg) {
2663                         AlertValue val;
2664
2665                         val = alertpanel
2666                                 (_("Queueing"),
2667                                  _("Error occurred while sending the message.\n"
2668                                    "Put this message into queue folder?"),
2669                                  _("OK"), _("Cancel"), NULL);
2670                         if (G_ALERTDEFAULT == val) {
2671                                 ok = compose_queue(compose, tmp);
2672                                 if (ok < 0)
2673                                         alertpanel_error(_("Can't queue the message."));
2674                         }
2675                 } else
2676                         alertpanel_error(_("Error occurred while sending the message."));
2677         } else {
2678                 if (compose->mode == COMPOSE_REEDIT) {
2679                         compose_remove_reedit_target(compose);
2680                         if (compose->targetinfo)
2681                                 folderview_update_item
2682                                         (compose->targetinfo->folder, TRUE);
2683                 }
2684         }
2685
2686         /* save message to outbox */
2687         if (ok == 0 && prefs_common.savemsg) {
2688                 if (compose_save_to_outbox(compose, tmp) < 0)
2689                         alertpanel_error
2690                                 (_("Can't save the message to outbox."));
2691         }
2692
2693         unlink(tmp);
2694         lock = FALSE;
2695         return ok;
2696 }
2697 #endif
2698
2699 static gboolean compose_use_attach(Compose *compose) {
2700     return(gtk_clist_get_row_data(GTK_CLIST(compose->attach_clist), 0) != NULL);
2701 }
2702
2703 static gint compose_bounce_write_headers_from_headerlist(Compose *compose, 
2704                                                          FILE *fp)
2705 {
2706         gchar buf[BUFFSIZE];
2707         gchar *str;
2708         gboolean first_address;
2709         GSList *list;
2710         ComposeHeaderEntry *headerentry;
2711         gchar *headerentryname;
2712         gchar *header_w_colon;
2713         gchar *cc_hdr;
2714         gchar *to_hdr;
2715
2716         debug_print(_("Writing bounce header\n"));
2717
2718         header_w_colon = g_strconcat("To:", NULL);
2719         to_hdr = (prefs_common.trans_hdr ? gettext(header_w_colon) : header_w_colon);
2720         header_w_colon = g_strconcat("Cc:", NULL);
2721         cc_hdr = (prefs_common.trans_hdr ? gettext(header_w_colon) : header_w_colon);
2722         
2723         first_address = TRUE;
2724         for(list = compose->header_list; list; list = list->next) {
2725                 headerentry = ((ComposeHeaderEntry *)list->data);
2726                 headerentryname = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry));
2727
2728                 if(g_strcasecmp(headerentryname, cc_hdr) == 0 
2729                    || g_strcasecmp(headerentryname, to_hdr) == 0) {
2730                         str = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
2731                         Xstrdup_a(str, str, return -1);
2732                         g_strstrip(str);
2733                         if(str[0] != '\0') {
2734                                 compose_convert_header
2735                                         (buf, sizeof(buf), str,
2736                                         strlen("Resent-To") + 2);
2737                                 if(first_address) {
2738                                         fprintf(fp, "Resent-To: ");
2739                                         first_address = FALSE;
2740                                 } else {
2741                                         fprintf(fp, ",");
2742                                 }
2743                                 fprintf(fp, "%s", buf);
2744                         }
2745                 }
2746         }
2747         /* if(!first_address) { */
2748         fprintf(fp, "\n");
2749         /* } */
2750
2751         return(0);
2752 }
2753
2754 static gint compose_bounce_write_headers(Compose *compose, FILE *fp)
2755 {
2756         gchar buf[BUFFSIZE];
2757         gchar *str;
2758         /* struct utsname utsbuf; */
2759
2760         g_return_val_if_fail(fp != NULL, -1);
2761         g_return_val_if_fail(compose->account != NULL, -1);
2762         g_return_val_if_fail(compose->account->address != NULL, -1);
2763
2764         /* Date */
2765         get_rfc822_date(buf, sizeof(buf));
2766         fprintf(fp, "Resent-Date: %s\n", buf);
2767
2768         /* From */
2769         if (compose->account->name && *compose->account->name) {
2770                 compose_convert_header
2771                         (buf, sizeof(buf), compose->account->name,
2772                          strlen("From: "));
2773                 fprintf(fp, "Resent-From: %s <%s>\n",
2774                         buf, compose->account->address);
2775         } else
2776                 fprintf(fp, "Resent-From: %s\n", compose->account->address);
2777
2778         /* To */
2779         compose_bounce_write_headers_from_headerlist(compose, fp);
2780
2781         /* separator between header and body */
2782         fputs("\n", fp);
2783
2784         return 0;
2785 }
2786
2787 static gint compose_bounce_write_to_file(Compose *compose, const gchar *file)
2788 {
2789         FILE *fp;
2790         FILE *fdest;
2791         size_t len;
2792         gchar buf[BUFFSIZE];
2793
2794         if ((fp = fopen(compose->bounce_filename, "r")) == NULL) {
2795                 FILE_OP_ERROR(file, "fopen");
2796                 return -1;
2797         }
2798
2799         if ((fdest = fopen(file, "w")) == NULL) {
2800                 FILE_OP_ERROR(file, "fopen");
2801                 fclose(fp);
2802                 return -1;
2803         }
2804
2805         /* chmod for security */
2806         if (change_file_mode_rw(fdest, file) < 0) {
2807                 FILE_OP_ERROR(file, "chmod");
2808                 g_warning(_("can't change file mode\n"));
2809         }
2810
2811         while (procheader_get_unfolded_line(buf, sizeof(buf), fp)) {
2812                 /* should filter returnpath, delivered-to */
2813                 if ((g_strncasecmp(buf, "Return-Path:",
2814                                    strlen("Return-Path:")) == 0)
2815                     || (g_strncasecmp(buf, "Delivered-To:",
2816                                       strlen("Delivered-To:")) == 0))
2817                         continue;
2818
2819                 if (fputs(buf, fdest) == -1)
2820                         goto error;
2821
2822                 if (g_strncasecmp(buf, "From:", strlen("From:")) == 0) {
2823                         fputs(" (by way of ", fdest);
2824                         if (compose->account->name
2825                             && *compose->account->name) {
2826                                 compose_convert_header
2827                                         (buf, sizeof(buf),
2828                                          compose->account->name,
2829                                          strlen("From: "));
2830                                 fprintf(fdest, "%s <%s>",
2831                                         buf, compose->account->address);
2832                         } else
2833                                 fprintf(fdest, "%s",
2834                                         compose->account->address);
2835                         fputs(")", fdest);
2836                 }
2837
2838                 if (fputs("\n", fdest) == -1)
2839                         goto error;
2840         }
2841
2842         compose_bounce_write_headers(compose, fdest);
2843
2844         while ((len = fread(buf, sizeof(gchar), BUFFSIZE, fp)) > 0) {
2845                 if (fwrite(buf, sizeof(gchar), len, fdest) == -1)
2846                         goto error;
2847         }
2848
2849         fclose(fdest);
2850         fclose(fp);
2851
2852         return 0;
2853  error:
2854         fclose(fdest);
2855         fclose(fp);
2856
2857         return -1;
2858 }
2859
2860
2861 #ifdef USE_GPGME
2862 /*
2863  * interfaces to rfc2015 to keep out the prefs stuff there.
2864  * returns 0 on success and -1 on error. */
2865 static int compose_create_signers_list (Compose *compose, GSList **pkey_list)
2866 {
2867         const char *keyid = NULL;
2868         GSList *key_list;
2869
2870         switch (compose->account->sign_key) {
2871         case SIGN_KEY_DEFAULT:
2872                 *pkey_list = NULL;
2873                 return 0;               /* nothing to do */
2874
2875         case SIGN_KEY_BY_FROM:
2876                 keyid = compose->account->address;
2877                 break;
2878
2879         case SIGN_KEY_CUSTOM:
2880                 keyid = compose->account->sign_key_id;
2881                 break;
2882
2883         default:
2884                 g_assert_not_reached ();
2885         }
2886
2887         key_list = rfc2015_create_signers_list(keyid);
2888
2889         if (!key_list) {
2890             alertpanel_error("Could not find any key associated with currently "
2891                                 "selected keyid `%s'!", keyid);
2892             return -1;
2893         }
2894         
2895         *pkey_list = key_list;
2896         return 0;
2897 }
2898 #endif /* USE_GPGME */
2899
2900 static gint compose_write_to_file(Compose *compose, const gchar *file,
2901                                   gboolean is_draft)
2902 {
2903         FILE *fp;
2904         size_t len;
2905         gchar *chars;
2906         gchar *buf;
2907         const gchar *out_codeset;
2908         EncodingType encoding;
2909
2910         if ((fp = fopen(file, "w")) == NULL) {
2911                 FILE_OP_ERROR(file, "fopen");
2912                 return -1;
2913         }
2914
2915         /* chmod for security */
2916         if (change_file_mode_rw(fp, file) < 0) {
2917                 FILE_OP_ERROR(file, "chmod");
2918                 g_warning(_("can't change file mode\n"));
2919         }
2920
2921         /* get all composed text */
2922         chars = gtk_editable_get_chars(GTK_EDITABLE(compose->text), 0, -1);
2923         len = strlen(chars);
2924         if (is_ascii_str(chars)) {
2925                 buf = g_strdup(chars);
2926                 out_codeset = CS_US_ASCII;
2927                 encoding = ENC_7BIT;
2928         } else {
2929                 const gchar *src_codeset;
2930
2931                 out_codeset = conv_get_outgoing_charset_str();
2932                 if (!strcasecmp(out_codeset, CS_US_ASCII))
2933                         out_codeset = CS_ISO_8859_1;
2934                 encoding = procmime_get_encoding_for_charset(out_codeset);
2935
2936                 src_codeset = conv_get_current_charset_str();
2937                 /* if current encoding is US-ASCII, set it the same as
2938                    outgoing one to prevent code conversion failure */
2939                 if (!strcasecmp(src_codeset, CS_US_ASCII))
2940                         src_codeset = out_codeset;
2941
2942                 debug_print("src encoding = %s, out encoding = %s, transfer encoding = %s\n",
2943                             src_codeset, out_codeset, procmime_get_encoding_str(encoding));
2944
2945                 buf = conv_codeset_strdup(chars, src_codeset, out_codeset);
2946                 if (!buf) {
2947                         g_free(chars);
2948                         fclose(fp);
2949                         unlink(file);
2950                         alertpanel_error(_("Can't convert the codeset of the message."));
2951                         return -1;
2952                 }
2953         }
2954         g_free(chars);
2955
2956         /* write headers */
2957         if (compose_write_headers
2958                 (compose, fp, out_codeset, encoding, is_draft) < 0) {
2959                 g_warning(_("can't write headers\n"));
2960                 fclose(fp);
2961                 /* unlink(file); */
2962                 g_free(buf);
2963                 return -1;
2964         }
2965
2966         if (compose_use_attach(compose)) {
2967 #if USE_GPGME
2968             /* This prolog message is ignored by mime software and
2969              * because it would make our signing/encryption task
2970              * tougher, we don't emit it in that case */
2971             if (!compose->use_signing && !compose->use_encryption)
2972 #endif
2973                 fputs("This is a multi-part message in MIME format.\n", fp);
2974
2975                 fprintf(fp, "\n--%s\n", compose->boundary);
2976                 fprintf(fp, "Content-Type: text/plain; charset=%s\n",
2977                         out_codeset);
2978                 fprintf(fp, "Content-Transfer-Encoding: %s\n",
2979                         procmime_get_encoding_str(encoding));
2980                 fputc('\n', fp);
2981         }
2982
2983         /* write body */
2984         len = strlen(buf);
2985         if (encoding == ENC_BASE64) {
2986                 gchar outbuf[B64_BUFFSIZE];
2987                 gint i, l;
2988
2989                 for (i = 0; i < len; i += B64_LINE_SIZE) {
2990                         l = MIN(B64_LINE_SIZE, len - i);
2991                         to64frombits(outbuf, buf + i, l);
2992                         fputs(outbuf, fp);
2993                         fputc('\n', fp);
2994                 }
2995         } else if (fwrite(buf, sizeof(gchar), len, fp) != len) {
2996                 FILE_OP_ERROR(file, "fwrite");
2997                 fclose(fp);
2998                 unlink(file);
2999                 g_free(buf);
3000                 return -1;
3001         }
3002         g_free(buf);
3003
3004         if (compose_use_attach(compose))
3005                 compose_write_attach(compose, fp);
3006
3007         if (fclose(fp) == EOF) {
3008                 FILE_OP_ERROR(file, "fclose");
3009                 unlink(file);
3010                 return -1;
3011         }
3012
3013 #if USE_GPGME
3014         if (compose->use_signing) {
3015                 GSList *key_list;
3016                 
3017                 if (compose_create_signers_list(compose, &key_list) == -1 ||
3018                         rfc2015_sign(file, key_list) < 0) {
3019                     
3020                         unlink(file);
3021                         return -1;
3022                 }
3023         }
3024         if (compose->use_encryption) {
3025                 if (rfc2015_encrypt(file, compose->to_list, compose->account->ascii_armored) < 0) {
3026                         unlink(file);
3027                         return -1;
3028                 }
3029         }
3030 #endif /* USE_GPGME */
3031
3032         return 0;
3033 }
3034
3035 static gint compose_write_body_to_file(Compose *compose, const gchar *file)
3036 {
3037         FILE *fp;
3038         size_t len;
3039         gchar *chars;
3040
3041         if ((fp = fopen(file, "w")) == NULL) {
3042                 FILE_OP_ERROR(file, "fopen");
3043                 return -1;
3044         }
3045
3046         /* chmod for security */
3047         if (change_file_mode_rw(fp, file) < 0) {
3048                 FILE_OP_ERROR(file, "chmod");
3049                 g_warning(_("can't change file mode\n"));
3050         }
3051
3052         chars = gtk_editable_get_chars(GTK_EDITABLE(compose->text), 0, -1);
3053
3054         /* write body */
3055         len = strlen(chars);
3056         if (fwrite(chars, sizeof(gchar), len, fp) != len) {
3057                 FILE_OP_ERROR(file, "fwrite");
3058                 g_free(chars);
3059                 fclose(fp);
3060                 unlink(file);
3061                 return -1;
3062         }
3063
3064         g_free(chars);
3065
3066         if (fclose(fp) == EOF) {
3067                 FILE_OP_ERROR(file, "fclose");
3068                 unlink(file);
3069                 return -1;
3070         }
3071         return 0;
3072 }
3073
3074 static gint compose_save_to_outbox(Compose *compose, const gchar *file)
3075 {
3076         FolderItem *outbox;
3077         gchar *path;
3078         gint num;
3079         FILE *fp;
3080
3081         debug_print(_("saving sent message...\n"));
3082
3083         outbox = folder_get_default_outbox();
3084         path = folder_item_get_path(outbox);
3085         if (!is_dir_exist(path))
3086                 make_dir_hier(path);
3087
3088         folder_item_scan(outbox);
3089         if ((num = folder_item_add_msg(outbox, file, FALSE)) < 0) {
3090                 g_free(path);
3091                 g_warning(_("can't save message\n"));
3092                 return -1;
3093         }
3094
3095         if ((fp = procmsg_open_mark_file(path, TRUE)) == NULL)
3096                 g_warning(_("can't open mark file\n"));
3097         else {
3098                 MsgInfo newmsginfo;
3099
3100                 newmsginfo.msgnum = num;
3101                 newmsginfo.flags.perm_flags = 0;
3102                 newmsginfo.flags.tmp_flags = 0;
3103                 procmsg_write_flags(&newmsginfo, fp);
3104                 fclose(fp);
3105         }
3106         g_free(path);
3107
3108         return 0;
3109 }
3110
3111 static gint compose_remove_reedit_target(Compose *compose)
3112 {
3113         FolderItem *item;
3114         MsgInfo *msginfo = compose->targetinfo;
3115
3116         g_return_val_if_fail(compose->mode == COMPOSE_REEDIT, -1);
3117         if (!msginfo) return -1;
3118
3119         item = msginfo->folder;
3120         g_return_val_if_fail(item != NULL, -1);
3121
3122         folder_item_scan(item);
3123         if (procmsg_msg_exist(msginfo) &&
3124             (item->stype == F_DRAFT || item->stype == F_QUEUE)) {
3125                 if (folder_item_remove_msg(item, msginfo->msgnum) < 0) {
3126                         g_warning(_("can't remove the old message\n"));
3127                         return -1;
3128                 }
3129         }
3130
3131         return 0;
3132 }
3133
3134
3135 static gint compose_queue(Compose *compose, gint *msgnum, FolderItem **item)
3136 {
3137         FolderItem *queue;
3138         gchar *tmp, *tmp2, *queue_path;
3139         FILE *fp, *src_fp;
3140         GSList *cur;
3141         gchar buf[BUFFSIZE];
3142         gint num;
3143         static gboolean lock = FALSE;
3144         PrefsAccount *mailac = NULL, *newsac = NULL;
3145         
3146         debug_print(_("queueing message...\n"));
3147         g_return_val_if_fail(compose->account != NULL, -1);
3148         g_return_val_if_fail(compose->orig_account != NULL, -1);
3149
3150         lock = TRUE;
3151         
3152         if(!compose_check_for_valid_recipient(compose)) {
3153                 alertpanel_error(_("Recipient is not specified."));
3154                 lock = FALSE;
3155                 return -1;
3156         }
3157                                                                         
3158         if (!compose->to_list && !compose->newsgroup_list) {
3159                 g_warning(_("can't get recipient list."));
3160                 lock = FALSE;
3161                 return -1;
3162         }
3163
3164         if(compose->to_list) {
3165                 if (compose->account->protocol != A_NNTP)
3166                         mailac = compose->account;
3167                 else if (compose->orig_account->protocol != A_NNTP)
3168                         mailac = compose->orig_account;
3169                 else if (cur_account && cur_account->protocol != A_NNTP)
3170                         mailac = cur_account;
3171                 else if (!(mailac = compose_current_mail_account())) {
3172                         lock = FALSE;
3173                         alertpanel_error(_("No account for sending mails available!"));
3174                         return -1;
3175                 }
3176         }
3177
3178         if(compose->newsgroup_list) {
3179                 if (compose->account->protocol == A_NNTP)
3180                         newsac = compose->account;
3181                 else if(!(newsac = compose->orig_account) || (newsac->protocol != A_NNTP)) {
3182                         lock = FALSE;
3183                         alertpanel_error(_("No account for posting news available!"));
3184                         return -1;
3185                 }                       
3186         }
3187
3188         if (prefs_common.linewrap_at_send)
3189                 compose_wrap_line_all(compose);
3190                         
3191         /* write to temporary file */
3192         tmp2 = g_strdup_printf("%s%ctmp%d", g_get_tmp_dir(),
3193                                       G_DIR_SEPARATOR, (gint)compose);
3194
3195         if (compose->bounce_filename != NULL) {
3196                 if (compose_bounce_write_to_file(compose, tmp2) < 0) {
3197                         unlink(tmp2);
3198                         lock = FALSE;
3199                         return -1;
3200                 }
3201         }
3202         else {
3203                 if (compose_write_to_file(compose, tmp2, FALSE) < 0) {
3204                         unlink(tmp2);
3205                         lock = FALSE;
3206                         return -1;
3207                 }
3208         }
3209
3210         /* add queue header */
3211         tmp = g_strdup_printf("%s%cqueue.%d", g_get_tmp_dir(),
3212                                       G_DIR_SEPARATOR, (gint)compose);
3213         if ((fp = fopen(tmp, "w")) == NULL) {
3214                 FILE_OP_ERROR(tmp, "fopen");
3215                 g_free(tmp);
3216                 return -1;
3217         }
3218         if ((src_fp = fopen(tmp2, "r")) == NULL) {
3219                 FILE_OP_ERROR(tmp2, "fopen");
3220                 fclose(fp);
3221                 unlink(tmp);
3222                 g_free(tmp);
3223                 unlink(tmp2);
3224                 g_free(tmp2);
3225                 return -1;
3226         }
3227         if (change_file_mode_rw(fp, tmp) < 0) {
3228                 FILE_OP_ERROR(tmp, "chmod");
3229                 g_warning(_("can't change file mode\n"));
3230         }
3231
3232         /* queueing variables */
3233         fprintf(fp, "AF:\n");
3234         fprintf(fp, "NF:0\n");
3235         fprintf(fp, "PS:10\n");
3236         fprintf(fp, "SRH:1\n");
3237         fprintf(fp, "SFN:\n");
3238         fprintf(fp, "DSR:\n");
3239         if (compose->msgid)
3240                 fprintf(fp, "MID:<%s>\n", compose->msgid);
3241         else
3242                 fprintf(fp, "MID:\n");
3243         fprintf(fp, "CFG:\n");
3244         fprintf(fp, "PT:0\n");
3245         fprintf(fp, "S:%s\n", compose->account->address);
3246         fprintf(fp, "RQ:\n");
3247         if (mailac)
3248                 fprintf(fp, "SSV:%s\n", mailac->smtp_server);
3249         else
3250                 fprintf(fp, "SSV:\n");
3251         if (newsac)
3252                 fprintf(fp, "NSV:%s\n", newsac->nntp_server);
3253         else
3254                 fprintf(fp, "NSV:\n");
3255         fprintf(fp, "SSH:\n");
3256         /* write recepient list */
3257         fprintf(fp, "R:");
3258         if(compose->to_list) {
3259                 fprintf(fp, "<%s>", (gchar *)compose->to_list->data);
3260                 for (cur = compose->to_list->next; cur != NULL; cur = cur->next)
3261                         fprintf(fp, ",<%s>", (gchar *)cur->data);
3262         }
3263         fprintf(fp, "\n");
3264         /* write newsgroup list */
3265         fprintf(fp, "NG:");
3266         if(compose->newsgroup_list) {
3267                 fprintf(fp, "%s", (gchar *)compose->newsgroup_list->data);
3268                 for (cur = compose->newsgroup_list->next; cur != NULL; cur = cur->next)
3269                         fprintf(fp, ",%s", (gchar *)cur->data);
3270         }
3271         fprintf(fp, "\n");
3272         /* Sylpheed account IDs */
3273         if(mailac) {
3274                 fprintf(fp, "MAID:%d\n", mailac->account_id);
3275         }
3276         if(newsac) {
3277                 fprintf(fp, "NAID:%d\n", newsac->account_id);
3278         }
3279         /* Save copy folder */
3280         if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn))) {
3281                 gchar *str;
3282                 
3283                 str = gtk_editable_get_chars(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
3284                 fprintf(fp, "SCF:%s\n", str);
3285                 g_free(str);
3286         }
3287         fprintf(fp, "\n");
3288
3289         while (fgets(buf, sizeof(buf), src_fp) != NULL) {
3290                 if (fputs(buf, fp) == EOF) {
3291                         FILE_OP_ERROR(tmp, "fputs");
3292                         fclose(fp);
3293                         fclose(src_fp);
3294                         unlink(tmp);
3295                         g_free(tmp);
3296                         unlink(tmp2);
3297                         g_free(tmp2);
3298                         return -1;
3299                 }
3300         }
3301         fclose(src_fp);
3302         if (fclose(fp) == EOF) {
3303                 FILE_OP_ERROR(tmp, "fclose");
3304                 unlink(tmp);
3305                 g_free(tmp);
3306                 unlink(tmp2);
3307                 g_free(tmp2);
3308                 return -1;
3309         }
3310                                                 
3311         /* queue message */
3312         queue = folder_get_default_queue();
3313
3314         folder_item_scan(queue);
3315         queue_path = folder_item_get_path(queue);
3316         if (!is_dir_exist(queue_path))
3317                 make_dir_hier(queue_path);
3318         if ((num = folder_item_add_msg(queue, tmp, TRUE)) < 0) {
3319                 g_warning(_("can't queue the message\n"));
3320                 unlink(tmp);
3321                 g_free(tmp);
3322                 g_free(queue_path);
3323                 return -1;
3324         }
3325         unlink(tmp);
3326         g_free(tmp);
3327         unlink(tmp2);
3328         g_free(tmp2);
3329
3330         if (compose->mode == COMPOSE_REEDIT) {
3331                 compose_remove_reedit_target(compose);
3332                 if (compose->targetinfo &&
3333                     compose->targetinfo->folder != queue)
3334                         folderview_update_item
3335                                 (compose->targetinfo->folder, TRUE);
3336         }
3337
3338         if ((fp = procmsg_open_mark_file(queue_path, TRUE)) == NULL)
3339                 g_warning(_("can't open mark file\n"));
3340         else {
3341                 MsgInfo newmsginfo;
3342
3343                 newmsginfo.msgnum = num;
3344                 newmsginfo.flags.perm_flags = 0;
3345                 newmsginfo.flags.tmp_flags = 0;
3346                 procmsg_write_flags(&newmsginfo, fp);
3347                 fclose(fp);
3348         }
3349         g_free(queue_path);
3350
3351         folder_item_scan(queue);
3352         folderview_update_item(queue, TRUE);
3353
3354         if((msgnum != NULL) && (item != NULL)) {
3355                 *msgnum = num;
3356                 *item = queue;
3357         }
3358
3359         return 0;
3360 }
3361
3362 static void compose_write_attach(Compose *compose, FILE *fp)
3363 {
3364         AttachInfo *ainfo;
3365         GtkCList *clist = GTK_CLIST(compose->attach_clist);
3366         gint row;
3367         FILE *attach_fp;
3368         gchar filename[BUFFSIZE];
3369         gint len;
3370
3371         for (row = 0; (ainfo = gtk_clist_get_row_data(clist, row)) != NULL;
3372              row++) {
3373                 if ((attach_fp = fopen(ainfo->file, "r")) == NULL) {
3374                         g_warning(_("Can't open file %s\n"), ainfo->file);
3375                         continue;
3376                 }
3377
3378                 fprintf(fp, "\n--%s\n", compose->boundary);
3379
3380                 if (!strcmp2(ainfo->content_type, "message/rfc822")) {
3381                         fprintf(fp, "Content-Type: %s\n", ainfo->content_type);
3382                         fprintf(fp, "Content-Disposition: inline\n");
3383                 } else {
3384                         conv_encode_header(filename, sizeof(filename),
3385                                            ainfo->name, 12);
3386                         fprintf(fp, "Content-Type: %s;\n"
3387                                     " name=\"%s\"\n",
3388                                 ainfo->content_type, filename);
3389                         fprintf(fp, "Content-Disposition: attachment;\n"
3390                                     " filename=\"%s\"\n", filename);
3391                 }
3392
3393                 fprintf(fp, "Content-Transfer-Encoding: %s\n\n",
3394                         procmime_get_encoding_str(ainfo->encoding));
3395
3396                 if (ainfo->encoding == ENC_7BIT) {
3397                         gchar buf[BUFFSIZE];
3398
3399                         while (fgets(buf, sizeof(buf), attach_fp) != NULL) {
3400                                 strcrchomp(buf);
3401                                 fputs(buf, fp);
3402                         }
3403                 } else {
3404                         gchar inbuf[B64_LINE_SIZE], outbuf[B64_BUFFSIZE];
3405
3406                         while ((len = fread(inbuf, sizeof(gchar),
3407                                             B64_LINE_SIZE, attach_fp))
3408                                == B64_LINE_SIZE) {
3409                                 to64frombits(outbuf, inbuf, B64_LINE_SIZE);
3410                                 fputs(outbuf, fp);
3411                                 fputc('\n', fp);
3412                         }
3413                         if (len > 0 && feof(attach_fp)) {
3414                                 to64frombits(outbuf, inbuf, len);
3415                                 fputs(outbuf, fp);
3416                                 fputc('\n', fp);
3417                         }
3418                 }
3419
3420                 fclose(attach_fp);
3421         }
3422
3423         fprintf(fp, "\n--%s--\n", compose->boundary);
3424 }
3425
3426 #define IS_IN_CUSTOM_HEADER(header) \
3427         (compose->account->add_customhdr && \
3428          custom_header_find(compose->account->customhdr_list, header) != NULL)
3429
3430 static gint compose_write_headers_from_headerlist(Compose *compose, 
3431                                                   FILE *fp, 
3432                                                   gchar *header)
3433 {
3434         gchar buf[BUFFSIZE];
3435         gchar *str, *header_w_colon, *trans_hdr;
3436         gboolean first_address;
3437         GSList *list;
3438         ComposeHeaderEntry *headerentry;
3439         gchar * headerentryname;
3440
3441         if (IS_IN_CUSTOM_HEADER(header)) {
3442                 return 0;
3443         }
3444
3445         debug_print(_("Writing %s-header\n"), header);
3446
3447         header_w_colon = g_strconcat(header, ":", NULL);
3448         trans_hdr = (prefs_common.trans_hdr ? gettext(header_w_colon) : header_w_colon);
3449
3450         first_address = TRUE;
3451         for(list = compose->header_list; list; list = list->next) {
3452                 headerentry = ((ComposeHeaderEntry *)list->data);
3453                 headerentryname = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry));
3454
3455                 if(!g_strcasecmp(trans_hdr, headerentryname)) {
3456                         str = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
3457                         Xstrdup_a(str, str, return -1);
3458                         g_strstrip(str);
3459                         if(str[0] != '\0') {
3460                                 compose_convert_header
3461                                         (buf, sizeof(buf), str,
3462                                         strlen(header) + 2);
3463                                 if(first_address) {
3464                                         fprintf(fp, "%s: ", header);
3465                                         first_address = FALSE;
3466                                 } else {
3467                                         fprintf(fp, ",");
3468                                 }
3469                                 fprintf(fp, "%s", buf);
3470                         }
3471                 }
3472         }
3473         if(!first_address) {
3474                 fprintf(fp, "\n");
3475         }
3476
3477         g_free(header_w_colon);
3478
3479         return(0);
3480 }
3481
3482 static gint compose_write_headers(Compose *compose, FILE *fp,
3483                                   const gchar *charset, EncodingType encoding,
3484                                   gboolean is_draft)
3485 {
3486         gchar buf[BUFFSIZE];
3487         gchar *str;
3488         /* struct utsname utsbuf; */
3489
3490         g_return_val_if_fail(fp != NULL, -1);
3491         g_return_val_if_fail(charset != NULL, -1);
3492         g_return_val_if_fail(compose->account != NULL, -1);
3493         g_return_val_if_fail(compose->account->address != NULL, -1);
3494
3495         /* Date */
3496         if (compose->account->add_date) {
3497                 get_rfc822_date(buf, sizeof(buf));
3498                 fprintf(fp, "Date: %s\n", buf);
3499         }
3500
3501         /* From */
3502         if (!IS_IN_CUSTOM_HEADER("From")) {
3503                 if (compose->account->name && *compose->account->name) {
3504                         compose_convert_header
3505                                 (buf, sizeof(buf), compose->account->name,
3506                                  strlen("From: "));
3507                         fprintf(fp, "From: %s <%s>\n",
3508                                 buf, compose->account->address);
3509                 } else
3510                         fprintf(fp, "From: %s\n", compose->account->address);
3511         }
3512         
3513         /* To */
3514         compose_write_headers_from_headerlist(compose, fp, "To");
3515 #if 0 /* NEW COMPOSE GUI */
3516         if (compose->use_to) {
3517                 str = gtk_entry_get_text(GTK_ENTRY(compose->to_entry));
3518                 if (*str != '\0') {
3519                         Xstrdup_a(str, str, return -1);
3520                         g_strstrip(str);
3521                         if (*str != '\0') {
3522                                 compose->to_list = address_list_append
3523                                         (compose->to_list, str);
3524                                 if (!IS_IN_CUSTOM_HEADER("To")) {
3525                                         compose_convert_header
3526                                                 (buf, sizeof(buf), str,
3527                                                  strlen("To: "));
3528                                         fprintf(fp, "To: %s\n", buf);
3529                                 }
3530                         }
3531                 }
3532         }
3533 #endif
3534
3535         /* Newsgroups */
3536         compose_write_headers_from_headerlist(compose, fp, "Newsgroups");
3537 #if 0 /* NEW COMPOSE GUI */
3538         str = gtk_entry_get_text(GTK_ENTRY(compose->newsgroups_entry));
3539         if (*str != '\0') {
3540                 Xstrdup_a(str, str, return -1);
3541                 g_strstrip(str);
3542                 remove_space(str);
3543                 if (*str != '\0') {
3544                         compose->newsgroup_list =
3545                                 newsgroup_list_append(compose->newsgroup_list,
3546                                                       str);
3547                         if (!IS_IN_CUSTOM_HEADER("Newsgroups")) {
3548                                 compose_convert_header(buf, sizeof(buf), str,
3549                                                        strlen("Newsgroups: "));
3550                                 fprintf(fp, "Newsgroups: %s\n", buf);
3551                         }
3552                 }
3553         }
3554 #endif
3555         /* Cc */
3556         compose_write_headers_from_headerlist(compose, fp, "Cc");
3557 #if 0 /* NEW COMPOSE GUI */
3558         if (compose->use_cc) {
3559                 str = gtk_entry_get_text(GTK_ENTRY(compose->cc_entry));
3560                 if (*str != '\0') {
3561                         Xstrdup_a(str, str, return -1);
3562                         g_strstrip(str);
3563                         if (*str != '\0') {
3564                                 compose->to_list = address_list_append
3565                                         (compose->to_list, str);
3566                                 if (!IS_IN_CUSTOM_HEADER("Cc")) {
3567                                         compose_convert_header
3568                                                 (buf, sizeof(buf), str,
3569                                                  strlen("Cc: "));
3570                                         fprintf(fp, "Cc: %s\n", buf);
3571                                 }
3572                         }
3573                 }
3574         }
3575 #endif
3576         /* Bcc */
3577         compose_write_headers_from_headerlist(compose, fp, "Bcc");
3578 #if 0 /* NEW COMPOSE GUI */
3579         if (compose->use_bcc) {
3580                 str = gtk_entry_get_text(GTK_ENTRY(compose->bcc_entry));
3581                 if (*str != '\0') {
3582                         Xstrdup_a(str, str, return -1);
3583                         g_strstrip(str);
3584                         if (*str != '\0') {
3585                                 compose->to_list = address_list_append
3586                                         (compose->to_list, str);
3587                                 compose_convert_header(buf, sizeof(buf), str,
3588                                                        strlen("Bcc: "));
3589                                 fprintf(fp, "Bcc: %s\n", buf);
3590                         }
3591                 }
3592         }
3593 #endif
3594
3595         /* Subject */
3596         str = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
3597         if (*str != '\0' && !IS_IN_CUSTOM_HEADER("Subject")) {
3598                 Xstrdup_a(str, str, return -1);
3599                 g_strstrip(str);
3600                 if (*str != '\0') {
3601                         compose_convert_header(buf, sizeof(buf), str,
3602                                                strlen("Subject: "));
3603                         fprintf(fp, "Subject: %s\n", buf);
3604                 }
3605         }
3606
3607         /* Message-ID */
3608         if (compose->account->gen_msgid) {
3609                 compose_generate_msgid(compose, buf, sizeof(buf));
3610                 fprintf(fp, "Message-Id: <%s>\n", buf);
3611                 compose->msgid = g_strdup(buf);
3612         }
3613
3614         /* In-Reply-To */
3615         if (compose->inreplyto && compose->to_list)
3616                 fprintf(fp, "In-Reply-To: <%s>\n", compose->inreplyto);
3617
3618         /* References */
3619         if (compose->references)
3620                 fprintf(fp, "References: %s\n", compose->references);
3621
3622         /* Followup-To */
3623         compose_write_headers_from_headerlist(compose, fp, "Followup-To");
3624 #if 0 /* NEW COMPOSE GUI */
3625         if (compose->use_followupto && !IS_IN_CUSTOM_HEADER("Followup-To")) {
3626                 str = gtk_entry_get_text(GTK_ENTRY(compose->followup_entry));
3627                 if (*str != '\0') {
3628                         Xstrdup_a(str, str, return -1);
3629                         g_strstrip(str);
3630                         remove_space(str);
3631                         if (*str != '\0') {
3632                                 compose_convert_header(buf, sizeof(buf), str,
3633                                                        strlen("Followup-To: "));
3634                                 fprintf(fp, "Followup-To: %s\n", buf);
3635                         }
3636                 }
3637         }
3638 #endif
3639         /* Reply-To */
3640         compose_write_headers_from_headerlist(compose, fp, "Reply-To");
3641 #if 0 /* NEW COMPOSE GUI */
3642         if (compose->use_replyto && !IS_IN_CUSTOM_HEADER("Reply-To")) {
3643                 str = gtk_entry_get_text(GTK_ENTRY(compose->reply_entry));
3644                 if (*str != '\0') {
3645                         Xstrdup_a(str, str, return -1);
3646                         g_strstrip(str);
3647                         if (*str != '\0') {
3648                                 compose_convert_header(buf, sizeof(buf), str,
3649                                                        strlen("Reply-To: "));
3650                                 fprintf(fp, "Reply-To: %s\n", buf);
3651                         }
3652                 }
3653         }
3654 #endif
3655         /* Organization */
3656         if (compose->account->organization &&
3657             !IS_IN_CUSTOM_HEADER("Organization")) {
3658                 compose_convert_header(buf, sizeof(buf),
3659                                        compose->account->organization,
3660                                        strlen("Organization: "));
3661                 fprintf(fp, "Organization: %s\n", buf);
3662         }
3663
3664         /* Program version and system info */
3665         /* uname(&utsbuf); */
3666         if (g_slist_length(compose->to_list) && !IS_IN_CUSTOM_HEADER("X-Mailer")) {
3667                 fprintf(fp, "X-Mailer: %s (GTK+ %d.%d.%d; %s)\n",
3668                         prog_version,
3669                         gtk_major_version, gtk_minor_version, gtk_micro_version,
3670                         HOST_ALIAS);
3671                         /* utsbuf.sysname, utsbuf.release, utsbuf.machine); */
3672         }
3673         if (g_slist_length(compose->newsgroup_list) && !IS_IN_CUSTOM_HEADER("X-Newsreader")) {
3674                 fprintf(fp, "X-Newsreader: %s (GTK+ %d.%d.%d; %s)\n",
3675                         prog_version,
3676                         gtk_major_version, gtk_minor_version, gtk_micro_version,
3677                         HOST_ALIAS);
3678                         /* utsbuf.sysname, utsbuf.release, utsbuf.machine); */
3679         }
3680
3681         /* custom headers */
3682         if (compose->account->add_customhdr) {
3683                 GSList *cur;
3684
3685                 for (cur = compose->account->customhdr_list; cur != NULL;
3686                      cur = cur->next) {
3687                         CustomHeader *chdr = (CustomHeader *)cur->data;
3688
3689                         if (strcasecmp(chdr->name, "Date")         != 0 &&
3690                             strcasecmp(chdr->name, "From")         != 0 &&
3691                             strcasecmp(chdr->name, "To")           != 0 &&
3692                          /* strcasecmp(chdr->name, "Sender")       != 0 && */
3693                             strcasecmp(chdr->name, "Message-Id")   != 0 &&
3694                             strcasecmp(chdr->name, "In-Reply-To")  != 0 &&
3695                             strcasecmp(chdr->name, "References")   != 0 &&
3696                             strcasecmp(chdr->name, "Mime-Version") != 0 &&
3697                             strcasecmp(chdr->name, "Content-Type") != 0 &&
3698                             strcasecmp(chdr->name, "Content-Transfer-Encoding")
3699                             != 0) {
3700                                 compose_convert_header
3701                                         (buf, sizeof(buf),
3702                                          chdr->value ? chdr->value : "",
3703                                          strlen(chdr->name) + 2);
3704                                 fprintf(fp, "%s: %s\n", chdr->name, buf);
3705                         }
3706                 }
3707         }
3708
3709         /* MIME */
3710         fprintf(fp, "Mime-Version: 1.0\n");
3711         if (compose_use_attach(compose)) {
3712                 get_rfc822_date(buf, sizeof(buf));
3713                 subst_char(buf, ' ', '_');
3714                 subst_char(buf, ',', '_');
3715                 compose->boundary = g_strdup_printf("Multipart_%s_%08x",
3716                                                     buf, (guint)compose);
3717                 fprintf(fp,
3718                         "Content-Type: multipart/mixed;\n"
3719                         " boundary=\"%s\"\n", compose->boundary);
3720         } else {
3721                 fprintf(fp, "Content-Type: text/plain; charset=%s\n", charset);
3722                 fprintf(fp, "Content-Transfer-Encoding: %s\n",
3723                         procmime_get_encoding_str(encoding));
3724         }
3725
3726         /* Request Return Receipt */
3727         if (!IS_IN_CUSTOM_HEADER("Disposition-Notification-To")) {
3728                 if (compose->return_receipt) {
3729                         if (compose->account->name
3730                             && *compose->account->name) {
3731                                 compose_convert_header(buf, sizeof(buf), compose->account->name, strlen("Disposition-Notification-To: "));
3732                                 fprintf(fp, "Disposition-Notification-To: %s <%s>\n", buf, compose->account->address);
3733                         } else
3734                                 fprintf(fp, "Disposition-Notification-To: %s\n", compose->account->address);
3735                 }
3736         }
3737
3738         /* separator between header and body */
3739         fputs("\n", fp);
3740
3741         return 0;
3742 }
3743
3744 #undef IS_IN_CUSTOM_HEADER
3745
3746 static void compose_convert_header(gchar *dest, gint len, gchar *src,
3747                                    gint header_len)
3748 {
3749         g_return_if_fail(src != NULL);
3750         g_return_if_fail(dest != NULL);
3751
3752         if (len < 1) return;
3753
3754         remove_return(src);
3755
3756         if (is_ascii_str(src)) {
3757                 strncpy2(dest, src, len);
3758                 dest[len - 1] = '\0';
3759                 return;
3760         } else
3761                 conv_encode_header(dest, len, src, header_len);
3762 }
3763
3764 static void compose_generate_msgid(Compose *compose, gchar *buf, gint len)
3765 {
3766         struct tm *lt;
3767         time_t t;
3768         gchar *addr;
3769
3770         t = time(NULL);
3771         lt = localtime(&t);
3772
3773         if (compose->account && compose->account->address &&
3774             *compose->account->address) {
3775                 if (strchr(compose->account->address, '@'))
3776                         addr = g_strdup(compose->account->address);
3777                 else
3778                         addr = g_strconcat(compose->account->address, "@",
3779                                            get_domain_name(), NULL);
3780         } else
3781                 addr = g_strconcat(g_get_user_name(), "@", get_domain_name(),
3782                                    NULL);
3783
3784         g_snprintf(buf, len, "%04d%02d%02d%02d%02d%02d.%08x.%s",
3785                    lt->tm_year + 1900, lt->tm_mon + 1,
3786                    lt->tm_mday, lt->tm_hour,
3787                    lt->tm_min, lt->tm_sec,
3788                    (guint)random(), addr);
3789
3790         debug_print(_("generated Message-ID: %s\n"), buf);
3791
3792         g_free(addr);
3793 }
3794
3795 static void compose_add_entry_field(GtkWidget *table, GtkWidget **hbox,
3796                                     GtkWidget **entry, gint *count,
3797                                     const gchar *label_str,
3798                                     gboolean is_addr_entry)
3799 {
3800         GtkWidget *label;
3801
3802         if (GTK_TABLE(table)->nrows < (*count) + 1)
3803                 gtk_table_resize(GTK_TABLE(table), (*count) + 1, 2);
3804
3805         *hbox = gtk_hbox_new(FALSE, 0);
3806         label = gtk_label_new
3807                 (prefs_common.trans_hdr ? gettext(label_str) : label_str);
3808         gtk_box_pack_end(GTK_BOX(*hbox), label, FALSE, FALSE, 0);
3809         gtk_table_attach(GTK_TABLE(table), *hbox, 0, 1, *count, (*count) + 1,
3810                          GTK_FILL, 0, 2, 0);
3811         *entry = gtk_entry_new_with_max_length(MAX_ENTRY_LENGTH);
3812         gtk_table_attach
3813                 (GTK_TABLE(table), *entry, 1, 2, *count, (*count) + 1, GTK_FILL | GTK_EXPAND, GTK_SHRINK, 0, 0);
3814 #if 0 /* NEW COMPOSE GUI */
3815         if (GTK_TABLE(table)->nrows > (*count) + 1)
3816                 gtk_table_set_row_spacing(GTK_TABLE(table), *count, 4);
3817 #endif
3818
3819         if (is_addr_entry)
3820                 address_completion_register_entry(GTK_ENTRY(*entry));
3821
3822         (*count)++;
3823 }
3824
3825 static void compose_create_header_entry(Compose *compose) 
3826 {
3827         gchar *headers[] = {"To:", "Cc:", "Bcc:", "Newsgroups:", "Reply-To:", "Followup-To:", NULL};
3828
3829         GtkWidget *combo;
3830         GtkWidget *entry;
3831         GList *combo_list = NULL;
3832         gchar **string, *header;
3833         ComposeHeaderEntry *headerentry;
3834
3835         headerentry = g_new0(ComposeHeaderEntry, 1);
3836
3837         /* Combo box */
3838         combo = gtk_combo_new();
3839         string = headers; 
3840         while(*string != NULL) {
3841             combo_list = g_list_append(combo_list, (prefs_common.trans_hdr ? gettext(*string) : *string));
3842             string++;
3843         }
3844         gtk_combo_set_popdown_strings(GTK_COMBO(combo), combo_list);
3845         g_list_free(combo_list);
3846         gtk_editable_set_editable(GTK_EDITABLE(GTK_COMBO(combo)->entry), FALSE);
3847         gtk_widget_show(combo);
3848         gtk_table_attach(GTK_TABLE(compose->header_table), combo, 0, 1, compose->header_nextrow, compose->header_nextrow+1, GTK_SHRINK, GTK_FILL, 0, 0);
3849         if(compose->header_last) {      
3850                 header = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry));
3851         } else {
3852                 switch(compose->account->protocol) {
3853                         case A_NNTP:
3854                                 header = prefs_common.trans_hdr ? _("Newsgroups:") : "Newsgroups:";
3855                                 break;
3856                         default:
3857                                 header = prefs_common.trans_hdr ? _("To:") : "To:";
3858                                 break;
3859                 }                                                                   
3860         }
3861         gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(combo)->entry), header);
3862
3863         /* Entry field */
3864         entry = gtk_entry_new(); 
3865         gtk_widget_show(entry);
3866         gtk_table_attach(GTK_TABLE(compose->header_table), entry, 1, 2, compose->header_nextrow, compose->header_nextrow+1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
3867
3868         gtk_signal_connect(GTK_OBJECT(entry), "key-press-event", GTK_SIGNAL_FUNC(compose_headerentry_key_press_event_cb), headerentry);
3869         gtk_signal_connect(GTK_OBJECT(entry), "changed", GTK_SIGNAL_FUNC(compose_headerentry_changed_cb), headerentry);
3870         gtk_signal_connect(GTK_OBJECT(entry), "activate", GTK_SIGNAL_FUNC(compose_ctl_enter_send_shortcut_cb), compose);
3871
3872         address_completion_register_entry(GTK_ENTRY(entry));
3873
3874         headerentry->compose = compose;
3875         headerentry->combo = combo;
3876         headerentry->entry = entry;
3877         headerentry->headernum = compose->header_nextrow;
3878
3879         compose->header_nextrow++;
3880         compose->header_last = headerentry;
3881 }
3882
3883 static void compose_add_header_entry(Compose *compose, gchar *header, gchar *text) 
3884 {
3885         ComposeHeaderEntry *last_header;
3886         
3887         last_header = compose->header_last;
3888         
3889         gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(last_header->combo)->entry), header);
3890         gtk_entry_set_text(GTK_ENTRY(last_header->entry), text);
3891 }
3892
3893 static GtkWidget *compose_create_header(Compose *compose) 
3894 {
3895         GtkWidget *label;
3896         GtkWidget *hbox;
3897         GtkWidget *from_optmenu_hbox;
3898 #if 0 /* NEW COMPOSE GUI */
3899         GtkWidget *to_entry;
3900         GtkWidget *to_hbox;
3901         GtkWidget *newsgroups_entry;
3902         GtkWidget *newsgroups_hbox;
3903 #endif
3904         GtkWidget *header_scrolledwin;
3905         GtkWidget *header_table;
3906 #if 0 /* NEW COMPOSE GUI */
3907         GtkWidget *cc_entry;
3908         GtkWidget *cc_hbox;
3909         GtkWidget *bcc_entry;
3910         GtkWidget *bcc_hbox;
3911         GtkWidget *reply_entry;
3912         GtkWidget *reply_hbox;
3913         GtkWidget *followup_entry;
3914         GtkWidget *followup_hbox;
3915 #endif
3916
3917         gint count = 0;
3918
3919         /* header labels and entries */
3920         header_scrolledwin = gtk_scrolled_window_new(NULL, NULL);
3921         gtk_widget_show(header_scrolledwin);
3922         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(header_scrolledwin), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
3923
3924         header_table = gtk_table_new(2, 2, FALSE);
3925         gtk_widget_show(header_table);
3926         gtk_container_set_border_width(GTK_CONTAINER(header_table), 2);
3927         gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(header_scrolledwin), header_table);
3928         gtk_viewport_set_shadow_type(GTK_VIEWPORT(GTK_BIN(header_scrolledwin)->child), GTK_SHADOW_ETCHED_IN);
3929         count = 0;
3930
3931         /* option menu for selecting accounts */
3932         hbox = gtk_hbox_new(FALSE, 0);
3933         label = gtk_label_new(prefs_common.trans_hdr ? _("From:") : "From:");
3934         gtk_box_pack_end(GTK_BOX(hbox), label, FALSE, FALSE, 0);
3935         gtk_table_attach(GTK_TABLE(header_table), hbox, 0, 1, count, count + 1,
3936                          GTK_FILL, 0, 2, 0);
3937         from_optmenu_hbox = compose_account_option_menu_create(compose);
3938         gtk_table_attach(GTK_TABLE(header_table), from_optmenu_hbox,
3939                                   1, 2, count, count + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
3940 #if 0 /* NEW COMPOSE GUI */
3941         gtk_table_set_row_spacing(GTK_TABLE(table), 0, 4);
3942 #endif
3943         count++;
3944
3945         compose->header_table = header_table;
3946         compose->header_list = NULL;
3947         compose->header_nextrow = count;
3948
3949         compose_create_header_entry(compose);
3950
3951 #if 0 /* NEW COMPOSE GUI */
3952         compose_add_entry_field(table, &to_hbox, &to_entry, &count,
3953                                 "To:", TRUE); 
3954         gtk_table_set_row_spacing(GTK_TABLE(table), 0, 4);
3955         compose_add_entry_field(table, &newsgroups_hbox, &newsgroups_entry,
3956                                 &count, "Newsgroups:", FALSE);
3957         gtk_table_set_row_spacing(GTK_TABLE(table), 1, 4);
3958
3959         gtk_table_set_row_spacing(GTK_TABLE(table), 2, 4);
3960
3961         compose_add_entry_field(table, &cc_hbox, &cc_entry, &count,
3962                                 "Cc:", TRUE);
3963         gtk_table_set_row_spacing(GTK_TABLE(table), 3, 4);
3964         compose_add_entry_field(table, &bcc_hbox, &bcc_entry, &count,
3965                                 "Bcc:", TRUE);
3966         gtk_table_set_row_spacing(GTK_TABLE(table), 4, 4);
3967         compose_add_entry_field(table, &reply_hbox, &reply_entry, &count,
3968                                 "Reply-To:", TRUE);
3969         gtk_table_set_row_spacing(GTK_TABLE(table), 5, 4);
3970         compose_add_entry_field(table, &followup_hbox, &followup_entry, &count,
3971                                 "Followup-To:", FALSE);
3972         gtk_table_set_row_spacing(GTK_TABLE(table), 6, 4);
3973
3974         gtk_table_set_col_spacings(GTK_TABLE(table), 4);
3975
3976         gtk_signal_connect(GTK_OBJECT(to_entry), "activate",
3977                            GTK_SIGNAL_FUNC(to_activated), compose);
3978         gtk_signal_connect(GTK_OBJECT(newsgroups_entry), "activate",
3979                            GTK_SIGNAL_FUNC(newsgroups_activated), compose);
3980         gtk_signal_connect(GTK_OBJECT(subject_entry), "activate",
3981                            GTK_SIGNAL_FUNC(subject_activated), compose);
3982         gtk_signal_connect(GTK_OBJECT(cc_entry), "activate",
3983                            GTK_SIGNAL_FUNC(cc_activated), compose);
3984         gtk_signal_connect(GTK_OBJECT(bcc_entry), "activate",
3985                            GTK_SIGNAL_FUNC(bcc_activated), compose);
3986         gtk_signal_connect(GTK_OBJECT(reply_entry), "activate",
3987                            GTK_SIGNAL_FUNC(replyto_activated), compose);
3988         gtk_signal_connect(GTK_OBJECT(followup_entry), "activate",
3989                            GTK_SIGNAL_FUNC(followupto_activated), compose);
3990
3991         gtk_signal_connect(GTK_OBJECT(subject_entry), "grab_focus",
3992                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
3993         gtk_signal_connect(GTK_OBJECT(to_entry), "grab_focus",
3994                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
3995         gtk_signal_connect(GTK_OBJECT(newsgroups_entry), "grab_focus",
3996                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
3997         gtk_signal_connect(GTK_OBJECT(cc_entry), "grab_focus",
3998                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
3999         gtk_signal_connect(GTK_OBJECT(bcc_entry), "grab_focus",
4000                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4001         gtk_signal_connect(GTK_OBJECT(reply_entry), "grab_focus",
4002                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4003         gtk_signal_connect(GTK_OBJECT(followup_entry), "grab_focus",
4004                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4005 #endif
4006
4007         compose->table            = NULL;
4008 #if 0 /* NEW COMPOSE GUI */
4009         compose->table            = table;
4010         compose->to_hbox          = to_hbox;
4011         compose->to_entry         = to_entry;
4012         compose->newsgroups_hbox  = newsgroups_hbox;
4013         compose->newsgroups_entry = newsgroups_entry;
4014 #endif
4015 #if 0 /* NEW COMPOSE GUI */
4016         compose->cc_hbox          = cc_hbox;
4017         compose->cc_entry         = cc_entry;
4018         compose->bcc_hbox         = bcc_hbox;
4019         compose->bcc_entry        = bcc_entry;
4020         compose->reply_hbox       = reply_hbox;
4021         compose->reply_entry      = reply_entry;
4022         compose->followup_hbox    = followup_hbox;
4023         compose->followup_entry   = followup_entry;
4024 #endif
4025
4026         return header_scrolledwin ;
4027 }
4028
4029 GtkWidget *compose_create_attach(Compose *compose)
4030 {
4031         gchar *titles[] = {_("MIME type"), _("Size"), _("Name")};
4032         gint i;
4033
4034         GtkWidget *attach_scrwin;
4035         GtkWidget *attach_clist;
4036
4037         /* attachment list */
4038         attach_scrwin = gtk_scrolled_window_new(NULL, NULL);
4039         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(attach_scrwin),
4040                                        GTK_POLICY_AUTOMATIC,
4041                                        GTK_POLICY_ALWAYS);
4042         gtk_widget_set_usize(attach_scrwin, -1, 80);
4043
4044         attach_clist = gtk_clist_new_with_titles(N_ATTACH_COLS, titles);
4045         gtk_clist_set_column_justification(GTK_CLIST(attach_clist), COL_SIZE,
4046                                            GTK_JUSTIFY_RIGHT);
4047         gtk_clist_set_column_width(GTK_CLIST(attach_clist), COL_MIMETYPE, 240);
4048         gtk_clist_set_column_width(GTK_CLIST(attach_clist), COL_SIZE, 64);
4049         gtk_clist_set_selection_mode(GTK_CLIST(attach_clist),
4050                                      GTK_SELECTION_EXTENDED);
4051         for (i = 0; i < N_ATTACH_COLS; i++)
4052                 GTK_WIDGET_UNSET_FLAGS
4053                         (GTK_CLIST(attach_clist)->column[i].button,
4054                          GTK_CAN_FOCUS);
4055         gtk_container_add(GTK_CONTAINER(attach_scrwin), attach_clist);
4056
4057         gtk_signal_connect(GTK_OBJECT(attach_clist), "select_row",
4058                            GTK_SIGNAL_FUNC(attach_selected), compose);
4059         gtk_signal_connect(GTK_OBJECT(attach_clist), "button_press_event",
4060                            GTK_SIGNAL_FUNC(attach_button_pressed), compose);
4061         gtk_signal_connect(GTK_OBJECT(attach_clist), "key_press_event",
4062                            GTK_SIGNAL_FUNC(attach_key_pressed), compose);
4063
4064         /* drag and drop */
4065         gtk_drag_dest_set(attach_clist,
4066                           GTK_DEST_DEFAULT_ALL, compose_mime_types, 1,
4067                           GDK_ACTION_COPY);
4068         gtk_signal_connect(GTK_OBJECT(attach_clist), "drag_data_received",
4069                            GTK_SIGNAL_FUNC(compose_attach_drag_received_cb),
4070                            compose);
4071
4072         compose->attach_scrwin = attach_scrwin;
4073         compose->attach_clist  = attach_clist;
4074
4075         return attach_scrwin;
4076 }
4077
4078 static void compose_savemsg_checkbtn_cb(GtkWidget *widget, Compose *compose);
4079 static void compose_savemsg_select_cb(GtkWidget *widget, Compose *compose);
4080
4081 static GtkWidget *compose_create_others(Compose *compose)
4082 {
4083         GtkWidget *table;
4084         GtkWidget *savemsg_checkbtn;
4085         GtkWidget *savemsg_entry;
4086         GtkWidget *savemsg_select;
4087         
4088         guint rowcount = 0;
4089         gchar *folderidentifier;
4090
4091         /* Table for settings */
4092         table = gtk_table_new(3, 1, FALSE);
4093         gtk_widget_show(table);
4094         gtk_table_set_row_spacings(GTK_TABLE(table), VSPACING_NARROW);
4095         rowcount = 0;
4096
4097         /* Save Message to folder */
4098         savemsg_checkbtn = gtk_check_button_new_with_label(_("Save Message to "));
4099         gtk_widget_show(savemsg_checkbtn);
4100         gtk_table_attach(GTK_TABLE(table), savemsg_checkbtn, 0, 1, rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
4101         if(folder_get_default_outbox()) {
4102                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(savemsg_checkbtn), prefs_common.savemsg);
4103         }
4104         gtk_signal_connect(GTK_OBJECT(savemsg_checkbtn), "toggled",
4105                             GTK_SIGNAL_FUNC(compose_savemsg_checkbtn_cb), compose);
4106
4107         savemsg_entry = gtk_entry_new();
4108         gtk_widget_show(savemsg_entry);
4109         gtk_table_attach_defaults(GTK_TABLE(table), savemsg_entry, 1, 2, rowcount, rowcount + 1);
4110         gtk_editable_set_editable(GTK_EDITABLE(savemsg_entry), prefs_common.savemsg);
4111         if(folder_get_default_outbox()) {
4112                 folderidentifier = folder_item_get_identifier(folder_get_default_outbox());
4113                 gtk_entry_set_text(GTK_ENTRY(savemsg_entry), folderidentifier);
4114                 g_free(folderidentifier);
4115         }
4116
4117         savemsg_select = gtk_button_new_with_label (_("Select ..."));
4118         gtk_widget_show (savemsg_select);
4119         gtk_table_attach(GTK_TABLE(table), savemsg_select, 2, 3, rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
4120         gtk_signal_connect (GTK_OBJECT (savemsg_select), "clicked",
4121                             GTK_SIGNAL_FUNC (compose_savemsg_select_cb),
4122                             compose);
4123
4124         rowcount++;
4125
4126         compose->savemsg_checkbtn = savemsg_checkbtn;
4127         compose->savemsg_entry = savemsg_entry;
4128
4129         return table;   
4130 }
4131
4132 static void compose_savemsg_checkbtn_cb(GtkWidget *widget, Compose *compose) 
4133 {
4134         gtk_editable_set_editable(GTK_EDITABLE(compose->savemsg_entry),
4135                 gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn)));
4136 }
4137
4138 static void compose_savemsg_select_cb(GtkWidget *widget, Compose *compose)
4139 {
4140         FolderItem *dest;
4141         gchar * path;
4142
4143         dest = foldersel_folder_sel(NULL, NULL);
4144         if (!dest) return;
4145
4146         path = folder_item_get_identifier(dest);
4147
4148         gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), path);
4149         g_free(path);
4150 }
4151
4152 static Compose *compose_create(PrefsAccount *account, ComposeMode mode)
4153 {
4154         Compose   *compose;
4155         GtkWidget *window;
4156         GtkWidget *vbox;
4157         GtkWidget *menubar;
4158         GtkWidget *handlebox;
4159
4160         GtkWidget *notebook;
4161
4162         GtkWidget *vbox2;
4163
4164         GtkWidget *label;
4165         GtkWidget *subject_hbox;
4166         GtkWidget *subject_frame;
4167         GtkWidget *subject_entry;
4168         GtkWidget *subject;
4169         GtkWidget *paned;
4170
4171         GtkWidget *edit_vbox;
4172         GtkWidget *ruler_hbox;
4173         GtkWidget *ruler;
4174         GtkWidget *scrolledwin;
4175         GtkWidget *text;
4176
4177         GtkWidget *table;
4178
4179         UndoMain *undostruct;
4180
4181         guint n_menu_entries;
4182         GtkStyle  *style, *new_style;
4183         GdkColormap *cmap;
4184         GdkColor color[1];
4185         gboolean success[1];
4186         GdkFont   *font;
4187         GtkWidget *popupmenu;
4188         GtkWidget *menuitem;
4189         GtkItemFactory *popupfactory;
4190         GtkItemFactory *ifactory;
4191         GtkWidget *tmpl_menu;
4192         gint n_entries;
4193
4194 #if USE_PSPELL
4195         GtkPspell * gtkpspell = NULL;
4196 #endif
4197
4198         g_return_val_if_fail(account != NULL, NULL);
4199
4200         debug_print(_("Creating compose window...\n"));
4201         compose = g_new0(Compose, 1);
4202
4203         compose->account = account;
4204         compose->orig_account = account;
4205
4206         window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
4207         gtk_window_set_policy(GTK_WINDOW(window), TRUE, TRUE, FALSE);
4208         gtk_widget_set_usize(window, -1, prefs_common.compose_height);
4209         gtk_window_set_wmclass(GTK_WINDOW(window), "compose window", "Sylpheed");
4210         gtk_signal_connect(GTK_OBJECT(window), "delete_event",
4211                            GTK_SIGNAL_FUNC(compose_delete_cb), compose);
4212         gtk_signal_connect(GTK_OBJECT(window), "destroy",
4213                            GTK_SIGNAL_FUNC(compose_destroy_cb), compose);
4214         gtk_signal_connect(GTK_OBJECT(window), "focus_in_event",
4215                            GTK_SIGNAL_FUNC(manage_window_focus_in), NULL);
4216         gtk_signal_connect(GTK_OBJECT(window), "focus_out_event",
4217                            GTK_SIGNAL_FUNC(manage_window_focus_out), NULL);
4218         gtk_widget_realize(window);
4219
4220         gtkut_widget_set_composer_icon(window);
4221
4222         vbox = gtk_vbox_new(FALSE, 0);
4223         gtk_container_add(GTK_CONTAINER(window), vbox);
4224
4225         n_menu_entries = sizeof(compose_entries) / sizeof(compose_entries[0]);
4226         menubar = menubar_create(window, compose_entries,
4227                                  n_menu_entries, "<Compose>", compose);
4228         gtk_box_pack_start(GTK_BOX(vbox), menubar, FALSE, TRUE, 0);
4229
4230         handlebox = gtk_handle_box_new();
4231         gtk_box_pack_start(GTK_BOX(vbox), handlebox, FALSE, FALSE, 0);
4232
4233         compose_toolbar_create(compose, handlebox);
4234
4235         vbox2 = gtk_vbox_new(FALSE, 2);
4236         gtk_box_pack_start(GTK_BOX(vbox), vbox2, TRUE, TRUE, 0);
4237         gtk_container_set_border_width(GTK_CONTAINER(vbox2), BORDER_WIDTH);
4238         
4239         /* Notebook */
4240         notebook = gtk_notebook_new();
4241         gtk_widget_set_usize(notebook, -1, 130);
4242         gtk_widget_show(notebook);
4243
4244         /* header labels and entries */
4245         gtk_notebook_append_page(GTK_NOTEBOOK(notebook), compose_create_header(compose), gtk_label_new(_("Header")));
4246         /* attachment list */
4247         gtk_notebook_append_page(GTK_NOTEBOOK(notebook), compose_create_attach(compose), gtk_label_new(_("Attachments")));
4248         /* Others Tab */
4249         gtk_notebook_append_page(GTK_NOTEBOOK(notebook), compose_create_others(compose), gtk_label_new(_("Others")));
4250
4251         /* Subject */
4252         subject_hbox = gtk_hbox_new(FALSE, 0);
4253         gtk_widget_show(subject_hbox);
4254
4255         subject_frame = gtk_frame_new(NULL);
4256         gtk_frame_set_shadow_type(GTK_FRAME(subject_frame), GTK_SHADOW_OUT);
4257         gtk_box_pack_start(GTK_BOX(subject_hbox), subject_frame, TRUE, TRUE, BORDER_WIDTH+1);
4258         gtk_widget_show(subject_frame);
4259
4260         subject = gtk_hbox_new(FALSE, 0);
4261         gtk_container_set_border_width(GTK_CONTAINER(subject), BORDER_WIDTH);
4262         gtk_widget_show(subject);
4263
4264         label = gtk_label_new(_("Subject:"));
4265         gtk_box_pack_start(GTK_BOX(subject), label, FALSE, FALSE, 4);
4266         gtk_widget_show(label);
4267
4268         subject_entry = gtk_entry_new();
4269         gtk_box_pack_start(GTK_BOX(subject), subject_entry, TRUE, TRUE, 2);
4270         gtk_signal_connect(GTK_OBJECT(subject_entry), "activate", GTK_SIGNAL_FUNC(compose_ctl_enter_send_shortcut_cb), compose);
4271         gtk_widget_show(subject_entry);
4272         compose->subject_entry = subject_entry;
4273         gtk_container_add(GTK_CONTAINER(subject_frame), subject);
4274         
4275         edit_vbox = gtk_vbox_new(FALSE, 0);
4276 #if 0 /* NEW COMPOSE GUI */
4277         gtk_box_pack_start(GTK_BOX(vbox2), edit_vbox, TRUE, TRUE, 0);
4278 #endif
4279
4280         gtk_box_pack_start(GTK_BOX(edit_vbox), subject_hbox, FALSE, FALSE, 0);
4281
4282         /* ruler */
4283         ruler_hbox = gtk_hbox_new(FALSE, 0);
4284         gtk_box_pack_start(GTK_BOX(edit_vbox), ruler_hbox, FALSE, FALSE, 0);
4285
4286         ruler = gtk_shruler_new();
4287         gtk_ruler_set_range(GTK_RULER(ruler), 0.0, 100.0, 1.0, 100.0);
4288         gtk_box_pack_start(GTK_BOX(ruler_hbox), ruler, TRUE, TRUE,
4289                            BORDER_WIDTH + 1);
4290         gtk_widget_set_usize(ruler_hbox, 1, -1);
4291
4292         /* text widget */
4293         scrolledwin = gtk_scrolled_window_new(NULL, NULL);
4294         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin),
4295                                        GTK_POLICY_NEVER, GTK_POLICY_ALWAYS);
4296         gtk_box_pack_start(GTK_BOX(edit_vbox), scrolledwin, TRUE, TRUE, 0);
4297         gtk_widget_set_usize(scrolledwin, prefs_common.compose_width, -1);
4298
4299         text = gtk_stext_new(gtk_scrolled_window_get_hadjustment
4300                             (GTK_SCROLLED_WINDOW(scrolledwin)),
4301                             gtk_scrolled_window_get_vadjustment
4302                             (GTK_SCROLLED_WINDOW(scrolledwin)));
4303         GTK_STEXT(text)->default_tab_width = 8;
4304         gtk_stext_set_editable(GTK_STEXT(text), TRUE);
4305
4306         if (prefs_common.block_cursor) {
4307                 GTK_STEXT(text)->cursor_type = GTK_STEXT_CURSOR_BLOCK;
4308         }
4309         
4310         if (prefs_common.smart_wrapping) {      
4311                 gtk_stext_set_word_wrap(GTK_STEXT(text), TRUE);
4312                 gtk_stext_set_wrap_rmargin(GTK_STEXT(text), prefs_common.linewrap_len);
4313         }               
4314
4315         gtk_container_add(GTK_CONTAINER(scrolledwin), text);
4316
4317         gtk_signal_connect(GTK_OBJECT(text), "changed",
4318                            GTK_SIGNAL_FUNC(compose_changed_cb), compose);
4319         gtk_signal_connect(GTK_OBJECT(text), "grab_focus",
4320                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4321         gtk_signal_connect(GTK_OBJECT(text), "activate",
4322                            GTK_SIGNAL_FUNC(compose_ctl_enter_send_shortcut_cb), compose);
4323         gtk_signal_connect_after(GTK_OBJECT(text), "button_press_event",
4324                                  GTK_SIGNAL_FUNC(compose_button_press_cb),
4325                                  edit_vbox);
4326 #if 0
4327         gtk_signal_connect_after(GTK_OBJECT(text), "key_press_event",
4328                                  GTK_SIGNAL_FUNC(compose_key_press_cb),
4329                                  compose);
4330 #endif
4331         gtk_signal_connect_after(GTK_OBJECT(text), "size_allocate",
4332                                  GTK_SIGNAL_FUNC(compose_edit_size_alloc),
4333                                  ruler);
4334
4335         /* drag and drop */
4336         gtk_drag_dest_set(text, GTK_DEST_DEFAULT_ALL, compose_mime_types, 1,
4337                           GDK_ACTION_COPY);
4338         gtk_signal_connect(GTK_OBJECT(text), "drag_data_received",
4339                            GTK_SIGNAL_FUNC(compose_insert_drag_received_cb),
4340                            compose);
4341 #if USE_PSPELL
4342         if (prefs_common.enable_pspell) {
4343                 gtkpspell = gtkpspell_new_with_config(gtkpspellconfig,
4344                                                       prefs_common.pspell_path,
4345                                                       prefs_common.dictionary,
4346                                                       prefs_common.pspell_sugmode,
4347                                                       conv_get_current_charset_str());
4348                 if (gtkpspell == NULL)
4349                         prefs_common.enable_pspell = FALSE;
4350                 else
4351                         gtkpspell_attach(gtkpspell, GTK_STEXT(text));
4352         }
4353 #endif
4354         gtk_widget_show_all(vbox);
4355
4356         /* pane between attach clist and text */
4357         paned = gtk_vpaned_new();
4358         gtk_paned_set_gutter_size(GTK_PANED(paned), 12);
4359         gtk_paned_set_handle_size(GTK_PANED(paned), 12);
4360         gtk_container_add(GTK_CONTAINER(vbox2), paned);
4361         gtk_paned_add1(GTK_PANED(paned), notebook);
4362         gtk_paned_add2(GTK_PANED(paned), edit_vbox);
4363         gtk_widget_show_all(paned);
4364
4365         style = gtk_widget_get_style(text);
4366
4367         /* workaround for the slow down of GtkSText when using Pixmap theme */
4368         if (style->engine) {
4369                 GtkThemeEngine *engine;
4370
4371                 engine = style->engine;
4372                 style->engine = NULL;
4373                 new_style = gtk_style_copy(style);
4374                 style->engine = engine;
4375         } else
4376                 new_style = gtk_style_copy(style);
4377
4378         if (prefs_common.textfont) {
4379                 CharSet charset;
4380
4381                 charset = conv_get_current_charset();
4382                 if (MB_CUR_MAX == 1) {
4383                         gchar *fontstr, *p;
4384
4385                         Xstrdup_a(fontstr, prefs_common.textfont, );
4386                         if (fontstr && (p = strchr(fontstr, ',')) != NULL)
4387                                 *p = '\0';
4388                         font = gdk_font_load(fontstr);
4389                 } else
4390                         font = gdk_fontset_load(prefs_common.textfont);
4391                 if (font) {
4392                         gdk_font_unref(new_style->font);
4393                         new_style->font = font;
4394                 }
4395         }
4396
4397         gtk_widget_set_style(text, new_style);
4398
4399         color[0] = quote_color;
4400         cmap = gdk_window_get_colormap(window->window);
4401         gdk_colormap_alloc_colors(cmap, color, 1, FALSE, TRUE, success);
4402         if (success[0] == FALSE) {
4403                 g_warning("Compose: color allocation failed.\n");
4404                 style = gtk_widget_get_style(text);
4405                 quote_color = style->black;
4406         }
4407
4408         n_entries = sizeof(compose_popup_entries) /
4409                 sizeof(compose_popup_entries[0]);
4410         popupmenu = menu_create_items(compose_popup_entries, n_entries,
4411                                       "<Compose>", &popupfactory,
4412                                       compose);
4413
4414         ifactory = gtk_item_factory_from_widget(menubar);
4415         menu_set_sensitive(ifactory, "/Edit/Undo", FALSE);
4416         menu_set_sensitive(ifactory, "/Edit/Redo", FALSE);
4417
4418         tmpl_menu = gtk_item_factory_get_item(ifactory, "/Tool/Template");
4419 #if 0 /* NEW COMPOSE GUI */
4420         gtk_widget_hide(bcc_hbox);
4421         gtk_widget_hide(bcc_entry);
4422         gtk_widget_hide(reply_hbox);
4423         gtk_widget_hide(reply_entry);
4424         gtk_widget_hide(followup_hbox);
4425         gtk_widget_hide(followup_entry);
4426         gtk_widget_hide(ruler_hbox);
4427         gtk_table_set_row_spacing(GTK_TABLE(table), 4, 0);
4428         gtk_table_set_row_spacing(GTK_TABLE(table), 5, 0);
4429         gtk_table_set_row_spacing(GTK_TABLE(table), 6, 0);
4430
4431         if (account->protocol == A_NNTP) {
4432                 gtk_widget_hide(to_hbox);
4433                 gtk_widget_hide(to_entry);
4434                 gtk_widget_hide(cc_hbox);
4435                 gtk_widget_hide(cc_entry);
4436                 gtk_table_set_row_spacing(GTK_TABLE(table), 1, 0);
4437                 gtk_table_set_row_spacing(GTK_TABLE(table), 3, 0);
4438         } else {
4439                 gtk_widget_hide(newsgroups_hbox);
4440                 gtk_widget_hide(newsgroups_entry);
4441                 gtk_table_set_row_spacing(GTK_TABLE(table), 2, 0);
4442                 menu_set_sensitive(ifactory, "/View/Followup to", FALSE);
4443         }
4444 #endif
4445
4446         switch (prefs_common.toolbar_style) {
4447         case TOOLBAR_NONE:
4448                 gtk_widget_hide(handlebox);
4449                 break;
4450         case TOOLBAR_ICON:
4451                 gtk_toolbar_set_style(GTK_TOOLBAR(compose->toolbar),
4452                                       GTK_TOOLBAR_ICONS);
4453                 break;
4454         case TOOLBAR_TEXT:
4455                 gtk_toolbar_set_style(GTK_TOOLBAR(compose->toolbar),
4456                                       GTK_TOOLBAR_TEXT);
4457                 break;
4458         case TOOLBAR_BOTH:
4459                 gtk_toolbar_set_style(GTK_TOOLBAR(compose->toolbar),
4460                                       GTK_TOOLBAR_BOTH);
4461                 break;
4462         }
4463
4464         undostruct = undo_init(text);
4465         undo_set_change_state_func(undostruct, &compose_undo_state_changed,
4466                                    menubar);
4467
4468         gtk_widget_show(window);
4469
4470         address_completion_start(window);
4471
4472         compose->window        = window;
4473         compose->vbox          = vbox;
4474         compose->menubar       = menubar;
4475         compose->handlebox     = handlebox;
4476
4477         compose->vbox2         = vbox2;
4478
4479         compose->paned = paned;
4480
4481         compose->edit_vbox     = edit_vbox;
4482         compose->ruler_hbox    = ruler_hbox;
4483         compose->ruler         = ruler;
4484         compose->scrolledwin   = scrolledwin;
4485         compose->text          = text;
4486
4487         compose->focused_editable = NULL;
4488
4489         compose->popupmenu    = popupmenu;
4490         compose->popupfactory = popupfactory;
4491
4492         compose->tmpl_menu = tmpl_menu;
4493
4494         compose->mode = mode;
4495
4496         compose->targetinfo = NULL;
4497         compose->replyinfo  = NULL;
4498
4499         compose->replyto     = NULL;
4500         compose->mailinglist = NULL;
4501         compose->cc          = NULL;
4502         compose->bcc         = NULL;
4503         compose->followup_to = NULL;
4504         compose->inreplyto   = NULL;
4505         compose->references  = NULL;
4506         compose->msgid       = NULL;
4507         compose->boundary    = NULL;
4508
4509 #if USE_GPGME
4510         compose->use_signing    = FALSE;
4511         compose->use_encryption = FALSE;
4512 #endif /* USE_GPGME */
4513
4514         compose->modified = FALSE;
4515
4516         compose->return_receipt = FALSE;
4517
4518         compose->to_list        = NULL;
4519         compose->newsgroup_list = NULL;
4520
4521         compose->exteditor_file    = NULL;
4522         compose->exteditor_pid     = -1;
4523         compose->exteditor_readdes = -1;
4524         compose->exteditor_tag     = -1;
4525
4526         compose->bounce_filename = NULL;
4527         compose->undostruct = undostruct;
4528
4529         compose_set_title(compose);
4530
4531 #if 0 /* NEW COMPOSE GUI */
4532         compose->use_bcc        = FALSE;
4533         compose->use_replyto    = FALSE;
4534         compose->use_followupto = FALSE;
4535 #endif
4536
4537 #if USE_PSPELL
4538         compose->gtkpspell      = gtkpspell;
4539 #endif
4540
4541 #if 0 /* NEW COMPOSE GUI */
4542         if (account->protocol != A_NNTP) {
4543                 menuitem = gtk_item_factory_get_item(ifactory, "/View/To");
4544                 gtk_check_menu_item_set_active
4545                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
4546                 gtk_widget_set_sensitive(menuitem, FALSE);
4547                 menuitem = gtk_item_factory_get_item(ifactory, "/View/Cc");
4548                 gtk_check_menu_item_set_active
4549                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
4550                 gtk_widget_set_sensitive(menuitem, FALSE);
4551         }
4552 #endif
4553         if (account->set_autocc && account->auto_cc && mode != COMPOSE_REEDIT) {
4554                 compose_entry_append(compose, account->auto_cc, COMPOSE_CC);
4555 #if 0 /* NEW COMPOSE GUI */
4556                 compose->use_cc = TRUE;
4557                 gtk_entry_set_text(GTK_ENTRY(cc_entry), account->auto_cc);
4558                 menuitem = gtk_item_factory_get_item(ifactory, "/View/Cc");
4559                 gtk_check_menu_item_set_active
4560                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
4561 #endif
4562         }
4563         if (account->set_autobcc) {
4564                 compose_entry_append(compose, account->auto_bcc, COMPOSE_BCC);
4565 #if 0 /* NEW COMPOSE GUI */
4566                 menuitem = gtk_item_factory_get_item(ifactory, "/View/Bcc");
4567                 gtk_check_menu_item_set_active
4568                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
4569                 if (account->auto_bcc && mode != COMPOSE_REEDIT)
4570                         gtk_entry_set_text(GTK_ENTRY(bcc_entry),
4571                                            account->auto_bcc);
4572 #endif
4573         }
4574         if (account->set_autoreplyto && account->auto_replyto && mode != COMPOSE_REEDIT) {
4575                 compose_entry_append(compose, account->auto_replyto, COMPOSE_REPLYTO);
4576 #if 0 /* NEW COMPOSE GUI */
4577                 compose->use_replyto = TRUE;
4578                 menuitem = gtk_item_factory_get_item(ifactory,
4579                                                      "/View/Reply to");
4580                 gtk_check_menu_item_set_active
4581                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
4582                 gtk_entry_set_text(GTK_ENTRY(reply_entry),
4583                                    account->auto_replyto);
4584 #endif
4585         }
4586
4587         if (account->protocol != A_NNTP) {
4588                 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry), prefs_common.trans_hdr ? _("To:") : "To:");
4589         } else {
4590                 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry), prefs_common.trans_hdr ? _("Newsgroups:") : "Newsgroups:");
4591         }
4592
4593 #if 0 /* NEW COMPOSE GUI */
4594         menuitem = gtk_item_factory_get_item(ifactory, "/View/Ruler");
4595         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
4596                                        prefs_common.show_ruler);
4597 #endif                                 
4598
4599 #if USE_GPGME
4600         menuitem = gtk_item_factory_get_item(ifactory, "/Message/Sign");
4601         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
4602                                        account->default_sign);
4603         menuitem = gtk_item_factory_get_item(ifactory, "/Message/Encrypt");
4604         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
4605                                        account->default_encrypt);
4606 #endif /* USE_GPGME */
4607
4608         addressbook_set_target_compose(compose);
4609         compose_set_template_menu(compose);
4610
4611         compose_list = g_list_append(compose_list, compose);
4612
4613 #if 0 /* NEW COMPOSE GUI */
4614         compose->use_to         = FALSE;
4615         compose->use_cc         = FALSE;
4616         compose->use_attach     = TRUE;
4617 #endif
4618
4619 #if 0 /* NEW COMPOSE GUI */
4620         if (!compose->use_bcc) {
4621                 gtk_widget_hide(bcc_hbox);
4622                 gtk_widget_hide(bcc_entry);
4623                 gtk_table_set_row_spacing(GTK_TABLE(table), 4, 0);
4624         }
4625         if (!compose->use_replyto) {
4626                 gtk_widget_hide(reply_hbox);
4627                 gtk_widget_hide(reply_entry);
4628                 gtk_table_set_row_spacing(GTK_TABLE(table), 5, 0);
4629         }
4630         if (!compose->use_followupto) {
4631                 gtk_widget_hide(followup_hbox);
4632                 gtk_widget_hide(followup_entry);
4633                 gtk_table_set_row_spacing(GTK_TABLE(table), 6, 0);
4634         }
4635 #endif
4636         if (!prefs_common.show_ruler)
4637                 gtk_widget_hide(ruler_hbox);
4638
4639         select_account(compose, account);
4640
4641         return compose;
4642 }
4643
4644 static void compose_toolbar_create(Compose *compose, GtkWidget *container)
4645 {
4646         GtkWidget *toolbar;
4647         GtkWidget *icon_wid;
4648         GtkWidget *send_btn;
4649         GtkWidget *sendl_btn;
4650         GtkWidget *draft_btn;
4651         GtkWidget *insert_btn;
4652         GtkWidget *attach_btn;
4653         GtkWidget *sig_btn;
4654         GtkWidget *exteditor_btn;
4655         GtkWidget *linewrap_btn;
4656         GtkWidget *addrbook_btn;
4657
4658         toolbar = gtk_toolbar_new(GTK_ORIENTATION_HORIZONTAL,
4659                                   GTK_TOOLBAR_BOTH);
4660         gtk_container_add(GTK_CONTAINER(container), toolbar);
4661         gtk_container_set_border_width(GTK_CONTAINER(container), 2);
4662         gtk_toolbar_set_button_relief(GTK_TOOLBAR(toolbar), GTK_RELIEF_NONE);
4663         gtk_toolbar_set_space_style(GTK_TOOLBAR(toolbar),
4664                                     GTK_TOOLBAR_SPACE_LINE);
4665
4666         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_MAIL_SEND);
4667         send_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4668                                            _("Send"),
4669                                            _("Send message"),
4670                                            "Send",
4671                                            icon_wid, toolbar_send_cb, compose);
4672
4673         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_MAIL_SEND_QUEUE);
4674         sendl_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4675                                            _("Send later"),
4676                                            _("Put into queue folder and send later"),
4677                                            "Send later",
4678                                            icon_wid, toolbar_send_later_cb,
4679                                            compose);
4680
4681         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_MAIL);
4682         draft_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4683                                             _("Draft"),
4684                                             _("Save to draft folder"),
4685                                             "Draft",
4686                                             icon_wid, toolbar_draft_cb,
4687                                             compose);
4688
4689         gtk_toolbar_append_space(GTK_TOOLBAR(toolbar));
4690
4691         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_PASTE);
4692         insert_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4693                                              _("Insert"),
4694                                              _("Insert file"),
4695                                              "Insert",
4696                                              icon_wid, toolbar_insert_cb,
4697                                              compose);
4698
4699         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_MAIL_ATTACH);
4700         attach_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4701                                              _("Attach"),
4702                                              _("Attach file"),
4703                                              "Attach",
4704                                              icon_wid, toolbar_attach_cb,
4705                                              compose);
4706
4707         gtk_toolbar_append_space(GTK_TOOLBAR(toolbar));
4708
4709         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_MAIL);
4710         sig_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4711                                           _("Signature"),
4712                                           _("Insert signature"),
4713                                           "Signature",
4714                                           icon_wid, toolbar_sig_cb, compose);
4715
4716         gtk_toolbar_append_space(GTK_TOOLBAR(toolbar));
4717
4718         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_MAIL_COMPOSE);
4719         exteditor_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4720                                                 _("Editor"),
4721                                                 _("Edit with external editor"),
4722                                                 "Editor",
4723                                                 icon_wid,
4724                                                 toolbar_ext_editor_cb,
4725                                                 compose);
4726
4727         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_LINEWRAP);
4728         linewrap_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4729                                                _("Linewrap"),
4730                                                _("Wrap all long lines"),
4731                                                "Linewrap",
4732                                                icon_wid,
4733                                                toolbar_linewrap_cb,
4734                                                compose);
4735
4736         gtk_toolbar_append_space(GTK_TOOLBAR(toolbar));
4737
4738         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_ADDRESS_BOOK);
4739         addrbook_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4740                                                _("Address"),
4741                                                _("Address book"),
4742                                                "Address",
4743                                                icon_wid, toolbar_address_cb,
4744                                                compose);
4745
4746         compose->toolbar       = toolbar;
4747         compose->send_btn      = send_btn;
4748         compose->sendl_btn     = sendl_btn;
4749         compose->draft_btn     = draft_btn;
4750         compose->insert_btn    = insert_btn;
4751         compose->attach_btn    = attach_btn;
4752         compose->sig_btn       = sig_btn;
4753         compose->exteditor_btn = exteditor_btn;
4754         compose->linewrap_btn  = linewrap_btn;
4755         compose->addrbook_btn  = addrbook_btn;
4756
4757         gtk_widget_show_all(toolbar);
4758 }
4759
4760 static GtkWidget *compose_account_option_menu_create(Compose *compose)
4761 {
4762         GList *accounts;
4763         GtkWidget *hbox;
4764         GtkWidget *optmenu;
4765         GtkWidget *menu;
4766         gint num = 0, def_menu = 0;
4767
4768         accounts = account_get_list();
4769         g_return_val_if_fail(accounts != NULL, NULL);
4770
4771         hbox = gtk_hbox_new(FALSE, 0);
4772         optmenu = gtk_option_menu_new();
4773         gtk_box_pack_start(GTK_BOX(hbox), optmenu, FALSE, FALSE, 0);
4774         menu = gtk_menu_new();
4775
4776         for (; accounts != NULL; accounts = accounts->next, num++) {
4777                 PrefsAccount *ac = (PrefsAccount *)accounts->data;
4778                 GtkWidget *menuitem;
4779                 gchar *name;
4780
4781                 if (ac == compose->account) def_menu = num;
4782
4783                 name = g_strdup_printf("%s: %s <%s>",
4784                                        ac->account_name, ac->name, ac->address);
4785                 MENUITEM_ADD(menu, menuitem, name, ac);
4786                 g_free(name);
4787                 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
4788                                    GTK_SIGNAL_FUNC(account_activated),
4789                                    compose);
4790         }
4791
4792         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), menu);
4793         gtk_option_menu_set_history(GTK_OPTION_MENU(optmenu), def_menu);
4794
4795         return hbox;
4796 }
4797
4798 static void compose_set_template_menu(Compose *compose)
4799 {
4800         GSList *tmpl_list, *cur;
4801         GtkWidget *menu;
4802         GtkWidget *item;
4803
4804         tmpl_list = template_get_config();
4805
4806         menu = gtk_menu_new();
4807
4808         for (cur = tmpl_list; cur != NULL; cur = cur->next) {
4809                 Template *tmpl = (Template *)cur->data;
4810
4811                 item = gtk_menu_item_new_with_label(tmpl->name);
4812                 gtk_menu_append(GTK_MENU(menu), item);
4813                 gtk_signal_connect(GTK_OBJECT(item), "activate",
4814                                    GTK_SIGNAL_FUNC(compose_template_activate_cb),
4815                                    compose);
4816                 gtk_object_set_data(GTK_OBJECT(item), "template", tmpl);
4817                 gtk_widget_show(item);
4818         }
4819
4820         gtk_widget_show(menu);
4821         gtk_menu_item_set_submenu(GTK_MENU_ITEM(compose->tmpl_menu), menu);
4822 }
4823
4824 void compose_reflect_prefs_all(void)
4825 {
4826         GList *cur;
4827         Compose *compose;
4828
4829         for (cur = compose_list; cur != NULL; cur = cur->next) {
4830                 compose = (Compose *)cur->data;
4831                 compose_set_template_menu(compose);
4832         }
4833 }
4834
4835 static void compose_template_apply(Compose *compose, Template *tmpl)
4836 {
4837         gchar *qmark;
4838         gchar *parsed_str;
4839
4840         if (!tmpl || !tmpl->value) return;
4841
4842         gtk_stext_freeze(GTK_STEXT(compose->text));
4843
4844         if (tmpl->subject && *tmpl->subject != '\0')
4845                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry),
4846                                    tmpl->subject);
4847         if (tmpl->to && *tmpl->to != '\0')
4848                 compose_entry_append(compose, tmpl->to, COMPOSE_TO);
4849
4850         if (compose->replyinfo == NULL) {
4851                 MsgInfo dummyinfo;
4852
4853                 memset(&dummyinfo, 0, sizeof(MsgInfo));
4854                 parsed_str = compose_quote_fmt(compose, &dummyinfo,
4855                                                tmpl->value, NULL);
4856         } else {
4857                 if (prefs_common.quotemark && *prefs_common.quotemark)
4858                         qmark = prefs_common.quotemark;
4859                 else
4860                         qmark = "> ";
4861
4862                 parsed_str = compose_quote_fmt(compose, compose->replyinfo,
4863                                                tmpl->value, qmark);
4864         }
4865
4866         if (parsed_str && prefs_common.auto_sig)
4867                 compose_insert_sig(compose);
4868
4869         gtk_stext_thaw(GTK_STEXT(compose->text));
4870 }
4871
4872 static void compose_destroy(Compose *compose)
4873 {
4874         gint row;
4875         GtkCList *clist = GTK_CLIST(compose->attach_clist);
4876         AttachInfo *ainfo;
4877
4878         /* NOTE: address_completion_end() does nothing with the window
4879          * however this may change. */
4880         address_completion_end(compose->window);
4881
4882         slist_free_strings(compose->to_list);
4883         g_slist_free(compose->to_list);
4884         slist_free_strings(compose->newsgroup_list);
4885         g_slist_free(compose->newsgroup_list);
4886         slist_free_strings(compose->header_list);
4887         g_slist_free(compose->header_list);
4888
4889         procmsg_msginfo_free(compose->targetinfo);
4890         procmsg_msginfo_free(compose->replyinfo);
4891
4892         g_free(compose->replyto);
4893         g_free(compose->cc);
4894         g_free(compose->bcc);
4895         g_free(compose->newsgroups);
4896         g_free(compose->followup_to);
4897
4898         g_free(compose->inreplyto);
4899         g_free(compose->references);
4900         g_free(compose->msgid);
4901         g_free(compose->boundary);
4902
4903         if (compose->bounce_filename)
4904                 g_free(compose->bounce_filename);
4905
4906         g_free(compose->exteditor_file);
4907
4908         for (row = 0; (ainfo = gtk_clist_get_row_data(clist, row)) != NULL;
4909              row++)
4910                 compose_attach_info_free(ainfo);
4911
4912         if (addressbook_get_target_compose() == compose)
4913                 addressbook_set_target_compose(NULL);
4914
4915         prefs_common.compose_width = compose->scrolledwin->allocation.width;
4916         prefs_common.compose_height = compose->window->allocation.height;
4917
4918         gtk_widget_destroy(compose->paned);
4919
4920         g_free(compose);
4921
4922         compose_list = g_list_remove(compose_list, compose);
4923 }
4924
4925 static void compose_attach_info_free(AttachInfo *ainfo)
4926 {
4927         g_free(ainfo->file);
4928         g_free(ainfo->content_type);
4929         g_free(ainfo->name);
4930         g_free(ainfo);
4931 }
4932
4933 static void compose_attach_remove_selected(Compose *compose)
4934 {
4935         GtkCList *clist = GTK_CLIST(compose->attach_clist);
4936         AttachInfo *ainfo;
4937         gint row;
4938
4939         while (clist->selection != NULL) {
4940                 row = GPOINTER_TO_INT(clist->selection->data);
4941                 ainfo = gtk_clist_get_row_data(clist, row);
4942                 compose_attach_info_free(ainfo);
4943                 gtk_clist_remove(clist, row);
4944         }
4945 }
4946
4947 static struct _AttachProperty
4948 {
4949         GtkWidget *window;
4950         GtkWidget *mimetype_entry;
4951         GtkWidget *encoding_optmenu;
4952         GtkWidget *path_entry;
4953         GtkWidget *filename_entry;
4954         GtkWidget *ok_btn;
4955         GtkWidget *cancel_btn;
4956 } attach_prop;
4957
4958 static void compose_attach_property(Compose *compose)
4959 {
4960         GtkCList *clist = GTK_CLIST(compose->attach_clist);
4961         AttachInfo *ainfo;
4962         gint row;
4963         GtkOptionMenu *optmenu;
4964         static gboolean cancelled;
4965
4966         if (!clist->selection) return;
4967         row = GPOINTER_TO_INT(clist->selection->data);
4968
4969         ainfo = gtk_clist_get_row_data(clist, row);
4970         if (!ainfo) return;
4971
4972         if (!attach_prop.window)
4973                 compose_attach_property_create(&cancelled);
4974         gtk_widget_grab_focus(attach_prop.ok_btn);
4975         gtk_widget_show(attach_prop.window);
4976         manage_window_set_transient(GTK_WINDOW(attach_prop.window));
4977
4978         optmenu = GTK_OPTION_MENU(attach_prop.encoding_optmenu);
4979         if (ainfo->encoding == ENC_UNKNOWN)
4980                 gtk_option_menu_set_history(optmenu, ENC_BASE64);
4981         else
4982                 gtk_option_menu_set_history(optmenu, ainfo->encoding);
4983
4984         gtk_entry_set_text(GTK_ENTRY(attach_prop.mimetype_entry),
4985                            ainfo->content_type ? ainfo->content_type : "");
4986         gtk_entry_set_text(GTK_ENTRY(attach_prop.path_entry),
4987                            ainfo->file ? ainfo->file : "");
4988         gtk_entry_set_text(GTK_ENTRY(attach_prop.filename_entry),
4989                            ainfo->name ? ainfo->name : "");
4990
4991         for (;;) {
4992                 gchar *text;
4993                 gchar *cnttype = NULL;
4994                 gchar *file = NULL;
4995                 off_t size = 0;
4996                 GtkWidget *menu;
4997                 GtkWidget *menuitem;
4998
4999                 cancelled = FALSE;
5000                 gtk_main();
5001
5002                 if (cancelled == TRUE) {
5003                         gtk_widget_hide(attach_prop.window);
5004                         break;
5005                 }
5006
5007                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.mimetype_entry));
5008                 if (*text != '\0') {
5009                         gchar *p;
5010
5011                         text = g_strstrip(g_strdup(text));
5012                         if ((p = strchr(text, '/')) && !strchr(p + 1, '/')) {
5013                                 cnttype = g_strdup(text);
5014                                 g_free(text);
5015                         } else {
5016                                 alertpanel_error(_("Invalid MIME type."));
5017                                 g_free(text);
5018                                 continue;
5019                         }
5020                 }
5021
5022                 menu = gtk_option_menu_get_menu(optmenu);
5023                 menuitem = gtk_menu_get_active(GTK_MENU(menu));
5024                 ainfo->encoding = GPOINTER_TO_INT
5025                         (gtk_object_get_user_data(GTK_OBJECT(menuitem)));
5026
5027                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.path_entry));
5028                 if (*text != '\0') {
5029                         if (is_file_exist(text) &&
5030                             (size = get_file_size(text)) > 0)
5031                                 file = g_strdup(text);
5032                         else {
5033                                 alertpanel_error
5034                                         (_("File doesn't exist or is empty."));
5035                                 g_free(cnttype);
5036                                 continue;
5037                         }
5038                 }
5039
5040                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.filename_entry));
5041                 if (*text != '\0') {
5042                         g_free(ainfo->name);
5043                         ainfo->name = g_strdup(text);
5044                 }
5045
5046                 if (cnttype) {
5047                         g_free(ainfo->content_type);
5048                         ainfo->content_type = cnttype;
5049                 }
5050                 if (file) {
5051                         g_free(ainfo->file);
5052                         ainfo->file = file;
5053                 }
5054                 if (size)
5055                         ainfo->size = size;
5056
5057                 gtk_clist_set_text(clist, row, COL_MIMETYPE,
5058                                    ainfo->content_type);
5059                 gtk_clist_set_text(clist, row, COL_SIZE,
5060                                    to_human_readable(ainfo->size));
5061                 gtk_clist_set_text(clist, row, COL_NAME, ainfo->name);
5062
5063                 gtk_widget_hide(attach_prop.window);
5064                 break;
5065         }
5066 }
5067
5068 #define SET_LABEL_AND_ENTRY(str, entry, top) \
5069 { \
5070         label = gtk_label_new(str); \
5071         gtk_table_attach(GTK_TABLE(table), label, 0, 1, top, (top + 1), \
5072                          GTK_FILL, 0, 0, 0); \
5073         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); \
5074  \
5075         entry = gtk_entry_new(); \
5076         gtk_table_attach(GTK_TABLE(table), entry, 1, 2, top, (top + 1), \
5077                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0); \
5078 }
5079
5080 static void compose_attach_property_create(gboolean *cancelled)
5081 {
5082         GtkWidget *window;
5083         GtkWidget *vbox;
5084         GtkWidget *table;
5085         GtkWidget *label;
5086         GtkWidget *mimetype_entry;
5087         GtkWidget *hbox;
5088         GtkWidget *optmenu;
5089         GtkWidget *optmenu_menu;
5090         GtkWidget *menuitem;
5091         GtkWidget *path_entry;
5092         GtkWidget *filename_entry;
5093         GtkWidget *hbbox;
5094         GtkWidget *ok_btn;
5095         GtkWidget *cancel_btn;
5096         GList     *mime_type_list, *strlist;
5097
5098         debug_print("Creating attach_property window...\n");
5099
5100         window = gtk_window_new(GTK_WINDOW_DIALOG);
5101         gtk_widget_set_usize(window, 480, -1);
5102         gtk_container_set_border_width(GTK_CONTAINER(window), 8);
5103         gtk_window_set_title(GTK_WINDOW(window), _("Property"));
5104         gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
5105         gtk_window_set_modal(GTK_WINDOW(window), TRUE);
5106         gtk_signal_connect(GTK_OBJECT(window), "delete_event",
5107                            GTK_SIGNAL_FUNC(attach_property_delete_event),
5108                            cancelled);
5109         gtk_signal_connect(GTK_OBJECT(window), "key_press_event",
5110                            GTK_SIGNAL_FUNC(attach_property_key_pressed),
5111                            cancelled);
5112
5113         vbox = gtk_vbox_new(FALSE, 8);
5114         gtk_container_add(GTK_CONTAINER(window), vbox);
5115
5116         table = gtk_table_new(4, 2, FALSE);
5117         gtk_box_pack_start(GTK_BOX(vbox), table, FALSE, FALSE, 0);
5118         gtk_table_set_row_spacings(GTK_TABLE(table), 8);
5119         gtk_table_set_col_spacings(GTK_TABLE(table), 8);
5120
5121         label = gtk_label_new(_("MIME type")); 
5122         gtk_table_attach(GTK_TABLE(table), label, 0, 1, 0, (0 + 1), 
5123                          GTK_FILL, 0, 0, 0); 
5124         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); 
5125         mimetype_entry = gtk_combo_new(); 
5126         gtk_table_attach(GTK_TABLE(table), mimetype_entry, 1, 2, 0, (0 + 1), 
5127                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0);
5128                          
5129         /* stuff with list */
5130         mime_type_list = procmime_get_mime_type_list();
5131         strlist = NULL;
5132         for (; mime_type_list != NULL; mime_type_list = mime_type_list->next) {
5133                 MimeType *type = (MimeType *) mime_type_list->data;
5134                 strlist = g_list_append(strlist, 
5135                                 g_strdup_printf("%s/%s",
5136                                         type->type, type->sub_type));
5137         }
5138         
5139         gtk_combo_set_popdown_strings(GTK_COMBO(mimetype_entry), strlist);
5140
5141         for (mime_type_list = strlist; mime_type_list != NULL; 
5142                 mime_type_list = mime_type_list->next)
5143                 g_free(mime_type_list->data);
5144         g_list_free(strlist);
5145                          
5146         mimetype_entry = GTK_COMBO(mimetype_entry)->entry;                       
5147
5148         label = gtk_label_new(_("Encoding"));
5149         gtk_table_attach(GTK_TABLE(table), label, 0, 1, 1, 2,
5150                          GTK_FILL, 0, 0, 0);
5151         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5);
5152
5153         hbox = gtk_hbox_new(FALSE, 0);
5154         gtk_table_attach(GTK_TABLE(table), hbox, 1, 2, 1, 2,
5155                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0);
5156
5157         optmenu = gtk_option_menu_new();
5158         gtk_box_pack_start(GTK_BOX(hbox), optmenu, FALSE, FALSE, 0);
5159
5160         optmenu_menu = gtk_menu_new();
5161         MENUITEM_ADD(optmenu_menu, menuitem, "7bit", ENC_7BIT);
5162         gtk_widget_set_sensitive(menuitem, FALSE);
5163         MENUITEM_ADD(optmenu_menu, menuitem, "8bit", ENC_8BIT);
5164         gtk_widget_set_sensitive(menuitem, FALSE);
5165         MENUITEM_ADD(optmenu_menu, menuitem, "quoted-printable", ENC_QUOTED_PRINTABLE);
5166         gtk_widget_set_sensitive(menuitem, FALSE);
5167         MENUITEM_ADD(optmenu_menu, menuitem, "base64", ENC_BASE64);
5168
5169         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
5170
5171         SET_LABEL_AND_ENTRY(_("Path"),      path_entry,     2);
5172         SET_LABEL_AND_ENTRY(_("File name"), filename_entry, 3);
5173
5174         gtkut_button_set_create(&hbbox, &ok_btn, _("OK"),
5175                                 &cancel_btn, _("Cancel"), NULL, NULL);
5176         gtk_box_pack_end(GTK_BOX(vbox), hbbox, FALSE, FALSE, 0);
5177         gtk_widget_grab_default(ok_btn);
5178
5179         gtk_signal_connect(GTK_OBJECT(ok_btn), "clicked",
5180                            GTK_SIGNAL_FUNC(attach_property_ok),
5181                            cancelled);
5182         gtk_signal_connect(GTK_OBJECT(cancel_btn), "clicked",
5183                            GTK_SIGNAL_FUNC(attach_property_cancel),
5184                            cancelled);
5185
5186         gtk_widget_show_all(vbox);
5187
5188         attach_prop.window           = window;
5189         attach_prop.mimetype_entry   = mimetype_entry;
5190         attach_prop.encoding_optmenu = optmenu;
5191         attach_prop.path_entry       = path_entry;
5192         attach_prop.filename_entry   = filename_entry;
5193         attach_prop.ok_btn           = ok_btn;
5194         attach_prop.cancel_btn       = cancel_btn;
5195 }
5196
5197 #undef SET_LABEL_AND_ENTRY
5198
5199 static void attach_property_ok(GtkWidget *widget, gboolean *cancelled)
5200 {
5201         *cancelled = FALSE;
5202         gtk_main_quit();
5203 }
5204
5205 static void attach_property_cancel(GtkWidget *widget, gboolean *cancelled)
5206 {
5207         *cancelled = TRUE;
5208         gtk_main_quit();
5209 }
5210
5211 static gint attach_property_delete_event(GtkWidget *widget, GdkEventAny *event,
5212                                          gboolean *cancelled)
5213 {
5214         *cancelled = TRUE;
5215         gtk_main_quit();
5216
5217         return TRUE;
5218 }
5219
5220 static void attach_property_key_pressed(GtkWidget *widget, GdkEventKey *event,
5221                                         gboolean *cancelled)
5222 {
5223         if (event && event->keyval == GDK_Escape) {
5224                 *cancelled = TRUE;
5225                 gtk_main_quit();
5226         }
5227 }
5228
5229 static void compose_exec_ext_editor(Compose *compose)
5230 {
5231         gchar tmp[64];
5232         pid_t pid;
5233         gint pipe_fds[2];
5234
5235         g_snprintf(tmp, sizeof(tmp), "%s%ctmpmsg.%08x",
5236                    g_get_tmp_dir(), G_DIR_SEPARATOR, (gint)compose);
5237
5238         if (pipe(pipe_fds) < 0) {
5239                 perror("pipe");
5240                 return;
5241         }
5242
5243         if ((pid = fork()) < 0) {
5244                 perror("fork");
5245                 return;
5246         }
5247
5248         if (pid != 0) {
5249                 /* close the write side of the pipe */
5250                 close(pipe_fds[1]);
5251
5252                 compose->exteditor_file    = g_strdup(tmp);
5253                 compose->exteditor_pid     = pid;
5254                 compose->exteditor_readdes = pipe_fds[0];
5255
5256                 compose_set_ext_editor_sensitive(compose, FALSE);
5257
5258                 compose->exteditor_tag =
5259                         gdk_input_add(pipe_fds[0], GDK_INPUT_READ,
5260                                       compose_input_cb, compose);
5261         } else {        /* process-monitoring process */
5262                 pid_t pid_ed;
5263
5264                 if (setpgid(0, 0))
5265                         perror("setpgid");
5266
5267                 /* close the read side of the pipe */
5268                 close(pipe_fds[0]);
5269
5270                 if (compose_write_body_to_file(compose, tmp) < 0) {
5271                         fd_write(pipe_fds[1], "2\n", 2);
5272                         _exit(1);
5273                 }
5274
5275                 pid_ed = compose_exec_ext_editor_real(tmp);
5276                 if (pid_ed < 0) {
5277                         fd_write(pipe_fds[1], "1\n", 2);
5278                         _exit(1);
5279                 }
5280
5281                 /* wait until editor is terminated */
5282                 waitpid(pid_ed, NULL, 0);
5283
5284                 fd_write(pipe_fds[1], "0\n", 2);
5285
5286                 close(pipe_fds[1]);
5287                 _exit(0);
5288         }
5289 }
5290
5291 static gint compose_exec_ext_editor_real(const gchar *file)
5292 {
5293         static gchar *def_cmd = "emacs %s";
5294         gchar buf[1024];
5295         gchar *p;
5296         gchar **cmdline;
5297         pid_t pid;
5298
5299         g_return_val_if_fail(file != NULL, -1);
5300
5301         if ((pid = fork()) < 0) {
5302                 perror("fork");
5303                 return -1;
5304         }
5305
5306         if (pid != 0) return pid;
5307
5308         /* grandchild process */
5309
5310         if (setpgid(0, getppid()))
5311                 perror("setpgid");
5312
5313         if (prefs_common.ext_editor_cmd &&
5314             (p = strchr(prefs_common.ext_editor_cmd, '%')) &&
5315             *(p + 1) == 's' && !strchr(p + 2, '%')) {
5316                 g_snprintf(buf, sizeof(buf), prefs_common.ext_editor_cmd, file);
5317         } else {
5318                 if (prefs_common.ext_editor_cmd)
5319                         g_warning(_("External editor command line is invalid: `%s'\n"),
5320                                   prefs_common.ext_editor_cmd);
5321                 g_snprintf(buf, sizeof(buf), def_cmd, file);
5322         }
5323
5324         cmdline = g_strsplit(buf, " ", 1024);
5325         execvp(cmdline[0], cmdline);
5326
5327         perror("execvp");
5328         g_strfreev(cmdline);
5329
5330         _exit(1);
5331 }
5332
5333 static gboolean compose_ext_editor_kill(Compose *compose)
5334 {
5335         pid_t pgid = compose->exteditor_pid * -1;
5336         gint ret;
5337
5338         ret = kill(pgid, 0);
5339
5340         if (ret == 0 || (ret == -1 && EPERM == errno)) {
5341                 AlertValue val;
5342                 gchar *msg;
5343
5344                 msg = g_strdup_printf
5345                         (_("The external editor is still working.\n"
5346                            "Force terminating the process?\n"
5347                            "process group id: %d"), -pgid);
5348                 val = alertpanel(_("Notice"), msg, _("Yes"), _("+No"), NULL);
5349                 g_free(msg);
5350
5351                 if (val == G_ALERTDEFAULT) {
5352                         gdk_input_remove(compose->exteditor_tag);
5353                         close(compose->exteditor_readdes);
5354
5355                         if (kill(pgid, SIGTERM) < 0) perror("kill");
5356                         waitpid(compose->exteditor_pid, NULL, 0);
5357
5358                         g_warning(_("Terminated process group id: %d"), -pgid);
5359                         g_warning(_("Temporary file: %s"),
5360                                   compose->exteditor_file);
5361
5362                         compose_set_ext_editor_sensitive(compose, TRUE);
5363
5364                         g_free(compose->exteditor_file);
5365                         compose->exteditor_file    = NULL;
5366                         compose->exteditor_pid     = -1;
5367                         compose->exteditor_readdes = -1;
5368                         compose->exteditor_tag     = -1;
5369                 } else
5370                         return FALSE;
5371         }
5372
5373         return TRUE;
5374 }
5375
5376 static void compose_input_cb(gpointer data, gint source,
5377                              GdkInputCondition condition)
5378 {
5379         gchar buf[3];
5380         Compose *compose = (Compose *)data;
5381         gint i = 0;
5382
5383         debug_print(_("Compose: input from monitoring process\n"));
5384
5385         gdk_input_remove(compose->exteditor_tag);
5386
5387         for (;;) {
5388                 if (read(source, &buf[i], 1) < 1) {
5389                         buf[0] = '3';
5390                         break;
5391                 }
5392                 if (buf[i] == '\n') {
5393                         buf[i] = '\0';
5394                         break;
5395                 }
5396                 i++;
5397                 if (i == sizeof(buf) - 1)
5398                         break;
5399         }
5400
5401         waitpid(compose->exteditor_pid, NULL, 0);
5402
5403         if (buf[0] == '0') {            /* success */
5404                 GtkSText *text = GTK_STEXT(compose->text);
5405
5406                 gtk_stext_freeze(text);
5407                 gtk_stext_set_point(text, 0);
5408                 gtk_stext_forward_delete(text, gtk_stext_get_length(text));
5409                 compose_insert_file(compose, compose->exteditor_file);
5410                 compose_changed_cb(NULL, compose);
5411                 gtk_stext_thaw(text);
5412
5413                 if (unlink(compose->exteditor_file) < 0)
5414                         FILE_OP_ERROR(compose->exteditor_file, "unlink");
5415         } else if (buf[0] == '1') {     /* failed */
5416                 g_warning(_("Couldn't exec external editor\n"));
5417                 if (unlink(compose->exteditor_file) < 0)
5418                         FILE_OP_ERROR(compose->exteditor_file, "unlink");
5419         } else if (buf[0] == '2') {
5420                 g_warning(_("Couldn't write to file\n"));
5421         } else if (buf[0] == '3') {
5422                 g_warning(_("Pipe read failed\n"));
5423         }
5424
5425         close(source);
5426
5427         compose_set_ext_editor_sensitive(compose, TRUE);
5428
5429         g_free(compose->exteditor_file);
5430         compose->exteditor_file    = NULL;
5431         compose->exteditor_pid     = -1;
5432         compose->exteditor_readdes = -1;
5433         compose->exteditor_tag     = -1;
5434 }
5435
5436 static void compose_set_ext_editor_sensitive(Compose *compose,
5437                                              gboolean sensitive)
5438 {
5439         GtkItemFactory *ifactory;
5440
5441         ifactory = gtk_item_factory_from_widget(compose->menubar);
5442
5443         menu_set_sensitive(ifactory, "/Message/Send", sensitive);
5444         menu_set_sensitive(ifactory, "/Message/Send later", sensitive);
5445         menu_set_sensitive(ifactory, "/Message/Save to draft folder",
5446                            sensitive);
5447         menu_set_sensitive(ifactory, "/File/Insert file", sensitive);
5448         menu_set_sensitive(ifactory, "/File/Insert signature", sensitive);
5449         menu_set_sensitive(ifactory, "/Edit/Wrap current paragraph", sensitive);
5450         menu_set_sensitive(ifactory, "/Edit/Wrap all long lines", sensitive);
5451         menu_set_sensitive(ifactory, "/Edit/Edit with external editor",
5452                            sensitive);
5453
5454         gtk_widget_set_sensitive(compose->text,          sensitive);
5455         gtk_widget_set_sensitive(compose->send_btn,      sensitive);
5456         gtk_widget_set_sensitive(compose->sendl_btn,     sensitive);
5457         gtk_widget_set_sensitive(compose->draft_btn,     sensitive);
5458         gtk_widget_set_sensitive(compose->insert_btn,    sensitive);
5459         gtk_widget_set_sensitive(compose->sig_btn,       sensitive);
5460         gtk_widget_set_sensitive(compose->exteditor_btn, sensitive);
5461         gtk_widget_set_sensitive(compose->linewrap_btn,  sensitive);
5462 }
5463
5464 /**
5465  * compose_undo_state_changed:
5466  *
5467  * Change the sensivity of the menuentries undo and redo
5468  **/
5469 static void compose_undo_state_changed(UndoMain *undostruct, gint undo_state,
5470                                        gint redo_state, gpointer data)
5471 {
5472         GtkWidget *widget = GTK_WIDGET(data);
5473         GtkItemFactory *ifactory;
5474
5475         g_return_if_fail(widget != NULL);
5476
5477         debug_print("Set_undo.  UNDO:%i  REDO:%i\n", undo_state, redo_state);
5478
5479         ifactory = gtk_item_factory_from_widget(widget);
5480
5481         switch (undo_state) {
5482         case UNDO_STATE_TRUE:
5483                 if (!undostruct->undo_state) {
5484                         debug_print ("Set_undo - Testpoint\n");
5485                         undostruct->undo_state = TRUE;
5486                         menu_set_sensitive(ifactory, "/Edit/Undo", TRUE);
5487                 }
5488                 break;
5489         case UNDO_STATE_FALSE:
5490                 if (undostruct->undo_state) {
5491                         undostruct->undo_state = FALSE;
5492                         menu_set_sensitive(ifactory, "/Edit/Undo", FALSE);
5493                 }
5494                 break;
5495         case UNDO_STATE_UNCHANGED:
5496                 break;
5497         case UNDO_STATE_REFRESH:
5498                 menu_set_sensitive(ifactory, "/Edit/Undo",
5499                                    undostruct->undo_state);
5500                 break;
5501         default:
5502                 g_warning("Undo state not recognized");
5503                 break;
5504         }
5505
5506         switch (redo_state) {
5507         case UNDO_STATE_TRUE:
5508                 if (!undostruct->redo_state) {
5509                         undostruct->redo_state = TRUE;
5510                         menu_set_sensitive(ifactory, "/Edit/Redo", TRUE);
5511                 }
5512                 break;
5513         case UNDO_STATE_FALSE:
5514                 if (undostruct->redo_state) {
5515                         undostruct->redo_state = FALSE;
5516                         menu_set_sensitive(ifactory, "/Edit/Redo", FALSE);
5517                 }
5518                 break;
5519         case UNDO_STATE_UNCHANGED:
5520                 break;
5521         case UNDO_STATE_REFRESH:
5522                 menu_set_sensitive(ifactory, "/Edit/Redo",
5523                                    undostruct->redo_state);
5524                 break;
5525         default:
5526                 g_warning("Redo state not recognized");
5527                 break;
5528         }
5529 }
5530
5531 static gint calc_cursor_xpos(GtkSText *text, gint extra, gint char_width)
5532 {
5533         gint cursor_pos;
5534
5535         cursor_pos = (text->cursor_pos_x - extra) / char_width;
5536         cursor_pos = MAX(cursor_pos, 0);
5537
5538         return cursor_pos;
5539 }
5540
5541 /* callback functions */
5542
5543 /* compose_edit_size_alloc() - called when resized. don't know whether Gtk
5544  * includes "non-client" (windows-izm) in calculation, so this calculation
5545  * may not be accurate.
5546  */
5547 static gboolean compose_edit_size_alloc(GtkEditable *widget,
5548                                         GtkAllocation *allocation,
5549                                         GtkSHRuler *shruler)
5550 {
5551         if (prefs_common.show_ruler) {
5552                 gint char_width;
5553                 gint line_width_in_chars;
5554
5555                 char_width = gtkut_get_font_width
5556                         (GTK_WIDGET(widget)->style->font);
5557                 line_width_in_chars =
5558                         (allocation->width - allocation->x) / char_width;
5559
5560                 /* got the maximum */
5561                 gtk_ruler_set_range(GTK_RULER(shruler),
5562                                     0.0, line_width_in_chars,
5563                                     calc_cursor_xpos(GTK_STEXT(widget),
5564                                                      allocation->x,
5565                                                      char_width),
5566                                     /*line_width_in_chars*/ char_width);
5567         }
5568
5569         return TRUE;
5570 }
5571
5572 static void toolbar_send_cb(GtkWidget *widget, gpointer data)
5573 {
5574         compose_send_cb(data, 0, NULL);
5575 }
5576
5577 static void toolbar_send_later_cb(GtkWidget *widget, gpointer data)
5578 {
5579         compose_send_later_cb(data, 0, NULL);
5580 }
5581
5582 static void toolbar_draft_cb(GtkWidget *widget, gpointer data)
5583 {
5584         compose_draft_cb(data, 0, NULL);
5585 }
5586
5587 static void toolbar_insert_cb(GtkWidget *widget, gpointer data)
5588 {
5589         compose_insert_file_cb(data, 0, NULL);
5590 }
5591
5592 static void toolbar_attach_cb(GtkWidget *widget, gpointer data)
5593 {
5594         compose_attach_cb(data, 0, NULL);
5595 }
5596
5597 static void toolbar_sig_cb(GtkWidget *widget, gpointer data)
5598 {
5599         Compose *compose = (Compose *)data;
5600
5601         compose_insert_sig(compose);
5602 }
5603
5604 static void toolbar_ext_editor_cb(GtkWidget *widget, gpointer data)
5605 {
5606         Compose *compose = (Compose *)data;
5607
5608         compose_exec_ext_editor(compose);
5609 }
5610
5611 static void toolbar_linewrap_cb(GtkWidget *widget, gpointer data)
5612 {
5613         Compose *compose = (Compose *)data;
5614
5615         compose_wrap_line(compose);
5616 }
5617
5618 static void toolbar_address_cb(GtkWidget *widget, gpointer data)
5619 {
5620         compose_address_cb(data, 0, NULL);
5621 }
5622
5623 static void select_account(Compose * compose, PrefsAccount * ac)
5624 {
5625         compose->account = ac;
5626         compose_set_title(compose);
5627
5628 #if 0 /* NEW COMPOSE GUI */
5629                 if (ac->protocol == A_NNTP) {
5630                         GtkItemFactory *ifactory;
5631                         GtkWidget *menuitem;
5632
5633                         ifactory = gtk_item_factory_from_widget(compose->menubar);
5634                         menu_set_sensitive(ifactory,
5635                                            "/Message/Followup to", TRUE);
5636                         gtk_widget_show(compose->newsgroups_hbox);
5637                         gtk_widget_show(compose->newsgroups_entry);
5638                         gtk_table_set_row_spacing(GTK_TABLE(compose->table),
5639                                                   1, 4);
5640
5641                         compose->use_to = FALSE;
5642                         compose->use_cc = FALSE;
5643
5644                         menuitem = gtk_item_factory_get_item(ifactory, "/Message/To");
5645                         gtk_check_menu_item_set_active
5646                                 (GTK_CHECK_MENU_ITEM(menuitem), FALSE);
5647
5648                         menu_set_sensitive(ifactory,
5649                                            "/Message/To", TRUE);
5650                         menuitem = gtk_item_factory_get_item(ifactory, "/Message/Cc");
5651                         gtk_check_menu_item_set_active
5652                                 (GTK_CHECK_MENU_ITEM(menuitem), FALSE);
5653
5654                         gtk_widget_hide(compose->to_hbox);
5655                         gtk_widget_hide(compose->to_entry);
5656                         gtk_widget_hide(compose->cc_hbox);
5657                         gtk_widget_hide(compose->cc_entry);
5658                         gtk_table_set_row_spacing(GTK_TABLE(compose->table),
5659                                                   0, 0);
5660                         gtk_table_set_row_spacing(GTK_TABLE(compose->table),
5661                                                   3, 0);
5662                 }
5663                 else {
5664                         GtkItemFactory *ifactory;
5665                         GtkWidget *menuitem;
5666
5667                         ifactory = gtk_item_factory_from_widget(compose->menubar);
5668                         menu_set_sensitive(ifactory,
5669                                            "/Message/Followup to", FALSE);
5670                         gtk_entry_set_text(GTK_ENTRY(compose->newsgroups_entry), "");
5671                         gtk_widget_hide(compose->newsgroups_hbox);
5672                         gtk_widget_hide(compose->newsgroups_entry);
5673                         gtk_table_set_row_spacing(GTK_TABLE(compose->table),
5674                                                   1, 0);
5675
5676                         compose->use_to = TRUE;
5677                         compose->use_cc = TRUE;
5678
5679                         menuitem = gtk_item_factory_get_item(ifactory, "/Message/To");
5680                         gtk_check_menu_item_set_active
5681                                 (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
5682                         menu_set_sensitive(ifactory,
5683                                            "/Message/To", FALSE);
5684                         menuitem = gtk_item_factory_get_item(ifactory, "/Message/Cc");
5685                         gtk_check_menu_item_set_active
5686                                 (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
5687                         gtk_widget_show(compose->to_hbox);
5688                         gtk_widget_show(compose->to_entry);
5689                         gtk_widget_show(compose->cc_hbox);
5690                         gtk_widget_show(compose->cc_entry);
5691
5692                         gtk_table_set_row_spacing(GTK_TABLE(compose->table),
5693                                                   0, 4);
5694                         gtk_table_set_row_spacing(GTK_TABLE(compose->table),
5695                                                   3, 4);
5696                 }
5697                 gtk_widget_queue_resize(compose->table_vbox);
5698 #endif
5699 }
5700
5701 static void account_activated(GtkMenuItem *menuitem, gpointer data)
5702 {
5703         Compose *compose = (Compose *)data;
5704
5705         PrefsAccount *ac;
5706
5707         ac = (PrefsAccount *)gtk_object_get_user_data(GTK_OBJECT(menuitem));
5708         g_return_if_fail(ac != NULL);
5709
5710         if (ac != compose->account)
5711                 select_account(compose, ac);
5712 }
5713
5714 static void attach_selected(GtkCList *clist, gint row, gint column,
5715                             GdkEvent *event, gpointer data)
5716 {
5717         Compose *compose = (Compose *)data;
5718
5719         if (event && event->type == GDK_2BUTTON_PRESS)
5720                 compose_attach_property(compose);
5721 }
5722
5723 static void attach_button_pressed(GtkWidget *widget, GdkEventButton *event,
5724                                   gpointer data)
5725 {
5726         Compose *compose = (Compose *)data;
5727         GtkCList *clist = GTK_CLIST(compose->attach_clist);
5728         gint row, column;
5729
5730         if (!event) return;
5731
5732         if (event->button == 3) {
5733                 if ((clist->selection && !clist->selection->next) ||
5734                     !clist->selection) {
5735                         gtk_clist_unselect_all(clist);
5736                         if (gtk_clist_get_selection_info(clist,
5737                                                          event->x, event->y,
5738                                                          &row, &column)) {
5739                                 gtk_clist_select_row(clist, row, column);
5740                                 gtkut_clist_set_focus_row(clist, row);
5741                         }
5742                 }
5743                 gtk_menu_popup(GTK_MENU(compose->popupmenu), NULL, NULL,
5744                                NULL, NULL, event->button, event->time);
5745         }
5746 }
5747
5748 static void attach_key_pressed(GtkWidget *widget, GdkEventKey *event,
5749                                gpointer data)
5750 {
5751         Compose *compose = (Compose *)data;
5752
5753         if (!event) return;
5754
5755         switch (event->keyval) {
5756         case GDK_Delete:
5757                 compose_attach_remove_selected(compose);
5758                 break;
5759         }
5760 }
5761
5762 static void compose_send_cb(gpointer data, guint action, GtkWidget *widget)
5763 {
5764         Compose *compose = (Compose *)data;
5765         gint val;
5766
5767         val = compose_send(compose);
5768
5769         if (val == 0) gtk_widget_destroy(compose->window);
5770 }
5771
5772 static void compose_send_later_cb(gpointer data, guint action,
5773                                   GtkWidget *widget)
5774 {
5775         Compose *compose = (Compose *)data;
5776         gint val;
5777
5778         val = compose_queue(compose, NULL, NULL);
5779         if (!val) gtk_widget_destroy(compose->window);
5780 }
5781
5782 static void compose_draft_cb(gpointer data, guint action, GtkWidget *widget)
5783 {
5784         Compose *compose = (Compose *)data;
5785         FolderItem *draft;
5786         gchar *tmp;
5787         gint msgnum;
5788         static gboolean lock = FALSE;
5789
5790         if (lock) return;
5791
5792         draft = folder_get_default_draft();
5793         g_return_if_fail(draft != NULL);
5794
5795         lock = TRUE;
5796
5797         tmp = g_strdup_printf("%s%cdraft.%d", g_get_tmp_dir(),
5798                               G_DIR_SEPARATOR, (gint)compose);
5799
5800         if (compose_write_to_file(compose, tmp, TRUE) < 0) {
5801                 g_free(tmp);
5802                 lock = FALSE;
5803                 return;
5804         }
5805
5806         folder_item_scan(draft);
5807         if ((msgnum = folder_item_add_msg(draft, tmp, TRUE)) <= 0) {
5808                 unlink(tmp);
5809                 g_free(tmp);
5810                 lock = FALSE;
5811                 return;
5812         }
5813         g_free(tmp);
5814         draft->mtime = 0;       /* force updating */
5815
5816         if (compose->mode == COMPOSE_REEDIT) {
5817                 compose_remove_reedit_target(compose);
5818                 if (compose->targetinfo &&
5819                     compose->targetinfo->folder != draft)
5820                         folderview_update_item(compose->targetinfo->folder,
5821                                                TRUE);
5822         }
5823
5824         folder_item_scan(draft);
5825         folderview_update_item(draft, TRUE);
5826
5827         lock = FALSE;
5828
5829         /* 0: quit editing  1: keep editing */
5830         if (action == 0)
5831                 gtk_widget_destroy(compose->window);
5832         else {
5833                 struct stat s;
5834                 gchar *path;
5835
5836                 path = folder_item_fetch_msg(draft, msgnum);
5837                 g_return_if_fail(path != NULL);
5838                 if (stat(path, &s) < 0) {
5839                         FILE_OP_ERROR(path, "stat");
5840                         g_free(path);
5841                         lock = FALSE;
5842                         return;
5843                 }
5844                 g_free(path);
5845
5846                 procmsg_msginfo_free(compose->targetinfo);
5847                 compose->targetinfo = g_new0(MsgInfo, 1);
5848                 compose->targetinfo->msgnum = msgnum;
5849                 compose->targetinfo->size = s.st_size;
5850                 compose->targetinfo->mtime = s.st_mtime;
5851                 compose->targetinfo->folder = draft;
5852                 compose->mode = COMPOSE_REEDIT;
5853         }
5854 }
5855
5856 static void compose_attach_cb(gpointer data, guint action, GtkWidget *widget)
5857 {
5858         Compose *compose = (Compose *)data;
5859         GList *file_list;
5860
5861         if (compose->bounce_filename != NULL)
5862                 return;
5863
5864         file_list = filesel_select_multiple_files(_("Select file"), NULL);
5865
5866         if (file_list) {
5867                 GList *tmp;
5868
5869                 for ( tmp = file_list; tmp; tmp = tmp->next) {
5870                         gchar *file = (gchar *) tmp->data;
5871                         compose_attach_append(compose, file, MIME_UNKNOWN);
5872                         g_free(file);
5873                 }
5874                 g_list_free(file_list);
5875         }               
5876 }
5877
5878 static void compose_insert_file_cb(gpointer data, guint action,
5879                                    GtkWidget *widget)
5880 {
5881         Compose *compose = (Compose *)data;
5882         GList *file_list;
5883
5884         file_list = filesel_select_multiple_files(_("Select file"), NULL);
5885
5886         if (file_list) {
5887                 GList *tmp;
5888
5889                 for ( tmp = file_list; tmp; tmp = tmp->next) {
5890                         gchar *file = (gchar *) tmp->data;
5891                         compose_insert_file(compose, file);
5892                         g_free(file);
5893                 }
5894                 g_list_free(file_list);
5895         }
5896 }
5897
5898 static gint compose_delete_cb(GtkWidget *widget, GdkEventAny *event,
5899                               gpointer data)
5900 {
5901         compose_close_cb(data, 0, NULL);
5902         return TRUE;
5903 }
5904
5905 static void compose_close_cb(gpointer data, guint action, GtkWidget *widget)
5906 {
5907         Compose *compose = (Compose *)data;
5908         AlertValue val;
5909
5910         if (compose->exteditor_tag != -1) {
5911                 if (!compose_ext_editor_kill(compose))
5912                         return;
5913         }
5914
5915         if (compose->modified) {
5916                 val = alertpanel(_("Discard message"),
5917                                  _("This message has been modified. discard it?"),
5918                                  _("Discard"), _("to Draft"), _("Cancel"));
5919
5920                 switch (val) {
5921                 case G_ALERTDEFAULT:
5922                         break;
5923                 case G_ALERTALTERNATE:
5924                         compose_draft_cb(data, 0, NULL);
5925                         return;
5926                 default:
5927                         return;
5928                 }
5929         }
5930 #if USE_PSPELL
5931         if (compose->gtkpspell) {
5932                 gtkpspell_detach(compose->gtkpspell);
5933                 compose->gtkpspell = gtkpspell_delete(compose->gtkpspell);
5934         }
5935 #endif
5936         gtk_widget_destroy(compose->window);
5937 }
5938
5939 static void compose_address_cb(gpointer data, guint action, GtkWidget *widget)
5940 {
5941         Compose *compose = (Compose *)data;
5942
5943         addressbook_open(compose);
5944 }
5945
5946 static void compose_template_activate_cb(GtkWidget *widget, gpointer data)
5947 {
5948         Compose *compose = (Compose *)data;
5949         Template *tmpl;
5950
5951         tmpl = gtk_object_get_data(GTK_OBJECT(widget), "template");
5952         g_return_if_fail(tmpl != NULL);
5953
5954         compose_template_apply(compose, tmpl);
5955 }
5956
5957 static void compose_ext_editor_cb(gpointer data, guint action,
5958                                   GtkWidget *widget)
5959 {
5960         Compose *compose = (Compose *)data;
5961
5962         compose_exec_ext_editor(compose);
5963 }
5964
5965 static void compose_destroy_cb(GtkWidget *widget, Compose *compose)
5966 {
5967         compose_destroy(compose);
5968 }
5969
5970 static void compose_undo_cb(Compose *compose)
5971 {
5972         undo_undo(compose->undostruct);
5973 }
5974
5975 static void compose_redo_cb(Compose *compose)
5976 {
5977         undo_redo(compose->undostruct);
5978 }
5979
5980 static void compose_cut_cb(Compose *compose)
5981 {
5982         if (compose->focused_editable &&
5983             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
5984                 gtk_editable_cut_clipboard
5985                         (GTK_EDITABLE(compose->focused_editable));
5986 }
5987
5988 static void compose_copy_cb(Compose *compose)
5989 {
5990         if (compose->focused_editable &&
5991             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
5992                 gtk_editable_copy_clipboard
5993                         (GTK_EDITABLE(compose->focused_editable));
5994 }
5995
5996 static void compose_paste_cb(Compose *compose)
5997 {
5998         if (compose->focused_editable &&
5999             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
6000                 gtk_editable_paste_clipboard
6001                         (GTK_EDITABLE(compose->focused_editable));
6002 }
6003
6004 static void compose_allsel_cb(Compose *compose)
6005 {
6006         if (compose->focused_editable &&
6007             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
6008                 gtk_editable_select_region
6009                         (GTK_EDITABLE(compose->focused_editable), 0, -1);
6010 }
6011
6012 static void compose_grab_focus_cb(GtkWidget *widget, Compose *compose)
6013 {
6014         if (GTK_IS_EDITABLE(widget))
6015                 compose->focused_editable = widget;
6016 }
6017
6018 static void compose_changed_cb(GtkEditable *editable, Compose *compose)
6019 {
6020         if (compose->modified == FALSE) {
6021                 compose->modified = TRUE;
6022                 compose_set_title(compose);
6023         }
6024 }
6025
6026 static void compose_button_press_cb(GtkWidget *widget, GdkEventButton *event,
6027                                     Compose *compose)
6028 {
6029         gtk_stext_set_point(GTK_STEXT(widget),
6030                            gtk_editable_get_position(GTK_EDITABLE(widget)));
6031 }
6032
6033 #if 0
6034 static void compose_key_press_cb(GtkWidget *widget, GdkEventKey *event,
6035                                  Compose *compose)
6036 {
6037         gtk_stext_set_point(GTK_STEXT(widget),
6038                            gtk_editable_get_position(GTK_EDITABLE(widget)));
6039 }
6040 #endif
6041
6042 #if 0 /* NEW COMPOSE GUI */
6043 static void compose_toggle_to_cb(gpointer data, guint action,
6044                                  GtkWidget *widget)
6045 {
6046         Compose *compose = (Compose *)data;
6047
6048         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6049                 gtk_widget_show(compose->to_hbox);
6050                 gtk_widget_show(compose->to_entry);
6051                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 1, 4);
6052                 compose->use_to = TRUE;
6053         } else {
6054                 gtk_widget_hide(compose->to_hbox);
6055                 gtk_widget_hide(compose->to_entry);
6056                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 1, 0);
6057                 gtk_widget_queue_resize(compose->table_vbox);
6058                 compose->use_to = FALSE;
6059         }
6060
6061         if (addressbook_get_target_compose() == compose)
6062                 addressbook_set_target_compose(compose);
6063 }
6064
6065 static void compose_toggle_cc_cb(gpointer data, guint action,
6066                                  GtkWidget *widget)
6067 {
6068         Compose *compose = (Compose *)data;
6069
6070         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6071                 gtk_widget_show(compose->cc_hbox);
6072                 gtk_widget_show(compose->cc_entry);
6073                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 3, 4);
6074                 compose->use_cc = TRUE;
6075         } else {
6076                 gtk_widget_hide(compose->cc_hbox);
6077                 gtk_widget_hide(compose->cc_entry);
6078                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 3, 0);
6079                 gtk_widget_queue_resize(compose->table_vbox);
6080                 compose->use_cc = FALSE;
6081         }
6082
6083         if (addressbook_get_target_compose() == compose)
6084                 addressbook_set_target_compose(compose);
6085 }
6086
6087 static void compose_toggle_bcc_cb(gpointer data, guint action,
6088                                   GtkWidget *widget)
6089 {
6090         Compose *compose = (Compose *)data;
6091
6092         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6093                 gtk_widget_show(compose->bcc_hbox);
6094                 gtk_widget_show(compose->bcc_entry);
6095                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 4, 4);
6096                 compose->use_bcc = TRUE;
6097         } else {
6098                 gtk_widget_hide(compose->bcc_hbox);
6099                 gtk_widget_hide(compose->bcc_entry);
6100                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 4, 0);
6101                 gtk_widget_queue_resize(compose->table_vbox);
6102                 compose->use_bcc = FALSE;
6103         }
6104
6105         if (addressbook_get_target_compose() == compose)
6106                 addressbook_set_target_compose(compose);
6107 }
6108
6109 static void compose_toggle_replyto_cb(gpointer data, guint action,
6110                                       GtkWidget *widget)
6111 {
6112         Compose *compose = (Compose *)data;
6113
6114         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6115                 gtk_widget_show(compose->reply_hbox);
6116                 gtk_widget_show(compose->reply_entry);
6117                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 5, 4);
6118                 compose->use_replyto = TRUE;
6119         } else {
6120                 gtk_widget_hide(compose->reply_hbox);
6121                 gtk_widget_hide(compose->reply_entry);
6122                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 5, 0);
6123                 gtk_widget_queue_resize(compose->table_vbox);
6124                 compose->use_replyto = FALSE;
6125         }
6126 }
6127
6128 static void compose_toggle_followupto_cb(gpointer data, guint action,
6129                                          GtkWidget *widget)
6130 {
6131         Compose *compose = (Compose *)data;
6132
6133         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6134                 gtk_widget_show(compose->followup_hbox);
6135                 gtk_widget_show(compose->followup_entry);
6136                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 6, 4);
6137                 compose->use_followupto = TRUE;
6138         } else {
6139                 gtk_widget_hide(compose->followup_hbox);
6140                 gtk_widget_hide(compose->followup_entry);
6141                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 6, 0);
6142                 gtk_widget_queue_resize(compose->table_vbox);
6143                 compose->use_followupto = FALSE;
6144         }
6145 }
6146
6147 static void compose_toggle_attach_cb(gpointer data, guint action,
6148                                      GtkWidget *widget)
6149 {
6150         Compose *compose = (Compose *)data;
6151
6152         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6153                 gtk_widget_ref(compose->edit_vbox);
6154
6155                 gtkut_container_remove(GTK_CONTAINER(compose->vbox2),
6156                                        compose->edit_vbox);
6157                 gtk_paned_add2(GTK_PANED(compose->paned), compose->edit_vbox);
6158                 gtk_box_pack_start(GTK_BOX(compose->vbox2), compose->paned,
6159                                    TRUE, TRUE, 0);
6160                 gtk_widget_show(compose->paned);
6161
6162                 gtk_widget_unref(compose->edit_vbox);
6163                 gtk_widget_unref(compose->paned);
6164
6165                 compose->use_attach = TRUE;
6166         } else {
6167                 gtk_widget_ref(compose->paned);
6168                 gtk_widget_ref(compose->edit_vbox);
6169
6170                 gtkut_container_remove(GTK_CONTAINER(compose->vbox2),
6171                                        compose->paned);
6172                 gtkut_container_remove(GTK_CONTAINER(compose->paned),
6173                                        compose->edit_vbox);
6174                 gtk_box_pack_start(GTK_BOX(compose->vbox2),
6175                                    compose->edit_vbox, TRUE, TRUE, 0);
6176
6177                 gtk_widget_unref(compose->edit_vbox);
6178
6179                 compose->use_attach = FALSE;
6180         }
6181 }
6182 #endif
6183
6184 #if USE_GPGME
6185 static void compose_toggle_sign_cb(gpointer data, guint action,
6186                                    GtkWidget *widget)
6187 {
6188         Compose *compose = (Compose *)data;
6189
6190         if (GTK_CHECK_MENU_ITEM(widget)->active)
6191                 compose->use_signing = TRUE;
6192         else
6193                 compose->use_signing = FALSE;
6194 }
6195
6196 static void compose_toggle_encrypt_cb(gpointer data, guint action,
6197                                       GtkWidget *widget)
6198 {
6199         Compose *compose = (Compose *)data;
6200
6201         if (GTK_CHECK_MENU_ITEM(widget)->active)
6202                 compose->use_encryption = TRUE;
6203         else
6204                 compose->use_encryption = FALSE;
6205 }
6206 #endif /* USE_GPGME */
6207
6208 static void compose_toggle_ruler_cb(gpointer data, guint action,
6209                                     GtkWidget *widget)
6210 {
6211         Compose *compose = (Compose *)data;
6212
6213         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6214                 gtk_widget_show(compose->ruler_hbox);
6215                 prefs_common.show_ruler = TRUE;
6216         } else {
6217                 gtk_widget_hide(compose->ruler_hbox);
6218                 gtk_widget_queue_resize(compose->edit_vbox);
6219                 prefs_common.show_ruler = FALSE;
6220         }
6221 }
6222
6223 static void compose_attach_drag_received_cb (GtkWidget          *widget,
6224                                              GdkDragContext     *drag_context,
6225                                              gint                x,
6226                                              gint                y,
6227                                              GtkSelectionData   *data,
6228                                              guint               info,
6229                                              guint               time,
6230                                              gpointer            user_data)
6231 {
6232         Compose *compose = (Compose *)user_data;
6233         GList *list, *tmp;
6234
6235         list = uri_list_extract_filenames((const gchar *)data->data);
6236         for (tmp = list; tmp != NULL; tmp = tmp->next)
6237                 compose_attach_append(compose, (const gchar *)tmp->data,
6238                                       MIME_UNKNOWN);
6239         list_free_strings(list);
6240         g_list_free(list);
6241 }
6242
6243 static void compose_insert_drag_received_cb (GtkWidget          *widget,
6244                                              GdkDragContext     *drag_context,
6245                                              gint                x,
6246                                              gint                y,
6247                                              GtkSelectionData   *data,
6248                                              guint               info,
6249                                              guint               time,
6250                                              gpointer            user_data)
6251 {
6252         Compose *compose = (Compose *)user_data;
6253         GList *list, *tmp;
6254
6255         list = uri_list_extract_filenames((const gchar *)data->data);
6256         for (tmp = list; tmp != NULL; tmp = tmp->next)
6257                 compose_insert_file(compose, (const gchar *)tmp->data);
6258         list_free_strings(list);
6259         g_list_free(list);
6260 }
6261
6262 #if 0 /* NEW COMPOSE GUI */
6263 static void to_activated(GtkWidget *widget, Compose *compose)
6264 {
6265         if (GTK_WIDGET_VISIBLE(compose->newsgroups_entry))
6266                 gtk_widget_grab_focus(compose->newsgroups_entry);
6267         else
6268                 gtk_widget_grab_focus(compose->subject_entry);
6269 }
6270
6271 static void newsgroups_activated(GtkWidget *widget, Compose *compose)
6272 {
6273         gtk_widget_grab_focus(compose->subject_entry);
6274 }
6275
6276 static void subject_activated(GtkWidget *widget, Compose *compose)
6277 {
6278         if (GTK_WIDGET_VISIBLE(compose->cc_entry))
6279                 gtk_widget_grab_focus(compose->cc_entry);
6280         else if (GTK_WIDGET_VISIBLE(compose->bcc_entry))
6281                 gtk_widget_grab_focus(compose->bcc_entry);
6282         else if (GTK_WIDGET_VISIBLE(compose->reply_entry))
6283                 gtk_widget_grab_focus(compose->reply_entry);
6284         else if (GTK_WIDGET_VISIBLE(compose->followup_entry))
6285                 gtk_widget_grab_focus(compose->followup_entry);
6286         else
6287                 gtk_widget_grab_focus(compose->text);
6288 }
6289
6290 static void cc_activated(GtkWidget *widget, Compose *compose)
6291 {
6292         if (GTK_WIDGET_VISIBLE(compose->bcc_entry))
6293                 gtk_widget_grab_focus(compose->bcc_entry);
6294         else if (GTK_WIDGET_VISIBLE(compose->reply_entry))
6295                 gtk_widget_grab_focus(compose->reply_entry);
6296         else if (GTK_WIDGET_VISIBLE(compose->followup_entry))
6297                 gtk_widget_grab_focus(compose->followup_entry);
6298         else
6299                 gtk_widget_grab_focus(compose->text);
6300 }
6301
6302 static void bcc_activated(GtkWidget *widget, Compose *compose)
6303 {
6304         if (GTK_WIDGET_VISIBLE(compose->reply_entry))
6305                 gtk_widget_grab_focus(compose->reply_entry);
6306         else if (GTK_WIDGET_VISIBLE(compose->followup_entry))
6307                 gtk_widget_grab_focus(compose->followup_entry);
6308         else
6309                 gtk_widget_grab_focus(compose->text);
6310 }
6311
6312 static void replyto_activated(GtkWidget *widget, Compose *compose)
6313 {
6314         if (GTK_WIDGET_VISIBLE(compose->followup_entry))
6315                 gtk_widget_grab_focus(compose->followup_entry);
6316         else
6317                 gtk_widget_grab_focus(compose->text);
6318 }
6319
6320 static void followupto_activated(GtkWidget *widget, Compose *compose)
6321 {
6322         gtk_widget_grab_focus(compose->text);
6323 }
6324 #endif
6325
6326 static void compose_toggle_return_receipt_cb(gpointer data, guint action,
6327                                              GtkWidget *widget)
6328 {
6329         Compose *compose = (Compose *)data;
6330
6331         if (GTK_CHECK_MENU_ITEM(widget)->active)
6332                 compose->return_receipt = TRUE;
6333         else
6334                 compose->return_receipt = FALSE;
6335 }
6336
6337 void compose_headerentry_key_press_event_cb(GtkWidget *entry,
6338                                             GdkEventKey *event,
6339                                             ComposeHeaderEntry *headerentry)
6340 {
6341         if ((g_slist_length(headerentry->compose->header_list) > 0) &&
6342             ((headerentry->headernum + 1) != headerentry->compose->header_nextrow) &&
6343             !(event->state & GDK_MODIFIER_MASK) &&
6344             (event->keyval == GDK_BackSpace) &&
6345             (strlen(gtk_entry_get_text(GTK_ENTRY(entry))) == 0)) {
6346                 gtk_container_remove
6347                         (GTK_CONTAINER(headerentry->compose->header_table),
6348                          headerentry->combo);
6349                 gtk_container_remove
6350                         (GTK_CONTAINER(headerentry->compose->header_table),
6351                          headerentry->entry);
6352                 headerentry->compose->header_list =
6353                         g_slist_remove(headerentry->compose->header_list,
6354                                        headerentry);
6355                 g_free(headerentry);
6356         } else  if (event->keyval == GDK_Tab) {
6357                 if (headerentry->compose->header_last == headerentry) {
6358                         /* Override default next focus, and give it to subject_entry
6359                          * instead of notebook tabs
6360                          */
6361                         gtk_signal_emit_stop_by_name(GTK_OBJECT(entry), "key-press-event"); 
6362                         gtk_widget_grab_focus(headerentry->compose->subject_entry);
6363                 }
6364         }
6365
6366 }
6367
6368 void compose_headerentry_changed_cb(GtkWidget *entry,
6369                                     ComposeHeaderEntry *headerentry)
6370 {
6371         if (strlen(gtk_entry_get_text(GTK_ENTRY(entry))) != 0) {
6372                 headerentry->compose->header_list =
6373                         g_slist_append(headerentry->compose->header_list,
6374                                        headerentry);
6375                 compose_create_header_entry(headerentry->compose);
6376                 gtk_signal_disconnect_by_func
6377                         (GTK_OBJECT(entry),
6378                          GTK_SIGNAL_FUNC(compose_headerentry_changed_cb),
6379                          headerentry);
6380                 /* Automatically scroll down */
6381                 compose_show_first_last_header(headerentry->compose, FALSE);
6382                 
6383         }
6384 }
6385
6386 static void compose_show_first_last_header(Compose *compose, gboolean show_first)
6387 {
6388         GtkAdjustment *vadj;
6389
6390         g_return_if_fail(compose);
6391         g_return_if_fail(GTK_IS_WIDGET(compose->header_table));
6392         g_return_if_fail(GTK_IS_VIEWPORT(compose->header_table->parent));
6393
6394         vadj = gtk_viewport_get_vadjustment(GTK_VIEWPORT(compose->header_table->parent));
6395         gtk_adjustment_set_value(vadj, (show_first ? vadj->lower : vadj->upper));
6396 }
6397
6398 static void compose_ctl_enter_send_shortcut_cb(GtkWidget *w, Compose *compose)
6399 {
6400         GtkItemFactory *ifactory;
6401         GtkAccelEntry  *accel;
6402         GtkWidget      *send_button;
6403         GSList *list;
6404         GdkEvent *e= gtk_get_current_event();
6405         
6406         if (e->type != GDK_KEY_PRESS || 
6407             !( ((GdkEventKey *)e)->state & GDK_CONTROL_MASK) )
6408                 return;
6409
6410         ifactory = gtk_item_factory_from_widget(compose->menubar);
6411         send_button = gtk_item_factory_get_widget(ifactory, "/Message/Send");
6412         list = gtk_accel_group_entries_from_object(GTK_OBJECT(send_button));
6413         accel = (GtkAccelEntry *) list->data;
6414         if (accel->accelerator_key == GDK_Return && 
6415             accel->accelerator_mods == GDK_CONTROL_MASK)
6416                 compose_send_cb(compose, 0, NULL);
6417 }