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