Return Receipt
[claws.git] / src / compose.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999,2000 Hiroyuki Yamamoto
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include "defs.h"
25
26 #include <glib.h>
27 #include <gdk/gdkkeysyms.h>
28 #include <gtk/gtkmain.h>
29 #include <gtk/gtkmenu.h>
30 #include <gtk/gtkmenuitem.h>
31 #include <gtk/gtkitemfactory.h>
32 #include <gtk/gtkcheckmenuitem.h>
33 #include <gtk/gtkoptionmenu.h>
34 #include <gtk/gtkwidget.h>
35 #include <gtk/gtkclist.h>
36 #include <gtk/gtkctree.h>
37 #include <gtk/gtkvpaned.h>
38 #include <gtk/gtkentry.h>
39 #include <gtk/gtkeditable.h>
40 #include <gtk/gtkwindow.h>
41 #include <gtk/gtksignal.h>
42 #include <gtk/gtkvbox.h>
43 #include <gtk/gtkcontainer.h>
44 #include <gtk/gtkhandlebox.h>
45 #include <gtk/gtktoolbar.h>
46 #include <gtk/gtktable.h>
47 #include <gtk/gtkhbox.h>
48 #include <gtk/gtklabel.h>
49 #include <gtk/gtkscrolledwindow.h>
50 #include <gtk/gtkthemes.h>
51 #include <gtk/gtkdnd.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <ctype.h>
56 #include <unistd.h>
57 #include <time.h>
58 /* #include <sys/utsname.h> */
59 #include <stdlib.h>
60 #include <sys/wait.h>
61 #include <signal.h>
62 #include <errno.h>
63
64 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
65 #  include <wchar.h>
66 #  include <wctype.h>
67 #endif
68
69
70 #include "gtkstext.h"
71
72 #include "intl.h"
73 #include "main.h"
74 #include "mainwindow.h"
75 #include "compose.h"
76 #include "addressbook.h"
77 #include "folderview.h"
78 #include "procmsg.h"
79 #include "menu.h"
80 #include "send.h"
81 #include "news.h"
82 #include "prefs_common.h"
83 #include "prefs_account.h"
84 #include "account.h"
85 #include "filesel.h"
86 #include "procheader.h"
87 #include "procmime.h"
88 #include "statusbar.h"
89 #include "about.h"
90 #include "base64.h"
91 #include "codeconv.h"
92 #include "utils.h"
93 #include "gtkutils.h"
94 #include "socket.h"
95 #include "alertpanel.h"
96 #include "manage_window.h"
97 #include "gtkshruler.h"
98 #include "folder.h"
99 #include "addr_compl.h"
100 #include "customheader.h"
101
102 #if USE_GPGME
103 #  include "rfc2015.h"
104 #endif
105
106 typedef enum
107 {
108         COL_MIMETYPE = 0,
109         COL_SIZE     = 1,
110         COL_NAME     = 2
111 } AttachColumnPos;
112
113 #define N_ATTACH_COLS           3
114
115 #define B64_LINE_SIZE           57
116 #define B64_BUFFSIZE            77
117
118 #define MAX_REFERENCES_LEN      999
119
120 static GdkColor quote_color = {0, 0, 0, 0xbfff};
121
122 static GList *compose_list = NULL;
123
124 static Compose *compose_create                  (PrefsAccount   *account);
125 static void compose_toolbar_create              (Compose        *compose,
126                                                  GtkWidget      *container);
127 static GtkWidget *compose_account_option_menu_create
128                                                 (Compose        *compose);
129 static void compose_destroy                     (Compose        *compose);
130
131 static gint compose_parse_header                (Compose        *compose,
132                                                  MsgInfo        *msginfo);
133 static gchar *compose_parse_references          (const gchar    *ref,
134                                                  const gchar    *msgid);
135 static void compose_quote_file                  (Compose        *compose,
136                                                  MsgInfo        *msginfo,
137                                                  FILE           *fp);
138 static gchar *compose_quote_parse_fmt           (Compose        *compose,
139                                                  MsgInfo        *msginfo,
140                                                  const gchar    *fmt);
141 static void compose_reply_set_entry             (Compose        *compose,
142                                                  MsgInfo        *msginfo,
143                                                  gboolean        to_all);
144 static void compose_reedit_set_entry            (Compose        *compose,
145                                                  MsgInfo        *msginfo);
146 static void compose_insert_sig                  (Compose        *compose);
147 static void compose_insert_file                 (Compose        *compose,
148                                                  const gchar    *file);
149 static void compose_attach_append               (Compose        *compose,
150                                                  const gchar    *file,
151                                                  ContentType     cnttype);
152 static void compose_wrap_line                   (Compose        *compose);
153 static void compose_set_title                   (Compose        *compose);
154
155 static gint compose_send                        (Compose        *compose);
156 static gint compose_write_to_file               (Compose        *compose,
157                                                  const gchar    *file,
158                                                  gboolean        is_draft);
159 static gint compose_write_body_to_file          (Compose        *compose,
160                                                  const gchar    *file);
161 static gint compose_save_to_outbox              (Compose        *compose,
162                                                  const gchar    *file);
163 static gint compose_queue                       (Compose        *compose,
164                                                  const gchar    *file);
165 static void compose_write_attach                (Compose        *compose,
166                                                  FILE           *fp);
167 static gint compose_write_headers               (Compose        *compose,
168                                                  FILE           *fp,
169                                                  const gchar    *charset,
170                                                  EncodingType    encoding,
171                                                  gboolean        is_draft);
172
173 static void compose_convert_header              (gchar          *dest,
174                                                  gint            len,
175                                                  gchar          *src,
176                                                  gint            header_len);
177 static void compose_generate_msgid              (Compose        *compose,
178                                                  gchar          *buf,
179                                                  gint            len);
180
181 static void compose_attach_info_free            (AttachInfo     *ainfo);
182 static void compose_attach_remove_selected      (Compose        *compose);
183
184 static void compose_attach_property             (Compose        *compose);
185 static void compose_attach_property_create      (gboolean       *cancelled);
186 static void attach_property_ok                  (GtkWidget      *widget,
187                                                  gboolean       *cancelled);
188 static void attach_property_cancel              (GtkWidget      *widget,
189                                                  gboolean       *cancelled);
190 static gint attach_property_delete_event        (GtkWidget      *widget,
191                                                  GdkEventAny    *event,
192                                                  gboolean       *cancelled);
193 static void attach_property_key_pressed         (GtkWidget      *widget,
194                                                  GdkEventKey    *event,
195                                                  gboolean       *cancelled);
196
197 static void compose_exec_ext_editor             (Compose           *compose);
198 static gint compose_exec_ext_editor_real        (const gchar       *file);
199 static gboolean compose_ext_editor_kill         (Compose           *compose);
200 static void compose_input_cb                    (gpointer           data,
201                                                  gint               source,
202                                                  GdkInputCondition  condition);
203 static void compose_set_ext_editor_sensitive    (Compose           *compose,
204                                                  gboolean           sensitive);
205
206 static gint calc_cursor_xpos    (GtkSText       *text,
207                                  gint            extra,
208                                  gint            char_width);
209
210 /* callback functions */
211
212 static gboolean compose_edit_size_alloc (GtkEditable    *widget,
213                                          GtkAllocation  *allocation,
214                                          GtkSHRuler     *shruler);
215
216 static void toolbar_send_cb             (GtkWidget      *widget,
217                                          gpointer        data);
218 static void toolbar_send_later_cb       (GtkWidget      *widget,
219                                          gpointer        data);
220 static void toolbar_draft_cb            (GtkWidget      *widget,
221                                          gpointer        data);
222 static void toolbar_insert_cb           (GtkWidget      *widget,
223                                          gpointer        data);
224 static void toolbar_attach_cb           (GtkWidget      *widget,
225                                          gpointer        data);
226 static void toolbar_sig_cb              (GtkWidget      *widget,
227                                          gpointer        data);
228 static void toolbar_ext_editor_cb       (GtkWidget      *widget,
229                                          gpointer        data);
230 static void toolbar_linewrap_cb         (GtkWidget      *widget,
231                                          gpointer        data);
232 static void toolbar_address_cb          (GtkWidget      *widget,
233                                          gpointer        data);
234
235 static void account_activated           (GtkMenuItem    *menuitem,
236                                          gpointer        data);
237
238 static void attach_selected             (GtkCList       *clist,
239                                          gint            row,
240                                          gint            column,
241                                          GdkEvent       *event,
242                                          gpointer        data);
243 static void attach_button_pressed       (GtkWidget      *widget,
244                                          GdkEventButton *event,
245                                          gpointer        data);
246 static void attach_key_pressed          (GtkWidget      *widget,
247                                          GdkEventKey    *event,
248                                          gpointer        data);
249
250 static void compose_send_cb             (gpointer        data,
251                                          guint           action,
252                                          GtkWidget      *widget);
253 static void compose_send_later_cb       (gpointer        data,
254                                          guint           action,
255                                          GtkWidget      *widget);
256
257 static void compose_draft_cb            (gpointer        data,
258                                          guint           action,
259                                          GtkWidget      *widget);
260
261 static void compose_attach_cb           (gpointer        data,
262                                          guint           action,
263                                          GtkWidget      *widget);
264 static void compose_insert_file_cb      (gpointer        data,
265                                          guint           action,
266                                          GtkWidget      *widget);
267
268 static void compose_close_cb            (gpointer        data,
269                                          guint           action,
270                                          GtkWidget      *widget);
271 static void compose_address_cb          (gpointer        data,
272                                          guint           action,
273                                          GtkWidget      *widget);
274
275 static void compose_ext_editor_cb       (gpointer        data,
276                                          guint           action,
277                                          GtkWidget      *widget);
278
279 static gint compose_delete_cb           (GtkWidget      *widget,
280                                          GdkEventAny    *event,
281                                          gpointer        data);
282 static void compose_destroy_cb          (GtkWidget      *widget,
283                                          Compose        *compose);
284
285 static void compose_cut_cb              (Compose        *compose);
286 static void compose_copy_cb             (Compose        *compose);
287 static void compose_paste_cb            (Compose        *compose);
288 static void compose_allsel_cb           (Compose        *compose);
289
290 static void compose_grab_focus_cb       (GtkWidget      *widget,
291                                          Compose        *compose);
292
293 static void compose_changed_cb          (GtkEditable    *editable,
294                                          Compose        *compose);
295 static void compose_button_press_cb     (GtkWidget      *widget,
296                                          GdkEventButton *event,
297                                          Compose        *compose);
298 #if 0
299 static void compose_key_press_cb        (GtkWidget      *widget,
300                                          GdkEventKey    *event,
301                                          Compose        *compose);
302 #endif
303
304 static void compose_toggle_to_cb        (gpointer        data,
305                                          guint           action,
306                                          GtkWidget      *widget);
307 static void compose_toggle_cc_cb        (gpointer        data,
308                                          guint           action,
309                                          GtkWidget      *widget);
310 static void compose_toggle_bcc_cb       (gpointer        data,
311                                          guint           action,
312                                          GtkWidget      *widget);
313 static void compose_toggle_replyto_cb   (gpointer        data,
314                                          guint           action,
315                                          GtkWidget      *widget);
316 static void compose_toggle_followupto_cb(gpointer        data,
317                                          guint           action,
318                                          GtkWidget      *widget);
319 static void compose_toggle_attach_cb    (gpointer        data,
320                                          guint           action,
321                                          GtkWidget      *widget);
322 static void compose_toggle_ruler_cb     (gpointer        data,
323                                          guint           action,
324                                          GtkWidget      *widget);
325 #if USE_GPGME
326 static void compose_toggle_sign_cb      (gpointer        data,
327                                          guint           action,
328                                          GtkWidget      *widget);
329 static void compose_toggle_encrypt_cb   (gpointer        data,
330                                          guint           action,
331                                          GtkWidget      *widget);
332 #endif
333 static void compose_toggle_return_receipt_cb(gpointer data, guint action,
334                                              GtkWidget *widget);
335
336 static void compose_attach_drag_received_cb (GtkWidget          *widget,
337                                              GdkDragContext     *drag_context,
338                                              gint                x,
339                                              gint                y,
340                                              GtkSelectionData   *data,
341                                              guint               info,
342                                              guint               time,
343                                              gpointer            user_data);
344 static void compose_insert_drag_received_cb (GtkWidget          *widget,
345                                              GdkDragContext     *drag_context,
346                                              gint                x,
347                                              gint                y,
348                                              GtkSelectionData   *data,
349                                              guint               info,
350                                              guint               time,
351                                              gpointer            user_data);
352
353 static void to_activated                (GtkWidget      *widget,
354                                          Compose        *compose);
355 static void newsgroups_activated        (GtkWidget      *widget,
356                                          Compose        *compose);
357 static void subject_activated           (GtkWidget      *widget,
358                                          Compose        *compose);
359 static void cc_activated                (GtkWidget      *widget,
360                                          Compose        *compose);
361 static void bcc_activated               (GtkWidget      *widget,
362                                          Compose        *compose);
363 static void replyto_activated           (GtkWidget      *widget,
364                                          Compose        *compose);
365 static void followupto_activated        (GtkWidget      *widget,
366                                          Compose        *compose);
367
368 static GtkItemFactoryEntry compose_popup_entries[] =
369 {
370         {N_("/_Add..."),        NULL, compose_attach_cb, 0, NULL},
371         {N_("/_Remove"),        NULL, compose_attach_remove_selected, 0, NULL},
372         {N_("/---"),            NULL, NULL, 0, "<Separator>"},
373         {N_("/_Property..."),   NULL, compose_attach_property, 0, NULL}
374 };
375
376 static GtkItemFactoryEntry compose_entries[] =
377 {
378         {N_("/_File"),                          NULL, NULL, 0, "<Branch>"},
379         {N_("/_File/_Attach file"),             "<control>M", compose_attach_cb, 0, NULL},
380         {N_("/_File/_Insert file"),             "<control>I", compose_insert_file_cb, 0, NULL},
381         {N_("/_File/Insert si_gnature"),        "<control>G", compose_insert_sig, 0, NULL},
382         {N_("/_File/---"),                      NULL, NULL, 0, "<Separator>"},
383         {N_("/_File/_Close"),                   "<alt>W", compose_close_cb, 0, NULL},
384
385         {N_("/_Edit"),             NULL,         NULL,  0, "<Branch>"},
386         {N_("/_Edit/_Undo"),       "<control>Z", NULL,  0, NULL},
387         {N_("/_Edit/_Redo"),       "<control>Y", NULL,  0, NULL},
388         {N_("/_Edit/---"),         NULL,         NULL,  0, "<Separator>"},
389         {N_("/_Edit/Cu_t"),        "<control>X", compose_cut_cb,    0, NULL},
390         {N_("/_Edit/_Copy"),       "<control>C", compose_copy_cb,   0, NULL},
391         {N_("/_Edit/_Paste"),      "<control>V", compose_paste_cb,  0, NULL},
392         {N_("/_Edit/Select _all"), "<control>A", compose_allsel_cb, 0, NULL},
393         {N_("/_Edit/---"),         NULL,         NULL,  0, "<Separator>"},
394         {N_("/_Edit/Wrap long _lines"), "<alt>L", compose_wrap_line, 0, NULL},
395         {N_("/_Edit/Edit with e_xternal editor"), "<alt>X",
396                                         compose_ext_editor_cb,  0, NULL},
397
398         {N_("/_Message"),               NULL,           NULL,   0, "<Branch>"},
399         {N_("/_Message/_Send"),         "<shift><control>S",
400                                         compose_send_cb, 0, NULL},
401         {N_("/_Message/Send _later"),   "<shift><alt>S",
402                                         compose_send_later_cb,  0, NULL},
403         {N_("/_Message/Save to _draft folder"),
404                                         "<alt>D",       compose_draft_cb, 0, NULL},
405         {N_("/_Message/---"),           NULL,           NULL,   0, "<Separator>"},
406         {N_("/_Message/_To"),           NULL, compose_toggle_to_cb, 0, "<ToggleItem>"},
407         {N_("/_Message/_Cc"),           NULL, compose_toggle_cc_cb, 0, "<ToggleItem>"},
408         {N_("/_Message/_Bcc"),          NULL, compose_toggle_bcc_cb, 0, "<ToggleItem>"},
409         {N_("/_Message/_Reply to"),     NULL, compose_toggle_replyto_cb, 0, "<ToggleItem>"},
410         {N_("/_Message/---"),           NULL,           NULL,   0, "<Separator>"},
411         {N_("/_Message/_Followup to"),  NULL, compose_toggle_followupto_cb, 0, "<ToggleItem>"},
412         {N_("/_Message/---"),           NULL,           NULL,   0, "<Separator>"},
413         {N_("/_Message/_Attach"),       NULL, compose_toggle_attach_cb, 0, "<ToggleItem>"},
414 #if USE_GPGME
415         {N_("/_Message/---"),           NULL,           NULL,   0, "<Separator>"},
416         {N_("/_Message/Si_gn"),         NULL, compose_toggle_sign_cb, 0, "<ToggleItem>"},
417         {N_("/_Message/_Encrypt"),      NULL, compose_toggle_encrypt_cb, 0, "<ToggleItem>"},
418 #endif /* USE_GPGME */
419         {N_("/_Message/---"),           NULL,           NULL,   0, "<Separator>"},
420         {N_("/_Message/_Request Return Receipt"),       NULL, compose_toggle_return_receipt_cb, 0, "<ToggleItem>"},
421         {N_("/_Tool"),                  NULL, NULL,     0, "<Branch>"},
422         {N_("/_Tool/Show _ruler"),      NULL, compose_toggle_ruler_cb,  0, "<ToggleItem>"},
423         {N_("/_Tool/_Address book"),    "<alt>A",       compose_address_cb, 0, NULL},
424         {N_("/_Help"),                  NULL, NULL,     0, "<LastBranch>"},
425         {N_("/_Help/_About"),           NULL,           about_show,     0, NULL}
426 };
427
428 static GtkTargetEntry compose_mime_types[] =
429 {
430         {"text/uri-list", 0, 0}
431 };
432
433 void compose_new(PrefsAccount *account)
434 {
435         compose_new_with_recipient(account, NULL);
436 }
437
438 void compose_new_with_recipient(PrefsAccount *account, const gchar *to)
439 {
440         Compose *compose;
441
442         if (!account) account = cur_account;
443         g_return_if_fail(account != NULL);
444
445         compose = compose_create(account);
446         compose->mode = COMPOSE_NEW;
447
448         if (prefs_common.auto_sig)
449                 compose_insert_sig(compose);
450         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
451         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
452
453         if (account->protocol != A_NNTP) {
454                 if (to) {
455                         compose_entry_append(compose, to, COMPOSE_TO);
456                         gtk_widget_grab_focus(compose->subject_entry);
457                 } else
458                         gtk_widget_grab_focus(compose->to_entry);
459         } else
460                 gtk_widget_grab_focus(compose->newsgroups_entry);
461 }
462
463 void compose_reply(MsgInfo *msginfo, gboolean quote, gboolean to_all)
464 {
465         Compose *compose;
466         PrefsAccount *account;
467         GtkSText *text;
468
469         g_return_if_fail(msginfo != NULL);
470         g_return_if_fail(msginfo->folder != NULL);
471
472         account = msginfo->folder->folder->account;
473         if (!account) account = cur_account;
474         g_return_if_fail(account != NULL);
475
476         MSG_UNSET_FLAGS(msginfo->flags, MSG_FORWARDED);
477         MSG_SET_FLAGS(msginfo->flags, MSG_REPLIED);
478
479         compose = compose_create(account);
480         compose->mode = COMPOSE_REPLY;
481
482         if (compose_parse_header(compose, msginfo) < 0) return;
483         compose_reply_set_entry(compose, msginfo, to_all);
484
485         text = GTK_STEXT(compose->text);
486         gtk_stext_freeze(text);
487
488         if (quote) {
489                 FILE *fp;
490                 gchar *quote_str;
491
492                 if ((fp = procmime_get_text_part(msginfo)) == NULL)
493                         g_warning(_("Can't get text part\n"));
494                 else {
495                         quote_str = compose_quote_parse_fmt
496                                 (compose, msginfo, prefs_common.quotefmt);
497                         gtk_stext_insert(text, NULL, NULL, NULL, quote_str, -1);
498                         g_free(quote_str);
499                         compose_quote_file(compose, msginfo, fp);
500                         fclose(fp);
501                 }
502         }
503
504         if (prefs_common.auto_sig)
505                 compose_insert_sig(compose);
506         gtk_editable_set_position(GTK_EDITABLE(text), 0);
507         gtk_stext_set_point(text, 0);
508
509         gtk_stext_thaw(text);
510         gtk_widget_grab_focus(compose->text);
511 }
512
513 #define INSERT_FW_HEADER(var, hdr) \
514 if (msginfo->var && *msginfo->var) { \
515         gtk_stext_insert(text, NULL, NULL, NULL, hdr, -1); \
516         gtk_stext_insert(text, NULL, NULL, NULL, msginfo->var, -1); \
517         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1); \
518 }
519
520 void compose_forward(MsgInfo *msginfo, gboolean as_attach)
521 {
522         Compose *compose;
523         PrefsAccount *account;
524         GtkSText *text;
525         FILE *fp;
526         gchar buf[BUFFSIZE];
527
528         g_return_if_fail(msginfo != NULL);
529         g_return_if_fail(msginfo->folder != NULL);
530
531         account = msginfo->folder->folder->account;
532         if (!account) account = cur_account;
533         g_return_if_fail(account != NULL);
534
535         MSG_UNSET_FLAGS(msginfo->flags, MSG_REPLIED);
536         MSG_SET_FLAGS(msginfo->flags, MSG_FORWARDED);
537
538         compose = compose_create(account);
539         compose->mode = COMPOSE_FORWARD;
540
541         if (msginfo->subject && *msginfo->subject) {
542                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), "Fw: ");
543                 gtk_entry_append_text(GTK_ENTRY(compose->subject_entry),
544                                       msginfo->subject);
545         }
546
547         text = GTK_STEXT(compose->text);
548         gtk_stext_freeze(text);
549
550         if (as_attach) {
551                 gchar *msgfile;
552
553                 msgfile = procmsg_get_message_file_path(msginfo);
554                 if (!is_file_exist(msgfile))
555                         g_warning(_("%s: file not exist\n"), msgfile);
556                 else
557                         compose_attach_append(compose, msgfile,
558                                               MIME_MESSAGE_RFC822);
559
560                 g_free(msgfile);
561         } else {
562                 if ((fp = procmime_get_text_part(msginfo)) == NULL)
563                         g_warning(_("Can't get text part\n"));
564                 else {
565                         /* insert header */
566                         gtk_stext_insert(text, NULL, NULL, NULL,
567                                         _("\n\nBegin forwarded message:\n\n"), -1);
568                         INSERT_FW_HEADER(date,       "Date: ");
569                         INSERT_FW_HEADER(from,       "From: ");
570                         INSERT_FW_HEADER(to,         "To: ");
571                         INSERT_FW_HEADER(newsgroups, "Newsgroups: ");
572                         INSERT_FW_HEADER(subject,    "Subject: ");
573                         gtk_stext_insert(text, NULL, NULL, NULL, "\n\n", 2);
574
575                         /* forward body */
576                         while (fgets(buf, sizeof(buf), fp) != NULL)
577                                 gtk_stext_insert(text, NULL, NULL, NULL,
578                                                 buf, -1);
579                         fclose(fp);
580                 }
581         }
582
583         if (prefs_common.auto_sig)
584                 compose_insert_sig(compose);
585         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
586         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
587
588         gtk_stext_thaw(text);
589         if (account->protocol != A_NNTP)
590                 gtk_widget_grab_focus(compose->to_entry);
591         else
592                 gtk_widget_grab_focus(compose->newsgroups_entry);
593 }
594
595 void compose_reedit(MsgInfo *msginfo)
596 {
597         Compose *compose;
598         PrefsAccount *account;
599         GtkSText *text;
600         FILE *fp;
601         gchar buf[BUFFSIZE];
602
603         g_return_if_fail(msginfo != NULL);
604         g_return_if_fail(msginfo->folder != NULL);
605
606         account = msginfo->folder->folder->account;
607         if (!account) account = cur_account;
608         g_return_if_fail(account != NULL);
609
610         compose = compose_create(account);
611         compose->mode = COMPOSE_REEDIT_DRAFT;
612         compose->targetinfo = procmsg_msginfo_copy(msginfo);
613
614         if (compose_parse_header(compose, msginfo) < 0) return;
615         compose_reedit_set_entry(compose, msginfo);
616
617         text = GTK_STEXT(compose->text);
618         gtk_stext_freeze(text);
619
620         if ((fp = procmime_get_text_part(msginfo)) == NULL)
621                 g_warning(_("Can't get text part\n"));
622         else {
623                 while (fgets(buf, sizeof(buf), fp) != NULL)
624                         gtk_stext_insert(text, NULL, NULL, NULL, buf, -1);
625                 fclose(fp);
626         }
627
628         gtk_stext_thaw(text);
629         gtk_widget_grab_focus(compose->text);
630 }
631
632 GList *compose_get_compose_list(void)
633 {
634         return compose_list;
635 }
636
637 void compose_entry_append(Compose *compose, const gchar *address,
638                           ComposeEntryType type)
639 {
640         GtkEntry *entry;
641         const gchar *text;
642
643         if (!address || *address == '\0') return;
644
645         switch (type) {
646         case COMPOSE_CC:
647                 entry = GTK_ENTRY(compose->cc_entry);
648                 break;
649         case COMPOSE_BCC:
650                 entry = GTK_ENTRY(compose->bcc_entry);
651                 break;
652         case COMPOSE_TO:
653         default:
654                 entry = GTK_ENTRY(compose->to_entry);
655                 break;
656         }
657
658         text = gtk_entry_get_text(entry);
659         if (*text != '\0')
660                 gtk_entry_append_text(entry, ", ");
661         gtk_entry_append_text(entry, address);
662 }
663
664 static gint compose_parse_header(Compose *compose, MsgInfo *msginfo)
665 {
666         static HeaderEntry hentry[] = {{"Reply-To:",    NULL, TRUE},
667                                        {"Cc:",          NULL, FALSE},
668                                        {"References:",  NULL, FALSE},
669                                        {"Bcc:",         NULL, FALSE},
670                                        {"Newsgroups:",  NULL, FALSE},
671                                        {"Followup-To:", NULL, FALSE},
672                                        {NULL,           NULL, FALSE}};
673
674         enum
675         {
676                 H_REPLY_TO      = 0,
677                 H_CC            = 1,
678                 H_REFERENCES    = 2,
679                 H_BCC           = 3,
680                 H_NEWSGROUPS    = 4,
681                 H_FOLLOWUP_TO   = 5
682         };
683
684         FILE *fp;
685
686         g_return_val_if_fail(msginfo != NULL, -1);
687
688         if ((fp = procmsg_open_message(msginfo)) == NULL) return -1;
689         procheader_get_header_fields(fp, hentry);
690         fclose(fp);
691
692         if (hentry[H_REPLY_TO].body != NULL) {
693                 conv_unmime_header_overwrite(hentry[H_REPLY_TO].body);
694                 compose->replyto = hentry[H_REPLY_TO].body;
695                 hentry[H_REPLY_TO].body = NULL;
696         }
697         if (hentry[H_CC].body != NULL) {
698                 conv_unmime_header_overwrite(hentry[H_CC].body);
699                 compose->cc = hentry[H_CC].body;
700                 hentry[H_CC].body = NULL;
701         }
702         if (hentry[H_REFERENCES].body != NULL) {
703                 if (compose->mode == COMPOSE_REEDIT_DRAFT)
704                         compose->references = hentry[H_REFERENCES].body;
705                 else {
706                         compose->references = compose_parse_references
707                                 (hentry[H_REFERENCES].body, msginfo->msgid);
708                         g_free(hentry[H_REFERENCES].body);
709                 }
710                 hentry[H_REFERENCES].body = NULL;
711         }
712         if (hentry[H_BCC].body != NULL) {
713                 if (compose->mode == COMPOSE_REEDIT_DRAFT) {
714                         conv_unmime_header_overwrite(hentry[H_BCC].body);
715                         compose->bcc = hentry[H_BCC].body;
716                 } else
717                         g_free(hentry[H_BCC].body);
718                 hentry[H_BCC].body = NULL;
719         }
720         if (hentry[H_NEWSGROUPS].body != NULL) {
721                 compose->newsgroups = hentry[H_NEWSGROUPS].body;
722                 hentry[H_NEWSGROUPS].body = NULL;
723         }
724         if (hentry[H_FOLLOWUP_TO].body != NULL) {
725                 conv_unmime_header_overwrite(hentry[H_FOLLOWUP_TO].body);
726                 compose->followup_to = hentry[H_FOLLOWUP_TO].body;
727                 hentry[H_FOLLOWUP_TO].body = NULL;
728         }
729
730         if (compose->mode == COMPOSE_REEDIT_DRAFT && msginfo->inreplyto)
731                 compose->inreplyto = g_strdup(msginfo->inreplyto);
732         else if (compose->mode != COMPOSE_REEDIT_DRAFT &&
733                  msginfo->msgid && *msginfo->msgid) {
734                 compose->inreplyto = g_strdup(msginfo->msgid);
735
736                 if (!compose->references) {
737                         if (msginfo->inreplyto && *msginfo->inreplyto)
738                                 compose->references =
739                                         g_strdup_printf("<%s>\n\t<%s>",
740                                                         msginfo->inreplyto,
741                                                         msginfo->msgid);
742                         else
743                                 compose->references =
744                                         g_strconcat("<", msginfo->msgid, ">",
745                                                     NULL);
746                 }
747         }
748
749         return 0;
750 }
751
752 static gchar *compose_parse_references(const gchar *ref, const gchar *msgid)
753 {
754         GSList *ref_id_list, *cur;
755         GString *new_ref;
756         gchar *new_ref_str;
757
758         ref_id_list = references_list_append(NULL, ref);
759         if (!ref_id_list) return NULL;
760         if (msgid && *msgid)
761                 ref_id_list = g_slist_append(ref_id_list, g_strdup(msgid));
762
763         for (;;) {
764                 gint len = 0;
765
766                 for (cur = ref_id_list; cur != NULL; cur = cur->next)
767                         /* "<" + Message-ID + ">" + CR+LF+TAB */
768                         len += strlen((gchar *)cur->data) + 5;
769
770                 if (len > MAX_REFERENCES_LEN) {
771                         /* remove second message-ID */
772                         if (ref_id_list && ref_id_list->next &&
773                             ref_id_list->next->next) {
774                                 g_free(ref_id_list->next->data);
775                                 ref_id_list = g_slist_remove
776                                         (ref_id_list, ref_id_list->next->data);
777                         } else {
778                                 slist_free_strings(ref_id_list);
779                                 g_slist_free(ref_id_list);
780                                 return NULL;
781                         }
782                 } else
783                         break;
784         }
785
786         new_ref = g_string_new("");
787         for (cur = ref_id_list; cur != NULL; cur = cur->next) {
788                 if (new_ref->len > 0)
789                         g_string_append(new_ref, "\n\t");
790                 g_string_sprintfa(new_ref, "<%s>", (gchar *)cur->data);
791         }
792
793         slist_free_strings(ref_id_list);
794         g_slist_free(ref_id_list);
795
796         new_ref_str = new_ref->str;
797         g_string_free(new_ref, FALSE);
798
799         return new_ref_str;
800 }
801
802 static void compose_quote_file(Compose *compose, MsgInfo *msginfo, FILE *fp)
803 {
804         GtkSText *text = GTK_STEXT(compose->text);
805         gchar *qmark;
806         gchar *quote_str;
807         GdkColor *qcolor = NULL;
808         gchar buf[BUFFSIZE];
809         gint qlen;
810         gchar *linep, *cur, *leftp;
811         gint line_len, cur_len;
812         gint wrap_len;
813         gint str_len;
814         gint ch_len;
815
816         /* if (prefs_common.enable_color) qcolor = &quote_color; */
817         if (prefs_common.quotemark && *prefs_common.quotemark)
818                 qmark = prefs_common.quotemark;
819         else
820                 qmark = "> ";
821         quote_str = compose_quote_parse_fmt(compose, msginfo, qmark);
822         g_return_if_fail(quote_str != NULL);
823         qlen = strlen(quote_str);
824
825         if (!prefs_common.linewrap_quote ||
826             prefs_common.linewrap_len <= qlen) {
827                 while (fgets(buf, sizeof(buf), fp) != NULL) {
828                         gtk_stext_insert(text, NULL, qcolor, NULL,
829                                         quote_str, -1);
830                         gtk_stext_insert(text, NULL, qcolor, NULL, buf, -1);
831                 }
832                 g_free(quote_str);
833                 return;
834         }
835
836         wrap_len = prefs_common.linewrap_len - qlen;
837
838         while (fgets(buf, sizeof(buf), fp) != NULL) {
839                 strretchomp(buf);
840                 str_len = strlen(buf);
841
842                 if (str_len <= wrap_len) {
843                         gtk_stext_insert(text, NULL, qcolor, NULL,
844                                         quote_str, -1);
845                         gtk_stext_insert(text, NULL, qcolor, NULL, buf, -1);
846                         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1);
847                         continue;
848                 }
849
850                 linep = cur = leftp = buf;
851                 line_len = cur_len = 0;
852
853                 while (*cur != '\0') {
854                         ch_len = mblen(cur, MB_CUR_MAX);
855                         if (ch_len < 0) ch_len = 1;
856
857                         if (ch_len == 1 && isspace(*cur)) {
858                                 linep = cur + ch_len;
859                                 line_len = cur_len + ch_len;
860                         }
861
862                         if (cur_len + ch_len > wrap_len && line_len > 0) {
863                                 gtk_stext_insert(text, NULL, qcolor, NULL,
864                                                 quote_str, -1);
865
866                                 if (isspace(*(linep - 1)))
867                                         gtk_stext_insert(text, NULL,
868                                                         qcolor, NULL,
869                                                         leftp, line_len - 1);
870                                 else
871                                         gtk_stext_insert(text, NULL,
872                                                         qcolor, NULL,
873                                                         leftp, line_len);
874                                 gtk_stext_insert(text, NULL, NULL, NULL,
875                                                 "\n", 1);
876
877                                 leftp = linep;
878                                 cur_len = cur_len - line_len + ch_len;
879                                 line_len = 0;
880                                 cur += ch_len;
881                                 continue;
882                         }
883
884                         if (ch_len > 1) {
885                                 linep = cur + ch_len;
886                                 line_len = cur_len + ch_len;
887                         }
888                         cur_len += ch_len;
889                         cur += ch_len;
890                 }
891
892                 if (*leftp) {
893                         gtk_stext_insert(text, NULL, qcolor, NULL,
894                                         quote_str, -1);
895                         gtk_stext_insert(text, NULL, qcolor, NULL, leftp, -1);
896                         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1);
897                 }
898         }
899
900         g_free(quote_str);
901 }
902
903 static gchar *compose_quote_parse_fmt(Compose *compose, MsgInfo *msginfo,
904                                       const gchar *fmt)
905 {
906         gchar *ext_str;
907         size_t buf_len = 1024;
908         size_t ext_len = 0;
909         gchar *str;
910         gchar *mbs;
911         wchar_t *wcsfmt;
912         wchar_t *sp;
913         gchar tmp[3];
914
915         if (!fmt || *fmt == '\0') return 0;
916
917         Xalloca(mbs, sizeof(wchar_t) + 1, return 0);
918         Xalloca(wcsfmt, (strlen(fmt) + 1) * sizeof(wchar_t), return 0);
919         mbstowcs(wcsfmt, fmt, strlen(fmt) + 1);
920         sp = wcsfmt;
921
922         ext_str = g_malloc(sizeof(gchar) * buf_len);
923         g_return_val_if_fail(ext_str != NULL, NULL);
924
925         while (*sp) {
926                 gint len;
927
928                 len = wctomb(mbs, *sp);
929                 mbs[len] = '\0';
930
931                 if (*mbs == '%') {
932                         gchar *p;
933
934                         wctomb(mbs, *(++sp));
935                         str = NULL;
936
937                         switch (*mbs) {
938                         case 'd':
939                                 str = msginfo->date;
940                                 sp++;
941                                 break;
942                         case 'f':
943                                 str = msginfo->from;
944                                 sp++;
945                                 break;
946                         case 'I':       /* initial */
947                                 if (!msginfo->fromname) {sp++; break;}
948                                 p = msginfo->fromname;
949                                 tmp[0] = tmp[1] = tmp[2] = '\0';
950
951                                 if (*p && isalnum(*p))
952                                         tmp[0] = toupper(*p);
953                                 else {
954                                         sp++;
955                                         break;
956                                 }
957
958                                 while (*p) {
959                                         while (*p && !isspace(*p)) p++;
960                                         while (*p && isspace(*p)) p++;
961                                         if (*p && isalnum(*p))
962                                                 tmp[1] = toupper(*p);
963                                 }
964
965                                 if (tmp[1]) str = tmp;
966                                 sp++;
967                                 break;
968                         case 'n':
969                                 str = msginfo->fromname;
970                                 sp++;
971                                 break;
972                         case 'N':
973                                 if (!msginfo->fromname) {sp++; break;}
974                                 Xstrdup_a(str, msginfo->fromname,
975                                           {sp++; break;});
976                                 p = str;
977                                 while (*p && !isspace(*p)) p++;
978                                 *p = '\0';
979                                 sp++;
980                                 break;
981                         case 's':
982                                 str = msginfo->subject;
983                                 sp++;
984                                 break;
985                         case 't':
986                                 str = msginfo->to;
987                                 sp++;
988                                 break;
989                         case 'i':
990                                 if (!msginfo->msgid) {sp++; break;}
991                                 Xalloca(str, strlen(msginfo->msgid) + 3,
992                                         {sp++; break;});
993                                 g_snprintf(str, strlen(msginfo->msgid) + 3,
994                                            "<%s>", msginfo->msgid);
995                                 sp++;
996                                 break;
997                         case '%':
998                                 str = "%";
999                                 sp++;
1000                                 break;
1001                         default:
1002                                 break;
1003                         }
1004
1005                         if (str) {
1006                                 while (ext_len + strlen(str) + 1 > buf_len)
1007                                         buf_len += 1024;
1008                                 ext_str = g_realloc(ext_str,
1009                                                     sizeof(gchar) * buf_len);
1010                                 g_return_val_if_fail(ext_str != NULL, NULL);
1011                                 strcpy(ext_str + ext_len, str);
1012                                 ext_len += strlen(str);
1013                         }
1014                 } else if (*mbs == '\\') {
1015                         wctomb(mbs, *(++sp));
1016                         str = NULL;
1017
1018                         switch (*mbs) {
1019                         case 'n':
1020                                 str = "\n";
1021                                 break;
1022                         case 't':
1023                                 str = "\t";
1024                                 break;
1025                         case '\\':
1026                                 str = "\\";
1027                                 break;
1028                         default:
1029                                 break;
1030                         }
1031
1032                         if (str) {
1033                                 while (ext_len + strlen(str) + 1 > buf_len)
1034                                         buf_len += 1024;
1035                                 ext_str = g_realloc(ext_str,
1036                                                     sizeof(gchar) * buf_len);
1037                                 g_return_val_if_fail(ext_str != NULL, NULL);
1038                                 strcpy(ext_str + ext_len, str);
1039                                 ext_len += strlen(str);
1040                                 sp++;
1041                         }
1042                 } else {
1043                         while (ext_len + len + 1 > buf_len) buf_len += 1024;
1044                         ext_str = g_realloc(ext_str, sizeof(gchar) * buf_len);
1045                         g_return_val_if_fail(ext_str != NULL, NULL);
1046                         strcpy(ext_str + ext_len, mbs);
1047                         ext_len += len;
1048                         sp++;
1049                 }
1050         }
1051
1052         if (ext_str)
1053                 ext_str = g_realloc(ext_str, strlen(ext_str) + 1);
1054
1055         return ext_str;
1056 }
1057
1058 static void compose_reply_set_entry(Compose *compose, MsgInfo *msginfo,
1059                                     gboolean to_all)
1060 {
1061         GSList *cc_list;
1062         GSList *cur;
1063         gchar *from;
1064         GHashTable *to_table;
1065
1066         g_return_if_fail(compose->account != NULL);
1067         g_return_if_fail(msginfo != NULL);
1068
1069         if (compose->account->protocol != A_NNTP)
1070                 gtk_entry_set_text(GTK_ENTRY(compose->to_entry),
1071                                    compose->replyto ? compose->replyto
1072                                    : msginfo->from ? msginfo->from : "");
1073         if (compose->account->protocol == A_NNTP)
1074                 gtk_entry_set_text(GTK_ENTRY(compose->newsgroups_entry),
1075                                    compose->followup_to ? compose->followup_to
1076                                    : compose->newsgroups ? compose->newsgroups
1077                                    : "");
1078
1079         if (msginfo->subject && *msginfo->subject) {
1080                 gchar *buf, *buf2, *p;
1081
1082                 buf = g_strdup(msginfo->subject);
1083                 while (!strncasecmp(buf, "Re:", 3)) {
1084                         p = buf + 3;
1085                         while (isspace(*p)) p++;
1086                         memmove(buf, p, strlen(p) + 1);
1087                 }
1088
1089                 buf2 = g_strdup_printf("Re: %s", buf);
1090                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), buf2);
1091                 g_free(buf2);
1092                 g_free(buf);
1093         } else
1094                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), "Re: ");
1095
1096         if (!to_all || compose->account->protocol == A_NNTP) return;
1097
1098         from = g_strdup(compose->replyto ? compose->replyto :
1099                         msginfo->from ? msginfo->from : "");
1100         extract_address(from);
1101
1102         cc_list = address_list_append(NULL, msginfo->to);
1103         cc_list = address_list_append(cc_list, compose->cc);
1104
1105         to_table = g_hash_table_new(g_str_hash, g_str_equal);
1106         g_hash_table_insert(to_table, from, GINT_TO_POINTER(1));
1107         if (compose->account)
1108                 g_hash_table_insert(to_table, compose->account->address,
1109                                     GINT_TO_POINTER(1));
1110
1111         /* remove address on To: and that of current account */
1112         for (cur = cc_list; cur != NULL; ) {
1113                 GSList *next = cur->next;
1114
1115                 if (g_hash_table_lookup(to_table, cur->data) != NULL)
1116                         cc_list = g_slist_remove(cc_list, cur->data);
1117                 else
1118                         g_hash_table_insert(to_table, cur->data, cur);
1119
1120                 cur = next;
1121         }
1122         g_hash_table_destroy(to_table);
1123         g_free(from);
1124
1125         if (cc_list) {
1126                 for (cur = cc_list; cur != NULL; cur = cur->next)
1127                         compose_entry_append(compose, (gchar *)cur->data,
1128                                              COMPOSE_CC);
1129                 slist_free_strings(cc_list);
1130                 g_slist_free(cc_list);
1131         }
1132 }
1133
1134 #define SET_ENTRY(entry, str) \
1135 { \
1136         if (str && *str) \
1137                 gtk_entry_set_text(GTK_ENTRY(compose->entry), str); \
1138 }
1139
1140 static void compose_reedit_set_entry(Compose *compose, MsgInfo *msginfo)
1141 {
1142         g_return_if_fail(msginfo != NULL);
1143
1144         SET_ENTRY(to_entry, msginfo->to);
1145         SET_ENTRY(subject_entry, msginfo->subject);
1146         SET_ENTRY(cc_entry, compose->cc);
1147         SET_ENTRY(bcc_entry, compose->bcc);
1148         SET_ENTRY(reply_entry, compose->replyto);
1149
1150         if (compose->bcc) {
1151                 GtkItemFactory *ifactory;
1152                 GtkWidget *menuitem;
1153
1154                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1155                 menuitem = gtk_item_factory_get_item(ifactory, "/Message/Bcc");
1156                 gtk_check_menu_item_set_active
1157                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
1158         }
1159         if (compose->replyto) {
1160                 GtkItemFactory *ifactory;
1161                 GtkWidget *menuitem;
1162
1163                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1164                 menuitem = gtk_item_factory_get_item
1165                         (ifactory, "/Message/Reply to");
1166                 gtk_check_menu_item_set_active
1167                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
1168         }
1169 }
1170
1171 static void compose_insert_sig(Compose *compose)
1172 {
1173         gchar *sigfile;
1174
1175         if (compose->account && compose->account->sig_path)
1176                 sigfile = g_strdup(compose->account->sig_path);
1177         else {
1178                 sigfile = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1179                                       DEFAULT_SIGNATURE, NULL);
1180         }
1181
1182         if (!is_file_or_fifo_exist(sigfile)) {
1183                 g_free(sigfile);
1184                 return;
1185         }
1186
1187         gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, "\n\n", 2);
1188         if (prefs_common.sig_sep) {
1189                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL,
1190                                 prefs_common.sig_sep, -1);
1191                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL,
1192                                 "\n", 1);
1193         }
1194
1195         compose_insert_file(compose, sigfile);
1196         g_free(sigfile);
1197 }
1198
1199 static void compose_insert_file(Compose *compose, const gchar *file)
1200 {
1201         GtkSText *text = GTK_STEXT(compose->text);
1202         gchar buf[BUFFSIZE];
1203         FILE *fp;
1204
1205         g_return_if_fail(file != NULL);
1206
1207         if ((fp = fopen(file, "r")) == NULL) {
1208                 FILE_OP_ERROR(file, "fopen");
1209                 return;
1210         }
1211
1212         gtk_stext_freeze(text);
1213
1214         while (fgets(buf, sizeof(buf), fp) != NULL)
1215                 gtk_stext_insert(text, NULL, NULL, NULL, buf, -1);
1216
1217         gtk_stext_thaw(text);
1218
1219         fclose(fp);
1220 }
1221
1222 static void compose_attach_append(Compose *compose, const gchar *file,
1223                                   ContentType cnttype)
1224 {
1225         AttachInfo *ainfo;
1226         gchar *text[N_ATTACH_COLS];
1227         off_t size;
1228         gint row;
1229
1230         if (!is_file_exist(file)) {
1231                 g_warning(_("File %s doesn't exist\n"), file);
1232                 return;
1233         }
1234         if ((size = get_file_size(file)) < 0) {
1235                 g_warning(_("Can't get file size of %s\n"), file);
1236                 return;
1237         }
1238         if (size == 0) {
1239                 alertpanel_notice(_("File %s is empty\n"), file);
1240                 return;
1241         }
1242
1243         if (!compose->use_attach) {
1244                 GtkItemFactory *ifactory;
1245                 GtkWidget *menuitem;
1246
1247                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1248                 menuitem = gtk_item_factory_get_item(ifactory,
1249                                                      "/Message/Attach");
1250                 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
1251                                                TRUE);
1252         }
1253
1254         ainfo = g_new0(AttachInfo, 1);
1255         ainfo->file = g_strdup(file);
1256
1257         if (cnttype == MIME_MESSAGE_RFC822) {
1258                 ainfo->content_type = g_strdup("message/rfc822");
1259                 ainfo->encoding = ENC_7BIT;
1260                 ainfo->name = g_strdup_printf(_("Message: %s"),
1261                                               g_basename(file));
1262         } else {
1263                 ainfo->content_type = procmime_get_mime_type(file);
1264                 if (!ainfo->content_type)
1265                         ainfo->content_type =
1266                                 g_strdup("application/octet-stream");
1267                 ainfo->encoding = ENC_BASE64;
1268                 ainfo->name = g_strdup(g_basename(file));
1269         }
1270         ainfo->size = size;
1271
1272         text[COL_MIMETYPE] = ainfo->content_type;
1273         text[COL_SIZE] = to_human_readable(size);
1274         text[COL_NAME] = ainfo->name;
1275
1276         row = gtk_clist_append(GTK_CLIST(compose->attach_clist), text);
1277         gtk_clist_set_row_data(GTK_CLIST(compose->attach_clist), row, ainfo);
1278
1279         if (cnttype != MIME_MESSAGE_RFC822)
1280                 compose_changed_cb(NULL, compose);
1281 }
1282
1283 static void compose_wrap_line(Compose *compose)
1284 {
1285         GtkSText *text = GTK_STEXT(compose->text);
1286         guint text_len;
1287         guint line_pos = 0, cur_pos = 0;
1288         gint line_len = 0, cur_len = 0;
1289         gint ch_len;
1290         gchar cbuf[MB_CUR_MAX];
1291
1292         gtk_stext_freeze(text);
1293
1294         text_len = gtk_stext_get_length(text);
1295
1296         for (; cur_pos < text_len; cur_pos++) {
1297                 if (text->use_wchar)
1298                         ch_len = wctomb
1299                                 (cbuf, (wchar_t)GTK_STEXT_INDEX(text, cur_pos));
1300                 else {
1301                         cbuf[0] = GTK_STEXT_INDEX(text, cur_pos);
1302                         ch_len = 1;
1303                 }
1304
1305                 if (ch_len == 1 && *cbuf == '\n') {
1306                         line_pos = cur_pos + 1;
1307                         line_len = cur_len = 0;
1308                         continue;
1309                 }
1310
1311                 if (ch_len < 0) {
1312                         cbuf[0] = '\0';
1313                         ch_len = 1;
1314                 }
1315
1316                 if (ch_len == 1 && isspace(*cbuf)) {
1317                         line_pos = cur_pos + 1;
1318                         line_len = cur_len + ch_len;
1319                 }
1320
1321                 if (cur_len + ch_len > prefs_common.linewrap_len &&
1322                     line_len > 0) {
1323                         gint tlen;
1324
1325                         if (text->use_wchar)
1326                                 tlen = wctomb(cbuf, (wchar_t)GTK_STEXT_INDEX(text, line_pos - 1));
1327                         else {
1328                                 cbuf[0] = GTK_STEXT_INDEX(text, line_pos - 1);
1329                                 tlen = 1;
1330                         }
1331                         if (tlen == 1 && isspace(*cbuf)) {
1332                                 gtk_stext_set_point(text, line_pos);
1333                                 gtk_stext_backward_delete(text, 1);
1334                                 text_len--;
1335                                 cur_pos--;
1336                                 line_pos--;
1337                                 cur_len--;
1338                                 line_len--;
1339                         }
1340
1341                         gtk_stext_set_point(text, line_pos);
1342                         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1);
1343                         text_len++;
1344                         cur_pos++;
1345                         line_pos++;
1346                         cur_len = cur_len - line_len + ch_len;
1347                         line_len = 0;
1348                         continue;
1349                 }
1350
1351                 if (ch_len > 1) {
1352                         line_pos = cur_pos + 1;
1353                         line_len = cur_len + ch_len;
1354                 }
1355                 cur_len += ch_len;
1356         }
1357
1358         gtk_stext_thaw(text);
1359 }
1360
1361 static void compose_set_title(Compose *compose)
1362 {
1363         gchar *str;
1364         gchar *edited;
1365
1366         edited = compose->modified ? _(" [Edited]") : "";
1367         if (compose->account && compose->account->address)
1368                 str = g_strdup_printf(_("%s - Compose message%s"),
1369                                       compose->account->address, edited);
1370         else
1371                 str = g_strdup_printf(_("Compose message%s"), edited);
1372         gtk_window_set_title(GTK_WINDOW(compose->window), str);
1373         g_free(str);
1374 }
1375
1376 static gint compose_send(Compose *compose)
1377 {
1378         gchar tmp[MAXPATHLEN + 1];
1379         gchar *to, *newsgroups;
1380         gint ok = 0;
1381         static gboolean lock = FALSE;
1382
1383         if (lock) return 1;
1384
1385         g_return_val_if_fail(compose->account != NULL, -1);
1386         g_return_val_if_fail(compose->orig_account != NULL, -1);
1387
1388         lock = TRUE;
1389
1390         to = gtk_entry_get_text(GTK_ENTRY(compose->to_entry));
1391         newsgroups = gtk_entry_get_text(GTK_ENTRY(compose->newsgroups_entry));
1392         if (*to == '\0' && *newsgroups == '\0') {
1393                 alertpanel_error(_("Recipient is not specified."));
1394                 lock = FALSE;
1395                 return 1;
1396         }
1397
1398         /* write to temporary file */
1399         g_snprintf(tmp, sizeof(tmp), "%s%ctmpmsg%d",
1400                    get_rc_dir(), G_DIR_SEPARATOR, (gint)compose);
1401
1402         if (prefs_common.linewrap_at_send)
1403                 compose_wrap_line(compose);
1404
1405         if (compose_write_to_file(compose, tmp, FALSE) < 0) {
1406                 lock = FALSE;
1407                 return -1;
1408         }
1409
1410         if (!compose->to_list && !compose->newsgroup_list) {
1411                 g_warning(_("can't get recipient list."));
1412                 unlink(tmp);
1413                 lock = FALSE;
1414                 return -1;
1415         }
1416
1417         if (compose->to_list) {
1418                 PrefsAccount *ac;
1419
1420                 if (compose->account->protocol != A_NNTP)
1421                         ac = compose->account;
1422                 else if (compose->orig_account->protocol != A_NNTP)
1423                         ac = compose->orig_account;
1424                 else if (cur_account && cur_account->protocol != A_NNTP)
1425                         ac = cur_account;
1426                 else {
1427                         ac = account_get_default();
1428                         if (!ac || ac->protocol == A_NNTP) {
1429                                 alertpanel_error(_("Account for sending mail is not specified.\n"
1430                                                    "Please select a mail account before sending."));
1431                                 unlink(tmp);
1432                                 lock = FALSE;
1433                                 return -1;
1434                         }
1435                 }
1436                 ok = send_message(tmp, ac, compose->to_list);
1437                 statusbar_pop_all();
1438         }
1439
1440         if (ok == 0 && compose->newsgroup_list) {
1441                 Folder *folder;
1442
1443                 if (compose->account->protocol == A_NNTP)
1444                         folder = FOLDER(compose->account->folder);
1445                 else
1446                         folder = FOLDER(compose->orig_account->folder);
1447
1448                 ok = news_post(folder, tmp);
1449                 if (ok < 0) {
1450                         alertpanel_error(_("Error occurred while posting the message to %s ."),
1451                                          compose->account->nntp_server);
1452                         unlink(tmp);
1453                         lock = FALSE;
1454                         return -1;
1455                 }
1456         }
1457
1458         /* queue message if failed to send */
1459         if (ok < 0) {
1460                 if (prefs_common.queue_msg) {
1461                         AlertValue val;
1462
1463                         val = alertpanel
1464                                 (_("Queueing"),
1465                                  _("Error occurred while sending the message.\n"
1466                                    "Put this message into queue folder?"),
1467                                  _("OK"), _("Cancel"), NULL);
1468                         if (G_ALERTDEFAULT == val) {
1469                                 ok = compose_queue(compose, tmp);
1470                                 if (ok < 0)
1471                                         alertpanel_error(_("Can't queue the message."));
1472                         }
1473                 } else
1474                         alertpanel_error(_("Error occurred while sending the message."));
1475         }
1476
1477         /* save message to outbox */
1478         if (ok == 0 && prefs_common.savemsg) {
1479                 if (compose_save_to_outbox(compose, tmp) < 0)
1480                         alertpanel_error
1481                                 (_("Can't save the message to outbox."));
1482         }
1483
1484         if (unlink(tmp) < 0) FILE_OP_ERROR(tmp, "unlink");
1485         lock = FALSE;
1486         return ok;
1487 }
1488
1489 static gint compose_write_to_file(Compose *compose, const gchar *file,
1490                                   gboolean is_draft)
1491 {
1492         FILE *fp;
1493         size_t len;
1494         gchar *chars;
1495         gchar *buf;
1496         const gchar *out_codeset;
1497         EncodingType encoding;
1498
1499         if ((fp = fopen(file, "w")) == NULL) {
1500                 FILE_OP_ERROR(file, "fopen");
1501                 return -1;
1502         }
1503
1504         /* chmod for security */
1505         if (change_file_mode_rw(fp, file) < 0) {
1506                 FILE_OP_ERROR(file, "chmod");
1507                 g_warning(_("can't change file mode\n"));
1508         }
1509
1510         /* get all composed text */
1511         chars = gtk_editable_get_chars(GTK_EDITABLE(compose->text), 0, -1);
1512         len = strlen(chars);
1513         if (is_ascii_str(chars)) {
1514                 buf = g_strdup(chars);
1515                 out_codeset = "US-ASCII";
1516                 encoding = ENC_7BIT;
1517         } else {
1518                 const gchar *src_codeset;
1519
1520                 out_codeset = conv_get_outgoing_charset_str();
1521                 if (!strcasecmp(out_codeset, "US-ASCII"))
1522                         out_codeset = "ISO-8859-1";
1523                 encoding = procmime_get_encoding_for_charset(out_codeset);
1524                 debug_print("charset = %s, encoding = %s\n",
1525                             out_codeset, procmime_get_encoding_str(encoding));
1526
1527                 src_codeset = conv_get_current_charset_str();
1528                 buf = conv_codeset_strdup(chars, src_codeset, out_codeset);
1529                 if (!buf) {
1530                         g_free(chars);
1531                         fclose(fp);
1532                         unlink(file);
1533                         alertpanel_error(_("Can't convert the codeset of the message."));
1534                         return -1;
1535                 }
1536         }
1537         g_free(chars);
1538
1539         /* write headers */
1540         if (compose_write_headers
1541                 (compose, fp, out_codeset, encoding, is_draft) < 0) {
1542                 g_warning(_("can't write headers\n"));
1543                 fclose(fp);
1544                 unlink(file);
1545                 g_free(buf);
1546                 return -1;
1547         }
1548
1549         if (compose->use_attach) {
1550 #if USE_GPGME
1551             /* This prolog message is ignored by mime software and
1552              * because it would make our signing/encryption task
1553              * tougher, we don't emit it in that case */
1554             if (!compose->use_signing && !compose->use_encryption)
1555 #endif
1556                 fputs("This is a multi-part message in MIME format.\n", fp);
1557
1558                 fprintf(fp, "\n--%s\n", compose->boundary);
1559                 fprintf(fp, "Content-Type: text/plain; charset=%s\n",
1560                         out_codeset);
1561                 fprintf(fp, "Content-Transfer-Encoding: %s\n",
1562                         procmime_get_encoding_str(encoding));
1563                 fputc('\n', fp);
1564         }
1565
1566         /* write body */
1567         len = strlen(buf);
1568         if (encoding == ENC_BASE64) {
1569                 gchar outbuf[B64_BUFFSIZE];
1570                 gint i, l;
1571
1572                 for (i = 0; i < len; i += B64_LINE_SIZE) {
1573                         l = MIN(B64_LINE_SIZE, len - i);
1574                         to64frombits(outbuf, buf + i, l);
1575                         fputs(outbuf, fp);
1576                         fputc('\n', fp);
1577                 }
1578         } else if (fwrite(buf, sizeof(gchar), len, fp) != len) {
1579                 FILE_OP_ERROR(file, "fwrite");
1580                 fclose(fp);
1581                 unlink(file);
1582                 g_free(buf);
1583                 return -1;
1584         }
1585         g_free(buf);
1586
1587         if (compose->use_attach)
1588                 compose_write_attach(compose, fp);
1589
1590         if (fclose(fp) == EOF) {
1591                 FILE_OP_ERROR(file, "fclose");
1592                 unlink(file);
1593                 return -1;
1594         }
1595
1596 #if USE_GPGME
1597         if (compose->use_signing) {
1598                 if (rfc2015_sign(file, compose->account) < 0) {
1599                         unlink(file);
1600                         return -1;
1601                 }
1602         }
1603         if (compose->use_encryption) {
1604                 if (rfc2015_encrypt(file, compose->to_list) < 0) {
1605                         unlink(file);
1606                         return -1;
1607                 }
1608         }
1609 #endif /* USE_GPGME */
1610
1611         return 0;
1612 }
1613
1614 static gint compose_write_body_to_file(Compose *compose, const gchar *file)
1615 {
1616         FILE *fp;
1617         size_t len;
1618         gchar *chars;
1619
1620         if ((fp = fopen(file, "w")) == NULL) {
1621                 FILE_OP_ERROR(file, "fopen");
1622                 return -1;
1623         }
1624
1625         /* chmod for security */
1626         if (change_file_mode_rw(fp, file) < 0) {
1627                 FILE_OP_ERROR(file, "chmod");
1628                 g_warning(_("can't change file mode\n"));
1629         }
1630
1631         chars = gtk_editable_get_chars(GTK_EDITABLE(compose->text), 0, -1);
1632
1633         /* write body */
1634         len = strlen(chars);
1635         if (fwrite(chars, sizeof(gchar), len, fp) != len) {
1636                 FILE_OP_ERROR(file, "fwrite");
1637                 g_free(chars);
1638                 fclose(fp);
1639                 unlink(file);
1640                 return -1;
1641         }
1642
1643         g_free(chars);
1644
1645         if (fclose(fp) == EOF) {
1646                 FILE_OP_ERROR(file, "fclose");
1647                 unlink(file);
1648                 return -1;
1649         }
1650         return 0;
1651 }
1652
1653 static gint compose_save_to_outbox(Compose *compose, const gchar *file)
1654 {
1655         FolderItem *outbox;
1656         gchar *path;
1657         gint num;
1658         FILE *fp;
1659
1660         debug_print(_("saving sent message...\n"));
1661
1662         outbox = folder_get_default_outbox();
1663         folder_item_scan(outbox);
1664         if ((num = folder_item_add_msg(outbox, file)) < 0) {
1665                 g_warning(_("can't save message\n"));
1666                 return -1;
1667         }
1668
1669         path = folder_item_get_path(outbox);
1670         if ((fp = procmsg_open_mark_file(path, TRUE)) == NULL)
1671                 g_warning(_("can't open mark file\n"));
1672         else {
1673                 MsgInfo newmsginfo;
1674
1675                 newmsginfo.msgnum = num;
1676                 newmsginfo.flags = 0;
1677                 procmsg_write_flags(&newmsginfo, fp);
1678                 fclose(fp);
1679         }
1680         g_free(path);
1681
1682         return 0;
1683 }
1684
1685 static gint compose_queue(Compose *compose, const gchar *file)
1686 {
1687         FolderItem *queue;
1688         gchar *tmp, *queue_path;
1689         FILE *fp, *src_fp;
1690         GSList *cur;
1691         gchar buf[BUFFSIZE];
1692         gint num;
1693
1694         debug_print(_("queueing message...\n"));
1695         g_return_val_if_fail(compose->to_list != NULL, -1);
1696         g_return_val_if_fail(compose->account != NULL, -1);
1697
1698         tmp = g_strdup_printf("%s%cqueue.%d", g_get_tmp_dir(),
1699                               G_DIR_SEPARATOR, (gint)compose);
1700         if ((fp = fopen(tmp, "w")) == NULL) {
1701                 FILE_OP_ERROR(tmp, "fopen");
1702                 g_free(tmp);
1703                 return -1;
1704         }
1705         if ((src_fp = fopen(file, "r")) == NULL) {
1706                 FILE_OP_ERROR(file, "fopen");
1707                 fclose(fp);
1708                 unlink(tmp);
1709                 g_free(tmp);
1710                 return -1;
1711         }
1712         if (change_file_mode_rw(fp, tmp) < 0) {
1713                 FILE_OP_ERROR(tmp, "chmod");
1714                 g_warning(_("can't change file mode\n"));
1715         }
1716
1717         /* queueing variables */
1718         fprintf(fp, "AF:\n");
1719         fprintf(fp, "NF:0\n");
1720         fprintf(fp, "PS:10\n");
1721         fprintf(fp, "SRH:1\n");
1722         fprintf(fp, "SFN:\n");
1723         fprintf(fp, "DSR:\n");
1724         if (compose->msgid)
1725                 fprintf(fp, "MID:<%s>\n", compose->msgid);
1726         else
1727                 fprintf(fp, "MID:\n");
1728         fprintf(fp, "CFG:\n");
1729         fprintf(fp, "PT:0\n");
1730         fprintf(fp, "S:%s\n", compose->account->address);
1731         fprintf(fp, "RQ:\n");
1732         if (compose->account->smtp_server)
1733                 fprintf(fp, "SSV:%s\n", compose->account->smtp_server);
1734         else
1735                 fprintf(fp, "SSV:\n");
1736         if (compose->account->nntp_server)
1737                 fprintf(fp, "NSV:%s\n", compose->account->nntp_server);
1738         else
1739                 fprintf(fp, "NSV:\n");
1740         fprintf(fp, "SSH:\n");
1741         fprintf(fp, "R:<%s>", (gchar *)compose->to_list->data);
1742         for (cur = compose->to_list->next; cur != NULL; cur = cur->next)
1743                 fprintf(fp, ",<%s>", (gchar *)cur->data);
1744         fprintf(fp, "\n");
1745         fprintf(fp, "\n");
1746
1747         while (fgets(buf, sizeof(buf), src_fp) != NULL) {
1748                 if (fputs(buf, fp) == EOF) {
1749                         FILE_OP_ERROR(tmp, "fputs");
1750                         fclose(fp);
1751                         fclose(src_fp);
1752                         unlink(tmp);
1753                         g_free(tmp);
1754                         return -1;
1755                 }
1756         }
1757
1758         fclose(src_fp);
1759         if (fclose(fp) == EOF) {
1760                 FILE_OP_ERROR(tmp, "fclose");
1761                 unlink(tmp);
1762                 g_free(tmp);
1763                 return -1;
1764         }
1765
1766         queue = folder_get_default_queue();
1767         folder_item_scan(queue);
1768         if ((num = folder_item_add_msg(queue, tmp)) < 0) {
1769                 g_warning(_("can't queue the message\n"));
1770                 unlink(tmp);
1771                 g_free(tmp);
1772                 return -1;
1773         }
1774         unlink(tmp);
1775         g_free(tmp);
1776
1777         queue_path = folder_item_get_path(queue);
1778         if ((fp = procmsg_open_mark_file(queue_path, TRUE)) == NULL)
1779                 g_warning(_("can't open mark file\n"));
1780         else {
1781                 MsgInfo newmsginfo;
1782
1783                 newmsginfo.msgnum = num;
1784                 newmsginfo.flags = 0;
1785                 procmsg_write_flags(&newmsginfo, fp);
1786                 fclose(fp);
1787         }
1788         g_free(queue_path);
1789
1790         folder_item_scan(queue);
1791         folderview_update_item(queue, TRUE);
1792
1793         return 0;
1794 }
1795
1796 static void compose_write_attach(Compose *compose, FILE *fp)
1797 {
1798         AttachInfo *ainfo;
1799         GtkCList *clist = GTK_CLIST(compose->attach_clist);
1800         gint row;
1801         FILE *attach_fp;
1802         gchar filename[BUFFSIZE];
1803         gint len;
1804
1805         for (row = 0; (ainfo = gtk_clist_get_row_data(clist, row)) != NULL;
1806              row++) {
1807                 if ((attach_fp = fopen(ainfo->file, "r")) == NULL) {
1808                         g_warning(_("Can't open file %s\n"), ainfo->file);
1809                         continue;
1810                 }
1811
1812                 fprintf(fp, "\n--%s\n", compose->boundary);
1813
1814                 if (!strcmp2(ainfo->content_type, "message/rfc822")) {
1815                         fprintf(fp, "Content-Type: %s\n", ainfo->content_type);
1816                         fprintf(fp, "Content-Disposition: inline\n");
1817                 } else {
1818                         conv_encode_header(filename, sizeof(filename),
1819                                            ainfo->name, 12);
1820                         fprintf(fp, "Content-Type: %s;\n"
1821                                     " name=\"%s\"\n",
1822                                 ainfo->content_type, filename);
1823                         fprintf(fp, "Content-Disposition: attachment;\n"
1824                                     " filename=\"%s\"\n", filename);
1825                 }
1826
1827                 fprintf(fp, "Content-Transfer-Encoding: %s\n\n",
1828                         procmime_get_encoding_str(ainfo->encoding));
1829
1830                 if (ainfo->encoding == ENC_7BIT) {
1831                         gchar buf[BUFFSIZE];
1832
1833                         while (fgets(buf, sizeof(buf), attach_fp) != NULL) {
1834                                 len = strlen(buf);
1835                                 if (len > 1 && buf[len - 1] == '\n' &&
1836                                     buf[len - 2] == '\r') {
1837                                         buf[len - 2] = '\n';
1838                                         buf[len - 1] = '\0';
1839                                 }
1840                                 fputs(buf, fp);
1841                         }
1842                 } else {
1843                         gchar inbuf[B64_LINE_SIZE], outbuf[B64_BUFFSIZE];
1844
1845                         while ((len = fread(inbuf, sizeof(gchar),
1846                                             B64_LINE_SIZE, attach_fp))
1847                                == B64_LINE_SIZE) {
1848                                 to64frombits(outbuf, inbuf, B64_LINE_SIZE);
1849                                 fputs(outbuf, fp);
1850                                 fputc('\n', fp);
1851                         }
1852                         if (len > 0 && feof(attach_fp)) {
1853                                 to64frombits(outbuf, inbuf, len);
1854                                 fputs(outbuf, fp);
1855                                 fputc('\n', fp);
1856                         }
1857                 }
1858
1859                 fclose(attach_fp);
1860         }
1861
1862         fprintf(fp, "\n--%s--\n", compose->boundary);
1863 }
1864
1865 static gint is_in_custom_headers(Compose *compose, gchar * header)
1866 {
1867         GSList * cur;
1868
1869         if (compose->account->add_customhdr) {
1870                 for (cur = compose->account->customhdr_list;
1871                      cur != NULL; cur = cur->next) {
1872                         CustomHeader * ch = (CustomHeader *) cur->data;
1873                         if (strcasecmp(ch->name, header) == 0)
1874                                 return 1;
1875                 }
1876         }
1877         return 0;
1878 }
1879
1880 static gint compose_write_headers(Compose *compose, FILE *fp,
1881                                   const gchar *charset, EncodingType encoding,
1882                                   gboolean is_draft)
1883 {
1884         gchar buf[BUFFSIZE];
1885         gchar *str;
1886         /* struct utsname utsbuf; */
1887         GSList * cur;
1888
1889         g_return_val_if_fail(fp != NULL, -1);
1890         g_return_val_if_fail(charset != NULL, -1);
1891         g_return_val_if_fail(compose->account != NULL, -1);
1892         g_return_val_if_fail(compose->account->address != NULL, -1);
1893
1894         /* Date */
1895         if (!is_in_custom_headers(compose, "Date")) {
1896                 if (compose->account->add_date) {
1897                         get_rfc822_date(buf, sizeof(buf));
1898                         fprintf(fp, "Date: %s\n", buf);
1899                 }
1900         }
1901
1902         /* From */
1903         if (!is_in_custom_headers(compose, "From")) {
1904                 if (compose->account->name && *compose->account->name) {
1905                         compose_convert_header
1906                                 (buf, sizeof(buf), compose->account->name,
1907                                  strlen("From: "));
1908                         fprintf(fp, "From: %s <%s>\n", buf, compose->account->address);
1909                 } else
1910                         fprintf(fp, "From: %s\n", compose->account->address);
1911         }
1912
1913         slist_free_strings(compose->to_list);
1914         g_slist_free(compose->to_list);
1915         compose->to_list = NULL;
1916
1917         /* To */
1918         if (compose->use_to) {
1919                 str = gtk_entry_get_text(GTK_ENTRY(compose->to_entry));
1920                 if (*str != '\0') {
1921                         Xstrdup_a(str, str, return -1);
1922                         g_strstrip(str);
1923                         if (*str != '\0') {
1924                                 compose->to_list = address_list_append
1925                                         (compose->to_list, str);
1926                                 compose_convert_header(buf, sizeof(buf), str,
1927                                                        strlen("To: "));
1928                                 if (!is_in_custom_headers(compose, "To")) {
1929                                         fprintf(fp, "To: %s\n", buf);
1930                                 }
1931                         }
1932                 }
1933         }
1934
1935         slist_free_strings(compose->newsgroup_list);
1936         g_slist_free(compose->newsgroup_list);
1937         compose->newsgroup_list = NULL;
1938
1939         /* Newsgroups */
1940         str = gtk_entry_get_text(GTK_ENTRY(compose->newsgroups_entry));
1941         if (*str != '\0') {
1942                 Xstrdup_a(str, str, return -1);
1943                 g_strstrip(str);
1944                 remove_space(str);
1945                 if (*str != '\0') {
1946                         compose->newsgroup_list =
1947                                 newsgroup_list_append(compose->newsgroup_list,
1948                                                       str);
1949                         compose_convert_header(buf, sizeof(buf), str,
1950                                                strlen("Newsgroups: "));
1951                         if (!is_in_custom_headers(compose, "Newsgroups")) {
1952                                 fprintf(fp, "Newsgroups: %s\n", buf);
1953                         }
1954                 }
1955         }
1956
1957         if (!is_draft && !compose->to_list && !compose->newsgroup_list)
1958                 return -1;
1959
1960         /* Cc */
1961         if (compose->use_cc) {
1962                 str = gtk_entry_get_text(GTK_ENTRY(compose->cc_entry));
1963                 if (*str != '\0') {
1964                         Xstrdup_a(str, str, return -1);
1965                         g_strstrip(str);
1966                         if (*str != '\0') {
1967                                 compose->to_list = address_list_append
1968                                         (compose->to_list, str);
1969                                 compose_convert_header(buf, sizeof(buf), str,
1970                                                        strlen("Cc: "));
1971                                 if (!is_in_custom_headers(compose, "Cc")) {
1972                                         fprintf(fp, "Cc: %s\n", buf);
1973                                 }
1974                         }
1975                 }
1976         }
1977
1978         /* Bcc */
1979         if (compose->use_bcc) {
1980                 str = gtk_entry_get_text(GTK_ENTRY(compose->bcc_entry));
1981                 if (*str != '\0') {
1982                         Xstrdup_a(str, str, return -1);
1983                         g_strstrip(str);
1984                         if (*str != '\0') {
1985                                 compose->to_list = address_list_append
1986                                         (compose->to_list, str);
1987                                 if (is_draft) {
1988                                         compose_convert_header
1989                                                 (buf, sizeof(buf), str,
1990                                                  strlen("Bcc: "));
1991                                         if (!is_in_custom_headers(compose,
1992                                                                   "Bcc")) {
1993                                                 fprintf(fp, "Bcc: %s\n", buf);
1994                                         }
1995                                 }
1996                         }
1997                 }
1998         }
1999
2000         /* Subject */
2001         if (!is_in_custom_headers(compose, "Subject")) {
2002                 str = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
2003                 if (*str != '\0') {
2004                         Xstrdup_a(str, str, return -1);
2005                         g_strstrip(str);
2006                         if (*str != '\0') {
2007                                 compose_convert_header(buf, sizeof(buf), str,
2008                                                        strlen("Subject: "));
2009                                 fprintf(fp, "Subject: %s\n", buf);
2010                         }
2011                 }
2012         }
2013
2014         /* Message-ID */
2015         if (!is_in_custom_headers(compose, "Message-Id")) {
2016                 if (compose->account->gen_msgid) {
2017                         compose_generate_msgid(compose, buf, sizeof(buf));
2018                         fprintf(fp, "Message-Id: <%s>\n", buf);
2019                         compose->msgid = g_strdup(buf);
2020                 }
2021         }
2022
2023         /* In-Reply-To */
2024         if (!is_in_custom_headers(compose, "In-Reply-To")) {
2025                 if (compose->inreplyto && compose->to_list)
2026                         fprintf(fp, "In-Reply-To: <%s>\n", compose->inreplyto);
2027         }
2028
2029         /* References */
2030         if (!is_in_custom_headers(compose, "References")) {
2031                 if (compose->references)
2032                         fprintf(fp, "References: %s\n", compose->references);
2033         }
2034
2035         /* Followup-To */
2036         if (!is_in_custom_headers(compose, "Followup-To")) {
2037                 if (compose->use_followupto) {
2038                         str = gtk_entry_get_text(GTK_ENTRY(compose->followup_entry));
2039                         if (*str != '\0') {
2040                                 Xstrdup_a(str, str, return -1);
2041                                 g_strstrip(str);
2042                                 remove_space(str);
2043                                 if (*str != '\0') {
2044                                         compose_convert_header(buf, sizeof(buf), str,
2045                                                                strlen("Followup-To: "));
2046                                         fprintf(fp, "Followup-To: %s\n", buf);
2047                                 }
2048                         }
2049                 }
2050         }
2051
2052         /* Reply-To */
2053         if (!is_in_custom_headers(compose, "Reply-To")) {
2054                 if (compose->use_replyto) {
2055                         str = gtk_entry_get_text(GTK_ENTRY(compose->reply_entry));
2056                         if (*str != '\0') {
2057                                 Xstrdup_a(str, str, return -1);
2058                                 g_strstrip(str);
2059                                 if (*str != '\0') {
2060                                         compose_convert_header(buf, sizeof(buf), str,
2061                                                                strlen("Reply-To: "));
2062                                         fprintf(fp, "Reply-To: %s\n", buf);
2063                                 }
2064                         }
2065                 }
2066         }
2067
2068         /* Program version and system info */
2069         /* uname(&utsbuf); */
2070         if (!is_in_custom_headers(compose, "X-Mailer")) {
2071                 str = gtk_entry_get_text(GTK_ENTRY(compose->to_entry));
2072                 if (*str != '\0') {
2073                         fprintf(fp, "X-Mailer: %s (GTK+ %d.%d.%d; %s)\n",
2074                                 prog_version,
2075                                 gtk_major_version, gtk_minor_version, gtk_micro_version,
2076                                 HOST_ALIAS);
2077                         /* utsbuf.sysname, utsbuf.release, utsbuf.machine); */
2078                 }
2079         }
2080
2081         if (!is_in_custom_headers(compose, "X-Newsreader")) {
2082                 str = gtk_entry_get_text(GTK_ENTRY(compose->newsgroups_entry));
2083                 if (*str != '\0') {
2084                 fprintf(fp, "X-Newsreader: %s (GTK+ %d.%d.%d; %s)\n",
2085                         prog_version,
2086                         gtk_major_version, gtk_minor_version, gtk_micro_version,
2087                         HOST_ALIAS);
2088                         /* utsbuf.sysname, utsbuf.release, utsbuf.machine); */
2089                 }
2090         }
2091
2092         /* Organization */
2093         if (!is_in_custom_headers(compose, "Organization")) {
2094                 if (compose->account->organization) {
2095                         compose_convert_header(buf, sizeof(buf),
2096                                                compose->account->organization,
2097                                                strlen("Organization: "));
2098                         fprintf(fp, "Organization: %s\n", buf);
2099                 }
2100         }
2101
2102         /* MIME */
2103         if (!is_in_custom_headers(compose, "Mime-Version")) {
2104                 fprintf(fp, "Mime-Version: 1.0\n");
2105         }
2106
2107         /* Request Return Receipt */
2108         if (!is_in_custom_headers(compose, "Disposition-Notification-To")) {
2109                 if (compose->return_receipt) {
2110                         if (compose->account->name
2111                             && *compose->account->name) {
2112                                 compose_convert_header(buf, sizeof(buf), compose->account->name, strlen("Disposition-Notification-To: "));
2113                                 fprintf(fp, "Disposition-Notification-To: %s <%s>\n", buf, compose->account->address);
2114                         } else
2115                                 fprintf(fp, "Disposition-Notification-To: %s\n", compose->account->address);
2116                 }
2117         }
2118
2119         if (compose->use_attach) {
2120                 get_rfc822_date(buf, sizeof(buf));
2121                 subst_char(buf, ' ', '_');
2122                 subst_char(buf, ',', '_');
2123                 compose->boundary = g_strdup_printf("Multipart_%s_%08x",
2124                                                     buf, (guint)compose);
2125                 if (!is_in_custom_headers(compose, "Content-Type")) {
2126                         fprintf(fp,
2127                                 "Content-Type: multipart/mixed;\n"
2128                                 " boundary=\"%s\"\n", compose->boundary);
2129                 }
2130         } else {
2131                 if (!is_in_custom_headers(compose, "Content-Type")) {
2132                         fprintf(fp, "Content-Type: text/plain; charset=%s\n", charset);
2133                 }
2134                 if (!is_in_custom_headers(compose,
2135                                           "Content-Transfer-Encoding")) {
2136                         fprintf(fp, "Content-Transfer-Encoding: %s\n",
2137                                 procmime_get_encoding_str(encoding));
2138                 }
2139         }
2140
2141         /* Custom Headers */
2142         if (compose->account->add_customhdr) {
2143                 for (cur = compose->account->customhdr_list; cur != NULL;
2144                      cur = cur->next) {
2145                         CustomHeader * ch = (CustomHeader *) cur->data;
2146                         fprintf(fp, "%s: %s\n", ch->name, ch->value);
2147                 }
2148         }
2149
2150         /* separator between header and body */
2151         fputs("\n", fp);
2152
2153         return 0;
2154 }
2155
2156 static void compose_convert_header(gchar *dest, gint len, gchar *src,
2157                                    gint header_len)
2158 {
2159         g_return_if_fail(src != NULL);
2160         g_return_if_fail(dest != NULL);
2161
2162         if (len < 1) return;
2163
2164         remove_return(src);
2165
2166         if (is_ascii_str(src)) {
2167                 strncpy2(dest, src, len);
2168                 dest[len - 1] = '\0';
2169                 return;
2170         } else
2171                 conv_encode_header(dest, len, src, header_len);
2172 }
2173
2174 static void compose_generate_msgid(Compose *compose, gchar *buf, gint len)
2175 {
2176         struct tm *lt;
2177         time_t t;
2178         gchar *addr;
2179
2180         t = time(NULL);
2181         lt = localtime(&t);
2182
2183         if (compose->account && compose->account->address &&
2184             *compose->account->address) {
2185                 if (strchr(compose->account->address, '@'))
2186                         addr = g_strdup(compose->account->address);
2187                 else
2188                         addr = g_strconcat(compose->account->address, "@",
2189                                            get_domain_name(), NULL);
2190         } else
2191                 addr = g_strconcat(g_get_user_name(), "@", get_domain_name(),
2192                                    NULL);
2193
2194         g_snprintf(buf, len, "%04d%02d%02d%02d%02d%02d.%08x.%s",
2195                    lt->tm_year + 1900, lt->tm_mon + 1,
2196                    lt->tm_mday, lt->tm_hour,
2197                    lt->tm_min, lt->tm_sec,
2198                    (guint)random(), addr);
2199
2200         debug_print(_("generated Message-ID: %s\n"), buf);
2201
2202         g_free(addr);
2203 }
2204
2205 static void compose_add_entry_field(GtkWidget *table, GtkWidget **hbox,
2206                                     GtkWidget **entry, gint *count,
2207                                     const gchar *label_str,
2208                                     gboolean is_addr_entry)
2209 {
2210         GtkWidget *label;
2211
2212         if (GTK_TABLE(table)->nrows < (*count) + 1)
2213                 gtk_table_resize(GTK_TABLE(table), (*count) + 1, 2);
2214
2215         *hbox = gtk_hbox_new(FALSE, 0);
2216         label = gtk_label_new
2217                 (prefs_common.trans_hdr ? gettext(label_str) : label_str);
2218         gtk_box_pack_end(GTK_BOX(*hbox), label, FALSE, FALSE, 0);
2219         gtk_table_attach(GTK_TABLE(table), *hbox, 0, 1, *count, (*count) + 1,
2220                          GTK_FILL, 0, 2, 0);
2221         *entry = gtk_entry_new();
2222         gtk_table_attach_defaults
2223                 (GTK_TABLE(table), *entry, 1, 2, *count, (*count) + 1);
2224         if (GTK_TABLE(table)->nrows > (*count) + 1)
2225                 gtk_table_set_row_spacing(GTK_TABLE(table), *count, 4);
2226
2227         if (is_addr_entry)
2228                 address_completion_register_entry(GTK_ENTRY(*entry));
2229
2230         (*count)++;
2231 }
2232
2233 static Compose *compose_create(PrefsAccount *account)
2234 {
2235         Compose   *compose;
2236         GtkWidget *window;
2237         GtkWidget *vbox;
2238         GtkWidget *menubar;
2239         GtkWidget *handlebox;
2240
2241         GtkWidget *vbox2;
2242
2243         GtkWidget *table_vbox;
2244         GtkWidget *label;
2245         GtkWidget *from_optmenu_hbox;
2246         GtkWidget *to_entry;
2247         GtkWidget *to_hbox;
2248         GtkWidget *newsgroups_entry;
2249         GtkWidget *newsgroups_hbox;
2250         GtkWidget *subject_entry;
2251         GtkWidget *cc_entry;
2252         GtkWidget *cc_hbox;
2253         GtkWidget *bcc_entry;
2254         GtkWidget *bcc_hbox;
2255         GtkWidget *reply_entry;
2256         GtkWidget *reply_hbox;
2257         GtkWidget *followup_entry;
2258         GtkWidget *followup_hbox;
2259
2260         GtkWidget *paned;
2261
2262         GtkWidget *attach_scrwin;
2263         GtkWidget *attach_clist;
2264
2265         GtkWidget *edit_vbox;
2266         GtkWidget *ruler_hbox;
2267         GtkWidget *ruler;
2268         GtkWidget *scrolledwin;
2269         GtkWidget *text;
2270
2271         GtkWidget *table;
2272         GtkWidget *hbox;
2273
2274         gchar *titles[] = {_("MIME type"), _("Size"), _("Name")};
2275         guint n_menu_entries;
2276         GtkStyle  *style, *new_style;
2277         GdkColormap *cmap;
2278         GdkColor color[1];
2279         gboolean success[1];
2280         GdkFont   *font;
2281         GtkWidget *popupmenu;
2282         GtkWidget *menuitem;
2283         GtkItemFactory *popupfactory;
2284         GtkItemFactory *ifactory;
2285         gint n_entries;
2286         gint count = 0;
2287         gint i;
2288
2289         g_return_val_if_fail(account != NULL, NULL);
2290
2291         debug_print(_("Creating compose window...\n"));
2292         compose = g_new0(Compose, 1);
2293
2294         compose->account = account;
2295         compose->orig_account = account;
2296
2297         window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
2298         gtk_window_set_policy(GTK_WINDOW(window), TRUE, TRUE, FALSE);
2299         gtk_widget_set_usize(window, -1, prefs_common.compose_height);
2300         gtk_signal_connect(GTK_OBJECT(window), "delete_event",
2301                            GTK_SIGNAL_FUNC(compose_delete_cb), compose);
2302         gtk_signal_connect(GTK_OBJECT(window), "destroy",
2303                            GTK_SIGNAL_FUNC(compose_destroy_cb), compose);
2304         gtk_signal_connect(GTK_OBJECT(window), "focus_in_event",
2305                            GTK_SIGNAL_FUNC(manage_window_focus_in), NULL);
2306         gtk_signal_connect(GTK_OBJECT(window), "focus_out_event",
2307                            GTK_SIGNAL_FUNC(manage_window_focus_out), NULL);
2308         gtk_widget_realize(window);
2309
2310         vbox = gtk_vbox_new(FALSE, 0);
2311         gtk_container_add(GTK_CONTAINER(window), vbox);
2312
2313         n_menu_entries = sizeof(compose_entries) / sizeof(compose_entries[0]);
2314         menubar = menubar_create(window, compose_entries,
2315                                  n_menu_entries, "<Compose>", compose);
2316         gtk_box_pack_start(GTK_BOX(vbox), menubar, FALSE, TRUE, 0);
2317
2318         handlebox = gtk_handle_box_new();
2319         gtk_box_pack_start(GTK_BOX(vbox), handlebox, FALSE, FALSE, 0);
2320
2321         compose_toolbar_create(compose, handlebox);
2322
2323         vbox2 = gtk_vbox_new(FALSE, 2);
2324         gtk_box_pack_start(GTK_BOX(vbox), vbox2, TRUE, TRUE, 0);
2325         gtk_container_set_border_width(GTK_CONTAINER(vbox2), BORDER_WIDTH);
2326
2327         table_vbox = gtk_vbox_new(FALSE, 0);
2328         gtk_box_pack_start(GTK_BOX(vbox2), table_vbox, FALSE, TRUE, 0);
2329         gtk_container_set_border_width(GTK_CONTAINER(table_vbox),
2330                                        BORDER_WIDTH * 2);
2331
2332         table = gtk_table_new(8, 2, FALSE);
2333         gtk_box_pack_start(GTK_BOX(table_vbox), table, FALSE, TRUE, 0);
2334
2335         /* option menu for selecting accounts */
2336         hbox = gtk_hbox_new(FALSE, 0);
2337         label = gtk_label_new(prefs_common.trans_hdr ? _("From:") : "From:");
2338         gtk_box_pack_end(GTK_BOX(hbox), label, FALSE, FALSE, 0);
2339         gtk_table_attach(GTK_TABLE(table), hbox, 0, 1, count, count + 1,
2340                          GTK_FILL, 0, 2, 0);
2341         from_optmenu_hbox = compose_account_option_menu_create(compose);
2342         gtk_table_attach_defaults(GTK_TABLE(table), from_optmenu_hbox,
2343                                   1, 2, count, count + 1);
2344         gtk_table_set_row_spacing(GTK_TABLE(table), 0, 4);
2345         count++;
2346
2347         /* header labels and entries */
2348         compose_add_entry_field(table, &to_hbox, &to_entry, &count,
2349                                 "To:", TRUE); 
2350         compose_add_entry_field(table, &newsgroups_hbox, &newsgroups_entry,
2351                                 &count, "Newsgroups:", FALSE);
2352         compose_add_entry_field(table, &hbox, &subject_entry, &count,
2353                                 "Subject:", FALSE);
2354         compose_add_entry_field(table, &cc_hbox, &cc_entry, &count,
2355                                 "Cc:", TRUE);
2356         compose_add_entry_field(table, &bcc_hbox, &bcc_entry, &count,
2357                                 "Bcc:", TRUE);
2358         compose_add_entry_field(table, &reply_hbox, &reply_entry, &count,
2359                                 "Reply-To:", TRUE);
2360         compose_add_entry_field(table, &followup_hbox, &followup_entry, &count,
2361                                 "Followup-To:", FALSE);
2362
2363         gtk_table_set_col_spacings(GTK_TABLE(table), 4);
2364
2365         gtk_signal_connect(GTK_OBJECT(to_entry), "activate",
2366                            GTK_SIGNAL_FUNC(to_activated), compose);
2367         gtk_signal_connect(GTK_OBJECT(newsgroups_entry), "activate",
2368                            GTK_SIGNAL_FUNC(newsgroups_activated), compose);
2369         gtk_signal_connect(GTK_OBJECT(subject_entry), "activate",
2370                            GTK_SIGNAL_FUNC(subject_activated), compose);
2371         gtk_signal_connect(GTK_OBJECT(cc_entry), "activate",
2372                            GTK_SIGNAL_FUNC(cc_activated), compose);
2373         gtk_signal_connect(GTK_OBJECT(bcc_entry), "activate",
2374                            GTK_SIGNAL_FUNC(bcc_activated), compose);
2375         gtk_signal_connect(GTK_OBJECT(reply_entry), "activate",
2376                            GTK_SIGNAL_FUNC(replyto_activated), compose);
2377         gtk_signal_connect(GTK_OBJECT(followup_entry), "activate",
2378                            GTK_SIGNAL_FUNC(followupto_activated), compose);
2379
2380         gtk_signal_connect(GTK_OBJECT(subject_entry), "grab_focus",
2381                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
2382         gtk_signal_connect(GTK_OBJECT(to_entry), "grab_focus",
2383                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
2384         gtk_signal_connect(GTK_OBJECT(newsgroups_entry), "grab_focus",
2385                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
2386         gtk_signal_connect(GTK_OBJECT(cc_entry), "grab_focus",
2387                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
2388         gtk_signal_connect(GTK_OBJECT(bcc_entry), "grab_focus",
2389                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
2390         gtk_signal_connect(GTK_OBJECT(reply_entry), "grab_focus",
2391                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
2392         gtk_signal_connect(GTK_OBJECT(followup_entry), "grab_focus",
2393                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
2394
2395         /* attachment list */
2396         attach_scrwin = gtk_scrolled_window_new(NULL, NULL);
2397         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(attach_scrwin),
2398                                        GTK_POLICY_AUTOMATIC,
2399                                        GTK_POLICY_ALWAYS);
2400         gtk_widget_set_usize(attach_scrwin, -1, 80);
2401
2402         attach_clist = gtk_clist_new_with_titles(N_ATTACH_COLS, titles);
2403         gtk_clist_set_column_justification(GTK_CLIST(attach_clist), COL_SIZE,
2404                                            GTK_JUSTIFY_RIGHT);
2405         gtk_clist_set_column_width(GTK_CLIST(attach_clist), COL_MIMETYPE, 240);
2406         gtk_clist_set_column_width(GTK_CLIST(attach_clist), COL_SIZE, 64);
2407         gtk_clist_set_selection_mode(GTK_CLIST(attach_clist),
2408                                      GTK_SELECTION_EXTENDED);
2409         for (i = 0; i < N_ATTACH_COLS; i++)
2410                 GTK_WIDGET_UNSET_FLAGS
2411                         (GTK_CLIST(attach_clist)->column[i].button,
2412                          GTK_CAN_FOCUS);
2413         gtk_container_add(GTK_CONTAINER(attach_scrwin), attach_clist);
2414
2415         gtk_signal_connect(GTK_OBJECT(attach_clist), "select_row",
2416                            GTK_SIGNAL_FUNC(attach_selected), compose);
2417         gtk_signal_connect(GTK_OBJECT(attach_clist), "button_press_event",
2418                            GTK_SIGNAL_FUNC(attach_button_pressed), compose);
2419         gtk_signal_connect(GTK_OBJECT(attach_clist), "key_press_event",
2420                            GTK_SIGNAL_FUNC(attach_key_pressed), compose);
2421
2422         /* drag and drop */
2423         gtk_drag_dest_set(attach_clist,
2424                           GTK_DEST_DEFAULT_ALL, compose_mime_types, 1,
2425                           GDK_ACTION_COPY);
2426         gtk_signal_connect(GTK_OBJECT(attach_clist), "drag_data_received",
2427                            GTK_SIGNAL_FUNC(compose_attach_drag_received_cb),
2428                            compose);
2429
2430         /* pane between attach clist and text */
2431         paned = gtk_vpaned_new();
2432         gtk_paned_add1(GTK_PANED(paned), attach_scrwin);
2433         gtk_widget_ref(paned);
2434         gtk_widget_show_all(paned);
2435
2436         edit_vbox = gtk_vbox_new(FALSE, 0);
2437         gtk_box_pack_start(GTK_BOX(vbox2), edit_vbox, TRUE, TRUE, 0);
2438
2439         /* ruler */
2440         ruler_hbox = gtk_hbox_new(FALSE, 0);
2441         gtk_box_pack_start(GTK_BOX(edit_vbox), ruler_hbox, FALSE, FALSE, 0);
2442
2443         ruler = gtk_shruler_new();
2444         gtk_ruler_set_range(GTK_RULER(ruler), 0.0, 100.0, 1.0, 100.0);
2445         gtk_box_pack_start(GTK_BOX(ruler_hbox), ruler, TRUE, TRUE,
2446                            BORDER_WIDTH + 1);
2447         gtk_widget_set_usize(ruler_hbox, 1, -1);
2448
2449         /* text widget */
2450         scrolledwin = gtk_scrolled_window_new(NULL, NULL);
2451         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin),
2452                                        GTK_POLICY_NEVER, GTK_POLICY_ALWAYS);
2453         gtk_box_pack_start(GTK_BOX(edit_vbox), scrolledwin, TRUE, TRUE, 0);
2454         gtk_widget_set_usize(scrolledwin, prefs_common.compose_width, -1);
2455
2456         text = gtk_stext_new(gtk_scrolled_window_get_hadjustment
2457                             (GTK_SCROLLED_WINDOW(scrolledwin)),
2458                             gtk_scrolled_window_get_vadjustment
2459                             (GTK_SCROLLED_WINDOW(scrolledwin)));
2460         gtk_stext_set_editable(GTK_STEXT(text), TRUE);
2461         gtk_stext_set_word_wrap(GTK_STEXT(text), TRUE);
2462         gtk_stext_set_wrap_rmargin(GTK_STEXT(text), prefs_common.linewrap_len);
2463
2464         gtk_container_add(GTK_CONTAINER(scrolledwin), text);
2465
2466         gtk_signal_connect(GTK_OBJECT(text), "changed",
2467                            GTK_SIGNAL_FUNC(compose_changed_cb), compose);
2468         gtk_signal_connect(GTK_OBJECT(text), "grab_focus",
2469                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
2470         gtk_signal_connect_after(GTK_OBJECT(text), "button_press_event",
2471                                  GTK_SIGNAL_FUNC(compose_button_press_cb),
2472                                  compose);
2473 #if 0
2474         gtk_signal_connect_after(GTK_OBJECT(text), "key_press_event",
2475                                  GTK_SIGNAL_FUNC(compose_key_press_cb),
2476                                  compose);
2477 #endif
2478         gtk_signal_connect_after(GTK_OBJECT(text), "size_allocate",
2479                                  GTK_SIGNAL_FUNC(compose_edit_size_alloc),
2480                                  ruler);
2481
2482         /* drag and drop */
2483         gtk_drag_dest_set(text, GTK_DEST_DEFAULT_ALL, compose_mime_types, 1,
2484                           GDK_ACTION_COPY);
2485         gtk_signal_connect(GTK_OBJECT(text), "drag_data_received",
2486                            GTK_SIGNAL_FUNC(compose_insert_drag_received_cb),
2487                            compose);
2488
2489         gtk_widget_show_all(vbox);
2490
2491         style = gtk_widget_get_style(text);
2492
2493         /* workaround for the slow down of GtkSText when using Pixmap theme */
2494         if (style->engine) {
2495                 GtkThemeEngine *engine;
2496
2497                 engine = style->engine;
2498                 style->engine = NULL;
2499                 new_style = gtk_style_copy(style);
2500                 style->engine = engine;
2501         } else
2502                 new_style = gtk_style_copy(style);
2503
2504         if (prefs_common.textfont) {
2505                 CharSet charset;
2506
2507                 charset = conv_get_current_charset();
2508                 if (MB_CUR_MAX == 1) {
2509                         gchar *fontstr, *p;
2510
2511                         Xstrdup_a(fontstr, prefs_common.textfont, );
2512                         if (fontstr && (p = strchr(fontstr, ',')) != NULL)
2513                                 *p = '\0';
2514                         font = gdk_font_load(fontstr);
2515                 } else
2516                         font = gdk_fontset_load(prefs_common.textfont);
2517                 if (font) {
2518                         gdk_font_unref(new_style->font);
2519                         new_style->font = font;
2520                 }
2521         }
2522
2523         gtk_widget_set_style(text, new_style);
2524
2525         color[0] = quote_color;
2526         cmap = gdk_window_get_colormap(window->window);
2527         gdk_colormap_alloc_colors(cmap, color, 1, FALSE, TRUE, success);
2528         if (success[0] == FALSE) {
2529                 g_warning("Compose: color allocation failed.\n");
2530                 style = gtk_widget_get_style(text);
2531                 quote_color = style->black;
2532         }
2533
2534         n_entries = sizeof(compose_popup_entries) /
2535                 sizeof(compose_popup_entries[0]);
2536         popupmenu = menu_create_items(compose_popup_entries, n_entries,
2537                                       "<Compose>", &popupfactory,
2538                                       compose);
2539
2540         ifactory = gtk_item_factory_from_widget(menubar);
2541         menu_set_sensitive(ifactory, "/Edit/Undo", FALSE);
2542         menu_set_sensitive(ifactory, "/Edit/Redo", FALSE);
2543
2544         gtk_widget_hide(bcc_hbox);
2545         gtk_widget_hide(bcc_entry);
2546         gtk_widget_hide(reply_hbox);
2547         gtk_widget_hide(reply_entry);
2548         gtk_widget_hide(followup_hbox);
2549         gtk_widget_hide(followup_entry);
2550         gtk_widget_hide(ruler_hbox);
2551         gtk_table_set_row_spacing(GTK_TABLE(table), 4, 0);
2552         gtk_table_set_row_spacing(GTK_TABLE(table), 5, 0);
2553         gtk_table_set_row_spacing(GTK_TABLE(table), 6, 0);
2554
2555         if (account->protocol == A_NNTP) {
2556                 gtk_widget_hide(to_hbox);
2557                 gtk_widget_hide(to_entry);
2558                 gtk_widget_hide(cc_hbox);
2559                 gtk_widget_hide(cc_entry);
2560                 gtk_table_set_row_spacing(GTK_TABLE(table), 1, 0);
2561                 gtk_table_set_row_spacing(GTK_TABLE(table), 3, 0);
2562         } else {
2563                 gtk_widget_hide(newsgroups_hbox);
2564                 gtk_widget_hide(newsgroups_entry);
2565                 gtk_table_set_row_spacing(GTK_TABLE(table), 2, 0);
2566                 menu_set_sensitive(ifactory, "/Message/Followup to", FALSE);
2567         }
2568
2569         switch (prefs_common.toolbar_style) {
2570         case TOOLBAR_NONE:
2571                 gtk_widget_hide(handlebox);
2572                 break;
2573         case TOOLBAR_ICON:
2574                 gtk_toolbar_set_style(GTK_TOOLBAR(compose->toolbar),
2575                                       GTK_TOOLBAR_ICONS);
2576                 break;
2577         case TOOLBAR_TEXT:
2578                 gtk_toolbar_set_style(GTK_TOOLBAR(compose->toolbar),
2579                                       GTK_TOOLBAR_TEXT);
2580                 break;
2581         case TOOLBAR_BOTH:
2582                 gtk_toolbar_set_style(GTK_TOOLBAR(compose->toolbar),
2583                                       GTK_TOOLBAR_BOTH);
2584                 break;
2585         }
2586
2587         gtk_widget_show(window);
2588
2589         address_completion_start(window);
2590
2591         compose->window        = window;
2592         compose->vbox          = vbox;
2593         compose->menubar       = menubar;
2594         compose->handlebox     = handlebox;
2595
2596         compose->vbox2         = vbox2;
2597
2598         compose->table_vbox       = table_vbox;
2599         compose->table            = table;
2600         compose->to_hbox          = to_hbox;
2601         compose->to_entry         = to_entry;
2602         compose->newsgroups_hbox  = newsgroups_hbox;
2603         compose->newsgroups_entry = newsgroups_entry;
2604         compose->subject_entry    = subject_entry;
2605         compose->cc_hbox          = cc_hbox;
2606         compose->cc_entry         = cc_entry;
2607         compose->bcc_hbox         = bcc_hbox;
2608         compose->bcc_entry        = bcc_entry;
2609         compose->reply_hbox       = reply_hbox;
2610         compose->reply_entry      = reply_entry;
2611         compose->followup_hbox    = followup_hbox;
2612         compose->followup_entry   = followup_entry;
2613
2614         compose->paned = paned;
2615
2616         compose->attach_scrwin = attach_scrwin;
2617         compose->attach_clist  = attach_clist;
2618
2619         compose->edit_vbox     = edit_vbox;
2620         compose->ruler_hbox    = ruler_hbox;
2621         compose->ruler         = ruler;
2622         compose->scrolledwin   = scrolledwin;
2623         compose->text          = text;
2624
2625         compose->focused_editable = NULL;
2626
2627         compose->popupmenu    = popupmenu;
2628         compose->popupfactory = popupfactory;
2629
2630         compose->mode = COMPOSE_NEW;
2631
2632         compose->replyto     = NULL;
2633         compose->cc          = NULL;
2634         compose->bcc         = NULL;
2635         compose->followup_to = NULL;
2636         compose->inreplyto   = NULL;
2637         compose->references  = NULL;
2638         compose->msgid       = NULL;
2639         compose->boundary    = NULL;
2640
2641         compose->use_to         = FALSE;
2642         compose->use_cc         = FALSE;
2643         compose->use_bcc        = FALSE;
2644         compose->use_replyto    = FALSE;
2645         compose->use_followupto = FALSE;
2646         compose->use_attach     = FALSE;
2647
2648 #if USE_GPGME
2649         compose->use_signing    = FALSE;
2650         compose->use_encryption = FALSE;
2651 #endif /* USE_GPGME */
2652
2653         compose->modified = FALSE;
2654
2655         compose->return_receipt = FALSE;
2656
2657         compose->to_list        = NULL;
2658         compose->newsgroup_list = NULL;
2659
2660         compose->exteditor_file    = NULL;
2661         compose->exteditor_pid     = -1;
2662         compose->exteditor_readdes = -1;
2663         compose->exteditor_tag     = -1;
2664
2665         compose_set_title(compose);
2666
2667         if (account->protocol != A_NNTP) {
2668                 menuitem = gtk_item_factory_get_item(ifactory, "/Message/To");
2669                 gtk_check_menu_item_set_active
2670                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
2671                 gtk_widget_set_sensitive(menuitem, FALSE);
2672                 menuitem = gtk_item_factory_get_item(ifactory, "/Message/Cc");
2673                 gtk_check_menu_item_set_active
2674                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
2675                 gtk_widget_set_sensitive(menuitem, FALSE);
2676         }
2677         if (account->set_autocc && account->auto_cc) {
2678                 gtk_entry_set_text(GTK_ENTRY(cc_entry), account->auto_cc);
2679                 menuitem = gtk_item_factory_get_item(ifactory, "/Message/Cc");
2680                 gtk_check_menu_item_set_active
2681                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
2682         }
2683         if (account->set_autobcc && account->auto_bcc) {
2684                 gtk_entry_set_text(GTK_ENTRY(bcc_entry), account->auto_bcc);
2685                 menuitem = gtk_item_factory_get_item(ifactory, "/Message/Bcc");
2686                 gtk_check_menu_item_set_active
2687                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
2688         }
2689         if (account->set_autoreplyto && account->auto_replyto) {
2690                 gtk_entry_set_text(GTK_ENTRY(reply_entry),
2691                                    account->auto_replyto);
2692                 menuitem = gtk_item_factory_get_item(ifactory,
2693                                                      "/Message/Reply to");
2694                 gtk_check_menu_item_set_active
2695                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
2696         }
2697
2698         menuitem = gtk_item_factory_get_item(ifactory, "/Tool/Show ruler");
2699         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
2700                                        prefs_common.show_ruler);
2701
2702 #if USE_GPGME
2703         menuitem = gtk_item_factory_get_item(ifactory, "/Message/Sign");
2704         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
2705                                        prefs_common.default_sign);
2706         menuitem = gtk_item_factory_get_item(ifactory, "/Message/Encrypt");
2707         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
2708                                        prefs_common.default_encrypt);
2709 #endif /* USE_GPGME */
2710
2711         addressbook_set_target_compose(compose);
2712
2713         compose_list = g_list_append(compose_list, compose);
2714
2715         return compose;
2716 }
2717
2718 #include "pixmaps/stock_mail_send.xpm"
2719 #include "pixmaps/stock_mail.xpm"
2720 #include "pixmaps/stock_paste.xpm"
2721 #include "pixmaps/stock_mail_attach.xpm"
2722 #include "pixmaps/stock_mail_compose.xpm"
2723 #include "pixmaps/linewrap.xpm"
2724 //#include "pixmaps/tb_mail_queue_send.xpm"
2725 #include "pixmaps/tb_address_book.xpm"
2726
2727 #define CREATE_TOOLBAR_ICON(xpm_d) \
2728 { \
2729         icon = gdk_pixmap_create_from_xpm_d(container->window, &mask, \
2730                                             &container->style->white, \
2731                                             xpm_d); \
2732         icon_wid = gtk_pixmap_new(icon, mask); \
2733 }
2734
2735 static void compose_toolbar_create(Compose *compose, GtkWidget *container)
2736 {
2737         GtkWidget *toolbar;
2738         GdkPixmap *icon;
2739         GdkBitmap *mask;
2740         GtkWidget *icon_wid;
2741         GtkWidget *send_btn;
2742         GtkWidget *sendl_btn;
2743         GtkWidget *draft_btn;
2744         GtkWidget *insert_btn;
2745         GtkWidget *attach_btn;
2746         GtkWidget *sig_btn;
2747         GtkWidget *exteditor_btn;
2748         GtkWidget *linewrap_btn;
2749         GtkWidget *addrbook_btn;
2750
2751         toolbar = gtk_toolbar_new(GTK_ORIENTATION_HORIZONTAL,
2752                                   GTK_TOOLBAR_BOTH);
2753         gtk_container_add(GTK_CONTAINER(container), toolbar);
2754         gtk_container_set_border_width(GTK_CONTAINER(container), 2);
2755         gtk_toolbar_set_button_relief(GTK_TOOLBAR(toolbar), GTK_RELIEF_NONE);
2756         gtk_toolbar_set_space_style(GTK_TOOLBAR(toolbar),
2757                                     GTK_TOOLBAR_SPACE_LINE);
2758
2759         CREATE_TOOLBAR_ICON(stock_mail_send_xpm);
2760         send_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
2761                                            _("Send"),
2762                                            _("Send message"),
2763                                            "Send",
2764                                            icon_wid, toolbar_send_cb, compose);
2765
2766         CREATE_TOOLBAR_ICON(stock_mail_send_xpm);
2767         //CREATE_TOOLBAR_ICON(tb_mail_queue_send_xpm);
2768         sendl_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
2769                                            _("Send later"),
2770                                            _("Put into queue folder and send later"),
2771                                            "Send later",
2772                                            icon_wid, toolbar_send_later_cb,
2773                                            compose);
2774
2775         CREATE_TOOLBAR_ICON(stock_mail_xpm);
2776         draft_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
2777                                             _("Draft"),
2778                                             _("Save to draft folder"),
2779                                             "Draft",
2780                                             icon_wid, toolbar_draft_cb,
2781                                             compose);
2782
2783         gtk_toolbar_append_space(GTK_TOOLBAR(toolbar));
2784
2785         CREATE_TOOLBAR_ICON(stock_paste_xpm);
2786         insert_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
2787                                              _("Insert"),
2788                                              _("Insert file"),
2789                                              "Insert",
2790                                              icon_wid, toolbar_insert_cb,
2791                                              compose);
2792
2793         CREATE_TOOLBAR_ICON(stock_mail_attach_xpm);
2794         attach_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
2795                                              _("Attach"),
2796                                              _("Attach file"),
2797                                              "Attach",
2798                                              icon_wid, toolbar_attach_cb,
2799                                              compose);
2800
2801         gtk_toolbar_append_space(GTK_TOOLBAR(toolbar));
2802
2803         CREATE_TOOLBAR_ICON(stock_mail_xpm);
2804         sig_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
2805                                           _("Signature"),
2806                                           _("Insert signature"),
2807                                           "Signature",
2808                                           icon_wid, toolbar_sig_cb, compose);
2809
2810         gtk_toolbar_append_space(GTK_TOOLBAR(toolbar));
2811
2812         CREATE_TOOLBAR_ICON(stock_mail_compose_xpm);
2813         exteditor_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
2814                                                 _("Editor"),
2815                                                 _("Edit with external editor"),
2816                                                 "Editor",
2817                                                 icon_wid,
2818                                                 toolbar_ext_editor_cb,
2819                                                 compose);
2820
2821         CREATE_TOOLBAR_ICON(linewrap_xpm);
2822         linewrap_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
2823                                                _("Linewrap"),
2824                                                _("Wrap long lines"),
2825                                                "Linewrap",
2826                                                icon_wid,
2827                                                toolbar_linewrap_cb,
2828                                                compose);
2829
2830         gtk_toolbar_append_space(GTK_TOOLBAR(toolbar));
2831
2832         CREATE_TOOLBAR_ICON(tb_address_book_xpm);
2833         addrbook_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
2834                                                _("Address"),
2835                                                _("Address book"),
2836                                                "Address",
2837                                                icon_wid, toolbar_address_cb,
2838                                                compose);
2839
2840         compose->toolbar       = toolbar;
2841         compose->send_btn      = send_btn;
2842         compose->sendl_btn     = sendl_btn;
2843         compose->draft_btn     = draft_btn;
2844         compose->insert_btn    = insert_btn;
2845         compose->attach_btn    = attach_btn;
2846         compose->sig_btn       = sig_btn;
2847         compose->exteditor_btn = exteditor_btn;
2848         compose->linewrap_btn  = linewrap_btn;
2849         compose->addrbook_btn  = addrbook_btn;
2850
2851         gtk_widget_show_all(toolbar);
2852 }
2853
2854 static GtkWidget *compose_account_option_menu_create(Compose *compose)
2855 {
2856         GList *accounts;
2857         GtkWidget *hbox;
2858         GtkWidget *optmenu;
2859         GtkWidget *menu;
2860         gint num = 0, def_menu = 0;
2861
2862         accounts = account_get_list();
2863         g_return_val_if_fail(accounts != NULL, NULL);
2864
2865         hbox = gtk_hbox_new(FALSE, 0);
2866         optmenu = gtk_option_menu_new();
2867         gtk_box_pack_start(GTK_BOX(hbox), optmenu, FALSE, FALSE, 0);
2868         menu = gtk_menu_new();
2869
2870         for (; accounts != NULL; accounts = accounts->next, num++) {
2871                 PrefsAccount *ac = (PrefsAccount *)accounts->data;
2872                 GtkWidget *menuitem;
2873                 gchar *name;
2874
2875                 if (ac == compose->account) def_menu = num;
2876
2877                 name = g_strdup_printf("%s <%s> (%s)",
2878                                        ac->name, ac->address, ac->account_name);
2879                 MENUITEM_ADD(menu, menuitem, name, ac);
2880                 g_free(name);
2881                 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2882                                    GTK_SIGNAL_FUNC(account_activated),
2883                                    compose);
2884         }
2885
2886         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), menu);
2887         gtk_option_menu_set_history(GTK_OPTION_MENU(optmenu), def_menu);
2888
2889         return hbox;
2890 }
2891
2892 static void compose_destroy(Compose *compose)
2893 {
2894         gint row;
2895         GtkCList *clist = GTK_CLIST(compose->attach_clist);
2896         AttachInfo *ainfo;
2897
2898         /* NOTE: address_completion_end() does nothing with the window
2899          * however this may change. */
2900         address_completion_end(compose->window);
2901
2902         slist_free_strings(compose->to_list);
2903         g_slist_free(compose->to_list);
2904         slist_free_strings(compose->newsgroup_list);
2905         g_slist_free(compose->newsgroup_list);
2906
2907         procmsg_msginfo_free(compose->targetinfo);
2908
2909         g_free(compose->replyto);
2910         g_free(compose->cc);
2911         g_free(compose->bcc);
2912         g_free(compose->newsgroups);
2913         g_free(compose->followup_to);
2914
2915         g_free(compose->inreplyto);
2916         g_free(compose->references);
2917         g_free(compose->msgid);
2918         g_free(compose->boundary);
2919
2920         g_free(compose->exteditor_file);
2921
2922         for (row = 0; (ainfo = gtk_clist_get_row_data(clist, row)) != NULL;
2923              row++)
2924                 compose_attach_info_free(ainfo);
2925
2926         if (addressbook_get_target_compose() == compose)
2927                 addressbook_set_target_compose(NULL);
2928
2929         prefs_common.compose_width = compose->scrolledwin->allocation.width;
2930         prefs_common.compose_height = compose->window->allocation.height;
2931
2932         gtk_widget_destroy(compose->paned);
2933
2934         g_free(compose);
2935
2936         compose_list = g_list_remove(compose_list, compose);
2937 }
2938
2939 static void compose_attach_info_free(AttachInfo *ainfo)
2940 {
2941         g_free(ainfo->file);
2942         g_free(ainfo->content_type);
2943         g_free(ainfo->name);
2944         g_free(ainfo);
2945 }
2946
2947 static void compose_attach_remove_selected(Compose *compose)
2948 {
2949         GtkCList *clist = GTK_CLIST(compose->attach_clist);
2950         AttachInfo *ainfo;
2951         gint row;
2952
2953         while (clist->selection != NULL) {
2954                 row = GPOINTER_TO_INT(clist->selection->data);
2955                 ainfo = gtk_clist_get_row_data(clist, row);
2956                 compose_attach_info_free(ainfo);
2957                 gtk_clist_remove(clist, row);
2958         }
2959 }
2960
2961 static struct _AttachProperty
2962 {
2963         GtkWidget *window;
2964         GtkWidget *mimetype_entry;
2965         GtkWidget *encoding_optmenu;
2966         GtkWidget *path_entry;
2967         GtkWidget *filename_entry;
2968         GtkWidget *ok_btn;
2969         GtkWidget *cancel_btn;
2970 } attach_prop;
2971
2972 static void compose_attach_property(Compose *compose)
2973 {
2974         GtkCList *clist = GTK_CLIST(compose->attach_clist);
2975         AttachInfo *ainfo;
2976         gint row;
2977         gboolean cancelled;
2978         GtkOptionMenu *optmenu;
2979
2980         if (!clist->selection) return;
2981         row = GPOINTER_TO_INT(clist->selection->data);
2982
2983         ainfo = gtk_clist_get_row_data(clist, row);
2984         if (!ainfo) return;
2985
2986         if (!attach_prop.window)
2987                 compose_attach_property_create(&cancelled);
2988         gtk_widget_grab_focus(attach_prop.ok_btn);
2989         gtk_widget_show(attach_prop.window);
2990         manage_window_set_transient(GTK_WINDOW(attach_prop.window));
2991
2992         optmenu = GTK_OPTION_MENU(attach_prop.encoding_optmenu);
2993         if (ainfo->encoding == ENC_UNKNOWN)
2994                 gtk_option_menu_set_history(optmenu, ENC_BASE64);
2995         else
2996                 gtk_option_menu_set_history(optmenu, ainfo->encoding);
2997
2998         gtk_entry_set_text(GTK_ENTRY(attach_prop.mimetype_entry),
2999                            ainfo->content_type ? ainfo->content_type : "");
3000         gtk_entry_set_text(GTK_ENTRY(attach_prop.path_entry),
3001                            ainfo->file ? ainfo->file : "");
3002         gtk_entry_set_text(GTK_ENTRY(attach_prop.filename_entry),
3003                            ainfo->name ? ainfo->name : "");
3004
3005         for (;;) {
3006                 gchar *text;
3007                 gchar *cnttype = NULL;
3008                 gchar *file = NULL;
3009                 off_t size = 0;
3010                 GtkWidget *menu;
3011                 GtkWidget *menuitem;
3012
3013                 gtk_main();
3014
3015                 if (cancelled == TRUE) {
3016                         gtk_widget_hide(attach_prop.window);
3017                         break;
3018                 }
3019
3020                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.mimetype_entry));
3021                 if (*text != '\0') {
3022                         gchar *p;
3023
3024                         text = g_strstrip(g_strdup(text));
3025                         if ((p = strchr(text, '/')) && !strchr(p + 1, '/')) {
3026                                 cnttype = g_strdup(text);
3027                                 g_free(text);
3028                         } else {
3029                                 alertpanel_error(_("Invalid MIME type."));
3030                                 g_free(text);
3031                                 continue;
3032                         }
3033                 }
3034
3035                 menu = gtk_option_menu_get_menu(optmenu);
3036                 menuitem = gtk_menu_get_active(GTK_MENU(menu));
3037                 ainfo->encoding = GPOINTER_TO_INT
3038                         (gtk_object_get_user_data(GTK_OBJECT(menuitem)));
3039
3040                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.path_entry));
3041                 if (*text != '\0') {
3042                         if (is_file_exist(text) &&
3043                             (size = get_file_size(text)) > 0)
3044                                 file = g_strdup(text);
3045                         else {
3046                                 alertpanel_error
3047                                         (_("File doesn't exist or is empty."));
3048                                 g_free(cnttype);
3049                                 continue;
3050                         }
3051                 }
3052
3053                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.filename_entry));
3054                 if (*text != '\0') {
3055                         g_free(ainfo->name);
3056                         ainfo->name = g_strdup(text);
3057                 }
3058
3059                 if (cnttype) {
3060                         g_free(ainfo->content_type);
3061                         ainfo->content_type = cnttype;
3062                 }
3063                 if (file) {
3064                         g_free(ainfo->file);
3065                         ainfo->file = file;
3066                 }
3067                 if (size)
3068                         ainfo->size = size;
3069
3070                 gtk_clist_set_text(clist, row, COL_MIMETYPE,
3071                                    ainfo->content_type);
3072                 gtk_clist_set_text(clist, row, COL_SIZE,
3073                                    to_human_readable(ainfo->size));
3074                 gtk_clist_set_text(clist, row, COL_NAME, ainfo->name);
3075
3076                 gtk_widget_hide(attach_prop.window);
3077                 break;
3078         }
3079 }
3080
3081 #define SET_LABEL_AND_ENTRY(str, entry, top) \
3082 { \
3083         label = gtk_label_new(str); \
3084         gtk_table_attach(GTK_TABLE(table), label, 0, 1, top, (top + 1), \
3085                          GTK_FILL, 0, 0, 0); \
3086         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); \
3087  \
3088         entry = gtk_entry_new(); \
3089         gtk_table_attach(GTK_TABLE(table), entry, 1, 2, top, (top + 1), \
3090                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0); \
3091 }
3092
3093 static void compose_attach_property_create(gboolean *cancelled)
3094 {
3095         GtkWidget *window;
3096         GtkWidget *vbox;
3097         GtkWidget *table;
3098         GtkWidget *label;
3099         GtkWidget *mimetype_entry;
3100         GtkWidget *hbox;
3101         GtkWidget *optmenu;
3102         GtkWidget *optmenu_menu;
3103         GtkWidget *menuitem;
3104         GtkWidget *path_entry;
3105         GtkWidget *filename_entry;
3106         GtkWidget *hbbox;
3107         GtkWidget *ok_btn;
3108         GtkWidget *cancel_btn;
3109
3110         debug_print("Creating attach_property window...\n");
3111
3112         window = gtk_window_new(GTK_WINDOW_DIALOG);
3113         gtk_widget_set_usize(window, 480, -1);
3114         gtk_container_set_border_width(GTK_CONTAINER(window), 8);
3115         gtk_window_set_title(GTK_WINDOW(window), _("Property"));
3116         gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
3117         gtk_window_set_modal(GTK_WINDOW(window), TRUE);
3118         gtk_signal_connect(GTK_OBJECT(window), "delete_event",
3119                            GTK_SIGNAL_FUNC(attach_property_delete_event),
3120                            cancelled);
3121         gtk_signal_connect(GTK_OBJECT(window), "key_press_event",
3122                            GTK_SIGNAL_FUNC(attach_property_key_pressed),
3123                            cancelled);
3124
3125         vbox = gtk_vbox_new(FALSE, 8);
3126         gtk_container_add(GTK_CONTAINER(window), vbox);
3127
3128         table = gtk_table_new(4, 2, FALSE);
3129         gtk_box_pack_start(GTK_BOX(vbox), table, FALSE, FALSE, 0);
3130         gtk_table_set_row_spacings(GTK_TABLE(table), 8);
3131         gtk_table_set_col_spacings(GTK_TABLE(table), 8);
3132
3133         SET_LABEL_AND_ENTRY(_("MIME type"), mimetype_entry, 0);
3134
3135         label = gtk_label_new(_("Encoding"));
3136         gtk_table_attach(GTK_TABLE(table), label, 0, 1, 1, 2,
3137                          GTK_FILL, 0, 0, 0);
3138         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5);
3139
3140         hbox = gtk_hbox_new(FALSE, 0);
3141         gtk_table_attach(GTK_TABLE(table), hbox, 1, 2, 1, 2,
3142                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0);
3143
3144         optmenu = gtk_option_menu_new();
3145         gtk_box_pack_start(GTK_BOX(hbox), optmenu, FALSE, FALSE, 0);
3146
3147         optmenu_menu = gtk_menu_new();
3148         MENUITEM_ADD(optmenu_menu, menuitem, "7bit", ENC_7BIT);
3149         gtk_widget_set_sensitive(menuitem, FALSE);
3150         MENUITEM_ADD(optmenu_menu, menuitem, "8bit", ENC_8BIT);
3151         gtk_widget_set_sensitive(menuitem, FALSE);
3152         MENUITEM_ADD(optmenu_menu, menuitem, "quoted-printable", ENC_QUOTED_PRINTABLE);
3153         gtk_widget_set_sensitive(menuitem, FALSE);
3154         MENUITEM_ADD(optmenu_menu, menuitem, "base64", ENC_BASE64);
3155
3156         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
3157
3158         SET_LABEL_AND_ENTRY(_("Path"),      path_entry,     2);
3159         SET_LABEL_AND_ENTRY(_("File name"), filename_entry, 3);
3160
3161         gtkut_button_set_create(&hbbox, &ok_btn, _("OK"),
3162                                 &cancel_btn, _("Cancel"), NULL, NULL);
3163         gtk_box_pack_end(GTK_BOX(vbox), hbbox, FALSE, FALSE, 0);
3164         gtk_widget_grab_default(ok_btn);
3165
3166         gtk_signal_connect(GTK_OBJECT(ok_btn), "clicked",
3167                            GTK_SIGNAL_FUNC(attach_property_ok),
3168                            cancelled);
3169         gtk_signal_connect(GTK_OBJECT(cancel_btn), "clicked",
3170                            GTK_SIGNAL_FUNC(attach_property_cancel),
3171                            cancelled);
3172
3173         gtk_widget_show_all(vbox);
3174
3175         attach_prop.window           = window;
3176         attach_prop.mimetype_entry   = mimetype_entry;
3177         attach_prop.encoding_optmenu = optmenu;
3178         attach_prop.path_entry       = path_entry;
3179         attach_prop.filename_entry   = filename_entry;
3180         attach_prop.ok_btn           = ok_btn;
3181         attach_prop.cancel_btn       = cancel_btn;
3182 }
3183
3184 static void attach_property_ok(GtkWidget *widget, gboolean *cancelled)
3185 {
3186         *cancelled = FALSE;
3187         gtk_main_quit();
3188 }
3189
3190 static void attach_property_cancel(GtkWidget *widget, gboolean *cancelled)
3191 {
3192         *cancelled = TRUE;
3193         gtk_main_quit();
3194 }
3195
3196 static gint attach_property_delete_event(GtkWidget *widget, GdkEventAny *event,
3197                                          gboolean *cancelled)
3198 {
3199         *cancelled = TRUE;
3200         gtk_main_quit();
3201
3202         return TRUE;
3203 }
3204
3205 static void attach_property_key_pressed(GtkWidget *widget, GdkEventKey *event,
3206                                         gboolean *cancelled)
3207 {
3208         if (event && event->keyval == GDK_Escape) {
3209                 *cancelled = TRUE;
3210                 gtk_main_quit();
3211         }
3212 }
3213
3214 static void compose_exec_ext_editor(Compose *compose)
3215 {
3216         gchar tmp[64];
3217         pid_t pid;
3218         gint pipe_fds[2];
3219
3220         g_snprintf(tmp, sizeof(tmp), "%s%ctmpmsg.%08x",
3221                    g_get_tmp_dir(), G_DIR_SEPARATOR, (gint)compose);
3222
3223         if (pipe(pipe_fds) < 0) {
3224                 perror("pipe");
3225                 return;
3226         }
3227
3228         if ((pid = fork()) < 0) {
3229                 perror("fork");
3230                 return;
3231         }
3232
3233         if (pid != 0) {
3234                 /* close the write side of the pipe */
3235                 close(pipe_fds[1]);
3236
3237                 compose->exteditor_file    = g_strdup(tmp);
3238                 compose->exteditor_pid     = pid;
3239                 compose->exteditor_readdes = pipe_fds[0];
3240
3241                 compose_set_ext_editor_sensitive(compose, FALSE);
3242
3243                 compose->exteditor_tag =
3244                         gdk_input_add(pipe_fds[0], GDK_INPUT_READ,
3245                                       compose_input_cb, compose);
3246         } else {        /* process-monitoring process */
3247                 pid_t pid_ed;
3248
3249                 if (setpgid(0, 0))
3250                         perror("setpgid");
3251
3252                 /* close the read side of the pipe */
3253                 close(pipe_fds[0]);
3254
3255                 if (compose_write_body_to_file(compose, tmp) < 0) {
3256                         fd_write(pipe_fds[1], "2\n", 2);
3257                         _exit(1);
3258                 }
3259
3260                 pid_ed = compose_exec_ext_editor_real(tmp);
3261                 if (pid_ed < 0) {
3262                         fd_write(pipe_fds[1], "1\n", 2);
3263                         _exit(1);
3264                 }
3265
3266                 /* wait until editor is terminated */
3267                 waitpid(pid_ed, NULL, 0);
3268
3269                 fd_write(pipe_fds[1], "0\n", 2);
3270
3271                 close(pipe_fds[1]);
3272                 _exit(0);
3273         }
3274 }
3275
3276 static gint compose_exec_ext_editor_real(const gchar *file)
3277 {
3278         static gchar *def_cmd = "emacs %s";
3279         gchar buf[1024];
3280         gchar *p;
3281         gchar **cmdline;
3282         pid_t pid;
3283
3284         g_return_val_if_fail(file != NULL, -1);
3285
3286         if ((pid = fork()) < 0) {
3287                 perror("fork");
3288                 return -1;
3289         }
3290
3291         if (pid != 0) return pid;
3292
3293         /* grandchild process */
3294
3295         if (setpgid(0, getppid()))
3296                 perror("setpgid");
3297
3298         if (prefs_common.ext_editor_cmd &&
3299             (p = strchr(prefs_common.ext_editor_cmd, '%')) &&
3300             *(p + 1) == 's' && !strchr(p + 2, '%')) {
3301                 g_snprintf(buf, sizeof(buf), prefs_common.ext_editor_cmd, file);
3302         } else {
3303                 if (prefs_common.ext_editor_cmd)
3304                         g_warning(_("External editor command line is invalid: `%s'\n"),
3305                                   prefs_common.ext_editor_cmd);
3306                 g_snprintf(buf, sizeof(buf), def_cmd, file);
3307         }
3308
3309         cmdline = g_strsplit(buf, " ", 1024);
3310         execvp(cmdline[0], cmdline);
3311
3312         perror("execvp");
3313         g_strfreev(cmdline);
3314
3315         _exit(1);
3316 }
3317
3318 static gboolean compose_ext_editor_kill(Compose *compose)
3319 {
3320         pid_t pgid = compose->exteditor_pid * -1;
3321         gint ret;
3322
3323         ret = kill(pgid, 0);
3324
3325         if (ret == 0 || (ret == -1 && EPERM == errno)) {
3326                 AlertValue val;
3327                 gchar *msg;
3328
3329                 msg = g_strdup_printf
3330                         (_("The external editor is still working.\n"
3331                            "Force terminating the process?\n"
3332                            "process group id: %d"), -pgid);
3333                 val = alertpanel(_("Notice"), msg, _("Yes"), _("+No"), NULL);
3334                 g_free(msg);
3335
3336                 if (val == G_ALERTDEFAULT) {
3337                         gdk_input_remove(compose->exteditor_tag);
3338                         close(compose->exteditor_readdes);
3339
3340                         if (kill(pgid, SIGTERM) < 0) perror("kill");
3341                         waitpid(compose->exteditor_pid, NULL, 0);
3342
3343                         g_warning(_("Terminated process group id: %d"), -pgid);
3344                         g_warning(_("Temporary file: %s"),
3345                                   compose->exteditor_file);
3346
3347                         compose_set_ext_editor_sensitive(compose, TRUE);
3348
3349                         g_free(compose->exteditor_file);
3350                         compose->exteditor_file    = NULL;
3351                         compose->exteditor_pid     = -1;
3352                         compose->exteditor_readdes = -1;
3353                         compose->exteditor_tag     = -1;
3354                 } else
3355                         return FALSE;
3356         }
3357
3358         return TRUE;
3359 }
3360
3361 static void compose_input_cb(gpointer data, gint source,
3362                              GdkInputCondition condition)
3363 {
3364         gchar buf[3];
3365         Compose *compose = (Compose *)data;
3366         gint i = 0;
3367
3368         debug_print(_("Compose: input from monitoring process\n"));
3369
3370         gdk_input_remove(compose->exteditor_tag);
3371
3372         for (;;) {
3373                 if (read(source, &buf[i], 1) < 1) {
3374                         buf[0] = '3';
3375                         break;
3376                 }
3377                 if (buf[i] == '\n') {
3378                         buf[i] = '\0';
3379                         break;
3380                 }
3381                 i++;
3382                 if (i == sizeof(buf) - 1)
3383                         break;
3384         }
3385
3386         waitpid(compose->exteditor_pid, NULL, 0);
3387
3388         if (buf[0] == '0') {            /* success */
3389                 GtkSText *text = GTK_STEXT(compose->text);
3390
3391                 gtk_stext_freeze(text);
3392                 gtk_stext_set_point(text, 0);
3393                 gtk_stext_forward_delete(text, gtk_stext_get_length(text));
3394                 compose_insert_file(compose, compose->exteditor_file);
3395                 compose_changed_cb(NULL, compose);
3396                 gtk_stext_thaw(text);
3397
3398                 if (unlink(compose->exteditor_file) < 0)
3399                         FILE_OP_ERROR(compose->exteditor_file, "unlink");
3400         } else if (buf[0] == '1') {     /* failed */
3401                 g_warning(_("Couldn't exec external editor\n"));
3402                 if (unlink(compose->exteditor_file) < 0)
3403                         FILE_OP_ERROR(compose->exteditor_file, "unlink");
3404         } else if (buf[0] == '2') {
3405                 g_warning(_("Couldn't write to file\n"));
3406         } else if (buf[0] == '3') {
3407                 g_warning(_("Pipe read failed\n"));
3408         }
3409
3410         close(source);
3411
3412         compose_set_ext_editor_sensitive(compose, TRUE);
3413
3414         g_free(compose->exteditor_file);
3415         compose->exteditor_file    = NULL;
3416         compose->exteditor_pid     = -1;
3417         compose->exteditor_readdes = -1;
3418         compose->exteditor_tag     = -1;
3419 }
3420
3421 static void compose_set_ext_editor_sensitive(Compose *compose,
3422                                              gboolean sensitive)
3423 {
3424         GtkItemFactory *ifactory;
3425
3426         ifactory = gtk_item_factory_from_widget(compose->menubar);
3427
3428         menu_set_sensitive(ifactory, "/Message/Send", sensitive);
3429         menu_set_sensitive(ifactory, "/Message/Send later", sensitive);
3430         menu_set_sensitive(ifactory, "/Message/Save to draft folder",
3431                            sensitive);
3432         menu_set_sensitive(ifactory, "/File/Insert file", sensitive);
3433         menu_set_sensitive(ifactory, "/File/Insert signature", sensitive);
3434         menu_set_sensitive(ifactory, "/Edit/Wrap long lines", sensitive);
3435         menu_set_sensitive(ifactory, "/Edit/Edit with external editor",
3436                            sensitive);
3437
3438         gtk_widget_set_sensitive(compose->text,          sensitive);
3439         gtk_widget_set_sensitive(compose->send_btn,      sensitive);
3440         gtk_widget_set_sensitive(compose->sendl_btn,     sensitive);
3441         gtk_widget_set_sensitive(compose->draft_btn,     sensitive);
3442         gtk_widget_set_sensitive(compose->insert_btn,    sensitive);
3443         gtk_widget_set_sensitive(compose->sig_btn,       sensitive);
3444         gtk_widget_set_sensitive(compose->exteditor_btn, sensitive);
3445         gtk_widget_set_sensitive(compose->linewrap_btn,  sensitive);
3446 }
3447
3448 static gint calc_cursor_xpos(GtkSText *text, gint extra, gint char_width)
3449 {
3450         gint cursor_pos;
3451
3452         cursor_pos = (text->cursor_pos_x - extra) / char_width;
3453         cursor_pos = MAX(cursor_pos, 0);
3454
3455         return cursor_pos;
3456 }
3457
3458 /* callback functions */
3459
3460 /* compose_edit_size_alloc() - called when resized. don't know whether Gtk
3461  * includes "non-client" (windows-izm) in calculation, so this calculation
3462  * may not be accurate.
3463  */
3464 static gboolean compose_edit_size_alloc(GtkEditable *widget,
3465                                         GtkAllocation *allocation,
3466                                         GtkSHRuler *shruler)
3467 {
3468         if (prefs_common.show_ruler) {
3469                 gint char_width;
3470                 gint line_width_in_chars;
3471
3472                 char_width = gtkut_get_font_width
3473                         (GTK_WIDGET(widget)->style->font);
3474                 line_width_in_chars =
3475                         (allocation->width - allocation->x) / char_width;
3476
3477                 /* got the maximum */
3478                 gtk_ruler_set_range(GTK_RULER(shruler),
3479                                     0.0, line_width_in_chars,
3480                                     calc_cursor_xpos(GTK_STEXT(widget),
3481                                                      allocation->x,
3482                                                      char_width),
3483                                     /*line_width_in_chars*/ char_width);
3484         }
3485
3486         return TRUE;
3487 }
3488
3489 static void toolbar_send_cb(GtkWidget *widget, gpointer data)
3490 {
3491         compose_send_cb(data, 0, NULL);
3492 }
3493
3494 static void toolbar_send_later_cb(GtkWidget *widget, gpointer data)
3495 {
3496         compose_send_later_cb(data, 0, NULL);
3497 }
3498
3499 static void toolbar_draft_cb(GtkWidget *widget, gpointer data)
3500 {
3501         compose_draft_cb(data, 0, NULL);
3502 }
3503
3504 static void toolbar_insert_cb(GtkWidget *widget, gpointer data)
3505 {
3506         compose_insert_file_cb(data, 0, NULL);
3507 }
3508
3509 static void toolbar_attach_cb(GtkWidget *widget, gpointer data)
3510 {
3511         compose_attach_cb(data, 0, NULL);
3512 }
3513
3514 static void toolbar_sig_cb(GtkWidget *widget, gpointer data)
3515 {
3516         Compose *compose = (Compose *)data;
3517
3518         compose_insert_sig(compose);
3519 }
3520
3521 static void toolbar_ext_editor_cb(GtkWidget *widget, gpointer data)
3522 {
3523         Compose *compose = (Compose *)data;
3524
3525         compose_exec_ext_editor(compose);
3526 }
3527
3528 static void toolbar_linewrap_cb(GtkWidget *widget, gpointer data)
3529 {
3530         Compose *compose = (Compose *)data;
3531
3532         compose_wrap_line(compose);
3533 }
3534
3535 static void toolbar_address_cb(GtkWidget *widget, gpointer data)
3536 {
3537         compose_address_cb(data, 0, NULL);
3538 }
3539
3540 static void account_activated(GtkMenuItem *menuitem, gpointer data)
3541 {
3542         Compose *compose = (Compose *)data;
3543
3544         PrefsAccount *ac;
3545
3546         ac = (PrefsAccount *)gtk_object_get_user_data(GTK_OBJECT(menuitem));
3547         g_return_if_fail(ac != NULL);
3548
3549         if (ac != compose->account) {
3550                 compose->account = ac;
3551                 compose_set_title(compose);
3552         }
3553 }
3554
3555 static void attach_selected(GtkCList *clist, gint row, gint column,
3556                             GdkEvent *event, gpointer data)
3557 {
3558         Compose *compose = (Compose *)data;
3559
3560         if (event && event->type == GDK_2BUTTON_PRESS)
3561                 compose_attach_property(compose);
3562 }
3563
3564 static void attach_button_pressed(GtkWidget *widget, GdkEventButton *event,
3565                                   gpointer data)
3566 {
3567         Compose *compose = (Compose *)data;
3568         GtkCList *clist = GTK_CLIST(compose->attach_clist);
3569         gint row, column;
3570
3571         if (!event) return;
3572
3573         if (event->button == 3) {
3574                 if ((clist->selection && !clist->selection->next) ||
3575                     !clist->selection) {
3576                         gtk_clist_unselect_all(clist);
3577                         if (gtk_clist_get_selection_info(clist,
3578                                                          event->x, event->y,
3579                                                          &row, &column)) {
3580                                 gtk_clist_select_row(clist, row, column);
3581                                 gtkut_clist_set_focus_row(clist, row);
3582                         }
3583                 }
3584                 gtk_menu_popup(GTK_MENU(compose->popupmenu), NULL, NULL,
3585                                NULL, NULL, event->button, event->time);
3586         }
3587 }
3588
3589 static void attach_key_pressed(GtkWidget *widget, GdkEventKey *event,
3590                                gpointer data)
3591 {
3592         Compose *compose = (Compose *)data;
3593
3594         if (!event) return;
3595
3596         switch (event->keyval) {
3597         case GDK_Delete:
3598                 compose_attach_remove_selected(compose);
3599                 break;
3600         }
3601 }
3602
3603 static void compose_send_cb(gpointer data, guint action, GtkWidget *widget)
3604 {
3605         Compose *compose = (Compose *)data;
3606         gint val;
3607
3608         val = compose_send(compose);
3609
3610         if (val == 0) gtk_widget_destroy(compose->window);
3611 }
3612
3613 static void compose_send_later_cb(gpointer data, guint action,
3614                                   GtkWidget *widget)
3615 {
3616         Compose *compose = (Compose *)data;
3617         gchar tmp[22];
3618         gchar *to, *newsgroups;
3619
3620         to = gtk_entry_get_text(GTK_ENTRY(compose->to_entry));
3621         newsgroups = gtk_entry_get_text(GTK_ENTRY(compose->newsgroups_entry));
3622         if (*to == '\0' && *newsgroups == '\0') {
3623                 alertpanel_error(_("Recipient is not specified."));
3624                 return;
3625         }
3626
3627         g_snprintf(tmp, 22, "%s%ctmpmsg%d",
3628                    g_get_tmp_dir(), G_DIR_SEPARATOR, (gint)compose);
3629
3630         if (prefs_common.linewrap_at_send)
3631                 compose_wrap_line(compose);
3632
3633         if (compose_write_to_file(compose, tmp, FALSE) < 0 ||
3634             compose_queue(compose, tmp) < 0) {
3635                 alertpanel_error(_("Can't queue the message."));
3636                 return;
3637         }
3638
3639         if (prefs_common.savemsg) {
3640                 if (compose_save_to_outbox(compose, tmp) < 0)
3641                         alertpanel_error
3642                                 (_("Can't save the message to outbox."));
3643         }
3644
3645         if (unlink(tmp) < 0)
3646                 FILE_OP_ERROR(tmp, "unlink");
3647
3648         gtk_widget_destroy(compose->window);
3649 }
3650
3651 static void compose_draft_cb(gpointer data, guint action, GtkWidget *widget)
3652 {
3653         Compose *compose = (Compose *)data;
3654         FolderItem *draft;
3655         gchar *tmp;
3656
3657         draft = folder_get_default_draft();
3658         folder_item_scan(draft);
3659
3660         if (procmsg_msg_exist(compose->targetinfo) &&
3661             compose->targetinfo->folder == draft) {
3662                 if (folder_item_remove_msg(draft,
3663                                            compose->targetinfo->msgnum) < 0)
3664                         g_warning(_("can't remove the old draft message\n"));
3665         }
3666         tmp = g_strdup_printf("%s%cdraft.%d", g_get_tmp_dir(),
3667                               G_DIR_SEPARATOR, (gint)compose);
3668
3669         if (compose_write_to_file(compose, tmp, TRUE) < 0) {
3670                 g_free(tmp);
3671                 return;
3672         }
3673
3674         if (folder_item_add_msg(draft, tmp) < 0) {
3675                 unlink(tmp);
3676                 g_free(tmp);
3677                 return;
3678         }
3679
3680         unlink(tmp);
3681         g_free(tmp);
3682
3683         //folderview_scan_folder_a(DRAFT_DIR, TRUE);
3684
3685         gtk_widget_destroy(compose->window);
3686 }
3687
3688 static void compose_attach_cb(gpointer data, guint action, GtkWidget *widget)
3689 {
3690         Compose *compose = (Compose *)data;
3691         gchar *file;
3692
3693         file = filesel_select_file(_("Select file"), NULL);
3694
3695         if (file)
3696                 compose_attach_append(compose, file, MIME_UNKNOWN);
3697 }
3698
3699 static void compose_insert_file_cb(gpointer data, guint action,
3700                                    GtkWidget *widget)
3701 {
3702         Compose *compose = (Compose *)data;
3703         gchar *file;
3704
3705         file = filesel_select_file(_("Select file"), NULL);
3706
3707         if (file)
3708                 compose_insert_file(compose, file);
3709 }
3710
3711 static gint compose_delete_cb(GtkWidget *widget, GdkEventAny *event,
3712                               gpointer data)
3713 {
3714         compose_close_cb(data, 0, NULL);
3715         return TRUE;
3716 }
3717
3718 static void compose_close_cb(gpointer data, guint action, GtkWidget *widget)
3719 {
3720         Compose *compose = (Compose *)data;
3721         AlertValue val;
3722
3723         if (compose->exteditor_tag != -1) {
3724                 if (!compose_ext_editor_kill(compose))
3725                         return;
3726         }
3727
3728         if (compose->modified) {
3729                 val = alertpanel(_("Discard message"),
3730                                  _("This message has been modified. discard it?"),
3731                                  _("Discard"), _("to Draft"), _("Cancel"));
3732
3733                 switch (val) {
3734                 case G_ALERTDEFAULT:
3735                         break;
3736                 case G_ALERTALTERNATE:
3737                         compose_draft_cb(data, 0, NULL);
3738                         return;
3739                 default:
3740                         return;
3741                 }
3742         }
3743
3744         gtk_widget_destroy(compose->window);
3745 }
3746
3747 static void compose_address_cb(gpointer data, guint action, GtkWidget *widget)
3748 {
3749         Compose *compose = (Compose *)data;
3750
3751         addressbook_open(compose);
3752 }
3753
3754 static void compose_ext_editor_cb(gpointer data, guint action,
3755                                   GtkWidget *widget)
3756 {
3757         Compose *compose = (Compose *)data;
3758
3759         compose_exec_ext_editor(compose);
3760 }
3761
3762 static void compose_destroy_cb(GtkWidget *widget, Compose *compose)
3763 {
3764         compose_destroy(compose);
3765 }
3766
3767 static void compose_cut_cb(Compose *compose)
3768 {
3769         if (compose->focused_editable &&
3770             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
3771                 gtk_editable_cut_clipboard
3772                         (GTK_EDITABLE(compose->focused_editable));
3773 }
3774
3775 static void compose_copy_cb(Compose *compose)
3776 {
3777         if (compose->focused_editable &&
3778             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
3779                 gtk_editable_copy_clipboard
3780                         (GTK_EDITABLE(compose->focused_editable));
3781 }
3782
3783 static void compose_paste_cb(Compose *compose)
3784 {
3785         if (compose->focused_editable &&
3786             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
3787                 gtk_editable_paste_clipboard
3788                         (GTK_EDITABLE(compose->focused_editable));
3789 }
3790
3791 static void compose_allsel_cb(Compose *compose)
3792 {
3793         if (compose->focused_editable &&
3794             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
3795                 gtk_editable_select_region
3796                         (GTK_EDITABLE(compose->focused_editable), 0, -1);
3797 }
3798
3799 static void compose_grab_focus_cb(GtkWidget *widget, Compose *compose)
3800 {
3801         if (GTK_IS_EDITABLE(widget))
3802                 compose->focused_editable = widget;
3803 }
3804
3805 static void compose_changed_cb(GtkEditable *editable, Compose *compose)
3806 {
3807         if (compose->modified == FALSE) {
3808                 compose->modified = TRUE;
3809                 compose_set_title(compose);
3810         }
3811 }
3812
3813 static void compose_button_press_cb(GtkWidget *widget, GdkEventButton *event,
3814                                     Compose *compose)
3815 {
3816         gtk_stext_set_point(GTK_STEXT(widget),
3817                            gtk_editable_get_position(GTK_EDITABLE(widget)));
3818 }
3819
3820 #if 0
3821 static void compose_key_press_cb(GtkWidget *widget, GdkEventKey *event,
3822                                  Compose *compose)
3823 {
3824         gtk_stext_set_point(GTK_STEXT(widget),
3825                            gtk_editable_get_position(GTK_EDITABLE(widget)));
3826 }
3827 #endif
3828
3829 static void compose_toggle_to_cb(gpointer data, guint action,
3830                                  GtkWidget *widget)
3831 {
3832         Compose *compose = (Compose *)data;
3833
3834         if (GTK_CHECK_MENU_ITEM(widget)->active) {
3835                 gtk_widget_show(compose->to_hbox);
3836                 gtk_widget_show(compose->to_entry);
3837                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 1, 4);
3838                 compose->use_to = TRUE;
3839         } else {
3840                 gtk_widget_hide(compose->to_hbox);
3841                 gtk_widget_hide(compose->to_entry);
3842                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 1, 0);
3843                 gtk_widget_queue_resize(compose->table_vbox);
3844                 compose->use_to = FALSE;
3845         }
3846
3847         if (addressbook_get_target_compose() == compose)
3848                 addressbook_set_target_compose(compose);
3849 }