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