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