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