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