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