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