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