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