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