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