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