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