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