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