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