66a90cf048ba87710236d9b701ad177425ee5544
[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, "/Message/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, "/Message/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, "/Message/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 *bcc = NULL;
1560         gchar *subject = NULL;
1561         gchar *body = NULL;
1562
1563         scan_mailto_url(mailto, &to, &cc, &bcc, &subject, &body);
1564
1565         if (to)
1566                 compose_entry_append(compose, to, COMPOSE_TO);
1567         if (cc)
1568                 compose_entry_append(compose, cc, COMPOSE_CC);
1569         if (bcc)
1570                 compose_entry_append(compose, bcc, COMPOSE_BCC);
1571         if (subject)
1572                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), subject);
1573         if (body) {
1574                 gtk_stext_insert(GTK_STEXT(compose->text),
1575                                 NULL, NULL, NULL, body, -1);
1576                 gtk_stext_insert(GTK_STEXT(compose->text),
1577                                 NULL, NULL, NULL, "\n", 1);
1578         }
1579
1580         g_free(to);
1581         g_free(cc);
1582         g_free(bcc);
1583         g_free(subject);
1584         g_free(body);
1585 }
1586
1587 static gint compose_parse_header(Compose *compose, MsgInfo *msginfo)
1588 {
1589         static HeaderEntry hentry[] = {{"Reply-To:",    NULL, TRUE},
1590                                        {"Cc:",          NULL, TRUE},
1591                                        {"References:",  NULL, FALSE},
1592                                        {"Bcc:",         NULL, TRUE},
1593                                        {"Newsgroups:",  NULL, TRUE},
1594                                        {"Followup-To:", NULL, TRUE},
1595                                        {"List-Post:",   NULL, FALSE},
1596                                        {"X-Priority:",  NULL, FALSE},
1597                                        {NULL,           NULL, FALSE}};
1598
1599         enum
1600         {
1601                 H_REPLY_TO      = 0,
1602                 H_CC            = 1,
1603                 H_REFERENCES    = 2,
1604                 H_BCC           = 3,
1605                 H_NEWSGROUPS    = 4,
1606                 H_FOLLOWUP_TO   = 5,
1607                 H_LIST_POST     = 6,
1608                 H_X_PRIORITY    = 7
1609         };
1610
1611         FILE *fp;
1612         gchar buf[BUFFSIZE];
1613
1614         g_return_val_if_fail(msginfo != NULL, -1);
1615
1616         if ((fp = procmsg_open_message(msginfo)) == NULL) return -1;
1617         procheader_get_header_fields(fp, hentry);
1618         fclose(fp);
1619
1620         if (hentry[H_REPLY_TO].body != NULL) {
1621                 conv_unmime_header(buf, sizeof(buf), hentry[H_REPLY_TO].body,
1622                                    NULL);
1623                 compose->replyto = g_strdup(buf);
1624                 g_free(hentry[H_REPLY_TO].body);
1625                 hentry[H_REPLY_TO].body = NULL;
1626                /* if empty replyto, let sylpheed figure it out, i.e.
1627                  * neglect the reply-to header. */
1628                 if (*(compose->replyto) == 0) {
1629                         g_free(compose->replyto);
1630                         compose->replyto = NULL;
1631                 }
1632         }
1633         if (hentry[H_CC].body != NULL) {
1634                 conv_unmime_header(buf, sizeof(buf), hentry[H_CC].body, NULL);
1635                 compose->cc = g_strdup(buf);
1636                 g_free(hentry[H_CC].body);
1637                 hentry[H_CC].body = NULL;
1638         }
1639         if (hentry[H_REFERENCES].body != NULL) {
1640                 if (compose->mode == COMPOSE_REEDIT)
1641                         compose->references = hentry[H_REFERENCES].body;
1642                 else {
1643                         compose->references = compose_parse_references
1644                                 (hentry[H_REFERENCES].body, msginfo->msgid);
1645                         g_free(hentry[H_REFERENCES].body);
1646                 }
1647                 hentry[H_REFERENCES].body = NULL;
1648         }
1649         if (hentry[H_BCC].body != NULL) {
1650                 if (compose->mode == COMPOSE_REEDIT) {
1651                         conv_unmime_header
1652                                 (buf, sizeof(buf), hentry[H_BCC].body, NULL);
1653                         compose->bcc = g_strdup(buf);
1654                 }
1655                 g_free(hentry[H_BCC].body);
1656                 hentry[H_BCC].body = NULL;
1657         }
1658         if (hentry[H_NEWSGROUPS].body != NULL) {
1659                 compose->newsgroups = hentry[H_NEWSGROUPS].body;
1660                 hentry[H_NEWSGROUPS].body = NULL;
1661         }
1662         if (hentry[H_FOLLOWUP_TO].body != NULL) {
1663                 conv_unmime_header
1664                         (buf, sizeof(buf), hentry[H_FOLLOWUP_TO].body, NULL);
1665                 compose->followup_to = g_strdup(buf);
1666                 g_free(hentry[H_FOLLOWUP_TO].body);
1667                 hentry[H_FOLLOWUP_TO].body = NULL;
1668         }
1669         if (hentry[H_LIST_POST].body != NULL) {
1670                 gchar *to = NULL;
1671
1672                 extract_address(hentry[H_LIST_POST].body);
1673                 if (hentry[H_LIST_POST].body[0] != '\0') {
1674                         scan_mailto_url(hentry[H_LIST_POST].body,
1675                                         &to, NULL, NULL, NULL, NULL);
1676                         if (to) {
1677                                 g_free(compose->ml_post);
1678                                 compose->ml_post = to;
1679                         }
1680                 }
1681                 g_free(hentry[H_LIST_POST].body);
1682                 hentry[H_LIST_POST].body = NULL;
1683         }
1684
1685         /* CLAWS - X-Priority */
1686         if (compose->mode == COMPOSE_REEDIT)
1687                 if (hentry[H_X_PRIORITY].body != NULL) {
1688                         gint priority;
1689                         
1690                         priority = atoi(hentry[H_X_PRIORITY].body);
1691                         g_free(hentry[H_X_PRIORITY].body);
1692                         
1693                         hentry[H_X_PRIORITY].body = NULL;
1694                         
1695                         if (priority < PRIORITY_HIGHEST || 
1696                             priority > PRIORITY_LOWEST)
1697                                 priority = PRIORITY_NORMAL;
1698                         
1699                         compose->priority =  priority;
1700                 }
1701  
1702         if (compose->mode == COMPOSE_REEDIT) {
1703                 if (msginfo->inreplyto && *msginfo->inreplyto)
1704                         compose->inreplyto = g_strdup(msginfo->inreplyto);
1705                 return 0;
1706         }
1707
1708         if (msginfo->msgid && *msginfo->msgid)
1709                 compose->inreplyto = g_strdup(msginfo->msgid);
1710
1711         if (!compose->references) {
1712                 if (msginfo->msgid && *msginfo->msgid) {
1713                         if (msginfo->inreplyto && *msginfo->inreplyto)
1714                                 compose->references =
1715                                         g_strdup_printf("<%s>\n\t<%s>",
1716                                                         msginfo->inreplyto,
1717                                                         msginfo->msgid);
1718                         else
1719                                 compose->references =
1720                                         g_strconcat("<", msginfo->msgid, ">",
1721                                                     NULL);
1722                 } else if (msginfo->inreplyto && *msginfo->inreplyto) {
1723                         compose->references =
1724                                 g_strconcat("<", msginfo->inreplyto, ">",
1725                                             NULL);
1726                 }
1727         }
1728
1729         return 0;
1730 }
1731
1732 static gchar *compose_parse_references(const gchar *ref, const gchar *msgid)
1733 {
1734         GSList *ref_id_list, *cur;
1735         GString *new_ref;
1736         gchar *new_ref_str;
1737
1738         ref_id_list = references_list_append(NULL, ref);
1739         if (!ref_id_list) return NULL;
1740         if (msgid && *msgid)
1741                 ref_id_list = g_slist_append(ref_id_list, g_strdup(msgid));
1742
1743         for (;;) {
1744                 gint len = 0;
1745
1746                 for (cur = ref_id_list; cur != NULL; cur = cur->next)
1747                         /* "<" + Message-ID + ">" + CR+LF+TAB */
1748                         len += strlen((gchar *)cur->data) + 5;
1749
1750                 if (len > MAX_REFERENCES_LEN) {
1751                         /* remove second message-ID */
1752                         if (ref_id_list && ref_id_list->next &&
1753                             ref_id_list->next->next) {
1754                                 g_free(ref_id_list->next->data);
1755                                 ref_id_list = g_slist_remove
1756                                         (ref_id_list, ref_id_list->next->data);
1757                         } else {
1758                                 slist_free_strings(ref_id_list);
1759                                 g_slist_free(ref_id_list);
1760                                 return NULL;
1761                         }
1762                 } else
1763                         break;
1764         }
1765
1766         new_ref = g_string_new("");
1767         for (cur = ref_id_list; cur != NULL; cur = cur->next) {
1768                 if (new_ref->len > 0)
1769                         g_string_append(new_ref, "\n\t");
1770                 g_string_sprintfa(new_ref, "<%s>", (gchar *)cur->data);
1771         }
1772
1773         slist_free_strings(ref_id_list);
1774         g_slist_free(ref_id_list);
1775
1776         new_ref_str = new_ref->str;
1777         g_string_free(new_ref, FALSE);
1778
1779         return new_ref_str;
1780 }
1781
1782 static gchar *compose_quote_fmt(Compose *compose, MsgInfo *msginfo,
1783                                 const gchar *fmt, const gchar *qmark,
1784                                 const gchar *body)
1785 {
1786         GtkSText *text = GTK_STEXT(compose->text);
1787         static MsgInfo dummyinfo;
1788         gchar *quote_str = NULL;
1789         gchar *buf;
1790         gchar *p, *lastp;
1791         gint len;
1792         const gchar *trimmed_body = body;
1793         
1794         if (!msginfo)
1795                 msginfo = &dummyinfo;
1796
1797         if (qmark != NULL) {
1798                 quote_fmt_init(msginfo, NULL, NULL);
1799                 quote_fmt_scan_string(qmark);
1800                 quote_fmt_parse();
1801
1802                 buf = quote_fmt_get_buffer();
1803                 if (buf == NULL)
1804                         alertpanel_error(_("Quote mark format error."));
1805                 else
1806                         Xstrdup_a(quote_str, buf, return NULL)
1807         }
1808
1809         if (fmt && *fmt != '\0') {
1810                 while (trimmed_body && strlen(trimmed_body) > 1
1811                         && trimmed_body[0]=='\n')
1812                         *trimmed_body++;
1813
1814                 quote_fmt_init(msginfo, quote_str, trimmed_body);
1815                 quote_fmt_scan_string(fmt);
1816                 quote_fmt_parse();
1817
1818                 buf = quote_fmt_get_buffer();
1819                 if (buf == NULL) {
1820                         alertpanel_error(_("Message reply/forward format error."));
1821                         return NULL;
1822                 }
1823         } else
1824                 buf = "";
1825
1826         gtk_stext_freeze(text);
1827
1828         for (p = buf; *p != '\0'; ) {
1829                 lastp = strchr(p, '\n');
1830                 len = lastp ? lastp - p + 1 : -1;
1831                 gtk_stext_insert(text, NULL, NULL, NULL, p, len);
1832                 if (lastp)
1833                         p = lastp + 1;
1834                 else
1835                         break;
1836         }
1837
1838         gtk_stext_thaw(text);
1839
1840         return buf;
1841 }
1842
1843 static void compose_reply_set_entry(Compose *compose, MsgInfo *msginfo,
1844                                     gboolean to_all, gboolean to_ml,
1845                                     gboolean to_sender,
1846                                     gboolean followup_and_reply_to)
1847 {
1848         GSList *cc_list = NULL;
1849         GSList *cur;
1850         gchar *from = NULL;
1851         gchar *replyto = NULL;
1852         GHashTable *to_table;
1853
1854         g_return_if_fail(compose->account != NULL);
1855         g_return_if_fail(msginfo != NULL);
1856
1857         if (compose->account->protocol != A_NNTP) {
1858                 if (!compose->replyto && to_ml && compose->ml_post
1859                     && !(msginfo->folder && msginfo->folder->prefs->enable_default_reply_to))
1860                         compose_entry_append(compose,
1861                                            compose->ml_post,
1862                                            COMPOSE_TO);
1863                 else if (!(to_all || to_sender)
1864                          && msginfo->folder
1865                          && msginfo->folder->prefs->enable_default_reply_to) {
1866                         compose_entry_append(compose,
1867                             msginfo->folder->prefs->default_reply_to,
1868                             COMPOSE_TO);
1869                 } else
1870                         compose_entry_append(compose,
1871                                  (compose->replyto && !to_sender)
1872                                   ? compose->replyto :
1873                                   msginfo->from ? msginfo->from : "",
1874                                   COMPOSE_TO);
1875         } else {
1876                 if (to_sender || (compose->followup_to && 
1877                         !strncmp(compose->followup_to, "poster", 6)))
1878                         compose_entry_append
1879                                 (compose, 
1880                                  (compose->replyto ? compose->replyto :
1881                                         msginfo->from ? msginfo->from : ""),
1882                                  COMPOSE_TO);
1883                                  
1884                 else if (followup_and_reply_to || to_all) {
1885                         compose_entry_append
1886                                 (compose,
1887                                  (compose->replyto ? compose->replyto :
1888                                  msginfo->from ? msginfo->from : ""),
1889                                  COMPOSE_TO);                           
1890                 
1891                         compose_entry_append
1892                                 (compose,
1893                                  compose->followup_to ? compose->followup_to :
1894                                  compose->newsgroups ? compose->newsgroups : "",
1895                                  COMPOSE_NEWSGROUPS);
1896                 } 
1897                 else 
1898                         compose_entry_append
1899                                 (compose,
1900                                  compose->followup_to ? compose->followup_to :
1901                                  compose->newsgroups ? compose->newsgroups : "",
1902                                  COMPOSE_NEWSGROUPS);
1903         }
1904
1905         if (msginfo->subject && *msginfo->subject) {
1906                 gchar *buf, *buf2;
1907                 guchar *p;
1908
1909                 buf = p = g_strdup(msginfo->subject);
1910                 p += subject_get_prefix_length(p);
1911                 memmove(buf, p, strlen(p) + 1);
1912
1913                 buf2 = g_strdup_printf("Re: %s", buf);
1914                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), buf2);
1915
1916                 g_free(buf2);
1917                 g_free(buf);
1918         } else
1919                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), "Re: ");
1920
1921         if (to_ml && compose->ml_post) return;
1922         if (!to_all || compose->account->protocol == A_NNTP) return;
1923
1924         if (compose->replyto) {
1925                 Xstrdup_a(replyto, compose->replyto, return);
1926                 extract_address(replyto);
1927         }
1928         if (msginfo->from) {
1929                 Xstrdup_a(from, msginfo->from, return);
1930                 extract_address(from);
1931         }
1932
1933         if (replyto && from)
1934                 cc_list = address_list_append_with_comments(cc_list, from);
1935         if (to_all && msginfo->folder && 
1936             msginfo->folder->prefs->enable_default_reply_to)
1937                 cc_list = address_list_append_with_comments(cc_list,
1938                                 msginfo->folder->prefs->default_reply_to);
1939         cc_list = address_list_append_with_comments(cc_list, msginfo->to);
1940         cc_list = address_list_append_with_comments(cc_list, compose->cc);
1941
1942         to_table = g_hash_table_new(g_str_hash, g_str_equal);
1943         if (replyto)
1944                 g_hash_table_insert(to_table, g_strdup(replyto), GINT_TO_POINTER(1));
1945         if (compose->account)
1946                 g_hash_table_insert(to_table, g_strdup(compose->account->address),
1947                                     GINT_TO_POINTER(1));
1948
1949         /* remove address on To: and that of current account */
1950         for (cur = cc_list; cur != NULL; ) {
1951                 GSList *next = cur->next;
1952                 gchar *addr;
1953
1954                 addr = g_strdup(cur->data);
1955                 extract_address(addr);
1956
1957                 if (GPOINTER_TO_INT(g_hash_table_lookup(to_table, addr)) == 1)
1958                         cc_list = g_slist_remove(cc_list, cur->data);
1959                 else
1960                         g_hash_table_insert(to_table, addr, GINT_TO_POINTER(1));
1961
1962                 cur = next;
1963         }
1964         hash_free_strings(to_table);
1965         g_hash_table_destroy(to_table);
1966
1967         if (cc_list) {
1968                 for (cur = cc_list; cur != NULL; cur = cur->next)
1969                         compose_entry_append(compose, (gchar *)cur->data,
1970                                              COMPOSE_CC);
1971                 slist_free_strings(cc_list);
1972                 g_slist_free(cc_list);
1973         }
1974
1975 }
1976
1977 #define SET_ENTRY(entry, str) \
1978 { \
1979         if (str && *str) \
1980                 gtk_entry_set_text(GTK_ENTRY(compose->entry), str); \
1981 }
1982
1983 #define SET_ADDRESS(type, str) \
1984 { \
1985         if (str && *str) \
1986                 compose_entry_append(compose, str, type); \
1987 }
1988
1989 static void compose_reedit_set_entry(Compose *compose, MsgInfo *msginfo)
1990 {
1991         g_return_if_fail(msginfo != NULL);
1992
1993         SET_ENTRY(subject_entry, msginfo->subject);
1994         SET_ADDRESS(COMPOSE_TO, msginfo->to);
1995         SET_ADDRESS(COMPOSE_CC, compose->cc);
1996         SET_ADDRESS(COMPOSE_BCC, compose->bcc);
1997         SET_ADDRESS(COMPOSE_REPLYTO, compose->replyto);
1998         SET_ADDRESS(COMPOSE_NEWSGROUPS, compose->newsgroups);
1999         SET_ADDRESS(COMPOSE_FOLLOWUPTO, compose->followup_to);
2000
2001         compose_update_priority_menu_item(compose);
2002         compose_update_privacy_system_menu_item(compose);
2003         compose_show_first_last_header(compose, TRUE);
2004 }
2005
2006 #undef SET_ENTRY
2007 #undef SET_ADDRESS
2008
2009 static void compose_insert_sig(Compose *compose, gboolean replace)
2010 {
2011         GtkSText *text = GTK_STEXT(compose->text);
2012         gint cur_pos;
2013         gint len;
2014
2015         g_return_if_fail(compose->account != NULL);
2016
2017         cur_pos = gtk_editable_get_position(GTK_EDITABLE(text));
2018
2019         gtk_stext_freeze(text);
2020
2021         if (replace) {
2022                 len = gtk_stext_get_length(text);
2023                 gtk_stext_set_point(text, len);
2024         }
2025
2026         if (replace && compose->sig_str) {
2027                 gint pos;
2028
2029                 if (compose->sig_str[0] == '\0')
2030                         pos = -1;
2031                 else
2032                         pos = gtkut_stext_find(text, 0, compose->sig_str, TRUE);
2033
2034                 if (pos != -1) {
2035                         len = get_mbs_len(compose->sig_str);
2036                         if (len >= 0) {
2037                                 gtk_stext_set_point(text, pos);
2038                                 gtk_stext_forward_delete(text, len);
2039                         }
2040                 }
2041         }
2042
2043         g_free(compose->sig_str);
2044         compose->sig_str = compose_get_signature_str(compose);
2045         if (!compose->sig_str || (replace && !compose->account->auto_sig))
2046                 compose->sig_str = g_strdup("");
2047
2048         gtk_stext_insert(text, NULL, NULL, NULL, compose->sig_str, -1);
2049
2050         gtk_stext_thaw(text);
2051
2052         if (cur_pos > gtk_stext_get_length(text))
2053                 cur_pos = gtk_stext_get_length(text);
2054
2055         gtk_editable_set_position(GTK_EDITABLE(text), cur_pos);
2056         gtk_stext_set_point(text, cur_pos);
2057 }
2058
2059 static gchar *compose_get_signature_str(Compose *compose)
2060 {
2061         gchar *sig_body = NULL;
2062         gchar *sig_str = NULL;
2063
2064         g_return_val_if_fail(compose->account != NULL, NULL);
2065
2066         if (!compose->account->sig_path)
2067                 return NULL;
2068
2069         if (compose->account->sig_type == SIG_FILE) {
2070                 if (!is_file_or_fifo_exist(compose->account->sig_path)) {
2071                         g_warning("can't open signature file: %s\n",
2072                                   compose->account->sig_path);
2073                         return NULL;
2074                 }
2075         }
2076
2077         if (compose->account->sig_type == SIG_COMMAND)
2078                 sig_body = get_command_output(compose->account->sig_path);
2079         else {
2080                 gchar *tmp;
2081
2082                 tmp = file_read_to_str(compose->account->sig_path);
2083                 if (!tmp)
2084                         return NULL;
2085                 sig_body = normalize_newlines(tmp);
2086                 g_free(tmp);
2087         }
2088
2089         if (compose->account->sig_sep)
2090                 sig_str = g_strconcat("\n\n", compose->account->sig_sep, "\n", sig_body,
2091                                       NULL);
2092         else
2093                 sig_str = g_strconcat("\n\n", sig_body, NULL);
2094
2095         g_free(sig_body);
2096         
2097         return sig_str;
2098 }
2099
2100 static ComposeInsertResult compose_insert_file(Compose *compose, const gchar *file)
2101 {
2102         GtkSText *text = GTK_STEXT(compose->text);
2103         gchar buf[BUFFSIZE];
2104         gint len;
2105         FILE *fp;
2106         gboolean badtxt = FALSE;
2107
2108         g_return_val_if_fail(file != NULL, COMPOSE_INSERT_NO_FILE);
2109
2110         if ((fp = fopen(file, "rb")) == NULL) {
2111                 FILE_OP_ERROR(file, "fopen");
2112                 return COMPOSE_INSERT_READ_ERROR;
2113         }
2114
2115         gtk_stext_freeze(text);
2116
2117         while (fgets(buf, sizeof(buf), fp) != NULL) {
2118                 /* strip <CR> if DOS/Windows file,
2119                    replace <CR> with <LF> if Macintosh file. */
2120                 strcrchomp(buf);
2121                 len = strlen(buf);
2122                 if (len > 0 && buf[len - 1] != '\n') {
2123                         while (--len >= 0)
2124                                 if (buf[len] == '\r') buf[len] = '\n';
2125                 }
2126                 if (mbstowcs(NULL, buf, 0) == -1)
2127                         badtxt = TRUE;
2128                 gtk_stext_insert(text, NULL, NULL, NULL, buf, -1);
2129         }
2130
2131         gtk_stext_thaw(text);
2132
2133         fclose(fp);
2134
2135         if (badtxt)
2136                 return COMPOSE_INSERT_INVALID_CHARACTER;
2137         else 
2138                 return COMPOSE_INSERT_SUCCESS;
2139 }
2140
2141 static void compose_attach_append(Compose *compose, const gchar *file,
2142                                   const gchar *filename,
2143                                   const gchar *content_type)
2144 {
2145         AttachInfo *ainfo;
2146         gchar *text[N_ATTACH_COLS];
2147         FILE *fp;
2148         off_t size;
2149         gint row;
2150
2151         if (!is_file_exist(file)) {
2152                 g_warning("File %s doesn't exist\n", file);
2153                 return;
2154         }
2155         if ((size = get_file_size(file)) < 0) {
2156                 g_warning("Can't get file size of %s\n", file);
2157                 return;
2158         }
2159         if (size == 0) {
2160                 alertpanel_notice(_("File %s is empty."), file);
2161                 return;
2162         }
2163         if ((fp = fopen(file, "rb")) == NULL) {
2164                 alertpanel_error(_("Can't read %s."), file);
2165                 return;
2166         }
2167         fclose(fp);
2168
2169 #if 0 /* NEW COMPOSE GUI */
2170         if (!compose->use_attach) {
2171                 GtkItemFactory *ifactory;
2172
2173                 ifactory = gtk_item_factory_from_widget(compose->menubar);
2174                 menu_set_active(ifactory, "/View/Attachment", TRUE);
2175         }
2176 #endif
2177         ainfo = g_new0(AttachInfo, 1);
2178         ainfo->file = g_strdup(file);
2179
2180         if (content_type) {
2181                 ainfo->content_type = g_strdup(content_type);
2182                 if (!g_strcasecmp(content_type, "message/rfc822")) {
2183                         MsgInfo *msginfo;
2184                         MsgFlags flags = {0, 0};
2185                         gchar *name;
2186
2187                         if (procmime_get_encoding_for_text_file(file) == ENC_7BIT)
2188                                 ainfo->encoding = ENC_7BIT;
2189                         else
2190                                 ainfo->encoding = ENC_8BIT;
2191
2192                         msginfo = procheader_parse_file(file, flags, FALSE, FALSE);
2193                         if (msginfo && msginfo->subject)
2194                                 name = msginfo->subject;
2195                         else
2196                                 name = g_basename(filename ? filename : file);
2197
2198                         ainfo->name = g_strdup_printf(_("Message: %s"), name);
2199
2200                         procmsg_msginfo_free(msginfo);
2201                 } else {
2202                         if (!g_strncasecmp(content_type, "text", 4))
2203                                 ainfo->encoding = procmime_get_encoding_for_text_file(file);
2204                         else
2205                                 ainfo->encoding = ENC_BASE64;
2206                         ainfo->name = g_strdup
2207                                 (g_basename(filename ? filename : file));
2208                 }
2209         } else {
2210                 ainfo->content_type = procmime_get_mime_type(file);
2211                 if (!ainfo->content_type) {
2212                         ainfo->content_type =
2213                                 g_strdup("application/octet-stream");
2214                         ainfo->encoding = ENC_BASE64;
2215                 } else if (!g_strncasecmp(ainfo->content_type, "text", 4))
2216                         ainfo->encoding =
2217                                 procmime_get_encoding_for_text_file(file);
2218                 else
2219                         ainfo->encoding = ENC_BASE64;
2220                 ainfo->name = g_strdup(g_basename(filename ? filename : file)); 
2221         }
2222
2223         if (!strcmp(ainfo->content_type, "unknown")) {
2224                 g_free(ainfo->content_type);
2225                 ainfo->content_type = g_strdup("application/octet-stream");
2226         }
2227
2228         ainfo->size = size;
2229
2230         text[COL_MIMETYPE] = ainfo->content_type;
2231         text[COL_SIZE] = to_human_readable(size);
2232         text[COL_NAME] = ainfo->name;
2233
2234         row = gtk_clist_append(GTK_CLIST(compose->attach_clist), text);
2235         gtk_clist_set_row_data(GTK_CLIST(compose->attach_clist), row, ainfo);
2236 }
2237
2238 static void compose_use_signing(Compose *compose, gboolean use_signing)
2239 {
2240         GtkItemFactory *ifactory;
2241         GtkWidget *menuitem = NULL;
2242
2243         compose->use_signing = use_signing;
2244         ifactory = gtk_item_factory_from_widget(compose->menubar);
2245         menuitem = gtk_item_factory_get_item
2246                 (ifactory, "/Options/Sign");
2247         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), 
2248                                        use_signing);
2249 }
2250
2251 static void compose_use_encryption(Compose *compose, gboolean use_encryption)
2252 {
2253         GtkItemFactory *ifactory;
2254         GtkWidget *menuitem = NULL;
2255
2256         compose->use_encryption = use_encryption;
2257         ifactory = gtk_item_factory_from_widget(compose->menubar);
2258         menuitem = gtk_item_factory_get_item
2259                 (ifactory, "/Options/Encrypt");
2260
2261         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), 
2262                                        use_encryption);
2263 }
2264
2265 #define NEXT_PART_NOT_CHILD(info)  \
2266 {  \
2267         node = info->node;  \
2268         while (node->children)  \
2269                 node = g_node_last_child(node);  \
2270         info = procmime_mimeinfo_next((MimeInfo *)node->data);  \
2271 }
2272
2273 static void compose_attach_parts(Compose *compose, MsgInfo *msginfo)
2274 {
2275         MimeInfo *mimeinfo;
2276         MimeInfo *child;
2277         MimeInfo *firsttext = NULL;
2278         MimeInfo *encrypted = NULL;
2279         GNode    *node;
2280         gchar *outfile;
2281         const gchar *partname = NULL;
2282
2283         mimeinfo = procmime_scan_message(msginfo);
2284         if (!mimeinfo) return;
2285
2286         if (mimeinfo->node->children == NULL) {
2287                 procmime_mimeinfo_free_all(mimeinfo);
2288                 return;
2289         }
2290
2291         /* find first content part */
2292         child = (MimeInfo *) mimeinfo->node->children->data;
2293         while (child && child->node->children && (child->type == MIMETYPE_MULTIPART))
2294                 child = (MimeInfo *)child->node->children->data;
2295
2296         if (child->type == MIMETYPE_TEXT) {
2297                 firsttext = child;
2298                 debug_print("First text part found\n");
2299         } else if (compose->mode == COMPOSE_REEDIT &&
2300                  child->type == MIMETYPE_APPLICATION &&
2301                  !g_strcasecmp(child->subtype, "pgp-encrypted")) {
2302                 AlertValue val;
2303                 val = alertpanel(_("Encrypted message"),
2304                                  _("Cannot re-edit an encrypted message. \n"
2305                                    "Discard encrypted part?"),
2306                                  _("Yes"), _("No"), NULL);
2307                 if (val == G_ALERTDEFAULT) 
2308                         encrypted = (MimeInfo *)child->node->parent->data;
2309         }
2310      
2311         child = (MimeInfo *) mimeinfo->node->children->data;
2312         while (child != NULL) {
2313                 if (child == encrypted) {
2314                         /* skip this part of tree */
2315                         NEXT_PART_NOT_CHILD(child);
2316                         continue;
2317                 }
2318
2319                 if (child->type == MIMETYPE_MULTIPART) {
2320                         /* get the actual content */
2321                         child = procmime_mimeinfo_next(child);
2322                         continue;
2323                 }
2324                     
2325                 if (child == firsttext) {
2326                         child = procmime_mimeinfo_next(child);
2327                         continue;
2328                 }
2329
2330                 outfile = procmime_get_tmp_file_name(child);
2331                 if (procmime_get_part(outfile, child) < 0)
2332                         g_warning("Can't get the part of multipart message.");
2333                 else {
2334                         gchar *content_type;
2335
2336                         content_type = procmime_get_content_type_str(child->type, child->subtype);
2337                         partname = procmime_mimeinfo_get_parameter(child, "name");
2338                         if (partname == NULL)
2339                                 partname = "";
2340                         compose_attach_append(compose, outfile, 
2341                                               partname, content_type);
2342                         g_free(content_type);
2343                 }
2344                 g_free(outfile);
2345                 NEXT_PART_NOT_CHILD(child);
2346         }
2347         procmime_mimeinfo_free_all(mimeinfo);
2348 }
2349
2350 #undef NEXT_PART_NOT_CHILD
2351
2352 #define GET_CHAR(pos, buf, len)                                              \
2353 {                                                                            \
2354         if (text->use_wchar)                                                 \
2355                 len = wctomb(buf, (wchar_t)GTK_STEXT_INDEX(text, (pos)));    \
2356         else {                                                               \
2357                 buf[0] = GTK_STEXT_INDEX(text, (pos));                       \
2358                 len = 1;                                                     \
2359         }                                                                    \
2360 }
2361
2362 #define DISP_WIDTH(len) \
2363         ((len > 2 && conv_get_current_charset() == C_UTF_8) ? 2 : \
2364          (len == 2 && conv_get_current_charset() == C_UTF_8) ? 1 : len)
2365
2366 #define SPACE_CHARS     " \t"
2367
2368 static void compose_wrap_line(Compose *compose)
2369 {
2370         GtkSText *text = GTK_STEXT(compose->text);
2371         gint ch_len, last_ch_len;
2372         gchar cbuf[MB_LEN_MAX], last_ch;
2373         guint text_len;
2374         guint line_end;
2375         guint quoted;
2376         gint p_start, p_end;
2377         gint line_pos, cur_pos;
2378         gint line_len, cur_len;
2379
2380         gtk_stext_freeze(text);
2381
2382         text_len = gtk_stext_get_length(text);
2383
2384         /* check to see if the point is on the paragraph mark (empty line). */
2385         cur_pos = gtk_stext_get_point(text);
2386         GET_CHAR(cur_pos, cbuf, ch_len);
2387         if ((ch_len == 1 && *cbuf == '\n') || cur_pos == text_len) {
2388                 if (cur_pos == 0)
2389                         goto compose_end; /* on the paragraph mark */
2390                 GET_CHAR(cur_pos - 1, cbuf, ch_len);
2391                 if (ch_len == 1 && *cbuf == '\n')
2392                         goto compose_end; /* on the paragraph mark */
2393         }
2394
2395         /* find paragraph start. */
2396         line_end = quoted = 0;
2397         for (p_start = cur_pos; p_start >= 0; --p_start) {
2398                 GET_CHAR(p_start, cbuf, ch_len);
2399                 if (ch_len == 1 && *cbuf == '\n') {
2400                         if (quoted)
2401                                 goto compose_end; /* quoted part */
2402                         if (line_end) {
2403                                 p_start += 2;
2404                                 break;
2405                         }
2406                         line_end = 1;
2407                 } else {
2408                         if (ch_len == 1 
2409                             && strchr(prefs_common.quote_chars, *cbuf))
2410                                 quoted = 1;
2411                         else if (ch_len != 1 || !isspace(*(guchar *)cbuf))
2412                                 quoted = 0;
2413
2414                         line_end = 0;
2415                 }
2416         }
2417         if (p_start < 0)
2418                 p_start = 0;
2419
2420         /* find paragraph end. */
2421         line_end = 0;
2422         for (p_end = cur_pos; p_end < text_len; p_end++) {
2423                 GET_CHAR(p_end, cbuf, ch_len);
2424                 if (ch_len == 1 && *cbuf == '\n') {
2425                         if (line_end) {
2426                                 p_end -= 1;
2427                                 break;
2428                         }
2429                         line_end = 1;
2430                 } else {
2431                         if (line_end && ch_len == 1 &&
2432                             strchr(prefs_common.quote_chars, *cbuf))
2433                                 goto compose_end; /* quoted part */
2434
2435                         line_end = 0;
2436                 }
2437         }
2438         if (p_end >= text_len)
2439                 p_end = text_len;
2440
2441         if (p_start >= p_end)
2442                 goto compose_end;
2443
2444         line_len = cur_len = 0;
2445         last_ch_len = 0;
2446         last_ch = '\0';
2447         line_pos = p_start;
2448         for (cur_pos = p_start; cur_pos < p_end; cur_pos++) {
2449                 guint space = 0;
2450
2451                 GET_CHAR(cur_pos, cbuf, ch_len);
2452
2453                 if (ch_len < 0) {
2454                         cbuf[0] = '\0';
2455                         ch_len = 1;
2456                 }
2457
2458                 if (ch_len == 1 && isspace(*(guchar *)cbuf))
2459                         space = 1;
2460
2461                 if (ch_len == 1 && *cbuf == '\n') {
2462                         guint replace = 0;
2463                         if (last_ch_len == 1 && !isspace((guchar)last_ch)) {
2464                                 if (cur_pos + 1 < p_end) {
2465                                         GET_CHAR(cur_pos + 1, cbuf, ch_len);
2466                                         if (ch_len == 1 &&
2467                                             !isspace(*(guchar *)cbuf))
2468                                                 replace = 1;
2469                                 }
2470                         }
2471                         gtk_stext_set_point(text, cur_pos + 1);
2472                         gtk_stext_backward_delete(text, 1);
2473                         if (replace) {
2474                                 gtk_stext_set_point(text, cur_pos);
2475                                 gtk_stext_insert(text, NULL, NULL, NULL, " ", 1);
2476                                 space = 1;
2477                         }
2478                         else {
2479                                 p_end--;
2480                                 cur_pos--;
2481                                 continue;
2482                         }
2483                 }
2484
2485                 last_ch_len = ch_len;
2486                 last_ch = *cbuf;
2487
2488                 if (space) {
2489                         line_pos = cur_pos + 1;
2490                         line_len = cur_len + ch_len;
2491                 }
2492
2493                 if (cur_len + DISP_WIDTH(ch_len) > prefs_common.linewrap_len &&
2494                     line_len > 0) {
2495                         gint tlen = ch_len;
2496
2497                         GET_CHAR(line_pos - 1, cbuf, ch_len);
2498                         if (ch_len == 1 && isspace(*(guchar *)cbuf)) {
2499                                 gtk_stext_set_point(text, line_pos);
2500                                 gtk_stext_backward_delete(text, 1);
2501                                 p_end--;
2502                                 cur_pos--;
2503                                 line_pos--;
2504                                 cur_len--;
2505                                 line_len--;
2506                         }
2507                         ch_len = tlen;
2508
2509                         gtk_stext_set_point(text, line_pos);
2510                         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1);
2511                         p_end++;
2512                         cur_pos++;
2513                         line_pos++;
2514                         cur_len = cur_len - line_len + DISP_WIDTH(ch_len);
2515                         line_len = 0;
2516                         continue;
2517                 }
2518
2519                 if (ch_len > 1) {
2520                         line_pos = cur_pos + 1;
2521                         line_len = cur_len + DISP_WIDTH(ch_len);
2522                 }
2523                 cur_len += DISP_WIDTH(ch_len);
2524         }
2525
2526 compose_end:
2527         gtk_stext_thaw(text);
2528 }
2529
2530 #undef WRAP_DEBUG
2531 #ifdef WRAP_DEBUG
2532 /* Darko: used when I debug wrapping */
2533 void dump_text(GtkSText *text, int pos, int tlen, int breakoncr)
2534 {
2535         gint i, clen;
2536         gchar cbuf[MB_LEN_MAX];
2537
2538         printf("%d [", pos);
2539         for (i = pos; i < tlen; i++) {
2540                 GET_CHAR(i, cbuf, clen);
2541                 if (clen < 0) break;
2542                 if (breakoncr && clen == 1 && cbuf[0] == '\n')
2543                         break;
2544                 fwrite(cbuf, clen, 1, stdout);
2545         }
2546         printf("]\n");
2547 }
2548 #endif
2549
2550 typedef enum {
2551         WAIT_FOR_SPACE,
2552         WAIT_FOR_INDENT_CHAR,
2553         WAIT_FOR_INDENT_CHAR_OR_SPACE
2554 } IndentState;
2555
2556 /* return indent length, we allow:
2557    > followed by spaces/tabs
2558    | followed by spaces/tabs
2559    uppercase characters immediately followed by >,
2560    and the repeating sequences of the above */
2561 /* return indent length */
2562 static guint get_indent_length(GtkSText *text, guint start_pos, guint text_len)
2563 {
2564         guint i_len = 0;
2565         guint i, ch_len, alnum_cnt = 0;
2566         IndentState state = WAIT_FOR_INDENT_CHAR;
2567         gchar cbuf[MB_LEN_MAX];
2568         gboolean is_space;
2569         gboolean is_indent;
2570
2571         if (prefs_common.quote_chars == NULL) {
2572                 return 0 ;
2573         }
2574
2575         for (i = start_pos; i < text_len; i++) {
2576                 GET_CHAR(i, cbuf, ch_len);
2577                 if (ch_len > 1)
2578                         break;
2579
2580                 if (cbuf[0] == '\n')
2581                         break;
2582
2583                 is_indent = strchr(prefs_common.quote_chars, cbuf[0]) ? TRUE : FALSE;
2584                 is_space = strchr(SPACE_CHARS, cbuf[0]) ? TRUE : FALSE;
2585
2586                 switch (state) {
2587                 case WAIT_FOR_SPACE:
2588                         if (is_space == FALSE)
2589                                 goto out;
2590                         state = WAIT_FOR_INDENT_CHAR_OR_SPACE;
2591                         break;
2592                 case WAIT_FOR_INDENT_CHAR_OR_SPACE:
2593                         if (is_indent == FALSE && is_space == FALSE &&
2594                             !isupper((guchar)cbuf[0]))
2595                                 goto out;
2596                         if (is_space == TRUE) {
2597                                 alnum_cnt = 0;
2598                                 state = WAIT_FOR_INDENT_CHAR_OR_SPACE;
2599                         } else if (is_indent == TRUE) {
2600                                 alnum_cnt = 0;
2601                                 state = WAIT_FOR_SPACE;
2602                         } else {
2603                                 alnum_cnt++;
2604                                 state = WAIT_FOR_INDENT_CHAR;
2605                         }
2606                         break;
2607                 case WAIT_FOR_INDENT_CHAR:
2608                         if (is_indent == FALSE && !isupper((guchar)cbuf[0]))
2609                                 goto out;
2610                         if (is_indent == TRUE) {
2611                                 if (alnum_cnt > 0 
2612                                     && !strchr(prefs_common.quote_chars, cbuf[0]))
2613                                         goto out;
2614                                 alnum_cnt = 0;
2615                                 state = WAIT_FOR_SPACE;
2616                         } else {
2617                                 alnum_cnt++;
2618                         }
2619                         break;
2620                 }
2621
2622                 i_len++;
2623         }
2624
2625 out:
2626         if ((i_len > 0) && (state == WAIT_FOR_INDENT_CHAR))
2627                 i_len -= alnum_cnt;
2628
2629         return i_len;
2630 }
2631
2632 /* insert quotation string when line was wrapped */
2633 static guint ins_quote(GtkSText *text, guint indent_len,
2634                        guint prev_line_pos, guint text_len,
2635                        gchar *quote_fmt)
2636 {
2637         guint i, ins_len = 0;
2638         gchar ch;
2639
2640         if (indent_len) {
2641                 for (i = 0; i < indent_len; i++) {
2642                         ch = GTK_STEXT_INDEX(text, prev_line_pos + i);
2643                         gtk_stext_insert(text, NULL, NULL, NULL, &ch, 1);
2644                 }
2645                 ins_len = indent_len;
2646         }
2647
2648         return ins_len;
2649 }
2650
2651 /* check if we should join the next line */
2652 static gboolean join_next_line(GtkSText *text, guint start_pos, guint tlen,
2653                                guint prev_ilen, gboolean autowrap)
2654 {
2655         guint indent_len, ch_len;
2656         gboolean do_join = FALSE;
2657         gchar cbuf[MB_LEN_MAX];
2658
2659         indent_len = get_indent_length(text, start_pos, tlen);
2660
2661         if ((autowrap || indent_len > 0) && indent_len == prev_ilen) {
2662                 GET_CHAR(start_pos + indent_len, cbuf, ch_len);
2663                 if (ch_len > 0 && (cbuf[0] != '\n'))
2664                         do_join = TRUE;
2665         }
2666
2667         return do_join;
2668 }
2669
2670 static void compose_wrap_line_all(Compose *compose)
2671 {
2672         compose_wrap_line_all_full(compose, FALSE);
2673 }
2674
2675 #define STEXT_FREEZE() \
2676         if (!frozen) { gtk_stext_freeze(text); frozen = TRUE; }
2677
2678 static void compose_wrap_line_all_full(Compose *compose, gboolean autowrap)
2679 {
2680         GtkSText *text = GTK_STEXT(compose->text);
2681         guint tlen;
2682         guint line_pos = 0, cur_pos = 0, p_pos = 0;
2683         gint line_len = 0, cur_len = 0;
2684         gint ch_len;
2685         gboolean is_new_line = TRUE, do_delete = FALSE;
2686         guint i_len = 0;
2687         gboolean linewrap_quote = prefs_common.linewrap_quote;
2688         gboolean set_editable_pos = FALSE;
2689         gint editable_pos = 0;
2690         gboolean frozen = FALSE;
2691         guint linewrap_len = prefs_common.linewrap_len;
2692         gchar *qfmt = prefs_common.quotemark;
2693         gchar cbuf[MB_LEN_MAX];
2694
2695         tlen = gtk_stext_get_length(text);
2696
2697         for (; cur_pos < tlen; cur_pos++) {
2698                 /* mark position of new line - needed for quotation wrap */
2699                 if (is_new_line) {
2700                         if (linewrap_quote)
2701                                 i_len = get_indent_length(text, cur_pos, tlen);
2702
2703                         is_new_line = FALSE;
2704                         p_pos = cur_pos;
2705 #ifdef WRAP_DEBUG
2706                         g_print("new line i_len=%d p_pos=", i_len);
2707                         dump_text(text, p_pos, tlen, 1);
2708 #endif
2709                 }
2710
2711                 GET_CHAR(cur_pos, cbuf, ch_len);
2712
2713                 /* fix line length for tabs */
2714                 if (ch_len == 1 && *cbuf == '\t') {
2715                         guint tab_width = text->default_tab_width;
2716                         guint tab_offset = line_len % tab_width;
2717
2718 #ifdef WRAP_DEBUG
2719                         g_print("found tab at pos=%d line_len=%d ", cur_pos,
2720                                 line_len);
2721 #endif
2722                         if (tab_offset) {
2723                                 line_len += tab_width - tab_offset - 1;
2724                                 cur_len = line_len;
2725                         }
2726 #ifdef WRAP_DEBUG
2727                         printf("new_len=%d\n", line_len);
2728 #endif
2729                 }
2730
2731                 /* we have encountered line break */
2732                 if (ch_len == 1 && *cbuf == '\n') {
2733                         gint clen;
2734                         gchar cb[MB_LEN_MAX];
2735
2736                         /* should we join the next line */
2737                         if ((autowrap || i_len != cur_len) && do_delete &&
2738                             join_next_line
2739                                 (text, cur_pos + 1, tlen, i_len, autowrap))
2740                                 do_delete = TRUE;
2741                         else
2742                                 do_delete = FALSE;
2743
2744 #ifdef WRAP_DEBUG
2745                         g_print("found CR at %d do_del is %d next line is ",
2746                                cur_pos, do_delete);
2747                         dump_text(text, cur_pos + 1, tlen, 1);
2748 #endif
2749
2750                         /* skip delete if it is continuous URL */
2751                         if (do_delete && (line_pos - p_pos <= i_len) &&
2752                             gtk_stext_is_uri_string(text, line_pos, tlen))
2753                                 do_delete = FALSE;
2754
2755 #ifdef WRAP_DEBUG
2756                         g_print("l_len=%d wrap_len=%d do_del=%d\n",
2757                                 line_len, linewrap_len, do_delete);
2758 #endif
2759                         if (line_len < linewrap_len && do_delete) {
2760                                 STEXT_FREEZE();
2761                                 /* get rid of newline */
2762                                 gtk_stext_set_point(text, cur_pos);
2763                                 gtk_stext_forward_delete(text, 1);
2764                                 tlen--;
2765
2766                                 /* if text starts with quote fmt or with
2767                                    indent string, delete them */
2768                                 if (i_len) {
2769                                         guint ilen;
2770                                         ilen =  gtk_stext_str_compare_n
2771                                                 (text, cur_pos, p_pos, i_len,
2772                                                  tlen);
2773                                         if (ilen) {
2774                                                 gtk_stext_forward_delete
2775                                                         (text, ilen);
2776                                                 tlen -= ilen;
2777                                         }
2778                                 }
2779
2780                                 GET_CHAR(cur_pos, cb, clen);
2781                                 /* insert space between the next line */
2782                                 if (cur_pos > 0) {
2783                                         gint clen_prev;
2784                                         gchar cb_prev[MB_LEN_MAX];
2785
2786                                         GET_CHAR(cur_pos - 1, cb_prev,
2787                                                  clen_prev);
2788                                         if ((clen_prev != clen && clen > 1) ||
2789                                             (clen == 1 &&
2790                                              !isspace((guchar)cb[0]))) {
2791                                                 gtk_stext_insert
2792                                                         (text, NULL, NULL,
2793                                                          NULL, " ", 1);
2794                                                 tlen++;
2795                                         }
2796                                 }
2797
2798                                 /* and start over with current line */
2799                                 cur_pos = p_pos - 1;
2800                                 line_pos = cur_pos;
2801                                 line_len = cur_len = 0;
2802                                 do_delete = FALSE;
2803                                 is_new_line = TRUE;
2804 #ifdef WRAP_DEBUG
2805                                 g_print("after delete l_pos=");
2806                                 dump_text(text, line_pos, tlen, 1);
2807 #endif
2808                                 /* move beginning of line if we are on LF */
2809                                 GET_CHAR(line_pos, cb, clen);
2810                                 if (clen == 1 && *cb == '\n')
2811                                         line_pos++;
2812 #ifdef WRAP_DEBUG
2813                                 g_print("new line_pos=%d\n", line_pos);
2814 #endif
2815
2816                                 continue;
2817                         }
2818
2819                         /* mark new line beginning */
2820                         line_pos = cur_pos + 1;
2821                         line_len = cur_len = 0;
2822                         do_delete = FALSE;
2823                         is_new_line = TRUE;
2824                         continue;
2825                 }
2826
2827                 if (ch_len < 0) {
2828                         cbuf[0] = '\0';
2829                         ch_len = 1;
2830                 }
2831
2832                 /* possible line break */
2833                 if (ch_len == 1 && isspace(*(guchar *)cbuf)) {
2834                         line_pos = cur_pos + 1;
2835                         line_len = cur_len + ch_len;
2836                 }
2837
2838                 /* are we over wrapping length set in preferences ? */
2839                 if (cur_len + DISP_WIDTH(ch_len) > linewrap_len) {
2840                         gint clen;
2841
2842 #ifdef WRAP_DEBUG
2843                         g_print("should wrap cur_pos=%d ", cur_pos);
2844                         dump_text(text, p_pos, tlen, 1);
2845                         dump_text(text, line_pos, tlen, 1);
2846 #endif
2847                         /* force wrapping if it is one long word but not URL */
2848                         if (line_pos - p_pos <= i_len)
2849                                 if (!gtk_stext_is_uri_string
2850                                     (text, line_pos, tlen))
2851                                         line_pos = cur_pos - 1;
2852 #ifdef WRAP_DEBUG
2853                         g_print("new line_pos=%d\n", line_pos);
2854 #endif
2855
2856                         GET_CHAR(line_pos - 1, cbuf, clen);
2857
2858                         /* if next character is space delete it */
2859                         if (clen == 1 && isspace(*(guchar *)cbuf)) {
2860                                 if (p_pos + i_len != line_pos ||
2861                                     !gtk_stext_is_uri_string
2862                                         (text, line_pos, tlen)) {
2863                                         STEXT_FREEZE();
2864                                         /* workaround for correct cursor
2865                                            position */
2866                                         if (set_editable_pos == FALSE) {
2867                                                 editable_pos = gtk_editable_get_position(GTK_EDITABLE(text));
2868                                                 if (editable_pos == line_pos)
2869                                                         set_editable_pos = TRUE;
2870                                         }
2871                                         gtk_stext_set_point(text, line_pos);
2872                                         gtk_stext_backward_delete(text, 1);
2873                                         tlen--;
2874                                         cur_pos--;
2875                                         line_pos--;
2876                                         cur_len--;
2877                                         line_len--;
2878                                 }
2879                         }
2880
2881                         /* if it is URL at beginning of line don't wrap */
2882                         if (p_pos + i_len == line_pos &&
2883                             gtk_stext_is_uri_string(text, line_pos, tlen)) {
2884 #ifdef WRAP_DEBUG
2885                                 g_print("found URL at ");
2886                                 dump_text(text, line_pos, tlen, 1);
2887 #endif
2888                                 continue;
2889                         }
2890
2891                         /* insert CR */
2892                         STEXT_FREEZE();
2893                         gtk_stext_set_point(text, line_pos);
2894                         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1);
2895                         gtk_stext_compact_buffer(text);
2896                         tlen++;
2897                         line_pos++;
2898                         /* for loop will increase it */
2899                         cur_pos = line_pos - 1;
2900                         /* start over with current line */
2901                         is_new_line = TRUE;
2902                         line_len = cur_len = 0;
2903                         if (autowrap || i_len > 0)
2904                                 do_delete = TRUE;
2905                         else
2906                                 do_delete = FALSE;
2907 #ifdef WRAP_DEBUG
2908                         g_print("after CR insert ");
2909                         dump_text(text, line_pos, tlen, 1);
2910                         dump_text(text, cur_pos, tlen, 1);
2911 #endif
2912
2913                         /* should we insert quotation ? */
2914                         if (linewrap_quote && i_len) {
2915                                 /* only if line is not already quoted  */
2916                                 if (!gtk_stext_str_compare
2917                                         (text, line_pos, tlen, qfmt)) {
2918                                         guint ins_len;
2919
2920                                         if (line_pos - p_pos > i_len) {
2921                                                 ins_len = ins_quote
2922                                                         (text, i_len, p_pos,
2923                                                          tlen, qfmt);
2924                                                 tlen += ins_len;
2925                                         }
2926 #ifdef WRAP_DEBUG
2927                                         g_print("after quote insert ");
2928                                         dump_text(text, line_pos, tlen, 1);
2929 #endif
2930                                 }
2931                         }
2932                         continue;
2933                 }
2934
2935                 if (ch_len > 1) {
2936                         line_pos = cur_pos + 1;
2937                         line_len = cur_len + DISP_WIDTH(ch_len);
2938                 }
2939                 /* advance to next character in buffer */
2940                 cur_len += DISP_WIDTH(ch_len);
2941         }
2942
2943         if (frozen)
2944                 gtk_stext_thaw(text);
2945
2946         if (set_editable_pos && editable_pos <= tlen)
2947                 gtk_editable_set_position(GTK_EDITABLE(text), editable_pos);
2948 }
2949
2950 #undef STEXT_FREEZE
2951 #undef GET_CHAR
2952
2953 static void compose_set_title(Compose *compose)
2954 {
2955         gchar *str;
2956         gchar *edited;
2957
2958         edited = compose->modified ? _(" [Edited]") : "";
2959         if (compose->account && compose->account->address)
2960                 str = g_strdup_printf(_("%s - Compose message%s"),
2961                                       compose->account->address, edited);
2962         else
2963                 str = g_strdup_printf(_("Compose message%s"), edited);
2964         gtk_window_set_title(GTK_WINDOW(compose->window), str);
2965         g_free(str);
2966 }
2967
2968 /**
2969  * compose_current_mail_account:
2970  * 
2971  * Find a current mail account (the currently selected account, or the
2972  * default account, if a news account is currently selected).  If a
2973  * mail account cannot be found, display an error message.
2974  * 
2975  * Return value: Mail account, or NULL if not found.
2976  **/
2977 static PrefsAccount *
2978 compose_current_mail_account(void)
2979 {
2980         PrefsAccount *ac;
2981
2982         if (cur_account && cur_account->protocol != A_NNTP)
2983                 ac = cur_account;
2984         else {
2985                 ac = account_get_default();
2986                 if (!ac || ac->protocol == A_NNTP) {
2987                         alertpanel_error(_("Account for sending mail is not specified.\n"
2988                                            "Please select a mail account before sending."));
2989                         return NULL;
2990                 }
2991         }
2992         return ac;
2993 }
2994
2995 static void compose_select_account(Compose *compose, PrefsAccount *account,
2996                                    gboolean init)
2997 {
2998         GtkItemFactory *ifactory;
2999
3000         g_return_if_fail(account != NULL);
3001
3002         compose->account = account;
3003
3004         compose_set_title(compose);
3005
3006         ifactory = gtk_item_factory_from_widget(compose->menubar);
3007 #if 0
3008         if (account->protocol == A_NNTP) {
3009                 gtk_widget_show(compose->newsgroups_hbox);
3010                 gtk_widget_show(compose->newsgroups_entry);
3011                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 2, 4);
3012                 compose->use_newsgroups = TRUE;
3013
3014                 menu_set_active(ifactory, "/View/To", FALSE);
3015                 menu_set_sensitive(ifactory, "/View/To", TRUE);
3016                 menu_set_active(ifactory, "/View/Cc", FALSE);
3017                 menu_set_sensitive(ifactory, "/View/Cc", TRUE);
3018                 menu_set_sensitive(ifactory, "/View/Followup to", TRUE);
3019         } else {
3020                 gtk_widget_hide(compose->newsgroups_hbox);
3021                 gtk_widget_hide(compose->newsgroups_entry);
3022                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 2, 0);
3023                 gtk_widget_queue_resize(compose->table_vbox);
3024                 compose->use_newsgroups = FALSE;
3025
3026                 menu_set_active(ifactory, "/View/To", TRUE);
3027                 menu_set_sensitive(ifactory, "/View/To", FALSE);
3028                 menu_set_active(ifactory, "/View/Cc", TRUE);
3029                 menu_set_sensitive(ifactory, "/View/Cc", FALSE);
3030                 menu_set_active(ifactory, "/View/Followup to", FALSE);
3031                 menu_set_sensitive(ifactory, "/View/Followup to", FALSE);
3032         }
3033
3034         if (account->set_autocc) {
3035                 compose_entry_show(compose, COMPOSE_ENTRY_CC);
3036                 if (account->auto_cc && compose->mode != COMPOSE_REEDIT)
3037                         compose_entry_set(compose, account->auto_cc,
3038                                           COMPOSE_ENTRY_CC);
3039         }
3040         if (account->set_autobcc) {
3041                 compose_entry_show(compose, COMPOSE_ENTRY_BCC);
3042                 if (account->auto_bcc && compose->mode != COMPOSE_REEDIT)
3043                         compose_entry_set(compose, account->auto_bcc,
3044                                           COMPOSE_ENTRY_BCC);
3045         }
3046         if (account->set_autoreplyto) {
3047                 compose_entry_show(compose, COMPOSE_ENTRY_REPLY_TO);
3048                 if (account->auto_replyto && compose->mode != COMPOSE_REEDIT)
3049                         compose_entry_set(compose, account->auto_replyto,
3050                                           COMPOSE_ENTRY_REPLY_TO);
3051         }
3052
3053 #endif
3054
3055         if (account->default_sign && compose->mode != COMPOSE_REDIRECT)
3056                 menu_set_active(ifactory, "/Options/Sign", TRUE);
3057         else
3058                 menu_set_active(ifactory, "/Options/Sign", FALSE);
3059         if (account->default_encrypt && compose->mode != COMPOSE_REDIRECT)
3060                 menu_set_active(ifactory, "/Options/Encrypt", TRUE);
3061         else
3062                 menu_set_active(ifactory, "/Options/Encrypt", FALSE);
3063                                        
3064         activate_privacy_system(compose, account);
3065
3066         if (!init && compose->mode != COMPOSE_REDIRECT)
3067                 compose_insert_sig(compose, TRUE);
3068 }
3069
3070 gboolean compose_check_for_valid_recipient(Compose *compose) {
3071         gchar *recipient_headers_mail[] = {"To:", "Cc:", "Bcc:", NULL};
3072         gchar *recipient_headers_news[] = {"Newsgroups:", NULL};
3073         gboolean recipient_found = FALSE;
3074         GSList *list;
3075         gchar **strptr;
3076
3077         /* free to and newsgroup list */
3078         slist_free_strings(compose->to_list);
3079         g_slist_free(compose->to_list);
3080         compose->to_list = NULL;
3081                         
3082         slist_free_strings(compose->newsgroup_list);
3083         g_slist_free(compose->newsgroup_list);
3084         compose->newsgroup_list = NULL;
3085
3086         /* search header entries for to and newsgroup entries */
3087         for (list = compose->header_list; list; list = list->next) {
3088                 gchar *header;
3089                 gchar *entry;
3090                 header = gtk_editable_get_chars(GTK_EDITABLE(GTK_COMBO(((ComposeHeaderEntry *)list->data)->combo)->entry), 0, -1);
3091                 entry = gtk_editable_get_chars(GTK_EDITABLE(((ComposeHeaderEntry *)list->data)->entry), 0, -1);
3092                 g_strstrip(entry);
3093                 if (entry[0] != '\0') {
3094                         for (strptr = recipient_headers_mail; *strptr != NULL; strptr++) {
3095                                 if (!strcmp(header, (prefs_common.trans_hdr ? gettext(*strptr) : *strptr))) {
3096                                         compose->to_list = address_list_append(compose->to_list, entry);
3097                                         recipient_found = TRUE;
3098                                 }
3099                         }
3100                         for (strptr = recipient_headers_news; *strptr != NULL; strptr++) {
3101                                 if (!strcmp(header, (prefs_common.trans_hdr ? gettext(*strptr) : *strptr))) {
3102                                         compose->newsgroup_list = newsgroup_list_append(compose->newsgroup_list, entry);
3103                                         recipient_found = TRUE;
3104                                 }
3105                         }
3106                 }
3107                 g_free(header);
3108                 g_free(entry);
3109         }
3110         return recipient_found;
3111 }
3112
3113 static gboolean compose_check_entries(Compose *compose, gboolean check_subject)
3114 {
3115         gchar *str;
3116
3117         if (compose_check_for_valid_recipient(compose) == FALSE) {
3118                 alertpanel_error(_("Recipient is not specified."));
3119                 return FALSE;
3120         }
3121
3122         str = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
3123         if (*str == '\0' && check_subject == TRUE) {
3124                 AlertValue aval;
3125
3126                 aval = alertpanel(_("Send"),
3127                                   _("Subject is empty. Send it anyway?"),
3128                                   _("Yes"), _("No"), NULL);
3129                 if (aval != G_ALERTDEFAULT)
3130                         return FALSE;
3131         }
3132
3133         return TRUE;
3134 }
3135
3136 gint compose_send(Compose *compose)
3137 {
3138         gint msgnum;
3139         FolderItem *folder;
3140         gint val = -1;
3141         gchar *msgpath;
3142
3143         compose_allow_user_actions (compose, FALSE);
3144         compose->sending = TRUE;
3145
3146         if (compose_check_entries(compose, TRUE) == FALSE)
3147                 goto bail;
3148
3149         val = compose_queue(compose, &msgnum, &folder);
3150
3151         if (val) {
3152                 alertpanel_error(_("Could not queue message for sending"));
3153                 goto bail;
3154         }
3155
3156
3157         if (prefs_common.send_dialog_mode != SEND_DIALOG_ALWAYS) {
3158                 compose->sending = FALSE;
3159                 compose_close(compose);
3160                 /* No more compose access in the normal codepath 
3161                  * after this point! */
3162         }
3163
3164         if (msgnum == 0) {
3165                 alertpanel_error(_("The message was queued but could not be "
3166                                    "sent.\nUse \"Send queued messages\" from "
3167                                    "the main window to retry."));
3168                 if (prefs_common.send_dialog_mode == SEND_DIALOG_ALWAYS) {
3169                         compose->sending = FALSE;
3170                         compose_allow_user_actions (compose, TRUE);
3171                 }
3172                 return 0;
3173         }
3174         
3175         msgpath = folder_item_fetch_msg(folder, msgnum);
3176         val = procmsg_send_message_queue(msgpath);
3177         g_free(msgpath);
3178
3179         if (prefs_common.send_dialog_mode == SEND_DIALOG_ALWAYS) {
3180                 compose->sending = FALSE;
3181                 compose_allow_user_actions (compose, TRUE);
3182                 if (val != 0) {
3183                         folder_item_remove_msg(folder, msgnum);
3184                         folder_item_scan(folder);
3185                 }
3186         }
3187
3188         if (val == 0) {
3189                 folder_item_remove_msg(folder, msgnum);
3190                 folder_item_scan(folder);
3191                 if (prefs_common.send_dialog_mode == SEND_DIALOG_ALWAYS)
3192                         compose_close(compose);
3193         } else {
3194                 alertpanel_error(_("The message was queued but could not be "
3195                                    "sent.\nUse \"Send queued messages\" from "
3196                                    "the main window to retry."));
3197                 if (prefs_common.send_dialog_mode == SEND_DIALOG_ALWAYS) {
3198                         compose_allow_user_actions (compose, TRUE);
3199                         compose->sending = FALSE;               
3200                 }
3201                 return -1;
3202         }
3203
3204         return 0;
3205
3206 bail:
3207         compose_allow_user_actions (compose, TRUE);
3208         compose->sending = FALSE;
3209
3210         return -1;
3211 }
3212
3213 static gboolean compose_use_attach(Compose *compose) 
3214 {
3215         return gtk_clist_get_row_data(GTK_CLIST(compose->attach_clist), 0) != NULL;
3216 }
3217
3218 static gint compose_redirect_write_headers_from_headerlist(Compose *compose, 
3219                                                            FILE *fp)
3220 {
3221         gchar buf[BUFFSIZE];
3222         gchar *str;
3223         gboolean first_to_address;
3224         gboolean first_cc_address;
3225         GSList *list;
3226         ComposeHeaderEntry *headerentry;
3227         gchar *headerentryname;
3228         gchar *cc_hdr;
3229         gchar *to_hdr;
3230
3231         debug_print("Writing redirect header\n");
3232
3233         cc_hdr = prefs_common.trans_hdr ? _("Cc:") : "Cc:";
3234         to_hdr = prefs_common.trans_hdr ? _("To:") : "To:";
3235
3236         first_to_address = TRUE;
3237         first_cc_address = TRUE;
3238         for (list = compose->header_list; list; list = list->next) {
3239                 headerentry = ((ComposeHeaderEntry *)list->data);
3240                 headerentryname = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry));
3241
3242                 if (g_strcasecmp(headerentryname, cc_hdr) == 0 
3243                    || g_strcasecmp(headerentryname, to_hdr) == 0) {
3244                         str = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
3245                         Xstrdup_a(str, str, return -1);
3246                         g_strstrip(str);
3247                         if (str[0] != '\0') {
3248                                 compose_convert_header
3249                                         (buf, sizeof(buf), str,
3250                                         strlen("Resent-To") + 2, TRUE);
3251                                 if (g_strcasecmp(headerentryname, to_hdr) == 0) {
3252                                         if (first_to_address) {
3253                                                 fprintf(fp, "Resent-To: ");
3254                                                 first_to_address = FALSE;
3255                                         } else {
3256                                                 fprintf(fp, ",");
3257                                         }
3258                                 }
3259                                 if (g_strcasecmp(headerentryname, cc_hdr) == 0) {
3260                                         if (first_cc_address) {
3261                                                 fprintf(fp, "\n");
3262                                                 fprintf(fp, "Resent-Cc: ");
3263                                                 first_cc_address = FALSE;
3264                                         } else {
3265                                                 fprintf(fp, ",");
3266                                         }
3267                                 }
3268                                 
3269                                 fprintf(fp, "%s", buf);
3270                         }
3271                 }
3272         }
3273         /* if (!first_address) { */
3274         fprintf(fp, "\n");
3275         /* } */
3276
3277         return(0);
3278 }
3279
3280 static gint compose_redirect_write_headers(Compose *compose, FILE *fp)
3281 {
3282         gchar buf[BUFFSIZE];
3283         gchar *str;
3284         /* struct utsname utsbuf; */
3285
3286         g_return_val_if_fail(fp != NULL, -1);
3287         g_return_val_if_fail(compose->account != NULL, -1);
3288         g_return_val_if_fail(compose->account->address != NULL, -1);
3289
3290         /* Resent-Date */
3291         get_rfc822_date(buf, sizeof(buf));
3292         fprintf(fp, "Resent-Date: %s\n", buf);
3293
3294         /* Resent-From */
3295         if (compose->account->name && *compose->account->name) {
3296                 compose_convert_header
3297                         (buf, sizeof(buf), compose->account->name,
3298                          strlen("From: "), TRUE);
3299                 fprintf(fp, "Resent-From: %s <%s>\n",
3300                         buf, compose->account->address);
3301         } else
3302                 fprintf(fp, "Resent-From: %s\n", compose->account->address);
3303
3304         /* Subject */
3305         str = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
3306         if (*str != '\0') {
3307                 Xstrdup_a(str, str, return -1);
3308                 g_strstrip(str);
3309                 if (*str != '\0') {
3310                         compose_convert_header(buf, sizeof(buf), str,
3311                                                strlen("Subject: "), FALSE);
3312                         fprintf(fp, "Subject: %s\n", buf);
3313                 }
3314         }
3315
3316         /* Resent-Message-ID */
3317         if (compose->account->gen_msgid) {
3318                 generate_msgid(buf, sizeof(buf));
3319                 fprintf(fp, "Resent-Message-ID: <%s>\n", buf);
3320                 compose->msgid = g_strdup(buf);
3321         }
3322
3323         compose_redirect_write_headers_from_headerlist(compose, fp);
3324
3325         /* separator between header and body */
3326         fputs("\n", fp);
3327
3328         return 0;
3329 }
3330
3331 static gint compose_redirect_write_to_file(Compose *compose, FILE *fdest)
3332 {
3333         FILE *fp;
3334         size_t len;
3335         gchar buf[BUFFSIZE];
3336
3337         if ((fp = fopen(compose->redirect_filename, "rb")) == NULL) {
3338                 FILE_OP_ERROR(compose->redirect_filename, "fopen");
3339                 return -1;
3340         }
3341
3342         while (procheader_get_one_field_asis(buf, sizeof(buf), fp) != -1) {
3343                 /* should filter returnpath, delivered-to */
3344                 if (g_strncasecmp(buf, "Return-Path:",
3345                                    strlen("Return-Path:")) == 0 ||
3346                     g_strncasecmp(buf, "Delivered-To:",
3347                                   strlen("Delivered-To:")) == 0 ||
3348                     g_strncasecmp(buf, "Received:",
3349                                   strlen("Received:")) == 0 ||
3350                     g_strncasecmp(buf, "Subject:",
3351                                   strlen("Subject:")) == 0 ||
3352                     g_strncasecmp(buf, "X-UIDL:",
3353                                   strlen("X-UIDL:")) == 0)
3354                         continue;
3355
3356                 if (fputs(buf, fdest) == -1)
3357                         goto error;
3358
3359                 if (!prefs_common.redirect_keep_from) {
3360                         if (g_strncasecmp(buf, "From:",
3361                                           strlen("From:")) == 0) {
3362                                 fputs(" (by way of ", fdest);
3363                                 if (compose->account->name
3364                                     && *compose->account->name) {
3365                                         compose_convert_header
3366                                                 (buf, sizeof(buf),
3367                                                  compose->account->name,
3368                                                  strlen("From: "),
3369                                                  FALSE);
3370                                         fprintf(fdest, "%s <%s>",
3371                                                 buf,
3372                                                 compose->account->address);
3373                                 } else
3374                                         fprintf(fdest, "%s",
3375                                                 compose->account->address);
3376                                 fputs(")", fdest);
3377                         }
3378                 }
3379
3380                 if (fputs("\n", fdest) == -1)
3381                         goto error;
3382         }
3383
3384         compose_redirect_write_headers(compose, fdest);
3385
3386         while ((len = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
3387                 if (fwrite(buf, sizeof(gchar), len, fdest) != len)
3388                         goto error;
3389         }
3390
3391         fclose(fp);
3392
3393         return 0;
3394 error:
3395         fclose(fp);
3396
3397         return -1;
3398 }
3399
3400 static gint compose_write_to_file(Compose *compose, FILE *fp, gint action)
3401 {
3402         gchar *chars;
3403         gchar *buf;
3404         const gchar *out_codeset;
3405         EncodingType encoding;
3406         MimeInfo *mimemsg, *mimetext;
3407
3408         /* create message MimeInfo */
3409         mimemsg = procmime_mimeinfo_new();
3410         mimemsg->type = MIMETYPE_MESSAGE;
3411         mimemsg->subtype = g_strdup("rfc822");
3412         mimemsg->content = MIMECONTENT_MEM;
3413         mimemsg->data.mem = compose_get_header(compose);
3414
3415         /* Create text part MimeInfo */
3416         /* get all composed text */
3417         chars = gtk_editable_get_chars(GTK_EDITABLE(compose->text), 0, -1);
3418         if (is_ascii_str(chars)) {
3419                 buf = chars;
3420                 chars = NULL;
3421                 out_codeset = CS_US_ASCII;
3422                 encoding = ENC_7BIT;
3423         } else {
3424                 const gchar *src_codeset;
3425
3426                 out_codeset = conv_get_outgoing_charset_str();
3427                 if (!g_strcasecmp(out_codeset, CS_US_ASCII))
3428                         out_codeset = CS_ISO_8859_1;
3429
3430                 if (prefs_common.encoding_method == CTE_BASE64)
3431                         encoding = ENC_BASE64;
3432                 else if (prefs_common.encoding_method == CTE_QUOTED_PRINTABLE)
3433                         encoding = ENC_QUOTED_PRINTABLE;
3434                 else if (prefs_common.encoding_method == CTE_8BIT)
3435                         encoding = ENC_8BIT;
3436                 else
3437                         encoding = procmime_get_encoding_for_charset(out_codeset);
3438
3439                 src_codeset = conv_get_current_charset_str();
3440                 /* if current encoding is US-ASCII, set it the same as
3441                    outgoing one to prevent code conversion failure */
3442                 if (!g_strcasecmp(src_codeset, CS_US_ASCII))
3443                         src_codeset = out_codeset;
3444
3445                 debug_print("src encoding = %s, out encoding = %s, transfer encoding = %s\n",
3446                             src_codeset, out_codeset, procmime_get_encoding_str(encoding));
3447
3448                 if (action == COMPOSE_WRITE_FOR_SEND) {
3449                         buf = conv_codeset_strdup(chars, src_codeset, out_codeset);
3450                         
3451                         if (!buf) {
3452                                 AlertValue aval;
3453                                 gchar *msg;
3454
3455                                 msg = g_strdup_printf(_("Can't convert the character encoding of the message from\n"
3456                                                         "%s to %s.\n"
3457                                                         "Send it anyway?"), src_codeset, out_codeset);
3458                                 aval = alertpanel_with_type
3459                                         (_("Error"), msg, _("Yes"), _("+No"), NULL, NULL, ALERT_ERROR);
3460                                 g_free(msg);
3461
3462                                 if (aval != G_ALERTDEFAULT) {
3463                                         g_free(chars);
3464                                         return -1;
3465                                 } else {
3466                                         buf = chars;
3467                                         out_codeset = src_codeset;
3468                                         chars = NULL;
3469                                 }
3470                         }
3471                 } else {
3472                         buf = chars;
3473                         out_codeset = src_codeset;
3474                         chars = NULL;
3475                 }
3476         }
3477         g_free(chars);
3478
3479         if (encoding == ENC_8BIT || encoding == ENC_7BIT) {
3480                 if (!strncmp(buf, "From ", sizeof("From ")-1) ||
3481                     strstr(buf, "\nFrom ") != NULL) {
3482                         encoding = ENC_QUOTED_PRINTABLE;
3483                 }
3484         }
3485
3486         mimetext = procmime_mimeinfo_new();
3487         mimetext->content = MIMECONTENT_MEM;
3488         mimetext->data.mem = buf;
3489         mimetext->type = MIMETYPE_TEXT;
3490         mimetext->subtype = g_strdup("plain");
3491         g_hash_table_insert(mimetext->typeparameters, g_strdup("charset"),
3492                             g_strdup(out_codeset));
3493         /* protect trailing spaces when signing message */
3494         if (action == COMPOSE_WRITE_FOR_SEND && compose->use_signing && 
3495             privacy_system_can_sign(compose->privacy_system))
3496                 if (encoding == ENC_7BIT)
3497                         encoding = ENC_QUOTED_PRINTABLE;
3498                 else if (encoding == ENC_8BIT)
3499                         encoding = ENC_BASE64;
3500         if (encoding != ENC_UNKNOWN)
3501                 procmime_encode_content(mimetext, encoding);
3502
3503         /* append attachment parts */
3504         if (compose_use_attach(compose)) {
3505                 MimeInfo *mimempart;
3506
3507                 mimempart = procmime_mimeinfo_new();
3508                 mimempart->content = MIMECONTENT_EMPTY;
3509                 mimempart->type = MIMETYPE_MULTIPART;
3510                 mimempart->subtype = g_strdup("mixed");
3511                 g_hash_table_insert(mimempart->typeparameters, g_strdup("boundary"),
3512                                     generate_mime_boundary(NULL));
3513
3514                 mimetext->disposition = DISPOSITIONTYPE_INLINE;
3515
3516                 g_node_append(mimempart->node, mimetext->node);
3517                 g_node_append(mimemsg->node, mimempart->node);
3518
3519                 compose_add_attachments(compose, mimempart);
3520         } else
3521                 g_node_append(mimemsg->node, mimetext->node);
3522
3523         /* sign message if sending */
3524         if (action == COMPOSE_WRITE_FOR_SEND && compose->use_signing && 
3525             privacy_system_can_sign(compose->privacy_system))
3526                 if (!privacy_sign(compose->privacy_system, mimemsg, compose->account))
3527                         return -1;
3528
3529         procmime_write_mimeinfo(mimemsg, fp);
3530         
3531         procmime_mimeinfo_free_all(mimemsg);
3532
3533         return 0;
3534 }
3535
3536 static gint compose_write_body_to_file(Compose *compose, const gchar *file)
3537 {
3538         FILE *fp;
3539         size_t len;
3540         gchar *chars;
3541
3542         if ((fp = fopen(file, "wb")) == NULL) {
3543                 FILE_OP_ERROR(file, "fopen");
3544                 return -1;
3545         }
3546
3547         /* chmod for security */
3548         if (change_file_mode_rw(fp, file) < 0) {
3549                 FILE_OP_ERROR(file, "chmod");
3550                 g_warning("can't change file mode\n");
3551         }
3552
3553         chars = gtk_editable_get_chars(GTK_EDITABLE(compose->text), 0, -1);
3554
3555         /* write body */
3556         len = strlen(chars);
3557         if (fwrite(chars, sizeof(gchar), len, fp) != len) {
3558                 FILE_OP_ERROR(file, "fwrite");
3559                 g_free(chars);
3560                 fclose(fp);
3561                 unlink(file);
3562                 return -1;
3563         }
3564
3565         g_free(chars);
3566
3567         if (fclose(fp) == EOF) {
3568                 FILE_OP_ERROR(file, "fclose");
3569                 unlink(file);
3570                 return -1;
3571         }
3572         return 0;
3573 }
3574
3575 static gint compose_remove_reedit_target(Compose *compose)
3576 {
3577         FolderItem *item;
3578         MsgInfo *msginfo = compose->targetinfo;
3579
3580         g_return_val_if_fail(compose->mode == COMPOSE_REEDIT, -1);
3581         if (!msginfo) return -1;
3582
3583         item = msginfo->folder;
3584         g_return_val_if_fail(item != NULL, -1);
3585
3586         if (procmsg_msg_exist(msginfo) &&
3587             (item->stype == F_DRAFT || item->stype == F_QUEUE 
3588              || msginfo == compose->autosaved_draft)) {
3589                 if (folder_item_remove_msg(item, msginfo->msgnum) < 0) {
3590                         g_warning("can't remove the old message\n");
3591                         return -1;
3592                 }
3593         }
3594
3595         return 0;
3596 }
3597
3598 void compose_remove_draft(Compose *compose)
3599 {
3600         FolderItem *drafts;
3601         MsgInfo *msginfo = compose->targetinfo;
3602         drafts = account_get_special_folder(compose->account, F_DRAFT);
3603
3604         if (procmsg_msg_exist(msginfo)) {
3605                 folder_item_remove_msg(drafts, msginfo->msgnum);
3606         }
3607
3608 }
3609
3610 static gint compose_queue(Compose *compose, gint *msgnum, FolderItem **item)
3611 {
3612         return compose_queue_sub (compose, msgnum, item, FALSE);
3613 }
3614 static gint compose_queue_sub(Compose *compose, gint *msgnum, FolderItem **item, gboolean check_subject)
3615 {
3616         FolderItem *queue;
3617         gchar *tmp;
3618         FILE *fp;
3619         GSList *cur;
3620         gint num;
3621         static gboolean lock = FALSE;
3622         PrefsAccount *mailac = NULL, *newsac = NULL;
3623         
3624         debug_print("queueing message...\n");
3625         g_return_val_if_fail(compose->account != NULL, -1);
3626
3627         lock = TRUE;
3628         
3629         if (compose_check_entries(compose, check_subject) == FALSE) {
3630                 lock = FALSE;
3631                 return -1;
3632         }
3633
3634         if (!compose->to_list && !compose->newsgroup_list) {
3635                 g_warning("can't get recipient list.");
3636                 lock = FALSE;
3637                 return -1;
3638         }
3639
3640         if (compose->to_list) {
3641                 if (compose->account->protocol != A_NNTP)
3642                         mailac = compose->account;
3643                 else if (cur_account && cur_account->protocol != A_NNTP)
3644                         mailac = cur_account;
3645                 else if (!(mailac = compose_current_mail_account())) {
3646                         lock = FALSE;
3647                         alertpanel_error(_("No account for sending mails available!"));
3648                         return -1;
3649                 }
3650         }
3651
3652         if (compose->newsgroup_list) {
3653                 if (compose->account->protocol == A_NNTP)
3654                         newsac = compose->account;
3655                 else if (!newsac->protocol != A_NNTP) {
3656                         lock = FALSE;
3657                         alertpanel_error(_("No account for posting news available!"));
3658                         return -1;
3659                 }                       
3660         }
3661
3662         if (prefs_common.linewrap_at_send)
3663                 compose_wrap_line_all(compose);
3664
3665         /* write queue header */
3666         tmp = g_strdup_printf("%s%cqueue.%p", get_tmp_dir(),
3667                               G_DIR_SEPARATOR, compose);
3668         if ((fp = fopen(tmp, "wb")) == NULL) {
3669                 FILE_OP_ERROR(tmp, "fopen");
3670                 g_free(tmp);
3671                 return -1;
3672         }
3673
3674         if (change_file_mode_rw(fp, tmp) < 0) {
3675                 FILE_OP_ERROR(tmp, "chmod");
3676                 g_warning("can't change file mode\n");
3677         }
3678
3679         /* queueing variables */
3680         fprintf(fp, "AF:\n");
3681         fprintf(fp, "NF:0\n");
3682         fprintf(fp, "PS:10\n");
3683         fprintf(fp, "SRH:1\n");
3684         fprintf(fp, "SFN:\n");
3685         fprintf(fp, "DSR:\n");
3686         if (compose->msgid)
3687                 fprintf(fp, "MID:<%s>\n", compose->msgid);
3688         else
3689                 fprintf(fp, "MID:\n");
3690         fprintf(fp, "CFG:\n");
3691         fprintf(fp, "PT:0\n");
3692         fprintf(fp, "S:%s\n", compose->account->address);
3693         fprintf(fp, "RQ:\n");
3694         if (mailac)
3695                 fprintf(fp, "SSV:%s\n", mailac->smtp_server);
3696         else
3697                 fprintf(fp, "SSV:\n");
3698         if (newsac)
3699                 fprintf(fp, "NSV:%s\n", newsac->nntp_server);
3700         else
3701                 fprintf(fp, "NSV:\n");
3702         fprintf(fp, "SSH:\n");
3703         /* write recepient list */
3704         if (compose->to_list) {
3705                 fprintf(fp, "R:<%s>", (gchar *)compose->to_list->data);
3706                 for (cur = compose->to_list->next; cur != NULL;
3707                      cur = cur->next)
3708                         fprintf(fp, ",<%s>", (gchar *)cur->data);
3709                 fprintf(fp, "\n");
3710         }
3711         /* write newsgroup list */
3712         if (compose->newsgroup_list) {
3713                 fprintf(fp, "NG:");
3714                 fprintf(fp, "%s", (gchar *)compose->newsgroup_list->data);
3715                 for (cur = compose->newsgroup_list->next; cur != NULL; cur = cur->next)
3716                         fprintf(fp, ",%s", (gchar *)cur->data);
3717                 fprintf(fp, "\n");
3718         }
3719         /* Sylpheed account IDs */
3720         if (mailac)
3721                 fprintf(fp, "MAID:%d\n", mailac->account_id);
3722         if (newsac)
3723                 fprintf(fp, "NAID:%d\n", newsac->account_id);
3724
3725         if (compose->privacy_system != NULL) {
3726                 fprintf(fp, "X-Sylpheed-Privacy-System:%s\n", compose->privacy_system);
3727                 fprintf(fp, "X-Sylpheed-Sign:%d\n", compose->use_signing);
3728                 fprintf(fp, "X-Sylpheed-Encrypt:%d\n", compose->use_encryption);
3729                 if (compose->use_encryption) {
3730                         gchar *encdata;
3731
3732                         encdata = privacy_get_encrypt_data(compose->privacy_system, compose->to_list);
3733                         if (encdata != NULL)
3734                                 fprintf(fp, "X-Sylpheed-Encrypt-Data:%s\n", 
3735                                         encdata);
3736                         g_free(encdata);
3737                 }
3738         }
3739
3740         /* Save copy folder */
3741         if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn))) {
3742                 gchar *savefolderid;
3743                 
3744                 savefolderid = gtk_editable_get_chars(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
3745                 fprintf(fp, "SCF:%s\n", savefolderid);
3746                 g_free(savefolderid);
3747         }
3748         /* Message-ID of message replying to */
3749         if ((compose->replyinfo != NULL) && (compose->replyinfo->msgid != NULL)) {
3750                 gchar *folderid;
3751                 
3752                 folderid = folder_item_get_identifier(compose->replyinfo->folder);
3753                 fprintf(fp, "RMID:%s\x7f%d\x7f%s\n", folderid, compose->replyinfo->msgnum, compose->replyinfo->msgid);
3754                 g_free(folderid);
3755         }
3756         /* Message-ID of message forwarding to */
3757         if ((compose->fwdinfo != NULL) && (compose->fwdinfo->msgid != NULL)) {
3758                 gchar *folderid;
3759                 
3760                 folderid = folder_item_get_identifier(compose->fwdinfo->folder);
3761                 fprintf(fp, "FMID:%s\x7f%d\x7f%s\n", folderid, compose->fwdinfo->msgnum, compose->fwdinfo->msgid);
3762                 g_free(folderid);
3763         }
3764         fprintf(fp, "\n");
3765
3766         if (compose->redirect_filename != NULL) {
3767                 if (compose_redirect_write_to_file(compose, fp) < 0) {
3768                         lock = FALSE;
3769                         fclose(fp);
3770                         unlink(tmp);
3771                         g_free(tmp);
3772                         return -1;
3773                 }
3774         } else {
3775                 if (compose_write_to_file(compose, fp, COMPOSE_WRITE_FOR_SEND) < 0) {
3776                         lock = FALSE;
3777                         fclose(fp);
3778                         unlink(tmp);
3779                         g_free(tmp);
3780                         return -1;
3781                 }
3782         }
3783
3784         if (fclose(fp) == EOF) {
3785                 FILE_OP_ERROR(tmp, "fclose");
3786                 unlink(tmp);
3787                 g_free(tmp);
3788                 return -1;
3789         }
3790
3791         queue = account_get_special_folder(compose->account, F_QUEUE);
3792         if (!queue) {
3793                 g_warning("can't find queue folder\n");
3794                 unlink(tmp);
3795                 g_free(tmp);
3796                 return -1;
3797         }
3798         folder_item_scan(queue);
3799         if ((num = folder_item_add_msg(queue, tmp, NULL, TRUE)) < 0) {
3800                 g_warning("can't queue the message\n");
3801                 unlink(tmp);
3802                 g_free(tmp);
3803                 return -1;
3804         }
3805         unlink(tmp);
3806         g_free(tmp);
3807
3808         if (compose->mode == COMPOSE_REEDIT) {
3809                 compose_remove_reedit_target(compose);
3810         }
3811
3812         if ((msgnum != NULL) && (item != NULL)) {
3813                 *msgnum = num;
3814                 *item = queue;
3815         }
3816
3817         return 0;
3818 }
3819
3820 static void compose_add_attachments(Compose *compose, MimeInfo *parent)
3821 {
3822         AttachInfo *ainfo;
3823         GtkCList *clist = GTK_CLIST(compose->attach_clist);
3824         gint row;
3825         MimeInfo *mimepart;
3826         struct stat statbuf;
3827         gchar *type, *subtype;
3828
3829         for (row = 0; (ainfo = gtk_clist_get_row_data(clist, row)) != NULL;
3830              row++) {
3831                 mimepart = procmime_mimeinfo_new();
3832                 mimepart->content = MIMECONTENT_FILE;
3833                 mimepart->data.filename = g_strdup(ainfo->file);
3834                 mimepart->offset = 0;
3835
3836                 stat(ainfo->file, &statbuf);
3837                 mimepart->length = statbuf.st_size;
3838
3839                 type = g_strdup(ainfo->content_type);
3840
3841                 if (!strchr(type, '/')) {
3842                         g_free(type);
3843                         type = g_strdup("application/octet-stream");
3844                 }
3845
3846                 subtype = strchr(type, '/') + 1;
3847                 *(subtype - 1) = '\0';
3848                 mimepart->type = procmime_get_media_type(type);
3849                 mimepart->subtype = g_strdup(subtype);
3850                 g_free(type);
3851
3852                 if (mimepart->type == MIMETYPE_MESSAGE && 
3853                     !g_strcasecmp(mimepart->subtype, "rfc822")) {
3854                         mimepart->disposition = DISPOSITIONTYPE_INLINE;
3855                 } else {
3856                         g_hash_table_insert(mimepart->typeparameters,
3857                                             g_strdup("name"), g_strdup(ainfo->name));
3858                         g_hash_table_insert(mimepart->dispositionparameters,
3859                                             g_strdup("filename"), g_strdup(ainfo->name));
3860                         mimepart->disposition = DISPOSITIONTYPE_ATTACHMENT;
3861                 }
3862
3863                 if (compose->use_signing) {
3864                         if (ainfo->encoding == ENC_7BIT)
3865                                 ainfo->encoding = ENC_QUOTED_PRINTABLE;
3866                         else if (ainfo->encoding == ENC_8BIT)
3867                                 ainfo->encoding = ENC_BASE64;
3868                 }
3869                 
3870                 procmime_encode_content(mimepart, ainfo->encoding);
3871
3872                 g_node_append(parent->node, mimepart->node);
3873         }
3874 }
3875
3876 #define QUOTE_IF_REQUIRED(out, str)                                     \
3877 {                                                                       \
3878         if (*str != '"' && strpbrk(str, ",.[]<>")) {                    \
3879                 gchar *__tmp;                                           \
3880                 gint len;                                               \
3881                                                                         \
3882                 len = strlen(str) + 3;                                  \
3883                 if ((__tmp = alloca(len)) == NULL) {                    \
3884                         g_warning("can't allocate memory\n");           \
3885                         g_string_free(header, TRUE);                    \
3886                         return NULL;                                    \
3887                 }                                                       \
3888                 g_snprintf(__tmp, len, "\"%s\"", str);                  \
3889                 out = __tmp;                                            \
3890         } else {                                                        \
3891                 gchar *__tmp;                                           \
3892                                                                         \
3893                 if ((__tmp = alloca(strlen(str) + 1)) == NULL) {        \
3894                         g_warning("can't allocate memory\n");           \
3895                         g_string_free(header, TRUE);                    \
3896                         return NULL;                                    \
3897                 } else                                                  \
3898                         strcpy(__tmp, str);                             \
3899                                                                         \
3900                 out = __tmp;                                            \
3901         }                                                               \
3902 }
3903
3904 #define IS_IN_CUSTOM_HEADER(header) \
3905         (compose->account->add_customhdr && \
3906          custom_header_find(compose->account->customhdr_list, header) != NULL)
3907
3908 static void compose_add_headerfield_from_headerlist(Compose *compose, 
3909                                                     GString *header, 
3910                                                     const gchar *fieldname,
3911                                                     const gchar *seperator)
3912 {
3913         gchar *str, *fieldname_w_colon, *trans_fieldname;
3914         gboolean add_field = FALSE;
3915         GSList *list;
3916         ComposeHeaderEntry *headerentry;
3917         gchar * headerentryname;
3918         GString *fieldstr;
3919
3920         if (IS_IN_CUSTOM_HEADER(fieldname))
3921                 return;
3922
3923         debug_print("Adding %s-fields\n", fieldname);
3924
3925         fieldstr = g_string_sized_new(64);
3926
3927         fieldname_w_colon = g_strconcat(fieldname, ":", NULL);
3928         trans_fieldname = (prefs_common.trans_hdr ? gettext(fieldname_w_colon) : fieldname_w_colon);
3929
3930         for (list = compose->header_list; list; list = list->next) {
3931                 headerentry = ((ComposeHeaderEntry *)list->data);
3932                 headerentryname = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry));
3933
3934                 if (!g_strcasecmp(trans_fieldname, headerentryname)) {
3935                         str = gtk_editable_get_chars(GTK_EDITABLE(headerentry->entry), 0, -1);
3936                         g_strstrip(str);
3937                         if (str[0] != '\0') {
3938                                 if (add_field)
3939                                         g_string_append(fieldstr, seperator);
3940                                 g_string_append(fieldstr, str);
3941                                 add_field = TRUE;
3942                         }
3943                         g_free(str);
3944                 }
3945         }
3946         if (add_field) {
3947                 gchar *buf;
3948
3949                 buf = g_new0(gchar, fieldstr->len * 4 + 256);
3950                 compose_convert_header
3951                         (buf, fieldstr->len * 4  + 256, fieldstr->str,
3952                         strlen(fieldname) + 2, TRUE);
3953                 g_string_sprintfa(header, "%s: %s\n", fieldname, buf);
3954                 g_free(buf);
3955         }
3956
3957         g_free(fieldname_w_colon);
3958         g_string_free(fieldstr, TRUE);
3959
3960         return;
3961 }
3962
3963 static gchar *compose_get_header(Compose *compose)
3964 {
3965         gchar buf[BUFFSIZE];
3966         gchar *str;
3967         gchar *name;
3968         GSList *list;
3969         gchar *std_headers[] = {"To:", "Cc:", "Bcc:", "Newsgroups:", "Reply-To:", "Followup-To:", NULL};
3970         GString *header;
3971
3972         /* struct utsname utsbuf; */
3973
3974         g_return_val_if_fail(compose->account != NULL, NULL);
3975         g_return_val_if_fail(compose->account->address != NULL, NULL);
3976
3977         header = g_string_sized_new(64);
3978
3979         /* Date */
3980         if (compose->account->add_date) {
3981                 get_rfc822_date(buf, sizeof(buf));
3982                 g_string_sprintfa(header, "Date: %s\n", buf);
3983         }
3984
3985         /* From */
3986         if (compose->account->name && *compose->account->name) {
3987                 compose_convert_header
3988                         (buf, sizeof(buf), compose->account->name,
3989                          strlen("From: "), TRUE);
3990                 QUOTE_IF_REQUIRED(name, buf);
3991                 g_string_sprintfa(header, "From: %s <%s>\n",
3992                         name, compose->account->address);
3993         } else
3994                 g_string_sprintfa(header, "From: %s\n", compose->account->address);
3995         
3996         /* To */
3997         compose_add_headerfield_from_headerlist(compose, header, "To", ", ");
3998
3999         /* Newsgroups */
4000         compose_add_headerfield_from_headerlist(compose, header, "Newsgroups", ",");
4001
4002         /* Cc */
4003         compose_add_headerfield_from_headerlist(compose, header, "Cc", ", ");
4004
4005         /* Bcc */
4006         compose_add_headerfield_from_headerlist(compose, header, "Bcc", ", ");
4007
4008         /* Subject */
4009         str = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
4010         if (*str != '\0' && !IS_IN_CUSTOM_HEADER("Subject")) {
4011                 gchar *tmpstr;
4012
4013                 tmpstr = g_strdup(str);
4014                 if (tmpstr == NULL) {
4015                         g_string_free(header, TRUE);
4016                         return NULL;
4017                 }
4018                 g_strstrip(str);
4019                 if (*str != '\0') {
4020                         compose_convert_header(buf, sizeof(buf), str,
4021                                                strlen("Subject: "), FALSE);
4022                         g_string_sprintfa(header, "Subject: %s\n", buf);
4023                 }
4024                 g_free(tmpstr);
4025         }
4026
4027         /* Message-ID */
4028         if (compose->account->gen_msgid) {
4029                 generate_msgid(buf, sizeof(buf));
4030                 g_string_sprintfa(header, "Message-ID: <%s>\n", buf);
4031                 compose->msgid = g_strdup(buf);
4032         }
4033
4034         if (compose->remove_references == FALSE) {
4035                 /* In-Reply-To */
4036                 if (compose->inreplyto && compose->to_list)
4037                         g_string_sprintfa(header, "In-Reply-To: <%s>\n", compose->inreplyto);
4038         
4039                 /* References */
4040                 if (compose->references)
4041                         g_string_sprintfa(header, "References: %s\n", compose->references);
4042         }
4043
4044         /* Followup-To */
4045         compose_add_headerfield_from_headerlist(compose, header, "Followup-To", ",");
4046
4047         /* Reply-To */
4048         compose_add_headerfield_from_headerlist(compose, header, "Reply-To", ", ");
4049
4050         /* Organization */
4051         if (compose->account->organization &&
4052             !IS_IN_CUSTOM_HEADER("Organization")) {
4053                 compose_convert_header(buf, sizeof(buf),
4054                                        compose->account->organization,
4055                                        strlen("Organization: "), FALSE);
4056                 g_string_sprintfa(header, "Organization: %s\n", buf);
4057         }
4058
4059         /* Program version and system info */
4060         /* uname(&utsbuf); */
4061         if (g_slist_length(compose->to_list) && !IS_IN_CUSTOM_HEADER("X-Mailer") &&
4062             !compose->newsgroup_list) {
4063                 g_string_sprintfa(header, "X-Mailer: %s (GTK+ %d.%d.%d; %s)\n",
4064                         prog_version,
4065                         gtk_major_version, gtk_minor_version, gtk_micro_version,
4066                         TARGET_ALIAS);
4067                         /* utsbuf.sysname, utsbuf.release, utsbuf.machine); */
4068         }
4069         if (g_slist_length(compose->newsgroup_list) && !IS_IN_CUSTOM_HEADER("X-Newsreader")) {
4070                 g_string_sprintfa(header, "X-Newsreader: %s (GTK+ %d.%d.%d; %s)\n",
4071                         prog_version,
4072                         gtk_major_version, gtk_minor_version, gtk_micro_version,
4073                         TARGET_ALIAS);
4074                         /* utsbuf.sysname, utsbuf.release, utsbuf.machine); */
4075         }
4076
4077         /* custom headers */
4078         if (compose->account->add_customhdr) {
4079                 GSList *cur;
4080
4081                 for (cur = compose->account->customhdr_list; cur != NULL;
4082                      cur = cur->next) {
4083                         CustomHeader *chdr = (CustomHeader *)cur->data;
4084
4085                         if (custom_header_is_allowed(chdr->name)) {
4086                                 compose_convert_header
4087                                         (buf, sizeof(buf),
4088                                          chdr->value ? chdr->value : "",
4089                                          strlen(chdr->name) + 2, FALSE);
4090                                 g_string_sprintfa(header, "%s: %s\n", chdr->name, buf);
4091                         }
4092                 }
4093         }
4094
4095         /* PRIORITY */
4096         switch (compose->priority) {
4097                 case PRIORITY_HIGHEST: g_string_sprintfa(header, "Importance: high\n"
4098                                                    "X-Priority: 1 (Highest)\n");
4099                         break;
4100                 case PRIORITY_HIGH: g_string_sprintfa(header, "Importance: high\n"
4101                                                 "X-Priority: 2 (High)\n");
4102                         break;
4103                 case PRIORITY_NORMAL: break;
4104                 case PRIORITY_LOW: g_string_sprintfa(header, "Importance: low\n"
4105                                                "X-Priority: 4 (Low)\n");
4106                         break;
4107                 case PRIORITY_LOWEST: g_string_sprintfa(header, "Importance: low\n"
4108                                                   "X-Priority: 5 (Lowest)\n");
4109                         break;
4110                 default: debug_print("compose: priority unknown : %d\n",
4111                                      compose->priority);
4112         }
4113
4114         /* Request Return Receipt */
4115         if (!IS_IN_CUSTOM_HEADER("Disposition-Notification-To")) {
4116                 if (compose->return_receipt) {
4117                         if (compose->account->name
4118                             && *compose->account->name) {
4119                                 compose_convert_header(buf, sizeof(buf), 
4120                                                        compose->account->name, 
4121                                                        strlen("Disposition-Notification-To: "),
4122                                                        TRUE);
4123                                 g_string_sprintfa(header, "Disposition-Notification-To: %s <%s>\n", buf, compose->account->address);
4124                         } else
4125                                 g_string_sprintfa(header, "Disposition-Notification-To: %s\n", compose->account->address);
4126                 }
4127         }
4128
4129         /* get special headers */
4130         for (list = compose->header_list; list; list = list->next) {
4131                 ComposeHeaderEntry *headerentry;
4132                 gchar *tmp;
4133                 gchar *headername;
4134                 gchar *headername_wcolon;
4135                 gchar *headername_trans;
4136                 gchar *headervalue;
4137                 gchar **string;
4138                 gboolean standard_header = FALSE;
4139
4140                 headerentry = ((ComposeHeaderEntry *)list->data);
4141                 
4142                 tmp = g_strdup(gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry)));
4143                 if (strchr(tmp, ' ') != NULL || strchr(tmp, '\r') != NULL || strchr(tmp, '\n') != NULL) {
4144                         g_free(tmp);
4145                         continue;
4146                 }
4147
4148                 if (!strstr(tmp, ":")) {
4149                         headername_wcolon = g_strconcat(tmp, ":", NULL);
4150                         headername = g_strdup(tmp);
4151                 } else {
4152                         headername_wcolon = g_strdup(tmp);
4153                         headername = g_strdup(strtok(tmp, ":"));
4154                 }
4155                 g_free(tmp);
4156                 
4157                 headervalue = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
4158                 subst_char(headervalue, '\r', ' ');
4159                 subst_char(headervalue, '\n', ' ');
4160                 string = std_headers;
4161                 while (*string != NULL) {
4162                         headername_trans = prefs_common.trans_hdr ? gettext(*string) : *string;
4163                         if (!strcmp(headername_trans,headername_wcolon))
4164                                 standard_header = TRUE;
4165                         string++;
4166                 }
4167                 if (!standard_header && !IS_IN_CUSTOM_HEADER(headername))
4168                         g_string_sprintfa(header, "%s %s\n", headername_wcolon, headervalue);
4169                                 
4170                 g_free(headername);
4171                 g_free(headername_wcolon);              
4172         }
4173
4174         str = header->str;
4175         g_string_free(header, FALSE);
4176
4177         return str;
4178 }
4179
4180 #undef IS_IN_CUSTOM_HEADER
4181
4182 static void compose_convert_header(gchar *dest, gint len, gchar *src,
4183                                    gint header_len, gboolean addr_field)
4184 {
4185         g_return_if_fail(src != NULL);
4186         g_return_if_fail(dest != NULL);
4187
4188         if (len < 1) return;
4189
4190         subst_char(src, '\n', ' ');
4191         subst_char(src, '\r', ' ');
4192         g_strchomp(src);
4193
4194         conv_encode_header(dest, len, src, header_len, addr_field);
4195 }
4196
4197 static void compose_create_header_entry(Compose *compose) 
4198 {
4199         gchar *headers[] = {"To:", "Cc:", "Bcc:", "Newsgroups:", "Reply-To:", "Followup-To:", NULL};
4200
4201         GtkWidget *combo;
4202         GtkWidget *entry;
4203         GList *combo_list = NULL;
4204         gchar **string, *header = NULL;
4205         ComposeHeaderEntry *headerentry;
4206         gboolean standard_header = FALSE;
4207
4208         headerentry = g_new0(ComposeHeaderEntry, 1);
4209
4210         /* Combo box */
4211         combo = gtk_combo_new();
4212         string = headers; 
4213         while(*string != NULL) {
4214                 combo_list = g_list_append(combo_list, (prefs_common.trans_hdr ? gettext(*string) : *string));
4215                 string++;
4216         }
4217         gtk_combo_set_popdown_strings(GTK_COMBO(combo), combo_list);
4218         g_list_free(combo_list);
4219         gtk_editable_set_editable(GTK_EDITABLE(GTK_COMBO(combo)->entry), TRUE);
4220         gtk_widget_show(combo);
4221         gtk_table_attach(GTK_TABLE(compose->header_table), combo, 0, 1, compose->header_nextrow, compose->header_nextrow+1, GTK_SHRINK, GTK_FILL, 0, 0);
4222         if (compose->header_last) {     
4223                 gchar *last_header_entry = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry));
4224                 string = headers;
4225                 while (*string != NULL) {
4226                         if (!strcmp(*string, last_header_entry))
4227                                 standard_header = TRUE;
4228                         string++;
4229                 }
4230                 if (standard_header)
4231                         header = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry));
4232         }
4233         if (!compose->header_last || !standard_header) {
4234                 switch(compose->account->protocol) {
4235                         case A_NNTP:
4236                                 header = prefs_common.trans_hdr ? _("Newsgroups:") : "Newsgroups:";
4237                                 break;
4238                         default:
4239                                 header = prefs_common.trans_hdr ? _("To:") : "To:";
4240                                 break;
4241                 }                                                                   
4242         }
4243         if (header)
4244                 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(combo)->entry), header);
4245
4246         /* Entry field */
4247         entry = gtk_entry_new(); 
4248         gtk_widget_show(entry);
4249         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);
4250
4251         gtk_signal_connect(GTK_OBJECT(entry), "key-press-event", GTK_SIGNAL_FUNC(compose_headerentry_key_press_event_cb), headerentry);
4252         gtk_signal_connect(GTK_OBJECT(entry), "changed", GTK_SIGNAL_FUNC(compose_headerentry_changed_cb), headerentry);
4253         gtk_signal_connect(GTK_OBJECT(entry), "activate", GTK_SIGNAL_FUNC(text_activated), compose);
4254         gtk_signal_connect(GTK_OBJECT(entry), "button-press-event", 
4255                            GTK_SIGNAL_FUNC(compose_headerentry_button_pressed),
4256                            NULL);
4257
4258         address_completion_register_entry(GTK_ENTRY(entry));
4259
4260         headerentry->compose = compose;
4261         headerentry->combo = combo;
4262         headerentry->entry = entry;
4263         headerentry->headernum = compose->header_nextrow;
4264
4265         compose->header_nextrow++;
4266         compose->header_last = headerentry;
4267 }
4268
4269 static void compose_add_header_entry(Compose *compose, gchar *header, gchar *text) 
4270 {
4271         ComposeHeaderEntry *last_header;
4272         
4273         last_header = compose->header_last;
4274         
4275         gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(last_header->combo)->entry), header);
4276         gtk_entry_set_text(GTK_ENTRY(last_header->entry), text);
4277 }
4278
4279 static GtkWidget *compose_create_header(Compose *compose) 
4280 {
4281         GtkWidget *label;
4282         GtkWidget *hbox;
4283         GtkWidget *from_optmenu_hbox;
4284 #if 0 /* NEW COMPOSE GUI */
4285         GtkWidget *to_entry;
4286         GtkWidget *to_hbox;
4287         GtkWidget *newsgroups_entry;
4288         GtkWidget *newsgroups_hbox;
4289 #endif
4290         GtkWidget *header_scrolledwin;
4291         GtkWidget *header_table;
4292 #if 0 /* NEW COMPOSE GUI */
4293         GtkWidget *cc_entry;
4294         GtkWidget *cc_hbox;
4295         GtkWidget *bcc_entry;
4296         GtkWidget *bcc_hbox;
4297         GtkWidget *reply_entry;
4298         GtkWidget *reply_hbox;
4299         GtkWidget *followup_entry;
4300         GtkWidget *followup_hbox;
4301 #endif
4302
4303         gint count = 0;
4304
4305         /* header labels and entries */
4306         header_scrolledwin = gtk_scrolled_window_new(NULL, NULL);
4307         gtk_widget_show(header_scrolledwin);
4308         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(header_scrolledwin), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
4309
4310         header_table = gtk_table_new(2, 2, FALSE);
4311         gtk_widget_show(header_table);
4312         gtk_container_set_border_width(GTK_CONTAINER(header_table), 2);
4313         gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(header_scrolledwin), header_table);
4314         gtk_viewport_set_shadow_type(GTK_VIEWPORT(GTK_BIN(header_scrolledwin)->child), GTK_SHADOW_ETCHED_IN);
4315         count = 0;
4316
4317         /* option menu for selecting accounts */
4318         hbox = gtk_hbox_new(FALSE, 0);
4319         label = gtk_label_new(prefs_common.trans_hdr ? _("From:") : "From:");
4320         gtk_box_pack_end(GTK_BOX(hbox), label, FALSE, FALSE, 0);
4321         gtk_table_attach(GTK_TABLE(header_table), hbox, 0, 1, count, count + 1,
4322                          GTK_FILL, 0, 2, 0);
4323         from_optmenu_hbox = compose_account_option_menu_create(compose);
4324         gtk_table_attach(GTK_TABLE(header_table), from_optmenu_hbox,
4325                                   1, 2, count, count + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
4326 #if 0 /* NEW COMPOSE GUI */
4327         gtk_table_set_row_spacing(GTK_TABLE(table), 0, 4);
4328 #endif
4329         count++;
4330
4331         compose->header_table = header_table;
4332         compose->header_list = NULL;
4333         compose->header_nextrow = count;
4334
4335         compose_create_header_entry(compose);
4336
4337 #if 0 /* NEW COMPOSE GUI */
4338         compose_add_entry_field(table, &to_hbox, &to_entry, &count,
4339                                 "To:", TRUE); 
4340         gtk_table_set_row_spacing(GTK_TABLE(table), 0, 4);
4341         compose_add_entry_field(table, &newsgroups_hbox, &newsgroups_entry,
4342                                 &count, "Newsgroups:", FALSE);
4343         gtk_table_set_row_spacing(GTK_TABLE(table), 1, 4);
4344
4345         gtk_table_set_row_spacing(GTK_TABLE(table), 2, 4);
4346
4347         compose_add_entry_field(table, &cc_hbox, &cc_entry, &count,
4348                                 "Cc:", TRUE);
4349         gtk_table_set_row_spacing(GTK_TABLE(table), 3, 4);
4350         compose_add_entry_field(table, &bcc_hbox, &bcc_entry, &count,
4351                                 "Bcc:", TRUE);
4352         gtk_table_set_row_spacing(GTK_TABLE(table), 4, 4);
4353         compose_add_entry_field(table, &reply_hbox, &reply_entry, &count,
4354                                 "Reply-To:", TRUE);
4355         gtk_table_set_row_spacing(GTK_TABLE(table), 5, 4);
4356         compose_add_entry_field(table, &followup_hbox, &followup_entry, &count,
4357                                 "Followup-To:", FALSE);
4358         gtk_table_set_row_spacing(GTK_TABLE(table), 6, 4);
4359
4360         gtk_table_set_col_spacings(GTK_TABLE(table), 4);
4361
4362         gtk_signal_connect(GTK_OBJECT(to_entry), "activate",
4363                            GTK_SIGNAL_FUNC(to_activated), compose);
4364         gtk_signal_connect(GTK_OBJECT(newsgroups_entry), "activate",
4365                            GTK_SIGNAL_FUNC(newsgroups_activated), compose);
4366         gtk_signal_connect(GTK_OBJECT(subject_entry), "activate",
4367                            GTK_SIGNAL_FUNC(subject_activated), compose);
4368         gtk_signal_connect(GTK_OBJECT(cc_entry), "activate",
4369                            GTK_SIGNAL_FUNC(cc_activated), compose);
4370         gtk_signal_connect(GTK_OBJECT(bcc_entry), "activate",
4371                            GTK_SIGNAL_FUNC(bcc_activated), compose);
4372         gtk_signal_connect(GTK_OBJECT(reply_entry), "activate",
4373                            GTK_SIGNAL_FUNC(replyto_activated), compose);
4374         gtk_signal_connect(GTK_OBJECT(followup_entry), "activate",
4375                            GTK_SIGNAL_FUNC(followupto_activated), compose);
4376
4377         gtk_signal_connect(GTK_OBJECT(subject_entry), "grab_focus",
4378                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4379         gtk_signal_connect(GTK_OBJECT(to_entry), "grab_focus",
4380                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4381         gtk_signal_connect(GTK_OBJECT(newsgroups_entry), "grab_focus",
4382                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4383         gtk_signal_connect(GTK_OBJECT(cc_entry), "grab_focus",
4384                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4385         gtk_signal_connect(GTK_OBJECT(bcc_entry), "grab_focus",
4386                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4387         gtk_signal_connect(GTK_OBJECT(reply_entry), "grab_focus",
4388                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4389         gtk_signal_connect(GTK_OBJECT(followup_entry), "grab_focus",
4390                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4391 #endif
4392
4393         compose->table            = NULL;
4394 #if 0 /* NEW COMPOSE GUI */
4395         compose->table            = table;
4396         compose->to_hbox          = to_hbox;
4397         compose->to_entry         = to_entry;
4398         compose->newsgroups_hbox  = newsgroups_hbox;
4399         compose->newsgroups_entry = newsgroups_entry;
4400 #endif
4401 #if 0 /* NEW COMPOSE GUI */
4402         compose->cc_hbox          = cc_hbox;
4403         compose->cc_entry         = cc_entry;
4404         compose->bcc_hbox         = bcc_hbox;
4405         compose->bcc_entry        = bcc_entry;
4406         compose->reply_hbox       = reply_hbox;
4407         compose->reply_entry      = reply_entry;
4408         compose->followup_hbox    = followup_hbox;
4409         compose->followup_entry   = followup_entry;
4410 #endif
4411
4412         return header_scrolledwin ;
4413 }
4414
4415 GtkWidget *compose_create_attach(Compose *compose)
4416 {
4417         gchar *titles[N_ATTACH_COLS];
4418         gint i;
4419
4420         GtkWidget *attach_scrwin;
4421         GtkWidget *attach_clist;
4422
4423         titles[COL_MIMETYPE] = _("MIME type");
4424         titles[COL_SIZE]     = _("Size");
4425         titles[COL_NAME]     = _("Name");
4426
4427         /* attachment list */
4428         attach_scrwin = gtk_scrolled_window_new(NULL, NULL);
4429         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(attach_scrwin),
4430                                        GTK_POLICY_AUTOMATIC,
4431                                        GTK_POLICY_ALWAYS);
4432         gtk_widget_set_usize(attach_scrwin, -1, 80);
4433
4434         attach_clist = gtk_clist_new_with_titles(N_ATTACH_COLS, titles);
4435         gtk_clist_set_column_justification(GTK_CLIST(attach_clist), COL_SIZE,
4436                                            GTK_JUSTIFY_RIGHT);
4437         gtk_clist_set_column_width(GTK_CLIST(attach_clist), COL_MIMETYPE, 240);
4438         gtk_clist_set_column_width(GTK_CLIST(attach_clist), COL_SIZE, 64);
4439         gtk_clist_set_selection_mode(GTK_CLIST(attach_clist),
4440                                      GTK_SELECTION_EXTENDED);
4441         for (i = 0; i < N_ATTACH_COLS; i++)
4442                 GTK_WIDGET_UNSET_FLAGS
4443                         (GTK_CLIST(attach_clist)->column[i].button,
4444                          GTK_CAN_FOCUS);
4445         gtk_container_add(GTK_CONTAINER(attach_scrwin), attach_clist);
4446
4447         gtk_signal_connect(GTK_OBJECT(attach_clist), "select_row",
4448                            GTK_SIGNAL_FUNC(attach_selected), compose);
4449         gtk_signal_connect(GTK_OBJECT(attach_clist), "button_press_event",
4450                            GTK_SIGNAL_FUNC(attach_button_pressed), compose);
4451         gtk_signal_connect(GTK_OBJECT(attach_clist), "key_press_event",
4452                            GTK_SIGNAL_FUNC(attach_key_pressed), compose);
4453
4454         /* drag and drop */
4455         gtk_drag_dest_set(attach_clist,
4456                           GTK_DEST_DEFAULT_ALL, compose_mime_types, 1,
4457                           GDK_ACTION_COPY | GDK_ACTION_MOVE);
4458         gtk_signal_connect(GTK_OBJECT(attach_clist), "drag_data_received",
4459                            GTK_SIGNAL_FUNC(compose_attach_drag_received_cb),
4460                            compose);
4461
4462         compose->attach_scrwin = attach_scrwin;
4463         compose->attach_clist  = attach_clist;
4464
4465         return attach_scrwin;
4466 }
4467
4468 static void compose_savemsg_checkbtn_cb(GtkWidget *widget, Compose *compose);
4469 static void compose_savemsg_select_cb(GtkWidget *widget, Compose *compose);
4470
4471 static GtkWidget *compose_create_others(Compose *compose)
4472 {
4473         GtkWidget *table;
4474         GtkWidget *savemsg_checkbtn;
4475         GtkWidget *savemsg_entry;
4476         GtkWidget *savemsg_select;
4477         
4478         guint rowcount = 0;
4479         gchar *folderidentifier;
4480
4481         /* Table for settings */
4482         table = gtk_table_new(3, 1, FALSE);
4483         gtk_widget_show(table);
4484         gtk_table_set_row_spacings(GTK_TABLE(table), VSPACING_NARROW);
4485         rowcount = 0;
4486
4487         /* Save Message to folder */
4488         savemsg_checkbtn = gtk_check_button_new_with_label(_("Save Message to "));
4489         gtk_widget_show(savemsg_checkbtn);
4490         gtk_table_attach(GTK_TABLE(table), savemsg_checkbtn, 0, 1, rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
4491         if (account_get_special_folder(compose->account, F_OUTBOX)) {
4492                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(savemsg_checkbtn), prefs_common.savemsg);
4493         }
4494         gtk_signal_connect(GTK_OBJECT(savemsg_checkbtn), "toggled",
4495                             GTK_SIGNAL_FUNC(compose_savemsg_checkbtn_cb), compose);
4496
4497         savemsg_entry = gtk_entry_new();
4498         gtk_widget_show(savemsg_entry);
4499         gtk_table_attach_defaults(GTK_TABLE(table), savemsg_entry, 1, 2, rowcount, rowcount + 1);
4500         gtk_editable_set_editable(GTK_EDITABLE(savemsg_entry), prefs_common.savemsg);
4501         if (account_get_special_folder(compose->account, F_OUTBOX)) {
4502                 folderidentifier = folder_item_get_identifier(account_get_special_folder
4503                                   (compose->account, F_OUTBOX));
4504                 gtk_entry_set_text(GTK_ENTRY(savemsg_entry), folderidentifier);
4505                 g_free(folderidentifier);
4506         }
4507
4508         savemsg_select = gtk_button_new_with_label (_("Select ..."));
4509         gtk_widget_show (savemsg_select);
4510         gtk_table_attach(GTK_TABLE(table), savemsg_select, 2, 3, rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
4511         gtk_signal_connect (GTK_OBJECT (savemsg_select), "clicked",
4512                             GTK_SIGNAL_FUNC (compose_savemsg_select_cb),
4513                             compose);
4514
4515         rowcount++;
4516
4517         compose->savemsg_checkbtn = savemsg_checkbtn;
4518         compose->savemsg_entry = savemsg_entry;
4519
4520         return table;   
4521 }
4522
4523 static void compose_savemsg_checkbtn_cb(GtkWidget *widget, Compose *compose) 
4524 {
4525         gtk_editable_set_editable(GTK_EDITABLE(compose->savemsg_entry),
4526                 gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn)));
4527 }
4528
4529 static void compose_savemsg_select_cb(GtkWidget *widget, Compose *compose)
4530 {
4531         FolderItem *dest;
4532         gchar * path;
4533
4534         dest = foldersel_folder_sel(NULL, FOLDER_SEL_COPY, NULL);
4535         if (!dest) return;
4536
4537         path = folder_item_get_identifier(dest);
4538
4539         gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), path);
4540         g_free(path);
4541 }
4542
4543 static Compose *compose_create(PrefsAccount *account, ComposeMode mode)
4544 {
4545         Compose   *compose;
4546         GtkWidget *window;
4547         GtkWidget *vbox;
4548         GtkWidget *menubar;
4549         GtkWidget *handlebox;
4550
4551         GtkWidget *notebook;
4552
4553         GtkWidget *vbox2;
4554
4555         GtkWidget *label;
4556         GtkWidget *subject_hbox;
4557         GtkWidget *subject_frame;
4558         GtkWidget *subject_entry;
4559         GtkWidget *subject;
4560         GtkWidget *paned;
4561
4562         GtkWidget *edit_vbox;
4563         GtkWidget *ruler_hbox;
4564         GtkWidget *ruler;
4565         GtkWidget *scrolledwin;
4566         GtkWidget *text;
4567
4568         UndoMain *undostruct;
4569
4570         gchar *titles[N_ATTACH_COLS];
4571         guint n_menu_entries;
4572         GtkStyle  *style, *new_style;
4573         GdkColormap *cmap;
4574         GdkColor color[1];
4575         gboolean success[1];
4576         GtkWidget *popupmenu;
4577         GtkItemFactory *popupfactory;
4578         GtkItemFactory *ifactory;
4579         GtkWidget *tmpl_menu;
4580         gint n_entries;
4581
4582 #if USE_ASPELL
4583         GtkAspell * gtkaspell = NULL;
4584 #endif
4585
4586         static GdkGeometry geometry;
4587
4588         g_return_val_if_fail(account != NULL, NULL);
4589
4590         debug_print("Creating compose window...\n");
4591         compose = g_new0(Compose, 1);
4592
4593         titles[COL_MIMETYPE] = _("MIME type");
4594         titles[COL_SIZE]     = _("Size");
4595         titles[COL_NAME]     = _("Name");
4596
4597         compose->account = account;
4598
4599         window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
4600         gtk_window_set_policy(GTK_WINDOW(window), TRUE, TRUE, FALSE);
4601         gtk_widget_set_usize(window, -1, prefs_common.compose_height);
4602         gtk_window_set_wmclass(GTK_WINDOW(window), "compose window", "Sylpheed");
4603
4604         if (!geometry.max_width) {
4605                 geometry.max_width = gdk_screen_width();
4606                 geometry.max_height = gdk_screen_height();
4607         }
4608         gtk_window_set_geometry_hints(GTK_WINDOW(window), NULL,
4609                                       &geometry, GDK_HINT_MAX_SIZE);
4610         gtk_widget_set_uposition(window, prefs_common.compose_x, 
4611                 prefs_common.compose_y);
4612         gtk_signal_connect(GTK_OBJECT(window), "delete_event",
4613                            GTK_SIGNAL_FUNC(compose_delete_cb), compose);
4614         gtk_signal_connect(GTK_OBJECT(window), "destroy",
4615                            GTK_SIGNAL_FUNC(compose_destroy_cb), compose);
4616         MANAGE_WINDOW_SIGNALS_CONNECT(window);
4617         gtk_widget_realize(window);
4618
4619         gtkut_widget_set_composer_icon(window);
4620
4621         vbox = gtk_vbox_new(FALSE, 0);
4622         gtk_container_add(GTK_CONTAINER(window), vbox);
4623
4624         n_menu_entries = sizeof(compose_entries) / sizeof(compose_entries[0]);
4625         menubar = menubar_create(window, compose_entries,
4626                                  n_menu_entries, "<Compose>", compose);
4627         gtk_box_pack_start(GTK_BOX(vbox), menubar, FALSE, TRUE, 0);
4628
4629         handlebox = gtk_handle_box_new();
4630         gtk_box_pack_start(GTK_BOX(vbox), handlebox, FALSE, FALSE, 0);
4631
4632         compose->toolbar = toolbar_create(TOOLBAR_COMPOSE, handlebox,
4633                                           (gpointer)compose);
4634
4635         vbox2 = gtk_vbox_new(FALSE, 2);
4636         gtk_box_pack_start(GTK_BOX(vbox), vbox2, TRUE, TRUE, 0);
4637         gtk_container_set_border_width(GTK_CONTAINER(vbox2), BORDER_WIDTH);
4638         
4639         /* Notebook */
4640         notebook = gtk_notebook_new();
4641         gtk_widget_set_usize(notebook, -1, 130);
4642         gtk_widget_show(notebook);
4643
4644         /* header labels and entries */
4645         gtk_notebook_append_page(GTK_NOTEBOOK(notebook), compose_create_header(compose), gtk_label_new(_("Header")));
4646         /* attachment list */
4647         gtk_notebook_append_page(GTK_NOTEBOOK(notebook), compose_create_attach(compose), gtk_label_new(_("Attachments")));
4648         /* Others Tab */
4649         gtk_notebook_append_page(GTK_NOTEBOOK(notebook), compose_create_others(compose), gtk_label_new(_("Others")));
4650
4651         /* Subject */
4652         subject_hbox = gtk_hbox_new(FALSE, 0);
4653         gtk_widget_show(subject_hbox);
4654
4655         subject_frame = gtk_frame_new(NULL);
4656         gtk_frame_set_shadow_type(GTK_FRAME(subject_frame), GTK_SHADOW_OUT);
4657         gtk_box_pack_start(GTK_BOX(subject_hbox), subject_frame, TRUE, TRUE, BORDER_WIDTH+1);
4658         gtk_widget_show(subject_frame);
4659
4660         subject = gtk_hbox_new(FALSE, 0);
4661         gtk_container_set_border_width(GTK_CONTAINER(subject), BORDER_WIDTH);
4662         gtk_widget_show(subject);
4663
4664         label = gtk_label_new(_("Subject:"));
4665         gtk_box_pack_start(GTK_BOX(subject), label, FALSE, FALSE, 4);
4666         gtk_widget_show(label);
4667
4668         subject_entry = gtk_entry_new();
4669         gtk_box_pack_start(GTK_BOX(subject), subject_entry, TRUE, TRUE, 2);
4670         gtk_signal_connect(GTK_OBJECT(subject_entry), "activate", GTK_SIGNAL_FUNC(text_activated), compose);
4671         gtk_widget_show(subject_entry);
4672         compose->subject_entry = subject_entry;
4673         gtk_container_add(GTK_CONTAINER(subject_frame), subject);
4674         
4675         edit_vbox = gtk_vbox_new(FALSE, 0);
4676
4677         gtk_box_pack_start(GTK_BOX(edit_vbox), subject_hbox, FALSE, FALSE, 0);
4678
4679         /* ruler */
4680         ruler_hbox = gtk_hbox_new(FALSE, 0);
4681         gtk_box_pack_start(GTK_BOX(edit_vbox), ruler_hbox, FALSE, FALSE, 0);
4682
4683         ruler = gtk_shruler_new();
4684         gtk_ruler_set_range(GTK_RULER(ruler), 0.0, 100.0, 1.0, 100.0);
4685         gtk_box_pack_start(GTK_BOX(ruler_hbox), ruler, TRUE, TRUE,
4686                            BORDER_WIDTH + 1);
4687         gtk_widget_set_usize(ruler_hbox, 1, -1);
4688
4689         /* text widget */
4690         scrolledwin = gtk_scrolled_window_new(NULL, NULL);
4691         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin),
4692                                        GTK_POLICY_NEVER, GTK_POLICY_ALWAYS);
4693         gtk_box_pack_start(GTK_BOX(edit_vbox), scrolledwin, TRUE, TRUE, 0);
4694         gtk_widget_set_usize(scrolledwin, prefs_common.compose_width, -1);
4695
4696         text = gtk_stext_new(gtk_scrolled_window_get_hadjustment
4697                             (GTK_SCROLLED_WINDOW(scrolledwin)),
4698                             gtk_scrolled_window_get_vadjustment
4699                             (GTK_SCROLLED_WINDOW(scrolledwin)));
4700         GTK_STEXT(text)->default_tab_width = 8;
4701         gtk_stext_set_editable(GTK_STEXT(text), TRUE);
4702
4703         if (prefs_common.block_cursor) {
4704                 GTK_STEXT(text)->cursor_type = GTK_STEXT_CURSOR_BLOCK;
4705         }
4706         
4707         gtk_container_add(GTK_CONTAINER(scrolledwin), text);
4708
4709         gtk_signal_connect(GTK_OBJECT(text), "changed",
4710                            GTK_SIGNAL_FUNC(compose_changed_cb), compose);
4711         gtk_signal_connect(GTK_OBJECT(text), "grab_focus",
4712                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4713         gtk_signal_connect(GTK_OBJECT(text), "activate",
4714                            GTK_SIGNAL_FUNC(text_activated), compose);
4715         gtk_signal_connect(GTK_OBJECT(text), "insert_text",
4716                            GTK_SIGNAL_FUNC(text_inserted), compose);
4717         gtk_signal_connect_after(GTK_OBJECT(text), "button_press_event",
4718                                  GTK_SIGNAL_FUNC(compose_button_press_cb),
4719                                  edit_vbox);
4720 #if 0
4721         gtk_signal_connect_after(GTK_OBJECT(text), "key_press_event",
4722                                  GTK_SIGNAL_FUNC(compose_key_press_cb),
4723                                  compose);
4724 #endif
4725         gtk_signal_connect_after(GTK_OBJECT(text), "size_allocate",
4726                                  GTK_SIGNAL_FUNC(compose_edit_size_alloc),
4727                                  ruler);
4728
4729         /* drag and drop */
4730         gtk_drag_dest_set(text, GTK_DEST_DEFAULT_ALL, compose_mime_types, 1,
4731                           GDK_ACTION_COPY | GDK_ACTION_MOVE);
4732         gtk_signal_connect(GTK_OBJECT(text), "drag_data_received",
4733                            GTK_SIGNAL_FUNC(compose_insert_drag_received_cb),
4734                            compose);
4735         gtk_widget_show_all(vbox);
4736
4737         /* pane between attach clist and text */
4738         paned = gtk_vpaned_new();
4739         gtk_paned_set_gutter_size(GTK_PANED(paned), 12);
4740         gtk_paned_set_handle_size(GTK_PANED(paned), 12);
4741         gtk_container_add(GTK_CONTAINER(vbox2), paned);
4742         gtk_paned_add1(GTK_PANED(paned), notebook);
4743         gtk_paned_add2(GTK_PANED(paned), edit_vbox);
4744         gtk_widget_show_all(paned);
4745
4746         style = gtk_widget_get_style(text);
4747
4748         /* workaround for the slow down of GtkSText when using Pixmap theme */
4749         if (style->engine) {
4750                 GtkThemeEngine *engine;
4751
4752                 engine = style->engine;
4753                 style->engine = NULL;
4754                 new_style = gtk_style_copy(style);
4755                 style->engine = engine;
4756         } else
4757                 new_style = gtk_style_copy(style);
4758
4759         if (prefs_common.textfont) {
4760                 GdkFont *font;
4761
4762                 if ((font = gtkut_font_load(prefs_common.textfont)) != NULL) {
4763                         gdk_font_unref(new_style->font);
4764                         new_style->font = font;
4765                 }
4766         }
4767
4768         gtk_widget_set_style(text, new_style);
4769
4770         color[0] = quote_color;
4771         cmap = gdk_window_get_colormap(window->window);
4772         gdk_colormap_alloc_colors(cmap, color, 1, FALSE, TRUE, success);
4773         if (success[0] == FALSE) {
4774                 g_warning("Compose: color allocation failed.\n");
4775                 style = gtk_widget_get_style(text);
4776                 quote_color = style->black;
4777         }
4778
4779         n_entries = sizeof(compose_popup_entries) /
4780                 sizeof(compose_popup_entries[0]);
4781         popupmenu = menu_create_items(compose_popup_entries, n_entries,
4782                                       "<Compose>", &popupfactory,
4783                                       compose);
4784
4785         ifactory = gtk_item_factory_from_widget(menubar);
4786         menu_set_sensitive(ifactory, "/Edit/Undo", FALSE);
4787         menu_set_sensitive(ifactory, "/Edit/Redo", FALSE);
4788         menu_set_sensitive(ifactory, "/Options/Remove references", FALSE);
4789
4790         tmpl_menu = gtk_item_factory_get_item(ifactory, "/Tools/Template");
4791
4792         undostruct = undo_init(text);
4793         undo_set_change_state_func(undostruct, &compose_undo_state_changed,
4794                                    menubar);
4795
4796         address_completion_start(window);
4797
4798         compose->window        = window;
4799         compose->vbox          = vbox;
4800         compose->menubar       = menubar;
4801         compose->handlebox     = handlebox;
4802
4803         compose->vbox2         = vbox2;
4804
4805         compose->paned = paned;
4806
4807         compose->edit_vbox     = edit_vbox;
4808         compose->ruler_hbox    = ruler_hbox;
4809         compose->ruler         = ruler;
4810         compose->scrolledwin   = scrolledwin;
4811         compose->text          = text;
4812
4813         compose->focused_editable = NULL;
4814
4815         compose->popupmenu    = popupmenu;
4816         compose->popupfactory = popupfactory;
4817
4818         compose->tmpl_menu = tmpl_menu;
4819
4820         compose->mode = mode;
4821
4822         compose->targetinfo = NULL;
4823         compose->replyinfo  = NULL;
4824         compose->fwdinfo    = NULL;
4825
4826         compose->replyto     = NULL;
4827         compose->cc          = NULL;
4828         compose->bcc         = NULL;
4829         compose->followup_to = NULL;
4830
4831         compose->ml_post     = NULL;
4832
4833         compose->inreplyto   = NULL;
4834         compose->references  = NULL;
4835         compose->msgid       = NULL;
4836         compose->boundary    = NULL;
4837
4838         compose->autowrap       = prefs_common.autowrap;
4839
4840         compose->use_signing    = FALSE;
4841         compose->use_encryption = FALSE;
4842         compose->privacy_system = NULL;
4843
4844         compose->modified = FALSE;
4845
4846         compose->return_receipt = FALSE;
4847
4848         compose->to_list        = NULL;
4849         compose->newsgroup_list = NULL;
4850
4851         compose->undostruct = undostruct;
4852
4853         compose->sig_str = NULL;
4854
4855         compose->exteditor_file    = NULL;
4856         compose->exteditor_pid     = -1;
4857         compose->exteditor_readdes = -1;
4858         compose->exteditor_tag     = -1;
4859         compose->draft_timeout_tag = -1;
4860
4861 #if USE_ASPELL
4862         menu_set_sensitive(ifactory, "/Spelling", FALSE);
4863         if (mode != COMPOSE_REDIRECT) {
4864                 if (prefs_common.enable_aspell && prefs_common.dictionary &&
4865                     strcmp(prefs_common.dictionary, _("None"))) {
4866                         gtkaspell = gtkaspell_new(prefs_common.aspell_path,
4867                                                   prefs_common.dictionary,
4868                                                   conv_get_current_charset_str(),
4869                                                   prefs_common.misspelled_col,
4870                                                   prefs_common.check_while_typing,
4871                                                   prefs_common.use_alternate,
4872                                                   GTK_STEXT(text));
4873                         if (!gtkaspell) {
4874                                 alertpanel_error(_("Spell checker could not "
4875                                                 "be started.\n%s"),
4876                                                 gtkaspell_checkers_strerror());
4877                                 gtkaspell_checkers_reset_error();
4878                         } else {
4879
4880                                 GtkWidget *menuitem;
4881
4882                                 if (!gtkaspell_set_sug_mode(gtkaspell,
4883                                                 prefs_common.aspell_sugmode)) {
4884                                         debug_print("Aspell: could not set "
4885                                                     "suggestion mode %s\n",
4886                                                     gtkaspell_checkers_strerror());
4887                                         gtkaspell_checkers_reset_error();
4888                                 }
4889
4890                                 menuitem = gtk_item_factory_get_item(ifactory,
4891                                         "/Spelling/Spelling Configuration");
4892                                 gtkaspell_populate_submenu(gtkaspell, menuitem);
4893                                 menu_set_sensitive(ifactory, "/Spelling", TRUE);
4894                         }
4895                 }
4896         }
4897         compose->gtkaspell = gtkaspell;
4898 #endif
4899
4900         compose_select_account(compose, account, TRUE);
4901
4902         menu_set_active(ifactory, "/Edit/Auto wrapping", prefs_common.autowrap);
4903         if (account->set_autocc && account->auto_cc && mode != COMPOSE_REEDIT)
4904                 compose_entry_append(compose, account->auto_cc, COMPOSE_CC);
4905
4906         if (account->set_autobcc && account->auto_bcc && mode != COMPOSE_REEDIT) 
4907                 compose_entry_append(compose, account->auto_bcc, COMPOSE_BCC);
4908         
4909         if (account->set_autoreplyto && account->auto_replyto && mode != COMPOSE_REEDIT)
4910                 compose_entry_append(compose, account->auto_replyto, COMPOSE_REPLYTO);
4911
4912
4913         if (account->protocol != A_NNTP)
4914                 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry), prefs_common.trans_hdr ? _("To:") : "To:");
4915         else
4916                 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry), prefs_common.trans_hdr ? _("Newsgroups:") : "Newsgroups:");
4917
4918         addressbook_set_target_compose(compose);
4919         
4920         if (mode != COMPOSE_REDIRECT)
4921                 compose_set_template_menu(compose);
4922         else {
4923                 GtkWidget *menuitem;
4924                 menuitem = gtk_item_factory_get_item(ifactory, "/Tools/Template");
4925                 menu_set_sensitive(ifactory, "/Tools/Template", FALSE);
4926         }
4927
4928         compose_list = g_list_append(compose_list, compose);
4929
4930         if (!prefs_common.show_ruler)
4931                 gtk_widget_hide(ruler_hbox);
4932
4933         /* Priority */
4934         compose->priority = PRIORITY_NORMAL;
4935         compose_update_priority_menu_item(compose);
4936
4937         /* Actions menu */
4938         compose_update_actions_menu(compose);
4939
4940         /* Privacy Systems menu */
4941         compose_update_privacy_systems_menu(compose);
4942
4943         activate_privacy_system(compose, account);
4944         toolbar_set_style(compose->toolbar->toolbar, compose->handlebox, prefs_common.toolbar_style);
4945         gtk_widget_show(window);
4946         
4947         return compose;
4948 }
4949
4950 static GtkWidget *compose_account_option_menu_create(Compose *compose)
4951 {
4952         GList *accounts;
4953         GtkWidget *hbox;
4954         GtkWidget *optmenu;
4955         GtkWidget *menu;
4956         gint num = 0, def_menu = 0;
4957
4958         accounts = account_get_list();
4959         g_return_val_if_fail(accounts != NULL, NULL);
4960
4961         hbox = gtk_hbox_new(FALSE, 0);
4962         optmenu = gtk_option_menu_new();
4963         gtk_box_pack_start(GTK_BOX(hbox), optmenu, FALSE, FALSE, 0);
4964         menu = gtk_menu_new();
4965
4966         for (; accounts != NULL; accounts = accounts->next, num++) {
4967                 PrefsAccount *ac = (PrefsAccount *)accounts->data;
4968                 GtkWidget *menuitem;
4969                 gchar *name;
4970
4971                 if (ac == compose->account) def_menu = num;
4972
4973                 if (ac->name)
4974                         name = g_strdup_printf("%s: %s <%s>",
4975                                                ac->account_name,
4976                                                ac->name, ac->address);
4977                 else
4978                         name = g_strdup_printf("%s: %s",
4979                                                ac->account_name, ac->address);
4980                 MENUITEM_ADD(menu, menuitem, name, ac->account_id);
4981                 g_free(name);
4982                 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
4983                                    GTK_SIGNAL_FUNC(account_activated),
4984                                    compose);
4985         }
4986
4987         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), menu);
4988         gtk_option_menu_set_history(GTK_OPTION_MENU(optmenu), def_menu);
4989
4990         return hbox;
4991 }
4992
4993 static void compose_set_priority_cb(gpointer data,
4994                                     guint action,
4995                                     GtkWidget *widget)
4996 {
4997         Compose *compose = (Compose *) data;
4998         compose->priority = action;
4999 }
5000
5001 static void compose_update_priority_menu_item(Compose * compose)
5002 {
5003         GtkItemFactory *ifactory;
5004         GtkWidget *menuitem = NULL;
5005
5006         ifactory = gtk_item_factory_from_widget(compose->menubar);
5007         
5008         switch (compose->priority) {
5009                 case PRIORITY_HIGHEST:
5010                         menuitem = gtk_item_factory_get_item
5011                                 (ifactory, "/Options/Priority/Highest");
5012                         break;
5013                 case PRIORITY_HIGH:
5014                         menuitem = gtk_item_factory_get_item
5015                                 (ifactory, "/Options/Priority/High");
5016                         break;
5017                 case PRIORITY_NORMAL:
5018                         menuitem = gtk_item_factory_get_item
5019                                 (ifactory, "/Options/Priority/Normal");
5020                         break;
5021                 case PRIORITY_LOW:
5022                         menuitem = gtk_item_factory_get_item
5023                                 (ifactory, "/Options/Priority/Low");
5024                         break;
5025                 case PRIORITY_LOWEST:
5026                         menuitem = gtk_item_factory_get_item
5027                                 (ifactory, "/Options/Priority/Lowest");
5028                         break;
5029         }
5030         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), TRUE);
5031 }       
5032
5033 static void compose_set_privacy_system_cb(GtkWidget *widget, gpointer data)
5034 {
5035         Compose *compose = (Compose *) data;
5036         gchar *systemid;
5037         GtkItemFactory *ifactory;
5038         gboolean can_sign = FALSE, can_encrypt = FALSE;
5039
5040         g_return_if_fail(GTK_IS_CHECK_MENU_ITEM(widget));
5041
5042         if (!GTK_CHECK_MENU_ITEM(widget)->active)
5043                 return;
5044
5045         systemid = gtk_object_get_data(GTK_OBJECT(widget), "privacy_system");
5046         g_free(compose->privacy_system);
5047         compose->privacy_system = NULL;
5048         if (systemid != NULL) {
5049                 compose->privacy_system = g_strdup(systemid);
5050
5051                 can_sign = privacy_system_can_sign(systemid);
5052                 can_encrypt = privacy_system_can_encrypt(systemid);
5053         }
5054
5055         debug_print("activated privacy system: %s\n", systemid != NULL ? systemid : "None");
5056
5057         ifactory = gtk_item_factory_from_widget(compose->menubar);
5058         menu_set_sensitive(ifactory, "/Options/Sign", can_sign);
5059         if (!can_sign)
5060                 menu_set_active(ifactory, "/Options/Sign", FALSE);
5061         menu_set_sensitive(ifactory, "/Options/Encrypt", can_encrypt);
5062         if (!can_encrypt)
5063                 menu_set_active(ifactory, "/Options/Encrypt", FALSE);
5064 }
5065
5066 static void compose_update_privacy_system_menu_item(Compose * compose)
5067 {
5068         static gchar *branch_path = "/Options/Privacy System";
5069         GtkItemFactory *ifactory;
5070         GtkWidget *menuitem = NULL;
5071         GList *amenu;
5072         gboolean can_sign = FALSE, can_encrypt = FALSE;
5073
5074         ifactory = gtk_item_factory_from_widget(compose->menubar);
5075
5076         if (compose->privacy_system != NULL) {
5077                 gchar *systemid;
5078
5079                 menuitem = gtk_item_factory_get_widget(ifactory, branch_path);
5080                 g_return_if_fail(menuitem != NULL);
5081
5082                 amenu = GTK_MENU_SHELL(menuitem)->children;
5083                 menuitem = NULL;
5084                 while (amenu != NULL) {
5085                         GList *alist = amenu->next;
5086
5087                         systemid = gtk_object_get_data(GTK_OBJECT(amenu->data), "privacy_system");
5088                         if (systemid != NULL)
5089                                 if (strcmp(systemid, compose->privacy_system) == 0) {
5090                                         menuitem = GTK_WIDGET(amenu->data);
5091
5092                                         can_sign = privacy_system_can_sign(systemid);
5093                                         can_encrypt = privacy_system_can_encrypt(systemid);
5094
5095                                         break;
5096                                 }
5097
5098                         amenu = alist;
5099                 }
5100                 if (menuitem != NULL)
5101                         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), TRUE);
5102         }
5103
5104         menu_set_sensitive(ifactory, "/Options/Sign", can_sign);
5105         menu_set_sensitive(ifactory, "/Options/Encrypt", can_encrypt);
5106 }       
5107  
5108 static void compose_set_template_menu(Compose *compose)
5109 {
5110         GSList *tmpl_list, *cur;
5111         GtkWidget *menu;
5112         GtkWidget *item;
5113
5114         tmpl_list = template_get_config();
5115
5116         menu = gtk_menu_new();
5117
5118         for (cur = tmpl_list; cur != NULL; cur = cur->next) {
5119                 Template *tmpl = (Template *)cur->data;
5120
5121                 item = gtk_menu_item_new_with_label(tmpl->name);
5122                 gtk_menu_append(GTK_MENU(menu), item);
5123                 gtk_signal_connect(GTK_OBJECT(item), "activate",
5124                                    GTK_SIGNAL_FUNC(compose_template_activate_cb),
5125                                    compose);
5126                 gtk_object_set_data(GTK_OBJECT(item), "template", tmpl);
5127                 gtk_widget_show(item);
5128         }
5129
5130         gtk_widget_show(menu);
5131         gtk_menu_item_set_submenu(GTK_MENU_ITEM(compose->tmpl_menu), menu);
5132 }
5133
5134 void compose_update_actions_menu(Compose *compose)
5135 {
5136         GtkItemFactory *ifactory;
5137
5138         ifactory = gtk_item_factory_from_widget(compose->menubar);
5139         action_update_compose_menu(ifactory, "/Tools/Actions", compose);
5140 }
5141
5142 void compose_update_privacy_systems_menu(Compose *compose)
5143 {
5144         static gchar *branch_path = "/Options/Privacy System";
5145         static gboolean connected = FALSE;
5146         GtkItemFactory *ifactory;
5147         GtkWidget *menuitem;
5148         GSList *systems, *cur;
5149         GList *amenu;
5150         GtkWidget *widget;
5151         GtkWidget *system_none;
5152         GSList *group;
5153
5154         ifactory = gtk_item_factory_from_widget(compose->menubar);
5155
5156         /* remove old entries */
5157         menuitem = gtk_item_factory_get_widget(ifactory, branch_path);
5158         g_return_if_fail(menuitem != NULL);
5159
5160         amenu = GTK_MENU_SHELL(menuitem)->children->next;
5161         while (amenu != NULL) {
5162                 GList *alist = amenu->next;
5163                 gtk_widget_destroy(GTK_WIDGET(amenu->data));
5164                 amenu = alist;
5165         }
5166
5167         system_none = gtk_item_factory_get_widget(ifactory,
5168                 "/Options/Privacy System/None");
5169         if (!connected) {
5170                 gtk_signal_connect(GTK_OBJECT(system_none), "activate",
5171                         GTK_SIGNAL_FUNC(compose_set_privacy_system_cb), compose);
5172                 connected = TRUE;
5173         }
5174
5175         systems = privacy_get_system_ids();
5176         for (cur = systems; cur != NULL; cur = g_slist_next(cur)) {
5177                 gchar *systemid = cur->data;
5178
5179                 group = gtk_radio_menu_item_group(GTK_RADIO_MENU_ITEM(system_none));
5180                 widget = gtk_radio_menu_item_new_with_label(group,
5181                         privacy_system_get_name(systemid));
5182                 gtk_object_set_data_full(GTK_OBJECT(widget), "privacy_system",
5183                                          g_strdup(systemid), g_free);
5184                 gtk_signal_connect(GTK_OBJECT(widget), "activate",
5185                         GTK_SIGNAL_FUNC(compose_set_privacy_system_cb), compose);
5186
5187                 gtk_menu_append(GTK_MENU(system_none->parent), widget);
5188                 gtk_widget_show(widget);
5189                 g_free(systemid);
5190         }
5191         g_slist_free(systems);
5192 }
5193
5194 void compose_reflect_prefs_all(void)
5195 {
5196         GList *cur;
5197         Compose *compose;
5198
5199         for (cur = compose_list; cur != NULL; cur = cur->next) {
5200                 compose = (Compose *)cur->data;
5201                 compose_set_template_menu(compose);
5202         }
5203 }
5204
5205 void compose_reflect_prefs_pixmap_theme(void)
5206 {
5207         GList *cur;
5208         Compose *compose;
5209
5210         for (cur = compose_list; cur != NULL; cur = cur->next) {
5211                 compose = (Compose *)cur->data;
5212                 toolbar_update(TOOLBAR_COMPOSE, compose);
5213         }
5214 }
5215
5216 static void compose_template_apply(Compose *compose, Template *tmpl,
5217                                    gboolean replace)
5218 {
5219         gchar *qmark;
5220         gchar *parsed_str;
5221
5222         if (!tmpl || !tmpl->value) return;
5223
5224         gtk_stext_freeze(GTK_STEXT(compose->text));
5225
5226         if (tmpl->subject && *tmpl->subject != '\0')
5227                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry),
5228                                    tmpl->subject);
5229         if (tmpl->to && *tmpl->to != '\0')
5230                 compose_entry_append(compose, tmpl->to, COMPOSE_TO);
5231         if (tmpl->cc && *tmpl->cc != '\0')
5232                 compose_entry_append(compose, tmpl->cc, COMPOSE_CC);
5233
5234         if (tmpl->bcc && *tmpl->bcc != '\0')
5235                 compose_entry_append(compose, tmpl->bcc, COMPOSE_BCC);
5236
5237         if (replace)
5238                 gtkut_stext_clear(GTK_STEXT(compose->text));
5239
5240         if ((compose->replyinfo == NULL) && (compose->fwdinfo == NULL)) {
5241                 parsed_str = compose_quote_fmt(compose, NULL, tmpl->value,
5242                                                NULL, NULL);
5243         } else {
5244                 if (prefs_common.quotemark && *prefs_common.quotemark)
5245                         qmark = prefs_common.quotemark;
5246                 else
5247                         qmark = "> ";
5248
5249                 if (compose->replyinfo != NULL)
5250                         parsed_str = compose_quote_fmt(compose, compose->replyinfo,
5251                                                        tmpl->value, qmark, NULL);
5252                 else if (compose->fwdinfo != NULL)
5253                         parsed_str = compose_quote_fmt(compose, compose->fwdinfo,
5254                                                        tmpl->value, qmark, NULL);
5255                 else
5256                         parsed_str = NULL;
5257         }
5258
5259         if (replace && parsed_str && compose->account->auto_sig)
5260                 compose_insert_sig(compose, FALSE);
5261
5262         if (replace && parsed_str) {
5263                 gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
5264                 gtk_stext_set_point(GTK_STEXT(compose->text), 0);
5265         }
5266
5267         if (parsed_str)
5268                 compose_changed_cb(NULL, compose);
5269
5270         gtk_stext_thaw(GTK_STEXT(compose->text));
5271 }
5272
5273 static void compose_destroy(Compose *compose)
5274 {
5275         gint row;
5276         GtkCList *clist = GTK_CLIST(compose->attach_clist);
5277         AttachInfo *ainfo;
5278
5279         /* NOTE: address_completion_end() does nothing with the window
5280          * however this may change. */
5281         address_completion_end(compose->window);
5282
5283         slist_free_strings(compose->to_list);
5284         g_slist_free(compose->to_list);
5285         slist_free_strings(compose->newsgroup_list);
5286         g_slist_free(compose->newsgroup_list);
5287         slist_free_strings(compose->header_list);
5288         g_slist_free(compose->header_list);
5289
5290         procmsg_msginfo_free(compose->targetinfo);
5291         procmsg_msginfo_free(compose->replyinfo);
5292         procmsg_msginfo_free(compose->fwdinfo);
5293
5294         g_free(compose->replyto);
5295         g_free(compose->cc);
5296         g_free(compose->bcc);
5297         g_free(compose->newsgroups);
5298         g_free(compose->followup_to);
5299
5300         g_free(compose->ml_post);
5301
5302         g_free(compose->inreplyto);
5303         g_free(compose->references);
5304         g_free(compose->msgid);
5305         g_free(compose->boundary);
5306
5307         if (compose->redirect_filename)
5308                 g_free(compose->redirect_filename);
5309         if (compose->undostruct)
5310                 undo_destroy(compose->undostruct);
5311
5312         g_free(compose->sig_str);
5313
5314         g_free(compose->exteditor_file);
5315
5316         for (row = 0; (ainfo = gtk_clist_get_row_data(clist, row)) != NULL;
5317              row++)
5318                 compose_attach_info_free(ainfo);
5319
5320         if (addressbook_get_target_compose() == compose)
5321                 addressbook_set_target_compose(NULL);
5322
5323 #if USE_ASPELL
5324         if (compose->gtkaspell) {
5325                 gtkaspell_delete(compose->gtkaspell);
5326         }
5327 #endif
5328
5329         prefs_common.compose_width = compose->scrolledwin->allocation.width;
5330         prefs_common.compose_height = compose->window->allocation.height;
5331
5332         if (!compose->paned->parent)
5333                 gtk_widget_destroy(compose->paned);
5334         gtk_widget_destroy(compose->popupmenu);
5335
5336         toolbar_destroy(compose->toolbar);
5337         g_free(compose->toolbar);
5338         g_free(compose);
5339
5340         compose_list = g_list_remove(compose_list, compose);
5341 }
5342
5343 static void compose_attach_info_free(AttachInfo *ainfo)
5344 {
5345         g_free(ainfo->file);
5346         g_free(ainfo->content_type);
5347         g_free(ainfo->name);
5348         g_free(ainfo);
5349 }
5350
5351 static void compose_attach_remove_selected(Compose *compose)
5352 {
5353         GtkCList *clist = GTK_CLIST(compose->attach_clist);
5354         AttachInfo *ainfo;
5355         gint row;
5356
5357         while (clist->selection != NULL) {
5358                 row = GPOINTER_TO_INT(clist->selection->data);
5359                 ainfo = gtk_clist_get_row_data(clist, row);
5360                 compose_attach_info_free(ainfo);
5361                 gtk_clist_remove(clist, row);
5362         }
5363 }
5364
5365 static struct _AttachProperty
5366 {
5367         GtkWidget *window;
5368         GtkWidget *mimetype_entry;
5369         GtkWidget *encoding_optmenu;
5370         GtkWidget *path_entry;
5371         GtkWidget *filename_entry;
5372         GtkWidget *ok_btn;
5373         GtkWidget *cancel_btn;
5374 } attach_prop;
5375
5376 static void compose_attach_property(Compose *compose)
5377 {
5378         GtkCList *clist = GTK_CLIST(compose->attach_clist);
5379         AttachInfo *ainfo;
5380         gint row;
5381         GtkOptionMenu *optmenu;
5382         static gboolean cancelled;
5383
5384         if (!clist->selection) return;
5385         row = GPOINTER_TO_INT(clist->selection->data);
5386
5387         ainfo = gtk_clist_get_row_data(clist, row);
5388         if (!ainfo) return;
5389
5390         if (!attach_prop.window)
5391                 compose_attach_property_create(&cancelled);
5392         gtk_widget_grab_focus(attach_prop.ok_btn);
5393         gtk_widget_show(attach_prop.window);
5394         manage_window_set_transient(GTK_WINDOW(attach_prop.window));
5395
5396         optmenu = GTK_OPTION_MENU(attach_prop.encoding_optmenu);
5397         if (ainfo->encoding == ENC_UNKNOWN)
5398                 menu_select_by_data(GTK_MENU(gtk_option_menu_get_menu(optmenu)),
5399                                     GINT_TO_POINTER(ENC_BASE64));
5400         else
5401                 menu_select_by_data(GTK_MENU(gtk_option_menu_get_menu(optmenu)),
5402                                     GINT_TO_POINTER(ainfo->encoding));
5403
5404         gtk_entry_set_text(GTK_ENTRY(attach_prop.mimetype_entry),
5405                            ainfo->content_type ? ainfo->content_type : "");
5406         gtk_entry_set_text(GTK_ENTRY(attach_prop.path_entry),
5407                            ainfo->file ? ainfo->file : "");
5408         gtk_entry_set_text(GTK_ENTRY(attach_prop.filename_entry),
5409                            ainfo->name ? ainfo->name : "");
5410
5411         for (;;) {
5412                 gchar *text;
5413                 gchar *cnttype = NULL;
5414                 gchar *file = NULL;
5415                 off_t size = 0;
5416                 GtkWidget *menu;
5417                 GtkWidget *menuitem;
5418
5419                 cancelled = FALSE;
5420                 gtk_main();
5421
5422                 if (cancelled == TRUE) {
5423                         gtk_widget_hide(attach_prop.window);
5424                         break;
5425                 }
5426
5427                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.mimetype_entry));
5428                 if (*text != '\0') {
5429                         gchar *p;
5430
5431                         text = g_strstrip(g_strdup(text));
5432                         if ((p = strchr(text, '/')) && !strchr(p + 1, '/')) {
5433                                 cnttype = g_strdup(text);
5434                                 g_free(text);
5435                         } else {
5436                                 alertpanel_error(_("Invalid MIME type."));
5437                                 g_free(text);
5438                                 continue;
5439                         }
5440                 }
5441
5442                 menu = gtk_option_menu_get_menu(optmenu);
5443                 menuitem = gtk_menu_get_active(GTK_MENU(menu));
5444                 ainfo->encoding = GPOINTER_TO_INT
5445                         (gtk_object_get_user_data(GTK_OBJECT(menuitem)));
5446
5447                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.path_entry));
5448                 if (*text != '\0') {
5449                         if (is_file_exist(text) &&
5450                             (size = get_file_size(text)) > 0)
5451                                 file = g_strdup(text);
5452                         else {
5453                                 alertpanel_error
5454                                         (_("File doesn't exist or is empty."));
5455                                 g_free(cnttype);
5456                                 continue;
5457                         }
5458                 }
5459
5460                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.filename_entry));
5461                 if (*text != '\0') {
5462                         g_free(ainfo->name);
5463                         ainfo->name = g_strdup(text);
5464                 }
5465
5466                 if (cnttype) {
5467                         g_free(ainfo->content_type);
5468                         ainfo->content_type = cnttype;
5469                 }
5470                 if (file) {
5471                         g_free(ainfo->file);
5472                         ainfo->file = file;
5473                 }
5474                 if (size)
5475                         ainfo->size = size;
5476
5477                 gtk_clist_set_text(clist, row, COL_MIMETYPE,
5478                                    ainfo->content_type);
5479                 gtk_clist_set_text(clist, row, COL_SIZE,
5480                                    to_human_readable(ainfo->size));
5481                 gtk_clist_set_text(clist, row, COL_NAME, ainfo->name);
5482
5483                 gtk_widget_hide(attach_prop.window);
5484                 break;
5485         }
5486 }
5487
5488 #define SET_LABEL_AND_ENTRY(str, entry, top) \
5489 { \
5490         label = gtk_label_new(str); \
5491         gtk_table_attach(GTK_TABLE(table), label, 0, 1, top, (top + 1), \
5492                          GTK_FILL, 0, 0, 0); \
5493         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); \
5494  \
5495         entry = gtk_entry_new(); \
5496         gtk_table_attach(GTK_TABLE(table), entry, 1, 2, top, (top + 1), \
5497                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0); \
5498 }
5499
5500 static void compose_attach_property_create(gboolean *cancelled)
5501 {
5502         GtkWidget *window;
5503         GtkWidget *vbox;
5504         GtkWidget *table;
5505         GtkWidget *label;
5506         GtkWidget *mimetype_entry;
5507         GtkWidget *hbox;
5508         GtkWidget *optmenu;
5509         GtkWidget *optmenu_menu;
5510         GtkWidget *menuitem;
5511         GtkWidget *path_entry;
5512         GtkWidget *filename_entry;
5513         GtkWidget *hbbox;
5514         GtkWidget *ok_btn;
5515         GtkWidget *cancel_btn;
5516         GList     *mime_type_list, *strlist;
5517
5518         debug_print("Creating attach_property window...\n");
5519
5520         window = gtk_window_new(GTK_WINDOW_DIALOG);
5521         gtk_widget_set_usize(window, 480, -1);
5522         gtk_container_set_border_width(GTK_CONTAINER(window), 8);
5523         gtk_window_set_title(GTK_WINDOW(window), _("Properties"));
5524         gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
5525         gtk_window_set_modal(GTK_WINDOW(window), TRUE);
5526         gtk_signal_connect(GTK_OBJECT(window), "delete_event",
5527                            GTK_SIGNAL_FUNC(attach_property_delete_event),
5528                            cancelled);
5529         gtk_signal_connect(GTK_OBJECT(window), "key_press_event",
5530                            GTK_SIGNAL_FUNC(attach_property_key_pressed),
5531                            cancelled);
5532
5533         vbox = gtk_vbox_new(FALSE, 8);
5534         gtk_container_add(GTK_CONTAINER(window), vbox);
5535
5536         table = gtk_table_new(4, 2, FALSE);
5537         gtk_box_pack_start(GTK_BOX(vbox), table, FALSE, FALSE, 0);
5538         gtk_table_set_row_spacings(GTK_TABLE(table), 8);
5539         gtk_table_set_col_spacings(GTK_TABLE(table), 8);
5540
5541         label = gtk_label_new(_("MIME type")); 
5542         gtk_table_attach(GTK_TABLE(table), label, 0, 1, 0, (0 + 1), 
5543                          GTK_FILL, 0, 0, 0); 
5544         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); 
5545         mimetype_entry = gtk_combo_new(); 
5546         gtk_table_attach(GTK_TABLE(table), mimetype_entry, 1, 2, 0, (0 + 1), 
5547                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0);
5548                          
5549         /* stuff with list */
5550         mime_type_list = procmime_get_mime_type_list();
5551         strlist = NULL;
5552         for (; mime_type_list != NULL; mime_type_list = mime_type_list->next) {
5553                 MimeType *type = (MimeType *) mime_type_list->data;
5554                 strlist = g_list_append(strlist, 
5555                                 g_strdup_printf("%s/%s",
5556                                         type->type, type->sub_type));
5557         }
5558         
5559         gtk_combo_set_popdown_strings(GTK_COMBO(mimetype_entry), strlist);
5560
5561         for (mime_type_list = strlist; mime_type_list != NULL; 
5562                 mime_type_list = mime_type_list->next)
5563                 g_free(mime_type_list->data);
5564         g_list_free(strlist);
5565                          
5566         mimetype_entry = GTK_COMBO(mimetype_entry)->entry;                       
5567
5568         label = gtk_label_new(_("Encoding"));
5569         gtk_table_attach(GTK_TABLE(table), label, 0, 1, 1, 2,
5570                          GTK_FILL, 0, 0, 0);
5571         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5);
5572
5573         hbox = gtk_hbox_new(FALSE, 0);
5574         gtk_table_attach(GTK_TABLE(table), hbox, 1, 2, 1, 2,
5575                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0);
5576
5577         optmenu = gtk_option_menu_new();
5578         gtk_box_pack_start(GTK_BOX(hbox), optmenu, TRUE, TRUE, 0);
5579
5580         optmenu_menu = gtk_menu_new();
5581         MENUITEM_ADD(optmenu_menu, menuitem, "7bit", ENC_7BIT);
5582         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
5583 #if 0
5584         gtk_widget_set_sensitive(menuitem, FALSE);
5585 #endif
5586         MENUITEM_ADD(optmenu_menu, menuitem, "8bit", ENC_8BIT);
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, "quoted-printable",
5592                      ENC_QUOTED_PRINTABLE);
5593         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
5594
5595         MENUITEM_ADD(optmenu_menu, menuitem, "base64", ENC_BASE64);
5596
5597         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
5598
5599         SET_LABEL_AND_ENTRY(_("Path"),      path_entry,     2);
5600         SET_LABEL_AND_ENTRY(_("File name"), filename_entry, 3);
5601
5602         gtkut_button_set_create(&hbbox, &ok_btn, _("OK"),
5603                                 &cancel_btn, _("Cancel"), NULL, NULL);
5604         gtk_box_pack_end(GTK_BOX(vbox), hbbox, FALSE, FALSE, 0);
5605         gtk_widget_grab_default(ok_btn);
5606
5607         gtk_signal_connect(GTK_OBJECT(ok_btn), "clicked",
5608                            GTK_SIGNAL_FUNC(attach_property_ok),
5609                            cancelled);
5610         gtk_signal_connect(GTK_OBJECT(cancel_btn), "clicked",
5611                            GTK_SIGNAL_FUNC(attach_property_cancel),
5612                            cancelled);
5613
5614         gtk_widget_show_all(vbox);
5615
5616         attach_prop.window           = window;
5617         attach_prop.mimetype_entry   = mimetype_entry;
5618         attach_prop.encoding_optmenu = optmenu;
5619         attach_prop.path_entry       = path_entry;
5620         attach_prop.filename_entry   = filename_entry;
5621         attach_prop.ok_btn           = ok_btn;
5622         attach_prop.cancel_btn       = cancel_btn;
5623 }
5624
5625 #undef SET_LABEL_AND_ENTRY
5626
5627 static void attach_property_ok(GtkWidget *widget, gboolean *cancelled)
5628 {
5629         *cancelled = FALSE;
5630         gtk_main_quit();
5631 }
5632
5633 static void attach_property_cancel(GtkWidget *widget, gboolean *cancelled)
5634 {
5635         *cancelled = TRUE;
5636         gtk_main_quit();
5637 }
5638
5639 static gint attach_property_delete_event(GtkWidget *widget, GdkEventAny *event,
5640                                          gboolean *cancelled)
5641 {
5642         *cancelled = TRUE;
5643         gtk_main_quit();
5644
5645         return TRUE;
5646 }
5647
5648 static void attach_property_key_pressed(GtkWidget *widget, GdkEventKey *event,
5649                                         gboolean *cancelled)
5650 {
5651         if (event && event->keyval == GDK_Escape) {
5652                 *cancelled = TRUE;
5653                 gtk_main_quit();
5654         }
5655 }
5656
5657 static void compose_exec_ext_editor(Compose *compose)
5658 {
5659         gchar *tmp;
5660         pid_t pid;
5661         gint pipe_fds[2];
5662
5663         tmp = g_strdup_printf("%s%ctmpmsg.%p", get_tmp_dir(),
5664                               G_DIR_SEPARATOR, compose);
5665
5666         if (pipe(pipe_fds) < 0) {
5667                 perror("pipe");
5668                 g_free(tmp);
5669                 return;
5670         }
5671
5672         if ((pid = fork()) < 0) {
5673                 perror("fork");
5674                 g_free(tmp);
5675                 return;
5676         }
5677
5678         if (pid != 0) {
5679                 /* close the write side of the pipe */
5680                 close(pipe_fds[1]);
5681
5682                 compose->exteditor_file    = g_strdup(tmp);
5683                 compose->exteditor_pid     = pid;
5684                 compose->exteditor_readdes = pipe_fds[0];
5685
5686                 compose_set_ext_editor_sensitive(compose, FALSE);
5687
5688                 compose->exteditor_tag =
5689                         gdk_input_add(pipe_fds[0], GDK_INPUT_READ,
5690                                       compose_input_cb, compose);
5691         } else {        /* process-monitoring process */
5692                 pid_t pid_ed;
5693
5694                 if (setpgid(0, 0))
5695                         perror("setpgid");
5696
5697                 /* close the read side of the pipe */
5698                 close(pipe_fds[0]);
5699
5700                 if (compose_write_body_to_file(compose, tmp) < 0) {
5701                         fd_write_all(pipe_fds[1], "2\n", 2);
5702                         _exit(1);
5703                 }
5704
5705                 pid_ed = compose_exec_ext_editor_real(tmp);
5706                 if (pid_ed < 0) {
5707                         fd_write_all(pipe_fds[1], "1\n", 2);
5708                         _exit(1);
5709                 }
5710
5711                 /* wait until editor is terminated */
5712                 waitpid(pid_ed, NULL, 0);
5713
5714                 fd_write_all(pipe_fds[1], "0\n", 2);
5715
5716                 close(pipe_fds[1]);
5717                 _exit(0);
5718         }
5719
5720         g_free(tmp);
5721 }
5722
5723 static gint compose_exec_ext_editor_real(const gchar *file)
5724 {
5725         static gchar *def_cmd = "emacs %s";
5726         gchar buf[1024];
5727         gchar *p;
5728         gchar **cmdline;
5729         pid_t pid;
5730
5731         g_return_val_if_fail(file != NULL, -1);
5732
5733         if ((pid = fork()) < 0) {
5734                 perror("fork");
5735                 return -1;
5736         }
5737
5738         if (pid != 0) return pid;
5739
5740         /* grandchild process */
5741
5742         if (setpgid(0, getppid()))
5743                 perror("setpgid");
5744
5745         if (prefs_common.ext_editor_cmd &&
5746             (p = strchr(prefs_common.ext_editor_cmd, '%')) &&
5747             *(p + 1) == 's' && !strchr(p + 2, '%')) {
5748                 g_snprintf(buf, sizeof(buf), prefs_common.ext_editor_cmd, file);
5749         } else {
5750                 if (prefs_common.ext_editor_cmd)
5751                         g_warning("External editor command line is invalid: `%s'\n",
5752                                   prefs_common.ext_editor_cmd);
5753                 g_snprintf(buf, sizeof(buf), def_cmd, file);
5754         }
5755
5756         cmdline = strsplit_with_quote(buf, " ", 1024);
5757         execvp(cmdline[0], cmdline);
5758
5759         perror("execvp");
5760         g_strfreev(cmdline);
5761
5762         _exit(1);
5763 }
5764
5765 static gboolean compose_ext_editor_kill(Compose *compose)
5766 {
5767         pid_t pgid = compose->exteditor_pid * -1;
5768         gint ret;
5769
5770         ret = kill(pgid, 0);
5771
5772         if (ret == 0 || (ret == -1 && EPERM == errno)) {
5773                 AlertValue val;
5774                 gchar *msg;
5775
5776                 msg = g_strdup_printf
5777                         (_("The external editor is still working.\n"
5778                            "Force terminating the process?\n"
5779                            "process group id: %d"), -pgid);
5780                 val = alertpanel(_("Notice"), msg, _("Yes"), _("+No"), NULL);
5781                 g_free(msg);
5782
5783                 if (val == G_ALERTDEFAULT) {
5784                         gdk_input_remove(compose->exteditor_tag);
5785                         close(compose->exteditor_readdes);
5786
5787                         if (kill(pgid, SIGTERM) < 0) perror("kill");
5788                         waitpid(compose->exteditor_pid, NULL, 0);
5789
5790                         g_warning("Terminated process group id: %d", -pgid);
5791                         g_warning("Temporary file: %s",
5792                                   compose->exteditor_file);
5793
5794                         compose_set_ext_editor_sensitive(compose, TRUE);
5795
5796                         g_free(compose->exteditor_file);
5797                         compose->exteditor_file    = NULL;
5798                         compose->exteditor_pid     = -1;
5799                         compose->exteditor_readdes = -1;
5800                         compose->exteditor_tag     = -1;
5801                 } else
5802                         return FALSE;
5803         }
5804
5805         return TRUE;
5806 }
5807
5808 static void compose_input_cb(gpointer data, gint source,
5809                              GdkInputCondition condition)
5810 {
5811         gchar buf[3];
5812         Compose *compose = (Compose *)data;
5813         gint i = 0;
5814
5815         debug_print("Compose: input from monitoring process\n");
5816
5817         gdk_input_remove(compose->exteditor_tag);
5818
5819         for (;;) {
5820                 if (read(source, &buf[i], 1) < 1) {
5821                         buf[0] = '3';
5822                         break;
5823                 }
5824                 if (buf[i] == '\n') {
5825                         buf[i] = '\0';
5826                         break;
5827                 }
5828                 i++;
5829                 if (i == sizeof(buf) - 1)
5830                         break;
5831         }
5832
5833         waitpid(compose->exteditor_pid, NULL, 0);
5834
5835         if (buf[0] == '0') {            /* success */
5836                 GtkSText *text = GTK_STEXT(compose->text);
5837
5838                 gtk_stext_freeze(text);
5839                 gtk_stext_set_point(text, 0);
5840                 gtk_stext_forward_delete(text, gtk_stext_get_length(text));
5841                 compose_insert_file(compose, compose->exteditor_file);
5842                 compose_changed_cb(NULL, compose);
5843                 gtk_stext_thaw(text);
5844
5845                 if (unlink(compose->exteditor_file) < 0)
5846                         FILE_OP_ERROR(compose->exteditor_file, "unlink");
5847         } else if (buf[0] == '1') {     /* failed */
5848                 g_warning("Couldn't exec external editor\n");
5849                 if (unlink(compose->exteditor_file) < 0)
5850                         FILE_OP_ERROR(compose->exteditor_file, "unlink");
5851         } else if (buf[0] == '2') {
5852                 g_warning("Couldn't write to file\n");
5853         } else if (buf[0] == '3') {
5854                 g_warning("Pipe read failed\n");
5855         }
5856
5857         close(source);
5858
5859         compose_set_ext_editor_sensitive(compose, TRUE);
5860
5861         g_free(compose->exteditor_file);
5862         compose->exteditor_file    = NULL;
5863         compose->exteditor_pid     = -1;
5864         compose->exteditor_readdes = -1;
5865         compose->exteditor_tag     = -1;
5866 }
5867
5868 static void compose_set_ext_editor_sensitive(Compose *compose,
5869                                              gboolean sensitive)
5870 {
5871         GtkItemFactory *ifactory;
5872
5873         ifactory = gtk_item_factory_from_widget(compose->menubar);
5874
5875         menu_set_sensitive(ifactory, "/Message/Send", sensitive);
5876         menu_set_sensitive(ifactory, "/Message/Send later", sensitive);
5877         menu_set_sensitive(ifactory, "/Message/Insert file", sensitive);
5878         menu_set_sensitive(ifactory, "/Message/Insert signature", sensitive);
5879         menu_set_sensitive(ifactory, "/Edit/Wrap current paragraph", sensitive);
5880         menu_set_sensitive(ifactory, "/Edit/Wrap all long lines", sensitive);
5881         menu_set_sensitive(ifactory, "/Edit/Edit with external editor",
5882                            sensitive);
5883
5884         gtk_widget_set_sensitive(compose->text,                   sensitive);
5885         gtk_widget_set_sensitive(compose->toolbar->send_btn,      sensitive);
5886         gtk_widget_set_sensitive(compose->toolbar->sendl_btn,     sensitive);
5887         gtk_widget_set_sensitive(compose->toolbar->draft_btn,     sensitive);
5888         gtk_widget_set_sensitive(compose->toolbar->insert_btn,    sensitive);
5889         gtk_widget_set_sensitive(compose->toolbar->sig_btn,       sensitive);
5890         gtk_widget_set_sensitive(compose->toolbar->exteditor_btn, sensitive);
5891         gtk_widget_set_sensitive(compose->toolbar->linewrap_current_btn,  sensitive);
5892         gtk_widget_set_sensitive(compose->toolbar->linewrap_all_btn,  sensitive);
5893 }
5894
5895 /**
5896  * compose_undo_state_changed:
5897  *
5898  * Change the sensivity of the menuentries undo and redo
5899  **/
5900 static void compose_undo_state_changed(UndoMain *undostruct, gint undo_state,
5901                                        gint redo_state, gpointer data)
5902 {
5903         GtkWidget *widget = GTK_WIDGET(data);
5904         GtkItemFactory *ifactory;
5905
5906         g_return_if_fail(widget != NULL);
5907
5908         ifactory = gtk_item_factory_from_widget(widget);
5909
5910         switch (undo_state) {
5911         case UNDO_STATE_TRUE:
5912                 if (!undostruct->undo_state) {
5913                         undostruct->undo_state = TRUE;
5914                         menu_set_sensitive(ifactory, "/Edit/Undo", TRUE);
5915                 }
5916                 break;
5917         case UNDO_STATE_FALSE:
5918                 if (undostruct->undo_state) {
5919                         undostruct->undo_state = FALSE;
5920                         menu_set_sensitive(ifactory, "/Edit/Undo", FALSE);
5921                 }
5922                 break;
5923         case UNDO_STATE_UNCHANGED:
5924                 break;
5925         case UNDO_STATE_REFRESH:
5926                 menu_set_sensitive(ifactory, "/Edit/Undo",
5927                                    undostruct->undo_state);
5928                 break;
5929         default:
5930                 g_warning("Undo state not recognized");
5931                 break;
5932         }
5933
5934         switch (redo_state) {
5935         case UNDO_STATE_TRUE:
5936                 if (!undostruct->redo_state) {
5937                         undostruct->redo_state = TRUE;
5938                         menu_set_sensitive(ifactory, "/Edit/Redo", TRUE);
5939                 }
5940                 break;
5941         case UNDO_STATE_FALSE:
5942                 if (undostruct->redo_state) {
5943                         undostruct->redo_state = FALSE;
5944                         menu_set_sensitive(ifactory, "/Edit/Redo", FALSE);
5945                 }
5946                 break;
5947         case UNDO_STATE_UNCHANGED:
5948                 break;
5949         case UNDO_STATE_REFRESH:
5950                 menu_set_sensitive(ifactory, "/Edit/Redo",
5951                                    undostruct->redo_state);
5952                 break;
5953         default:
5954                 g_warning("Redo state not recognized");
5955                 break;
5956         }
5957 }
5958
5959 static gint calc_cursor_xpos(GtkSText *text, gint extra, gint char_width)
5960 {
5961         gint cursor_pos;
5962
5963         cursor_pos = (text->cursor_pos_x - extra) / char_width;
5964         cursor_pos = MAX(cursor_pos, 0);
5965
5966         return cursor_pos;
5967 }
5968
5969 /* callback functions */
5970
5971 /* compose_edit_size_alloc() - called when resized. don't know whether Gtk
5972  * includes "non-client" (windows-izm) in calculation, so this calculation
5973  * may not be accurate.
5974  */
5975 static gboolean compose_edit_size_alloc(GtkEditable *widget,
5976                                         GtkAllocation *allocation,
5977                                         GtkSHRuler *shruler)
5978 {
5979         if (prefs_common.show_ruler) {
5980                 gint char_width;
5981                 gint line_width_in_chars;
5982
5983                 char_width = gtkut_get_font_width
5984                         (GTK_WIDGET(widget)->style->font);
5985                 line_width_in_chars =
5986                         (allocation->width - allocation->x) / char_width;
5987
5988                 /* got the maximum */
5989                 gtk_ruler_set_range(GTK_RULER(shruler),
5990                                     0.0, line_width_in_chars,
5991                                     calc_cursor_xpos(GTK_STEXT(widget),
5992                                                      allocation->x,
5993                                                      char_width),
5994                                     /*line_width_in_chars*/ char_width);
5995         }
5996
5997         return TRUE;
5998 }
5999
6000 static void account_activated(GtkMenuItem *menuitem, gpointer data)
6001 {
6002         Compose *compose = (Compose *)data;
6003
6004         PrefsAccount *ac;
6005         gchar *folderidentifier;
6006
6007         ac = account_find_from_id(
6008                 GPOINTER_TO_INT(gtk_object_get_user_data(GTK_OBJECT(menuitem))));
6009         g_return_if_fail(ac != NULL);
6010
6011         if (ac != compose->account)
6012                 compose_select_account(compose, ac, FALSE);
6013
6014         /* Set message save folder */
6015         if (account_get_special_folder(compose->account, F_OUTBOX)) {
6016                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), prefs_common.savemsg);
6017         }
6018         gtk_signal_connect(GTK_OBJECT(compose->savemsg_checkbtn), "toggled",
6019                            GTK_SIGNAL_FUNC(compose_savemsg_checkbtn_cb), compose);
6020                            
6021         gtk_editable_delete_text(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
6022         if (account_get_special_folder(compose->account, F_OUTBOX)) {
6023                 folderidentifier = folder_item_get_identifier(account_get_special_folder
6024                                   (compose->account, F_OUTBOX));
6025                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
6026                 g_free(folderidentifier);
6027         }
6028 }
6029
6030 static void attach_selected(GtkCList *clist, gint row, gint column,
6031                             GdkEvent *event, gpointer data)
6032 {
6033         Compose *compose = (Compose *)data;
6034
6035         if (event && event->type == GDK_2BUTTON_PRESS)
6036                 compose_attach_property(compose);
6037 }
6038
6039 static void attach_button_pressed(GtkWidget *widget, GdkEventButton *event,
6040                                   gpointer data)
6041 {
6042         Compose *compose = (Compose *)data;
6043         GtkCList *clist = GTK_CLIST(compose->attach_clist);
6044         gint row, column;
6045
6046         if (!event) return;
6047
6048         if (event->button == 3) {
6049                 if ((clist->selection && !clist->selection->next) ||
6050                     !clist->selection) {
6051                         gtk_clist_unselect_all(clist);
6052                         if (gtk_clist_get_selection_info(clist,
6053                                                          event->x, event->y,
6054                                                          &row, &column)) {
6055                                 gtk_clist_select_row(clist, row, column);
6056                                 gtkut_clist_set_focus_row(clist, row);
6057                         }
6058                 }
6059                 gtk_menu_popup(GTK_MENU(compose->popupmenu), NULL, NULL,
6060                                NULL, NULL, event->button, event->time);
6061         }
6062 }
6063
6064 static void attach_key_pressed(GtkWidget *widget, GdkEventKey *event,
6065                                gpointer data)
6066 {
6067         Compose *compose = (Compose *)data;
6068
6069         if (!event) return;
6070
6071         switch (event->keyval) {
6072         case GDK_Delete:
6073                 compose_attach_remove_selected(compose);
6074                 break;
6075         }
6076 }
6077
6078 static void compose_allow_user_actions (Compose *compose, gboolean allow)
6079 {
6080         GtkItemFactory *ifactory = gtk_item_factory_from_widget(compose->menubar);
6081         toolbar_comp_set_sensitive(compose, allow);
6082         menu_set_sensitive(ifactory, "/Message", allow);
6083         menu_set_sensitive(ifactory, "/Edit", allow);
6084 #if USE_ASPELL
6085         menu_set_sensitive(ifactory, "/Spelling", allow);
6086 #endif  
6087         menu_set_sensitive(ifactory, "/Options", allow);
6088         menu_set_sensitive(ifactory, "/Tools", allow);
6089         menu_set_sensitive(ifactory, "/Help", allow);
6090 }
6091
6092 static void compose_send_cb(gpointer data, guint action, GtkWidget *widget)
6093 {
6094         Compose *compose = (Compose *)data;
6095         
6096         if (prefs_common.work_offline)
6097                 if (alertpanel(_("Offline warning"), 
6098                                _("You're working offline. Override?"),
6099                                _("Yes"), _("No"), NULL) != G_ALERTDEFAULT)
6100                         return;
6101         
6102         if (compose->draft_timeout_tag != -1) { /* CLAWS: disable draft timeout */
6103                 gtk_timeout_remove(compose->draft_timeout_tag);
6104                 compose->draft_timeout_tag = -1;
6105         }
6106
6107         compose_send(compose);
6108 }
6109
6110 static void compose_send_later_cb(gpointer data, guint action,
6111                                   GtkWidget *widget)
6112 {
6113         Compose *compose = (Compose *)data;
6114         gint val;
6115
6116         val = compose_queue_sub(compose, NULL, NULL, TRUE);
6117         if (!val) 
6118                 compose_close(compose);
6119 }
6120
6121 void compose_draft (gpointer data) 
6122 {
6123         compose_draft_cb(data, COMPOSE_QUIT_EDITING, NULL);     
6124 }
6125
6126 static void compose_draft_cb(gpointer data, guint action, GtkWidget *widget)
6127 {
6128         Compose *compose = (Compose *)data;
6129         FolderItem *draft;
6130         gchar *tmp;
6131         gint msgnum;
6132         MsgFlags flag = {0, 0};
6133         static gboolean lock = FALSE;
6134         MsgInfo *newmsginfo;
6135         FILE *fp;
6136         
6137         if (lock) return;
6138
6139         draft = account_get_special_folder(compose->account, F_DRAFT);
6140         g_return_if_fail(draft != NULL);
6141
6142         lock = TRUE;
6143
6144         tmp = g_strdup_printf("%s%cdraft.%p", get_tmp_dir(),
6145                               G_DIR_SEPARATOR, compose);
6146         if ((fp = fopen(tmp, "wb")) == NULL) {
6147                 FILE_OP_ERROR(tmp, "fopen");
6148                 return;
6149         }
6150
6151         /* chmod for security */
6152         if (change_file_mode_rw(fp, tmp) < 0) {
6153                 FILE_OP_ERROR(tmp, "chmod");
6154                 g_warning("can't change file mode\n");
6155         }
6156
6157         /* Save draft infos */
6158         fprintf(fp, "X-Sylpheed-Account-Id:%d\n", compose->account->account_id);
6159         fprintf(fp, "S:%s\n", compose->account->address);
6160         if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn))) {
6161                 gchar *savefolderid;
6162
6163                 savefolderid = gtk_editable_get_chars(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
6164                 fprintf(fp, "SCF:%s\n", savefolderid);
6165                 g_free(savefolderid);
6166         }
6167         if (compose->privacy_system) {
6168                 fprintf(fp, "X-Sylpheed-Sign:%d\n", compose->use_signing);
6169                 fprintf(fp, "X-Sylpheed-Encrypt:%d\n", compose->use_encryption);
6170                 fprintf(fp, "X-Sylpheed-Privacy-System:%s\n", compose->privacy_system);
6171         }
6172         fprintf(fp, "\n");
6173
6174         if (compose_write_to_file(compose, fp, COMPOSE_WRITE_FOR_STORE) < 0) {
6175                 fclose(fp);
6176                 unlink(tmp);
6177                 g_free(tmp);
6178                 lock = FALSE;
6179                 return;
6180         }
6181         fclose(fp);
6182
6183         folder_item_scan(draft);
6184         if ((msgnum = folder_item_add_msg(draft, tmp, &flag, TRUE)) < 0) {
6185                 unlink(tmp);
6186                 g_free(tmp);
6187                 lock = FALSE;
6188                 return;
6189         }
6190         g_free(tmp);
6191         draft->mtime = 0;       /* force updating */
6192
6193         if (compose->mode == COMPOSE_REEDIT) {
6194                 compose_remove_reedit_target(compose);
6195         }
6196
6197         newmsginfo = folder_item_get_msginfo(draft, msgnum);
6198         if (newmsginfo) {
6199                 procmsg_msginfo_unset_flags(newmsginfo, ~0, ~0);
6200                 procmsg_msginfo_set_flags(newmsginfo, 0, MSG_DRAFT);
6201                 if (compose_use_attach(compose))
6202                         procmsg_msginfo_set_flags(newmsginfo, 0,
6203                                                   MSG_HAS_ATTACHMENT);
6204
6205                 procmsg_msginfo_free(newmsginfo);
6206         }
6207         
6208         folder_item_scan(draft);
6209         
6210         lock = FALSE;
6211
6212         if (action == COMPOSE_QUIT_EDITING)
6213                 compose_close(compose);
6214         else {
6215                 struct stat s;
6216                 gchar *path;
6217
6218                 path = folder_item_fetch_msg(draft, msgnum);
6219                 g_return_if_fail(path != NULL);
6220                 if (stat(path, &s) < 0) {
6221                         FILE_OP_ERROR(path, "stat");
6222                         g_free(path);
6223                         lock = FALSE;
6224                         return;
6225                 }
6226                 g_free(path);
6227
6228                 procmsg_msginfo_free(compose->targetinfo);
6229                 compose->targetinfo = procmsg_msginfo_new();
6230                 compose->targetinfo->msgnum = msgnum;
6231                 compose->targetinfo->size = s.st_size;
6232                 compose->targetinfo->mtime = s.st_mtime;
6233                 compose->targetinfo->folder = draft;
6234                 compose->mode = COMPOSE_REEDIT;
6235                 
6236                 if (action == COMPOSE_AUTO_SAVE) {
6237                         compose->autosaved_draft = compose->targetinfo;
6238                 }
6239         }
6240 }
6241
6242 static void compose_attach_cb(gpointer data, guint action, GtkWidget *widget)
6243 {
6244         Compose *compose = (Compose *)data;
6245         GList *file_list;
6246
6247         if (compose->redirect_filename != NULL)
6248                 return;
6249
6250         file_list = filesel_select_multiple_files(_("Select file"), NULL);
6251
6252         if (file_list) {
6253                 GList *tmp;
6254
6255                 for ( tmp = file_list; tmp; tmp = tmp->next) {
6256                         gchar *file = (gchar *) tmp->data;
6257                         compose_attach_append(compose, file, file, NULL);
6258                         compose_changed_cb(NULL, compose);
6259                         g_free(file);
6260                 }
6261                 g_list_free(file_list);
6262         }               
6263 }
6264
6265 static void compose_insert_file_cb(gpointer data, guint action,
6266                                    GtkWidget *widget)
6267 {
6268         Compose *compose = (Compose *)data;
6269         GList *file_list;
6270
6271         file_list = filesel_select_multiple_files(_("Select file"), NULL);
6272
6273         if (file_list) {
6274                 GList *tmp;
6275
6276                 for ( tmp = file_list; tmp; tmp = tmp->next) {
6277                         gchar *file = (gchar *) tmp->data;
6278                         gchar *filedup = g_strdup(file);
6279                         gchar *shortfile;
6280                         ComposeInsertResult res;
6281
6282                         res = compose_insert_file(compose, file);
6283                         shortfile = g_basename(filedup);
6284                         if (res == COMPOSE_INSERT_READ_ERROR) {
6285                                 alertpanel_error(_("File '%s' could not be read."), shortfile);
6286                         } else if (res == COMPOSE_INSERT_INVALID_CHARACTER) {
6287                                 alertpanel_error(_("File '%s' contained invalid characters\n"
6288                                                    "for the current encoding, insertion may be incorrect."), shortfile);
6289                         }
6290                         g_free(filedup);
6291                         g_free(file);
6292                 }
6293                 g_list_free(file_list);
6294         }
6295 }
6296
6297 static void compose_insert_sig_cb(gpointer data, guint action,
6298                                   GtkWidget *widget)
6299 {
6300         Compose *compose = (Compose *)data;
6301
6302         compose_insert_sig(compose, FALSE);
6303 }
6304
6305 static gint compose_delete_cb(GtkWidget *widget, GdkEventAny *event,
6306                               gpointer data)
6307 {
6308         gint x, y;
6309         Compose *compose = (Compose *)data;
6310
6311         gtkut_widget_get_uposition(widget, &x, &y);
6312         prefs_common.compose_x = x;
6313         prefs_common.compose_y = y;
6314
6315         if (compose->sending)
6316                 return TRUE;
6317         compose_close_cb(compose, 0, NULL);
6318         return TRUE;
6319 }
6320
6321 static void compose_close_cb(gpointer data, guint action, GtkWidget *widget)
6322 {
6323         Compose *compose = (Compose *)data;
6324         AlertValue val;
6325
6326         if (compose->exteditor_tag != -1) {
6327                 if (!compose_ext_editor_kill(compose))
6328                         return;
6329         }
6330
6331         if (compose->modified) {
6332                 val = alertpanel(_("Discard message"),
6333                                  _("This message has been modified. discard it?"),
6334                                  _("Discard"), _("to Draft"), _("Cancel"));
6335
6336                 switch (val) {
6337                 case G_ALERTDEFAULT:
6338                         if (prefs_common.autosave)
6339                                 compose_remove_draft(compose);                  
6340                         break;
6341                 case G_ALERTALTERNATE:
6342                         compose_draft_cb(data, COMPOSE_QUIT_EDITING, NULL);
6343                         return;
6344                 default:
6345                         return;
6346                 }
6347         }
6348
6349         compose_close(compose);
6350 }
6351
6352 static void compose_address_cb(gpointer data, guint action, GtkWidget *widget)
6353 {
6354         Compose *compose = (Compose *)data;
6355
6356         addressbook_open(compose);
6357 }
6358
6359 static void compose_template_activate_cb(GtkWidget *widget, gpointer data)
6360 {
6361         Compose *compose = (Compose *)data;
6362         Template *tmpl;
6363         gchar *msg;
6364         AlertValue val;
6365
6366         tmpl = gtk_object_get_data(GTK_OBJECT(widget), "template");
6367         g_return_if_fail(tmpl != NULL);
6368
6369         msg = g_strdup_printf(_("Do you want to apply the template `%s' ?"),
6370                               tmpl->name);
6371         val = alertpanel(_("Apply template"), msg,
6372                          _("Replace"), _("Insert"), _("Cancel"));
6373         g_free(msg);
6374
6375         if (val == G_ALERTDEFAULT)
6376                 compose_template_apply(compose, tmpl, TRUE);
6377         else if (val == G_ALERTALTERNATE)
6378                 compose_template_apply(compose, tmpl, FALSE);
6379 }
6380
6381 static void compose_ext_editor_cb(gpointer data, guint action,
6382                                   GtkWidget *widget)
6383 {
6384         Compose *compose = (Compose *)data;
6385
6386         compose_exec_ext_editor(compose);
6387 }
6388
6389 static void compose_destroy_cb(GtkWidget *widget, Compose *compose)
6390 {
6391         if (compose->sending)
6392                 return;
6393         compose_destroy(compose);
6394 }
6395
6396 static void compose_undo_cb(Compose *compose)
6397 {
6398         undo_undo(compose->undostruct);
6399 }
6400
6401 static void compose_redo_cb(Compose *compose)
6402 {
6403         undo_redo(compose->undostruct);
6404 }
6405
6406 static void compose_cut_cb(Compose *compose)
6407 {
6408         if (compose->focused_editable &&
6409             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
6410                 gtk_editable_cut_clipboard
6411                         (GTK_EDITABLE(compose->focused_editable));
6412 }
6413
6414 static void compose_copy_cb(Compose *compose)
6415 {
6416         if (compose->focused_editable &&
6417             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
6418                 gtk_editable_copy_clipboard
6419                         (GTK_EDITABLE(compose->focused_editable));
6420 }
6421
6422 static void compose_paste_cb(Compose *compose)
6423 {
6424         if (compose->focused_editable &&
6425             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
6426                 gtk_editable_paste_clipboard
6427                         (GTK_EDITABLE(compose->focused_editable));
6428 }
6429
6430 static void compose_paste_as_quote_cb(Compose *compose)
6431 {
6432         if (compose->focused_editable &&
6433             GTK_WIDGET_HAS_FOCUS(compose->focused_editable)) {
6434                 /* let text_insert() (called directly or at a later time
6435                  * after the gtk_editable_paste_clipboard) know that 
6436                  * text is to be inserted as a quotation. implemented
6437                  * by using a simple refcount... */
6438                 gint paste_as_quotation = GPOINTER_TO_INT(gtk_object_get_data(
6439                                                 GTK_OBJECT(compose->focused_editable),
6440                                                 "paste_as_quotation"));
6441                 gtk_object_set_data(GTK_OBJECT(compose->focused_editable),
6442                                     "paste_as_quotation",
6443                                     GINT_TO_POINTER(paste_as_quotation + 1));
6444                 gtk_editable_paste_clipboard
6445                         (GTK_EDITABLE(compose->focused_editable));
6446         }
6447 }
6448
6449 static void compose_allsel_cb(Compose *compose)
6450 {
6451         if (compose->focused_editable &&
6452             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
6453                 gtk_editable_select_region
6454                         (GTK_EDITABLE(compose->focused_editable), 0, -1);
6455 }
6456
6457 static void compose_gtk_stext_action_cb(Compose *compose,
6458                                         ComposeCallGtkSTextAction action)
6459 {
6460         GtkSText *text = GTK_STEXT(compose->text);
6461         static struct {
6462                 void (*do_action) (GtkSText *text);
6463         } action_table[] = {
6464                 {gtk_stext_move_beginning_of_line},
6465                 {gtk_stext_move_forward_character},
6466                 {gtk_stext_move_backward_character},
6467                 {gtk_stext_move_forward_word},
6468                 {gtk_stext_move_backward_word},
6469                 {gtk_stext_move_end_of_line},
6470                 {gtk_stext_move_next_line},
6471                 {gtk_stext_move_previous_line},
6472                 {gtk_stext_delete_forward_character},
6473                 {gtk_stext_delete_backward_character},
6474                 {gtk_stext_delete_forward_word},
6475                 {gtk_stext_delete_backward_word},
6476                 {gtk_stext_delete_line},
6477                 {gtk_stext_delete_line}, /* gtk_stext_delete_line_n */
6478                 {gtk_stext_delete_to_line_end}
6479         };
6480
6481         if (!GTK_WIDGET_HAS_FOCUS(text)) return;
6482
6483         if (action >= COMPOSE_CALL_GTK_STEXT_MOVE_BEGINNING_OF_LINE &&
6484             action <= COMPOSE_CALL_GTK_STEXT_DELETE_TO_LINE_END)
6485                 action_table[action].do_action(text);
6486 }
6487
6488 static void compose_grab_focus_cb(GtkWidget *widget, Compose *compose)
6489 {
6490         if (GTK_IS_EDITABLE(widget))
6491                 compose->focused_editable = widget;
6492 }
6493
6494 static void compose_changed_cb(GtkEditable *editable, Compose *compose)
6495 {
6496         if (compose->modified == FALSE) {
6497                 compose->modified = TRUE;
6498                 compose_set_title(compose);
6499         }
6500 }
6501
6502 static void compose_button_press_cb(GtkWidget *widget, GdkEventButton *event,
6503                                     Compose *compose)
6504 {
6505         gtk_stext_set_point(GTK_STEXT(widget),
6506                            gtk_editable_get_position(GTK_EDITABLE(widget)));
6507 }
6508
6509 #if 0
6510 static void compose_key_press_cb(GtkWidget *widget, GdkEventKey *event,
6511                                  Compose *compose)
6512 {
6513         gtk_stext_set_point(GTK_STEXT(widget),
6514                            gtk_editable_get_position(GTK_EDITABLE(widget)));
6515 }
6516 #endif
6517
6518 static void compose_toggle_autowrap_cb(gpointer data, guint action,
6519                                        GtkWidget *widget)
6520 {
6521         Compose *compose = (Compose *)data;
6522
6523         compose->autowrap = GTK_CHECK_MENU_ITEM(widget)->active;
6524         if (compose->autowrap)
6525                 compose_wrap_line_all_full(compose, TRUE);
6526 }
6527
6528 static void compose_toggle_sign_cb(gpointer data, guint action,
6529                                    GtkWidget *widget)
6530 {
6531         Compose *compose = (Compose *)data;
6532
6533         if (GTK_CHECK_MENU_ITEM(widget)->active)
6534                 compose->use_signing = TRUE;
6535         else
6536                 compose->use_signing = FALSE;
6537 }
6538
6539 static void compose_toggle_encrypt_cb(gpointer data, guint action,
6540                                       GtkWidget *widget)
6541 {
6542         Compose *compose = (Compose *)data;
6543
6544         if (GTK_CHECK_MENU_ITEM(widget)->active)
6545                 compose->use_encryption = TRUE;
6546         else
6547                 compose->use_encryption = FALSE;
6548 }
6549
6550 static void activate_privacy_system(Compose *compose, PrefsAccount *account) 
6551 {
6552         g_free(compose->privacy_system);
6553         compose->privacy_system = g_strdup(account->default_privacy_system);
6554         compose_update_privacy_system_menu_item(compose);
6555 }
6556
6557 static void compose_toggle_ruler_cb(gpointer data, guint action,
6558                                     GtkWidget *widget)
6559 {
6560         Compose *compose = (Compose *)data;
6561
6562         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6563                 gtk_widget_show(compose->ruler_hbox);
6564                 prefs_common.show_ruler = TRUE;
6565         } else {
6566                 gtk_widget_hide(compose->ruler_hbox);
6567                 gtk_widget_queue_resize(compose->edit_vbox);
6568                 prefs_common.show_ruler = FALSE;
6569         }
6570 }
6571
6572 static void compose_attach_drag_received_cb (GtkWidget          *widget,
6573                                              GdkDragContext     *drag_context,
6574                                              gint                x,
6575                                              gint                y,
6576                                              GtkSelectionData   *data,
6577                                              guint               info,
6578                                              guint               time,
6579                                              gpointer            user_data)
6580 {
6581         Compose *compose = (Compose *)user_data;
6582         GList *list, *tmp;
6583
6584         list = uri_list_extract_filenames((const gchar *)data->data);
6585         for (tmp = list; tmp != NULL; tmp = tmp->next)
6586                 compose_attach_append
6587                         (compose, (const gchar *)tmp->data,
6588                          (const gchar *)tmp->data, NULL);
6589         if (list) compose_changed_cb(NULL, compose);
6590         list_free_strings(list);
6591         g_list_free(list);
6592 }
6593
6594 static void compose_insert_drag_received_cb (GtkWidget          *widget,
6595                                              GdkDragContext     *drag_context,
6596                                              gint                x,
6597                                              gint                y,
6598                                              GtkSelectionData   *data,
6599                                              guint               info,
6600                                              guint               time,
6601                                              gpointer            user_data)
6602 {
6603         Compose *compose = (Compose *)user_data;
6604         GList *list, *tmp;
6605
6606         list = uri_list_extract_filenames((const gchar *)data->data);
6607         for (tmp = list; tmp != NULL; tmp = tmp->next)
6608                 compose_insert_file(compose, (const gchar *)tmp->data);
6609         list_free_strings(list);
6610         g_list_free(list);
6611 }
6612
6613 #if 0 /* NEW COMPOSE GUI */
6614 static void to_activated(GtkWidget *widget, Compose *compose)
6615 {
6616         if (GTK_WIDGET_VISIBLE(compose->newsgroups_entry))
6617                 gtk_widget_grab_focus(compose->newsgroups_entry);
6618         else
6619                 gtk_widget_grab_focus(compose->subject_entry);
6620 }
6621
6622 static void newsgroups_activated(GtkWidget *widget, Compose *compose)
6623 {
6624         gtk_widget_grab_focus(compose->subject_entry);
6625 }
6626
6627 static void subject_activated(GtkWidget *widget, Compose *compose)
6628 {
6629         if (GTK_WIDGET_VISIBLE(compose->cc_entry))
6630                 gtk_widget_grab_focus(compose->cc_entry);
6631         else if (GTK_WIDGET_VISIBLE(compose->bcc_entry))
6632                 gtk_widget_grab_focus(compose->bcc_entry);
6633         else if (GTK_WIDGET_VISIBLE(compose->reply_entry))
6634                 gtk_widget_grab_focus(compose->reply_entry);
6635         else if (GTK_WIDGET_VISIBLE(compose->followup_entry))
6636                 gtk_widget_grab_focus(compose->followup_entry);
6637         else
6638                 gtk_widget_grab_focus(compose->text);
6639 }
6640
6641 static void cc_activated(GtkWidget *widget, Compose *compose)
6642 {
6643         if (GTK_WIDGET_VISIBLE(compose->bcc_entry))
6644                 gtk_widget_grab_focus(compose->bcc_entry);
6645         else if (GTK_WIDGET_VISIBLE(compose->reply_entry))
6646                 gtk_widget_grab_focus(compose->reply_entry);
6647         else if (GTK_WIDGET_VISIBLE(compose->followup_entry))
6648                 gtk_widget_grab_focus(compose->followup_entry);
6649         else
6650                 gtk_widget_grab_focus(compose->text);
6651 }
6652
6653 static void bcc_activated(GtkWidget *widget, Compose *compose)
6654 {
6655         if (GTK_WIDGET_VISIBLE(compose->reply_entry))
6656                 gtk_widget_grab_focus(compose->reply_entry);
6657         else if (GTK_WIDGET_VISIBLE(compose->followup_entry))
6658                 gtk_widget_grab_focus(compose->followup_entry);
6659         else
6660                 gtk_widget_grab_focus(compose->text);
6661 }
6662
6663 static void replyto_activated(GtkWidget *widget, Compose *compose)
6664 {
6665         if (GTK_WIDGET_VISIBLE(compose->followup_entry))
6666                 gtk_widget_grab_focus(compose->followup_entry);
6667         else
6668                 gtk_widget_grab_focus(compose->text);
6669 }
6670
6671 static void followupto_activated(GtkWidget *widget, Compose *compose)
6672 {
6673         gtk_widget_grab_focus(compose->text);
6674 }
6675 #endif
6676
6677 static void compose_toggle_return_receipt_cb(gpointer data, guint action,
6678                                              GtkWidget *widget)
6679 {
6680         Compose *compose = (Compose *)data;
6681
6682         if (GTK_CHECK_MENU_ITEM(widget)->active)
6683                 compose->return_receipt = TRUE;
6684         else
6685                 compose->return_receipt = FALSE;
6686 }
6687
6688 static void compose_toggle_remove_refs_cb(gpointer data, guint action,
6689                                              GtkWidget *widget)
6690 {
6691         Compose *compose = (Compose *)data;
6692
6693         if (GTK_CHECK_MENU_ITEM(widget)->active)
6694                 compose->remove_references = TRUE;
6695         else
6696                 compose->remove_references = FALSE;
6697 }
6698
6699 void compose_headerentry_key_press_event_cb(GtkWidget *entry,
6700                                             GdkEventKey *event,
6701                                             ComposeHeaderEntry *headerentry)
6702 {
6703         if ((g_slist_length(headerentry->compose->header_list) > 0) &&
6704             ((headerentry->headernum + 1) != headerentry->compose->header_nextrow) &&
6705             !(event->state & GDK_MODIFIER_MASK) &&
6706             (event->keyval == GDK_BackSpace) &&
6707             (strlen(gtk_entry_get_text(GTK_ENTRY(entry))) == 0)) {
6708                 gtk_container_remove
6709                         (GTK_CONTAINER(headerentry->compose->header_table),
6710                          headerentry->combo);
6711                 gtk_container_remove
6712                         (GTK_CONTAINER(headerentry->compose->header_table),
6713                          headerentry->entry);
6714                 headerentry->compose->header_list =
6715                         g_slist_remove(headerentry->compose->header_list,
6716                                        headerentry);
6717                 g_free(headerentry);
6718         } else  if (event->keyval == GDK_Tab) {
6719                 if (headerentry->compose->header_last == headerentry) {
6720                         /* Override default next focus, and give it to subject_entry
6721                          * instead of notebook tabs
6722                          */
6723                         gtk_signal_emit_stop_by_name(GTK_OBJECT(entry), "key-press-event"); 
6724                         gtk_widget_grab_focus(headerentry->compose->subject_entry);
6725                 }
6726         }
6727
6728 }
6729
6730 void compose_headerentry_changed_cb(GtkWidget *entry,
6731                                     ComposeHeaderEntry *headerentry)
6732 {
6733         if (strlen(gtk_entry_get_text(GTK_ENTRY(entry))) != 0) {
6734                 headerentry->compose->header_list =
6735                         g_slist_append(headerentry->compose->header_list,
6736                                        headerentry);
6737                 compose_create_header_entry(headerentry->compose);
6738                 gtk_signal_disconnect_by_func
6739                         (GTK_OBJECT(entry),
6740                          GTK_SIGNAL_FUNC(compose_headerentry_changed_cb),
6741                          headerentry);
6742                 /* Automatically scroll down */
6743                 compose_show_first_last_header(headerentry->compose, FALSE);
6744                 
6745         }
6746 }
6747
6748 static gboolean compose_headerentry_button_pressed
6749         (GtkWidget *entry, GdkEventButton *event, gpointer data)
6750 {
6751         /* if this is a lclick, grab the focus */
6752         if (event->button == 1)
6753                 gtk_widget_grab_focus(entry);
6754         return FALSE;
6755 }
6756
6757 static void compose_show_first_last_header(Compose *compose, gboolean show_first)
6758 {
6759         GtkAdjustment *vadj;
6760
6761         g_return_if_fail(compose);
6762         g_return_if_fail(GTK_IS_WIDGET(compose->header_table));
6763         g_return_if_fail(GTK_IS_VIEWPORT(compose->header_table->parent));
6764
6765         vadj = gtk_viewport_get_vadjustment(GTK_VIEWPORT(compose->header_table->parent));
6766         gtk_adjustment_set_value(vadj, (show_first ? vadj->lower : vadj->upper));
6767 }
6768
6769 static void text_activated(GtkWidget *widget, Compose *compose)
6770 {
6771         compose_send_control_enter(compose);
6772 }
6773
6774 static void text_inserted(GtkWidget *widget, const gchar *text,
6775                           gint length, gint *position, Compose *compose)
6776 {
6777         GtkEditable *editable = GTK_EDITABLE(widget);
6778         gint paste_as_quotation = GPOINTER_TO_INT(gtk_object_get_data
6779                                 (GTK_OBJECT(widget), "paste_as_quotation"));
6780
6781         gtk_signal_handler_block_by_func(GTK_OBJECT(widget),
6782                                          GTK_SIGNAL_FUNC(text_inserted),
6783                                          compose);
6784         if (paste_as_quotation) {
6785                 gchar *new_text;
6786                 gchar *qmark;
6787                 gint pos;
6788
6789                 new_text = g_strndup(text, length);
6790                 if (prefs_common.quotemark && *prefs_common.quotemark)
6791                         qmark = prefs_common.quotemark;
6792                 else
6793                         qmark = "> ";
6794                 gtk_stext_set_point(GTK_STEXT(widget), *position);
6795                 compose_quote_fmt(compose, NULL, "%Q", qmark, new_text);
6796                 pos = gtk_stext_get_point(GTK_STEXT(widget));
6797                 gtk_editable_set_position(editable, pos);
6798                 *position = pos;
6799                 g_free(new_text);
6800                 gtk_object_set_data(GTK_OBJECT(widget), "paste_as_quotation",
6801                                     GINT_TO_POINTER(paste_as_quotation - 1));
6802         } else
6803                 gtk_editable_insert_text(editable, text, length, position);
6804
6805         if (compose->autowrap)
6806                 compose_wrap_line_all_full(compose, TRUE);
6807
6808         gtk_signal_handler_unblock_by_func(GTK_OBJECT(widget),
6809                                            GTK_SIGNAL_FUNC(text_inserted),
6810                                            compose);
6811         gtk_signal_emit_stop_by_name(GTK_OBJECT(editable), "insert_text");
6812
6813         if (prefs_common.autosave && 
6814             gtk_stext_get_length(GTK_STEXT(widget)) % prefs_common.autosave_length == 0)
6815                 compose->draft_timeout_tag = gtk_timeout_add
6816                         (500, (GtkFunction) compose_defer_auto_save_draft, compose);
6817 }
6818
6819 static gint compose_defer_auto_save_draft(Compose *compose)
6820 {
6821         compose->draft_timeout_tag = -1;
6822         compose_draft_cb((gpointer)compose, COMPOSE_AUTO_SAVE, NULL);
6823         return FALSE;
6824 }
6825
6826 static gboolean compose_send_control_enter(Compose *compose)
6827 {
6828         GdkEvent *ev;
6829         GdkEventKey *kev;
6830         GtkItemFactory *ifactory;
6831         GtkAccelEntry *accel;
6832         GtkWidget *send_menu;
6833         GSList *list;
6834         GdkModifierType ignored_mods =
6835                 (GDK_LOCK_MASK | GDK_MOD2_MASK | GDK_MOD3_MASK |
6836                  GDK_MOD4_MASK | GDK_MOD5_MASK);
6837
6838         ev = gtk_get_current_event();
6839         if (ev->type != GDK_KEY_PRESS) return FALSE;
6840
6841         kev = (GdkEventKey *)ev;
6842         if (!(kev->keyval == GDK_Return && (kev->state & GDK_CONTROL_MASK)))
6843                 return FALSE;
6844
6845         if (compose->exteditor_tag != -1)
6846                 return FALSE;
6847
6848         ifactory = gtk_item_factory_from_widget(compose->menubar);
6849         send_menu = gtk_item_factory_get_widget(ifactory, "/Message/Send");
6850         list = gtk_accel_group_entries_from_object(GTK_OBJECT(send_menu));
6851         if (!list)
6852                 return FALSE;
6853
6854         accel = (GtkAccelEntry *)list->data;
6855         if (accel && accel->accelerator_key == kev->keyval &&
6856             (accel->accelerator_mods & ~ignored_mods) ==
6857             (kev->state & ~ignored_mods)) {
6858                 compose_send_cb(compose, 0, NULL);
6859                 return TRUE;
6860         }
6861
6862         return FALSE;
6863 }
6864
6865 #if USE_ASPELL
6866 static void compose_check_all(Compose *compose)
6867 {
6868         if (compose->gtkaspell)
6869                 gtkaspell_check_all(compose->gtkaspell);
6870 }
6871
6872 static void compose_highlight_all(Compose *compose)
6873 {
6874         if (compose->gtkaspell)
6875                 gtkaspell_highlight_all(compose->gtkaspell);
6876 }
6877
6878 static void compose_check_backwards(Compose *compose)
6879 {
6880         if (compose->gtkaspell) 
6881                 gtkaspell_check_backwards(compose->gtkaspell);
6882         else {
6883                 GtkItemFactory *ifactory;
6884                 ifactory = gtk_item_factory_from_widget(compose->popupmenu);
6885                 menu_set_sensitive(ifactory, "/Edit/Check backwards misspelled word", FALSE);
6886                 menu_set_sensitive(ifactory, "/Edit/Forward to next misspelled word", FALSE);
6887         }
6888 }
6889
6890 static void compose_check_forwards_go(Compose *compose)
6891 {
6892         if (compose->gtkaspell) 
6893                 gtkaspell_check_forwards_go(compose->gtkaspell);
6894         else {
6895                 GtkItemFactory *ifactory;
6896                 ifactory = gtk_item_factory_from_widget(compose->popupmenu);
6897                 menu_set_sensitive(ifactory, "/Edit/Check backwards misspelled word", FALSE);
6898                 menu_set_sensitive(ifactory, "/Edit/Forward to next misspelled word", FALSE);
6899         }
6900 }
6901 #endif
6902
6903 /*!
6904  *\brief        Guess originating forward account from MsgInfo and several 
6905  *              "common preference" settings. Return NULL if no guess. 
6906  */
6907 static PrefsAccount *compose_guess_forward_account_from_msginfo(MsgInfo *msginfo)
6908 {
6909         PrefsAccount *account = NULL;
6910         
6911         g_return_val_if_fail(msginfo, NULL);
6912         g_return_val_if_fail(msginfo->folder, NULL);
6913         g_return_val_if_fail(msginfo->folder->prefs, NULL);
6914
6915         if (msginfo->folder->prefs->enable_default_account)
6916                 account = account_find_from_id(msginfo->folder->prefs->default_account);
6917                 
6918         if (!account) 
6919                 account = msginfo->folder->folder->account;
6920                 
6921         if (!account && msginfo->to && prefs_common.forward_account_autosel) {
6922                 gchar *to;
6923                 Xstrdup_a(to, msginfo->to, return NULL);
6924                 extract_address(to);
6925                 account = account_find_from_address(to);
6926         }
6927
6928         if (!account && prefs_common.forward_account_autosel) {
6929                 gchar cc[BUFFSIZE];
6930                 if (!procheader_get_header_from_msginfo
6931                         (msginfo, cc,sizeof cc , "CC:")) { /* Found a CC header */
6932                         extract_address(cc);
6933                         account = account_find_from_address(cc);
6934                 }
6935         }
6936         
6937         return account;
6938 }
6939
6940 static void compose_close(Compose *compose)
6941 {
6942         gint x, y;
6943
6944         g_return_if_fail(compose);
6945         gtkut_widget_get_uposition(compose->window, &x, &y);
6946         prefs_common.compose_x = x;
6947         prefs_common.compose_y = y;
6948         gtk_widget_destroy(compose->window);
6949 }
6950
6951 /**
6952  * Add entry field for each address in list.
6953  * \param compose     E-Mail composition object.
6954  * \param listAddress List of (formatted) E-Mail addresses.
6955  */
6956 static void compose_add_field_list( Compose *compose, GList *listAddress ) {
6957         GList *node;
6958         gchar *addr;
6959         node = listAddress;
6960         while( node ) {
6961                 addr = ( gchar * ) node->data;
6962                 compose_entry_append( compose, addr, COMPOSE_TO );
6963                 node = g_list_next( node );
6964         }
6965 }
6966
6967 void compose_reply_from_messageview(MessageView *msgview, GSList *msginfo_list, 
6968                                     guint action)
6969 {
6970         gchar *body;
6971         GSList *new_msglist = NULL;
6972         MsgInfo *tmp_msginfo = NULL;
6973
6974         g_return_if_fail(msgview != NULL);
6975
6976         g_return_if_fail(msginfo_list != NULL);
6977
6978         if (g_slist_length(msginfo_list) == 1) {
6979                 MimeInfo *mimeinfo = messageview_get_selected_mime_part(msgview);
6980                 MsgInfo *orig_msginfo = (MsgInfo *)msginfo_list->data;
6981                 
6982                 if (mimeinfo != NULL && mimeinfo->type == MIMETYPE_MESSAGE && 
6983                     !g_strcasecmp(mimeinfo->subtype, "rfc822")) {
6984                         
6985                         tmp_msginfo = procmsg_msginfo_new_from_mimeinfo(
6986                                                 orig_msginfo, mimeinfo);
6987                         if (tmp_msginfo != NULL) {
6988                                 new_msglist = g_slist_append(NULL, tmp_msginfo);
6989                         } 
6990                 }
6991         }
6992
6993         body = messageview_get_selection(msgview);
6994
6995         if (new_msglist) {
6996                 compose_reply_mode((ComposeMode)action, new_msglist, body);
6997                 procmsg_msginfo_free(tmp_msginfo);
6998                 g_slist_free(new_msglist);
6999         } else
7000                 compose_reply_mode((ComposeMode)action, msginfo_list, body);
7001
7002         g_free(body);
7003 }
7004
7005 /*
7006  * End of Source.
7007  */