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