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