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