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