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