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