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