2006-02-07 [colin] 2.0.0cvs28
[claws.git] / src / compose.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2006 Hiroyuki Yamamoto and the Sylpheed-Claws team
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include "defs.h"
25
26 #ifndef PANGO_ENABLE_ENGINE
27 #  define PANGO_ENABLE_ENGINE
28 #endif
29
30 #include <glib.h>
31 #include <glib/gi18n.h>
32 #include <gdk/gdkkeysyms.h>
33 #include <gtk/gtkmain.h>
34 #include <gtk/gtkmenu.h>
35 #include <gtk/gtkmenuitem.h>
36 #include <gtk/gtkitemfactory.h>
37 #include <gtk/gtkcheckmenuitem.h>
38 #include <gtk/gtkoptionmenu.h>
39 #include <gtk/gtkwidget.h>
40 #include <gtk/gtkvpaned.h>
41 #include <gtk/gtkentry.h>
42 #include <gtk/gtkeditable.h>
43 #include <gtk/gtkwindow.h>
44 #include <gtk/gtksignal.h>
45 #include <gtk/gtkvbox.h>
46 #include <gtk/gtkcontainer.h>
47 #include <gtk/gtkhandlebox.h>
48 #include <gtk/gtktoolbar.h>
49 #include <gtk/gtktable.h>
50 #include <gtk/gtkhbox.h>
51 #include <gtk/gtklabel.h>
52 #include <gtk/gtkscrolledwindow.h>
53 #include <gtk/gtktreeview.h>
54 #include <gtk/gtkliststore.h>
55 #include <gtk/gtktreeselection.h>
56 #include <gtk/gtktreemodel.h>
57
58 #include <gtk/gtkdnd.h>
59 #include <gtk/gtkclipboard.h>
60 #include <pango/pango-break.h>
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <string.h>
64 #include <ctype.h>
65 #include <sys/types.h>
66 #include <sys/stat.h>
67 #include <unistd.h>
68 #include <time.h>
69 #include <stdlib.h>
70 #if HAVE_SYS_WAIT_H
71 #  include <sys/wait.h>
72 #endif
73 #include <signal.h>
74 #include <errno.h>
75 #ifndef G_OS_WIN32  /* fixme we should have a configure test. */
76 #include <libgen.h>
77 #endif
78
79 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
80 #  include <wchar.h>
81 #  include <wctype.h>
82 #endif
83
84 #include "sylpheed.h"
85 #include "main.h"
86 #include "mainwindow.h"
87 #include "compose.h"
88 #include "addressbook.h"
89 #include "folderview.h"
90 #include "procmsg.h"
91 #include "menu.h"
92 #include "stock_pixmap.h"
93 #include "send_message.h"
94 #include "imap.h"
95 #include "news.h"
96 #include "customheader.h"
97 #include "prefs_common.h"
98 #include "prefs_account.h"
99 #include "action.h"
100 #include "account.h"
101 #include "filesel.h"
102 #include "procheader.h"
103 #include "procmime.h"
104 #include "statusbar.h"
105 #include "about.h"
106 #include "base64.h"
107 #include "quoted-printable.h"
108 #include "codeconv.h"
109 #include "utils.h"
110 #include "gtkutils.h"
111 #include "socket.h"
112 #include "alertpanel.h"
113 #include "manage_window.h"
114 #include "gtkshruler.h"
115 #include "folder.h"
116 #include "addr_compl.h"
117 #include "quote_fmt.h"
118 #include "template.h"
119 #include "undo.h"
120 #include "foldersel.h"
121 #include "toolbar.h"
122 #include "inc.h"
123 enum
124 {
125         COL_MIMETYPE = 0,
126         COL_SIZE     = 1,
127         COL_NAME     = 2,
128         COL_DATA     = 3,
129         COL_AUTODATA = 4,
130         N_COL_COLUMNS
131 };
132
133 #define N_ATTACH_COLS   (N_COL_COLUMNS)
134
135 typedef enum
136 {
137         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BEGINNING_OF_LINE,
138         COMPOSE_CALL_ADVANCED_ACTION_MOVE_FORWARD_CHARACTER,
139         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BACKWARD_CHARACTER,
140         COMPOSE_CALL_ADVANCED_ACTION_MOVE_FORWARD_WORD,
141         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BACKWARD_WORD,
142         COMPOSE_CALL_ADVANCED_ACTION_MOVE_END_OF_LINE,
143         COMPOSE_CALL_ADVANCED_ACTION_MOVE_NEXT_LINE,
144         COMPOSE_CALL_ADVANCED_ACTION_MOVE_PREVIOUS_LINE,
145         COMPOSE_CALL_ADVANCED_ACTION_DELETE_FORWARD_CHARACTER,
146         COMPOSE_CALL_ADVANCED_ACTION_DELETE_BACKWARD_CHARACTER,
147         COMPOSE_CALL_ADVANCED_ACTION_DELETE_FORWARD_WORD,
148         COMPOSE_CALL_ADVANCED_ACTION_DELETE_BACKWARD_WORD,
149         COMPOSE_CALL_ADVANCED_ACTION_DELETE_LINE,
150         COMPOSE_CALL_ADVANCED_ACTION_DELETE_LINE_N,
151         COMPOSE_CALL_ADVANCED_ACTION_DELETE_TO_LINE_END
152 } ComposeCallAdvancedAction;
153
154 typedef enum
155 {
156         PRIORITY_HIGHEST = 1,
157         PRIORITY_HIGH,
158         PRIORITY_NORMAL,
159         PRIORITY_LOW,
160         PRIORITY_LOWEST
161 } PriorityLevel;
162
163 typedef enum
164 {
165         COMPOSE_INSERT_SUCCESS,
166         COMPOSE_INSERT_READ_ERROR,
167         COMPOSE_INSERT_INVALID_CHARACTER,
168         COMPOSE_INSERT_NO_FILE
169 } ComposeInsertResult;
170
171 typedef enum
172 {
173         COMPOSE_QUIT_EDITING,
174         COMPOSE_KEEP_EDITING,
175         COMPOSE_AUTO_SAVE
176 } ComposeDraftAction;
177
178 typedef enum
179 {
180         COMPOSE_WRITE_FOR_SEND,
181         COMPOSE_WRITE_FOR_STORE
182 } ComposeWriteType;
183
184 #define B64_LINE_SIZE           57
185 #define B64_BUFFSIZE            77
186
187 #define MAX_REFERENCES_LEN      999
188
189 static GList *compose_list = NULL;
190
191 Compose *compose_generic_new                    (PrefsAccount   *account,
192                                                  const gchar    *to,
193                                                  FolderItem     *item,
194                                                  GPtrArray      *attach_files,
195                                                  GList          *listAddress );
196
197 static Compose *compose_create                  (PrefsAccount   *account,
198                                                  ComposeMode     mode);
199
200 static GtkWidget *compose_account_option_menu_create
201                                                 (Compose        *compose);
202 static void compose_set_out_encoding            (Compose        *compose);
203 static void compose_set_template_menu           (Compose        *compose);
204 static void compose_template_apply              (Compose        *compose,
205                                                  Template       *tmpl,
206                                                  gboolean        replace);
207 static void compose_destroy                     (Compose        *compose);
208
209 static void compose_entries_set                 (Compose        *compose,
210                                                  const gchar    *mailto);
211 static gint compose_parse_header                (Compose        *compose,
212                                                  MsgInfo        *msginfo);
213 static gchar *compose_parse_references          (const gchar    *ref,
214                                                  const gchar    *msgid);
215
216 static gchar *compose_quote_fmt                 (Compose        *compose,
217                                                  MsgInfo        *msginfo,
218                                                  const gchar    *fmt,
219                                                  const gchar    *qmark,
220                                                  const gchar    *body,
221                                                  gboolean        rewrap);
222
223 static void compose_reply_set_entry             (Compose        *compose,
224                                                  MsgInfo        *msginfo,
225                                                  gboolean        to_all,
226                                                  gboolean        to_ml,
227                                                  gboolean        to_sender,
228                                                  gboolean
229                                                  followup_and_reply_to);
230 static void compose_reedit_set_entry            (Compose        *compose,
231                                                  MsgInfo        *msginfo);
232
233 static void compose_insert_sig                  (Compose        *compose,
234                                                  gboolean        replace);
235 static gchar *compose_get_signature_str         (Compose        *compose);
236 static ComposeInsertResult compose_insert_file  (Compose        *compose,
237                                                  const gchar    *file);
238
239 static void compose_attach_append               (Compose        *compose,
240                                                  const gchar    *file,
241                                                  const gchar    *type,
242                                                  const gchar    *content_type);
243 static void compose_attach_parts                (Compose        *compose,
244                                                  MsgInfo        *msginfo);
245
246 static void compose_beautify_paragraph          (Compose        *compose,
247                                                  GtkTextIter    *par_iter,
248                                                  gboolean        force);
249 static void compose_wrap_all                    (Compose        *compose);
250 static void compose_wrap_all_full               (Compose        *compose,
251                                                  gboolean        autowrap);
252
253 static void compose_set_title                   (Compose        *compose);
254 static void compose_select_account              (Compose        *compose,
255                                                  PrefsAccount   *account,
256                                                  gboolean        init);
257
258 static PrefsAccount *compose_current_mail_account(void);
259 /* static gint compose_send                     (Compose        *compose); */
260 static gboolean compose_check_for_valid_recipient
261                                                 (Compose        *compose);
262 static gboolean compose_check_entries           (Compose        *compose,
263                                                  gboolean       check_subject);
264 static gint compose_write_to_file               (Compose        *compose,
265                                                  FILE           *fp,
266                                                  gint            action);
267 static gint compose_write_body_to_file          (Compose        *compose,
268                                                  const gchar    *file);
269 static gint compose_remove_reedit_target        (Compose        *compose,
270                                                  gboolean        force);
271 void compose_remove_draft                       (Compose        *compose);
272 static gint compose_queue                       (Compose        *compose,
273                                                  gint           *msgnum,
274                                                  FolderItem     **item);
275 static gint compose_queue_sub                   (Compose        *compose,
276                                                  gint           *msgnum,
277                                                  FolderItem     **item,
278                                                  gboolean       check_subject);
279 static void compose_add_attachments             (Compose        *compose,
280                                                  MimeInfo       *parent);
281 static gchar *compose_get_header                (Compose        *compose);
282
283 static void compose_convert_header              (Compose        *compose,
284                                                  gchar          *dest,
285                                                  gint            len,
286                                                  gchar          *src,
287                                                  gint            header_len,
288                                                  gboolean        addr_field);
289
290 static void compose_attach_info_free            (AttachInfo     *ainfo);
291 static void compose_attach_remove_selected      (Compose        *compose);
292
293 static void compose_attach_property             (Compose        *compose);
294 static void compose_attach_property_create      (gboolean       *cancelled);
295 static void attach_property_ok                  (GtkWidget      *widget,
296                                                  gboolean       *cancelled);
297 static void attach_property_cancel              (GtkWidget      *widget,
298                                                  gboolean       *cancelled);
299 static gint attach_property_delete_event        (GtkWidget      *widget,
300                                                  GdkEventAny    *event,
301                                                  gboolean       *cancelled);
302 static gboolean attach_property_key_pressed     (GtkWidget      *widget,
303                                                  GdkEventKey    *event,
304                                                  gboolean       *cancelled);
305
306 static void compose_exec_ext_editor             (Compose        *compose);
307 #ifdef G_OS_UNIX
308 static gint compose_exec_ext_editor_real        (const gchar    *file);
309 static gboolean compose_ext_editor_kill         (Compose        *compose);
310 static gboolean compose_input_cb                (GIOChannel     *source,
311                                                  GIOCondition    condition,
312                                                  gpointer        data);
313 static void compose_set_ext_editor_sensitive    (Compose        *compose,
314                                                  gboolean        sensitive);
315 #endif /* G_OS_UNIX */
316
317 static void compose_undo_state_changed          (UndoMain       *undostruct,
318                                                  gint            undo_state,
319                                                  gint            redo_state,
320                                                  gpointer        data);
321
322 static void compose_create_header_entry (Compose *compose);
323 static void compose_add_header_entry    (Compose *compose, gchar *header, gchar *text);
324 static void compose_update_priority_menu_item(Compose * compose);
325
326 static void compose_add_field_list      ( Compose *compose,
327                                           GList *listAddress );
328
329 /* callback functions */
330
331 static gboolean compose_edit_size_alloc (GtkEditable    *widget,
332                                          GtkAllocation  *allocation,
333                                          GtkSHRuler     *shruler);
334 static void account_activated           (GtkMenuItem    *menuitem,
335                                          gpointer        data);
336 static void attach_selected             (GtkTreeView    *tree_view, 
337                                          GtkTreePath    *tree_path,
338                                          GtkTreeViewColumn *column, 
339                                          Compose *compose);
340 static gboolean attach_button_pressed   (GtkWidget      *widget,
341                                          GdkEventButton *event,
342                                          gpointer        data);
343 static gboolean attach_key_pressed      (GtkWidget      *widget,
344                                          GdkEventKey    *event,
345                                          gpointer        data);
346
347 static void compose_send_cb             (gpointer        data,
348                                          guint           action,
349                                          GtkWidget      *widget);
350 static void compose_send_later_cb       (gpointer        data,
351                                          guint           action,
352                                          GtkWidget      *widget);
353
354 static void compose_draft_cb            (gpointer        data,
355                                          guint           action,
356                                          GtkWidget      *widget);
357
358 static void compose_attach_cb           (gpointer        data,
359                                          guint           action,
360                                          GtkWidget      *widget);
361 static void compose_insert_file_cb      (gpointer        data,
362                                          guint           action,
363                                          GtkWidget      *widget);
364 static void compose_insert_sig_cb       (gpointer        data,
365                                          guint           action,
366                                          GtkWidget      *widget);
367
368 static void compose_close_cb            (gpointer        data,
369                                          guint           action,
370                                          GtkWidget      *widget);
371
372 static void compose_set_encoding_cb     (gpointer        data,
373                                          guint           action,
374                                          GtkWidget      *widget);
375
376 static void compose_address_cb          (gpointer        data,
377                                          guint           action,
378                                          GtkWidget      *widget);
379 static void compose_template_activate_cb(GtkWidget      *widget,
380                                          gpointer        data);
381
382 static void compose_ext_editor_cb       (gpointer        data,
383                                          guint           action,
384                                          GtkWidget      *widget);
385
386 static gint compose_delete_cb           (GtkWidget      *widget,
387                                          GdkEventAny    *event,
388                                          gpointer        data);
389
390 static void compose_undo_cb             (Compose        *compose);
391 static void compose_redo_cb             (Compose        *compose);
392 static void compose_cut_cb              (Compose        *compose);
393 static void compose_copy_cb             (Compose        *compose);
394 static void compose_paste_cb            (Compose        *compose);
395 static void compose_paste_as_quote_cb   (Compose        *compose);
396 static void compose_paste_no_wrap_cb    (Compose        *compose);
397 static void compose_paste_wrap_cb       (Compose        *compose);
398 static void compose_allsel_cb           (Compose        *compose);
399
400 static void compose_advanced_action_cb  (Compose                   *compose,
401                                          ComposeCallAdvancedAction  action);
402
403 static void compose_grab_focus_cb       (GtkWidget      *widget,
404                                          Compose        *compose);
405
406 static void compose_changed_cb          (GtkTextBuffer  *textbuf,
407                                          Compose        *compose);
408
409 static void compose_wrap_cb             (gpointer        data,
410                                          guint           action,
411                                          GtkWidget      *widget);
412 static void compose_toggle_autowrap_cb  (gpointer        data,
413                                          guint           action,
414                                          GtkWidget      *widget);
415
416 static void compose_toggle_ruler_cb     (gpointer        data,
417                                          guint           action,
418                                          GtkWidget      *widget);
419 static void compose_toggle_sign_cb      (gpointer        data,
420                                          guint           action,
421                                          GtkWidget      *widget);
422 static void compose_toggle_encrypt_cb   (gpointer        data,
423                                          guint           action,
424                                          GtkWidget      *widget);
425 static void compose_set_privacy_system_cb(GtkWidget      *widget,
426                                           gpointer        data);
427 static void compose_update_privacy_system_menu_item(Compose * compose, gboolean warn);
428 static void activate_privacy_system     (Compose *compose, 
429                                          PrefsAccount *account,
430                                          gboolean warn);
431 static void compose_use_signing(Compose *compose, gboolean use_signing);
432 static void compose_use_encryption(Compose *compose, gboolean use_encryption);
433 static void compose_toggle_return_receipt_cb(gpointer data, guint action,
434                                              GtkWidget *widget);
435 static void compose_toggle_remove_refs_cb(gpointer data, guint action,
436                                              GtkWidget *widget);
437 static void compose_set_priority_cb     (gpointer        data,
438                                          guint           action,
439                                          GtkWidget      *widget);
440
441 static void compose_attach_drag_received_cb (GtkWidget          *widget,
442                                              GdkDragContext     *drag_context,
443                                              gint                x,
444                                              gint                y,
445                                              GtkSelectionData   *data,
446                                              guint               info,
447                                              guint               time,
448                                              gpointer            user_data);
449 static void compose_insert_drag_received_cb (GtkWidget          *widget,
450                                              GdkDragContext     *drag_context,
451                                              gint                x,
452                                              gint                y,
453                                              GtkSelectionData   *data,
454                                              guint               info,
455                                              guint               time,
456                                              gpointer            user_data);
457 static void compose_header_drag_received_cb (GtkWidget          *widget,
458                                              GdkDragContext     *drag_context,
459                                              gint                x,
460                                              gint                y,
461                                              GtkSelectionData   *data,
462                                              guint               info,
463                                              guint               time,
464                                              gpointer            user_data);
465
466 static gboolean compose_drag_drop           (GtkWidget *widget,
467                                              GdkDragContext *drag_context,
468                                              gint x, gint y,
469                                              guint time, gpointer user_data);
470
471 static void text_inserted               (GtkTextBuffer  *buffer,
472                                          GtkTextIter    *iter,
473                                          const gchar    *text,
474                                          gint            len,
475                                          Compose        *compose);
476 static Compose *compose_generic_reply(MsgInfo *msginfo, gboolean quote,
477                                   gboolean to_all, gboolean to_ml,
478                                   gboolean to_sender,
479                                   gboolean followup_and_reply_to,
480                                   const gchar *body);
481
482 gboolean compose_headerentry_changed_cb    (GtkWidget          *entry,
483                                             ComposeHeaderEntry *headerentry);
484 gboolean compose_headerentry_key_press_event_cb(GtkWidget              *entry,
485                                             GdkEventKey        *event,
486                                             ComposeHeaderEntry *headerentry);
487
488 static void compose_show_first_last_header (Compose *compose, gboolean show_first);
489
490 static void compose_allow_user_actions (Compose *compose, gboolean allow);
491
492 #if USE_ASPELL
493 static void compose_check_all              (Compose *compose);
494 static void compose_highlight_all          (Compose *compose);
495 static void compose_check_backwards        (Compose *compose);
496 static void compose_check_forwards_go      (Compose *compose);
497 #endif
498
499 static gint compose_defer_auto_save_draft       (Compose        *compose);
500 static PrefsAccount *compose_guess_forward_account_from_msginfo (MsgInfo *msginfo);
501
502 static gboolean compose_close   (Compose *compose);
503
504 static GtkItemFactoryEntry compose_popup_entries[] =
505 {
506         {N_("/_Add..."),        NULL, compose_attach_cb, 0, NULL},
507         {N_("/_Remove"),        NULL, compose_attach_remove_selected, 0, NULL},
508         {N_("/---"),            NULL, NULL, 0, "<Separator>"},
509         {N_("/_Properties..."), NULL, compose_attach_property, 0, NULL}
510 };
511
512 static GtkItemFactoryEntry compose_entries[] =
513 {
514         {N_("/_Message"),                               NULL, NULL, 0, "<Branch>"},
515         {N_("/_Message/_Send"),         "<control>Return",
516                                         compose_send_cb, 0, NULL},
517         {N_("/_Message/Send _later"),   "<shift><control>S",
518                                         compose_send_later_cb,  0, NULL},
519         {N_("/_Message/---"),                   NULL, NULL, 0, "<Separator>"},
520         {N_("/_Message/_Attach file"),          "<control>M", compose_attach_cb,      0, NULL},
521         {N_("/_Message/_Insert file"),          "<control>I", compose_insert_file_cb, 0, NULL},
522         {N_("/_Message/Insert si_gnature"),     "<control>G", compose_insert_sig_cb,  0, NULL},
523         {N_("/_Message/---"),                   NULL, NULL, 0, "<Separator>"},
524         {N_("/_Message/_Save"),
525                                                 "<control>S", compose_draft_cb, COMPOSE_KEEP_EDITING, NULL},
526         {N_("/_Message/---"),                   NULL, NULL, 0, "<Separator>"},
527         {N_("/_Message/_Close"),                        "<control>W", compose_close_cb, 0, NULL},
528
529         {N_("/_Edit"),                  NULL, NULL, 0, "<Branch>"},
530         {N_("/_Edit/_Undo"),            "<control>Z", compose_undo_cb, 0, NULL},
531         {N_("/_Edit/_Redo"),            "<control>Y", compose_redo_cb, 0, NULL},
532         {N_("/_Edit/---"),              NULL, NULL, 0, "<Separator>"},
533         {N_("/_Edit/Cu_t"),             "<control>X", compose_cut_cb,    0, NULL},
534         {N_("/_Edit/_Copy"),            "<control>C", compose_copy_cb,   0, NULL},
535         {N_("/_Edit/_Paste"),           "<control>V", compose_paste_cb,  0, NULL},
536         {N_("/_Edit/Special paste"),    NULL, NULL, 0, "<Branch>"},
537         {N_("/_Edit/Special paste/as _quotation"),
538                                         NULL, compose_paste_as_quote_cb, 0, NULL},
539         {N_("/_Edit/Special paste/_wrapped"),
540                                         NULL, compose_paste_wrap_cb, 0, NULL},
541         {N_("/_Edit/Special paste/_unwrapped"),
542                                         NULL, compose_paste_no_wrap_cb, 0, NULL},
543         {N_("/_Edit/Select _all"),      "<control>A", compose_allsel_cb, 0, NULL},
544         {N_("/_Edit/A_dvanced"),        NULL, NULL, 0, "<Branch>"},
545         {N_("/_Edit/A_dvanced/Move a character backward"),
546                                         "<control>B",
547                                         compose_advanced_action_cb,
548                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BACKWARD_CHARACTER,
549                                         NULL},
550         {N_("/_Edit/A_dvanced/Move a character forward"),
551                                         "<control>F",
552                                         compose_advanced_action_cb,
553                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_FORWARD_CHARACTER,
554                                         NULL},
555         {N_("/_Edit/A_dvanced/Move a word backward"),
556                                         NULL, /* "<alt>B" */
557                                         compose_advanced_action_cb,
558                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BACKWARD_WORD,
559                                         NULL},
560         {N_("/_Edit/A_dvanced/Move a word forward"),
561                                         NULL, /* "<alt>F" */
562                                         compose_advanced_action_cb,
563                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_FORWARD_WORD,
564                                         NULL},
565         {N_("/_Edit/A_dvanced/Move to beginning of line"),
566                                         NULL, /* "<control>A" */
567                                         compose_advanced_action_cb,
568                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_BEGINNING_OF_LINE,
569                                         NULL},
570         {N_("/_Edit/A_dvanced/Move to end of line"),
571                                         "<control>E",
572                                         compose_advanced_action_cb,
573                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_END_OF_LINE,
574                                         NULL},
575         {N_("/_Edit/A_dvanced/Move to previous line"),
576                                         "<control>P",
577                                         compose_advanced_action_cb,
578                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_PREVIOUS_LINE,
579                                         NULL},
580         {N_("/_Edit/A_dvanced/Move to next line"),
581                                         "<control>N",
582                                         compose_advanced_action_cb,
583                                         COMPOSE_CALL_ADVANCED_ACTION_MOVE_NEXT_LINE,
584                                         NULL},
585         {N_("/_Edit/A_dvanced/Delete a character backward"),
586                                         "<control>H",
587                                         compose_advanced_action_cb,
588                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_BACKWARD_CHARACTER,
589                                         NULL},
590         {N_("/_Edit/A_dvanced/Delete a character forward"),
591                                         "<control>D",
592                                         compose_advanced_action_cb,
593                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_FORWARD_CHARACTER,
594                                         NULL},
595         {N_("/_Edit/A_dvanced/Delete a word backward"),
596                                         NULL, /* "<control>W" */
597                                         compose_advanced_action_cb,
598                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_BACKWARD_WORD,
599                                         NULL},
600         {N_("/_Edit/A_dvanced/Delete a word forward"),
601                                         NULL, /* "<alt>D", */
602                                         compose_advanced_action_cb,
603                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_FORWARD_WORD,
604                                         NULL},
605         {N_("/_Edit/A_dvanced/Delete line"),
606                                         "<control>U",
607                                         compose_advanced_action_cb,
608                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_LINE,
609                                         NULL},
610         {N_("/_Edit/A_dvanced/Delete entire line"),
611                                         NULL,
612                                         compose_advanced_action_cb,
613                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_LINE_N,
614                                         NULL},
615         {N_("/_Edit/A_dvanced/Delete to end of line"),
616                                         "<control>K",
617                                         compose_advanced_action_cb,
618                                         COMPOSE_CALL_ADVANCED_ACTION_DELETE_TO_LINE_END,
619                                         NULL},
620         {N_("/_Edit/---"),              NULL, NULL, 0, "<Separator>"},
621         {N_("/_Edit/_Wrap current paragraph"),
622                                         "<control>L", compose_wrap_cb, 0, NULL},
623         {N_("/_Edit/Wrap all long _lines"),
624                                         "<control><alt>L", compose_wrap_cb, 1, NULL},
625         {N_("/_Edit/Aut_o wrapping"),   "<shift><control>L", compose_toggle_autowrap_cb, 0, "<ToggleItem>"},
626         {N_("/_Edit/---"),              NULL, NULL, 0, "<Separator>"},
627         {N_("/_Edit/Edit with e_xternal editor"),
628                                         "<shift><control>X", compose_ext_editor_cb, 0, NULL},
629 #if USE_ASPELL
630         {N_("/_Spelling"),              NULL, NULL, 0, "<Branch>"},
631         {N_("/_Spelling/_Check all or check selection"),
632                                         NULL, compose_check_all, 0, NULL},
633         {N_("/_Spelling/_Highlight all misspelled words"),
634                                         NULL, compose_highlight_all, 0, NULL},
635         {N_("/_Spelling/Check _backwards misspelled word"),
636                                         NULL, compose_check_backwards , 0, NULL},
637         {N_("/_Spelling/_Forward to next misspelled word"),
638                                         NULL, compose_check_forwards_go, 0, NULL},
639 #endif
640         {N_("/_Options"),               NULL, NULL, 0, "<Branch>"},
641         {N_("/_Options/Privacy System"),                NULL, NULL,   0, "<Branch>"},
642         {N_("/_Options/Privacy System/None"),   NULL, NULL,   0, "<RadioItem>"},
643         {N_("/_Options/Si_gn"),         NULL, compose_toggle_sign_cb   , 0, "<ToggleItem>"},
644         {N_("/_Options/_Encrypt"),      NULL, compose_toggle_encrypt_cb, 0, "<ToggleItem>"},
645         {N_("/_Options/---"),           NULL,           NULL,   0, "<Separator>"},
646         {N_("/_Options/_Priority"),     NULL,           NULL,   0, "<Branch>"},
647         {N_("/_Options/Priority/_Highest"), NULL, compose_set_priority_cb, PRIORITY_HIGHEST, "<RadioItem>"},
648         {N_("/_Options/Priority/Hi_gh"),    NULL, compose_set_priority_cb, PRIORITY_HIGH, "/Options/Priority/Highest"},
649         {N_("/_Options/Priority/_Normal"),  NULL, compose_set_priority_cb, PRIORITY_NORMAL, "/Options/Priority/Highest"},
650         {N_("/_Options/Priority/Lo_w"),    NULL, compose_set_priority_cb, PRIORITY_LOW, "/Options/Priority/Highest"},
651         {N_("/_Options/Priority/_Lowest"),  NULL, compose_set_priority_cb, PRIORITY_LOWEST, "/Options/Priority/Highest"},
652         {N_("/_Options/---"),           NULL,           NULL,   0, "<Separator>"},
653         {N_("/_Options/_Request Return Receipt"),       NULL, compose_toggle_return_receipt_cb, 0, "<ToggleItem>"},
654         {N_("/_Options/---"),           NULL,           NULL,   0, "<Separator>"},
655         {N_("/_Options/Remo_ve references"),    NULL, compose_toggle_remove_refs_cb, 0, "<ToggleItem>"},
656         {N_("/_Options/---"),           NULL,           NULL,   0, "<Separator>"},
657
658 #define ENC_ACTION(action) \
659         NULL, compose_set_encoding_cb, action, \
660         "/Options/Character encoding/Automatic"
661
662         {N_("/_Options/Character _encoding"), NULL, NULL, 0, "<Branch>"},
663         {N_("/_Options/Character _encoding/_Automatic"),
664                         NULL, compose_set_encoding_cb, C_AUTO, "<RadioItem>"},
665         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
666
667         {N_("/_Options/Character _encoding/7bit ascii (US-ASC_II)"),
668          ENC_ACTION(C_US_ASCII)},
669         {N_("/_Options/Character _encoding/Unicode (_UTF-8)"),
670          ENC_ACTION(C_UTF_8)},
671         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
672
673         {N_("/_Options/Character _encoding/Western European (ISO-8859-_1)"),
674          ENC_ACTION(C_ISO_8859_1)},
675         {N_("/_Options/Character _encoding/Western European (ISO-8859-15)"),
676          ENC_ACTION(C_ISO_8859_15)},
677         {N_("/_Options/Character _encoding/Western European (Windows-1252)"),
678          ENC_ACTION(C_WINDOWS_1252)},
679         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
680
681         {N_("/_Options/Character _encoding/Central European (ISO-8859-_2)"),
682          ENC_ACTION(C_ISO_8859_2)},
683         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
684
685         {N_("/_Options/Character _encoding/_Baltic (ISO-8859-13)"),
686          ENC_ACTION(C_ISO_8859_13)},
687         {N_("/_Options/Character _encoding/Baltic (ISO-8859-_4)"),
688          ENC_ACTION(C_ISO_8859_4)},
689         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
690
691         {N_("/_Options/Character _encoding/Greek (ISO-8859-_7)"),
692          ENC_ACTION(C_ISO_8859_7)},
693         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
694
695         {N_("/_Options/Character _encoding/Hebrew (ISO-8859-_8)"),
696          ENC_ACTION(C_ISO_8859_8)},
697         {N_("/_Options/Character _encoding/Hebrew (Windows-1255)"),
698          ENC_ACTION(C_WINDOWS_1255)},
699         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
700
701         {N_("/_Options/Character _encoding/Arabic (ISO-8859-_6)"),
702          ENC_ACTION(C_ISO_8859_6)},
703         {N_("/_Options/Character _encoding/Arabic (Windows-1256)"),
704          ENC_ACTION(C_CP1256)},
705         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
706
707         {N_("/_Options/Character _encoding/Turkish (ISO-8859-_9)"),
708          ENC_ACTION(C_ISO_8859_9)},
709         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
710
711         {N_("/_Options/Character _encoding/Cyrillic (ISO-8859-_5)"),
712          ENC_ACTION(C_ISO_8859_5)},
713         {N_("/_Options/Character _encoding/Cyrillic (KOI8-_R)"),
714          ENC_ACTION(C_KOI8_R)},
715         {N_("/_Options/Character _encoding/Cyrillic (KOI8-U)"),
716          ENC_ACTION(C_KOI8_U)},
717         {N_("/_Options/Character _encoding/Cyrillic (Windows-1251)"),
718          ENC_ACTION(C_WINDOWS_1251)},
719         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
720
721         {N_("/_Options/Character _encoding/Japanese (ISO-2022-_JP)"),
722          ENC_ACTION(C_ISO_2022_JP)},
723         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
724
725         {N_("/_Options/Character _encoding/Simplified Chinese (_GB2312)"),
726          ENC_ACTION(C_GB2312)},
727         {N_("/_Options/Character _encoding/Simplified Chinese (GBK)"),
728          ENC_ACTION(C_GBK)},
729         {N_("/_Options/Character _encoding/Traditional Chinese (_Big5)"),
730          ENC_ACTION(C_BIG5)},
731         {N_("/_Options/Character _encoding/Traditional Chinese (EUC-_TW)"),
732          ENC_ACTION(C_EUC_TW)},
733         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
734
735         {N_("/_Options/Character _encoding/Korean (EUC-_KR)"),
736          ENC_ACTION(C_EUC_KR)},
737         {N_("/_Options/Character _encoding/---"), NULL, NULL, 0, "<Separator>"},
738
739         {N_("/_Options/Character _encoding/Thai (TIS-620)"),
740          ENC_ACTION(C_TIS_620)},
741         {N_("/_Options/Character _encoding/Thai (Windows-874)"),
742          ENC_ACTION(C_WINDOWS_874)},
743
744         {N_("/_Tools"),                 NULL, NULL, 0, "<Branch>"},
745         {N_("/_Tools/Show _ruler"),     NULL, compose_toggle_ruler_cb, 0, "<ToggleItem>"},
746         {N_("/_Tools/_Address book"),   "<shift><control>A", compose_address_cb , 0, NULL},
747         {N_("/_Tools/_Template"),       NULL, NULL, 0, "<Branch>"},
748         {N_("/_Tools/Actio_ns"),        NULL, NULL, 0, "<Branch>"},
749         {N_("/_Help"),                  NULL, NULL, 0, "<Branch>"},
750         {N_("/_Help/_About"),           NULL, about_show, 0, NULL}
751 };
752
753 static GtkTargetEntry compose_mime_types[] =
754 {
755         {"text/uri-list", 0, 0},
756         {"text/plain", 0, 0},
757         {"STRING", 0, 0}
758 };
759
760 static gboolean compose_put_existing_to_front(MsgInfo *info)
761 {
762         GList *compose_list = compose_get_compose_list();
763         GList *elem = NULL;
764         
765         if (compose_list) {
766                 for (elem = compose_list; elem != NULL && elem->data != NULL; 
767                      elem = elem->next) {
768                         Compose *c = (Compose*)elem->data;
769
770                         if (!c->targetinfo || !c->targetinfo->msgid ||
771                             !info->msgid)
772                                 continue;
773
774                         if (!strcmp(c->targetinfo->msgid, info->msgid)) {
775                                 gtkut_window_popup(c->window);
776                                 return TRUE;
777                         }
778                 }
779         }
780         return FALSE;
781 }
782
783 static GdkColor quote_color = 
784         {(gulong)0, (gushort)0, (gushort)0, (gushort)0};
785
786 static GdkColor signature_color = {
787         (gulong)0,
788         (gushort)0x7fff,
789         (gushort)0x7fff,
790         (gushort)0x7fff
791 };
792
793 static GdkColor uri_color = {
794         (gulong)0,
795         (gushort)0,
796         (gushort)0,
797         (gushort)0
798 };
799
800 static void compose_create_tags(GtkTextView *text, Compose *compose)
801 {
802         GtkTextBuffer *buffer;
803         GdkColor black = {(gulong)0, (gushort)0, (gushort)0, (gushort)0};
804
805         buffer = gtk_text_view_get_buffer(text);
806         
807         if (prefs_common.enable_color) {
808                 /* grab the quote colors, converting from an int to a GdkColor */
809                 gtkut_convert_int_to_gdk_color(prefs_common.quote_level1_col,
810                                                &quote_color);
811                 gtkut_convert_int_to_gdk_color(prefs_common.signature_col,
812                                                &signature_color);
813                 gtkut_convert_int_to_gdk_color(prefs_common.uri_col,
814                                                &uri_color);
815         } else {
816                 signature_color = quote_color = uri_color = black;
817         }
818
819         gtk_text_buffer_create_tag(buffer, "quote",
820                                    "foreground-gdk", &quote_color,
821                                    NULL);
822         gtk_text_buffer_create_tag(buffer, "signature",
823                                    "foreground-gdk", &signature_color,
824                                    NULL);
825         gtk_text_buffer_create_tag(buffer, "link",
826                                          "foreground-gdk", &uri_color,
827                                          NULL);
828         compose->no_wrap_tag = gtk_text_buffer_create_tag(buffer, "no_wrap", NULL);
829         compose->no_join_tag = gtk_text_buffer_create_tag(buffer, "no_join", NULL);
830 }
831
832 Compose *compose_new(PrefsAccount *account, const gchar *mailto,
833                      GPtrArray *attach_files)
834 {
835         return compose_generic_new(account, mailto, NULL, attach_files, NULL);
836 }
837
838 Compose *compose_new_with_folderitem(PrefsAccount *account, FolderItem *item)
839 {
840         return compose_generic_new(account, NULL, item, NULL, NULL);
841 }
842
843 Compose *compose_new_with_list( PrefsAccount *account, GList *listAddress )
844 {
845         return compose_generic_new( account, NULL, NULL, NULL, listAddress );
846 }
847
848 Compose *compose_generic_new(PrefsAccount *account, const gchar *mailto, FolderItem *item,
849                              GPtrArray *attach_files, GList *listAddress )
850 {
851         Compose *compose;
852         GtkTextView *textview;
853         GtkTextBuffer *textbuf;
854         GtkTextIter iter;
855         GtkItemFactory *ifactory;
856
857         if (item && item->prefs && item->prefs->enable_default_account)
858                 account = account_find_from_id(item->prefs->default_account);
859
860         if (!account) account = cur_account;
861         g_return_val_if_fail(account != NULL, NULL);
862
863         compose = compose_create(account, COMPOSE_NEW);
864         ifactory = gtk_item_factory_from_widget(compose->menubar);
865
866         compose->replyinfo = NULL;
867         compose->fwdinfo   = NULL;
868
869         textview = GTK_TEXT_VIEW(compose->text);
870         textbuf = gtk_text_view_get_buffer(textview);
871         compose_create_tags(textview, compose);
872
873         undo_block(compose->undostruct);
874 #ifdef USE_ASPELL
875         if (item && item->prefs && item->prefs->enable_default_dictionary &&
876             compose->gtkaspell) 
877                 gtkaspell_change_dict(compose->gtkaspell, 
878                     item->prefs->default_dictionary);
879 #endif
880
881         if (account->auto_sig)
882                 compose_insert_sig(compose, FALSE);
883         gtk_text_buffer_get_start_iter(textbuf, &iter);
884         gtk_text_buffer_place_cursor(textbuf, &iter);
885
886         if (account->protocol != A_NNTP) {
887                 if (mailto && *mailto != '\0') {
888                         compose_entries_set(compose, mailto);
889
890                 } else if (item && item->prefs->enable_default_to) {
891                         compose_entry_append(compose, item->prefs->default_to, COMPOSE_TO);
892                         compose_entry_mark_default_to(compose, item->prefs->default_to);
893                 }
894                 if (item && item->ret_rcpt) {
895                         menu_set_active(ifactory, "/Options/Request Return Receipt", TRUE);
896                 }
897         } else {
898                 if (mailto) {
899                         compose_entry_append(compose, mailto, COMPOSE_NEWSGROUPS);
900                 } else if (item) {
901                         compose_entry_append(compose, item->path, COMPOSE_NEWSGROUPS);
902                 }
903                 /*
904                  * CLAWS: just don't allow return receipt request, even if the user
905                  * may want to send an email. simple but foolproof.
906                  */
907                 menu_set_sensitive(ifactory, "/Options/Request Return Receipt", FALSE); 
908         }
909         compose_add_field_list( compose, listAddress );
910
911         if (attach_files) {
912                 gint i;
913                 gchar *file;
914
915                 for (i = 0; i < attach_files->len; i++) {
916                         file = g_ptr_array_index(attach_files, i);
917                         compose_attach_append(compose, file, file, NULL);
918                 }
919         }
920
921         compose_show_first_last_header(compose, TRUE);
922
923         /* Set save folder */
924         if (item && item->prefs && item->prefs->save_copy_to_folder) {
925                 gchar *folderidentifier;
926
927                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), prefs_common.savemsg);
928                 folderidentifier = folder_item_get_identifier(item);
929                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
930                 g_free(folderidentifier);
931         }
932         
933         gtk_widget_grab_focus(compose->header_last->entry);
934
935         undo_unblock(compose->undostruct);
936
937         if (prefs_common.auto_exteditor)
938                 compose_exec_ext_editor(compose);
939
940         compose->modified = FALSE;
941         compose_set_title(compose);
942         return compose;
943 }
944
945 static void compose_force_encryption(Compose *compose, PrefsAccount *account,
946                 gboolean override_pref)
947 {
948         gchar *privacy = NULL;
949
950         g_return_if_fail(compose != NULL);
951         g_return_if_fail(account != NULL);
952
953         if (override_pref == FALSE && account->default_encrypt_reply == FALSE)
954                 return;
955
956         if (account->default_privacy_system
957         &&  strlen(account->default_privacy_system)) {
958                 privacy = account->default_privacy_system;
959         } else {
960                 GSList *privacy_avail = privacy_get_system_ids();
961                 if (privacy_avail && g_slist_length(privacy_avail)) {
962                         privacy = (gchar *)(privacy_avail->data);
963                 }
964         }
965         if (privacy != NULL) {
966                 compose->privacy_system = g_strdup(privacy);
967                 compose_update_privacy_system_menu_item(compose, FALSE);
968                 compose_use_encryption(compose, TRUE);
969         }
970 }       
971
972 static void compose_force_signing(Compose *compose, PrefsAccount *account)
973 {
974         gchar *privacy = NULL;
975
976         if (account->default_privacy_system
977         &&  strlen(account->default_privacy_system)) {
978                 privacy = account->default_privacy_system;
979         } else {
980                 GSList *privacy_avail = privacy_get_system_ids();
981                 if (privacy_avail && g_slist_length(privacy_avail)) {
982                         privacy = (gchar *)(privacy_avail->data);
983                 }
984         }
985         if (privacy != NULL) {
986                 compose->privacy_system = g_strdup(privacy);
987                 compose_update_privacy_system_menu_item(compose, FALSE);
988                 compose_use_signing(compose, TRUE);
989         }
990 }       
991
992 Compose *compose_reply_mode(ComposeMode mode, GSList *msginfo_list, gchar *body)
993 {
994         MsgInfo *msginfo;
995         guint list_len;
996         Compose *compose = NULL;
997         g_return_val_if_fail(msginfo_list != NULL, NULL);
998
999         msginfo = (MsgInfo*)g_slist_nth_data(msginfo_list, 0);
1000         g_return_val_if_fail(msginfo != NULL, NULL);
1001
1002         list_len = g_slist_length(msginfo_list);
1003
1004         switch (mode) {
1005         case COMPOSE_REPLY:
1006                 compose = compose_reply(msginfo, prefs_common.reply_with_quote,
1007                               FALSE, prefs_common.default_reply_list, FALSE, body);
1008                 break;
1009         case COMPOSE_REPLY_WITH_QUOTE:
1010                 compose = compose_reply(msginfo, TRUE, 
1011                         FALSE, prefs_common.default_reply_list, FALSE, body);
1012                 break;
1013         case COMPOSE_REPLY_WITHOUT_QUOTE:
1014                 compose = compose_reply(msginfo, FALSE, 
1015                         FALSE, prefs_common.default_reply_list, FALSE, NULL);
1016                 break;
1017         case COMPOSE_REPLY_TO_SENDER:
1018                 compose = compose_reply(msginfo, prefs_common.reply_with_quote,
1019                               FALSE, FALSE, TRUE, body);
1020                 break;
1021         case COMPOSE_FOLLOWUP_AND_REPLY_TO:
1022                 compose = compose_followup_and_reply_to(msginfo,
1023                                               prefs_common.reply_with_quote,
1024                                               FALSE, FALSE, body);
1025                 break;
1026         case COMPOSE_REPLY_TO_SENDER_WITH_QUOTE:
1027                 compose = compose_reply(msginfo, TRUE, 
1028                         FALSE, FALSE, TRUE, body);
1029                 break;
1030         case COMPOSE_REPLY_TO_SENDER_WITHOUT_QUOTE:
1031                 compose = compose_reply(msginfo, FALSE, 
1032                         FALSE, FALSE, TRUE, NULL);
1033                 break;
1034         case COMPOSE_REPLY_TO_ALL:
1035                 compose = compose_reply(msginfo, prefs_common.reply_with_quote,
1036                         TRUE, FALSE, FALSE, body);
1037                 break;
1038         case COMPOSE_REPLY_TO_ALL_WITH_QUOTE:
1039                 compose = compose_reply(msginfo, TRUE, 
1040                         TRUE, FALSE, FALSE, body);
1041                 break;
1042         case COMPOSE_REPLY_TO_ALL_WITHOUT_QUOTE:
1043                 compose = compose_reply(msginfo, FALSE, 
1044                         TRUE, FALSE, FALSE, NULL);
1045                 break;
1046         case COMPOSE_REPLY_TO_LIST:
1047                 compose = compose_reply(msginfo, prefs_common.reply_with_quote,
1048                         FALSE, TRUE, FALSE, body);
1049                 break;
1050         case COMPOSE_REPLY_TO_LIST_WITH_QUOTE:
1051                 compose = compose_reply(msginfo, TRUE, 
1052                         FALSE, TRUE, FALSE, body);
1053                 break;
1054         case COMPOSE_REPLY_TO_LIST_WITHOUT_QUOTE:
1055                 compose = compose_reply(msginfo, FALSE, 
1056                         FALSE, TRUE, FALSE, NULL);
1057                 break;
1058         case COMPOSE_FORWARD:
1059                 if (prefs_common.forward_as_attachment) {
1060                         compose = compose_reply_mode(COMPOSE_FORWARD_AS_ATTACH, msginfo_list, body);
1061                         return compose;
1062                 } else {
1063                         compose = compose_reply_mode(COMPOSE_FORWARD_INLINE, msginfo_list, body);
1064                         return compose;
1065                 }
1066                 break;
1067         case COMPOSE_FORWARD_INLINE:
1068                 /* check if we reply to more than one Message */
1069                 if (list_len == 1) {
1070                         compose = compose_forward(NULL, msginfo, FALSE, body, FALSE);
1071                         break;
1072                 } 
1073                 /* more messages FALL THROUGH */
1074         case COMPOSE_FORWARD_AS_ATTACH:
1075                 compose = compose_forward_multiple(NULL, msginfo_list);
1076                 break;
1077         case COMPOSE_REDIRECT:
1078                 compose = compose_redirect(NULL, msginfo);
1079                 break;
1080         default:
1081                 g_warning("compose_reply(): invalid Compose Mode: %d\n", mode);
1082         }
1083         return compose;
1084 }
1085
1086 Compose *compose_reply(MsgInfo *msginfo, gboolean quote, gboolean to_all,
1087                    gboolean to_ml, gboolean to_sender, 
1088                    const gchar *body)
1089 {
1090         return compose_generic_reply(msginfo, quote, to_all, to_ml, 
1091                               to_sender, FALSE, body);
1092 }
1093
1094 Compose *compose_followup_and_reply_to(MsgInfo *msginfo, gboolean quote,
1095                                    gboolean to_all,
1096                                    gboolean to_sender,
1097                                    const gchar *body)
1098 {
1099         return compose_generic_reply(msginfo, quote, to_all, FALSE, 
1100                               to_sender, TRUE, body);
1101 }
1102
1103 static void compose_extract_original_charset(Compose *compose)
1104 {
1105         MsgInfo *info = NULL;
1106         if (compose->replyinfo) {
1107                 info = compose->replyinfo;
1108         } else if (compose->fwdinfo) {
1109                 info = compose->fwdinfo;
1110         } else if (compose->targetinfo) {
1111                 info = compose->targetinfo;
1112         }
1113         if (info) {
1114                 MimeInfo *mimeinfo = procmime_scan_message(info);
1115                 MimeInfo *partinfo = mimeinfo;
1116                 while (partinfo && partinfo->type != MIMETYPE_TEXT)
1117                         partinfo = procmime_mimeinfo_next(partinfo);
1118                 if (partinfo) {
1119                         compose->orig_charset = 
1120                                 g_strdup(procmime_mimeinfo_get_parameter(
1121                                                 partinfo, "charset"));
1122                 }
1123                 procmime_mimeinfo_free_all(mimeinfo);
1124         }
1125 }
1126
1127 #define SIGNAL_BLOCK(buffer) {                                  \
1128         g_signal_handlers_block_by_func(G_OBJECT(buffer),       \
1129                                 G_CALLBACK(compose_changed_cb), \
1130                                 compose);                       \
1131         g_signal_handlers_block_by_func(G_OBJECT(buffer),       \
1132                                 G_CALLBACK(text_inserted),      \
1133                                 compose);                       \
1134 }
1135
1136 #define SIGNAL_UNBLOCK(buffer) {                                \
1137         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),     \
1138                                 G_CALLBACK(compose_changed_cb), \
1139                                 compose);                       \
1140         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),     \
1141                                 G_CALLBACK(text_inserted),      \
1142                                 compose);                       \
1143 }
1144
1145 static Compose *compose_generic_reply(MsgInfo *msginfo, gboolean quote,
1146                                   gboolean to_all, gboolean to_ml,
1147                                   gboolean to_sender,
1148                                   gboolean followup_and_reply_to,
1149                                   const gchar *body)
1150 {
1151         GtkItemFactory *ifactory;
1152         Compose *compose;
1153         PrefsAccount *account = NULL;
1154         PrefsAccount *reply_account;
1155         GtkTextView *textview;
1156         GtkTextBuffer *textbuf;
1157
1158         g_return_val_if_fail(msginfo != NULL, NULL);
1159         g_return_val_if_fail(msginfo->folder != NULL, NULL);
1160
1161         account = account_get_reply_account(msginfo, prefs_common.reply_account_autosel);
1162         
1163         g_return_val_if_fail(account != NULL, NULL);
1164
1165         if (to_sender && account->protocol == A_NNTP &&
1166             !followup_and_reply_to) {
1167                 reply_account =
1168                         account_find_from_address(account->address);
1169                 if (!reply_account)
1170                         reply_account = compose_current_mail_account();
1171                 if (!reply_account)
1172                         return NULL;
1173         } else
1174                 reply_account = account;
1175
1176         compose = compose_create(account, COMPOSE_REPLY);
1177         ifactory = gtk_item_factory_from_widget(compose->menubar);
1178
1179         menu_set_active(ifactory, "/Options/Remove references", FALSE);
1180         menu_set_sensitive(ifactory, "/Options/Remove references", TRUE);
1181
1182         compose->replyinfo = procmsg_msginfo_get_full_info(msginfo);
1183
1184         if (!compose->replyinfo)
1185                 compose->replyinfo = procmsg_msginfo_copy(msginfo);
1186         
1187         compose_extract_original_charset(compose);
1188         
1189         if (msginfo->folder && msginfo->folder->ret_rcpt)
1190                 menu_set_active(ifactory, "/Options/Request Return Receipt", TRUE);
1191
1192         /* Set save folder */
1193         if (msginfo->folder && msginfo->folder->prefs && msginfo->folder->prefs->save_copy_to_folder) {
1194                 gchar *folderidentifier;
1195
1196                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), TRUE);
1197                 folderidentifier = folder_item_get_identifier(msginfo->folder);
1198                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
1199                 g_free(folderidentifier);
1200         }
1201
1202         if (compose_parse_header(compose, msginfo) < 0) return NULL;
1203         compose_reply_set_entry(compose, msginfo, to_all, to_ml, 
1204                                 to_sender, followup_and_reply_to);
1205         compose_show_first_last_header(compose, TRUE);
1206
1207         textview = (GTK_TEXT_VIEW(compose->text));
1208         textbuf = gtk_text_view_get_buffer(textview);
1209         compose_create_tags(textview, compose);
1210
1211         undo_block(compose->undostruct);
1212 #ifdef USE_ASPELL
1213         if (msginfo->folder && msginfo->folder->prefs && 
1214             msginfo->folder->prefs && 
1215             msginfo->folder->prefs->enable_default_dictionary &&
1216             compose->gtkaspell)
1217                 gtkaspell_change_dict(compose->gtkaspell, 
1218                     msginfo->folder->prefs->default_dictionary);
1219 #endif
1220
1221         if (quote) {
1222                 gchar *qmark;
1223
1224                 if (prefs_common.quotemark && *prefs_common.quotemark)
1225                         qmark = prefs_common.quotemark;
1226                 else
1227                         qmark = "> ";
1228
1229                 compose_quote_fmt(compose, compose->replyinfo,
1230                                   prefs_common.quotefmt,
1231                                   qmark, body, FALSE);
1232         }
1233         if (procmime_msginfo_is_encrypted(compose->replyinfo)) {
1234                 compose_force_encryption(compose, account, FALSE);
1235         }
1236
1237         SIGNAL_BLOCK(textbuf);
1238         
1239         if (account->auto_sig)
1240                 compose_insert_sig(compose, FALSE);
1241
1242         compose_wrap_all(compose);
1243
1244         SIGNAL_UNBLOCK(textbuf);
1245         
1246         gtk_widget_grab_focus(compose->text);
1247
1248         undo_unblock(compose->undostruct);
1249
1250         if (prefs_common.auto_exteditor)
1251                 compose_exec_ext_editor(compose);
1252                 
1253         compose->modified = FALSE;
1254         compose_set_title(compose);
1255         return compose;
1256 }
1257
1258 #define INSERT_FW_HEADER(var, hdr) \
1259 if (msginfo->var && *msginfo->var) { \
1260         gtk_stext_insert(text, NULL, NULL, NULL, hdr, -1); \
1261         gtk_stext_insert(text, NULL, NULL, NULL, msginfo->var, -1); \
1262         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1); \
1263 }
1264
1265 Compose *compose_forward(PrefsAccount *account, MsgInfo *msginfo,
1266                          gboolean as_attach, const gchar *body,
1267                          gboolean no_extedit)
1268 {
1269         Compose *compose;
1270         GtkTextView *textview;
1271         GtkTextBuffer *textbuf;
1272         GtkTextIter iter;
1273
1274         g_return_val_if_fail(msginfo != NULL, NULL);
1275         g_return_val_if_fail(msginfo->folder != NULL, NULL);
1276
1277         if (!account && 
1278             !(account = compose_guess_forward_account_from_msginfo
1279                                 (msginfo)))
1280                 account = cur_account;
1281
1282         compose = compose_create(account, COMPOSE_FORWARD);
1283
1284         compose->fwdinfo = procmsg_msginfo_get_full_info(msginfo);
1285         if (!compose->fwdinfo)
1286                 compose->fwdinfo = procmsg_msginfo_copy(msginfo);
1287
1288         compose_extract_original_charset(compose);
1289
1290         if (msginfo->subject && *msginfo->subject) {
1291                 gchar *buf, *buf2, *p;
1292
1293                 buf = p = g_strdup(msginfo->subject);
1294                 p += subject_get_prefix_length(p);
1295                 memmove(buf, p, strlen(p) + 1);
1296
1297                 buf2 = g_strdup_printf("Fw: %s", buf);
1298                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), buf2);
1299                 
1300                 g_free(buf);
1301                 g_free(buf2);
1302         }
1303
1304         textview = GTK_TEXT_VIEW(compose->text);
1305         textbuf = gtk_text_view_get_buffer(textview);
1306         compose_create_tags(textview, compose);
1307         
1308         undo_block(compose->undostruct);
1309         if (as_attach) {
1310                 gchar *msgfile;
1311
1312                 msgfile = procmsg_get_message_file_path(msginfo);
1313                 if (!is_file_exist(msgfile))
1314                         g_warning("%s: file not exist\n", msgfile);
1315                 else
1316                         compose_attach_append(compose, msgfile, msgfile,
1317                                               "message/rfc822");
1318
1319                 g_free(msgfile);
1320         } else {
1321                 gchar *qmark;
1322                 MsgInfo *full_msginfo;
1323
1324                 full_msginfo = procmsg_msginfo_get_full_info(msginfo);
1325                 if (!full_msginfo)
1326                         full_msginfo = procmsg_msginfo_copy(msginfo);
1327
1328                 if (prefs_common.fw_quotemark &&
1329                     *prefs_common.fw_quotemark)
1330                         qmark = prefs_common.fw_quotemark;
1331                 else
1332                         qmark = "> ";
1333
1334                 compose_quote_fmt(compose, full_msginfo,
1335                                   prefs_common.fw_quotefmt,
1336                                   qmark, body, FALSE);
1337                 compose_attach_parts(compose, msginfo);
1338
1339                 procmsg_msginfo_free(full_msginfo);
1340         }
1341
1342         SIGNAL_BLOCK(textbuf);
1343
1344         if (account->auto_sig)
1345                 compose_insert_sig(compose, FALSE);
1346
1347         compose_wrap_all(compose);
1348
1349         SIGNAL_UNBLOCK(textbuf);
1350         
1351         gtk_text_buffer_get_start_iter(textbuf, &iter);
1352         gtk_text_buffer_place_cursor(textbuf, &iter);
1353
1354         gtk_widget_grab_focus(compose->header_last->entry);
1355
1356         if (!no_extedit && prefs_common.auto_exteditor)
1357                 compose_exec_ext_editor(compose);
1358         
1359         /*save folder*/
1360         if (msginfo->folder && msginfo->folder->prefs && msginfo->folder->prefs->save_copy_to_folder) {
1361                 gchar *folderidentifier;
1362
1363                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), TRUE);
1364                 folderidentifier = folder_item_get_identifier(msginfo->folder);
1365                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
1366                 g_free(folderidentifier);
1367         }
1368
1369         undo_unblock(compose->undostruct);
1370         
1371         compose->modified = FALSE;
1372         compose_set_title(compose);
1373         return compose;
1374 }
1375
1376 #undef INSERT_FW_HEADER
1377
1378 Compose *compose_forward_multiple(PrefsAccount *account, GSList *msginfo_list)
1379 {
1380         Compose *compose;
1381         GtkTextView *textview;
1382         GtkTextBuffer *textbuf;
1383         GtkTextIter iter;
1384         GSList *msginfo;
1385         gchar *msgfile;
1386         gboolean single_mail = TRUE;
1387         
1388         g_return_val_if_fail(msginfo_list != NULL, NULL);
1389
1390         if (g_slist_length(msginfo_list) > 1)
1391                 single_mail = FALSE;
1392
1393         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next)
1394                 if (((MsgInfo *)msginfo->data)->folder == NULL)
1395                         return NULL;
1396
1397         /* guess account from first selected message */
1398         if (!account && 
1399             !(account = compose_guess_forward_account_from_msginfo
1400                                 (msginfo_list->data)))
1401                 account = cur_account;
1402
1403         g_return_val_if_fail(account != NULL, NULL);
1404
1405         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1406                 MSG_UNSET_PERM_FLAGS(((MsgInfo *)msginfo->data)->flags, MSG_REPLIED);
1407                 MSG_SET_PERM_FLAGS(((MsgInfo *)msginfo->data)->flags, MSG_FORWARDED);
1408         }
1409
1410         compose = compose_create(account, COMPOSE_FORWARD);
1411
1412         textview = GTK_TEXT_VIEW(compose->text);
1413         textbuf = gtk_text_view_get_buffer(textview);
1414         compose_create_tags(textview, compose);
1415         
1416         undo_block(compose->undostruct);
1417         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1418                 msgfile = procmsg_get_message_file_path((MsgInfo *)msginfo->data);
1419                 if (!is_file_exist(msgfile))
1420                         g_warning("%s: file not exist\n", msgfile);
1421                 else
1422                         compose_attach_append(compose, msgfile, msgfile,
1423                                 "message/rfc822");
1424                 g_free(msgfile);
1425         }
1426         
1427         if (single_mail) {
1428                 MsgInfo *info = (MsgInfo *)msginfo_list->data;
1429                 if (info->subject && *info->subject) {
1430                         gchar *buf, *buf2, *p;
1431
1432                         buf = p = g_strdup(info->subject);
1433                         p += subject_get_prefix_length(p);
1434                         memmove(buf, p, strlen(p) + 1);
1435
1436                         buf2 = g_strdup_printf("Fw: %s", buf);
1437                         gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), buf2);
1438
1439                         g_free(buf);
1440                         g_free(buf2);
1441                 }
1442         } else {
1443                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry),
1444                         _("Fw: multiple emails"));
1445         }
1446
1447         SIGNAL_BLOCK(textbuf);
1448         
1449         if (account->auto_sig)
1450                 compose_insert_sig(compose, FALSE);
1451
1452         compose_wrap_all(compose);
1453
1454         SIGNAL_UNBLOCK(textbuf);
1455         
1456         gtk_text_buffer_get_start_iter(textbuf, &iter);
1457         gtk_text_buffer_place_cursor(textbuf, &iter);
1458
1459         gtk_widget_grab_focus(compose->header_last->entry);
1460         undo_unblock(compose->undostruct);
1461         compose->modified = FALSE;
1462         compose_set_title(compose);
1463         return compose;
1464 }
1465
1466 static gboolean compose_is_sig_separator(Compose *compose, GtkTextBuffer *textbuf, GtkTextIter *iter) 
1467 {
1468         GtkTextIter start = *iter;
1469         GtkTextIter end_iter;
1470         int start_pos = gtk_text_iter_get_offset(&start);
1471         gchar *str = NULL;
1472         if (!compose->account->sig_sep)
1473                 return FALSE;
1474         
1475         gtk_text_buffer_get_iter_at_offset(textbuf, &end_iter,
1476                 start_pos+strlen(compose->account->sig_sep));
1477
1478         /* check sig separator */
1479         str = gtk_text_iter_get_text(&start, &end_iter);
1480         if (!strcmp(str, compose->account->sig_sep)) {
1481                 gchar *tmp = NULL;
1482                 /* check end of line (\n) */
1483                 gtk_text_buffer_get_iter_at_offset(textbuf, &start,
1484                         start_pos+strlen(compose->account->sig_sep));
1485                 gtk_text_buffer_get_iter_at_offset(textbuf, &end_iter,
1486                         start_pos+strlen(compose->account->sig_sep)+1);
1487                 tmp = gtk_text_iter_get_text(&start, &end_iter);
1488                 if (!strcmp(tmp,"\n")) {
1489                         g_free(str);
1490                         g_free(tmp);
1491                         return TRUE;
1492                 }
1493                 g_free(tmp);    
1494         }
1495         g_free(str);
1496
1497         return FALSE;
1498 }
1499
1500 static void compose_colorize_signature(Compose *compose)
1501 {
1502         GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(compose->text));
1503         GtkTextIter iter;
1504         GtkTextIter end_iter;
1505         gtk_text_buffer_get_start_iter(buffer, &iter);
1506         while (gtk_text_iter_forward_line(&iter))
1507                 if (compose_is_sig_separator(compose, buffer, &iter)) {
1508                         gtk_text_buffer_get_end_iter(buffer, &end_iter);
1509                         gtk_text_buffer_apply_tag_by_name(buffer,"signature",&iter, &end_iter);
1510                 }
1511 }
1512
1513 void compose_reedit(MsgInfo *msginfo)
1514 {
1515         Compose *compose = NULL;
1516         PrefsAccount *account = NULL;
1517         GtkTextView *textview;
1518         GtkTextBuffer *textbuf;
1519         GtkTextMark *mark;
1520         GtkTextIter iter;
1521         FILE *fp;
1522         gchar buf[BUFFSIZE];
1523         gboolean use_signing = FALSE;
1524         gboolean use_encryption = FALSE;
1525         gchar *privacy_system = NULL;
1526
1527         g_return_if_fail(msginfo != NULL);
1528         g_return_if_fail(msginfo->folder != NULL);
1529
1530         if (compose_put_existing_to_front(msginfo)) 
1531                 return;
1532
1533         if (folder_has_parent_of_type(msginfo->folder, F_QUEUE) ||
1534             folder_has_parent_of_type(msginfo->folder, F_DRAFT)) {
1535                 gchar queueheader_buf[BUFFSIZE];
1536                 gint id, param;
1537
1538                 /* Select Account from queue headers */
1539                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1540                                              sizeof(queueheader_buf), "X-Sylpheed-Account-Id:")) {
1541                         id = atoi(&queueheader_buf[strlen("X-Sylpheed-Account-Id:")]);
1542                         account = account_find_from_id(id);
1543                 }
1544                 if (!account && !procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1545                                              sizeof(queueheader_buf), "NAID:")) {
1546                         id = atoi(&queueheader_buf[strlen("NAID:")]);
1547                         account = account_find_from_id(id);
1548                 }
1549                 if (!account && !procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1550                                                     sizeof(queueheader_buf), "MAID:")) {
1551                         id = atoi(&queueheader_buf[strlen("MAID:")]);
1552                         account = account_find_from_id(id);
1553                 }
1554                 if (!account && !procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1555                                                                 sizeof(queueheader_buf), "S:")) {
1556                         account = account_find_from_address(queueheader_buf);
1557                 }
1558                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1559                                              sizeof(queueheader_buf), "X-Sylpheed-Sign:")) {
1560                         param = atoi(&queueheader_buf[strlen("X-Sylpheed-Sign:")]);
1561                         use_signing = param;
1562                         
1563                 }
1564                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1565                                              sizeof(queueheader_buf), "X-Sylpheed-Encrypt:")) {
1566                         param = atoi(&queueheader_buf[strlen("X-Sylpheed-Encrypt:")]);
1567                         use_encryption = param;
1568                 }
1569                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1570                                             sizeof(queueheader_buf), "X-Sylpheed-Privacy-System:")) {
1571                         privacy_system = g_strdup(&queueheader_buf[strlen("X-Sylpheed-Privacy-System:")]);
1572                 }
1573                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, 
1574                                              sizeof(queueheader_buf), "X-Priority: ")) {
1575                         param = atoi(&queueheader_buf[strlen("X-Priority: ")]); /* mind the space */
1576                         compose->priority = param;
1577                 }
1578         } else 
1579                 account = msginfo->folder->folder->account;
1580
1581         if (!account && prefs_common.reedit_account_autosel) {
1582                 gchar from[BUFFSIZE];
1583                 if (!procheader_get_header_from_msginfo(msginfo, from, sizeof(from), "FROM:")){
1584                         extract_address(from);
1585                         account = account_find_from_address(from);
1586                 }
1587         }
1588         if (!account) account = cur_account;
1589         g_return_if_fail(account != NULL);
1590
1591         compose = compose_create(account, COMPOSE_REEDIT);
1592         if (privacy_system != NULL) {
1593                 compose->privacy_system = privacy_system;
1594                 compose_use_signing(compose, use_signing);
1595                 compose_use_encryption(compose, use_encryption);
1596                 compose_update_privacy_system_menu_item(compose, FALSE);
1597         } else {
1598                 activate_privacy_system(compose, account, FALSE);
1599         }
1600         compose->targetinfo = procmsg_msginfo_copy(msginfo);
1601
1602         compose_extract_original_charset(compose);
1603
1604         if (folder_has_parent_of_type(msginfo->folder, F_QUEUE) ||
1605             folder_has_parent_of_type(msginfo->folder, F_DRAFT)) {
1606                 gchar queueheader_buf[BUFFSIZE];
1607
1608                 /* Set message save folder */
1609                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, sizeof(queueheader_buf), "SCF:")) {
1610                         gint startpos = 0;
1611
1612                         gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), TRUE);
1613                         gtk_editable_delete_text(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
1614                         gtk_editable_insert_text(GTK_EDITABLE(compose->savemsg_entry), &queueheader_buf[4], strlen(&queueheader_buf[4]), &startpos);
1615                 }
1616                 if (!procheader_get_header_from_msginfo(msginfo, queueheader_buf, sizeof(queueheader_buf), "RRCPT:")) {
1617                         gint active = atoi(&queueheader_buf[strlen("RRCPT:")]);
1618                         if (active) {
1619                                 GtkItemFactory *ifactory;
1620                                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1621                                 menu_set_active(ifactory, "/Options/Request Return Receipt", TRUE);
1622                         }
1623                 }
1624         }
1625         
1626         if (compose_parse_header(compose, msginfo) < 0) return;
1627         compose_reedit_set_entry(compose, msginfo);
1628
1629         textview = GTK_TEXT_VIEW(compose->text);
1630         textbuf = gtk_text_view_get_buffer(textview);
1631         compose_create_tags(textview, compose);
1632
1633         mark = gtk_text_buffer_get_insert(textbuf);
1634         gtk_text_buffer_get_iter_at_mark(textbuf, &iter, mark);
1635
1636         g_signal_handlers_block_by_func(G_OBJECT(textbuf),
1637                                         G_CALLBACK(compose_changed_cb),
1638                                         compose);
1639         
1640         if (procmime_msginfo_is_encrypted(msginfo)) {
1641                 fp = procmime_get_first_encrypted_text_content(msginfo);
1642                 if (fp) 
1643                         compose_force_encryption(compose, account, TRUE);
1644         } else
1645                 fp = procmime_get_first_text_content(msginfo);
1646         if (fp == NULL)
1647                 g_warning("Can't get text part\n");
1648
1649         if (fp != NULL) {
1650                 gboolean prev_autowrap = compose->autowrap;
1651
1652                 compose->autowrap = FALSE;
1653                 while (fgets(buf, sizeof(buf), fp) != NULL) {
1654                         strcrchomp(buf);
1655                         gtk_text_buffer_insert(textbuf, &iter, buf, -1);
1656                 }
1657                 compose_wrap_all_full(compose, FALSE);
1658                 compose->autowrap = prev_autowrap;
1659                 fclose(fp);
1660         }
1661         
1662         compose_attach_parts(compose, msginfo);
1663
1664         compose_colorize_signature(compose);
1665
1666         g_signal_handlers_unblock_by_func(G_OBJECT(textbuf),
1667                                         G_CALLBACK(compose_changed_cb),
1668                                         compose);
1669
1670         gtk_widget_grab_focus(compose->text);
1671
1672         if (prefs_common.auto_exteditor)
1673                 compose_exec_ext_editor(compose);
1674         compose->modified = FALSE;
1675         compose_set_title(compose);
1676 }
1677
1678 Compose *compose_redirect(PrefsAccount *account, MsgInfo *msginfo)
1679 {
1680         Compose *compose;
1681         gchar *filename;
1682         GtkItemFactory *ifactory;
1683         FolderItem *item;
1684
1685         g_return_val_if_fail(msginfo != NULL, NULL);
1686
1687         if (!account)
1688                 account = account_get_reply_account(msginfo,
1689                                         prefs_common.reply_account_autosel);
1690         g_return_val_if_fail(account != NULL, NULL);
1691
1692         compose = compose_create(account, COMPOSE_REDIRECT);
1693         ifactory = gtk_item_factory_from_widget(compose->menubar);
1694         compose_create_tags(GTK_TEXT_VIEW(compose->text), compose);
1695         compose->replyinfo = NULL;
1696         compose->fwdinfo = NULL;
1697
1698         compose_show_first_last_header(compose, TRUE);
1699
1700         gtk_widget_grab_focus(compose->header_last->entry);
1701
1702         filename = procmsg_get_message_file_path(msginfo);
1703         if (filename == NULL)
1704                 return NULL;
1705
1706         compose->redirect_filename = filename;
1707         
1708         /* Set save folder */
1709         item = msginfo->folder;
1710         if (item && item->prefs && item->prefs->save_copy_to_folder) {
1711                 gchar *folderidentifier;
1712
1713                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), prefs_common.savemsg);
1714                 folderidentifier = folder_item_get_identifier(item);
1715                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
1716                 g_free(folderidentifier);
1717         }
1718
1719         compose_attach_parts(compose, msginfo);
1720
1721         if (msginfo->subject)
1722                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry),
1723                                    msginfo->subject);
1724         gtk_editable_set_editable(GTK_EDITABLE(compose->subject_entry), FALSE);
1725
1726         compose_quote_fmt(compose, msginfo, "%M", NULL, NULL, FALSE);
1727         gtk_text_view_set_editable(GTK_TEXT_VIEW(compose->text), FALSE);
1728
1729         compose_colorize_signature(compose);
1730
1731         ifactory = gtk_item_factory_from_widget(compose->popupmenu);
1732         menu_set_sensitive(ifactory, "/Add...", FALSE);
1733         menu_set_sensitive(ifactory, "/Remove", FALSE);
1734         menu_set_sensitive(ifactory, "/Properties...", FALSE);
1735
1736         ifactory = gtk_item_factory_from_widget(compose->menubar);
1737         menu_set_sensitive(ifactory, "/Message/Save", FALSE);
1738         menu_set_sensitive(ifactory, "/Message/Insert file", FALSE);
1739         menu_set_sensitive(ifactory, "/Message/Attach file", FALSE);
1740         menu_set_sensitive(ifactory, "/Message/Insert signature", FALSE);
1741         menu_set_sensitive(ifactory, "/Edit", FALSE);
1742         menu_set_sensitive(ifactory, "/Options", FALSE);
1743         menu_set_sensitive(ifactory, "/Tools/Show ruler", FALSE);
1744         menu_set_sensitive(ifactory, "/Tools/Actions", FALSE);
1745         
1746         gtk_widget_set_sensitive(compose->toolbar->draft_btn, FALSE);
1747         gtk_widget_set_sensitive(compose->toolbar->insert_btn, FALSE);
1748         gtk_widget_set_sensitive(compose->toolbar->attach_btn, FALSE);
1749         gtk_widget_set_sensitive(compose->toolbar->sig_btn, FALSE);
1750         gtk_widget_set_sensitive(compose->toolbar->exteditor_btn, FALSE);
1751         gtk_widget_set_sensitive(compose->toolbar->linewrap_current_btn, FALSE);
1752         gtk_widget_set_sensitive(compose->toolbar->linewrap_all_btn, FALSE);
1753
1754         compose->modified = FALSE;
1755         compose_set_title(compose);
1756         return compose;
1757 }
1758
1759 GList *compose_get_compose_list(void)
1760 {
1761         return compose_list;
1762 }
1763
1764 void compose_entry_append(Compose *compose, const gchar *address,
1765                           ComposeEntryType type)
1766 {
1767         gchar *header;
1768         gchar *cur, *begin;
1769         gboolean in_quote = FALSE;
1770         if (!address || *address == '\0') return;
1771
1772         switch (type) {
1773         case COMPOSE_CC:
1774                 header = N_("Cc:");
1775                 break;
1776         case COMPOSE_BCC:
1777                 header = N_("Bcc:");
1778                 break;
1779         case COMPOSE_REPLYTO:
1780                 header = N_("Reply-To:");
1781                 break;
1782         case COMPOSE_NEWSGROUPS:
1783                 header = N_("Newsgroups:");
1784                 break;
1785         case COMPOSE_FOLLOWUPTO:
1786                 header = N_( "Followup-To:");
1787                 break;
1788         case COMPOSE_TO:
1789         default:
1790                 header = N_("To:");
1791                 break;
1792         }
1793         header = prefs_common.trans_hdr ? gettext(header) : header;
1794         
1795         cur = begin = (gchar *)address;
1796         
1797         /* we separate the line by commas, but not if we're inside a quoted
1798          * string */
1799         while (*cur != '\0') {
1800                 if (*cur == '"') 
1801                         in_quote = !in_quote;
1802                 if (*cur == ',' && !in_quote) {
1803                         gchar *tmp = g_strdup(begin);
1804                         gchar *o_tmp = tmp;
1805                         tmp[cur-begin]='\0';
1806                         cur++;
1807                         begin = cur;
1808                         while (*tmp == ' ')
1809                                 tmp++;
1810                         compose_add_header_entry(compose, header, tmp);
1811                         g_free(o_tmp);
1812                         continue;
1813                 }
1814                 cur++;
1815         }
1816         if (begin < cur) {
1817                 gchar *tmp = g_strdup(begin);
1818                 gchar *o_tmp = tmp;
1819                 tmp[cur-begin]='\0';
1820                 cur++;
1821                 begin = cur;
1822                 while (*tmp == ' ')
1823                         tmp++;
1824                 compose_add_header_entry(compose, header, tmp);
1825                 g_free(o_tmp);          
1826         }
1827 }
1828
1829 void compose_entry_mark_default_to(Compose *compose, const gchar *mailto)
1830 {
1831         static GdkColor yellow;
1832         static GdkColor black;
1833         static gboolean yellow_initialised = FALSE;
1834         GSList *h_list;
1835         GtkEntry *entry;
1836                 
1837         if (!yellow_initialised) {
1838                 gdk_color_parse("#f5f6be", &yellow);
1839                 gdk_color_parse("#000000", &black);
1840                 yellow_initialised = gdk_colormap_alloc_color(
1841                         gdk_colormap_get_system(), &yellow, FALSE, TRUE);
1842                 yellow_initialised &= gdk_colormap_alloc_color(
1843                         gdk_colormap_get_system(), &black, FALSE, TRUE);
1844         }
1845
1846         for (h_list = compose->header_list; h_list != NULL; h_list = h_list->next) {
1847                 entry = GTK_ENTRY(((ComposeHeaderEntry *)h_list->data)->entry);
1848                 if (gtk_entry_get_text(entry) && 
1849                     !g_utf8_collate(gtk_entry_get_text(entry), mailto)) {
1850                         if (yellow_initialised) {
1851                                 gtk_widget_modify_base(
1852                                         GTK_WIDGET(((ComposeHeaderEntry *)h_list->data)->entry),
1853                                         GTK_STATE_NORMAL, &yellow);
1854                                 gtk_widget_modify_text(
1855                                         GTK_WIDGET(((ComposeHeaderEntry *)h_list->data)->entry),
1856                                         GTK_STATE_NORMAL, &black);
1857                         }
1858                 }
1859         }
1860 }
1861
1862 void compose_toolbar_cb(gint action, gpointer data)
1863 {
1864         ToolbarItem *toolbar_item = (ToolbarItem*)data;
1865         Compose *compose = (Compose*)toolbar_item->parent;
1866         
1867         g_return_if_fail(compose != NULL);
1868
1869         switch(action) {
1870         case A_SEND:
1871                 compose_send_cb(compose, 0, NULL);
1872                 break;
1873         case A_SENDL:
1874                 compose_send_later_cb(compose, 0, NULL);
1875                 break;
1876         case A_DRAFT:
1877                 compose_draft_cb(compose, COMPOSE_QUIT_EDITING, NULL);
1878                 break;
1879         case A_INSERT:
1880                 compose_insert_file_cb(compose, 0, NULL);
1881                 break;
1882         case A_ATTACH:
1883                 compose_attach_cb(compose, 0, NULL);
1884                 break;
1885         case A_SIG:
1886                 compose_insert_sig(compose, FALSE);
1887                 break;
1888         case A_EXTEDITOR:
1889                 compose_ext_editor_cb(compose, 0, NULL);
1890                 break;
1891         case A_LINEWRAP_CURRENT:
1892                 compose_beautify_paragraph(compose, NULL, TRUE);
1893                 break;
1894         case A_LINEWRAP_ALL:
1895                 compose_wrap_all_full(compose, TRUE);
1896                 break;
1897         case A_ADDRBOOK:
1898                 compose_address_cb(compose, 0, NULL);
1899                 break;
1900 #ifdef USE_ASPELL
1901         case A_CHECK_SPELLING:
1902                 compose_check_all(compose);
1903                 break;
1904 #endif
1905         default:
1906                 break;
1907         }
1908 }
1909
1910 static void compose_entries_set(Compose *compose, const gchar *mailto)
1911 {
1912         gchar *to = NULL;
1913         gchar *cc = NULL;
1914         gchar *subject = NULL;
1915         gchar *body = NULL;
1916         gchar *temp = NULL;
1917         gint  len = 0;
1918
1919         scan_mailto_url(mailto, &to, &cc, NULL, &subject, &body);
1920
1921         if (to)
1922                 compose_entry_append(compose, to, COMPOSE_TO);
1923         if (cc)
1924                 compose_entry_append(compose, cc, COMPOSE_CC);
1925         if (subject) {
1926                 if (!g_utf8_validate (subject, -1, NULL)) {
1927                         temp = g_locale_to_utf8 (subject, -1, NULL, &len, NULL);
1928                         gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), temp);
1929                         g_free(temp);
1930                 } else {
1931                         gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), subject);
1932                 }
1933         }
1934         if (body) {
1935                 GtkTextView *text = GTK_TEXT_VIEW(compose->text);
1936                 GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
1937                 GtkTextMark *mark;
1938                 GtkTextIter iter;
1939                 gboolean prev_autowrap = compose->autowrap;
1940
1941                 compose->autowrap = FALSE;
1942
1943                 mark = gtk_text_buffer_get_insert(buffer);
1944                 gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
1945
1946                 if (!g_utf8_validate (body, -1, NULL)) {
1947                         temp = g_locale_to_utf8 (body, -1, NULL, &len, NULL);
1948                         gtk_text_buffer_insert(buffer, &iter, temp, -1);
1949                         g_free(temp);
1950                 } else {
1951                         gtk_text_buffer_insert(buffer, &iter, body, -1);
1952                 }
1953                 gtk_text_buffer_insert(buffer, &iter, "\n", 1);
1954
1955                 compose->autowrap = prev_autowrap;
1956                 if (compose->autowrap)
1957                         compose_wrap_all(compose);
1958         }
1959
1960         g_free(to);
1961         g_free(cc);
1962         g_free(subject);
1963         g_free(body);
1964 }
1965
1966 static gint compose_parse_header(Compose *compose, MsgInfo *msginfo)
1967 {
1968         static HeaderEntry hentry[] = {{"Reply-To:",    NULL, TRUE},
1969                                        {"Cc:",          NULL, TRUE},
1970                                        {"References:",  NULL, FALSE},
1971                                        {"Bcc:",         NULL, TRUE},
1972                                        {"Newsgroups:",  NULL, TRUE},
1973                                        {"Followup-To:", NULL, TRUE},
1974                                        {"List-Post:",   NULL, FALSE},
1975                                        {"X-Priority:",  NULL, FALSE},
1976                                        {NULL,           NULL, FALSE}};
1977
1978         enum
1979         {
1980                 H_REPLY_TO      = 0,
1981                 H_CC            = 1,
1982                 H_REFERENCES    = 2,
1983                 H_BCC           = 3,
1984                 H_NEWSGROUPS    = 4,
1985                 H_FOLLOWUP_TO   = 5,
1986                 H_LIST_POST     = 6,
1987                 H_X_PRIORITY    = 7
1988         };
1989
1990         FILE *fp;
1991
1992         g_return_val_if_fail(msginfo != NULL, -1);
1993
1994         if ((fp = procmsg_open_message(msginfo)) == NULL) return -1;
1995         procheader_get_header_fields(fp, hentry);
1996         fclose(fp);
1997
1998         if (hentry[H_REPLY_TO].body != NULL) {
1999                 if (hentry[H_REPLY_TO].body[0] != '\0') {
2000                         compose->replyto =
2001                                 conv_unmime_header(hentry[H_REPLY_TO].body,
2002                                                    NULL);
2003                 }
2004                 g_free(hentry[H_REPLY_TO].body);
2005                 hentry[H_REPLY_TO].body = NULL;
2006         }
2007         if (hentry[H_CC].body != NULL) {
2008                 compose->cc = conv_unmime_header(hentry[H_CC].body, NULL);
2009                 g_free(hentry[H_CC].body);
2010                 hentry[H_CC].body = NULL;
2011         }
2012         if (hentry[H_REFERENCES].body != NULL) {
2013                 if (compose->mode == COMPOSE_REEDIT)
2014                         compose->references = hentry[H_REFERENCES].body;
2015                 else {
2016                         compose->references = compose_parse_references
2017                                 (hentry[H_REFERENCES].body, msginfo->msgid);
2018                         g_free(hentry[H_REFERENCES].body);
2019                 }
2020                 hentry[H_REFERENCES].body = NULL;
2021         }
2022         if (hentry[H_BCC].body != NULL) {
2023                 if (compose->mode == COMPOSE_REEDIT)
2024                         compose->bcc =
2025                                 conv_unmime_header(hentry[H_BCC].body, NULL);
2026                 g_free(hentry[H_BCC].body);
2027                 hentry[H_BCC].body = NULL;
2028         }
2029         if (hentry[H_NEWSGROUPS].body != NULL) {
2030                 compose->newsgroups = hentry[H_NEWSGROUPS].body;
2031                 hentry[H_NEWSGROUPS].body = NULL;
2032         }
2033         if (hentry[H_FOLLOWUP_TO].body != NULL) {
2034                 if (hentry[H_FOLLOWUP_TO].body[0] != '\0') {
2035                         compose->followup_to =
2036                                 conv_unmime_header(hentry[H_FOLLOWUP_TO].body,
2037                                                    NULL);
2038                 }
2039                 g_free(hentry[H_FOLLOWUP_TO].body);
2040                 hentry[H_FOLLOWUP_TO].body = NULL;
2041         }
2042         if (hentry[H_LIST_POST].body != NULL) {
2043                 gchar *to = NULL;
2044
2045                 extract_address(hentry[H_LIST_POST].body);
2046                 if (hentry[H_LIST_POST].body[0] != '\0') {
2047                         scan_mailto_url(hentry[H_LIST_POST].body,
2048                                         &to, NULL, NULL, NULL, NULL);
2049                         if (to) {
2050                                 g_free(compose->ml_post);
2051                                 compose->ml_post = to;
2052                         }
2053                 }
2054                 g_free(hentry[H_LIST_POST].body);
2055                 hentry[H_LIST_POST].body = NULL;
2056         }
2057
2058         /* CLAWS - X-Priority */
2059         if (compose->mode == COMPOSE_REEDIT)
2060                 if (hentry[H_X_PRIORITY].body != NULL) {
2061                         gint priority;
2062                         
2063                         priority = atoi(hentry[H_X_PRIORITY].body);
2064                         g_free(hentry[H_X_PRIORITY].body);
2065                         
2066                         hentry[H_X_PRIORITY].body = NULL;
2067                         
2068                         if (priority < PRIORITY_HIGHEST || 
2069                             priority > PRIORITY_LOWEST)
2070                                 priority = PRIORITY_NORMAL;
2071                         
2072                         compose->priority =  priority;
2073                 }
2074  
2075         if (compose->mode == COMPOSE_REEDIT) {
2076                 if (msginfo->inreplyto && *msginfo->inreplyto)
2077                         compose->inreplyto = g_strdup(msginfo->inreplyto);
2078                 return 0;
2079         }
2080
2081         if (msginfo->msgid && *msginfo->msgid)
2082                 compose->inreplyto = g_strdup(msginfo->msgid);
2083
2084         if (!compose->references) {
2085                 if (msginfo->msgid && *msginfo->msgid) {
2086                         if (msginfo->inreplyto && *msginfo->inreplyto)
2087                                 compose->references =
2088                                         g_strdup_printf("<%s>\n\t<%s>",
2089                                                         msginfo->inreplyto,
2090                                                         msginfo->msgid);
2091                         else
2092                                 compose->references =
2093                                         g_strconcat("<", msginfo->msgid, ">",
2094                                                     NULL);
2095                 } else if (msginfo->inreplyto && *msginfo->inreplyto) {
2096                         compose->references =
2097                                 g_strconcat("<", msginfo->inreplyto, ">",
2098                                             NULL);
2099                 }
2100         }
2101
2102         return 0;
2103 }
2104
2105 static gchar *compose_parse_references(const gchar *ref, const gchar *msgid)
2106 {
2107         GSList *ref_id_list, *cur;
2108         GString *new_ref;
2109         gchar *new_ref_str;
2110
2111         ref_id_list = references_list_append(NULL, ref);
2112         if (!ref_id_list) return NULL;
2113         if (msgid && *msgid)
2114                 ref_id_list = g_slist_append(ref_id_list, g_strdup(msgid));
2115
2116         for (;;) {
2117                 gint len = 0;
2118
2119                 for (cur = ref_id_list; cur != NULL; cur = cur->next)
2120                         /* "<" + Message-ID + ">" + CR+LF+TAB */
2121                         len += strlen((gchar *)cur->data) + 5;
2122
2123                 if (len > MAX_REFERENCES_LEN) {
2124                         /* remove second message-ID */
2125                         if (ref_id_list && ref_id_list->next &&
2126                             ref_id_list->next->next) {
2127                                 g_free(ref_id_list->next->data);
2128                                 ref_id_list = g_slist_remove
2129                                         (ref_id_list, ref_id_list->next->data);
2130                         } else {
2131                                 slist_free_strings(ref_id_list);
2132                                 g_slist_free(ref_id_list);
2133                                 return NULL;
2134                         }
2135                 } else
2136                         break;
2137         }
2138
2139         new_ref = g_string_new("");
2140         for (cur = ref_id_list; cur != NULL; cur = cur->next) {
2141                 if (new_ref->len > 0)
2142                         g_string_append(new_ref, "\n\t");
2143                 g_string_append_printf(new_ref, "<%s>", (gchar *)cur->data);
2144         }
2145
2146         slist_free_strings(ref_id_list);
2147         g_slist_free(ref_id_list);
2148
2149         new_ref_str = new_ref->str;
2150         g_string_free(new_ref, FALSE);
2151
2152         return new_ref_str;
2153 }
2154
2155 static gchar *compose_quote_fmt(Compose *compose, MsgInfo *msginfo,
2156                                 const gchar *fmt, const gchar *qmark,
2157                                 const gchar *body, gboolean rewrap)
2158 {
2159         static MsgInfo dummyinfo;
2160         gchar *quote_str = NULL;
2161         gchar *buf;
2162         gboolean prev_autowrap;
2163         const gchar *trimmed_body = body;
2164         gint cursor_pos = -1;
2165         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
2166         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
2167         GtkTextIter iter;
2168         GtkTextMark *mark;
2169         
2170
2171         SIGNAL_BLOCK(buffer);
2172
2173         if (!msginfo)
2174                 msginfo = &dummyinfo;
2175
2176         if (qmark != NULL) {
2177                 quote_fmt_init(msginfo, NULL, NULL, FALSE);
2178                 quote_fmt_scan_string(qmark);
2179                 quote_fmt_parse();
2180
2181                 buf = quote_fmt_get_buffer();
2182                 if (buf == NULL)
2183                         alertpanel_error(_("Quote mark format error."));
2184                 else
2185                         Xstrdup_a(quote_str, buf, goto error)
2186         }
2187
2188         if (fmt && *fmt != '\0') {
2189                 while (trimmed_body && strlen(trimmed_body) > 1
2190                         && trimmed_body[0]=='\n')
2191                         *trimmed_body++;
2192
2193                 quote_fmt_init(msginfo, quote_str, trimmed_body, FALSE);
2194                 quote_fmt_scan_string(fmt);
2195                 quote_fmt_parse();
2196
2197                 buf = quote_fmt_get_buffer();
2198                 if (buf == NULL) {
2199                         alertpanel_error(_("Message reply/forward format error."));
2200                         goto error;
2201                 }
2202         } else
2203                 buf = "";
2204
2205         prev_autowrap = compose->autowrap;
2206         compose->autowrap = FALSE;
2207
2208         mark = gtk_text_buffer_get_insert(buffer);
2209         gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
2210         if (g_utf8_validate(buf, -1, NULL)) { 
2211                 gtk_text_buffer_insert(buffer, &iter, buf, -1);
2212         } else {
2213                 gchar *tmpout = NULL;
2214                 tmpout = conv_codeset_strdup
2215                         (buf, conv_get_locale_charset_str(),
2216                          CS_INTERNAL);
2217                 if (!tmpout || !g_utf8_validate(tmpout, -1, NULL)) {
2218                         g_free(tmpout);
2219                         tmpout = g_malloc(strlen(buf)*2+1);
2220                         conv_localetodisp(tmpout, strlen(buf)*2+1, buf);
2221                 }
2222                 gtk_text_buffer_insert(buffer, &iter, tmpout, -1);
2223                 g_free(tmpout);
2224         }
2225
2226         cursor_pos = quote_fmt_get_cursor_pos();
2227         compose->set_cursor_pos = cursor_pos;
2228         if (cursor_pos == -1) {
2229                 cursor_pos = 0;
2230         }
2231         gtk_text_buffer_get_start_iter(buffer, &iter);
2232         gtk_text_buffer_get_iter_at_offset(buffer, &iter, cursor_pos);
2233         gtk_text_buffer_place_cursor(buffer, &iter);
2234
2235         compose->autowrap = prev_autowrap;
2236         if (compose->autowrap && rewrap)
2237                 compose_wrap_all(compose);
2238
2239         goto ok;
2240
2241 error:
2242         buf = NULL;
2243 ok:
2244         SIGNAL_UNBLOCK(buffer);
2245
2246
2247         return buf;
2248 }
2249
2250 /* if ml_post is of type addr@host and from is of type
2251  * addr-anything@host, return TRUE
2252  */
2253 static gboolean is_subscription(const gchar *ml_post, const gchar *from)
2254 {
2255         gchar *left_ml = NULL;
2256         gchar *right_ml = NULL;
2257         gchar *left_from = NULL;
2258         gchar *right_from = NULL;
2259         gboolean result = FALSE;
2260         
2261         if (!ml_post || !from)
2262                 return FALSE;
2263         
2264         left_ml = g_strdup(ml_post);
2265         if (strstr(left_ml, "@")) {
2266                 right_ml = strstr(left_ml, "@")+1;
2267                 *(strstr(left_ml, "@")) = '\0';
2268         }
2269         
2270         left_from = g_strdup(from);
2271         if (strstr(left_from, "@")) {
2272                 right_from = strstr(left_from, "@")+1;
2273                 *(strstr(left_from, "@")) = '\0';
2274         }
2275         
2276         if (left_ml && left_from && right_ml && right_from
2277         &&  !strncmp(left_from, left_ml, strlen(left_ml))
2278         &&  !strcmp(right_from, right_ml)) {
2279                 result = TRUE;
2280         }
2281         g_free(left_ml);
2282         g_free(left_from);
2283         
2284         return result;
2285 }
2286
2287 static gboolean same_address(const gchar *addr1, const gchar *addr2)
2288 {
2289         gchar *my_addr1, *my_addr2;
2290         
2291         if (!addr1 || !addr2)
2292                 return FALSE;
2293
2294         Xstrdup_a(my_addr1, addr1, return FALSE);
2295         Xstrdup_a(my_addr2, addr2, return FALSE);
2296         
2297         extract_address(my_addr1);
2298         extract_address(my_addr2);
2299         
2300         return !strcmp(my_addr1, my_addr2);
2301 }
2302
2303 static void compose_reply_set_entry(Compose *compose, MsgInfo *msginfo,
2304                                     gboolean to_all, gboolean to_ml,
2305                                     gboolean to_sender,
2306                                     gboolean followup_and_reply_to)
2307 {
2308         GSList *cc_list = NULL;
2309         GSList *cur;
2310         gchar *from = NULL;
2311         gchar *replyto = NULL;
2312         GHashTable *to_table;
2313
2314         gboolean reply_to_ml = FALSE;
2315         gboolean default_reply_to = FALSE;
2316
2317         g_return_if_fail(compose->account != NULL);
2318         g_return_if_fail(msginfo != NULL);
2319
2320         reply_to_ml = to_ml && compose->ml_post;
2321
2322         default_reply_to = msginfo->folder && 
2323                 msginfo->folder->prefs->enable_default_reply_to;
2324
2325         if (compose->account->protocol != A_NNTP) {
2326                 if (reply_to_ml && !default_reply_to) {
2327                         
2328                         gboolean is_subscr = is_subscription(compose->ml_post,
2329                                                              msginfo->from);
2330                         if (!is_subscr) {
2331                                 /* normal answer to ml post with a reply-to */
2332                                 compose_entry_append(compose,
2333                                            compose->ml_post,
2334                                            COMPOSE_TO);
2335                                 if (compose->replyto
2336                                 &&  !same_address(compose->ml_post, compose->replyto))
2337                                         compose_entry_append(compose,
2338                                                 compose->replyto,
2339                                                 COMPOSE_CC);
2340                         } else {
2341                                 /* answer to subscription confirmation */
2342                                 if (compose->replyto)
2343                                         compose_entry_append(compose,
2344                                                 compose->replyto,
2345                                                 COMPOSE_TO);
2346                                 else if (msginfo->from)
2347                                         compose_entry_append(compose,
2348                                                 msginfo->from,
2349                                                 COMPOSE_TO);
2350                         }
2351                 }
2352                 else if (!(to_all || to_sender) && default_reply_to) {
2353                         compose_entry_append(compose,
2354                             msginfo->folder->prefs->default_reply_to,
2355                             COMPOSE_TO);
2356                         compose_entry_mark_default_to(compose,
2357                                 msginfo->folder->prefs->default_reply_to);
2358                 } else {
2359                         gchar *tmp1 = NULL;
2360                         Xstrdup_a(tmp1, msginfo->from, return);
2361                         extract_address(tmp1);
2362                         if (to_all || to_sender ||
2363                             !account_find_from_address(tmp1))
2364                                 compose_entry_append(compose,
2365                                  (compose->replyto && !to_sender)
2366                                           ? compose->replyto :
2367                                           msginfo->from ? msginfo->from : "",
2368                                           COMPOSE_TO);
2369                         else if (!to_all && !to_sender) {
2370                                 /* reply to the last list of recipients */
2371                                 compose_entry_append(compose,
2372                                           msginfo->to ? msginfo->to : "",
2373                                           COMPOSE_TO);
2374                                 compose_entry_append(compose,
2375                                           msginfo->cc ? msginfo->cc : "",
2376                                           COMPOSE_CC);
2377                         }
2378                 }
2379         } else {
2380                 if (to_sender || (compose->followup_to && 
2381                         !strncmp(compose->followup_to, "poster", 6)))
2382                         compose_entry_append
2383                                 (compose, 
2384                                  (compose->replyto ? compose->replyto :
2385                                         msginfo->from ? msginfo->from : ""),
2386                                  COMPOSE_TO);
2387                                  
2388                 else if (followup_and_reply_to || to_all) {
2389                         compose_entry_append
2390                                 (compose,
2391                                  (compose->replyto ? compose->replyto :
2392                                  msginfo->from ? msginfo->from : ""),
2393                                  COMPOSE_TO);                           
2394                 
2395                         compose_entry_append
2396                                 (compose,
2397                                  compose->followup_to ? compose->followup_to :
2398                                  compose->newsgroups ? compose->newsgroups : "",
2399                                  COMPOSE_NEWSGROUPS);
2400                 } 
2401                 else 
2402                         compose_entry_append
2403                                 (compose,
2404                                  compose->followup_to ? compose->followup_to :
2405                                  compose->newsgroups ? compose->newsgroups : "",
2406                                  COMPOSE_NEWSGROUPS);
2407         }
2408
2409         if (msginfo->subject && *msginfo->subject) {
2410                 gchar *buf, *buf2;
2411                 guchar *p;
2412
2413                 buf = p = g_strdup(msginfo->subject);
2414                 p += subject_get_prefix_length(p);
2415                 memmove(buf, p, strlen(p) + 1);
2416
2417                 buf2 = g_strdup_printf("Re: %s", buf);
2418                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), buf2);
2419
2420                 g_free(buf2);
2421                 g_free(buf);
2422         } else
2423                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), "Re: ");
2424
2425         if (to_ml && compose->ml_post) return;
2426         if (!to_all || compose->account->protocol == A_NNTP) return;
2427
2428         if (compose->replyto) {
2429                 Xstrdup_a(replyto, compose->replyto, return);
2430                 extract_address(replyto);
2431         }
2432         if (msginfo->from) {
2433                 Xstrdup_a(from, msginfo->from, return);
2434                 extract_address(from);
2435         }
2436
2437         if (replyto && from)
2438                 cc_list = address_list_append_with_comments(cc_list, from);
2439         if (to_all && msginfo->folder && 
2440             msginfo->folder->prefs->enable_default_reply_to)
2441                 cc_list = address_list_append_with_comments(cc_list,
2442                                 msginfo->folder->prefs->default_reply_to);
2443         cc_list = address_list_append_with_comments(cc_list, msginfo->to);
2444         cc_list = address_list_append_with_comments(cc_list, compose->cc);
2445
2446         to_table = g_hash_table_new(g_str_hash, g_str_equal);
2447         if (replyto)
2448                 g_hash_table_insert(to_table, g_strdup(replyto), GINT_TO_POINTER(1));
2449         if (compose->account)
2450                 g_hash_table_insert(to_table, g_strdup(compose->account->address),
2451                                     GINT_TO_POINTER(1));
2452
2453         /* remove address on To: and that of current account */
2454         for (cur = cc_list; cur != NULL; ) {
2455                 GSList *next = cur->next;
2456                 gchar *addr;
2457
2458                 addr = g_strdup(cur->data);
2459                 extract_address(addr);
2460
2461                 if (GPOINTER_TO_INT(g_hash_table_lookup(to_table, addr)) == 1)
2462                         cc_list = g_slist_remove(cc_list, cur->data);
2463                 else
2464                         g_hash_table_insert(to_table, addr, GINT_TO_POINTER(1));
2465
2466                 cur = next;
2467         }
2468         hash_free_strings(to_table);
2469         g_hash_table_destroy(to_table);
2470
2471         if (cc_list) {
2472                 for (cur = cc_list; cur != NULL; cur = cur->next)
2473                         compose_entry_append(compose, (gchar *)cur->data,
2474                                              COMPOSE_CC);
2475                 slist_free_strings(cc_list);
2476                 g_slist_free(cc_list);
2477         }
2478
2479 }
2480
2481 #define SET_ENTRY(entry, str) \
2482 { \
2483         if (str && *str) \
2484                 gtk_entry_set_text(GTK_ENTRY(compose->entry), str); \
2485 }
2486
2487 #define SET_ADDRESS(type, str) \
2488 { \
2489         if (str && *str) \
2490                 compose_entry_append(compose, str, type); \
2491 }
2492
2493 static void compose_reedit_set_entry(Compose *compose, MsgInfo *msginfo)
2494 {
2495         g_return_if_fail(msginfo != NULL);
2496
2497         SET_ENTRY(subject_entry, msginfo->subject);
2498         SET_ADDRESS(COMPOSE_TO, msginfo->to);
2499         SET_ADDRESS(COMPOSE_CC, compose->cc);
2500         SET_ADDRESS(COMPOSE_BCC, compose->bcc);
2501         SET_ADDRESS(COMPOSE_REPLYTO, compose->replyto);
2502         SET_ADDRESS(COMPOSE_NEWSGROUPS, compose->newsgroups);
2503         SET_ADDRESS(COMPOSE_FOLLOWUPTO, compose->followup_to);
2504
2505         compose_update_priority_menu_item(compose);
2506         compose_update_privacy_system_menu_item(compose, FALSE);
2507         compose_show_first_last_header(compose, TRUE);
2508 }
2509
2510 #undef SET_ENTRY
2511 #undef SET_ADDRESS
2512
2513 static void compose_insert_sig(Compose *compose, gboolean replace)
2514 {
2515         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
2516         GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
2517         GtkTextMark *mark;
2518         GtkTextIter iter, iter_end;
2519         gint cur_pos;
2520         gboolean prev_autowrap;
2521
2522         
2523         g_return_if_fail(compose->account != NULL);
2524
2525         prev_autowrap = compose->autowrap;
2526         compose->autowrap = FALSE;
2527
2528         g_signal_handlers_block_by_func(G_OBJECT(buffer),
2529                                         G_CALLBACK(compose_changed_cb),
2530                                         compose);
2531         
2532         mark = gtk_text_buffer_get_insert(buffer);
2533         gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
2534         cur_pos = gtk_text_iter_get_offset (&iter);
2535
2536         gtk_text_buffer_get_end_iter(buffer, &iter);
2537
2538         if (replace && compose->sig_str) {
2539                 gboolean found;
2540                 GtkTextIter first_iter, start_iter, end_iter;
2541
2542                 gtk_text_buffer_get_start_iter(buffer, &first_iter);
2543
2544                 if (compose->sig_str[0] == '\0')
2545                         found = FALSE;
2546                 else
2547                         found = gtk_text_iter_forward_search(&first_iter,
2548                                                              compose->sig_str,
2549                                                              GTK_TEXT_SEARCH_TEXT_ONLY,
2550                                                              &start_iter, &end_iter,
2551                                                              NULL);
2552
2553                 if (found) {
2554                         gtk_text_buffer_delete(buffer, &start_iter, &end_iter);
2555                         iter = start_iter;
2556                 }
2557         }
2558
2559         g_free(compose->sig_str);
2560         compose->sig_str = compose_get_signature_str(compose);
2561         if (!compose->sig_str || (replace && !compose->account->auto_sig))
2562                 compose->sig_str = g_strdup("");
2563
2564         cur_pos = gtk_text_iter_get_offset(&iter);
2565         gtk_text_buffer_insert(buffer, &iter, compose->sig_str, -1);
2566         /* skip \n\n */
2567         gtk_text_buffer_get_iter_at_offset(buffer, &iter, cur_pos);
2568         gtk_text_iter_forward_char(&iter);
2569         gtk_text_iter_forward_char(&iter);
2570         gtk_text_buffer_get_end_iter(buffer, &iter_end);
2571         gtk_text_buffer_apply_tag_by_name(buffer,"signature",&iter, &iter_end);
2572
2573         if (cur_pos > gtk_text_buffer_get_char_count (buffer))
2574                 cur_pos = gtk_text_buffer_get_char_count (buffer);
2575
2576         /* put the cursor where it should be 
2577          * either where the quote_fmt says, either before the signature */
2578         if (compose->set_cursor_pos < 0)
2579                 gtk_text_buffer_get_iter_at_offset(buffer, &iter, cur_pos);
2580         else
2581                 gtk_text_buffer_get_iter_at_offset(buffer, &iter, 
2582                         compose->set_cursor_pos);
2583                 
2584         gtk_text_buffer_place_cursor(buffer, &iter);
2585         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),
2586                                         G_CALLBACK(compose_changed_cb),
2587                                         compose);
2588                 
2589         compose->autowrap = prev_autowrap;
2590         if (compose->autowrap)
2591                 compose_wrap_all(compose);
2592 }
2593
2594 static gchar *compose_get_signature_str(Compose *compose)
2595 {
2596         gchar *sig_body = NULL;
2597         gchar *sig_str = NULL;
2598         gchar *utf8_sig_str = NULL;
2599
2600         g_return_val_if_fail(compose->account != NULL, NULL);
2601
2602         if (!compose->account->sig_path)
2603                 return NULL;
2604
2605         if (compose->account->sig_type == SIG_FILE) {
2606                 if (!is_file_or_fifo_exist(compose->account->sig_path)) {
2607                         g_warning("can't open signature file: %s\n",
2608                                   compose->account->sig_path);
2609                         return NULL;
2610                 }
2611         }
2612
2613         if (compose->account->sig_type == SIG_COMMAND)
2614                 sig_body = get_command_output(compose->account->sig_path);
2615         else {
2616                 gchar *tmp;
2617
2618                 tmp = file_read_to_str(compose->account->sig_path);
2619                 if (!tmp)
2620                         return NULL;
2621                 sig_body = normalize_newlines(tmp);
2622                 g_free(tmp);
2623         }
2624
2625         if (compose->account->sig_sep) {
2626                 sig_str = g_strconcat("\n\n", compose->account->sig_sep, "\n", sig_body,
2627                                       NULL);
2628                 g_free(sig_body);
2629         } else
2630                 sig_str = g_strconcat("\n\n", sig_body, NULL);
2631
2632         if (sig_str) {
2633                 if (g_utf8_validate(sig_str, -1, NULL) == TRUE)
2634                         utf8_sig_str = sig_str;
2635                 else {
2636                         utf8_sig_str = conv_codeset_strdup
2637                                 (sig_str, conv_get_locale_charset_str(),
2638                                  CS_INTERNAL);
2639                         g_free(sig_str);
2640                 }
2641         }
2642
2643         return utf8_sig_str;
2644 }
2645
2646 static ComposeInsertResult compose_insert_file(Compose *compose, const gchar *file)
2647 {
2648         GtkTextView *text;
2649         GtkTextBuffer *buffer;
2650         GtkTextMark *mark;
2651         GtkTextIter iter;
2652         const gchar *cur_encoding;
2653         gchar buf[BUFFSIZE];
2654         gint len;
2655         FILE *fp;
2656         gboolean prev_autowrap;
2657         gboolean badtxt = FALSE;
2658
2659         g_return_val_if_fail(file != NULL, COMPOSE_INSERT_NO_FILE);
2660
2661         if ((fp = g_fopen(file, "rb")) == NULL) {
2662                 FILE_OP_ERROR(file, "fopen");
2663                 return COMPOSE_INSERT_READ_ERROR;
2664         }
2665
2666         prev_autowrap = compose->autowrap;
2667         compose->autowrap = FALSE;
2668
2669         text = GTK_TEXT_VIEW(compose->text);
2670         buffer = gtk_text_view_get_buffer(text);
2671         mark = gtk_text_buffer_get_insert(buffer);
2672         gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
2673
2674         g_signal_handlers_block_by_func(G_OBJECT(buffer),
2675                                         G_CALLBACK(text_inserted),
2676                                         compose);
2677
2678         cur_encoding = conv_get_locale_charset_str();
2679
2680         while (fgets(buf, sizeof(buf), fp) != NULL) {
2681                 gchar *str;
2682
2683                 if (g_utf8_validate(buf, -1, NULL) == TRUE)
2684                         str = g_strdup(buf);
2685                 else
2686                         str = conv_codeset_strdup
2687                                 (buf, cur_encoding, CS_INTERNAL);
2688                 if (!str) continue;
2689
2690                 /* strip <CR> if DOS/Windows file,
2691                    replace <CR> with <LF> if Macintosh file. */
2692                 strcrchomp(str);
2693                 len = strlen(str);
2694                 if (len > 0 && str[len - 1] != '\n') {
2695                         while (--len >= 0)
2696                                 if (str[len] == '\r') str[len] = '\n';
2697                 }
2698
2699                 gtk_text_buffer_insert(buffer, &iter, str, -1);
2700                 g_free(str);
2701         }
2702
2703         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),
2704                                           G_CALLBACK(text_inserted),
2705                                           compose);
2706         compose->autowrap = prev_autowrap;
2707         if (compose->autowrap)
2708                 compose_wrap_all(compose);
2709
2710         fclose(fp);
2711
2712         if (badtxt)
2713                 return COMPOSE_INSERT_INVALID_CHARACTER;
2714         else 
2715                 return COMPOSE_INSERT_SUCCESS;
2716 }
2717
2718 static void compose_attach_append(Compose *compose, const gchar *file,
2719                                   const gchar *filename,
2720                                   const gchar *content_type)
2721 {
2722         AttachInfo *ainfo;
2723         GtkTreeIter iter;
2724         FILE *fp;
2725         off_t size;
2726         GAuto *auto_ainfo;
2727         gchar *size_text;
2728         GtkListStore *store;
2729         gchar *name;
2730
2731         if (!is_file_exist(file)) {
2732                 g_warning("File %s doesn't exist\n", filename);
2733                 return;
2734         }
2735         if ((size = get_file_size(file)) < 0) {
2736                 g_warning("Can't get file size of %s\n", filename);
2737                 return;
2738         }
2739         if (size == 0) {
2740                 alertpanel_notice(_("File %s is empty."), filename);
2741                 return;
2742         }
2743         if ((fp = g_fopen(file, "rb")) == NULL) {
2744                 alertpanel_error(_("Can't read %s."), filename);
2745                 return;
2746         }
2747         fclose(fp);
2748
2749         ainfo = g_new0(AttachInfo, 1);
2750         auto_ainfo = g_auto_pointer_new_with_free
2751                         (ainfo, (GFreeFunc) compose_attach_info_free); 
2752         ainfo->file = g_strdup(file);
2753
2754         if (content_type) {
2755                 ainfo->content_type = g_strdup(content_type);
2756                 if (!g_ascii_strcasecmp(content_type, "message/rfc822")) {
2757                         MsgInfo *msginfo;
2758                         MsgFlags flags = {0, 0};
2759
2760                         if (procmime_get_encoding_for_text_file(file) == ENC_7BIT)
2761                                 ainfo->encoding = ENC_7BIT;
2762                         else
2763                                 ainfo->encoding = ENC_8BIT;
2764
2765                         msginfo = procheader_parse_file(file, flags, FALSE, FALSE);
2766                         if (msginfo && msginfo->subject)
2767                                 name = g_strdup(msginfo->subject);
2768                         else
2769                                 name = g_path_get_basename(filename ? filename : file);
2770
2771                         ainfo->name = g_strdup_printf(_("Message: %s"), name);
2772
2773                         procmsg_msginfo_free(msginfo);
2774                 } else {
2775                         if (!g_ascii_strncasecmp(content_type, "text", 4))
2776                                 ainfo->encoding = procmime_get_encoding_for_text_file(file);
2777                         else
2778                                 ainfo->encoding = ENC_BASE64;
2779                         name = g_path_get_basename(filename ? filename : file);
2780                         ainfo->name = g_strdup(name);
2781                 }
2782                 g_free(name);
2783         } else {
2784                 ainfo->content_type = procmime_get_mime_type(file);
2785                 if (!ainfo->content_type) {
2786                         ainfo->content_type =
2787                                 g_strdup("application/octet-stream");
2788                         ainfo->encoding = ENC_BASE64;
2789                 } else if (!g_ascii_strncasecmp(ainfo->content_type, "text", 4))
2790                         ainfo->encoding =
2791                                 procmime_get_encoding_for_text_file(file);
2792                 else
2793                         ainfo->encoding = ENC_BASE64;
2794                 name = g_path_get_basename(filename ? filename : file);
2795                 ainfo->name = g_strdup(name);   
2796                 g_free(name);
2797         }
2798
2799         if (!strcmp(ainfo->content_type, "unknown")) {
2800                 g_free(ainfo->content_type);
2801                 ainfo->content_type = g_strdup("application/octet-stream");
2802         }
2803
2804         ainfo->size = size;
2805         size_text = to_human_readable(size);
2806
2807         store = GTK_LIST_STORE(gtk_tree_view_get_model
2808                         (GTK_TREE_VIEW(compose->attach_clist)));
2809                 
2810         gtk_list_store_append(store, &iter);
2811         gtk_list_store_set(store, &iter, 
2812                            COL_MIMETYPE, ainfo->content_type,
2813                            COL_SIZE, size_text,
2814                            COL_NAME, ainfo->name,
2815                            COL_DATA, ainfo,
2816                            COL_AUTODATA, auto_ainfo,
2817                            -1);
2818         
2819         g_auto_pointer_free(auto_ainfo);
2820 }
2821
2822 static void compose_use_signing(Compose *compose, gboolean use_signing)
2823 {
2824         GtkItemFactory *ifactory;
2825         GtkWidget *menuitem = NULL;
2826
2827         compose->use_signing = use_signing;
2828         ifactory = gtk_item_factory_from_widget(compose->menubar);
2829         menuitem = gtk_item_factory_get_item
2830                 (ifactory, "/Options/Sign");
2831         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), 
2832                                        use_signing);
2833 }
2834
2835 static void compose_use_encryption(Compose *compose, gboolean use_encryption)
2836 {
2837         GtkItemFactory *ifactory;
2838         GtkWidget *menuitem = NULL;
2839
2840         compose->use_encryption = use_encryption;
2841         ifactory = gtk_item_factory_from_widget(compose->menubar);
2842         menuitem = gtk_item_factory_get_item
2843                 (ifactory, "/Options/Encrypt");
2844
2845         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), 
2846                                        use_encryption);
2847 }
2848
2849 #define NEXT_PART_NOT_CHILD(info)  \
2850 {  \
2851         node = info->node;  \
2852         while (node->children)  \
2853                 node = g_node_last_child(node);  \
2854         info = procmime_mimeinfo_next((MimeInfo *)node->data);  \
2855 }
2856
2857 static void compose_attach_parts(Compose *compose, MsgInfo *msginfo)
2858 {
2859         MimeInfo *mimeinfo;
2860         MimeInfo *child;
2861         MimeInfo *firsttext = NULL;
2862         MimeInfo *encrypted = NULL;
2863         GNode    *node;
2864         gchar *outfile;
2865         const gchar *partname = NULL;
2866
2867         mimeinfo = procmime_scan_message(msginfo);
2868         if (!mimeinfo) return;
2869
2870         if (mimeinfo->node->children == NULL) {
2871                 procmime_mimeinfo_free_all(mimeinfo);
2872                 return;
2873         }
2874
2875         /* find first content part */
2876         child = (MimeInfo *) mimeinfo->node->children->data;
2877         while (child && child->node->children && (child->type == MIMETYPE_MULTIPART))
2878                 child = (MimeInfo *)child->node->children->data;
2879
2880         if (child->type == MIMETYPE_TEXT) {
2881                 firsttext = child;
2882                 debug_print("First text part found\n");
2883         } else if (compose->mode == COMPOSE_REEDIT &&
2884                  child->type == MIMETYPE_APPLICATION &&
2885                  !g_ascii_strcasecmp(child->subtype, "pgp-encrypted")) {
2886                 encrypted = (MimeInfo *)child->node->parent->data;
2887         }
2888      
2889         child = (MimeInfo *) mimeinfo->node->children->data;
2890         while (child != NULL) {
2891                 if (child == encrypted) {
2892                         /* skip this part of tree */
2893                         NEXT_PART_NOT_CHILD(child);
2894                         continue;
2895                 }
2896
2897                 if (child->type == MIMETYPE_MULTIPART) {
2898                         /* get the actual content */
2899                         child = procmime_mimeinfo_next(child);
2900                         continue;
2901                 }
2902                     
2903                 if (child == firsttext) {
2904                         child = procmime_mimeinfo_next(child);
2905                         continue;
2906                 }
2907
2908                 outfile = procmime_get_tmp_file_name(child);
2909                 if (procmime_get_part(outfile, child) < 0)
2910                         g_warning("Can't get the part of multipart message.");
2911                 else {
2912                         gchar *content_type;
2913
2914                         content_type = procmime_get_content_type_str(child->type, child->subtype);
2915
2916                         /* if we meet a pgp signature, we don't attach it, but
2917                          * we force signing. */
2918                         if (strcmp(content_type, "application/pgp-signature")) {
2919                                 partname = procmime_mimeinfo_get_parameter(child, "filename");
2920                                 if (partname == NULL)
2921                                         partname = procmime_mimeinfo_get_parameter(child, "name");
2922                                 if (partname == NULL)
2923                                         partname = "";
2924                                 compose_attach_append(compose, outfile, 
2925                                                       partname, content_type);
2926                         } else {
2927                                 compose_force_signing(compose, compose->account);
2928                         }
2929                         g_free(content_type);
2930                 }
2931                 g_free(outfile);
2932                 NEXT_PART_NOT_CHILD(child);
2933         }
2934         procmime_mimeinfo_free_all(mimeinfo);
2935 }
2936
2937 #undef NEXT_PART_NOT_CHILD
2938
2939
2940
2941 typedef enum {
2942         WAIT_FOR_INDENT_CHAR,
2943         WAIT_FOR_INDENT_CHAR_OR_SPACE,
2944 } IndentState;
2945
2946 /* return indent length, we allow:
2947    indent characters followed by indent characters or spaces/tabs,
2948    alphabets and numbers immediately followed by indent characters,
2949    and the repeating sequences of the above
2950    If quote ends with multiple spaces, only the first one is included. */
2951 static gchar *compose_get_quote_str(GtkTextBuffer *buffer,
2952                                     const GtkTextIter *start, gint *len)
2953 {
2954         GtkTextIter iter = *start;
2955         gunichar wc;
2956         gchar ch[6];
2957         gint clen;
2958         IndentState state = WAIT_FOR_INDENT_CHAR;
2959         gboolean is_space;
2960         gboolean is_indent;
2961         gint alnum_count = 0;
2962         gint space_count = 0;
2963         gint quote_len = 0;
2964
2965         if (prefs_common.quote_chars == NULL) {
2966                 return 0 ;
2967         }
2968
2969         while (!gtk_text_iter_ends_line(&iter)) {
2970                 wc = gtk_text_iter_get_char(&iter);
2971                 if (g_unichar_iswide(wc))
2972                         break;
2973                 clen = g_unichar_to_utf8(wc, ch);
2974                 if (clen != 1)
2975                         break;
2976
2977                 is_indent = strchr(prefs_common.quote_chars, ch[0]) ? TRUE : FALSE;
2978                 is_space = g_unichar_isspace(wc);
2979
2980                 if (state == WAIT_FOR_INDENT_CHAR) {
2981                         if (!is_indent && !g_unichar_isalnum(wc))
2982                                 break;
2983                         if (is_indent) {
2984                                 quote_len += alnum_count + space_count + 1;
2985                                 alnum_count = space_count = 0;
2986                                 state = WAIT_FOR_INDENT_CHAR_OR_SPACE;
2987                         } else
2988                                 alnum_count++;
2989                 } else if (state == WAIT_FOR_INDENT_CHAR_OR_SPACE) {
2990                         if (!is_indent && !is_space && !g_unichar_isalnum(wc))
2991                                 break;
2992                         if (is_space)
2993                                 space_count++;
2994                         else if (is_indent) {
2995                                 quote_len += alnum_count + space_count + 1;
2996                                 alnum_count = space_count = 0;
2997                         } else {
2998                                 alnum_count++;
2999                                 state = WAIT_FOR_INDENT_CHAR;
3000                         }
3001                 }
3002
3003                 gtk_text_iter_forward_char(&iter);
3004         }
3005
3006         if (quote_len > 0 && space_count > 0)
3007                 quote_len++;
3008
3009         if (len)
3010                 *len = quote_len;
3011
3012         if (quote_len > 0) {
3013                 iter = *start;
3014                 gtk_text_iter_forward_chars(&iter, quote_len);
3015                 return gtk_text_buffer_get_text(buffer, start, &iter, FALSE);
3016         }
3017
3018         return NULL;
3019 }
3020
3021 /* return TRUE if the line is itemized */
3022 static gboolean compose_is_itemized(GtkTextBuffer *buffer,
3023                                     const GtkTextIter *start)
3024 {
3025         GtkTextIter iter = *start;
3026         gunichar wc;
3027         gchar ch[6];
3028         gint clen;
3029
3030         if (gtk_text_iter_ends_line(&iter))
3031                 return FALSE;
3032
3033         while (1) {
3034                 wc = gtk_text_iter_get_char(&iter);
3035                 if (!g_unichar_isspace(wc))
3036                         break;
3037                 gtk_text_iter_forward_char(&iter);
3038                 if (gtk_text_iter_ends_line(&iter))
3039                         return FALSE;
3040         }
3041
3042         clen = g_unichar_to_utf8(wc, ch);
3043         if (clen != 1)
3044                 return FALSE;
3045
3046         if (!strchr("*-+", ch[0]))
3047                 return FALSE;
3048
3049         gtk_text_iter_forward_char(&iter);
3050         if (gtk_text_iter_ends_line(&iter))
3051                 return FALSE;
3052         wc = gtk_text_iter_get_char(&iter);
3053         if (g_unichar_isspace(wc))
3054                 return TRUE;
3055
3056         return FALSE;
3057 }
3058
3059 static gboolean compose_get_line_break_pos(GtkTextBuffer *buffer,
3060                                            const GtkTextIter *start,
3061                                            GtkTextIter *break_pos,
3062                                            gint max_col,
3063                                            gint quote_len)
3064 {
3065         GtkTextIter iter = *start, line_end = *start;
3066         PangoLogAttr *attrs;
3067         gchar *str;
3068         gchar *p;
3069         gint len;
3070         gint i;
3071         gint col = 0;
3072         gint pos = 0;
3073         gboolean can_break = FALSE;
3074         gboolean do_break = FALSE;
3075         gboolean was_white = FALSE;
3076         gboolean prev_dont_break = FALSE;
3077
3078         gtk_text_iter_forward_to_line_end(&line_end);
3079         str = gtk_text_buffer_get_text(buffer, &iter, &line_end, FALSE);
3080         len = g_utf8_strlen(str, -1);
3081         /* g_print("breaking line: %d: %s (len = %d)\n",
3082                 gtk_text_iter_get_line(&iter), str, len); */
3083         attrs = g_new(PangoLogAttr, len + 1);
3084
3085         pango_default_break(str, -1, NULL, attrs, len + 1);
3086
3087         p = str;
3088
3089         /* skip quote and leading spaces */
3090         for (i = 0; *p != '\0' && i < len; i++) {
3091                 gunichar wc;
3092
3093                 wc = g_utf8_get_char(p);
3094                 if (i >= quote_len && !g_unichar_isspace(wc))
3095                         break;
3096                 if (g_unichar_iswide(wc))
3097                         col += 2;
3098                 else if (*p == '\t')
3099                         col += 8;
3100                 else
3101                         col++;
3102                 p = g_utf8_next_char(p);
3103         }
3104
3105         for (; *p != '\0' && i < len; i++) {
3106                 PangoLogAttr *attr = attrs + i;
3107                 gunichar wc;
3108                 gint uri_len;
3109
3110                 if (attr->is_line_break && can_break && was_white && !prev_dont_break)
3111                         pos = i;
3112                 
3113                 was_white = attr->is_white;
3114
3115                 /* don't wrap URI */
3116                 if ((uri_len = get_uri_len(p)) > 0) {
3117                         col += uri_len;
3118                         if (pos > 0 && col > max_col) {
3119                                 do_break = TRUE;
3120                                 break;
3121                         }
3122                         i += uri_len - 1;
3123                         p += uri_len;
3124                         can_break = TRUE;
3125                         continue;
3126                 }
3127
3128                 wc = g_utf8_get_char(p);
3129                 if (g_unichar_iswide(wc)) {
3130                         col += 2;
3131                         if (prev_dont_break && can_break && attr->is_line_break)
3132                                 pos = i;
3133                 } else if (*p == '\t')
3134                         col += 8;
3135                 else
3136                         col++;
3137                 if (pos > 0 && col > max_col) {
3138                         do_break = TRUE;
3139                         break;
3140                 }
3141
3142                 if (*p == '-' || *p == '/')
3143                         prev_dont_break = TRUE;
3144                 else
3145                         prev_dont_break = FALSE;
3146
3147                 p = g_utf8_next_char(p);
3148                 can_break = TRUE;
3149         }
3150
3151         debug_print("compose_get_line_break_pos(): do_break = %d, pos = %d, col = %d\n", do_break, pos, col);
3152
3153         g_free(attrs);
3154         g_free(str);
3155
3156         *break_pos = *start;
3157         gtk_text_iter_set_line_offset(break_pos, pos);
3158
3159         return do_break;
3160 }
3161
3162 static gboolean compose_join_next_line(Compose *compose,
3163                                        GtkTextBuffer *buffer,
3164                                        GtkTextIter *iter,
3165                                        const gchar *quote_str)
3166 {
3167         GtkTextIter iter_ = *iter, cur, prev, next, end;
3168         PangoLogAttr attrs[3];
3169         gchar *str;
3170         gchar *next_quote_str;
3171         gunichar wc1, wc2;
3172         gint quote_len;
3173         gboolean keep_cursor = FALSE;
3174
3175         if (!gtk_text_iter_forward_line(&iter_) ||
3176             gtk_text_iter_ends_line(&iter_))
3177                 return FALSE;
3178
3179         next_quote_str = compose_get_quote_str(buffer, &iter_, &quote_len);
3180
3181         if ((quote_str || next_quote_str) &&
3182             strcmp2(quote_str, next_quote_str) != 0) {
3183                 g_free(next_quote_str);
3184                 return FALSE;
3185         }
3186         g_free(next_quote_str);
3187
3188         end = iter_;
3189         if (quote_len > 0) {
3190                 gtk_text_iter_forward_chars(&end, quote_len);
3191                 if (gtk_text_iter_ends_line(&end))
3192                         return FALSE;
3193         }
3194
3195         /* don't join itemized lines */
3196         if (compose_is_itemized(buffer, &end))
3197                 return FALSE;
3198
3199         /* don't join signature separator */
3200         if (compose_is_sig_separator(compose, buffer, &iter_))
3201                 return FALSE;
3202
3203         /* delete quote str */
3204         if (quote_len > 0)
3205                 gtk_text_buffer_delete(buffer, &iter_, &end);
3206
3207         /* don't join line breaks put by the user */
3208         prev = cur = iter_;
3209         gtk_text_iter_backward_char(&cur);
3210         if (gtk_text_iter_has_tag(&cur, compose->no_join_tag)) {
3211                 gtk_text_iter_forward_char(&cur);
3212                 *iter = cur;
3213                 return FALSE;
3214         }
3215         gtk_text_iter_forward_char(&cur);
3216         /* delete linebreak and extra spaces */
3217         while (gtk_text_iter_backward_char(&cur)) {
3218                 wc1 = gtk_text_iter_get_char(&cur);
3219                 if (!g_unichar_isspace(wc1))
3220                         break;
3221                 prev = cur;
3222         }
3223         next = cur = iter_;
3224         while (!gtk_text_iter_ends_line(&cur)) {
3225                 wc1 = gtk_text_iter_get_char(&cur);
3226                 if (!g_unichar_isspace(wc1))
3227                         break;
3228                 gtk_text_iter_forward_char(&cur);
3229                 next = cur;
3230         }
3231         if (!gtk_text_iter_equal(&prev, &next)) {
3232                 GtkTextMark *mark;
3233
3234                 mark = gtk_text_buffer_get_insert(buffer);
3235                 gtk_text_buffer_get_iter_at_mark(buffer, &cur, mark);
3236                 if (gtk_text_iter_equal(&prev, &cur))
3237                         keep_cursor = TRUE;
3238                 gtk_text_buffer_delete(buffer, &prev, &next);
3239         }
3240         iter_ = prev;
3241
3242         /* insert space if required */
3243         gtk_text_iter_backward_char(&prev);
3244         wc1 = gtk_text_iter_get_char(&prev);
3245         wc2 = gtk_text_iter_get_char(&next);
3246         gtk_text_iter_forward_char(&next);
3247         str = gtk_text_buffer_get_text(buffer, &prev, &next, FALSE);
3248         pango_default_break(str, -1, NULL, attrs, 3);
3249         if (!attrs[1].is_line_break ||
3250             (!g_unichar_iswide(wc1) || !g_unichar_iswide(wc2))) {
3251                 gtk_text_buffer_insert(buffer, &iter_, " ", 1);
3252                 if (keep_cursor) {
3253                         gtk_text_iter_backward_char(&iter_);
3254                         gtk_text_buffer_place_cursor(buffer, &iter_);
3255                 }
3256         }
3257         g_free(str);
3258
3259         *iter = iter_;
3260         return TRUE;
3261 }
3262
3263 #define ADD_TXT_POS(bp_, ep_, pti_) \
3264         if ((last->next = alloca(sizeof(struct txtpos))) != NULL) { \
3265                 last = last->next; \
3266                 last->bp = (bp_); last->ep = (ep_); last->pti = (pti_); \
3267                 last->next = NULL; \
3268         } else { \
3269                 g_warning("alloc error scanning URIs\n"); \
3270         }
3271
3272 static gboolean automatic_break = FALSE;
3273 static void compose_beautify_paragraph(Compose *compose, GtkTextIter *par_iter, gboolean force)
3274 {
3275         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
3276         GtkTextBuffer *buffer;
3277         GtkTextIter iter, break_pos, end_of_line;
3278         gchar *quote_str = NULL;
3279         gint quote_len;
3280         gboolean wrap_quote = prefs_common.linewrap_quote;
3281         gboolean prev_autowrap = compose->autowrap;
3282         gint startq_offset = -1, noq_offset = -1;
3283         gint uri_start = -1, uri_stop = -1;
3284         gint nouri_start = -1, nouri_stop = -1;
3285         gint num_blocks = 0;
3286
3287         compose->autowrap = FALSE;
3288
3289         buffer = gtk_text_view_get_buffer(text);
3290         undo_wrapping(compose->undostruct, TRUE);
3291         if (par_iter) {
3292                 iter = *par_iter;
3293         } else {
3294                 GtkTextMark *mark;
3295                 mark = gtk_text_buffer_get_insert(buffer);
3296                 gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
3297         }
3298
3299         /* move to paragraph start */
3300         gtk_text_iter_set_line_offset(&iter, 0);
3301         if (gtk_text_iter_ends_line(&iter)) {
3302                 while (gtk_text_iter_ends_line(&iter) &&
3303                        gtk_text_iter_forward_line(&iter))
3304                         ;
3305         } else {
3306                 while (gtk_text_iter_backward_line(&iter)) {
3307                         if (gtk_text_iter_ends_line(&iter)) {
3308                                 gtk_text_iter_forward_line(&iter);
3309                                 break;
3310                         }
3311                 }
3312         }
3313
3314         /* go until paragraph end (empty line) */
3315         
3316         while (!gtk_text_iter_ends_line(&iter)) {
3317                 gchar *scanpos = NULL;
3318                 /* parse table - in order of priority */
3319                 struct table {
3320                         const gchar *needle; /* token */
3321
3322                         /* token search function */
3323                         gchar    *(*search)     (const gchar *haystack,
3324                                                  const gchar *needle);
3325                         /* part parsing function */
3326                         gboolean  (*parse)      (const gchar *start,
3327                                                  const gchar *scanpos,
3328                                                  const gchar **bp_,
3329                                                  const gchar **ep_,
3330                                                  gboolean hdr);
3331                         /* part to URI function */
3332                         gchar    *(*build_uri)  (const gchar *bp,
3333                                                  const gchar *ep);
3334                 };
3335
3336                 static struct table parser[] = {
3337                         {"http://",  strcasestr, get_uri_part,   make_uri_string},
3338                         {"https://", strcasestr, get_uri_part,   make_uri_string},
3339                         {"ftp://",   strcasestr, get_uri_part,   make_uri_string},
3340                         {"www.",     strcasestr, get_uri_part,   make_http_string},
3341                         {"mailto:",  strcasestr, get_uri_part,   make_uri_string},
3342                         {"@",        strcasestr, get_email_part, make_email_string}
3343                 };
3344                 const gint PARSE_ELEMS = sizeof parser / sizeof parser[0];
3345                 gint last_index = PARSE_ELEMS;
3346                 gint  n;
3347                 gchar *o_walk = NULL, *walk = NULL, *bp = NULL, *ep = NULL;
3348                 gint walk_pos;
3349                 
3350                 if (!prev_autowrap && num_blocks == 0) {
3351                         num_blocks++;
3352                         g_signal_handlers_block_by_func(G_OBJECT(buffer),
3353                                         G_CALLBACK(text_inserted),
3354                                         compose);
3355                 }
3356                 if (gtk_text_iter_has_tag(&iter, compose->no_wrap_tag) && !force)
3357                         goto colorize;
3358
3359                 uri_start = uri_stop = -1;
3360                 quote_len = 0;
3361                 quote_str = compose_get_quote_str(buffer, &iter, &quote_len);
3362
3363                 if (quote_str) {
3364                         if (!wrap_quote) {
3365                                 if (startq_offset == -1) {
3366                                         startq_offset = gtk_text_iter_get_offset(&iter);
3367                                 }
3368                                 goto colorize;
3369                         }
3370                         debug_print("compose_beautify_paragraph(): quote_str = '%s'\n", quote_str);
3371                         if (startq_offset == -1) 
3372                                 startq_offset = gtk_text_iter_get_offset(&iter);
3373                 } else {
3374                         if (startq_offset == -1)
3375                                 noq_offset = gtk_text_iter_get_offset(&iter);
3376                 }
3377
3378                 if (prev_autowrap == FALSE && !force && !wrap_quote) {
3379                         goto colorize;
3380                 }
3381                 if (compose_get_line_break_pos(buffer, &iter, &break_pos,
3382                                                prefs_common.linewrap_len,
3383                                                quote_len)) {
3384                         GtkTextIter prev, next, cur;
3385                         
3386                         if (prev_autowrap != FALSE || force) {
3387                                 automatic_break = TRUE;
3388                                 gtk_text_buffer_insert(buffer, &break_pos, "\n", 1);
3389                                 automatic_break = FALSE;
3390                         } else if (quote_str && wrap_quote) {
3391                                 automatic_break = TRUE;
3392                                 gtk_text_buffer_insert(buffer, &break_pos, "\n", 1);
3393                                 automatic_break = FALSE;
3394                         } else 
3395                                 goto colorize;
3396                         /* remove trailing spaces */
3397                         cur = break_pos;
3398                         gtk_text_iter_backward_char(&cur);
3399                         prev = next = cur;
3400                         while (!gtk_text_iter_starts_line(&cur)) {
3401                                 gunichar wc;
3402
3403                                 gtk_text_iter_backward_char(&cur);
3404                                 wc = gtk_text_iter_get_char(&cur);
3405                                 if (!g_unichar_isspace(wc))
3406                                         break;
3407                                 prev = cur;
3408                         }
3409                         if (!gtk_text_iter_equal(&prev, &next)) {
3410                                 gtk_text_buffer_delete(buffer, &prev, &next);
3411                                 break_pos = next;
3412                                 gtk_text_iter_forward_char(&break_pos);
3413                         }
3414
3415                         if (quote_str)
3416                                 gtk_text_buffer_insert(buffer, &break_pos,
3417                                                        quote_str, -1);
3418
3419                         iter = break_pos;
3420                         compose_join_next_line(compose, buffer, &iter, quote_str);
3421
3422                         /* move iter to current line start */
3423                         gtk_text_iter_set_line_offset(&iter, 0);
3424                         if (quote_str) {
3425                                 g_free(quote_str);
3426                                 quote_str = NULL;
3427                         }
3428                         continue;
3429                 } else {
3430                         /* move iter to next line start */
3431                         iter = break_pos;
3432                 }
3433
3434 colorize:
3435                 if (!prev_autowrap) {
3436                         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),
3437                                         G_CALLBACK(text_inserted),
3438                                         compose);
3439                 }
3440                 end_of_line = iter;
3441                 while (!gtk_text_iter_ends_line(&end_of_line)) {
3442                         gtk_text_iter_forward_char(&end_of_line);
3443                 }
3444                 o_walk = walk = gtk_text_buffer_get_text(buffer, &iter, &end_of_line, FALSE);
3445
3446                 nouri_start = gtk_text_iter_get_offset(&iter);
3447                 nouri_stop = gtk_text_iter_get_offset(&end_of_line);
3448
3449                 walk_pos = gtk_text_iter_get_offset(&iter);
3450                 /* FIXME: this looks phony. scanning for anything in the parse table */
3451                 for (n = 0; n < PARSE_ELEMS; n++) {
3452                         gchar *tmp;
3453
3454                         tmp = parser[n].search(walk, parser[n].needle);
3455                         if (tmp) {
3456                                 if (scanpos == NULL || tmp < scanpos) {
3457                                         scanpos = tmp;
3458                                         last_index = n;
3459                                 }
3460                         }                                       
3461                 }
3462
3463                 bp = ep = 0;
3464                 if (scanpos) {
3465                         /* check if URI can be parsed */
3466                         if (parser[last_index].parse(walk, scanpos, (const gchar **)&bp,
3467                                         (const gchar **)&ep, FALSE)
3468                             && (size_t) (ep - bp - 1) > strlen(parser[last_index].needle)) {
3469                                         walk = ep;
3470                         } else
3471                                 walk = scanpos +
3472                                         strlen(parser[last_index].needle);
3473                 } 
3474                 if (bp && ep) {
3475                         uri_start = walk_pos + (bp - o_walk);
3476                         uri_stop  = walk_pos + (ep - o_walk);
3477                 }
3478                 g_free(o_walk);
3479                 o_walk = NULL;
3480                 gtk_text_iter_forward_line(&iter);
3481                 g_free(quote_str);
3482                 quote_str = NULL;
3483                 if (startq_offset != -1) {
3484                         GtkTextIter startquote, endquote;
3485                         gtk_text_buffer_get_iter_at_offset(
3486                                 buffer, &startquote, startq_offset);
3487                         endquote = iter;
3488                         gtk_text_buffer_apply_tag_by_name(
3489                                 buffer, "quote", &startquote, &endquote);
3490                         startq_offset = -1;
3491                 } else if (noq_offset != -1) {
3492                         GtkTextIter startnoquote, endnoquote;
3493                         gtk_text_buffer_get_iter_at_offset(
3494                                 buffer, &startnoquote, noq_offset);
3495                         endnoquote = iter;
3496                         gtk_text_buffer_remove_tag_by_name(
3497                                 buffer, "quote", &startnoquote, &endnoquote);
3498                         noq_offset = -1;
3499                 }
3500                 
3501                 /* always */ {
3502                         GtkTextIter nouri_start_iter, nouri_end_iter;
3503                         gtk_text_buffer_get_iter_at_offset(
3504                                 buffer, &nouri_start_iter, nouri_start);
3505                         gtk_text_buffer_get_iter_at_offset(
3506                                 buffer, &nouri_end_iter, nouri_stop);
3507                         gtk_text_buffer_remove_tag_by_name(
3508                                 buffer, "link", &nouri_start_iter, &nouri_end_iter);
3509                 }
3510                 if (uri_start > 0 && uri_stop > 0) {
3511                         GtkTextIter uri_start_iter, uri_end_iter;
3512                         gtk_text_buffer_get_iter_at_offset(
3513                                 buffer, &uri_start_iter, uri_start);
3514                         gtk_text_buffer_get_iter_at_offset(
3515                                 buffer, &uri_end_iter, uri_stop);
3516                         gtk_text_buffer_apply_tag_by_name(
3517                                 buffer, "link", &uri_start_iter, &uri_end_iter);
3518                 }
3519         }
3520
3521         if (par_iter)
3522                 *par_iter = iter;
3523         undo_wrapping(compose->undostruct, FALSE);
3524         compose->autowrap = prev_autowrap;
3525 }
3526
3527 void compose_action_cb(void *data)
3528 {
3529         Compose *compose = (Compose *)data;
3530         compose_wrap_all(compose);
3531 }
3532
3533 static void compose_wrap_all(Compose *compose)
3534 {
3535         compose_wrap_all_full(compose, FALSE);
3536 }
3537
3538 static void compose_wrap_all_full(Compose *compose, gboolean force)
3539 {
3540         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
3541         GtkTextBuffer *buffer;
3542         GtkTextIter iter;
3543
3544         buffer = gtk_text_view_get_buffer(text);
3545
3546         gtk_text_buffer_get_start_iter(buffer, &iter);
3547         while (!gtk_text_iter_is_end(&iter))
3548                 compose_beautify_paragraph(compose, &iter, force);
3549
3550 }
3551
3552 static void compose_set_title(Compose *compose)
3553 {
3554         gchar *str;
3555         gchar *edited;
3556         gchar *subject;
3557         
3558         edited = compose->modified ? _(" [Edited]") : "";
3559         
3560         subject = gtk_editable_get_chars(
3561                         GTK_EDITABLE(compose->subject_entry), 0, -1);
3562
3563         if (subject && strlen(subject))
3564                 str = g_strdup_printf(_("%s - Compose message%s"),
3565                                       subject, edited); 
3566         else
3567                 str = g_strdup_printf(_("[no subject] - Compose message%s"), edited);
3568         gtk_window_set_title(GTK_WINDOW(compose->window), str);
3569         g_free(str);
3570         g_free(subject);
3571 }
3572
3573 /**
3574  * compose_current_mail_account:
3575  * 
3576  * Find a current mail account (the currently selected account, or the
3577  * default account, if a news account is currently selected).  If a
3578  * mail account cannot be found, display an error message.
3579  * 
3580  * Return value: Mail account, or NULL if not found.
3581  **/
3582 static PrefsAccount *
3583 compose_current_mail_account(void)
3584 {
3585         PrefsAccount *ac;
3586
3587         if (cur_account && cur_account->protocol != A_NNTP)
3588                 ac = cur_account;
3589         else {
3590                 ac = account_get_default();
3591                 if (!ac || ac->protocol == A_NNTP) {
3592                         alertpanel_error(_("Account for sending mail is not specified.\n"
3593                                            "Please select a mail account before sending."));
3594                         return NULL;
3595                 }
3596         }
3597         return ac;
3598 }
3599
3600 static void compose_select_account(Compose *compose, PrefsAccount *account,
3601                                    gboolean init)
3602 {
3603         GtkItemFactory *ifactory;
3604
3605         g_return_if_fail(account != NULL);
3606
3607         compose->account = account;
3608
3609         compose_set_title(compose);
3610
3611         ifactory = gtk_item_factory_from_widget(compose->menubar);
3612
3613         if (account->default_sign && compose->mode != COMPOSE_REDIRECT)
3614                 menu_set_active(ifactory, "/Options/Sign", TRUE);
3615         else
3616                 menu_set_active(ifactory, "/Options/Sign", FALSE);
3617         if (account->default_encrypt && compose->mode != COMPOSE_REDIRECT)
3618                 menu_set_active(ifactory, "/Options/Encrypt", TRUE);
3619         else
3620                 menu_set_active(ifactory, "/Options/Encrypt", FALSE);
3621                                        
3622         activate_privacy_system(compose, account, FALSE);
3623
3624         if (!init && compose->mode != COMPOSE_REDIRECT)
3625                 compose_insert_sig(compose, TRUE);
3626 }
3627
3628 gboolean compose_check_for_valid_recipient(Compose *compose) {
3629         gchar *recipient_headers_mail[] = {"To:", "Cc:", "Bcc:", NULL};
3630         gchar *recipient_headers_news[] = {"Newsgroups:", NULL};
3631         gboolean recipient_found = FALSE;
3632         GSList *list;
3633         gchar **strptr;
3634
3635         /* free to and newsgroup list */
3636         slist_free_strings(compose->to_list);
3637         g_slist_free(compose->to_list);
3638         compose->to_list = NULL;
3639                         
3640         slist_free_strings(compose->newsgroup_list);
3641         g_slist_free(compose->newsgroup_list);
3642         compose->newsgroup_list = NULL;
3643
3644         /* search header entries for to and newsgroup entries */
3645         for (list = compose->header_list; list; list = list->next) {
3646                 gchar *header;
3647                 gchar *entry;
3648                 header = gtk_editable_get_chars(GTK_EDITABLE(GTK_COMBO(((ComposeHeaderEntry *)list->data)->combo)->entry), 0, -1);
3649                 entry = gtk_editable_get_chars(GTK_EDITABLE(((ComposeHeaderEntry *)list->data)->entry), 0, -1);
3650                 g_strstrip(entry);
3651                 if (entry[0] != '\0') {
3652                         for (strptr = recipient_headers_mail; *strptr != NULL; strptr++) {
3653                                 if (!strcmp(header, (prefs_common.trans_hdr ? gettext(*strptr) : *strptr))) {
3654                                         compose->to_list = address_list_append(compose->to_list, entry);
3655                                         recipient_found = TRUE;
3656                                 }
3657                         }
3658                         for (strptr = recipient_headers_news; *strptr != NULL; strptr++) {
3659                                 if (!strcmp(header, (prefs_common.trans_hdr ? gettext(*strptr) : *strptr))) {
3660                                         compose->newsgroup_list = newsgroup_list_append(compose->newsgroup_list, entry);
3661                                         recipient_found = TRUE;
3662                                 }
3663                         }
3664                 }
3665                 g_free(header);
3666                 g_free(entry);
3667         }
3668         return recipient_found;
3669 }
3670
3671 static gboolean compose_check_for_set_recipients(Compose *compose)
3672 {
3673         if (compose->account->set_autocc && compose->account->auto_cc) {
3674                 gboolean found_other = FALSE;
3675                 GSList *list;
3676                 /* search header entries for to and newsgroup entries */
3677                 for (list = compose->header_list; list; list = list->next) {
3678                         gchar *entry;
3679                         gchar *header;
3680                         entry = gtk_editable_get_chars(GTK_EDITABLE(((ComposeHeaderEntry *)list->data)->entry), 0, -1);
3681                         header = gtk_editable_get_chars(GTK_EDITABLE(GTK_COMBO(((ComposeHeaderEntry *)list->data)->combo)->entry), 0, -1);
3682                         g_strstrip(entry);
3683                         if (strcmp(entry, compose->account->auto_cc)
3684                         ||  strcmp(header, (prefs_common.trans_hdr ? gettext("Cc:") : "Cc:"))) {
3685                                 found_other = TRUE;
3686                                 g_free(entry);
3687                                 break;
3688                         }
3689                         g_free(entry);
3690                         g_free(header);
3691                 }
3692                 if (!found_other) {
3693                         AlertValue aval;
3694                         aval = alertpanel(_("Send"),
3695                                           _("The only recipient is the default CC address. Send anyway?"),
3696                                           GTK_STOCK_CANCEL, _("+_Send"), NULL);
3697                         if (aval != G_ALERTALTERNATE)
3698                                 return FALSE;
3699                 }
3700         }
3701         if (compose->account->set_autobcc && compose->account->auto_bcc) {
3702                 gboolean found_other = FALSE;
3703                 GSList *list;
3704                 /* search header entries for to and newsgroup entries */
3705                 for (list = compose->header_list; list; list = list->next) {
3706                         gchar *entry;
3707                         gchar *header;
3708                         entry = gtk_editable_get_chars(GTK_EDITABLE(((ComposeHeaderEntry *)list->data)->entry), 0, -1);
3709                         header = gtk_editable_get_chars(GTK_EDITABLE(GTK_COMBO(((ComposeHeaderEntry *)list->data)->combo)->entry), 0, -1);
3710                         g_strstrip(entry);
3711                         if (strcmp(entry, compose->account->auto_cc)
3712                         ||  strcmp(header, (prefs_common.trans_hdr ? gettext("Bcc:") : "Bcc:"))) {
3713                                 found_other = TRUE;
3714                                 g_free(entry);
3715                                 break;
3716                         }
3717                         g_free(entry);
3718                         g_free(header);
3719                 }
3720                 if (!found_other) {
3721                         AlertValue aval;
3722                         aval = alertpanel(_("Send"),
3723                                           _("The only recipient is the default BCC address. Send anyway?"),
3724                                           GTK_STOCK_CANCEL, _("+_Send"), NULL);
3725                         if (aval != G_ALERTALTERNATE)
3726                                 return FALSE;
3727                 }
3728         }
3729         return TRUE;
3730 }
3731
3732 static gboolean compose_check_entries(Compose *compose, gboolean check_subject)
3733 {
3734         const gchar *str;
3735
3736         if (compose_check_for_valid_recipient(compose) == FALSE) {
3737                 alertpanel_error(_("Recipient is not specified."));
3738                 return FALSE;
3739         }
3740
3741         if (compose_check_for_set_recipients(compose) == FALSE) {
3742                 return FALSE;
3743         }
3744
3745         str = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
3746         if (*str == '\0' && check_subject == TRUE) {
3747                 AlertValue aval;
3748
3749                 aval = alertpanel(_("Send"),
3750                                   _("Subject is empty. Send it anyway?"),
3751                                   GTK_STOCK_CANCEL, _("+_Send"), NULL);
3752                 if (aval != G_ALERTALTERNATE)
3753                         return FALSE;
3754         }
3755
3756         return TRUE;
3757 }
3758
3759 gint compose_send(Compose *compose)
3760 {
3761         gint msgnum;
3762         FolderItem *folder;
3763         gint val = -1;
3764         gchar *msgpath;
3765
3766         compose_allow_user_actions (compose, FALSE);
3767         compose->sending = TRUE;
3768
3769         if (compose_check_entries(compose, TRUE) == FALSE)
3770                 goto bail;
3771
3772         val = compose_queue(compose, &msgnum, &folder);
3773
3774         if (val) {
3775                 if (val == -4) {
3776                         alertpanel_error(_("Could not queue message for sending:\n\n"
3777                                            "Charset conversion failed."));
3778                 } else if (val == -3) {
3779                         alertpanel_error(_("Could not queue message for sending:\n\n"
3780                                            "Signature failed."));
3781                 } else if (val == -2 && errno != 0) {
3782                         alertpanel_error(_("Could not queue message for sending:\n\n%s."), strerror(errno));
3783                 } else {
3784                         alertpanel_error(_("Could not queue message for sending."));
3785                 }
3786                 goto bail;
3787         }
3788
3789
3790         if (prefs_common.send_dialog_mode != SEND_DIALOG_ALWAYS) {
3791                 compose->sending = FALSE;
3792                 compose_close(compose);
3793                 /* No more compose access in the normal codepath 
3794                  * after this point! */
3795                 compose = NULL;
3796         }
3797
3798         if (msgnum == 0) {
3799                 alertpanel_error(_("The message was queued but could not be "
3800                                    "sent.\nUse \"Send queued messages\" from "
3801                                    "the main window to retry."));
3802                 if (prefs_common.send_dialog_mode == SEND_DIALOG_ALWAYS) {
3803                         compose->sending = FALSE;
3804                         compose->modified = TRUE; 
3805                         compose_allow_user_actions (compose, TRUE);
3806                 }
3807                 return 0;
3808         }
3809         
3810         msgpath = folder_item_fetch_msg(folder, msgnum);
3811         val = procmsg_send_message_queue(msgpath);
3812         g_free(msgpath);
3813
3814         if (prefs_common.send_dialog_mode == SEND_DIALOG_ALWAYS) {
3815                 compose->sending = FALSE;
3816                 compose_allow_user_actions (compose, TRUE);
3817                 if (val != 0) {
3818                         folder_item_remove_msg(folder, msgnum);
3819                         folder_item_scan(folder);
3820                 }
3821         }
3822
3823         if (val == 0) {
3824                 folder_item_remove_msg(folder, msgnum);
3825                 folder_item_scan(folder);
3826                 if (prefs_common.send_dialog_mode == SEND_DIALOG_ALWAYS)
3827                         compose_close(compose);
3828         } else {
3829                 alertpanel_error(_("The message was queued but could not be "
3830                                    "sent.\nUse \"Send queued messages\" from "
3831                                    "the main window to retry."));
3832                 if (prefs_common.send_dialog_mode == SEND_DIALOG_ALWAYS) {
3833                         compose_allow_user_actions (compose, TRUE);
3834                         compose->modified = TRUE; 
3835                         compose->sending = FALSE;               
3836                 }
3837                 return -1;
3838         }
3839
3840         return 0;
3841
3842 bail:
3843         compose_allow_user_actions (compose, TRUE);
3844         compose->sending = FALSE;
3845         compose->modified = TRUE; 
3846
3847         return -1;
3848 }
3849
3850 static gboolean compose_use_attach(Compose *compose) 
3851 {
3852         GtkTreeModel *model = gtk_tree_view_get_model
3853                                 (GTK_TREE_VIEW(compose->attach_clist));
3854         return gtk_tree_model_iter_n_children(model, NULL) > 0;
3855 }
3856
3857 static gint compose_redirect_write_headers_from_headerlist(Compose *compose, 
3858                                                            FILE *fp)
3859 {
3860         gchar buf[BUFFSIZE];
3861         gchar *str;
3862         gboolean first_to_address;
3863         gboolean first_cc_address;
3864         GSList *list;
3865         ComposeHeaderEntry *headerentry;
3866         const gchar *headerentryname;
3867         gchar *cc_hdr;
3868         gchar *to_hdr;
3869
3870         debug_print("Writing redirect header\n");
3871
3872         cc_hdr = prefs_common.trans_hdr ? _("Cc:") : "Cc:";
3873         to_hdr = prefs_common.trans_hdr ? _("To:") : "To:";
3874
3875         first_to_address = TRUE;
3876         for (list = compose->header_list; list; list = list->next) {
3877                 headerentry = ((ComposeHeaderEntry *)list->data);
3878                 headerentryname = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry));
3879
3880                 if (g_utf8_collate(headerentryname, to_hdr) == 0) {
3881                         const gchar *entstr = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
3882                         Xstrdup_a(str, entstr, return -1);
3883                         g_strstrip(str);
3884                         if (str[0] != '\0') {
3885                                 compose_convert_header
3886                                         (compose, buf, sizeof(buf), str,
3887                                         strlen("Resent-To") + 2, TRUE);
3888
3889                                 if (first_to_address) {
3890                                         fprintf(fp, "Resent-To: ");
3891                                         first_to_address = FALSE;
3892                                 } else {
3893                                         fprintf(fp, ",");
3894                                 }
3895                                 fprintf(fp, "%s", buf);
3896                         }
3897                 }
3898         }
3899         if (!first_to_address) {
3900                 fprintf(fp, "\n");
3901         }
3902
3903         first_cc_address = TRUE;
3904         for (list = compose->header_list; list; list = list->next) {
3905                 headerentry = ((ComposeHeaderEntry *)list->data);
3906                 headerentryname = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry));
3907
3908                 if (g_utf8_collate(headerentryname, cc_hdr) == 0) {
3909                         const gchar *strg = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
3910                         Xstrdup_a(str, strg, return -1);
3911                         g_strstrip(str);
3912                         if (str[0] != '\0') {
3913                                 compose_convert_header
3914                                         (compose, buf, sizeof(buf), str,
3915                                         strlen("Resent-Cc") + 2, TRUE);
3916
3917                                 if (first_cc_address) {
3918                                         fprintf(fp, "Resent-Cc: ");
3919                                         first_cc_address = FALSE;
3920                                 } else {
3921                                         fprintf(fp, ",");
3922                                 }
3923                                 fprintf(fp, "%s", buf);
3924                         }
3925                 }
3926         }
3927         if (!first_cc_address) {
3928                 fprintf(fp, "\n");
3929         }
3930         
3931         return(0);
3932 }
3933
3934 static gint compose_redirect_write_headers(Compose *compose, FILE *fp)
3935 {
3936         gchar buf[BUFFSIZE];
3937         gchar *str;
3938         const gchar *entstr;
3939         /* struct utsname utsbuf; */
3940
3941         g_return_val_if_fail(fp != NULL, -1);
3942         g_return_val_if_fail(compose->account != NULL, -1);
3943         g_return_val_if_fail(compose->account->address != NULL, -1);
3944
3945         /* Resent-Date */
3946         get_rfc822_date(buf, sizeof(buf));
3947         fprintf(fp, "Resent-Date: %s\n", buf);
3948
3949         /* Resent-From */
3950         if (compose->account->name && *compose->account->name) {
3951                 compose_convert_header
3952                         (compose, buf, sizeof(buf), compose->account->name,
3953                          strlen("From: "), TRUE);
3954                 fprintf(fp, "Resent-From: %s <%s>\n",
3955                         buf, compose->account->address);
3956         } else
3957                 fprintf(fp, "Resent-From: %s\n", compose->account->address);
3958
3959         /* Subject */
3960         entstr = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
3961         if (*entstr != '\0') {
3962                 Xstrdup_a(str, entstr, return -1);
3963                 g_strstrip(str);
3964                 if (*str != '\0') {
3965                         compose_convert_header(compose, buf, sizeof(buf), str,
3966                                                strlen("Subject: "), FALSE);
3967                         fprintf(fp, "Subject: %s\n", buf);
3968                 }
3969         }
3970
3971         /* Resent-Message-ID */
3972         if (compose->account->gen_msgid) {
3973                 generate_msgid(buf, sizeof(buf));
3974                 fprintf(fp, "Resent-Message-ID: <%s>\n", buf);
3975                 compose->msgid = g_strdup(buf);
3976         }
3977
3978         compose_redirect_write_headers_from_headerlist(compose, fp);
3979
3980         /* separator between header and body */
3981         fputs("\n", fp);
3982
3983         return 0;
3984 }
3985
3986 static gint compose_redirect_write_to_file(Compose *compose, FILE *fdest)
3987 {
3988         FILE *fp;
3989         size_t len;
3990         gchar buf[BUFFSIZE];
3991
3992         if ((fp = g_fopen(compose->redirect_filename, "rb")) == NULL) {
3993                 FILE_OP_ERROR(compose->redirect_filename, "fopen");
3994                 return -1;
3995         }
3996
3997         while (procheader_get_one_field_asis(buf, sizeof(buf), fp) != -1) {
3998                 /* should filter returnpath, delivered-to */
3999                 if (g_ascii_strncasecmp(buf, "Return-Path:",
4000                                         strlen("Return-Path:")) == 0 ||
4001                     g_ascii_strncasecmp(buf, "Delivered-To:",
4002                                         strlen("Delivered-To:")) == 0 ||
4003                     g_ascii_strncasecmp(buf, "Received:",
4004                                         strlen("Received:")) == 0 ||
4005                     g_ascii_strncasecmp(buf, "Subject:",
4006                                         strlen("Subject:")) == 0 ||
4007                     g_ascii_strncasecmp(buf, "X-UIDL:",
4008                                         strlen("X-UIDL:")) == 0)
4009                         continue;
4010
4011                 if (fputs(buf, fdest) == -1)
4012                         goto error;
4013
4014                 if (!prefs_common.redirect_keep_from) {
4015                         if (g_ascii_strncasecmp(buf, "From:",
4016                                           strlen("From:")) == 0) {
4017                                 fputs(" (by way of ", fdest);
4018                                 if (compose->account->name
4019                                     && *compose->account->name) {
4020                                         compose_convert_header
4021                                                 (compose, buf, sizeof(buf),
4022                                                  compose->account->name,
4023                                                  strlen("From: "),
4024                                                  FALSE);
4025                                         fprintf(fdest, "%s <%s>",
4026                                                 buf,
4027                                                 compose->account->address);
4028                                 } else
4029                                         fprintf(fdest, "%s",
4030                                                 compose->account->address);
4031                                 fputs(")", fdest);
4032                         }
4033                 }
4034
4035                 if (fputs("\n", fdest) == -1)
4036                         goto error;
4037         }
4038
4039         compose_redirect_write_headers(compose, fdest);
4040
4041         while ((len = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
4042                 if (fwrite(buf, sizeof(gchar), len, fdest) != len)
4043                         goto error;
4044         }
4045
4046         fclose(fp);
4047
4048         return 0;
4049 error:
4050         fclose(fp);
4051
4052         return -1;
4053 }
4054
4055 static gint compose_write_to_file(Compose *compose, FILE *fp, gint action)
4056 {
4057         GtkTextBuffer *buffer;
4058         GtkTextIter start, end;
4059         gchar *chars;
4060         gchar *buf;
4061         const gchar *out_codeset;
4062         EncodingType encoding;
4063         MimeInfo *mimemsg, *mimetext;
4064         gint line;
4065
4066         /* create message MimeInfo */
4067         mimemsg = procmime_mimeinfo_new();
4068         mimemsg->type = MIMETYPE_MESSAGE;
4069         mimemsg->subtype = g_strdup("rfc822");
4070         mimemsg->content = MIMECONTENT_MEM;
4071         mimemsg->tmp = TRUE; /* must free content later */
4072         mimemsg->data.mem = compose_get_header(compose);
4073
4074         /* Create text part MimeInfo */
4075         /* get all composed text */
4076         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(compose->text));
4077         gtk_text_buffer_get_start_iter(buffer, &start);
4078         gtk_text_buffer_get_end_iter(buffer, &end);
4079         chars = gtk_text_buffer_get_text(buffer, &start, &end, FALSE);
4080         if (is_ascii_str(chars)) {
4081                 buf = chars;
4082                 chars = NULL;
4083                 out_codeset = CS_US_ASCII;
4084                 encoding = ENC_7BIT;
4085         } else {
4086                 const gchar *src_codeset = CS_INTERNAL;
4087
4088                 out_codeset = conv_get_charset_str(compose->out_encoding);
4089
4090                 if (!out_codeset) {
4091                         gchar *test_conv_global_out = NULL;
4092                         gchar *test_conv_reply = NULL;
4093
4094                         /* automatic mode. be automatic. */
4095                         codeconv_set_strict(TRUE);
4096                         
4097                         out_codeset = conv_get_outgoing_charset_str();
4098                         if (out_codeset) {
4099                                 debug_print("trying to convert to %s\n", out_codeset);
4100                                 test_conv_global_out = conv_codeset_strdup(chars, src_codeset, out_codeset);
4101                         }
4102                         
4103                         if (!test_conv_global_out && compose->orig_charset
4104                         &&  strcmp(compose->orig_charset, CS_US_ASCII)) {
4105                                 out_codeset = compose->orig_charset;
4106                                 debug_print("failure; trying to convert to %s\n", out_codeset);
4107                                 test_conv_reply = conv_codeset_strdup(chars, src_codeset, out_codeset);
4108                         }
4109                         
4110                         if (!test_conv_global_out && !test_conv_reply) {
4111                                 /* we're lost */
4112                                 out_codeset = CS_INTERNAL;
4113                                 debug_print("failure; finally using %s\n", out_codeset);
4114                         }
4115                         g_free(test_conv_global_out);
4116                         g_free(test_conv_reply);
4117                         codeconv_set_strict(FALSE);
4118                 }
4119
4120                 if (!g_ascii_strcasecmp(out_codeset, CS_US_ASCII))
4121                         out_codeset = CS_ISO_8859_1;
4122
4123                 if (prefs_common.encoding_method == CTE_BASE64)
4124                         encoding = ENC_BASE64;
4125                 else if (prefs_common.encoding_method == CTE_QUOTED_PRINTABLE)
4126                         encoding = ENC_QUOTED_PRINTABLE;
4127                 else if (prefs_common.encoding_method == CTE_8BIT)
4128                         encoding = ENC_8BIT;
4129                 else
4130                         encoding = procmime_get_encoding_for_charset(out_codeset);
4131
4132                 debug_print("src encoding = %s, out encoding = %s, transfer encoding = %s\n",
4133                             src_codeset, out_codeset, procmime_get_encoding_str(encoding));
4134
4135                 if (action == COMPOSE_WRITE_FOR_SEND) {
4136                         codeconv_set_strict(TRUE);
4137                         buf = conv_codeset_strdup(chars, src_codeset, out_codeset);
4138                         codeconv_set_strict(FALSE);
4139
4140                         if (!buf) {
4141                                 AlertValue aval;
4142                                 gchar *msg;
4143
4144                                 msg = g_strdup_printf(_("Can't convert the character encoding of the message \n"
4145                                                         "to the specified %s charset.\n"
4146                                                         "Send it as %s?"), out_codeset, src_codeset);
4147                                 aval = alertpanel_full(_("Error"), msg, GTK_STOCK_CANCEL, _("+_Send"), NULL, FALSE,
4148                                                       NULL, ALERT_ERROR, G_ALERTDEFAULT);
4149                                 g_free(msg);
4150
4151                                 if (aval != G_ALERTALTERNATE) {
4152                                         g_free(chars);
4153                                         return -3;
4154                                 } else {
4155                                         buf = chars;
4156                                         out_codeset = src_codeset;
4157                                         chars = NULL;
4158                                 }
4159                         }
4160                 } else {
4161                         buf = chars;
4162                         out_codeset = src_codeset;
4163                         chars = NULL;
4164                 }
4165         }
4166         g_free(chars);
4167
4168         if (encoding == ENC_8BIT || encoding == ENC_7BIT) {
4169                 if (!strncmp(buf, "From ", sizeof("From ")-1) ||
4170                     strstr(buf, "\nFrom ") != NULL) {
4171                         encoding = ENC_QUOTED_PRINTABLE;
4172                 }
4173         }
4174
4175         mimetext = procmime_mimeinfo_new();
4176         mimetext->content = MIMECONTENT_MEM;
4177         mimetext->tmp = TRUE; /* must free content later */
4178         mimetext->data.mem = buf;
4179         mimetext->type = MIMETYPE_TEXT;
4180         mimetext->subtype = g_strdup("plain");
4181         g_hash_table_insert(mimetext->typeparameters, g_strdup("charset"),
4182                             g_strdup(out_codeset));
4183         /* protect trailing spaces when signing message */
4184         if (action == COMPOSE_WRITE_FOR_SEND && compose->use_signing && 
4185             privacy_system_can_sign(compose->privacy_system)) {
4186                 encoding = ENC_QUOTED_PRINTABLE;
4187         }
4188         
4189         /* check for line length limit */
4190         if (action == COMPOSE_WRITE_FOR_SEND &&
4191             encoding != ENC_QUOTED_PRINTABLE && encoding != ENC_BASE64 &&
4192             check_line_length(buf, 1000, &line) < 0) {
4193                 AlertValue aval;
4194                 gchar *msg;
4195
4196                 msg = g_strdup_printf
4197                         (_("Line %d exceeds the line length limit (998 bytes).\n"
4198                            "The contents of the message might be broken on the way to the delivery.\n"
4199                            "\n"
4200                            "Send it anyway?"), line + 1);
4201                 aval = alertpanel(_("Warning"), msg, GTK_STOCK_CANCEL, GTK_STOCK_OK, NULL);
4202                 g_free(msg);
4203                 if (aval != G_ALERTALTERNATE) {
4204                         return -1;
4205                 }
4206         }
4207         
4208         if (encoding != ENC_UNKNOWN)
4209                 procmime_encode_content(mimetext, encoding);
4210
4211         /* append attachment parts */
4212         if (compose_use_attach(compose)) {
4213                 MimeInfo *mimempart;
4214                 gchar *boundary = NULL;
4215                 mimempart = procmime_mimeinfo_new();
4216                 mimempart->content = MIMECONTENT_EMPTY;
4217                 mimempart->type = MIMETYPE_MULTIPART;
4218                 mimempart->subtype = g_strdup("mixed");
4219
4220                 do {
4221                         if (boundary)
4222                                 g_free(boundary);
4223                         boundary = generate_mime_boundary(NULL);
4224                 } while (strstr(buf, boundary) != NULL);
4225
4226                 g_hash_table_insert(mimempart->typeparameters, g_strdup("boundary"),
4227                                     boundary);
4228
4229                 mimetext->disposition = DISPOSITIONTYPE_INLINE;
4230
4231                 g_node_append(mimempart->node, mimetext->node);
4232                 g_node_append(mimemsg->node, mimempart->node);
4233
4234                 compose_add_attachments(compose, mimempart);
4235         } else
4236                 g_node_append(mimemsg->node, mimetext->node);
4237
4238         /* sign message if sending */
4239         if (action == COMPOSE_WRITE_FOR_SEND && compose->use_signing && 
4240             privacy_system_can_sign(compose->privacy_system))
4241                 if (!privacy_sign(compose->privacy_system, mimemsg, compose->account))
4242                         return -2;
4243
4244         procmime_write_mimeinfo(mimemsg, fp);
4245         
4246         procmime_mimeinfo_free_all(mimemsg);
4247
4248         return 0;
4249 }
4250
4251 static gint compose_write_body_to_file(Compose *compose, const gchar *file)
4252 {
4253         GtkTextBuffer *buffer;
4254         GtkTextIter start, end;
4255         FILE *fp;
4256         size_t len;
4257         gchar *chars, *tmp;
4258
4259         if ((fp = g_fopen(file, "wb")) == NULL) {
4260                 FILE_OP_ERROR(file, "fopen");
4261                 return -1;
4262         }
4263
4264         /* chmod for security */
4265         if (change_file_mode_rw(fp, file) < 0) {
4266                 FILE_OP_ERROR(file, "chmod");
4267                 g_warning("can't change file mode\n");
4268         }
4269
4270         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(compose->text));
4271         gtk_text_buffer_get_start_iter(buffer, &start);
4272         gtk_text_buffer_get_end_iter(buffer, &end);
4273         tmp = gtk_text_buffer_get_text(buffer, &start, &end, FALSE);
4274
4275         chars = conv_codeset_strdup
4276                 (tmp, CS_INTERNAL, conv_get_locale_charset_str());
4277
4278         g_free(tmp);
4279         if (!chars) return -1;
4280
4281         /* write body */
4282         len = strlen(chars);
4283         if (fwrite(chars, sizeof(gchar), len, fp) != len) {
4284                 FILE_OP_ERROR(file, "fwrite");
4285                 g_free(chars);
4286                 fclose(fp);
4287                 g_unlink(file);
4288                 return -1;
4289         }
4290
4291         g_free(chars);
4292
4293         if (fclose(fp) == EOF) {
4294                 FILE_OP_ERROR(file, "fclose");
4295                 g_unlink(file);
4296                 return -1;
4297         }
4298         return 0;
4299 }
4300
4301 static gint compose_remove_reedit_target(Compose *compose, gboolean force)
4302 {
4303         FolderItem *item;
4304         MsgInfo *msginfo = compose->targetinfo;
4305
4306         g_return_val_if_fail(compose->mode == COMPOSE_REEDIT, -1);
4307         if (!msginfo) return -1;
4308
4309         if (!force && MSG_IS_LOCKED(msginfo->flags))
4310                 return 0;
4311
4312         item = msginfo->folder;
4313         g_return_val_if_fail(item != NULL, -1);
4314
4315         if (procmsg_msg_exist(msginfo) &&
4316             (folder_has_parent_of_type(item, F_QUEUE) ||
4317              folder_has_parent_of_type(item, F_DRAFT) 
4318              || msginfo == compose->autosaved_draft)) {
4319                 if (folder_item_remove_msg(item, msginfo->msgnum) < 0) {
4320                         g_warning("can't remove the old message\n");
4321                         return -1;
4322                 }
4323         }
4324
4325         return 0;
4326 }
4327
4328 void compose_remove_draft(Compose *compose)
4329 {
4330         FolderItem *drafts;
4331         MsgInfo *msginfo = compose->targetinfo;
4332         drafts = account_get_special_folder(compose->account, F_DRAFT);
4333
4334         if (procmsg_msg_exist(msginfo)) {
4335                 folder_item_remove_msg(drafts, msginfo->msgnum);
4336         }
4337
4338 }
4339
4340 static gint compose_queue(Compose *compose, gint *msgnum, FolderItem **item)
4341 {
4342         return compose_queue_sub (compose, msgnum, item, FALSE);
4343 }
4344 static gint compose_queue_sub(Compose *compose, gint *msgnum, FolderItem **item, gboolean check_subject)
4345 {
4346         FolderItem *queue;
4347         gchar *tmp;
4348         FILE *fp;
4349         GSList *cur;
4350         gint num;
4351         static gboolean lock = FALSE;
4352         PrefsAccount *mailac = NULL, *newsac = NULL;
4353         
4354         debug_print("queueing message...\n");
4355         g_return_val_if_fail(compose->account != NULL, -1);
4356
4357         lock = TRUE;
4358         
4359         if (compose_check_entries(compose, check_subject) == FALSE) {
4360                 lock = FALSE;
4361                 return -1;
4362         }
4363
4364         if (!compose->to_list && !compose->newsgroup_list) {
4365                 g_warning("can't get recipient list.");
4366                 lock = FALSE;
4367                 return -1;
4368         }
4369
4370         if (compose->to_list) {
4371                 if (compose->account->protocol != A_NNTP)
4372                         mailac = compose->account;
4373                 else if (cur_account && cur_account->protocol != A_NNTP)
4374                         mailac = cur_account;
4375                 else if (!(mailac = compose_current_mail_account())) {
4376                         lock = FALSE;
4377                         alertpanel_error(_("No account for sending mails available!"));
4378                         return -1;
4379                 }
4380         }
4381
4382         if (compose->newsgroup_list) {
4383                 if (compose->account->protocol == A_NNTP)
4384                         newsac = compose->account;
4385                 else if (!newsac->protocol != A_NNTP) {
4386                         lock = FALSE;
4387                         alertpanel_error(_("No account for posting news available!"));
4388                         return -1;
4389                 }                       
4390         }
4391
4392         /* write queue header */
4393         tmp = g_strdup_printf("%s%cqueue.%p", get_tmp_dir(),
4394                               G_DIR_SEPARATOR, compose);
4395         if ((fp = g_fopen(tmp, "wb")) == NULL) {
4396                 FILE_OP_ERROR(tmp, "fopen");
4397                 g_free(tmp);
4398                 return -2;
4399         }
4400
4401         if (change_file_mode_rw(fp, tmp) < 0) {
4402                 FILE_OP_ERROR(tmp, "chmod");
4403                 g_warning("can't change file mode\n");
4404         }
4405
4406         /* queueing variables */
4407         fprintf(fp, "AF:\n");
4408         fprintf(fp, "NF:0\n");
4409         fprintf(fp, "PS:10\n");
4410         fprintf(fp, "SRH:1\n");
4411         fprintf(fp, "SFN:\n");
4412         fprintf(fp, "DSR:\n");
4413         if (compose->msgid)
4414                 fprintf(fp, "MID:<%s>\n", compose->msgid);
4415         else
4416                 fprintf(fp, "MID:\n");
4417         fprintf(fp, "CFG:\n");
4418         fprintf(fp, "PT:0\n");
4419         fprintf(fp, "S:%s\n", compose->account->address);
4420         fprintf(fp, "RQ:\n");
4421         if (mailac)
4422                 fprintf(fp, "SSV:%s\n", mailac->smtp_server);
4423         else
4424                 fprintf(fp, "SSV:\n");
4425         if (newsac)
4426                 fprintf(fp, "NSV:%s\n", newsac->nntp_server);
4427         else
4428                 fprintf(fp, "NSV:\n");
4429         fprintf(fp, "SSH:\n");
4430         /* write recepient list */
4431         if (compose->to_list) {
4432                 fprintf(fp, "R:<%s>", (gchar *)compose->to_list->data);
4433                 for (cur = compose->to_list->next; cur != NULL;
4434                      cur = cur->next)
4435                         fprintf(fp, ",<%s>", (gchar *)cur->data);
4436                 fprintf(fp, "\n");
4437         }
4438         /* write newsgroup list */
4439         if (compose->newsgroup_list) {
4440                 fprintf(fp, "NG:");
4441                 fprintf(fp, "%s", (gchar *)compose->newsgroup_list->data);
4442                 for (cur = compose->newsgroup_list->next; cur != NULL; cur = cur->next)
4443                         fprintf(fp, ",%s", (gchar *)cur->data);
4444                 fprintf(fp, "\n");
4445         }
4446         /* Sylpheed account IDs */
4447         if (mailac)
4448                 fprintf(fp, "MAID:%d\n", mailac->account_id);
4449         if (newsac)
4450                 fprintf(fp, "NAID:%d\n", newsac->account_id);
4451
4452         if (compose->privacy_system != NULL) {
4453                 fprintf(fp, "X-Sylpheed-Privacy-System:%s\n", compose->privacy_system);
4454                 fprintf(fp, "X-Sylpheed-Sign:%d\n", compose->use_signing);
4455                 if (compose->use_encryption) {
4456                         gchar *encdata;
4457
4458                         encdata = privacy_get_encrypt_data(compose->privacy_system, compose->to_list);
4459                         if (encdata != NULL) {
4460                                 if (strcmp(encdata, "_DONT_ENCRYPT_")) {
4461                                         fprintf(fp, "X-Sylpheed-Encrypt:%d\n", compose->use_encryption);
4462                                         fprintf(fp, "X-Sylpheed-Encrypt-Data:%s\n", 
4463                                                 encdata);
4464                                 } /* else we finally dont want to encrypt */
4465                         } else {
4466                                 fprintf(fp, "X-Sylpheed-Encrypt:%d\n", compose->use_encryption);
4467                                 /* and if encdata was null, it means there's been a problem in 
4468                                  * key selection */
4469                         }
4470                         g_free(encdata);
4471                 }
4472         }
4473
4474         /* Save copy folder */
4475         if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn))) {
4476                 gchar *savefolderid;
4477                 
4478                 savefolderid = gtk_editable_get_chars(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
4479                 fprintf(fp, "SCF:%s\n", savefolderid);
4480                 g_free(savefolderid);
4481         }
4482         /* Save copy folder */
4483         if (compose->return_receipt) {
4484                 fprintf(fp, "RRCPT:1\n");
4485         }
4486         /* Message-ID of message replying to */
4487         if ((compose->replyinfo != NULL) && (compose->replyinfo->msgid != NULL)) {
4488                 gchar *folderid;
4489                 
4490                 folderid = folder_item_get_identifier(compose->replyinfo->folder);
4491                 fprintf(fp, "RMID:%s\x7f%d\x7f%s\n", folderid, compose->replyinfo->msgnum, compose->replyinfo->msgid);
4492                 g_free(folderid);
4493         }
4494         /* Message-ID of message forwarding to */
4495         if ((compose->fwdinfo != NULL) && (compose->fwdinfo->msgid != NULL)) {
4496                 gchar *folderid;
4497                 
4498                 folderid = folder_item_get_identifier(compose->fwdinfo->folder);
4499                 fprintf(fp, "FMID:%s\x7f%d\x7f%s\n", folderid, compose->fwdinfo->msgnum, compose->fwdinfo->msgid);
4500                 g_free(folderid);
4501         }
4502         fprintf(fp, "\n");
4503
4504         if (compose->redirect_filename != NULL) {
4505                 if (compose_redirect_write_to_file(compose, fp) < 0) {
4506                         lock = FALSE;
4507                         fclose(fp);
4508                         g_unlink(tmp);
4509                         g_free(tmp);
4510                         return -2;
4511                 }
4512         } else {
4513                 gint result = 0;
4514                 if ((result = compose_write_to_file(compose, fp, COMPOSE_WRITE_FOR_SEND)) < 0) {
4515                         lock = FALSE;
4516                         fclose(fp);
4517                         g_unlink(tmp);
4518                         g_free(tmp);
4519                         return result - 1; /* -2 for a generic error, -3 for signing error, -4 for encoding */
4520                 }
4521         }
4522
4523         if (fclose(fp) == EOF) {
4524                 FILE_OP_ERROR(tmp, "fclose");
4525                 g_unlink(tmp);
4526                 g_free(tmp);
4527                 return -2;
4528         }
4529
4530         queue = account_get_special_folder(compose->account, F_QUEUE);
4531         if (!queue) {
4532                 g_warning("can't find queue folder\n");
4533                 g_unlink(tmp);
4534                 g_free(tmp);
4535                 return -1;
4536         }
4537         folder_item_scan(queue);
4538         if ((num = folder_item_add_msg(queue, tmp, NULL, TRUE)) < 0) {
4539                 g_warning("can't queue the message\n");
4540                 g_unlink(tmp);
4541                 g_free(tmp);
4542                 return -1;
4543         }
4544         g_unlink(tmp);
4545         g_free(tmp);
4546
4547         if (compose->mode == COMPOSE_REEDIT) {
4548                 compose_remove_reedit_target(compose, FALSE);
4549         }
4550
4551         if ((msgnum != NULL) && (item != NULL)) {
4552                 *msgnum = num;
4553                 *item = queue;
4554         }
4555
4556         return 0;
4557 }
4558
4559 static void compose_add_attachments(Compose *compose, MimeInfo *parent)
4560 {
4561         AttachInfo *ainfo;
4562         GtkTreeView *tree_view = GTK_TREE_VIEW(compose->attach_clist);
4563         MimeInfo *mimepart;
4564         struct stat statbuf;
4565         gchar *type, *subtype;
4566         GtkTreeModel *model;
4567         GtkTreeIter iter;
4568
4569         model = gtk_tree_view_get_model(tree_view);
4570         
4571         if (!gtk_tree_model_get_iter_first(model, &iter))
4572                 return;
4573         do {
4574                 gtk_tree_model_get(model, &iter,
4575                                    COL_DATA, &ainfo,
4576                                    -1);
4577                                                            
4578                 mimepart = procmime_mimeinfo_new();
4579                 mimepart->content = MIMECONTENT_FILE;
4580                 mimepart->data.filename = g_strdup(ainfo->file);
4581                 mimepart->tmp = FALSE; /* or we destroy our attachment */
4582                 mimepart->offset = 0;
4583
4584                 stat(ainfo->file, &statbuf);
4585                 mimepart->length = statbuf.st_size;
4586
4587                 type = g_strdup(ainfo->content_type);
4588
4589                 if (!strchr(type, '/')) {
4590                         g_free(type);
4591                         type = g_strdup("application/octet-stream");
4592                 }
4593
4594                 subtype = strchr(type, '/') + 1;
4595                 *(subtype - 1) = '\0';
4596                 mimepart->type = procmime_get_media_type(type);
4597                 mimepart->subtype = g_strdup(subtype);
4598                 g_free(type);
4599
4600                 if (mimepart->type == MIMETYPE_MESSAGE && 
4601                     !g_ascii_strcasecmp(mimepart->subtype, "rfc822")) {
4602                         mimepart->disposition = DISPOSITIONTYPE_INLINE;
4603                 } else {
4604                         g_hash_table_insert(mimepart->typeparameters,
4605                                             g_strdup("name"), g_strdup(ainfo->name));
4606                         g_hash_table_insert(mimepart->dispositionparameters,
4607                                             g_strdup("filename"), g_strdup(ainfo->name));
4608                         mimepart->disposition = DISPOSITIONTYPE_ATTACHMENT;
4609                 }
4610
4611                 if (compose->use_signing) {
4612                         if (ainfo->encoding == ENC_7BIT)
4613                                 ainfo->encoding = ENC_QUOTED_PRINTABLE;
4614                         else if (ainfo->encoding == ENC_8BIT)
4615                                 ainfo->encoding = ENC_BASE64;
4616                 }
4617                 
4618                 procmime_encode_content(mimepart, ainfo->encoding);
4619
4620                 g_node_append(parent->node, mimepart->node);
4621         } while (gtk_tree_model_iter_next(model, &iter));
4622 }
4623
4624 #define QUOTE_IF_REQUIRED(out, str)                                     \
4625 {                                                                       \
4626         if (*str != '"' && strpbrk(str, ",.[]<>")) {                    \
4627                 gchar *__tmp;                                           \
4628                 gint len;                                               \
4629                                                                         \
4630                 len = strlen(str) + 3;                                  \
4631                 if ((__tmp = alloca(len)) == NULL) {                    \
4632                         g_warning("can't allocate memory\n");           \
4633                         g_string_free(header, TRUE);                    \
4634                         return NULL;                                    \
4635                 }                                                       \
4636                 g_snprintf(__tmp, len, "\"%s\"", str);                  \
4637                 out = __tmp;                                            \
4638         } else {                                                        \
4639                 gchar *__tmp;                                           \
4640                                                                         \
4641                 if ((__tmp = alloca(strlen(str) + 1)) == NULL) {        \
4642                         g_warning("can't allocate memory\n");           \
4643                         g_string_free(header, TRUE);                    \
4644                         return NULL;                                    \
4645                 } else                                                  \
4646                         strcpy(__tmp, str);                             \
4647                                                                         \
4648                 out = __tmp;                                            \
4649         }                                                               \
4650 }
4651
4652 #define IS_IN_CUSTOM_HEADER(header) \
4653         (compose->account->add_customhdr && \
4654          custom_header_find(compose->account->customhdr_list, header) != NULL)
4655
4656 static void compose_add_headerfield_from_headerlist(Compose *compose, 
4657                                                     GString *header, 
4658                                                     const gchar *fieldname,
4659                                                     const gchar *seperator)
4660 {
4661         gchar *str, *fieldname_w_colon, *trans_fieldname;
4662         gboolean add_field = FALSE;
4663         GSList *list;
4664         ComposeHeaderEntry *headerentry;
4665         const gchar * headerentryname;
4666         GString *fieldstr;
4667
4668         if (IS_IN_CUSTOM_HEADER(fieldname))
4669                 return;
4670
4671         debug_print("Adding %s-fields\n", fieldname);
4672
4673         fieldstr = g_string_sized_new(64);
4674
4675         fieldname_w_colon = g_strconcat(fieldname, ":", NULL);
4676         trans_fieldname = (prefs_common.trans_hdr ? gettext(fieldname_w_colon) : fieldname_w_colon);
4677
4678         for (list = compose->header_list; list; list = list->next) {
4679                 headerentry = ((ComposeHeaderEntry *)list->data);
4680                 headerentryname = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry));
4681
4682                 if (!g_utf8_collate(trans_fieldname, headerentryname)) {
4683                         str = gtk_editable_get_chars(GTK_EDITABLE(headerentry->entry), 0, -1);
4684                         g_strstrip(str);
4685                         if (str[0] != '\0') {
4686                                 if (add_field)
4687                                         g_string_append(fieldstr, seperator);
4688                                 g_string_append(fieldstr, str);
4689                                 add_field = TRUE;
4690                         }
4691                         g_free(str);
4692                 }
4693         }
4694         if (add_field) {
4695                 gchar *buf;
4696
4697                 buf = g_new0(gchar, fieldstr->len * 4 + 256);
4698                 compose_convert_header
4699                         (compose, buf, fieldstr->len * 4  + 256, fieldstr->str,
4700                         strlen(fieldname) + 2, TRUE);
4701                 g_string_append_printf(header, "%s: %s\n", fieldname, buf);
4702                 g_free(buf);
4703         }
4704
4705         g_free(fieldname_w_colon);
4706         g_string_free(fieldstr, TRUE);
4707
4708         return;
4709 }
4710
4711 static gchar *compose_get_header(Compose *compose)
4712 {
4713         gchar buf[BUFFSIZE];
4714         const gchar *entry_str;
4715         gchar *str;
4716         gchar *name;
4717         GSList *list;
4718         gchar *std_headers[] = {"To:", "Cc:", "Bcc:", "Newsgroups:", "Reply-To:", "Followup-To:", NULL};
4719         GString *header;
4720
4721         g_return_val_if_fail(compose->account != NULL, NULL);
4722         g_return_val_if_fail(compose->account->address != NULL, NULL);
4723
4724         header = g_string_sized_new(64);
4725
4726         /* Date */
4727         if (compose->account->add_date) {
4728                 get_rfc822_date(buf, sizeof(buf));
4729                 g_string_append_printf(header, "Date: %s\n", buf);
4730         }
4731
4732         /* From */
4733         if (compose->account->name && *compose->account->name) {
4734                 compose_convert_header
4735                         (compose, buf, sizeof(buf), compose->account->name,
4736                          strlen("From: "), TRUE);
4737                 QUOTE_IF_REQUIRED(name, buf);
4738                 g_string_append_printf(header, "From: %s <%s>\n",
4739                         name, compose->account->address);
4740         } else
4741                 g_string_append_printf(header, "From: %s\n", compose->account->address);
4742         
4743         /* To */
4744         compose_add_headerfield_from_headerlist(compose, header, "To", ", ");
4745
4746         /* Newsgroups */
4747         compose_add_headerfield_from_headerlist(compose, header, "Newsgroups", ",");
4748
4749         /* Cc */
4750         compose_add_headerfield_from_headerlist(compose, header, "Cc", ", ");
4751
4752         /* Bcc */
4753         compose_add_headerfield_from_headerlist(compose, header, "Bcc", ", ");
4754
4755         /* Subject */
4756         str = gtk_editable_get_chars(GTK_EDITABLE(compose->subject_entry), 0, -1);
4757
4758         if (*str != '\0' && !IS_IN_CUSTOM_HEADER("Subject")) {
4759                 g_strstrip(str);
4760                 if (*str != '\0') {
4761                         compose_convert_header(compose, buf, sizeof(buf), str,
4762                                                strlen("Subject: "), FALSE);
4763                         g_string_append_printf(header, "Subject: %s\n", buf);
4764                 }
4765         }
4766         g_free(str);
4767
4768         /* Message-ID */
4769         if (compose->account->gen_msgid) {
4770                 generate_msgid(buf, sizeof(buf));
4771                 g_string_append_printf(header, "Message-ID: <%s>\n", buf);
4772                 compose->msgid = g_strdup(buf);
4773         }
4774
4775         if (compose->remove_references == FALSE) {
4776                 /* In-Reply-To */
4777                 if (compose->inreplyto && compose->to_list)
4778                         g_string_append_printf(header, "In-Reply-To: <%s>\n", compose->inreplyto);
4779         
4780                 /* References */
4781                 if (compose->references)
4782                         g_string_append_printf(header, "References: %s\n", compose->references);
4783         }
4784
4785         /* Followup-To */
4786         compose_add_headerfield_from_headerlist(compose, header, "Followup-To", ",");
4787
4788         /* Reply-To */
4789         compose_add_headerfield_from_headerlist(compose, header, "Reply-To", ", ");
4790
4791         /* Organization */
4792         if (compose->account->organization &&
4793             strlen(compose->account->organization) &&
4794             !IS_IN_CUSTOM_HEADER("Organization")) {
4795                 compose_convert_header(compose, buf, sizeof(buf),
4796                                        compose->account->organization,
4797                                        strlen("Organization: "), FALSE);
4798                 g_string_append_printf(header, "Organization: %s\n", buf);
4799         }
4800
4801         /* Program version and system info */
4802         if (g_slist_length(compose->to_list) && !IS_IN_CUSTOM_HEADER("X-Mailer") &&
4803             !compose->newsgroup_list) {
4804                 g_string_append_printf(header, "X-Mailer: %s (GTK+ %d.%d.%d; %s)\n",
4805                         prog_version,
4806                         gtk_major_version, gtk_minor_version, gtk_micro_version,
4807                         TARGET_ALIAS);
4808         }
4809         if (g_slist_length(compose->newsgroup_list) && !IS_IN_CUSTOM_HEADER("X-Newsreader")) {
4810                 g_string_append_printf(header, "X-Newsreader: %s (GTK+ %d.%d.%d; %s)\n",
4811                         prog_version,
4812                         gtk_major_version, gtk_minor_version, gtk_micro_version,
4813                         TARGET_ALIAS);
4814         }
4815
4816         /* custom headers */
4817         if (compose->account->add_customhdr) {
4818                 GSList *cur;
4819
4820                 for (cur = compose->account->customhdr_list; cur != NULL;
4821                      cur = cur->next) {
4822                         CustomHeader *chdr = (CustomHeader *)cur->data;
4823
4824                         if (custom_header_is_allowed(chdr->name)) {
4825                                 compose_convert_header
4826                                         (compose, buf, sizeof(buf),
4827                                          chdr->value ? chdr->value : "",
4828                                          strlen(chdr->name) + 2, FALSE);
4829                                 g_string_append_printf(header, "%s: %s\n", chdr->name, buf);
4830                         }
4831                 }
4832         }
4833
4834         /* PRIORITY */
4835         switch (compose->priority) {
4836                 case PRIORITY_HIGHEST: g_string_append_printf(header, "Importance: high\n"
4837                                                    "X-Priority: 1 (Highest)\n");
4838                         break;
4839                 case PRIORITY_HIGH: g_string_append_printf(header, "Importance: high\n"
4840                                                 "X-Priority: 2 (High)\n");
4841                         break;
4842                 case PRIORITY_NORMAL: break;
4843                 case PRIORITY_LOW: g_string_append_printf(header, "Importance: low\n"
4844                                                "X-Priority: 4 (Low)\n");
4845                         break;
4846                 case PRIORITY_LOWEST: g_string_append_printf(header, "Importance: low\n"
4847                                                   "X-Priority: 5 (Lowest)\n");
4848                         break;
4849                 default: debug_print("compose: priority unknown : %d\n",
4850                                      compose->priority);
4851         }
4852
4853         /* Request Return Receipt */
4854         if (!IS_IN_CUSTOM_HEADER("Disposition-Notification-To")) {
4855                 if (compose->return_receipt) {
4856                         if (compose->account->name
4857                             && *compose->account->name) {
4858                                 compose_convert_header(compose, buf, sizeof(buf), 
4859                                                        compose->account->name, 
4860                                                        strlen("Disposition-Notification-To: "),
4861                                                        TRUE);
4862                                 g_string_append_printf(header, "Disposition-Notification-To: %s <%s>\n", buf, compose->account->address);
4863                         } else
4864                                 g_string_append_printf(header, "Disposition-Notification-To: %s\n", compose->account->address);
4865                 }
4866         }
4867
4868         /* get special headers */
4869         for (list = compose->header_list; list; list = list->next) {
4870                 ComposeHeaderEntry *headerentry;
4871                 gchar *tmp;
4872                 gchar *headername;
4873                 gchar *headername_wcolon;
4874                 gchar *headername_trans;
4875                 gchar *headervalue;
4876                 gchar **string;
4877                 gboolean standard_header = FALSE;
4878
4879                 headerentry = ((ComposeHeaderEntry *)list->data);
4880                 
4881                 tmp = g_strdup(gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry)));
4882                 if (strchr(tmp, ' ') != NULL || strchr(tmp, '\r') != NULL || strchr(tmp, '\n') != NULL) {
4883                         g_free(tmp);
4884                         continue;
4885                 }
4886
4887                 if (!strstr(tmp, ":")) {
4888                         headername_wcolon = g_strconcat(tmp, ":", NULL);
4889                         headername = g_strdup(tmp);
4890                 } else {
4891                         headername_wcolon = g_strdup(tmp);
4892                         headername = g_strdup(strtok(tmp, ":"));
4893                 }
4894                 g_free(tmp);
4895                 
4896                 entry_str = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
4897                 Xstrdup_a(headervalue, entry_str, return NULL);
4898                 subst_char(headervalue, '\r', ' ');
4899                 subst_char(headervalue, '\n', ' ');
4900                 string = std_headers;
4901                 while (*string != NULL) {
4902                         headername_trans = prefs_common.trans_hdr ? gettext(*string) : *string;
4903                         if (!strcmp(headername_trans,headername_wcolon))
4904                                 standard_header = TRUE;
4905                         string++;
4906                 }
4907                 if (!standard_header && !IS_IN_CUSTOM_HEADER(headername))
4908                         g_string_append_printf(header, "%s %s\n", headername_wcolon, headervalue);
4909                                 
4910                 g_free(headername);
4911                 g_free(headername_wcolon);              
4912         }
4913
4914         str = header->str;
4915         g_string_free(header, FALSE);
4916
4917         return str;
4918 }
4919
4920 #undef IS_IN_CUSTOM_HEADER
4921
4922 static void compose_convert_header(Compose *compose, gchar *dest, gint len, gchar *src,
4923                                    gint header_len, gboolean addr_field)
4924 {
4925         gchar *tmpstr = NULL;
4926         const gchar *out_codeset = NULL;
4927
4928         g_return_if_fail(src != NULL);
4929         g_return_if_fail(dest != NULL);
4930
4931         if (len < 1) return;
4932
4933         tmpstr = g_strdup(src);
4934
4935         subst_char(tmpstr, '\n', ' ');
4936         subst_char(tmpstr, '\r', ' ');
4937         g_strchomp(tmpstr);
4938
4939         if (!g_utf8_validate(tmpstr, -1, NULL)) {
4940                 gchar *mybuf = g_malloc(strlen(tmpstr)*2 +1);
4941                 conv_localetodisp(mybuf, strlen(tmpstr)*2 +1, tmpstr);
4942                 g_free(tmpstr);
4943                 tmpstr = mybuf;
4944         }
4945
4946         codeconv_set_strict(TRUE);
4947         conv_encode_header_full(dest, len, tmpstr, header_len, addr_field, 
4948                 conv_get_charset_str(compose->out_encoding));
4949         codeconv_set_strict(FALSE);
4950         
4951         if (!dest || *dest == '\0') {
4952                 gchar *test_conv_global_out = NULL;
4953                 gchar *test_conv_reply = NULL;
4954
4955                 /* automatic mode. be automatic. */
4956                 codeconv_set_strict(TRUE);
4957
4958                 out_codeset = conv_get_outgoing_charset_str();
4959                 if (out_codeset) {
4960                         debug_print("trying to convert to %s\n", out_codeset);
4961                         test_conv_global_out = conv_codeset_strdup(src, CS_INTERNAL, out_codeset);
4962                 }
4963
4964                 if (!test_conv_global_out && compose->orig_charset) {
4965                         out_codeset = compose->orig_charset;
4966                         debug_print("failure; trying to convert to %s\n", out_codeset);
4967                         test_conv_reply = conv_codeset_strdup(src, CS_INTERNAL, out_codeset);
4968                 }
4969
4970                 if (!test_conv_global_out && !test_conv_reply) {
4971                         /* we're lost */
4972                         out_codeset = CS_INTERNAL;
4973                         debug_print("finally using %s\n", out_codeset);
4974                 }
4975                 g_free(test_conv_global_out);
4976                 g_free(test_conv_reply);
4977                 conv_encode_header_full(dest, len, tmpstr, header_len, addr_field, 
4978                                         out_codeset);
4979                 codeconv_set_strict(FALSE);
4980         }
4981         g_free(tmpstr);
4982 }
4983
4984 static void compose_create_header_entry(Compose *compose) 
4985 {
4986         gchar *headers[] = {"To:", "Cc:", "Bcc:", "Newsgroups:", "Reply-To:", "Followup-To:", NULL};
4987
4988         GtkWidget *combo;
4989         GtkWidget *entry;
4990         GList *combo_list = NULL;
4991         gchar **string;
4992         const gchar *header = NULL;
4993         ComposeHeaderEntry *headerentry;
4994         gboolean standard_header = FALSE;
4995
4996         headerentry = g_new0(ComposeHeaderEntry, 1);
4997
4998         /* Combo box */
4999         combo = gtk_combo_new();
5000         string = headers; 
5001         while(*string != NULL) {
5002                 combo_list = g_list_append(combo_list, (prefs_common.trans_hdr ? gettext(*string) : *string));
5003                 string++;
5004         }
5005         gtk_combo_set_popdown_strings(GTK_COMBO(combo), combo_list);
5006         g_list_free(combo_list);
5007         gtk_editable_set_editable(GTK_EDITABLE(GTK_COMBO(combo)->entry), TRUE);
5008         g_signal_connect(G_OBJECT(GTK_COMBO(combo)->entry), "grab_focus",
5009                          G_CALLBACK(compose_grab_focus_cb), compose);
5010         gtk_widget_show(combo);
5011         gtk_table_attach(GTK_TABLE(compose->header_table), combo, 0, 1, compose->header_nextrow, compose->header_nextrow+1, GTK_SHRINK, GTK_FILL, 0, 0);
5012         if (compose->header_last) {     
5013                 const gchar *last_header_entry = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry));
5014                 string = headers;
5015                 while (*string != NULL) {
5016                         if (!strcmp(*string, last_header_entry))
5017                                 standard_header = TRUE;
5018                         string++;
5019                 }
5020                 if (standard_header)
5021                         header = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry));
5022         }
5023         if (!compose->header_last || !standard_header) {
5024                 switch(compose->account->protocol) {
5025                         case A_NNTP:
5026                                 header = prefs_common.trans_hdr ? _("Newsgroups:") : "Newsgroups:";
5027                                 break;
5028                         default:
5029                                 header = prefs_common.trans_hdr ? _("To:") : "To:";
5030                                 break;
5031                 }                                                                   
5032         }
5033         if (header)
5034                 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(combo)->entry), header);
5035
5036         g_signal_connect_after(G_OBJECT(GTK_COMBO(combo)->entry), "grab_focus",
5037                          G_CALLBACK(compose_grab_focus_cb), compose);
5038
5039         /* Entry field */
5040         entry = gtk_entry_new(); 
5041         gtk_widget_show(entry);
5042         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);
5043
5044         g_signal_connect(G_OBJECT(entry), "key-press-event", 
5045                          G_CALLBACK(compose_headerentry_key_press_event_cb), 
5046                          headerentry);
5047         g_signal_connect(G_OBJECT(entry), "changed", 
5048                          G_CALLBACK(compose_headerentry_changed_cb), 
5049                          headerentry);
5050         g_signal_connect_after(G_OBJECT(entry), "grab_focus",
5051                          G_CALLBACK(compose_grab_focus_cb), compose);
5052                          
5053         /* email dnd */
5054         gtk_drag_dest_set(entry, GTK_DEST_DEFAULT_ALL, compose_mime_types, 
5055                           sizeof(compose_mime_types)/sizeof(compose_mime_types[0]),
5056                           GDK_ACTION_COPY | GDK_ACTION_MOVE);
5057         g_signal_connect(G_OBJECT(entry), "drag_data_received",
5058                          G_CALLBACK(compose_header_drag_received_cb),
5059                          entry);
5060         g_signal_connect(G_OBJECT(entry), "drag-drop",
5061                          G_CALLBACK(compose_drag_drop),
5062                          compose);
5063         
5064         address_completion_register_entry(GTK_ENTRY(entry));
5065
5066         headerentry->compose = compose;
5067         headerentry->combo = combo;
5068         headerentry->entry = entry;
5069         headerentry->headernum = compose->header_nextrow;
5070
5071         compose->header_nextrow++;
5072         compose->header_last = headerentry;
5073 }
5074
5075 static void compose_add_header_entry(Compose *compose, gchar *header, gchar *text) 
5076 {
5077         ComposeHeaderEntry *last_header;
5078         
5079         last_header = compose->header_last;
5080         
5081         gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(last_header->combo)->entry), header);
5082         gtk_entry_set_text(GTK_ENTRY(last_header->entry), text);
5083 }
5084
5085 static GtkWidget *compose_create_header(Compose *compose) 
5086 {
5087         GtkWidget *label;
5088         GtkWidget *hbox;
5089         GtkWidget *from_optmenu_hbox;
5090         GtkWidget *header_scrolledwin;
5091         GtkWidget *header_table;
5092
5093         gint count = 0;
5094
5095         /* header labels and entries */
5096         header_scrolledwin = gtk_scrolled_window_new(NULL, NULL);
5097         gtk_widget_show(header_scrolledwin);
5098         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(header_scrolledwin), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
5099
5100         header_table = gtk_table_new(2, 2, FALSE);
5101         gtk_widget_show(header_table);
5102         gtk_container_set_border_width(GTK_CONTAINER(header_table), 2);
5103         gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(header_scrolledwin), header_table);
5104         gtk_viewport_set_shadow_type(GTK_VIEWPORT(GTK_BIN(header_scrolledwin)->child), GTK_SHADOW_ETCHED_IN);
5105         count = 0;
5106
5107         /* option menu for selecting accounts */
5108         hbox = gtk_hbox_new(FALSE, 0);
5109         label = gtk_label_new(prefs_common.trans_hdr ? _("From:") : "From:");
5110         gtk_box_pack_end(GTK_BOX(hbox), label, FALSE, FALSE, 0);
5111         gtk_table_attach(GTK_TABLE(header_table), hbox, 0, 1, count, count + 1,
5112                          GTK_FILL, 0, 2, 0);
5113         from_optmenu_hbox = compose_account_option_menu_create(compose);
5114         gtk_table_attach(GTK_TABLE(header_table), from_optmenu_hbox,
5115                                   1, 2, count, count + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
5116         count++;
5117
5118         compose->header_table = header_table;
5119         compose->header_list = NULL;
5120         compose->header_nextrow = count;
5121
5122         compose_create_header_entry(compose);
5123
5124         compose->table            = NULL;
5125
5126         return header_scrolledwin ;
5127 }
5128
5129 GtkWidget *compose_create_attach(Compose *compose)
5130 {
5131         GtkWidget *attach_scrwin;
5132         GtkWidget *attach_clist;
5133
5134         GtkListStore *store;
5135         GtkCellRenderer *renderer;
5136         GtkTreeViewColumn *column;
5137         GtkTreeSelection *selection;
5138
5139         /* attachment list */
5140         attach_scrwin = gtk_scrolled_window_new(NULL, NULL);
5141         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(attach_scrwin),
5142                                        GTK_POLICY_AUTOMATIC,
5143                                        GTK_POLICY_AUTOMATIC);
5144         gtk_widget_set_size_request(attach_scrwin, -1, 80);
5145
5146         store = gtk_list_store_new(N_ATTACH_COLS, 
5147                                    G_TYPE_STRING,
5148                                    G_TYPE_STRING,
5149                                    G_TYPE_STRING,
5150                                    G_TYPE_POINTER,
5151                                    G_TYPE_AUTO_POINTER,
5152                                    -1);
5153         attach_clist = GTK_WIDGET(gtk_tree_view_new_with_model
5154                                         (GTK_TREE_MODEL(store)));
5155         gtk_container_add(GTK_CONTAINER(attach_scrwin), attach_clist);
5156         g_object_unref(store);
5157         
5158         renderer = gtk_cell_renderer_text_new();
5159         column = gtk_tree_view_column_new_with_attributes
5160                         (_("Mime type"), renderer, "text", 
5161                          COL_MIMETYPE, NULL);
5162         gtk_tree_view_append_column(GTK_TREE_VIEW(attach_clist), column);                        
5163         
5164         renderer = gtk_cell_renderer_text_new();
5165         column = gtk_tree_view_column_new_with_attributes
5166                         (_("Size"), renderer, "text", 
5167                          COL_SIZE, NULL);
5168         gtk_tree_view_append_column(GTK_TREE_VIEW(attach_clist), column);                        
5169         
5170         renderer = gtk_cell_renderer_text_new();
5171         column = gtk_tree_view_column_new_with_attributes
5172                         (_("Name"), renderer, "text", 
5173                          COL_NAME, NULL);
5174         gtk_tree_view_append_column(GTK_TREE_VIEW(attach_clist), column);
5175
5176         gtk_tree_view_set_rules_hint(GTK_TREE_VIEW(attach_clist),
5177                                      prefs_common.enable_rules_hint);
5178         selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(attach_clist));
5179         gtk_tree_selection_set_mode(selection, GTK_SELECTION_MULTIPLE);
5180
5181         g_signal_connect(G_OBJECT(attach_clist), "row_activated",
5182                          G_CALLBACK(attach_selected), compose);
5183         g_signal_connect(G_OBJECT(attach_clist), "button_press_event",
5184                          G_CALLBACK(attach_button_pressed), compose);
5185         g_signal_connect(G_OBJECT(attach_clist), "key_press_event",
5186                          G_CALLBACK(attach_key_pressed), compose);
5187
5188         /* drag and drop */
5189         gtk_drag_dest_set(attach_clist,
5190                           GTK_DEST_DEFAULT_ALL, compose_mime_types, 
5191                           sizeof(compose_mime_types)/sizeof(compose_mime_types[0]),
5192                           GDK_ACTION_COPY | GDK_ACTION_MOVE);
5193         g_signal_connect(G_OBJECT(attach_clist), "drag_data_received",
5194                          G_CALLBACK(compose_attach_drag_received_cb),
5195                          compose);
5196         g_signal_connect(G_OBJECT(attach_clist), "drag-drop",
5197                          G_CALLBACK(compose_drag_drop),
5198                          compose);
5199
5200         compose->attach_scrwin = attach_scrwin;
5201         compose->attach_clist  = attach_clist;
5202
5203         return attach_scrwin;
5204 }
5205
5206 static void compose_savemsg_checkbtn_cb(GtkWidget *widget, Compose *compose);
5207 static void compose_savemsg_select_cb(GtkWidget *widget, Compose *compose);
5208
5209 static GtkWidget *compose_create_others(Compose *compose)
5210 {
5211         GtkWidget *table;
5212         GtkWidget *savemsg_checkbtn;
5213         GtkWidget *savemsg_entry;
5214         GtkWidget *savemsg_select;
5215         
5216         guint rowcount = 0;
5217         gchar *folderidentifier;
5218
5219         /* Table for settings */
5220         table = gtk_table_new(3, 1, FALSE);
5221         gtk_widget_show(table);
5222         gtk_table_set_row_spacings(GTK_TABLE(table), VSPACING_NARROW);
5223         rowcount = 0;
5224
5225         /* Save Message to folder */
5226         savemsg_checkbtn = gtk_check_button_new_with_label(_("Save Message to "));
5227         gtk_widget_show(savemsg_checkbtn);
5228         gtk_table_attach(GTK_TABLE(table), savemsg_checkbtn, 0, 1, rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
5229         if (account_get_special_folder(compose->account, F_OUTBOX)) {
5230                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(savemsg_checkbtn), prefs_common.savemsg);
5231         }
5232         g_signal_connect(G_OBJECT(savemsg_checkbtn), "toggled",
5233                          G_CALLBACK(compose_savemsg_checkbtn_cb), compose);
5234
5235         savemsg_entry = gtk_entry_new();
5236         gtk_widget_show(savemsg_entry);
5237         gtk_table_attach_defaults(GTK_TABLE(table), savemsg_entry, 1, 2, rowcount, rowcount + 1);
5238         gtk_editable_set_editable(GTK_EDITABLE(savemsg_entry), prefs_common.savemsg);
5239         g_signal_connect_after(G_OBJECT(savemsg_entry), "grab_focus",
5240                          G_CALLBACK(compose_grab_focus_cb), compose);
5241         if (account_get_special_folder(compose->account, F_OUTBOX)) {
5242                 folderidentifier = folder_item_get_identifier(account_get_special_folder
5243                                   (compose->account, F_OUTBOX));
5244                 gtk_entry_set_text(GTK_ENTRY(savemsg_entry), folderidentifier);
5245                 g_free(folderidentifier);
5246         }
5247
5248         savemsg_select = gtkut_get_browse_file_btn(_("_Browse"));
5249         gtk_widget_show(savemsg_select);
5250         gtk_table_attach(GTK_TABLE(table), savemsg_select, 2, 3, rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
5251         g_signal_connect(G_OBJECT(savemsg_select), "clicked",
5252                          G_CALLBACK(compose_savemsg_select_cb),
5253                          compose);
5254
5255         rowcount++;
5256
5257         compose->savemsg_checkbtn = savemsg_checkbtn;
5258         compose->savemsg_entry = savemsg_entry;
5259
5260         return table;   
5261 }
5262
5263 static void compose_savemsg_checkbtn_cb(GtkWidget *widget, Compose *compose) 
5264 {
5265         gtk_editable_set_editable(GTK_EDITABLE(compose->savemsg_entry),
5266                 gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn)));
5267 }
5268
5269 static void compose_savemsg_select_cb(GtkWidget *widget, Compose *compose)
5270 {
5271         FolderItem *dest;
5272         gchar * path;
5273
5274         dest = foldersel_folder_sel(NULL, FOLDER_SEL_COPY, NULL);
5275         if (!dest) return;
5276
5277         path = folder_item_get_identifier(dest);
5278
5279         gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), path);
5280         g_free(path);
5281 }
5282
5283 static void entry_paste_clipboard(Compose *compose, GtkWidget *entry, gboolean wrap,
5284                                   GdkAtom clip);
5285
5286 #define BLOCK_WRAP() {                                                  \
5287         prev_autowrap = compose->autowrap;                              \
5288         buffer = gtk_text_view_get_buffer(                              \
5289                                         GTK_TEXT_VIEW(compose->text));  \
5290         compose->autowrap = FALSE;                                      \
5291                                                                         \
5292         g_signal_handlers_block_by_func(G_OBJECT(buffer),               \
5293                                 G_CALLBACK(compose_changed_cb),         \
5294                                 compose);                               \
5295         g_signal_handlers_block_by_func(G_OBJECT(buffer),               \
5296                                 G_CALLBACK(text_inserted),              \
5297                                 compose);                               \
5298 }
5299 #define UNBLOCK_WRAP() {                                                \
5300         compose->autowrap = prev_autowrap;                              \
5301         if (compose->autowrap)                                          \
5302                 compose_wrap_all(compose);                              \
5303                                                                         \
5304         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),             \
5305                                 G_CALLBACK(compose_changed_cb),         \
5306                                 compose);                               \
5307         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),             \
5308                                 G_CALLBACK(text_inserted),              \
5309                                 compose);                               \
5310 }
5311
5312
5313 static gboolean text_clicked(GtkWidget *text, GdkEventButton *event,
5314                                        Compose *compose)
5315 {
5316         gint prev_autowrap;
5317         GtkTextBuffer *buffer;
5318 #if USE_ASPELL
5319         if (event->button == 3) {
5320                 GtkTextIter iter;
5321                 GtkTextIter sel_start, sel_end;
5322                 gboolean stuff_selected;
5323                 gint x, y;
5324                 /* move the cursor to allow GtkAspell to check the word
5325                  * under the mouse */
5326                 gtk_text_view_window_to_buffer_coords(GTK_TEXT_VIEW(text),
5327                         GTK_TEXT_WINDOW_TEXT, event->x, event->y,
5328                         &x, &y);
5329                 gtk_text_view_get_iter_at_location (GTK_TEXT_VIEW(text),
5330                         &iter, x, y);
5331                 /* get selection */
5332                 stuff_selected = gtk_text_buffer_get_selection_bounds(
5333                                 GTK_TEXT_VIEW(text)->buffer,
5334                                 &sel_start, &sel_end);
5335
5336                 gtk_text_buffer_place_cursor (GTK_TEXT_VIEW(text)->buffer, &iter);
5337                 /* reselect stuff */
5338                 if (stuff_selected 
5339                 && gtk_text_iter_in_range(&iter, &sel_start, &sel_end)) {
5340                         gtk_text_buffer_select_range(GTK_TEXT_VIEW(text)->buffer,
5341                                 &sel_start, &sel_end);
5342                 }
5343                 return FALSE; /* pass the event so that the right-click goes through */
5344         }
5345 #endif
5346         if (event->button == 2) {
5347                 BLOCK_WRAP();
5348                 entry_paste_clipboard(compose, compose->focused_editable, 
5349                                 prefs_common.linewrap_pastes,
5350                                 GDK_SELECTION_PRIMARY);
5351                 UNBLOCK_WRAP();
5352                 return TRUE;
5353         }
5354         return FALSE;
5355 }
5356
5357 static Compose *compose_create(PrefsAccount *account, ComposeMode mode)
5358 {
5359         Compose   *compose;
5360         GtkWidget *window;
5361         GtkWidget *vbox;
5362         GtkWidget *menubar;
5363         GtkWidget *handlebox;
5364
5365         GtkWidget *notebook;
5366
5367         GtkWidget *vbox2;
5368
5369         GtkWidget *label;
5370         GtkWidget *subject_hbox;
5371         GtkWidget *subject_frame;
5372         GtkWidget *subject_entry;
5373         GtkWidget *subject;
5374         GtkWidget *paned;
5375
5376         GtkWidget *edit_vbox;
5377         GtkWidget *ruler_hbox;
5378         GtkWidget *ruler;
5379         GtkWidget *scrolledwin;
5380         GtkWidget *text;
5381         GtkTextBuffer *buffer;
5382         GtkClipboard *clipboard;
5383
5384         UndoMain *undostruct;
5385
5386         gchar *titles[N_ATTACH_COLS];
5387         guint n_menu_entries;
5388         GdkColormap *cmap;
5389         GdkColor color[1];
5390         gboolean success[1];
5391         GtkWidget *popupmenu;
5392         GtkItemFactory *popupfactory;
5393         GtkItemFactory *ifactory;
5394         GtkWidget *tmpl_menu;
5395         gint n_entries;
5396         GtkWidget *menuitem;
5397
5398 #if USE_ASPELL
5399         GtkAspell * gtkaspell = NULL;
5400 #endif
5401
5402         static GdkGeometry geometry;
5403
5404         g_return_val_if_fail(account != NULL, NULL);
5405
5406         debug_print("Creating compose window...\n");
5407         compose = g_new0(Compose, 1);
5408
5409         titles[COL_MIMETYPE] = _("MIME type");
5410         titles[COL_SIZE]     = _("Size");
5411         titles[COL_NAME]     = _("Name");
5412
5413         compose->account = account;
5414         
5415         compose->mutex = g_mutex_new();
5416         compose->set_cursor_pos = -1;
5417
5418         window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
5419         gtk_window_set_resizable(GTK_WINDOW(window), TRUE);
5420         gtk_widget_set_size_request(window, -1, prefs_common.compose_height);
5421
5422         if (!geometry.max_width) {
5423                 geometry.max_width = gdk_screen_width();
5424                 geometry.max_height = gdk_screen_height();
5425         }
5426
5427         gtk_window_set_geometry_hints(GTK_WINDOW(window), NULL,
5428                                       &geometry, GDK_HINT_MAX_SIZE);
5429         if (!geometry.min_width) {
5430                 geometry.min_width = 600;
5431                 geometry.min_height = 480;
5432         }
5433         gtk_window_set_geometry_hints(GTK_WINDOW(window), NULL,
5434                                       &geometry, GDK_HINT_MIN_SIZE);
5435         gtk_widget_set_uposition(window, prefs_common.compose_x, 
5436                                  prefs_common.compose_y);
5437
5438         g_signal_connect(G_OBJECT(window), "delete_event",
5439                          G_CALLBACK(compose_delete_cb), compose);
5440         MANAGE_WINDOW_SIGNALS_CONNECT(window);
5441         gtk_widget_realize(window);
5442
5443         gtkut_widget_set_composer_icon(window);
5444
5445         vbox = gtk_vbox_new(FALSE, 0);
5446         gtk_container_add(GTK_CONTAINER(window), vbox);
5447
5448         n_menu_entries = sizeof(compose_entries) / sizeof(compose_entries[0]);
5449         menubar = menubar_create(window, compose_entries,
5450                                  n_menu_entries, "<Compose>", compose);
5451         gtk_box_pack_start(GTK_BOX(vbox), menubar, FALSE, TRUE, 0);
5452
5453         if (prefs_common.toolbar_detachable) {
5454                 handlebox = gtk_handle_box_new();
5455         } else {
5456                 handlebox = gtk_hbox_new(FALSE, 0);
5457         }
5458         gtk_box_pack_start(GTK_BOX(vbox), handlebox, FALSE, FALSE, 0);
5459
5460         gtk_widget_realize(handlebox);
5461         compose->toolbar = toolbar_create(TOOLBAR_COMPOSE, handlebox,
5462                                           (gpointer)compose);
5463
5464         vbox2 = gtk_vbox_new(FALSE, 2);
5465         gtk_box_pack_start(GTK_BOX(vbox), vbox2, TRUE, TRUE, 0);
5466         gtk_container_set_border_width(GTK_CONTAINER(vbox2), 0);
5467         
5468         /* Notebook */
5469         notebook = gtk_notebook_new();
5470         gtk_widget_set_size_request(notebook, -1, 130);
5471         gtk_widget_show(notebook);
5472
5473         /* header labels and entries */
5474         gtk_notebook_append_page(GTK_NOTEBOOK(notebook), compose_create_header(compose), gtk_label_new(_("Header")));
5475         /* attachment list */
5476         gtk_notebook_append_page(GTK_NOTEBOOK(notebook), compose_create_attach(compose), gtk_label_new(_("Attachments")));
5477         /* Others Tab */
5478         gtk_notebook_append_page(GTK_NOTEBOOK(notebook), compose_create_others(compose), gtk_label_new(_("Others")));
5479
5480         /* Subject */
5481         subject_hbox = gtk_hbox_new(FALSE, 0);
5482         gtk_widget_show(subject_hbox);
5483
5484         subject_frame = gtk_frame_new(NULL);
5485         gtk_frame_set_shadow_type(GTK_FRAME(subject_frame), GTK_SHADOW_NONE);
5486         gtk_box_pack_start(GTK_BOX(subject_hbox), subject_frame, TRUE, TRUE, 0);
5487         gtk_widget_show(subject_frame);
5488
5489         subject = gtk_hbox_new(FALSE, 0);
5490         gtk_container_set_border_width(GTK_CONTAINER(subject), 0);
5491         gtk_widget_show(subject);
5492
5493         label = gtk_label_new(_("Subject:"));
5494         gtk_box_pack_start(GTK_BOX(subject), label, FALSE, FALSE, 0);
5495         gtk_widget_show(label);
5496
5497         subject_entry = gtk_entry_new();
5498         gtk_box_pack_start(GTK_BOX(subject), subject_entry, TRUE, TRUE, 0);
5499         g_signal_connect_after(G_OBJECT(subject_entry), "grab_focus",
5500                          G_CALLBACK(compose_grab_focus_cb), compose);
5501         gtk_widget_show(subject_entry);
5502         compose->subject_entry = subject_entry;
5503         gtk_container_add(GTK_CONTAINER(subject_frame), subject);
5504         
5505         edit_vbox = gtk_vbox_new(FALSE, 0);
5506
5507         gtk_box_pack_start(GTK_BOX(edit_vbox), subject_hbox, FALSE, FALSE, 0);
5508
5509         /* ruler */
5510         ruler_hbox = gtk_hbox_new(FALSE, 0);
5511         gtk_box_pack_start(GTK_BOX(edit_vbox), ruler_hbox, FALSE, FALSE, 0);
5512
5513         ruler = gtk_shruler_new();
5514         gtk_ruler_set_range(GTK_RULER(ruler), 0.0, 100.0, 1.0, 100.0);
5515         gtk_box_pack_start(GTK_BOX(ruler_hbox), ruler, TRUE, TRUE,
5516                            BORDER_WIDTH);
5517
5518         /* text widget */
5519         scrolledwin = gtk_scrolled_window_new(NULL, NULL);
5520         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin),
5521                                        GTK_POLICY_AUTOMATIC,
5522                                        GTK_POLICY_AUTOMATIC);
5523         gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scrolledwin),
5524                                             GTK_SHADOW_IN);
5525         gtk_box_pack_start(GTK_BOX(edit_vbox), scrolledwin, TRUE, TRUE, 0);
5526         gtk_widget_set_size_request(scrolledwin, prefs_common.compose_width, -1);
5527
5528         text = gtk_text_view_new();
5529         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
5530         gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(text), GTK_WRAP_WORD_CHAR);
5531         gtk_text_view_set_editable(GTK_TEXT_VIEW(text), TRUE);
5532         clipboard = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
5533         gtk_text_buffer_add_selection_clipboard(buffer, clipboard);
5534         
5535         gtk_container_add(GTK_CONTAINER(scrolledwin), text);
5536
5537         g_signal_connect_after(G_OBJECT(text), "size_allocate",
5538                                G_CALLBACK(compose_edit_size_alloc),
5539                                ruler);
5540         g_signal_connect(G_OBJECT(buffer), "changed",
5541                          G_CALLBACK(compose_changed_cb), compose);
5542         g_signal_connect(G_OBJECT(text), "grab_focus",
5543                          G_CALLBACK(compose_grab_focus_cb), compose);
5544         g_signal_connect(G_OBJECT(buffer), "insert_text",
5545                          G_CALLBACK(text_inserted), compose);
5546         g_signal_connect(G_OBJECT(text), "button_press_event",
5547                          G_CALLBACK(text_clicked), compose);
5548         g_signal_connect(G_OBJECT(subject_entry), "changed",
5549                          G_CALLBACK(compose_changed_cb), compose);
5550
5551         /* drag and drop */
5552         gtk_drag_dest_set(text, GTK_DEST_DEFAULT_ALL, compose_mime_types, 
5553                           sizeof(compose_mime_types)/sizeof(compose_mime_types[0]),
5554                           GDK_ACTION_COPY | GDK_ACTION_MOVE);
5555         g_signal_connect(G_OBJECT(text), "drag_data_received",
5556                          G_CALLBACK(compose_insert_drag_received_cb),
5557                          compose);
5558         g_signal_connect(G_OBJECT(text), "drag-drop",
5559                          G_CALLBACK(compose_drag_drop),
5560                          compose);
5561         gtk_widget_show_all(vbox);
5562
5563         /* pane between attach clist and text */
5564         paned = gtk_vpaned_new();
5565         gtk_paned_set_gutter_size(GTK_PANED(paned), 12);
5566         gtk_container_add(GTK_CONTAINER(vbox2), paned);
5567         gtk_paned_add1(GTK_PANED(paned), notebook);
5568         gtk_paned_add2(GTK_PANED(paned), edit_vbox);
5569         gtk_widget_show_all(paned);
5570
5571
5572         if (prefs_common.textfont) {
5573                 PangoFontDescription *font_desc;
5574
5575                 font_desc = pango_font_description_from_string
5576                         (prefs_common.textfont);
5577                 if (font_desc) {
5578                         gtk_widget_modify_font(text, font_desc);
5579                         pango_font_description_free(font_desc);
5580                 }
5581         }
5582
5583         color[0] = quote_color;
5584         cmap = gdk_drawable_get_colormap(window->window);
5585         gdk_colormap_alloc_colors(cmap, color, 1, FALSE, TRUE, success);
5586         if (success[0] == FALSE) {
5587                 GtkStyle *style;
5588
5589                 g_warning("Compose: color allocation failed.\n");
5590                 style = gtk_widget_get_style(text);
5591                 quote_color = style->black;
5592         }
5593
5594         n_entries = sizeof(compose_popup_entries) /
5595                 sizeof(compose_popup_entries[0]);
5596         popupmenu = menu_create_items(compose_popup_entries, n_entries,
5597                                       "<Compose>", &popupfactory,
5598                                       compose);
5599
5600         ifactory = gtk_item_factory_from_widget(menubar);
5601         menu_set_sensitive(ifactory, "/Edit/Undo", FALSE);
5602         menu_set_sensitive(ifactory, "/Edit/Redo", FALSE);
5603         menu_set_sensitive(ifactory, "/Options/Remove references", FALSE);
5604
5605         tmpl_menu = gtk_item_factory_get_item(ifactory, "/Tools/Template");
5606
5607         undostruct = undo_init(text);
5608         undo_set_change_state_func(undostruct, &compose_undo_state_changed,
5609                                    menubar);
5610
5611         address_completion_start(window);
5612
5613         compose->window        = window;
5614         compose->vbox          = vbox;
5615         compose->menubar       = menubar;
5616         compose->handlebox     = handlebox;
5617
5618         compose->vbox2         = vbox2;
5619
5620         compose->paned = paned;
5621
5622         compose->edit_vbox     = edit_vbox;
5623         compose->ruler_hbox    = ruler_hbox;
5624         compose->ruler         = ruler;
5625         compose->scrolledwin   = scrolledwin;
5626         compose->text          = text;
5627
5628         compose->focused_editable = NULL;
5629
5630         compose->popupmenu    = popupmenu;
5631         compose->popupfactory = popupfactory;
5632
5633         compose->tmpl_menu = tmpl_menu;
5634
5635         compose->mode = mode;
5636
5637         compose->targetinfo = NULL;
5638         compose->replyinfo  = NULL;
5639         compose->fwdinfo    = NULL;
5640
5641         compose->replyto     = NULL;
5642         compose->cc          = NULL;
5643         compose->bcc         = NULL;
5644         compose->followup_to = NULL;
5645
5646         compose->ml_post     = NULL;
5647
5648         compose->inreplyto   = NULL;
5649         compose->references  = NULL;
5650         compose->msgid       = NULL;
5651         compose->boundary    = NULL;
5652
5653         compose->autowrap       = prefs_common.autowrap;
5654
5655         compose->use_signing    = FALSE;
5656         compose->use_encryption = FALSE;
5657         compose->privacy_system = NULL;
5658
5659         compose->modified = FALSE;
5660
5661         compose->return_receipt = FALSE;
5662
5663         compose->to_list        = NULL;
5664         compose->newsgroup_list = NULL;
5665
5666         compose->undostruct = undostruct;
5667
5668         compose->sig_str = NULL;
5669
5670         compose->exteditor_file    = NULL;
5671         compose->exteditor_pid     = -1;
5672         compose->exteditor_tag     = -1;
5673         compose->draft_timeout_tag = -1;
5674
5675 #if USE_ASPELL
5676         menu_set_sensitive(ifactory, "/Spelling", FALSE);
5677         if (mode != COMPOSE_REDIRECT) {
5678                 if (prefs_common.enable_aspell && prefs_common.dictionary &&
5679                     strcmp(prefs_common.dictionary, _("None"))) {
5680                         gtkaspell = gtkaspell_new(prefs_common.aspell_path,
5681                                                   prefs_common.dictionary,
5682                                                   conv_get_locale_charset_str(),
5683                                                   prefs_common.misspelled_col,
5684                                                   prefs_common.check_while_typing,
5685                                                   prefs_common.use_alternate,
5686                                                   GTK_TEXT_VIEW(text),
5687                                                   GTK_WINDOW(compose->window));
5688                         if (!gtkaspell) {
5689                                 alertpanel_error(_("Spell checker could not "
5690                                                 "be started.\n%s"),
5691                                                 gtkaspell_checkers_strerror());
5692                                 gtkaspell_checkers_reset_error();
5693                         } else {
5694                                 if (!gtkaspell_set_sug_mode(gtkaspell,
5695                                                 prefs_common.aspell_sugmode)) {
5696                                         debug_print("Aspell: could not set "
5697                                                     "suggestion mode %s\n",
5698                                                     gtkaspell_checkers_strerror());
5699                                         gtkaspell_checkers_reset_error();
5700                                 }
5701
5702                                 menu_set_sensitive(ifactory, "/Spelling", TRUE);
5703                         }
5704                 }
5705         }
5706         compose->gtkaspell = gtkaspell;
5707 #endif
5708
5709         compose_select_account(compose, account, TRUE);
5710
5711         menu_set_active(ifactory, "/Edit/Auto wrapping", prefs_common.autowrap);
5712         if (account->set_autocc && account->auto_cc && mode != COMPOSE_REEDIT)
5713                 compose_entry_append(compose, account->auto_cc, COMPOSE_CC);
5714
5715         if (account->set_autobcc && account->auto_bcc && mode != COMPOSE_REEDIT) 
5716                 compose_entry_append(compose, account->auto_bcc, COMPOSE_BCC);
5717         
5718         if (account->set_autoreplyto && account->auto_replyto && mode != COMPOSE_REEDIT)
5719                 compose_entry_append(compose, account->auto_replyto, COMPOSE_REPLYTO);
5720
5721
5722         if (account->protocol != A_NNTP)
5723                 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry), prefs_common.trans_hdr ? _("To:") : "To:");
5724         else
5725                 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry), prefs_common.trans_hdr ? _("Newsgroups:") : "Newsgroups:");
5726
5727         addressbook_set_target_compose(compose);
5728         
5729         if (mode != COMPOSE_REDIRECT)
5730                 compose_set_template_menu(compose);
5731         else {
5732                 menuitem = gtk_item_factory_get_item(ifactory, "/Tools/Template");
5733                 menu_set_sensitive(ifactory, "/Tools/Template", FALSE);
5734         }
5735
5736         compose_list = g_list_append(compose_list, compose);
5737
5738         if (!prefs_common.show_ruler)
5739                 gtk_widget_hide(ruler_hbox);
5740                 
5741         menuitem = gtk_item_factory_get_item(ifactory, "/Tools/Show ruler");
5742         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
5743                                        prefs_common.show_ruler);
5744
5745         /* Priority */
5746         compose->priority = PRIORITY_NORMAL;
5747         compose_update_priority_menu_item(compose);
5748
5749         compose_set_out_encoding(compose);
5750         
5751         /* Actions menu */
5752         compose_update_actions_menu(compose);
5753
5754         /* Privacy Systems menu */
5755         compose_update_privacy_systems_menu(compose);
5756
5757         activate_privacy_system(compose, account, TRUE);
5758         toolbar_set_style(compose->toolbar->toolbar, compose->handlebox, prefs_common.toolbar_style);
5759         gtk_widget_show(window);
5760         
5761         return compose;
5762 }
5763
5764 static GtkWidget *compose_account_option_menu_create(Compose *compose)
5765 {
5766         GList *accounts;
5767         GtkWidget *hbox;
5768         GtkWidget *optmenu;
5769         GtkWidget *menu;
5770         gint num = 0, def_menu = 0;
5771
5772         accounts = account_get_list();
5773         g_return_val_if_fail(accounts != NULL, NULL);
5774
5775         hbox = gtk_hbox_new(FALSE, 0);
5776         optmenu = gtk_option_menu_new();
5777         gtk_box_pack_start(GTK_BOX(hbox), optmenu, FALSE, FALSE, 0);
5778         menu = gtk_menu_new();
5779
5780         for (; accounts != NULL; accounts = accounts->next, num++) {
5781                 PrefsAccount *ac = (PrefsAccount *)accounts->data;
5782                 GtkWidget *menuitem;
5783                 gchar *name;
5784
5785                 if (ac == compose->account) def_menu = num;
5786
5787                 if (ac->name)
5788                         name = g_strdup_printf("%s: %s <%s>",
5789                                                ac->account_name,
5790                                                ac->name, ac->address);
5791                 else
5792                         name = g_strdup_printf("%s: %s",
5793                                                ac->account_name, ac->address);
5794                 MENUITEM_ADD(menu, menuitem, name, ac->account_id);
5795                 g_free(name);
5796                 g_signal_connect(G_OBJECT(menuitem), "activate",
5797                                  G_CALLBACK(account_activated),
5798                                  compose);
5799         }
5800
5801         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), menu);
5802         gtk_option_menu_set_history(GTK_OPTION_MENU(optmenu), def_menu);
5803
5804         return hbox;
5805 }
5806
5807 static void compose_set_priority_cb(gpointer data,
5808                                     guint action,
5809                                     GtkWidget *widget)
5810 {
5811         Compose *compose = (Compose *) data;
5812         compose->priority = action;
5813 }
5814
5815 static void compose_update_priority_menu_item(Compose * compose)
5816 {
5817         GtkItemFactory *ifactory;
5818         GtkWidget *menuitem = NULL;
5819
5820         ifactory = gtk_item_factory_from_widget(compose->menubar);
5821         
5822         switch (compose->priority) {
5823                 case PRIORITY_HIGHEST:
5824                         menuitem = gtk_item_factory_get_item
5825                                 (ifactory, "/Options/Priority/Highest");
5826                         break;
5827                 case PRIORITY_HIGH:
5828                         menuitem = gtk_item_factory_get_item
5829                                 (ifactory, "/Options/Priority/High");
5830                         break;
5831                 case PRIORITY_NORMAL:
5832                         menuitem = gtk_item_factory_get_item
5833                                 (ifactory, "/Options/Priority/Normal");
5834                         break;
5835                 case PRIORITY_LOW:
5836                         menuitem = gtk_item_factory_get_item
5837                                 (ifactory, "/Options/Priority/Low");
5838                         break;
5839                 case PRIORITY_LOWEST:
5840                         menuitem = gtk_item_factory_get_item
5841                                 (ifactory, "/Options/Priority/Lowest");
5842                         break;
5843         }
5844         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), TRUE);
5845 }       
5846
5847 static void compose_set_privacy_system_cb(GtkWidget *widget, gpointer data)
5848 {
5849         Compose *compose = (Compose *) data;
5850         gchar *systemid;
5851         GtkItemFactory *ifactory;
5852         gboolean can_sign = FALSE, can_encrypt = FALSE;
5853
5854         g_return_if_fail(GTK_IS_CHECK_MENU_ITEM(widget));
5855
5856         if (!GTK_CHECK_MENU_ITEM(widget)->active)
5857                 return;
5858
5859         systemid = g_object_get_data(G_OBJECT(widget), "privacy_system");
5860         g_free(compose->privacy_system);
5861         compose->privacy_system = NULL;
5862         if (systemid != NULL) {
5863                 compose->privacy_system = g_strdup(systemid);
5864
5865                 can_sign = privacy_system_can_sign(systemid);
5866                 can_encrypt = privacy_system_can_encrypt(systemid);
5867         }
5868
5869         debug_print("activated privacy system: %s\n", systemid != NULL ? systemid : "None");
5870
5871         ifactory = gtk_item_factory_from_widget(compose->menubar);
5872         menu_set_sensitive(ifactory, "/Options/Sign", can_sign);
5873         menu_set_sensitive(ifactory, "/Options/Encrypt", can_encrypt);
5874 }
5875
5876 static void compose_update_privacy_system_menu_item(Compose * compose, gboolean warn)
5877 {
5878         static gchar *branch_path = "/Options/Privacy System";
5879         GtkItemFactory *ifactory;
5880         GtkWidget *menuitem = NULL;
5881         GList *amenu;
5882         gboolean can_sign = FALSE, can_encrypt = FALSE;
5883         gboolean found = FALSE;
5884
5885         ifactory = gtk_item_factory_from_widget(compose->menubar);
5886
5887         if (compose->privacy_system != NULL) {
5888                 gchar *systemid;
5889
5890                 menuitem = gtk_item_factory_get_widget(ifactory, branch_path);
5891                 g_return_if_fail(menuitem != NULL);
5892
5893                 amenu = GTK_MENU_SHELL(menuitem)->children;
5894                 menuitem = NULL;
5895                 while (amenu != NULL) {
5896                         GList *alist = amenu->next;
5897
5898                         systemid = g_object_get_data(G_OBJECT(amenu->data), "privacy_system");
5899                         if (systemid != NULL) {
5900                                 if (strcmp(systemid, compose->privacy_system) == 0) {
5901                                         menuitem = GTK_WIDGET(amenu->data);
5902
5903                                         can_sign = privacy_system_can_sign(systemid);
5904                                         can_encrypt = privacy_system_can_encrypt(systemid);
5905                                         found = TRUE;
5906                                         break;
5907                                 } 
5908                         } else if (strlen(compose->privacy_system) == 0) {
5909                                         menuitem = GTK_WIDGET(amenu->data);
5910
5911                                         can_sign = FALSE;
5912                                         can_encrypt = FALSE;
5913                                         found = TRUE;
5914                                         break;
5915                         }
5916
5917                         amenu = alist;
5918                 }
5919                 if (menuitem != NULL)
5920                         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), TRUE);
5921                 
5922                 if (warn && !found && strlen(compose->privacy_system)) {
5923                         gchar *tmp = g_strdup_printf(
5924                                 _("The privacy system '%s' cannot be loaded. You "
5925                                   "will not be able to sign or encrypt this message."),
5926                                   compose->privacy_system);
5927                         alertpanel_warning(tmp);
5928                         g_free(tmp);
5929                 }
5930         } 
5931
5932         menu_set_sensitive(ifactory, "/Options/Sign", can_sign);
5933         menu_set_sensitive(ifactory, "/Options/Encrypt", can_encrypt);
5934 }       
5935  
5936 static void compose_set_out_encoding(Compose *compose)
5937 {
5938         GtkItemFactoryEntry *entry;
5939         GtkItemFactory *ifactory;
5940         CharSet out_encoding;
5941         gchar *path, *p, *q;
5942         GtkWidget *item;
5943
5944         out_encoding = conv_get_charset_from_str(prefs_common.outgoing_charset);
5945         ifactory = gtk_item_factory_from_widget(compose->menubar);
5946
5947         for (entry = compose_entries; entry->callback != compose_address_cb;
5948              entry++) {
5949                 if (entry->callback == compose_set_encoding_cb &&
5950                     (CharSet)entry->callback_action == out_encoding) {
5951                         p = q = path = g_strdup(entry->path);
5952                         while (*p) {
5953                                 if (*p == '_') {
5954                                         if (p[1] == '_') {
5955                                                 p++;
5956                                                 *q++ = '_';
5957                                         }
5958                                 } else
5959                                         *q++ = *p;
5960                                 p++;
5961                         }
5962                         *q = '\0';
5963                         item = gtk_item_factory_get_item(ifactory, path);
5964                         gtk_widget_activate(item);
5965                         g_free(path);
5966                         break;
5967                 }
5968         }
5969 }
5970
5971 static void compose_set_template_menu(Compose *compose)
5972 {
5973         GSList *tmpl_list, *cur;
5974         GtkWidget *menu;
5975         GtkWidget *item;
5976
5977         tmpl_list = template_get_config();
5978
5979         menu = gtk_menu_new();
5980
5981         for (cur = tmpl_list; cur != NULL; cur = cur->next) {
5982                 Template *tmpl = (Template *)cur->data;
5983
5984                 item = gtk_menu_item_new_with_label(tmpl->name);
5985                 gtk_menu_shell_append(GTK_MENU_SHELL(menu), item);
5986                 g_signal_connect(G_OBJECT(item), "activate",
5987                                  G_CALLBACK(compose_template_activate_cb),
5988                                  compose);
5989                 g_object_set_data(G_OBJECT(item), "template", tmpl);
5990                 gtk_widget_show(item);
5991         }
5992
5993         gtk_widget_show(menu);
5994         gtk_menu_item_set_submenu(GTK_MENU_ITEM(compose->tmpl_menu), menu);
5995 }
5996
5997 void compose_update_actions_menu(Compose *compose)
5998 {
5999         GtkItemFactory *ifactory;
6000
6001         ifactory = gtk_item_factory_from_widget(compose->menubar);
6002         action_update_compose_menu(ifactory, "/Tools/Actions", compose);
6003 }
6004
6005 void compose_update_privacy_systems_menu(Compose *compose)
6006 {
6007         static gchar *branch_path = "/Options/Privacy System";
6008         GtkItemFactory *ifactory;
6009         GtkWidget *menuitem;
6010         GSList *systems, *cur;
6011         GList *amenu;
6012         GtkWidget *widget;
6013         GtkWidget *system_none;
6014         GSList *group;
6015
6016         ifactory = gtk_item_factory_from_widget(compose->menubar);
6017
6018         /* remove old entries */
6019         menuitem = gtk_item_factory_get_widget(ifactory, branch_path);
6020         g_return_if_fail(menuitem != NULL);
6021
6022         amenu = GTK_MENU_SHELL(menuitem)->children->next;
6023         while (amenu != NULL) {
6024                 GList *alist = amenu->next;
6025                 gtk_widget_destroy(GTK_WIDGET(amenu->data));
6026                 amenu = alist;
6027         }
6028
6029         system_none = gtk_item_factory_get_widget(ifactory,
6030                 "/Options/Privacy System/None");
6031
6032         g_signal_connect(G_OBJECT(system_none), "activate",
6033                 G_CALLBACK(compose_set_privacy_system_cb), compose);
6034
6035         systems = privacy_get_system_ids();
6036         for (cur = systems; cur != NULL; cur = g_slist_next(cur)) {
6037                 gchar *systemid = cur->data;
6038
6039                 group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(system_none));
6040                 widget = gtk_radio_menu_item_new_with_label(group,
6041                         privacy_system_get_name(systemid));
6042                 g_object_set_data_full(G_OBJECT(widget), "privacy_system",
6043                                        g_strdup(systemid), g_free);
6044                 g_signal_connect(G_OBJECT(widget), "activate",
6045                         G_CALLBACK(compose_set_privacy_system_cb), compose);
6046
6047                 gtk_menu_append(GTK_MENU(system_none->parent), widget);
6048                 gtk_widget_show(widget);
6049                 g_free(systemid);
6050         }
6051         g_slist_free(systems);
6052 }
6053
6054 void compose_reflect_prefs_all(void)
6055 {
6056         GList *cur;
6057         Compose *compose;
6058
6059         for (cur = compose_list; cur != NULL; cur = cur->next) {
6060                 compose = (Compose *)cur->data;
6061                 compose_set_template_menu(compose);
6062         }
6063 }
6064
6065 void compose_reflect_prefs_pixmap_theme(void)
6066 {
6067         GList *cur;
6068         Compose *compose;
6069
6070         for (cur = compose_list; cur != NULL; cur = cur->next) {
6071                 compose = (Compose *)cur->data;
6072                 toolbar_update(TOOLBAR_COMPOSE, compose);
6073         }
6074 }
6075
6076 static void compose_template_apply(Compose *compose, Template *tmpl,
6077                                    gboolean replace)
6078 {
6079         GtkTextView *text;
6080         GtkTextBuffer *buffer;
6081         GtkTextMark *mark;
6082         GtkTextIter iter;
6083         gchar *qmark;
6084         gchar *parsed_str = NULL;
6085         gint cursor_pos = 0;
6086         if (!tmpl) return;
6087
6088         text = GTK_TEXT_VIEW(compose->text);
6089         buffer = gtk_text_view_get_buffer(text);
6090
6091         if (tmpl->subject && *tmpl->subject != '\0')
6092                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry),
6093                                    tmpl->subject);
6094         if (tmpl->to && *tmpl->to != '\0')
6095                 compose_entry_append(compose, tmpl->to, COMPOSE_TO);
6096         if (tmpl->cc && *tmpl->cc != '\0')
6097                 compose_entry_append(compose, tmpl->cc, COMPOSE_CC);
6098
6099         if (tmpl->bcc && *tmpl->bcc != '\0')
6100                 compose_entry_append(compose, tmpl->bcc, COMPOSE_BCC);
6101
6102         if (replace)
6103                 gtk_text_buffer_set_text(buffer, "", -1);
6104
6105         mark = gtk_text_buffer_get_insert(buffer);
6106         gtk_text_buffer_get_iter_at_mark(buffer, &iter, mark);
6107
6108         if (tmpl->value) {
6109                 if ((compose->replyinfo == NULL) && (compose->fwdinfo == NULL)) {
6110                         parsed_str = compose_quote_fmt(compose, NULL, tmpl->value,
6111                                                        NULL, NULL, FALSE);
6112                 } else {
6113                         if (prefs_common.quotemark && *prefs_common.quotemark)
6114                                 qmark = prefs_common.quotemark;
6115                         else
6116                                 qmark = "> ";
6117
6118                         if (compose->replyinfo != NULL)
6119                                 parsed_str = compose_quote_fmt(compose, compose->replyinfo,
6120                                                                tmpl->value, qmark, NULL, FALSE);
6121                         else if (compose->fwdinfo != NULL)
6122                                 parsed_str = compose_quote_fmt(compose, compose->fwdinfo,
6123                                                                tmpl->value, qmark, NULL, FALSE);
6124                         else
6125                                 parsed_str = NULL;
6126                 }
6127         }
6128         if (replace && parsed_str && compose->account->auto_sig)
6129                 compose_insert_sig(compose, FALSE);
6130
6131         if (replace && parsed_str) {
6132                 gtk_text_buffer_get_start_iter(buffer, &iter);
6133                 gtk_text_buffer_place_cursor(buffer, &iter);
6134         }
6135         
6136         if (parsed_str) {
6137                 cursor_pos = quote_fmt_get_cursor_pos();
6138                 compose->set_cursor_pos = cursor_pos;
6139                 if (cursor_pos == -1)
6140                         cursor_pos = 0;
6141                 gtk_text_buffer_get_start_iter(buffer, &iter);
6142                 gtk_text_buffer_get_iter_at_offset(buffer, &iter, cursor_pos);
6143                 gtk_text_buffer_place_cursor(buffer, &iter);
6144         }
6145
6146         compose_changed_cb(NULL, compose);
6147 }
6148
6149 static void compose_destroy(Compose *compose)
6150 {
6151         compose_list = g_list_remove(compose_list, compose);
6152
6153         /* NOTE: address_completion_end() does nothing with the window
6154          * however this may change. */
6155         address_completion_end(compose->window);
6156
6157         slist_free_strings(compose->to_list);
6158         g_slist_free(compose->to_list);
6159         slist_free_strings(compose->newsgroup_list);
6160         g_slist_free(compose->newsgroup_list);
6161         slist_free_strings(compose->header_list);
6162         g_slist_free(compose->header_list);
6163
6164         procmsg_msginfo_free(compose->targetinfo);
6165         procmsg_msginfo_free(compose->replyinfo);
6166         procmsg_msginfo_free(compose->fwdinfo);
6167
6168         g_free(compose->replyto);
6169         g_free(compose->cc);
6170         g_free(compose->bcc);
6171         g_free(compose->newsgroups);
6172         g_free(compose->followup_to);
6173
6174         g_free(compose->ml_post);
6175
6176         g_free(compose->inreplyto);
6177         g_free(compose->references);
6178         g_free(compose->msgid);
6179         g_free(compose->boundary);
6180
6181         if (compose->redirect_filename)
6182                 g_free(compose->redirect_filename);
6183         if (compose->undostruct)
6184                 undo_destroy(compose->undostruct);
6185
6186         g_free(compose->sig_str);
6187
6188         g_free(compose->exteditor_file);
6189
6190         g_free(compose->orig_charset);
6191
6192         g_free(compose->privacy_system);
6193
6194         if (addressbook_get_target_compose() == compose)
6195                 addressbook_set_target_compose(NULL);
6196
6197 #if USE_ASPELL
6198         if (compose->gtkaspell) {
6199                 gtkaspell_delete(compose->gtkaspell);
6200                 compose->gtkaspell = NULL;
6201         }
6202 #endif
6203
6204         prefs_common.compose_width = compose->scrolledwin->allocation.width;
6205         prefs_common.compose_height = compose->window->allocation.height;
6206
6207         if (!gtk_widget_get_parent(compose->paned))
6208                 gtk_widget_destroy(compose->paned);
6209         gtk_widget_destroy(compose->popupmenu);
6210
6211         gtk_widget_destroy(compose->window);
6212         toolbar_destroy(compose->toolbar);
6213         g_free(compose->toolbar);
6214         g_mutex_free(compose->mutex);
6215         g_free(compose);
6216 }
6217
6218 static void compose_attach_info_free(AttachInfo *ainfo)
6219 {
6220         g_free(ainfo->file);
6221         g_free(ainfo->content_type);
6222         g_free(ainfo->name);
6223         g_free(ainfo);
6224 }
6225
6226 static void compose_attach_remove_selected(Compose *compose)
6227 {
6228         GtkTreeView *tree_view = GTK_TREE_VIEW(compose->attach_clist);
6229         GtkTreeSelection *selection;
6230         GList *sel, *cur;
6231         GtkTreeModel *model;
6232
6233         selection = gtk_tree_view_get_selection(tree_view);
6234         sel = gtk_tree_selection_get_selected_rows(selection, &model);
6235
6236         if (!sel) 
6237                 return;
6238
6239         for (cur = sel; cur != NULL; cur = cur->next) {
6240                 GtkTreePath *path = cur->data;
6241                 GtkTreeRowReference *ref = gtk_tree_row_reference_new
6242                                                 (model, cur->data);
6243                 cur->data = ref;
6244                 gtk_tree_path_free(path);
6245         }
6246
6247         for (cur = sel; cur != NULL; cur = cur->next) {
6248                 GtkTreeRowReference *ref = cur->data;
6249                 GtkTreePath *path = gtk_tree_row_reference_get_path(ref);
6250                 GtkTreeIter iter;
6251
6252                 if (gtk_tree_model_get_iter(model, &iter, path))
6253                         gtk_list_store_remove(GTK_LIST_STORE(model), &iter);
6254                 
6255                 gtk_tree_path_free(path);
6256                 gtk_tree_row_reference_free(ref);
6257         }
6258
6259         g_list_free(sel);
6260 }
6261
6262 static struct _AttachProperty
6263 {
6264         GtkWidget *window;
6265         GtkWidget *mimetype_entry;
6266         GtkWidget *encoding_optmenu;
6267         GtkWidget *path_entry;
6268         GtkWidget *filename_entry;
6269         GtkWidget *ok_btn;
6270         GtkWidget *cancel_btn;
6271 } attach_prop;
6272
6273 static void gtk_tree_path_free_(gpointer ptr, gpointer data)
6274 {       
6275         gtk_tree_path_free((GtkTreePath *)ptr);
6276 }
6277
6278 static void compose_attach_property(Compose *compose)
6279 {
6280         GtkTreeView *tree_view = GTK_TREE_VIEW(compose->attach_clist);
6281         AttachInfo *ainfo;
6282         GtkOptionMenu *optmenu;
6283         GtkTreeSelection *selection;
6284         GList *sel;
6285         GtkTreeModel *model;
6286         GtkTreeIter iter;
6287         GtkTreePath *path;
6288         static gboolean cancelled;
6289
6290         /* only if one selected */
6291         selection = gtk_tree_view_get_selection(tree_view);
6292         if (gtk_tree_selection_count_selected_rows(selection) != 1) 
6293                 return;
6294
6295         sel = gtk_tree_selection_get_selected_rows(selection, &model);
6296         if (!sel)
6297                 return;
6298
6299         path = (GtkTreePath *) sel->data;
6300         gtk_tree_model_get_iter(model, &iter, path);
6301         gtk_tree_model_get(model, &iter, COL_DATA, &ainfo, -1); 
6302         
6303         if (!ainfo) {
6304                 g_list_foreach(sel, gtk_tree_path_free_, NULL);
6305                 g_list_free(sel);
6306                 return;
6307         }               
6308         g_list_free(sel);
6309
6310         if (!attach_prop.window)
6311                 compose_attach_property_create(&cancelled);
6312         gtk_widget_grab_focus(attach_prop.ok_btn);
6313         gtk_widget_show(attach_prop.window);
6314         manage_window_set_transient(GTK_WINDOW(attach_prop.window));
6315
6316         optmenu = GTK_OPTION_MENU(attach_prop.encoding_optmenu);
6317         if (ainfo->encoding == ENC_UNKNOWN)
6318                 menu_select_by_data(GTK_MENU(gtk_option_menu_get_menu(optmenu)),
6319                                     GINT_TO_POINTER(ENC_BASE64));
6320         else
6321                 menu_select_by_data(GTK_MENU(gtk_option_menu_get_menu(optmenu)),
6322                                     GINT_TO_POINTER(ainfo->encoding));
6323
6324         gtk_entry_set_text(GTK_ENTRY(attach_prop.mimetype_entry),
6325                            ainfo->content_type ? ainfo->content_type : "");
6326         gtk_entry_set_text(GTK_ENTRY(attach_prop.path_entry),
6327                            ainfo->file ? ainfo->file : "");
6328         gtk_entry_set_text(GTK_ENTRY(attach_prop.filename_entry),
6329                            ainfo->name ? ainfo->name : "");
6330
6331         for (;;) {
6332                 const gchar *entry_text;
6333                 gchar *text;
6334                 gchar *cnttype = NULL;
6335                 gchar *file = NULL;
6336                 off_t size = 0;
6337                 GtkWidget *menu;
6338                 GtkWidget *menuitem;
6339
6340                 cancelled = FALSE;
6341                 gtk_main();
6342
6343                 gtk_widget_hide(attach_prop.window);
6344                 
6345                 if (cancelled) 
6346                         break;
6347
6348                 entry_text = gtk_entry_get_text(GTK_ENTRY(attach_prop.mimetype_entry));
6349                 if (*entry_text != '\0') {
6350                         gchar *p;
6351
6352                         text = g_strstrip(g_strdup(entry_text));
6353                         if ((p = strchr(text, '/')) && !strchr(p + 1, '/')) {
6354                                 cnttype = g_strdup(text);
6355                                 g_free(text);
6356                         } else {
6357                                 alertpanel_error(_("Invalid MIME type."));
6358                                 g_free(text);
6359                                 continue;
6360                         }
6361                 }
6362
6363                 menu = gtk_option_menu_get_menu(optmenu);
6364                 menuitem = gtk_menu_get_active(GTK_MENU(menu));
6365                 ainfo->encoding = GPOINTER_TO_INT
6366                         (g_object_get_data(G_OBJECT(menuitem), MENU_VAL_ID));
6367
6368                 entry_text = gtk_entry_get_text(GTK_ENTRY(attach_prop.path_entry));
6369                 if (*entry_text != '\0') {
6370                         if (is_file_exist(entry_text) &&
6371                             (size = get_file_size(entry_text)) > 0)
6372                                 file = g_strdup(entry_text);
6373                         else {
6374                                 alertpanel_error
6375                                         (_("File doesn't exist or is empty."));
6376                                 g_free(cnttype);
6377                                 continue;
6378                         }
6379                 }
6380
6381                 entry_text = gtk_entry_get_text(GTK_ENTRY(attach_prop.filename_entry));
6382                 if (*entry_text != '\0') {
6383                         g_free(ainfo->name);
6384                         ainfo->name = g_strdup(entry_text);
6385                 }
6386
6387                 if (cnttype) {
6388                         g_free(ainfo->content_type);
6389                         ainfo->content_type = cnttype;
6390                 }
6391                 if (file) {
6392                         g_free(ainfo->file);
6393                         ainfo->file = file;
6394                 }
6395                 if (size)
6396                         ainfo->size = size;
6397
6398                 /* update tree store */
6399                 text = to_human_readable(ainfo->size);
6400                 gtk_tree_model_get_iter(model, &iter, path);
6401                 gtk_list_store_set(GTK_LIST_STORE(model), &iter,
6402                                    COL_MIMETYPE, ainfo->content_type,
6403                                    COL_SIZE, text,
6404                                    COL_NAME, ainfo->name,
6405                                    -1);
6406                 
6407                 break;
6408         }
6409
6410         gtk_tree_path_free(path);
6411 }
6412
6413 #define SET_LABEL_AND_ENTRY(str, entry, top) \
6414 { \
6415         label = gtk_label_new(str); \
6416         gtk_table_attach(GTK_TABLE(table), label, 0, 1, top, (top + 1), \
6417                          GTK_FILL, 0, 0, 0); \
6418         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); \
6419  \
6420         entry = gtk_entry_new(); \
6421         gtk_table_attach(GTK_TABLE(table), entry, 1, 2, top, (top + 1), \
6422                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0); \
6423 }
6424
6425 static void compose_attach_property_create(gboolean *cancelled)
6426 {
6427         GtkWidget *window;
6428         GtkWidget *vbox;
6429         GtkWidget *table;
6430         GtkWidget *label;
6431         GtkWidget *mimetype_entry;
6432         GtkWidget *hbox;
6433         GtkWidget *optmenu;
6434         GtkWidget *optmenu_menu;
6435         GtkWidget *menuitem;
6436         GtkWidget *path_entry;
6437         GtkWidget *filename_entry;
6438         GtkWidget *hbbox;
6439         GtkWidget *ok_btn;
6440         GtkWidget *cancel_btn;
6441         GList     *mime_type_list, *strlist;
6442
6443         debug_print("Creating attach_property window...\n");
6444
6445         window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
6446         gtk_widget_set_size_request(window, 480, -1);
6447         gtk_container_set_border_width(GTK_CONTAINER(window), 8);
6448         gtk_window_set_title(GTK_WINDOW(window), _("Properties"));
6449         gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
6450         gtk_window_set_modal(GTK_WINDOW(window), TRUE);
6451         g_signal_connect(G_OBJECT(window), "delete_event",
6452                          G_CALLBACK(attach_property_delete_event),
6453                          cancelled);
6454         g_signal_connect(G_OBJECT(window), "key_press_event",
6455                          G_CALLBACK(attach_property_key_pressed),
6456                          cancelled);
6457
6458         vbox = gtk_vbox_new(FALSE, 8);
6459         gtk_container_add(GTK_CONTAINER(window), vbox);
6460
6461         table = gtk_table_new(4, 2, FALSE);
6462         gtk_box_pack_start(GTK_BOX(vbox), table, FALSE, FALSE, 0);
6463         gtk_table_set_row_spacings(GTK_TABLE(table), 8);
6464         gtk_table_set_col_spacings(GTK_TABLE(table), 8);
6465
6466         label = gtk_label_new(_("MIME type")); 
6467         gtk_table_attach(GTK_TABLE(table), label, 0, 1, 0, (0 + 1), 
6468                          GTK_FILL, 0, 0, 0); 
6469         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); 
6470         mimetype_entry = gtk_combo_new(); 
6471         gtk_table_attach(GTK_TABLE(table), mimetype_entry, 1, 2, 0, (0 + 1), 
6472                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0);
6473                          
6474         /* stuff with list */
6475         mime_type_list = procmime_get_mime_type_list();
6476         strlist = NULL;
6477         for (; mime_type_list != NULL; mime_type_list = mime_type_list->next) {
6478                 MimeType *type = (MimeType *) mime_type_list->data;
6479                 gchar *tmp;
6480
6481                 tmp = g_strdup_printf("%s/%s", type->type, type->sub_type);
6482
6483                 if (g_list_find_custom(strlist, tmp, (GCompareFunc)strcmp2))
6484                         g_free(tmp);
6485                 else
6486                         strlist = g_list_insert_sorted(strlist, (gpointer)tmp,
6487                                         (GCompareFunc)strcmp2);
6488         }
6489
6490         gtk_combo_set_popdown_strings(GTK_COMBO(mimetype_entry), strlist);
6491
6492         for (mime_type_list = strlist; mime_type_list != NULL; 
6493                 mime_type_list = mime_type_list->next)
6494                 g_free(mime_type_list->data);
6495         g_list_free(strlist);
6496                          
6497         mimetype_entry = GTK_COMBO(mimetype_entry)->entry;                       
6498
6499         label = gtk_label_new(_("Encoding"));
6500         gtk_table_attach(GTK_TABLE(table), label, 0, 1, 1, 2,
6501                          GTK_FILL, 0, 0, 0);
6502         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5);
6503
6504         hbox = gtk_hbox_new(FALSE, 0);
6505         gtk_table_attach(GTK_TABLE(table), hbox, 1, 2, 1, 2,
6506                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0);
6507
6508         optmenu = gtk_option_menu_new();
6509         gtk_box_pack_start(GTK_BOX(hbox), optmenu, TRUE, TRUE, 0);
6510
6511         optmenu_menu = gtk_menu_new();
6512         MENUITEM_ADD(optmenu_menu, menuitem, "7bit", ENC_7BIT);
6513         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
6514         MENUITEM_ADD(optmenu_menu, menuitem, "8bit", ENC_8BIT);
6515         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
6516         MENUITEM_ADD(optmenu_menu, menuitem, "quoted-printable",
6517                      ENC_QUOTED_PRINTABLE);
6518         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
6519
6520         MENUITEM_ADD(optmenu_menu, menuitem, "base64", ENC_BASE64);
6521
6522         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
6523
6524         SET_LABEL_AND_ENTRY(_("Path"),      path_entry,     2);
6525         SET_LABEL_AND_ENTRY(_("File name"), filename_entry, 3);
6526
6527         gtkut_stock_button_set_create(&hbbox, &cancel_btn, GTK_STOCK_CANCEL,
6528                                       &ok_btn, GTK_STOCK_OK,
6529                                       NULL, NULL);
6530         gtk_box_pack_end(GTK_BOX(vbox), hbbox, FALSE, FALSE, 0);
6531         gtk_widget_grab_default(ok_btn);
6532
6533         g_signal_connect(G_OBJECT(ok_btn), "clicked",
6534                          G_CALLBACK(attach_property_ok),
6535                          cancelled);
6536         g_signal_connect(G_OBJECT(cancel_btn), "clicked",
6537                          G_CALLBACK(attach_property_cancel),
6538                          cancelled);
6539
6540         gtk_widget_show_all(vbox);
6541
6542         attach_prop.window           = window;
6543         attach_prop.mimetype_entry   = mimetype_entry;
6544         attach_prop.encoding_optmenu = optmenu;
6545         attach_prop.path_entry       = path_entry;
6546         attach_prop.filename_entry   = filename_entry;
6547         attach_prop.ok_btn           = ok_btn;
6548         attach_prop.cancel_btn       = cancel_btn;
6549 }
6550
6551 #undef SET_LABEL_AND_ENTRY
6552
6553 static void attach_property_ok(GtkWidget *widget, gboolean *cancelled)
6554 {
6555         *cancelled = FALSE;
6556         gtk_main_quit();
6557 }
6558
6559 static void attach_property_cancel(GtkWidget *widget, gboolean *cancelled)
6560 {
6561         *cancelled = TRUE;
6562         gtk_main_quit();
6563 }
6564
6565 static gint attach_property_delete_event(GtkWidget *widget, GdkEventAny *event,
6566                                          gboolean *cancelled)
6567 {
6568         *cancelled = TRUE;
6569         gtk_main_quit();
6570
6571         return TRUE;
6572 }
6573
6574 static gboolean attach_property_key_pressed(GtkWidget *widget,
6575                                             GdkEventKey *event,
6576                                             gboolean *cancelled)
6577 {
6578         if (event && event->keyval == GDK_Escape) {
6579                 *cancelled = TRUE;
6580                 gtk_main_quit();
6581         }
6582         return FALSE;
6583 }
6584
6585 static void compose_exec_ext_editor(Compose *compose)
6586 {
6587 #ifdef G_OS_UNIX
6588         gchar *tmp;
6589         pid_t pid;
6590         gint pipe_fds[2];
6591
6592         tmp = g_strdup_printf("%s%ctmpmsg.%p", get_tmp_dir(),
6593                               G_DIR_SEPARATOR, compose);
6594
6595         if (pipe(pipe_fds) < 0) {
6596                 perror("pipe");
6597                 g_free(tmp);
6598                 return;
6599         }
6600
6601         if ((pid = fork()) < 0) {
6602                 perror("fork");
6603                 g_free(tmp);
6604                 return;
6605         }
6606
6607         if (pid != 0) {
6608                 /* close the write side of the pipe */
6609                 close(pipe_fds[1]);
6610
6611                 compose->exteditor_file    = g_strdup(tmp);
6612                 compose->exteditor_pid     = pid;
6613
6614                 compose_set_ext_editor_sensitive(compose, FALSE);
6615
6616                 compose->exteditor_ch = g_io_channel_unix_new(pipe_fds[0]);
6617                 compose->exteditor_tag = g_io_add_watch(compose->exteditor_ch,
6618                                                         G_IO_IN,
6619                                                         compose_input_cb,
6620                                                         compose);
6621         } else {        /* process-monitoring process */
6622                 pid_t pid_ed;
6623
6624                 if (setpgid(0, 0))
6625                         perror("setpgid");
6626
6627                 /* close the read side of the pipe */
6628                 close(pipe_fds[0]);
6629
6630                 if (compose_write_body_to_file(compose, tmp) < 0) {
6631                         fd_write_all(pipe_fds[1], "2\n", 2);
6632                         _exit(1);
6633                 }
6634
6635                 pid_ed = compose_exec_ext_editor_real(tmp);
6636                 if (pid_ed < 0) {
6637                         fd_write_all(pipe_fds[1], "1\n", 2);
6638                         _exit(1);
6639                 }
6640
6641                 /* wait until editor is terminated */
6642                 waitpid(pid_ed, NULL, 0);
6643
6644                 fd_write_all(pipe_fds[1], "0\n", 2);
6645
6646                 close(pipe_fds[1]);
6647                 _exit(0);
6648         }
6649
6650         g_free(tmp);
6651 #endif /* G_OS_UNIX */
6652 }
6653
6654 #ifdef G_OS_UNIX
6655 static gint compose_exec_ext_editor_real(const gchar *file)
6656 {
6657         gchar buf[1024];
6658         gchar *p;
6659         gchar **cmdline;
6660         pid_t pid;
6661
6662         g_return_val_if_fail(file != NULL, -1);
6663
6664         if ((pid = fork()) < 0) {
6665                 perror("fork");
6666                 return -1;
6667         }
6668
6669         if (pid != 0) return pid;
6670
6671         /* grandchild process */
6672
6673         if (setpgid(0, getppid()))
6674                 perror("setpgid");
6675
6676         if (prefs_common.ext_editor_cmd &&
6677             (p = strchr(prefs_common.ext_editor_cmd, '%')) &&
6678             *(p + 1) == 's' && !strchr(p + 2, '%')) {
6679                 g_snprintf(buf, sizeof(buf), prefs_common.ext_editor_cmd, file);
6680         } else {
6681                 if (prefs_common.ext_editor_cmd)
6682                         g_warning("External editor command line is invalid: '%s'\n",
6683                                   prefs_common.ext_editor_cmd);
6684                 g_snprintf(buf, sizeof(buf), DEFAULT_EDITOR_CMD, file);
6685         }
6686
6687         cmdline = strsplit_with_quote(buf, " ", 1024);
6688         execvp(cmdline[0], cmdline);
6689
6690         perror("execvp");
6691         g_strfreev(cmdline);
6692
6693         _exit(1);
6694 }
6695
6696 static gboolean compose_ext_editor_kill(Compose *compose)
6697 {
6698         pid_t pgid = compose->exteditor_pid * -1;
6699         gint ret;
6700
6701         ret = kill(pgid, 0);
6702
6703         if (ret == 0 || (ret == -1 && EPERM == errno)) {
6704                 AlertValue val;
6705                 gchar *msg;
6706
6707                 msg = g_strdup_printf
6708                         (_("The external editor is still working.\n"
6709                            "Force terminating the process?\n"
6710                            "process group id: %d"), -pgid);
6711                 val = alertpanel_full(_("Notice"), msg, GTK_STOCK_NO, GTK_STOCK_YES,
6712                                       NULL, FALSE, NULL, ALERT_WARNING, G_ALERTDEFAULT);
6713                         
6714                 g_free(msg);
6715
6716                 if (val == G_ALERTALTERNATE) {
6717                         g_source_remove(compose->exteditor_tag);
6718                         g_io_channel_shutdown(compose->exteditor_ch,
6719                                               FALSE, NULL);
6720                         g_io_channel_unref(compose->exteditor_ch);
6721
6722                         if (kill(pgid, SIGTERM) < 0) perror("kill");
6723                         waitpid(compose->exteditor_pid, NULL, 0);
6724
6725                         g_warning("Terminated process group id: %d", -pgid);
6726                         g_warning("Temporary file: %s",
6727                                   compose->exteditor_file);
6728
6729                         compose_set_ext_editor_sensitive(compose, TRUE);
6730
6731                         g_free(compose->exteditor_file);
6732                         compose->exteditor_file    = NULL;
6733                         compose->exteditor_pid     = -1;
6734                         compose->exteditor_ch      = NULL;
6735                         compose->exteditor_tag     = -1;
6736                 } else
6737                         return FALSE;
6738         }
6739
6740         return TRUE;
6741 }
6742
6743 static gboolean compose_input_cb(GIOChannel *source, GIOCondition condition,
6744                                  gpointer data)
6745 {
6746         gchar buf[3] = "3";
6747         Compose *compose = (Compose *)data;
6748         gsize bytes_read;
6749
6750         debug_print(_("Compose: input from monitoring process\n"));
6751
6752         g_io_channel_read_chars(source, buf, sizeof(buf), &bytes_read, NULL);
6753
6754         g_io_channel_shutdown(source, FALSE, NULL);
6755         g_io_channel_unref(source);
6756
6757         waitpid(compose->exteditor_pid, NULL, 0);
6758
6759         if (buf[0] == '0') {            /* success */
6760                 GtkTextView *text = GTK_TEXT_VIEW(compose->text);
6761                 GtkTextBuffer *buffer = gtk_text_view_get_buffer(text);
6762
6763                 gtk_text_buffer_set_text(buffer, "", -1);
6764                 compose_insert_file(compose, compose->exteditor_file);
6765                 compose_changed_cb(NULL, compose);
6766
6767                 if (g_unlink(compose->exteditor_file) < 0)
6768                         FILE_OP_ERROR(compose->exteditor_file, "unlink");
6769         } else if (buf[0] == '1') {     /* failed */
6770                 g_warning("Couldn't exec external editor\n");
6771                 if (g_unlink(compose->exteditor_file) < 0)
6772                         FILE_OP_ERROR(compose->exteditor_file, "unlink");
6773         } else if (buf[0] == '2') {
6774                 g_warning("Couldn't write to file\n");
6775         } else if (buf[0] == '3') {
6776                 g_warning("Pipe read failed\n");
6777         }
6778
6779         compose_set_ext_editor_sensitive(compose, TRUE);
6780
6781         g_free(compose->exteditor_file);
6782         compose->exteditor_file    = NULL;
6783         compose->exteditor_pid     = -1;
6784         compose->exteditor_ch      = NULL;
6785         compose->exteditor_tag     = -1;
6786
6787         return FALSE;
6788 }
6789
6790 static void compose_set_ext_editor_sensitive(Compose *compose,
6791                                              gboolean sensitive)
6792 {
6793         GtkItemFactory *ifactory;
6794
6795         ifactory = gtk_item_factory_from_widget(compose->menubar);
6796
6797         menu_set_sensitive(ifactory, "/Message/Send", sensitive);
6798         menu_set_sensitive(ifactory, "/Message/Send later", sensitive);
6799         menu_set_sensitive(ifactory, "/Message/Insert file", sensitive);
6800         menu_set_sensitive(ifactory, "/Message/Insert signature", sensitive);
6801         menu_set_sensitive(ifactory, "/Edit/Wrap current paragraph", sensitive);
6802         menu_set_sensitive(ifactory, "/Edit/Wrap all long lines", sensitive);
6803         menu_set_sensitive(ifactory, "/Edit/Edit with external editor",
6804                            sensitive);
6805
6806         gtk_widget_set_sensitive(compose->text,                   sensitive);
6807         gtk_widget_set_sensitive(compose->toolbar->send_btn,      sensitive);
6808         gtk_widget_set_sensitive(compose->toolbar->sendl_btn,     sensitive);
6809         gtk_widget_set_sensitive(compose->toolbar->draft_btn,     sensitive);
6810         gtk_widget_set_sensitive(compose->toolbar->insert_btn,    sensitive);
6811         gtk_widget_set_sensitive(compose->toolbar->sig_btn,       sensitive);
6812         gtk_widget_set_sensitive(compose->toolbar->exteditor_btn, sensitive);
6813         gtk_widget_set_sensitive(compose->toolbar->linewrap_current_btn,  sensitive);
6814         gtk_widget_set_sensitive(compose->toolbar->linewrap_all_btn,  sensitive);
6815 }
6816 #endif /* G_OS_UNIX */
6817
6818 /**
6819  * compose_undo_state_changed:
6820  *
6821  * Change the sensivity of the menuentries undo and redo
6822  **/
6823 static void compose_undo_state_changed(UndoMain *undostruct, gint undo_state,
6824                                        gint redo_state, gpointer data)
6825 {
6826         GtkWidget *widget = GTK_WIDGET(data);
6827         GtkItemFactory *ifactory;
6828
6829         g_return_if_fail(widget != NULL);
6830
6831         ifactory = gtk_item_factory_from_widget(widget);
6832
6833         switch (undo_state) {
6834         case UNDO_STATE_TRUE:
6835                 if (!undostruct->undo_state) {
6836                         undostruct->undo_state = TRUE;
6837                         menu_set_sensitive(ifactory, "/Edit/Undo", TRUE);
6838                 }
6839                 break;
6840         case UNDO_STATE_FALSE:
6841                 if (undostruct->undo_state) {
6842                         undostruct->undo_state = FALSE;
6843                         menu_set_sensitive(ifactory, "/Edit/Undo", FALSE);
6844                 }
6845                 break;
6846         case UNDO_STATE_UNCHANGED:
6847                 break;
6848         case UNDO_STATE_REFRESH:
6849                 menu_set_sensitive(ifactory, "/Edit/Undo",
6850                                    undostruct->undo_state);
6851                 break;
6852         default:
6853                 g_warning("Undo state not recognized");
6854                 break;
6855         }
6856
6857         switch (redo_state) {
6858         case UNDO_STATE_TRUE:
6859                 if (!undostruct->redo_state) {
6860                         undostruct->redo_state = TRUE;
6861                         menu_set_sensitive(ifactory, "/Edit/Redo", TRUE);
6862                 }
6863                 break;
6864         case UNDO_STATE_FALSE:
6865                 if (undostruct->redo_state) {
6866                         undostruct->redo_state = FALSE;
6867                         menu_set_sensitive(ifactory, "/Edit/Redo", FALSE);
6868                 }
6869                 break;
6870         case UNDO_STATE_UNCHANGED:
6871                 break;
6872         case UNDO_STATE_REFRESH:
6873                 menu_set_sensitive(ifactory, "/Edit/Redo",
6874                                    undostruct->redo_state);
6875                 break;
6876         default:
6877                 g_warning("Redo state not recognized");
6878                 break;
6879         }
6880 }
6881
6882 /* callback functions */
6883
6884 /* compose_edit_size_alloc() - called when resized. don't know whether Gtk
6885  * includes "non-client" (windows-izm) in calculation, so this calculation
6886  * may not be accurate.
6887  */
6888 static gboolean compose_edit_size_alloc(GtkEditable *widget,
6889                                         GtkAllocation *allocation,
6890                                         GtkSHRuler *shruler)
6891 {
6892         if (prefs_common.show_ruler) {
6893                 gint char_width = 0, char_height = 0;
6894                 gint line_width_in_chars;
6895
6896                 gtkut_get_font_size(GTK_WIDGET(widget),
6897                                     &char_width, &char_height);
6898                 line_width_in_chars =
6899                         (allocation->width - allocation->x) / char_width;
6900
6901                 /* got the maximum */
6902                 gtk_ruler_set_range(GTK_RULER(shruler),
6903                                     0.0, line_width_in_chars, 0,
6904                                     /*line_width_in_chars*/ char_width);
6905         }
6906
6907         return TRUE;
6908 }
6909
6910 static void account_activated(GtkMenuItem *menuitem, gpointer data)
6911 {
6912         Compose *compose = (Compose *)data;
6913
6914         PrefsAccount *ac;
6915         gchar *folderidentifier;
6916
6917         ac = account_find_from_id(
6918                 GPOINTER_TO_INT(g_object_get_data(G_OBJECT(menuitem), MENU_VAL_ID)));
6919         g_return_if_fail(ac != NULL);
6920
6921         if (ac != compose->account)
6922                 compose_select_account(compose, ac, FALSE);
6923
6924         /* Set message save folder */
6925         if (account_get_special_folder(compose->account, F_OUTBOX)) {
6926                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), prefs_common.savemsg);
6927         }
6928         g_signal_connect(G_OBJECT(compose->savemsg_checkbtn), "toggled",
6929                          G_CALLBACK(compose_savemsg_checkbtn_cb), compose);
6930                            
6931         gtk_editable_delete_text(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
6932         if (account_get_special_folder(compose->account, F_OUTBOX)) {
6933                 folderidentifier = folder_item_get_identifier(account_get_special_folder
6934                                   (compose->account, F_OUTBOX));
6935                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
6936                 g_free(folderidentifier);
6937         }
6938 }
6939
6940 static void attach_selected(GtkTreeView *tree_view, GtkTreePath *tree_path,
6941                             GtkTreeViewColumn *column, Compose *compose)
6942 {
6943         compose_attach_property(compose);
6944 }
6945
6946 static gboolean attach_button_pressed(GtkWidget *widget, GdkEventButton *event,
6947                                       gpointer data)
6948 {
6949         Compose *compose = (Compose *)data;
6950         GtkTreeSelection *attach_selection;
6951         gint attach_nr_selected;
6952         GtkItemFactory *ifactory;
6953         
6954         if (!event) return FALSE;
6955
6956         if (event->button == 3) {
6957                 attach_selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(widget));
6958                 attach_nr_selected = gtk_tree_selection_count_selected_rows(attach_selection);
6959                 ifactory = gtk_item_factory_from_widget(compose->popupmenu);
6960                         
6961                 if (attach_nr_selected > 0)
6962                 {
6963                         menu_set_sensitive(ifactory, "/Remove", TRUE);
6964                         menu_set_sensitive(ifactory, "/Properties...", TRUE);
6965                 } else {
6966                         menu_set_sensitive(ifactory, "/Remove", FALSE);
6967                         menu_set_sensitive(ifactory, "/Properties...", FALSE);
6968                 }
6969                         
6970                 gtk_menu_popup(GTK_MENU(compose->popupmenu), NULL, NULL,
6971                                NULL, NULL, event->button, event->time);
6972                 return TRUE;                           
6973         }
6974
6975         return FALSE;
6976 }
6977
6978 static gboolean attach_key_pressed(GtkWidget *widget, GdkEventKey *event,
6979                                    gpointer data)
6980 {
6981         Compose *compose = (Compose *)data;
6982
6983         if (!event) return FALSE;
6984
6985         switch (event->keyval) {
6986         case GDK_Delete:
6987                 compose_attach_remove_selected(compose);
6988                 break;
6989         }
6990         return FALSE;
6991 }
6992
6993 static void compose_allow_user_actions (Compose *compose, gboolean allow)
6994 {
6995         GtkItemFactory *ifactory = gtk_item_factory_from_widget(compose->menubar);
6996         toolbar_comp_set_sensitive(compose, allow);
6997         menu_set_sensitive(ifactory, "/Message", allow);
6998         menu_set_sensitive(ifactory, "/Edit", allow);
6999 #if USE_ASPELL
7000         menu_set_sensitive(ifactory, "/Spelling", allow);
7001 #endif  
7002         menu_set_sensitive(ifactory, "/Options", allow);
7003         menu_set_sensitive(ifactory, "/Tools", allow);
7004         menu_set_sensitive(ifactory, "/Help", allow);
7005         
7006         gtk_text_view_set_editable(GTK_TEXT_VIEW(compose->text), allow);
7007
7008 }
7009
7010 static void compose_send_cb(gpointer data, guint action, GtkWidget *widget)
7011 {
7012         Compose *compose = (Compose *)data;
7013         
7014         if (prefs_common.work_offline && !inc_offline_should_override())
7015                 return;
7016         
7017         if (compose->draft_timeout_tag != -1) { /* CLAWS: disable draft timeout */
7018                 gtk_timeout_remove(compose->draft_timeout_tag);
7019                 compose->draft_timeout_tag = -1;
7020         }
7021
7022         compose_send(compose);
7023 }
7024
7025 static void compose_send_later_cb(gpointer data, guint action,
7026                                   GtkWidget *widget)
7027 {
7028         Compose *compose = (Compose *)data;
7029         gint val;
7030
7031         val = compose_queue_sub(compose, NULL, NULL, TRUE);
7032         if (!val) 
7033                 compose_close(compose);
7034         else if (val == -2) {
7035                 alertpanel_error(_("Could not queue message:\n\n%s."), strerror(errno));
7036         }
7037 }
7038
7039 void compose_draft (gpointer data) 
7040 {
7041         compose_draft_cb(data, COMPOSE_QUIT_EDITING, NULL);     
7042 }
7043
7044 static void compose_draft_cb(gpointer data, guint action, GtkWidget *widget)
7045 {
7046         Compose *compose = (Compose *)data;
7047         FolderItem *draft;
7048         gchar *tmp;
7049         gint msgnum;
7050         MsgFlags flag = {0, 0};
7051         static gboolean lock = FALSE;
7052         MsgInfo *newmsginfo;
7053         FILE *fp;
7054         gboolean target_locked = FALSE;
7055         
7056         if (lock) return;
7057
7058         draft = account_get_special_folder(compose->account, F_DRAFT);
7059         g_return_if_fail(draft != NULL);
7060         
7061         if (!g_mutex_trylock(compose->mutex)) {
7062                 /* we don't want to lock the mutex once it's available,
7063                  * because as the only other part of compose.c locking
7064                  * it is compose_close - which means once unlocked,
7065                  * the compose struct will be freed */
7066                 debug_print("couldn't lock mutex, probably sending\n");
7067                 return;
7068         }
7069         
7070         lock = TRUE;
7071
7072         tmp = g_strdup_printf("%s%cdraft.%p", get_tmp_dir(),
7073                               G_DIR_SEPARATOR, compose);
7074         if ((fp = g_fopen(tmp, "wb")) == NULL) {
7075                 FILE_OP_ERROR(tmp, "fopen");
7076                 goto unlock;
7077         }
7078
7079         /* chmod for security */
7080         if (change_file_mode_rw(fp, tmp) < 0) {
7081                 FILE_OP_ERROR(tmp, "chmod");
7082                 g_warning("can't change file mode\n");
7083         }
7084
7085         /* Save draft infos */
7086         fprintf(fp, "X-Sylpheed-Account-Id:%d\n", compose->account->account_id);
7087         fprintf(fp, "S:%s\n", compose->account->address);
7088         if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn))) {
7089                 gchar *savefolderid;
7090
7091                 savefolderid = gtk_editable_get_chars(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
7092                 fprintf(fp, "SCF:%s\n", savefolderid);
7093                 g_free(savefolderid);
7094         }
7095         if (compose->return_receipt) {
7096                 fprintf(fp, "RRCPT:1\n");
7097         }
7098         if (compose->privacy_system) {
7099                 fprintf(fp, "X-Sylpheed-Sign:%d\n", compose->use_signing);
7100                 fprintf(fp, "X-Sylpheed-Encrypt:%d\n", compose->use_encryption);
7101                 fprintf(fp, "X-Sylpheed-Privacy-System:%s\n", compose->privacy_system);
7102         }
7103         fprintf(fp, "\n");
7104
7105         if (compose_write_to_file(compose, fp, COMPOSE_WRITE_FOR_STORE) < 0) {
7106                 fclose(fp);
7107                 g_unlink(tmp);
7108                 g_free(tmp);
7109                 goto unlock;
7110         }
7111         fclose(fp);
7112         
7113         if (compose->targetinfo) {
7114                 target_locked = MSG_IS_LOCKED(compose->targetinfo->flags);
7115                 flag.perm_flags = target_locked?MSG_LOCKED:0;
7116         }
7117         flag.tmp_flags = MSG_DRAFT;
7118
7119         folder_item_scan(draft);
7120         if ((msgnum = folder_item_add_msg(draft, tmp, &flag, TRUE)) < 0) {
7121                 g_unlink(tmp);
7122                 g_free(tmp);
7123                 if (action != COMPOSE_AUTO_SAVE)
7124                         alertpanel_error(_("Could not save draft."));
7125                 goto unlock;
7126         }
7127         g_free(tmp);
7128         draft->mtime = 0;       /* force updating */
7129
7130         if (compose->mode == COMPOSE_REEDIT) {
7131                 compose_remove_reedit_target(compose, TRUE);
7132         }
7133
7134         newmsginfo = folder_item_get_msginfo(draft, msgnum);
7135         if (newmsginfo) {
7136                 procmsg_msginfo_unset_flags(newmsginfo, ~0, ~0);
7137                 if (target_locked)
7138                         procmsg_msginfo_set_flags(newmsginfo, MSG_LOCKED, MSG_DRAFT);
7139                 else
7140                         procmsg_msginfo_set_flags(newmsginfo, 0, MSG_DRAFT);
7141                 if (compose_use_attach(compose))
7142                         procmsg_msginfo_set_flags(newmsginfo, 0,
7143                                                   MSG_HAS_ATTACHMENT);
7144
7145                 procmsg_msginfo_free(newmsginfo);
7146         }
7147         
7148         folder_item_scan(draft);
7149         
7150         if (action == COMPOSE_QUIT_EDITING) {
7151                 lock = FALSE;
7152                 g_mutex_unlock(compose->mutex); /* must be done before closing */
7153                 compose_close(compose);
7154                 return;
7155         } else {
7156                 struct stat s;
7157                 gchar *path;
7158
7159                 path = folder_item_fetch_msg(draft, msgnum);
7160                 if (path == NULL) {
7161                         debug_print("can't fetch %s:%d\n",draft->path, msgnum);
7162                         goto unlock;
7163                 }
7164                 if (g_stat(path, &s) < 0) {
7165                         FILE_OP_ERROR(path, "stat");
7166                         g_free(path);
7167                         goto unlock;
7168                 }
7169                 g_free(path);
7170
7171                 procmsg_msginfo_free(compose->targetinfo);
7172                 compose->targetinfo = procmsg_msginfo_new();
7173                 compose->targetinfo->msgnum = msgnum;
7174                 compose->targetinfo->size = s.st_size;
7175                 compose->targetinfo->mtime = s.st_mtime;
7176                 compose->targetinfo->folder = draft;
7177                 if (target_locked)
7178                         procmsg_msginfo_set_flags(compose->targetinfo, MSG_LOCKED, 0);
7179                 compose->mode = COMPOSE_REEDIT;
7180                 
7181                 if (action == COMPOSE_AUTO_SAVE) {
7182                         compose->autosaved_draft = compose->targetinfo;
7183                 }
7184                 compose->modified = FALSE;
7185                 compose_set_title(compose);
7186         }
7187 unlock:
7188         lock = FALSE;
7189         g_mutex_unlock(compose->mutex);
7190 }
7191
7192 static void compose_attach_cb(gpointer data, guint action, GtkWidget *widget)
7193 {
7194         Compose *compose = (Compose *)data;
7195         GList *file_list;
7196
7197         if (compose->redirect_filename != NULL)
7198                 return;
7199
7200         file_list = filesel_select_multiple_files_open(_("Select file"));
7201
7202         if (file_list) {
7203                 GList *tmp;
7204
7205                 for ( tmp = file_list; tmp; tmp = tmp->next) {
7206                         gchar *file = (gchar *) tmp->data;
7207                         gchar *utf8_filename = conv_filename_to_utf8(file);
7208                         compose_attach_append(compose, file, utf8_filename, NULL);
7209                         compose_changed_cb(NULL, compose);
7210                         g_free(file);
7211                         g_free(utf8_filename);
7212                 }
7213                 g_list_free(file_list);
7214         }               
7215 }
7216
7217 static void compose_insert_file_cb(gpointer data, guint action,
7218                                    GtkWidget *widget)
7219 {
7220         Compose *compose = (Compose *)data;
7221         GList *file_list;
7222
7223         file_list = filesel_select_multiple_files_open(_("Select file"));
7224
7225         if (file_list) {
7226                 GList *tmp;
7227
7228                 for ( tmp = file_list; tmp; tmp = tmp->next) {
7229                         gchar *file = (gchar *) tmp->data;
7230                         gchar *filedup = g_strdup(file);
7231                         gchar *shortfile = g_path_get_basename(filedup);
7232                         ComposeInsertResult res;
7233
7234                         res = compose_insert_file(compose, file);
7235                         if (res == COMPOSE_INSERT_READ_ERROR) {
7236                                 alertpanel_error(_("File '%s' could not be read."), shortfile);
7237                         } else if (res == COMPOSE_INSERT_INVALID_CHARACTER) {
7238                                 alertpanel_error(_("File '%s' contained invalid characters\n"
7239                                                    "for the current encoding, insertion may be incorrect."), shortfile);
7240                         }
7241                         g_free(shortfile);
7242                         g_free(filedup);
7243                         g_free(file);
7244                 }
7245                 g_list_free(file_list);
7246         }
7247 }
7248
7249 static void compose_insert_sig_cb(gpointer data, guint action,
7250                                   GtkWidget *widget)
7251 {
7252         Compose *compose = (Compose *)data;
7253
7254         compose_insert_sig(compose, FALSE);
7255 }
7256
7257 static gint compose_delete_cb(GtkWidget *widget, GdkEventAny *event,
7258                               gpointer data)
7259 {
7260         gint x, y;
7261         Compose *compose = (Compose *)data;
7262
7263         gtkut_widget_get_uposition(widget, &x, &y);
7264         prefs_common.compose_x = x;
7265         prefs_common.compose_y = y;
7266
7267         if (compose->sending)
7268                 return TRUE;
7269         compose_close_cb(compose, 0, NULL);
7270         return TRUE;
7271 }
7272
7273 static void compose_close_cb(gpointer data, guint action, GtkWidget *widget)
7274 {
7275         Compose *compose = (Compose *)data;
7276         AlertValue val;
7277
7278 #ifdef G_OS_UNIX
7279         if (compose->exteditor_tag != -1) {
7280                 if (!compose_ext_editor_kill(compose))
7281                         return;
7282         }
7283 #endif
7284
7285         if (compose->modified) {
7286                 val = alertpanel(_("Discard message"),
7287                                  _("This message has been modified. Discard it?"),
7288                                  _("_Discard"), _("_Save to Drafts"), GTK_STOCK_CANCEL);
7289
7290                 switch (val) {
7291                 case G_ALERTDEFAULT:
7292                         if (prefs_common.autosave)
7293                                 compose_remove_draft(compose);                  
7294                         break;
7295                 case G_ALERTALTERNATE:
7296                         compose_draft_cb(data, COMPOSE_QUIT_EDITING, NULL);
7297                         return;
7298                 default:
7299                         return;
7300                 }
7301         }
7302
7303         compose_close(compose);
7304 }
7305
7306 static void compose_set_encoding_cb(gpointer data, guint action,
7307                                     GtkWidget *widget)
7308 {
7309         Compose *compose = (Compose *)data;
7310
7311         if (GTK_CHECK_MENU_ITEM(widget)->active)
7312                 compose->out_encoding = (CharSet)action;
7313 }
7314
7315 static void compose_address_cb(gpointer data, guint action, GtkWidget *widget)
7316 {
7317         Compose *compose = (Compose *)data;
7318
7319         addressbook_open(compose);
7320 }
7321
7322 static void compose_template_activate_cb(GtkWidget *widget, gpointer data)
7323 {
7324         Compose *compose = (Compose *)data;
7325         Template *tmpl;
7326         gchar *msg;
7327         AlertValue val;
7328
7329         tmpl = g_object_get_data(G_OBJECT(widget), "template");
7330         g_return_if_fail(tmpl != NULL);
7331
7332         msg = g_strdup_printf(_("Do you want to apply the template '%s' ?"),
7333                               tmpl->name);
7334         val = alertpanel(_("Apply template"), msg,
7335                          _("_Replace"), _("_Insert"), GTK_STOCK_CANCEL);
7336         g_free(msg);
7337
7338         if (val == G_ALERTDEFAULT)
7339                 compose_template_apply(compose, tmpl, TRUE);
7340         else if (val == G_ALERTALTERNATE)
7341                 compose_template_apply(compose, tmpl, FALSE);
7342 }
7343
7344 static void compose_ext_editor_cb(gpointer data, guint action,
7345                                   GtkWidget *widget)
7346 {
7347         Compose *compose = (Compose *)data;
7348
7349         compose_exec_ext_editor(compose);
7350 }
7351
7352 static void compose_undo_cb(Compose *compose)
7353 {
7354         gboolean prev_autowrap = compose->autowrap;
7355
7356         compose->autowrap = FALSE;
7357         undo_undo(compose->undostruct);
7358         compose->autowrap = prev_autowrap;
7359 }
7360
7361 static void compose_redo_cb(Compose *compose)
7362 {
7363         gboolean prev_autowrap = compose->autowrap;
7364         
7365         compose->autowrap = FALSE;
7366         undo_redo(compose->undostruct);
7367         compose->autowrap = prev_autowrap;
7368 }
7369
7370 static void entry_cut_clipboard(GtkWidget *entry)
7371 {
7372         if (GTK_IS_EDITABLE(entry))
7373                 gtk_editable_cut_clipboard (GTK_EDITABLE(entry));
7374         else if (GTK_IS_TEXT_VIEW(entry))
7375                 gtk_text_buffer_cut_clipboard(
7376                         gtk_text_view_get_buffer(GTK_TEXT_VIEW(entry)),
7377                         gtk_clipboard_get(GDK_SELECTION_CLIPBOARD),
7378                         TRUE);
7379 }
7380
7381 static void entry_copy_clipboard(GtkWidget *entry)
7382 {
7383         if (GTK_IS_EDITABLE(entry))
7384                 gtk_editable_copy_clipboard (GTK_EDITABLE(entry));
7385         else if (GTK_IS_TEXT_VIEW(entry))
7386                 gtk_text_buffer_copy_clipboard(
7387                         gtk_text_view_get_buffer(GTK_TEXT_VIEW(entry)),
7388                         gtk_clipboard_get(GDK_SELECTION_CLIPBOARD));
7389 }
7390
7391 static void entry_paste_clipboard(Compose *compose, GtkWidget *entry, 
7392                                   gboolean wrap, GdkAtom clip)
7393 {
7394         if (GTK_IS_TEXT_VIEW(entry)) {
7395                 GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(entry));
7396                 GtkTextMark *mark_start = gtk_text_buffer_get_insert(buffer);
7397                 GtkTextIter start_iter, end_iter;
7398                 gint start, end;
7399                 
7400                 gchar *contents = gtk_clipboard_wait_for_text(gtk_clipboard_get(clip));
7401
7402                 if (contents == NULL)
7403                         return;
7404
7405                 gtk_text_buffer_delete_selection(buffer, FALSE, TRUE);
7406                 gtk_text_buffer_get_iter_at_mark(buffer, &start_iter, mark_start);
7407                 
7408                 start = gtk_text_iter_get_offset(&start_iter);
7409
7410                 gtk_text_buffer_insert(buffer, &start_iter, contents, strlen(contents));
7411                 
7412                 if (!wrap) {
7413                         end = start + strlen(contents);
7414                         gtk_text_buffer_get_iter_at_offset(buffer, &start_iter, start);
7415                         gtk_text_buffer_get_iter_at_offset(buffer, &end_iter, end);
7416                         gtk_text_buffer_apply_tag_by_name(buffer, "no_wrap", &start_iter, &end_iter);
7417                 } else if (wrap && clip == GDK_SELECTION_PRIMARY) {
7418                         mark_start = gtk_text_buffer_get_insert(buffer);
7419                         gtk_text_buffer_get_iter_at_mark(buffer, &start_iter, mark_start);
7420                         gtk_text_iter_backward_char(&start_iter);
7421                         compose_beautify_paragraph(compose, &start_iter, TRUE);
7422                 }
7423                 
7424         } else if (GTK_IS_EDITABLE(entry))
7425                 gtk_editable_paste_clipboard (GTK_EDITABLE(entry));
7426         
7427 }
7428
7429 static void entry_allsel(GtkWidget *entry)
7430 {
7431         if (GTK_IS_EDITABLE(entry))
7432                 gtk_editable_select_region(GTK_EDITABLE(entry), 0, -1);
7433         else if (GTK_IS_TEXT_VIEW(entry)) {
7434                 GtkTextIter startiter, enditer;
7435                 GtkTextBuffer *textbuf;
7436
7437                 textbuf = gtk_text_view_get_buffer(GTK_TEXT_VIEW(entry));
7438                 gtk_text_buffer_get_start_iter(textbuf, &startiter);
7439                 gtk_text_buffer_get_end_iter(textbuf, &enditer);
7440
7441                 gtk_text_buffer_move_mark_by_name(textbuf, 
7442                         "selection_bound", &startiter);
7443                 gtk_text_buffer_move_mark_by_name(textbuf, 
7444                         "insert", &enditer);
7445         }
7446 }
7447
7448 static void compose_cut_cb(Compose *compose)
7449 {
7450         if (compose->focused_editable &&
7451             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
7452                 entry_cut_clipboard(compose->focused_editable);
7453 }
7454
7455 static void compose_copy_cb(Compose *compose)
7456 {
7457         if (compose->focused_editable &&
7458             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
7459                 entry_copy_clipboard(compose->focused_editable);
7460 }
7461
7462 static void compose_paste_cb(Compose *compose)
7463 {
7464         gint prev_autowrap;
7465         GtkTextBuffer *buffer;
7466         BLOCK_WRAP();
7467         if (compose->focused_editable &&
7468             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
7469                 entry_paste_clipboard(compose, compose->focused_editable, 
7470                                 prefs_common.linewrap_pastes,
7471                                 GDK_SELECTION_CLIPBOARD);
7472         UNBLOCK_WRAP();
7473 }
7474
7475 static void compose_paste_as_quote_cb(Compose *compose)
7476 {
7477         gint wrap_quote = prefs_common.linewrap_quote;
7478         if (compose->focused_editable &&
7479             GTK_WIDGET_HAS_FOCUS(compose->focused_editable)) {
7480                 /* let text_insert() (called directly or at a later time
7481                  * after the gtk_editable_paste_clipboard) know that 
7482                  * text is to be inserted as a quotation. implemented
7483                  * by using a simple refcount... */
7484                 gint paste_as_quotation = GPOINTER_TO_INT(g_object_get_data(
7485                                                 G_OBJECT(compose->focused_editable),
7486                                                 "paste_as_quotation"));
7487                 g_object_set_data(G_OBJECT(compose->focused_editable),
7488                                     "paste_as_quotation",
7489                                     GINT_TO_POINTER(paste_as_quotation + 1));
7490                 prefs_common.linewrap_quote = prefs_common.linewrap_pastes;
7491                 entry_paste_clipboard(compose, compose->focused_editable, 
7492                                 prefs_common.linewrap_pastes,
7493                                 GDK_SELECTION_CLIPBOARD);
7494                 prefs_common.linewrap_quote = wrap_quote;
7495         }
7496 }
7497
7498 static void compose_paste_no_wrap_cb(Compose *compose)
7499 {
7500         gint prev_autowrap;
7501         GtkTextBuffer *buffer;
7502         BLOCK_WRAP();
7503         if (compose->focused_editable &&
7504             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
7505                 entry_paste_clipboard(compose, compose->focused_editable, FALSE,
7506                         GDK_SELECTION_CLIPBOARD);
7507         UNBLOCK_WRAP();
7508 }
7509
7510 static void compose_paste_wrap_cb(Compose *compose)
7511 {
7512         gint prev_autowrap;
7513         GtkTextBuffer *buffer;
7514         BLOCK_WRAP();
7515         if (compose->focused_editable &&
7516             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
7517                 entry_paste_clipboard(compose, compose->focused_editable, TRUE,
7518                         GDK_SELECTION_CLIPBOARD);
7519         UNBLOCK_WRAP();
7520 }
7521
7522 static void compose_allsel_cb(Compose *compose)
7523 {
7524         if (compose->focused_editable &&
7525             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
7526                 entry_allsel(compose->focused_editable);
7527 }
7528
7529 static void textview_move_beginning_of_line (GtkTextView *text)
7530 {
7531         GtkTextBuffer *buffer;
7532         GtkTextMark *mark;
7533         GtkTextIter ins;
7534
7535         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7536
7537         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7538         mark = gtk_text_buffer_get_insert(buffer);
7539         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7540         gtk_text_iter_set_line_offset(&ins, 0);
7541         gtk_text_buffer_place_cursor(buffer, &ins);
7542 }
7543
7544 static void textview_move_forward_character (GtkTextView *text)
7545 {
7546         GtkTextBuffer *buffer;
7547         GtkTextMark *mark;
7548         GtkTextIter ins;
7549
7550         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7551
7552         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7553         mark = gtk_text_buffer_get_insert(buffer);
7554         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7555         if (gtk_text_iter_forward_cursor_position(&ins))
7556                 gtk_text_buffer_place_cursor(buffer, &ins);
7557 }
7558
7559 static void textview_move_backward_character (GtkTextView *text)
7560 {
7561         GtkTextBuffer *buffer;
7562         GtkTextMark *mark;
7563         GtkTextIter ins;
7564
7565         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7566
7567         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7568         mark = gtk_text_buffer_get_insert(buffer);
7569         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7570         if (gtk_text_iter_backward_cursor_position(&ins))
7571                 gtk_text_buffer_place_cursor(buffer, &ins);
7572 }
7573
7574 static void textview_move_forward_word (GtkTextView *text)
7575 {
7576         GtkTextBuffer *buffer;
7577         GtkTextMark *mark;
7578         GtkTextIter ins;
7579         gint count;
7580
7581         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7582
7583         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7584         mark = gtk_text_buffer_get_insert(buffer);
7585         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7586         count = gtk_text_iter_inside_word (&ins) ? 2 : 1;
7587         if (gtk_text_iter_forward_word_ends(&ins, count)) {
7588                 gtk_text_iter_backward_word_start(&ins);
7589                 gtk_text_buffer_place_cursor(buffer, &ins);
7590         }
7591 }
7592
7593 static void textview_move_backward_word (GtkTextView *text)
7594 {
7595         GtkTextBuffer *buffer;
7596         GtkTextMark *mark;
7597         GtkTextIter ins;
7598         gint count;
7599
7600         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7601
7602         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7603         mark = gtk_text_buffer_get_insert(buffer);
7604         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7605         count = gtk_text_iter_inside_word (&ins) ? 2 : 1;
7606         if (gtk_text_iter_backward_word_starts(&ins, 1))
7607                 gtk_text_buffer_place_cursor(buffer, &ins);
7608 }
7609
7610 static void textview_move_end_of_line (GtkTextView *text)
7611 {
7612         GtkTextBuffer *buffer;
7613         GtkTextMark *mark;
7614         GtkTextIter ins;
7615
7616         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7617
7618         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7619         mark = gtk_text_buffer_get_insert(buffer);
7620         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7621         if (gtk_text_iter_forward_to_line_end(&ins))
7622                 gtk_text_buffer_place_cursor(buffer, &ins);
7623 }
7624
7625 static void textview_move_next_line (GtkTextView *text)
7626 {
7627         GtkTextBuffer *buffer;
7628         GtkTextMark *mark;
7629         GtkTextIter ins;
7630         gint offset;
7631
7632         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7633
7634         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7635         mark = gtk_text_buffer_get_insert(buffer);
7636         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7637         offset = gtk_text_iter_get_line_offset(&ins);
7638         if (gtk_text_iter_forward_line(&ins)) {
7639                 gtk_text_iter_set_line_offset(&ins, offset);
7640                 gtk_text_buffer_place_cursor(buffer, &ins);
7641         }
7642 }
7643
7644 static void textview_move_previous_line (GtkTextView *text)
7645 {
7646         GtkTextBuffer *buffer;
7647         GtkTextMark *mark;
7648         GtkTextIter ins;
7649         gint offset;
7650
7651         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7652
7653         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7654         mark = gtk_text_buffer_get_insert(buffer);
7655         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7656         offset = gtk_text_iter_get_line_offset(&ins);
7657         if (gtk_text_iter_backward_line(&ins)) {
7658                 gtk_text_iter_set_line_offset(&ins, offset);
7659                 gtk_text_buffer_place_cursor(buffer, &ins);
7660         }
7661 }
7662
7663 static void textview_delete_forward_character (GtkTextView *text)
7664 {
7665         GtkTextBuffer *buffer;
7666         GtkTextMark *mark;
7667         GtkTextIter ins, end_iter;
7668
7669         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7670
7671         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7672         mark = gtk_text_buffer_get_insert(buffer);
7673         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7674         end_iter = ins;
7675         if (gtk_text_iter_forward_char(&end_iter)) {
7676                 gtk_text_buffer_delete(buffer, &ins, &end_iter);
7677         }
7678 }
7679
7680 static void textview_delete_backward_character (GtkTextView *text)
7681 {
7682         GtkTextBuffer *buffer;
7683         GtkTextMark *mark;
7684         GtkTextIter ins, end_iter;
7685
7686         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7687
7688         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7689         mark = gtk_text_buffer_get_insert(buffer);
7690         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7691         end_iter = ins;
7692         if (gtk_text_iter_backward_char(&end_iter)) {
7693                 gtk_text_buffer_delete(buffer, &end_iter, &ins);
7694         }
7695 }
7696
7697 static void textview_delete_forward_word (GtkTextView *text)
7698 {
7699         GtkTextBuffer *buffer;
7700         GtkTextMark *mark;
7701         GtkTextIter ins, end_iter;
7702
7703         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7704
7705         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7706         mark = gtk_text_buffer_get_insert(buffer);
7707         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7708         end_iter = ins;
7709         if (gtk_text_iter_forward_word_end(&end_iter)) {
7710                 gtk_text_buffer_delete(buffer, &ins, &end_iter);
7711         }
7712 }
7713
7714 static void textview_delete_backward_word (GtkTextView *text)
7715 {
7716         GtkTextBuffer *buffer;
7717         GtkTextMark *mark;
7718         GtkTextIter ins, end_iter;
7719
7720         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7721
7722         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7723         mark = gtk_text_buffer_get_insert(buffer);
7724         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7725         end_iter = ins;
7726         if (gtk_text_iter_backward_word_start(&end_iter)) {
7727                 gtk_text_buffer_delete(buffer, &end_iter, &ins);
7728         }
7729 }
7730
7731 static void textview_delete_line (GtkTextView *text)
7732 {
7733         GtkTextBuffer *buffer;
7734         GtkTextMark *mark;
7735         GtkTextIter ins, start_iter, end_iter;
7736         gboolean found;
7737
7738         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7739
7740         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7741         mark = gtk_text_buffer_get_insert(buffer);
7742         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7743
7744         start_iter = ins;
7745         gtk_text_iter_set_line_offset(&start_iter, 0);
7746
7747         end_iter = ins;
7748         if (gtk_text_iter_ends_line(&end_iter))
7749                 found = gtk_text_iter_forward_char(&end_iter);
7750         else
7751                 found = gtk_text_iter_forward_to_line_end(&end_iter);
7752
7753         if (found)
7754                 gtk_text_buffer_delete(buffer, &start_iter, &end_iter);
7755 }
7756
7757 static void textview_delete_to_line_end (GtkTextView *text)
7758 {
7759         GtkTextBuffer *buffer;
7760         GtkTextMark *mark;
7761         GtkTextIter ins, end_iter;
7762         gboolean found;
7763
7764         g_return_if_fail(GTK_IS_TEXT_VIEW(text));
7765
7766         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text));
7767         mark = gtk_text_buffer_get_insert(buffer);
7768         gtk_text_buffer_get_iter_at_mark(buffer, &ins, mark);
7769         end_iter = ins;
7770         if (gtk_text_iter_ends_line(&end_iter))
7771                 found = gtk_text_iter_forward_char(&end_iter);
7772         else
7773                 found = gtk_text_iter_forward_to_line_end(&end_iter);
7774         if (found)
7775                 gtk_text_buffer_delete(buffer, &ins, &end_iter);
7776 }
7777
7778 static void compose_advanced_action_cb(Compose *compose,
7779                                         ComposeCallAdvancedAction action)
7780 {
7781         GtkTextView *text = GTK_TEXT_VIEW(compose->text);
7782         static struct {
7783                 void (*do_action) (GtkTextView *text);
7784         } action_table[] = {
7785                 {textview_move_beginning_of_line},
7786                 {textview_move_forward_character},
7787                 {textview_move_backward_character},
7788                 {textview_move_forward_word},
7789                 {textview_move_backward_word},
7790                 {textview_move_end_of_line},
7791                 {textview_move_next_line},
7792                 {textview_move_previous_line},
7793                 {textview_delete_forward_character},
7794                 {textview_delete_backward_character},
7795                 {textview_delete_forward_word},
7796                 {textview_delete_backward_word},
7797                 {textview_delete_line},
7798                 {NULL}, /* gtk_stext_delete_line_n */
7799                 {textview_delete_to_line_end}
7800         };
7801
7802         if (!GTK_WIDGET_HAS_FOCUS(text)) return;
7803
7804         if (action >= COMPOSE_CALL_ADVANCED_ACTION_MOVE_BEGINNING_OF_LINE &&
7805             action <= COMPOSE_CALL_ADVANCED_ACTION_DELETE_TO_LINE_END) {
7806                 if (action_table[action].do_action)
7807                         action_table[action].do_action(text);
7808                 else
7809                         g_warning("Not implemented yet.");
7810         }
7811 }
7812
7813 static void compose_grab_focus_cb(GtkWidget *widget, Compose *compose)
7814 {
7815         gchar *str = NULL;
7816         
7817         if (GTK_IS_EDITABLE(widget)) {
7818                 str = gtk_editable_get_chars(GTK_EDITABLE(widget), 0, -1);
7819                 gtk_editable_set_position(GTK_EDITABLE(widget), 
7820                         strlen(str));
7821                 g_free(str);
7822                 if (widget->parent && widget->parent->parent
7823                  && widget->parent->parent->parent) {
7824                         if (GTK_IS_SCROLLED_WINDOW(widget->parent->parent->parent)) {
7825                                 gint y = widget->allocation.y;
7826                                 gint height = widget->allocation.height;
7827                                 GtkAdjustment *shown = gtk_scrolled_window_get_vadjustment
7828                                         (GTK_SCROLLED_WINDOW(widget->parent->parent->parent));
7829
7830                                 if (y < (int)shown->value) {
7831                                         gtk_adjustment_set_value(GTK_ADJUSTMENT(shown), y - 1);
7832                                 }
7833                                 if (y + height > (int)shown->value + (int)shown->page_size) {
7834                                         if (y - height - 1 < (int)shown->upper - (int)shown->page_size) {
7835                                                 gtk_adjustment_set_value(GTK_ADJUSTMENT(shown), 
7836                                                         y + height - (int)shown->page_size - 1);
7837                                         } else {
7838                                                 gtk_adjustment_set_value(GTK_ADJUSTMENT(shown), 
7839                                                         (int)shown->upper - (int)shown->page_size - 1);
7840                                         }
7841                                 }
7842                         }
7843                 }
7844         }
7845
7846         if (GTK_IS_EDITABLE(widget) || GTK_IS_TEXT_VIEW(widget))
7847                 compose->focused_editable = widget;
7848 }
7849
7850 static void compose_changed_cb(GtkTextBuffer *textbuf, Compose *compose)
7851 {
7852         compose->modified = TRUE;
7853         compose_set_title(compose);
7854 }
7855
7856 static void compose_wrap_cb(gpointer data, guint action, GtkWidget *widget)
7857 {
7858         Compose *compose = (Compose *)data;
7859
7860         if (action == 1)
7861                 compose_wrap_all_full(compose, TRUE);
7862         else
7863                 compose_beautify_paragraph(compose, NULL, TRUE);
7864 }
7865
7866 static void compose_toggle_autowrap_cb(gpointer data, guint action,
7867                                        GtkWidget *widget)
7868 {
7869         Compose *compose = (Compose *)data;
7870         compose->autowrap = GTK_CHECK_MENU_ITEM(widget)->active;
7871         if (compose->autowrap)
7872                 compose_wrap_all_full(compose, TRUE);
7873         compose->autowrap = GTK_CHECK_MENU_ITEM(widget)->active;
7874 }
7875
7876 static void compose_toggle_sign_cb(gpointer data, guint action,
7877                                    GtkWidget *widget)
7878 {
7879         Compose *compose = (Compose *)data;
7880
7881         if (GTK_CHECK_MENU_ITEM(widget)->active)
7882                 compose->use_signing = TRUE;
7883         else
7884                 compose->use_signing = FALSE;
7885 }
7886
7887 static void compose_toggle_encrypt_cb(gpointer data, guint action,
7888                                       GtkWidget *widget)
7889 {
7890         Compose *compose = (Compose *)data;
7891
7892         if (GTK_CHECK_MENU_ITEM(widget)->active)
7893                 compose->use_encryption = TRUE;
7894         else
7895                 compose->use_encryption = FALSE;
7896 }
7897
7898 static void activate_privacy_system(Compose *compose, PrefsAccount *account, gboolean warn) 
7899 {
7900         g_free(compose->privacy_system);
7901
7902         compose->privacy_system = g_strdup(account->default_privacy_system);
7903         compose_update_privacy_system_menu_item(compose, warn);
7904 }
7905
7906 static void compose_toggle_ruler_cb(gpointer data, guint action,
7907                                     GtkWidget *widget)
7908 {
7909         Compose *compose = (Compose *)data;
7910
7911         if (GTK_CHECK_MENU_ITEM(widget)->active) {
7912                 gtk_widget_show(compose->ruler_hbox);
7913                 prefs_common.show_ruler = TRUE;
7914         } else {
7915                 gtk_widget_hide(compose->ruler_hbox);
7916                 gtk_widget_queue_resize(compose->edit_vbox);
7917                 prefs_common.show_ruler = FALSE;
7918         }
7919 }
7920
7921 static void compose_attach_drag_received_cb (GtkWidget          *widget,
7922                                              GdkDragContext     *context,
7923                                              gint                x,
7924                                              gint                y,
7925                                              GtkSelectionData   *data,
7926                                              guint               info,
7927                                              guint               time,
7928                                              gpointer            user_data)
7929 {
7930         Compose *compose = (Compose *)user_data;
7931         GList *list, *tmp;
7932
7933         if (gdk_atom_name(data->type) && 
7934             !strcmp(gdk_atom_name(data->type), "text/uri-list")
7935             && gtk_drag_get_source_widget(context) != 
7936                 mainwindow_get_mainwindow()->summaryview->ctree) {
7937                 list = uri_list_extract_filenames((const gchar *)data->data);
7938                 for (tmp = list; tmp != NULL; tmp = tmp->next)
7939                         compose_attach_append
7940                                 (compose, (const gchar *)tmp->data,
7941                                  (const gchar *)tmp->data, NULL);
7942                 if (list) compose_changed_cb(NULL, compose);
7943                 list_free_strings(list);
7944                 g_list_free(list);
7945         } else if (gtk_drag_get_source_widget(context) 
7946                    == mainwindow_get_mainwindow()->summaryview->ctree) {
7947                 /* comes from our summaryview */
7948                 SummaryView * summaryview = NULL;
7949                 GSList * list = NULL, *cur = NULL;
7950                 
7951                 if (mainwindow_get_mainwindow())
7952                         summaryview = mainwindow_get_mainwindow()->summaryview;
7953                 
7954                 if (summaryview)
7955                         list = summary_get_selected_msg_list(summaryview);
7956                 
7957                 for (cur = list; cur; cur = cur->next) {
7958                         MsgInfo *msginfo = (MsgInfo *)cur->data;
7959                         gchar *file = NULL;
7960                         if (msginfo)
7961                                 file = procmsg_get_message_file_full(msginfo, 
7962                                         TRUE, TRUE);
7963                         if (file) {
7964                                 compose_attach_append(compose, (const gchar *)file, 
7965                                         (const gchar *)file, "message/rfc822");
7966                                 g_free(file);
7967                         }
7968                 }
7969                 g_slist_free(list);
7970         }
7971 }
7972
7973 static gboolean compose_drag_drop(GtkWidget *widget,
7974                                   GdkDragContext *drag_context,
7975                                   gint x, gint y,
7976                                   guint time, gpointer user_data)
7977 {
7978         /* not handling this signal makes compose_insert_drag_received_cb
7979          * called twice */
7980         return TRUE;                                     
7981 }
7982
7983 static void compose_insert_drag_received_cb (GtkWidget          *widget,
7984                                              GdkDragContext     *drag_context,
7985                                              gint                x,
7986                                              gint                y,
7987                                              GtkSelectionData   *data,
7988                                              guint               info,
7989                                              guint               time,
7990                                              gpointer            user_data)
7991 {
7992         Compose *compose = (Compose *)user_data;
7993         GList *list, *tmp;
7994
7995         /* strangely, testing data->type == gdk_atom_intern("text/uri-list", TRUE)
7996          * does not work */
7997         if (gdk_atom_name(data->type) && !strcmp(gdk_atom_name(data->type), "text/uri-list")) {
7998                 list = uri_list_extract_filenames((const gchar *)data->data);
7999                 for (tmp = list; tmp != NULL; tmp = tmp->next) {
8000                         compose_insert_file(compose, (const gchar *)tmp->data);
8001                 }
8002                 list_free_strings(list);
8003                 g_list_free(list);
8004                 gtk_drag_finish(drag_context, TRUE, FALSE, time);
8005                 return;
8006         } else {
8007 #if GTK_CHECK_VERSION(2, 8, 0)
8008                 /* do nothing, handled by GTK */
8009 #else
8010                 gchar *tmpfile = get_tmp_file();
8011                 str_write_to_file((const gchar *)data->data, tmpfile);
8012                 compose_insert_file(compose, tmpfile);
8013                 g_unlink(tmpfile);
8014                 g_free(tmpfile);
8015                 gtk_drag_finish(drag_context, TRUE, FALSE, time);
8016 #endif
8017                 return;
8018         }
8019         gtk_drag_finish(drag_context, TRUE, FALSE, time);
8020 }
8021
8022 static void compose_header_drag_received_cb (GtkWidget          *widget,
8023                                              GdkDragContext     *drag_context,
8024                                              gint                x,
8025                                              gint                y,
8026                                              GtkSelectionData   *data,
8027                                              guint               info,
8028                                              guint               time,
8029                                              gpointer            user_data)
8030 {
8031         GtkEditable *entry = (GtkEditable *)user_data;
8032         gchar *email = (gchar *)data->data;
8033
8034         /* strangely, testing data->type == gdk_atom_intern("text/plain", TRUE)
8035          * does not work */
8036
8037         if (!strncmp(email, "mailto:", strlen("mailto:"))) {
8038                 gchar *decoded=g_new(gchar, strlen(email));
8039                 int start = 0;
8040
8041                 email += strlen("mailto:");
8042                 decode_uri(decoded, email); /* will fit */
8043                 gtk_editable_delete_text(entry, 0, -1);
8044                 gtk_editable_insert_text(entry, decoded, strlen(decoded), &start);
8045                 gtk_drag_finish(drag_context, TRUE, FALSE, time);
8046                 g_free(decoded);
8047                 return;
8048         }
8049         gtk_drag_finish(drag_context, TRUE, FALSE, time);
8050 }
8051
8052 static void compose_toggle_return_receipt_cb(gpointer data, guint action,
8053                                              GtkWidget *widget)
8054 {
8055         Compose *compose = (Compose *)data;
8056
8057         if (GTK_CHECK_MENU_ITEM(widget)->active)
8058                 compose->return_receipt = TRUE;
8059         else
8060                 compose->return_receipt = FALSE;
8061 }
8062
8063 static void compose_toggle_remove_refs_cb(gpointer data, guint action,
8064                                              GtkWidget *widget)
8065 {
8066         Compose *compose = (Compose *)data;
8067
8068         if (GTK_CHECK_MENU_ITEM(widget)->active)
8069                 compose->remove_references = TRUE;
8070         else
8071                 compose->remove_references = FALSE;
8072 }
8073
8074 gboolean compose_headerentry_key_press_event_cb(GtkWidget *entry,
8075                                             GdkEventKey *event,
8076                                             ComposeHeaderEntry *headerentry)
8077 {
8078         if ((g_slist_length(headerentry->compose->header_list) > 0) &&
8079             ((headerentry->headernum + 1) != headerentry->compose->header_nextrow) &&
8080             !(event->state & GDK_MODIFIER_MASK) &&
8081             (event->keyval == GDK_BackSpace) &&
8082             (strlen(gtk_entry_get_text(GTK_ENTRY(entry))) == 0)) {
8083                 gtk_container_remove
8084                         (GTK_CONTAINER(headerentry->compose->header_table),
8085                          headerentry->combo);
8086                 gtk_container_remove
8087                         (GTK_CONTAINER(headerentry->compose->header_table),
8088                          headerentry->entry);
8089                 headerentry->compose->header_list =
8090                         g_slist_remove(headerentry->compose->header_list,
8091                                        headerentry);
8092                 g_free(headerentry);
8093         } else  if (event->keyval == GDK_Tab) {
8094                 if (headerentry->compose->header_last == headerentry) {
8095                         /* Override default next focus, and give it to subject_entry
8096                          * instead of notebook tabs
8097                          */
8098                         g_signal_stop_emission_by_name(G_OBJECT(entry), "key-press-event"); 
8099                         gtk_widget_grab_focus(headerentry->compose->subject_entry);
8100                         return TRUE;
8101                 }
8102         }
8103         return FALSE;
8104 }
8105
8106 gboolean compose_headerentry_changed_cb(GtkWidget *entry,
8107                                     ComposeHeaderEntry *headerentry)
8108 {
8109         if (strlen(gtk_entry_get_text(GTK_ENTRY(entry))) != 0) {
8110                 headerentry->compose->header_list =
8111                         g_slist_append(headerentry->compose->header_list,
8112                                        headerentry);
8113                 
8114                 compose_create_header_entry(headerentry->compose);
8115                 g_signal_handlers_disconnect_matched
8116                         (G_OBJECT(entry), G_SIGNAL_MATCH_DATA,
8117                          0, 0, NULL, NULL, headerentry);
8118                 
8119                 /* Automatically scroll down */
8120                 compose_show_first_last_header(headerentry->compose, FALSE);
8121                 
8122         }
8123         return FALSE;
8124 }
8125
8126 static void compose_show_first_last_header(Compose *compose, gboolean show_first)
8127 {
8128         GtkAdjustment *vadj;
8129
8130         g_return_if_fail(compose);
8131         g_return_if_fail(GTK_IS_WIDGET(compose->header_table));
8132         g_return_if_fail(GTK_IS_VIEWPORT(compose->header_table->parent));
8133
8134         vadj = gtk_viewport_get_vadjustment(GTK_VIEWPORT(compose->header_table->parent));
8135         gtk_adjustment_set_value(vadj, (show_first ? vadj->lower : vadj->upper));
8136 }
8137
8138 static void text_inserted(GtkTextBuffer *buffer, GtkTextIter *iter,
8139                           const gchar *text, gint len, Compose *compose)
8140 {
8141         gint paste_as_quotation = GPOINTER_TO_INT(g_object_get_data
8142                                 (G_OBJECT(compose->text), "paste_as_quotation"));
8143         GtkTextMark *mark;
8144
8145         g_return_if_fail(text != NULL);
8146
8147         g_signal_handlers_block_by_func(G_OBJECT(buffer),
8148                                         G_CALLBACK(text_inserted),
8149                                         compose);
8150         if (paste_as_quotation) {
8151                 gchar *new_text;
8152                 gchar *qmark;
8153
8154                 if (len < 0)
8155                         len = strlen(text);
8156
8157                 new_text = g_strndup(text, len);
8158                 if (prefs_common.quotemark && *prefs_common.quotemark)
8159                         qmark = prefs_common.quotemark;
8160                 else
8161                         qmark = "> ";
8162
8163                 mark = gtk_text_buffer_create_mark(buffer, NULL, iter, FALSE);
8164                 gtk_text_buffer_place_cursor(buffer, iter);
8165
8166                 compose_quote_fmt(compose, NULL, "%Q", qmark, new_text, TRUE);
8167                 g_free(new_text);
8168                 g_object_set_data(G_OBJECT(compose->text), "paste_as_quotation",
8169                                   GINT_TO_POINTER(paste_as_quotation - 1));
8170                                   
8171                 gtk_text_buffer_get_iter_at_mark(buffer, iter, mark);
8172                 gtk_text_buffer_place_cursor(buffer, iter);
8173         } else {
8174                 if (strcmp(text, "\n") || automatic_break
8175                 || gtk_text_iter_starts_line(iter))
8176                         gtk_text_buffer_insert(buffer, iter, text, len);
8177                 else {
8178                         debug_print("insert nowrap \\n\n");
8179                         gtk_text_buffer_insert_with_tags_by_name(buffer, 
8180                                 iter, text, len, "no_join", NULL);
8181                 }
8182         }
8183         
8184         mark = gtk_text_buffer_create_mark(buffer, NULL, iter, FALSE);
8185         
8186         compose_beautify_paragraph(compose, iter, FALSE);
8187
8188         gtk_text_buffer_get_iter_at_mark(buffer, iter, mark);
8189         gtk_text_buffer_delete_mark(buffer, mark);
8190
8191         g_signal_handlers_unblock_by_func(G_OBJECT(buffer),
8192                                           G_CALLBACK(text_inserted),
8193                                           compose);
8194         g_signal_stop_emission_by_name(G_OBJECT(buffer), "insert-text");
8195
8196         if (prefs_common.autosave && 
8197             gtk_text_buffer_get_char_count(buffer) % prefs_common.autosave_length == 0)
8198                 compose->draft_timeout_tag = gtk_timeout_add
8199                         (500, (GtkFunction) compose_defer_auto_save_draft, compose);
8200 }
8201 static gint compose_defer_auto_save_draft(Compose *compose)
8202 {
8203         compose->draft_timeout_tag = -1;
8204         compose_draft_cb((gpointer)compose, COMPOSE_AUTO_SAVE, NULL);
8205         return FALSE;
8206 }
8207
8208 #if USE_ASPELL
8209 static void compose_check_all(Compose *compose)
8210 {
8211         if (compose->gtkaspell)
8212                 gtkaspell_check_all(compose->gtkaspell);
8213 }
8214
8215 static void compose_highlight_all(Compose *compose)
8216 {
8217         if (compose->gtkaspell)
8218                 gtkaspell_highlight_all(compose->gtkaspell);
8219 }
8220
8221 static void compose_check_backwards(Compose *compose)
8222 {
8223         if (compose->gtkaspell) 
8224                 gtkaspell_check_backwards(compose->gtkaspell);
8225         else {
8226                 GtkItemFactory *ifactory;
8227                 ifactory = gtk_item_factory_from_widget(compose->popupmenu);
8228                 menu_set_sensitive(ifactory, "/Edit/Check backwards misspelled word", FALSE);
8229                 menu_set_sensitive(ifactory, "/Edit/Forward to next misspelled word", FALSE);
8230         }
8231 }
8232
8233 static void compose_check_forwards_go(Compose *compose)
8234 {
8235         if (compose->gtkaspell) 
8236                 gtkaspell_check_forwards_go(compose->gtkaspell);
8237         else {
8238                 GtkItemFactory *ifactory;
8239                 ifactory = gtk_item_factory_from_widget(compose->popupmenu);
8240                 menu_set_sensitive(ifactory, "/Edit/Check backwards misspelled word", FALSE);
8241                 menu_set_sensitive(ifactory, "/Edit/Forward to next misspelled word", FALSE);
8242         }
8243 }
8244 #endif
8245
8246 /*!
8247  *\brief        Guess originating forward account from MsgInfo and several 
8248  *              "common preference" settings. Return NULL if no guess. 
8249  */
8250 static PrefsAccount *compose_guess_forward_account_from_msginfo(MsgInfo *msginfo)
8251 {
8252         PrefsAccount *account = NULL;
8253         
8254         g_return_val_if_fail(msginfo, NULL);
8255         g_return_val_if_fail(msginfo->folder, NULL);
8256         g_return_val_if_fail(msginfo->folder->prefs, NULL);
8257
8258         if (msginfo->folder->prefs->enable_default_account)
8259                 account = account_find_from_id(msginfo->folder->prefs->default_account);
8260                 
8261         if (!account) 
8262                 account = msginfo->folder->folder->account;
8263                 
8264         if (!account && msginfo->to && prefs_common.forward_account_autosel) {
8265                 gchar *to;
8266                 Xstrdup_a(to, msginfo->to, return NULL);
8267                 extract_address(to);
8268                 account = account_find_from_address(to);
8269         }
8270
8271         if (!account && prefs_common.forward_account_autosel) {
8272                 gchar cc[BUFFSIZE];
8273                 if (!procheader_get_header_from_msginfo
8274                         (msginfo, cc,sizeof cc , "CC:")) { /* Found a CC header */
8275                         extract_address(cc);
8276                         account = account_find_from_address(cc);
8277                 }
8278         }
8279         
8280         return account;
8281 }
8282
8283 static gboolean compose_close(Compose *compose)
8284 {
8285         gint x, y;
8286
8287         if (!g_mutex_trylock(compose->mutex)) {
8288                 /* we have to wait for the (possibly deferred by auto-save)
8289                  * drafting to be done, before destroying the compose under
8290                  * it. */
8291                 debug_print("waiting for drafting to finish...\n");
8292                 g_timeout_add (500, (GSourceFunc) compose_close, compose);
8293                 return FALSE;
8294         }
8295         g_return_val_if_fail(compose, FALSE);
8296         gtkut_widget_get_uposition(compose->window, &x, &y);
8297         prefs_common.compose_x = x;
8298         prefs_common.compose_y = y;
8299         g_mutex_unlock(compose->mutex);
8300         compose_destroy(compose);
8301         return FALSE;
8302 }
8303
8304 /**
8305  * Add entry field for each address in list.
8306  * \param compose     E-Mail composition object.
8307  * \param listAddress List of (formatted) E-Mail addresses.
8308  */
8309 static void compose_add_field_list( Compose *compose, GList *listAddress ) {
8310         GList *node;
8311         gchar *addr;
8312         node = listAddress;
8313         while( node ) {
8314                 addr = ( gchar * ) node->data;
8315                 compose_entry_append( compose, addr, COMPOSE_TO );
8316                 node = g_list_next( node );
8317         }
8318 }
8319
8320 void compose_reply_from_messageview(MessageView *msgview, GSList *msginfo_list, 
8321                                     guint action)
8322 {
8323         gchar *body;
8324         GSList *new_msglist = NULL;
8325         MsgInfo *tmp_msginfo = NULL;
8326         gboolean originally_enc = FALSE;
8327         Compose *compose = NULL;
8328
8329         g_return_if_fail(msgview != NULL);
8330
8331         g_return_if_fail(msginfo_list != NULL);
8332
8333         if (g_slist_length(msginfo_list) == 1) {
8334                 MimeInfo *mimeinfo = messageview_get_selected_mime_part(msgview);
8335                 MsgInfo *orig_msginfo = (MsgInfo *)msginfo_list->data;
8336                 
8337                 if (mimeinfo != NULL && mimeinfo->type == MIMETYPE_MESSAGE && 
8338                     !g_ascii_strcasecmp(mimeinfo->subtype, "rfc822")) {
8339                         tmp_msginfo = procmsg_msginfo_new_from_mimeinfo(
8340                                                 orig_msginfo, mimeinfo);
8341                         if (tmp_msginfo != NULL) {
8342                                 new_msglist = g_slist_append(NULL, tmp_msginfo);
8343                                 if (procmime_msginfo_is_encrypted(orig_msginfo)) {
8344                                         originally_enc = TRUE;
8345                                 }
8346                         } 
8347                 }
8348         }
8349
8350         body = messageview_get_selection(msgview);
8351
8352         if (new_msglist) {
8353                 compose = compose_reply_mode((ComposeMode)action, new_msglist, body);
8354                 procmsg_msginfo_free(tmp_msginfo);
8355                 g_slist_free(new_msglist);
8356         } else
8357                 compose = compose_reply_mode((ComposeMode)action, msginfo_list, body);
8358
8359         if (originally_enc) {
8360                 compose_force_encryption(compose, compose->account, FALSE);
8361         }
8362
8363         g_free(body);
8364 }
8365
8366 /*
8367  * End of Source.
8368  */