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