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