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