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