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