sync with 0.4.65cvs11
[claws.git] / src / compose.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999,2000 Hiroyuki Yamamoto
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include "defs.h"
25
26 #include <glib.h>
27 #include <gdk/gdkkeysyms.h>
28 #include <gtk/gtkmain.h>
29 #include <gtk/gtkmenu.h>
30 #include <gtk/gtkmenuitem.h>
31 #include <gtk/gtkitemfactory.h>
32 #include <gtk/gtkcheckmenuitem.h>
33 #include <gtk/gtkoptionmenu.h>
34 #include <gtk/gtkwidget.h>
35 #include <gtk/gtkclist.h>
36 #include <gtk/gtkctree.h>
37 #include <gtk/gtkvpaned.h>
38 #include <gtk/gtkentry.h>
39 #include <gtk/gtkeditable.h>
40 #include <gtk/gtkwindow.h>
41 #include <gtk/gtksignal.h>
42 #include <gtk/gtkvbox.h>
43 #include <gtk/gtkcontainer.h>
44 #include <gtk/gtkhandlebox.h>
45 #include <gtk/gtktoolbar.h>
46 #include <gtk/gtktable.h>
47 #include <gtk/gtkhbox.h>
48 #include <gtk/gtklabel.h>
49 #include <gtk/gtkscrolledwindow.h>
50 #include <gtk/gtkthemes.h>
51 #include <gtk/gtkdnd.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <ctype.h>
56 #include <unistd.h>
57 #include <time.h>
58 /* #include <sys/utsname.h> */
59 #include <stdlib.h>
60 #include <sys/wait.h>
61 #include <signal.h>
62 #include <errno.h>
63
64 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
65 #  include <wchar.h>
66 #  include <wctype.h>
67 #endif
68
69
70 #include "gtkstext.h"
71
72 #include "intl.h"
73 #include "main.h"
74 #include "mainwindow.h"
75 #include "compose.h"
76 #include "addressbook.h"
77 #include "folderview.h"
78 #include "procmsg.h"
79 #include "menu.h"
80 #include "send.h"
81 #include "news.h"
82 #include "prefs_common.h"
83 #include "prefs_account.h"
84 #include "account.h"
85 #include "filesel.h"
86 #include "procheader.h"
87 #include "procmime.h"
88 #include "statusbar.h"
89 #include "about.h"
90 #include "base64.h"
91 #include "codeconv.h"
92 #include "utils.h"
93 #include "gtkutils.h"
94 #include "socket.h"
95 #include "alertpanel.h"
96 #include "manage_window.h"
97 #include "gtkshruler.h"
98 #include "folder.h"
99 #include "addr_compl.h"
100 #include "headers.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
334 static void compose_attach_drag_received_cb (GtkWidget          *widget,
335                                              GdkDragContext     *drag_context,
336                                              gint                x,
337                                              gint                y,
338                                              GtkSelectionData   *data,
339                                              guint               info,
340                                              guint               time,
341                                              gpointer            user_data);
342 static void compose_insert_drag_received_cb (GtkWidget          *widget,
343                                              GdkDragContext     *drag_context,
344                                              gint                x,
345                                              gint                y,
346                                              GtkSelectionData   *data,
347                                              guint               info,
348                                              guint               time,
349                                              gpointer            user_data);
350
351 static void to_activated                (GtkWidget      *widget,
352                                          Compose        *compose);
353 static void newsgroups_activated        (GtkWidget      *widget,
354                                          Compose        *compose);
355 static void subject_activated           (GtkWidget      *widget,
356                                          Compose        *compose);
357 static void cc_activated                (GtkWidget      *widget,
358                                          Compose        *compose);
359 static void bcc_activated               (GtkWidget      *widget,
360                                          Compose        *compose);
361 static void replyto_activated           (GtkWidget      *widget,
362                                          Compose        *compose);
363 static void followupto_activated        (GtkWidget      *widget,
364                                          Compose        *compose);
365
366 static GtkItemFactoryEntry compose_popup_entries[] =
367 {
368         {N_("/_Add..."),        NULL, compose_attach_cb, 0, NULL},
369         {N_("/_Remove"),        NULL, compose_attach_remove_selected, 0, NULL},
370         {N_("/---"),            NULL, NULL, 0, "<Separator>"},
371         {N_("/_Property..."),   NULL, compose_attach_property, 0, NULL}
372 };
373
374 static GtkItemFactoryEntry compose_entries[] =
375 {
376         {N_("/_File"),                          NULL, NULL, 0, "<Branch>"},
377         {N_("/_File/_Attach file"),             "<control>M", compose_attach_cb, 0, NULL},
378         {N_("/_File/_Insert file"),             "<control>I", compose_insert_file_cb, 0, NULL},
379         {N_("/_File/Insert si_gnature"),        "<control>G", compose_insert_sig, 0, NULL},
380         {N_("/_File/---"),                      NULL, NULL, 0, "<Separator>"},
381         {N_("/_File/_Close"),                   "<alt>W", compose_close_cb, 0, NULL},
382
383         {N_("/_Edit"),             NULL,         NULL,  0, "<Branch>"},
384         {N_("/_Edit/_Undo"),       "<control>Z", NULL,  0, NULL},
385         {N_("/_Edit/_Redo"),       "<control>Y", NULL,  0, NULL},
386         {N_("/_Edit/---"),         NULL,         NULL,  0, "<Separator>"},
387         {N_("/_Edit/Cu_t"),        "<control>X", compose_cut_cb,    0, NULL},
388         {N_("/_Edit/_Copy"),       "<control>C", compose_copy_cb,   0, NULL},
389         {N_("/_Edit/_Paste"),      "<control>V", compose_paste_cb,  0, NULL},
390         {N_("/_Edit/Select _all"), "<control>A", compose_allsel_cb, 0, NULL},
391         {N_("/_Edit/---"),         NULL,         NULL,  0, "<Separator>"},
392         {N_("/_Edit/Wrap long _lines"), "<alt>L", compose_wrap_line, 0, NULL},
393         {N_("/_Edit/Edit with e_xternal editor"), "<alt>X",
394                                         compose_ext_editor_cb,  0, NULL},
395
396         {N_("/_Message"),               NULL,           NULL,   0, "<Branch>"},
397         {N_("/_Message/_Send"),         "<shift><control>S",
398                                         compose_send_cb, 0, NULL},
399         {N_("/_Message/Send _later"),   "<shift><alt>S",
400                                         compose_send_later_cb,  0, NULL},
401         {N_("/_Message/Save to _draft folder"),
402                                         "<alt>D",       compose_draft_cb, 0, NULL},
403         {N_("/_Message/---"),           NULL,           NULL,   0, "<Separator>"},
404         {N_("/_Message/_To"),           NULL, compose_toggle_to_cb, 0, "<ToggleItem>"},
405         {N_("/_Message/_Cc"),           NULL, compose_toggle_cc_cb, 0, "<ToggleItem>"},
406         {N_("/_Message/_Bcc"),          NULL, compose_toggle_bcc_cb, 0, "<ToggleItem>"},
407         {N_("/_Message/_Reply to"),     NULL, compose_toggle_replyto_cb, 0, "<ToggleItem>"},
408         {N_("/_Message/---"),           NULL,           NULL,   0, "<Separator>"},
409         {N_("/_Message/_Followup to"),  NULL, compose_toggle_followupto_cb, 0, "<ToggleItem>"},
410         {N_("/_Message/---"),           NULL,           NULL,   0, "<Separator>"},
411         {N_("/_Message/_Attach"),       NULL, compose_toggle_attach_cb, 0, "<ToggleItem>"},
412 #if USE_GPGME
413         {N_("/_Message/---"),           NULL,           NULL,   0, "<Separator>"},
414         {N_("/_Message/Si_gn"),         NULL, compose_toggle_sign_cb, 0, "<ToggleItem>"},
415         {N_("/_Message/_Encrypt"),      NULL, compose_toggle_encrypt_cb, 0, "<ToggleItem>"},
416 #endif /* USE_GPGME */
417         {N_("/_Tool"),                  NULL, NULL,     0, "<Branch>"},
418         {N_("/_Tool/Show _ruler"),      NULL, compose_toggle_ruler_cb,  0, "<ToggleItem>"},
419         {N_("/_Tool/_Address book"),    "<alt>A",       compose_address_cb, 0, NULL},
420         {N_("/_Help"),                  NULL, NULL,     0, "<LastBranch>"},
421         {N_("/_Help/_About"),           NULL,           about_show,     0, NULL}
422 };
423
424 static GtkTargetEntry compose_mime_types[] =
425 {
426         {"text/uri-list", 0, 0}
427 };
428
429 void compose_new(PrefsAccount *account)
430 {
431         compose_new_with_recipient(account, NULL);
432 }
433
434 void compose_new_with_recipient(PrefsAccount *account, const gchar *to)
435 {
436         Compose *compose;
437
438         if (!account) account = cur_account;
439         g_return_if_fail(account != NULL);
440
441         compose = compose_create(account);
442         compose->mode = COMPOSE_NEW;
443
444         if (prefs_common.auto_sig)
445                 compose_insert_sig(compose);
446         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
447         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
448
449         if (account->protocol != A_NNTP) {
450                 if (to) {
451                         compose_entry_append(compose, to, COMPOSE_TO);
452                         gtk_widget_grab_focus(compose->subject_entry);
453                 } else
454                         gtk_widget_grab_focus(compose->to_entry);
455         } else
456                 gtk_widget_grab_focus(compose->newsgroups_entry);
457 }
458
459 void compose_reply(MsgInfo *msginfo, gboolean quote, gboolean to_all)
460 {
461         Compose *compose;
462         PrefsAccount *account;
463         GtkSText *text;
464
465         g_return_if_fail(msginfo != NULL);
466         g_return_if_fail(msginfo->folder != NULL);
467
468         account = msginfo->folder->folder->account;
469         if (!account) account = cur_account;
470         g_return_if_fail(account != NULL);
471
472         MSG_UNSET_FLAGS(msginfo->flags, MSG_FORWARDED);
473         MSG_SET_FLAGS(msginfo->flags, MSG_REPLIED);
474
475         compose = compose_create(account);
476         compose->mode = COMPOSE_REPLY;
477
478         if (compose_parse_header(compose, msginfo) < 0) return;
479         compose_reply_set_entry(compose, msginfo, to_all);
480
481         text = GTK_STEXT(compose->text);
482         gtk_stext_freeze(text);
483
484         if (quote) {
485                 FILE *fp;
486                 gchar *quote_str;
487
488                 if ((fp = procmime_get_text_part(msginfo)) == NULL)
489                         g_warning(_("Can't get text part\n"));
490                 else {
491                         quote_str = compose_quote_parse_fmt
492                                 (compose, msginfo, prefs_common.quotefmt);
493                         gtk_stext_insert(text, NULL, NULL, NULL, quote_str, -1);
494                         g_free(quote_str);
495                         compose_quote_file(compose, msginfo, fp);
496                         fclose(fp);
497                 }
498         }
499
500         if (prefs_common.auto_sig)
501                 compose_insert_sig(compose);
502         gtk_editable_set_position(GTK_EDITABLE(text), 0);
503         gtk_stext_set_point(text, 0);
504
505         gtk_stext_thaw(text);
506         gtk_widget_grab_focus(compose->text);
507 }
508
509 #define INSERT_FW_HEADER(var, hdr) \
510 if (msginfo->var && *msginfo->var) { \
511         gtk_stext_insert(text, NULL, NULL, NULL, hdr, -1); \
512         gtk_stext_insert(text, NULL, NULL, NULL, msginfo->var, -1); \
513         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1); \
514 }
515
516 void compose_forward(MsgInfo *msginfo, gboolean as_attach)
517 {
518         Compose *compose;
519         PrefsAccount *account;
520         GtkSText *text;
521         FILE *fp;
522         gchar buf[BUFFSIZE];
523
524         g_return_if_fail(msginfo != NULL);
525         g_return_if_fail(msginfo->folder != NULL);
526
527         account = msginfo->folder->folder->account;
528         if (!account) account = cur_account;
529         g_return_if_fail(account != NULL);
530
531         MSG_UNSET_FLAGS(msginfo->flags, MSG_REPLIED);
532         MSG_SET_FLAGS(msginfo->flags, MSG_FORWARDED);
533
534         compose = compose_create(account);
535         compose->mode = COMPOSE_FORWARD;
536
537         if (msginfo->subject && *msginfo->subject) {
538                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), "Fw: ");
539                 gtk_entry_append_text(GTK_ENTRY(compose->subject_entry),
540                                       msginfo->subject);
541         }
542
543         text = GTK_STEXT(compose->text);
544         gtk_stext_freeze(text);
545
546         if (as_attach) {
547                 gchar *msgfile;
548
549                 msgfile = procmsg_get_message_file_path(msginfo);
550                 if (!is_file_exist(msgfile))
551                         g_warning(_("%s: file not exist\n"), msgfile);
552                 else
553                         compose_attach_append(compose, msgfile,
554                                               MIME_MESSAGE_RFC822);
555
556                 g_free(msgfile);
557         } else {
558                 if ((fp = procmime_get_text_part(msginfo)) == NULL)
559                         g_warning(_("Can't get text part\n"));
560                 else {
561                         /* insert header */
562                         gtk_stext_insert(text, NULL, NULL, NULL,
563                                         _("\n\nBegin forwarded message:\n\n"), -1);
564                         INSERT_FW_HEADER(date,       "Date: ");
565                         INSERT_FW_HEADER(from,       "From: ");
566                         INSERT_FW_HEADER(to,         "To: ");
567                         INSERT_FW_HEADER(newsgroups, "Newsgroups: ");
568                         INSERT_FW_HEADER(subject,    "Subject: ");
569                         gtk_stext_insert(text, NULL, NULL, NULL, "\n\n", 2);
570
571                         /* forward body */
572                         while (fgets(buf, sizeof(buf), fp) != NULL)
573                                 gtk_stext_insert(text, NULL, NULL, NULL,
574                                                 buf, -1);
575                         fclose(fp);
576                 }
577         }
578
579         if (prefs_common.auto_sig)
580                 compose_insert_sig(compose);
581         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
582         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
583
584         gtk_stext_thaw(text);
585         if (account->protocol != A_NNTP)
586                 gtk_widget_grab_focus(compose->to_entry);
587         else
588                 gtk_widget_grab_focus(compose->newsgroups_entry);
589 }
590
591 void compose_reedit(MsgInfo *msginfo)
592 {
593         Compose *compose;
594         PrefsAccount *account;
595         GtkSText *text;
596         FILE *fp;
597         gchar buf[BUFFSIZE];
598
599         g_return_if_fail(msginfo != NULL);
600         g_return_if_fail(msginfo->folder != NULL);
601
602         account = msginfo->folder->folder->account;
603         if (!account) account = cur_account;
604         g_return_if_fail(account != NULL);
605
606         compose = compose_create(account);
607         compose->mode = COMPOSE_REEDIT_DRAFT;
608         compose->targetinfo = procmsg_msginfo_copy(msginfo);
609
610         if (compose_parse_header(compose, msginfo) < 0) return;
611         compose_reedit_set_entry(compose, msginfo);
612
613         text = GTK_STEXT(compose->text);
614         gtk_stext_freeze(text);
615
616         if ((fp = procmime_get_text_part(msginfo)) == NULL)
617                 g_warning(_("Can't get text part\n"));
618         else {
619                 while (fgets(buf, sizeof(buf), fp) != NULL)
620                         gtk_stext_insert(text, NULL, NULL, NULL, buf, -1);
621                 fclose(fp);
622         }
623
624         gtk_stext_thaw(text);
625         gtk_widget_grab_focus(compose->text);
626 }
627
628 GList *compose_get_compose_list(void)
629 {
630         return compose_list;
631 }
632
633 void compose_entry_append(Compose *compose, const gchar *address,
634                           ComposeEntryType type)
635 {
636         GtkEntry *entry;
637         const gchar *text;
638
639         if (!address || *address == '\0') return;
640
641         switch (type) {
642         case COMPOSE_CC:
643                 entry = GTK_ENTRY(compose->cc_entry);
644                 break;
645         case COMPOSE_BCC:
646                 entry = GTK_ENTRY(compose->bcc_entry);
647                 break;
648         case COMPOSE_TO:
649         default:
650                 entry = GTK_ENTRY(compose->to_entry);
651                 break;
652         }
653
654         text = gtk_entry_get_text(entry);
655         if (*text != '\0')
656                 gtk_entry_append_text(entry, ", ");
657         gtk_entry_append_text(entry, address);
658 }
659
660 static gint compose_parse_header(Compose *compose, MsgInfo *msginfo)
661 {
662         static HeaderEntry hentry[] = {{"Reply-To:",    NULL, TRUE},
663                                        {"Cc:",          NULL, FALSE},
664                                        {"References:",  NULL, FALSE},
665                                        {"Bcc:",         NULL, FALSE},
666                                        {"Newsgroups:",  NULL, FALSE},
667                                        {"Followup-To:", NULL, FALSE},
668                                        {NULL,           NULL, FALSE}};
669
670         enum
671         {
672                 H_REPLY_TO      = 0,
673                 H_CC            = 1,
674                 H_REFERENCES    = 2,
675                 H_BCC           = 3,
676                 H_NEWSGROUPS    = 4,
677                 H_FOLLOWUP_TO   = 5
678         };
679
680         FILE *fp;
681
682         g_return_val_if_fail(msginfo != NULL, -1);
683
684         if ((fp = procmsg_open_message(msginfo)) == NULL) return -1;
685         procheader_get_header_fields(fp, hentry);
686         fclose(fp);
687
688         if (hentry[H_REPLY_TO].body != NULL) {
689                 conv_unmime_header_overwrite(hentry[H_REPLY_TO].body);
690                 compose->replyto = hentry[H_REPLY_TO].body;
691                 hentry[H_REPLY_TO].body = NULL;
692         }
693         if (hentry[H_CC].body != NULL) {
694                 conv_unmime_header_overwrite(hentry[H_CC].body);
695                 compose->cc = hentry[H_CC].body;
696                 hentry[H_CC].body = NULL;
697         }
698         if (hentry[H_REFERENCES].body != NULL) {
699                 if (compose->mode == COMPOSE_REEDIT_DRAFT)
700                         compose->references = hentry[H_REFERENCES].body;
701                 else {
702                         compose->references = compose_parse_references
703                                 (hentry[H_REFERENCES].body, msginfo->msgid);
704                         g_free(hentry[H_REFERENCES].body);
705                 }
706                 hentry[H_REFERENCES].body = NULL;
707         }
708         if (hentry[H_BCC].body != NULL) {
709                 if (compose->mode == COMPOSE_REEDIT_DRAFT) {
710                         conv_unmime_header_overwrite(hentry[H_BCC].body);
711                         compose->bcc = hentry[H_BCC].body;
712                 } else
713                         g_free(hentry[H_BCC].body);
714                 hentry[H_BCC].body = NULL;
715         }
716         if (hentry[H_NEWSGROUPS].body != NULL) {
717                 compose->newsgroups = hentry[H_NEWSGROUPS].body;
718                 hentry[H_NEWSGROUPS].body = NULL;
719         }
720         if (hentry[H_FOLLOWUP_TO].body != NULL) {
721                 conv_unmime_header_overwrite(hentry[H_FOLLOWUP_TO].body);
722                 compose->followup_to = hentry[H_FOLLOWUP_TO].body;
723                 hentry[H_FOLLOWUP_TO].body = NULL;
724         }
725
726         if (compose->mode == COMPOSE_REEDIT_DRAFT && msginfo->inreplyto)
727                 compose->inreplyto = g_strdup(msginfo->inreplyto);
728         else if (compose->mode != COMPOSE_REEDIT_DRAFT &&
729                  msginfo->msgid && *msginfo->msgid) {
730                 compose->inreplyto = g_strdup(msginfo->msgid);
731
732                 if (!compose->references) {
733                         if (msginfo->inreplyto && *msginfo->inreplyto)
734                                 compose->references =
735                                         g_strdup_printf("<%s>\n\t<%s>",
736                                                         msginfo->inreplyto,
737                                                         msginfo->msgid);
738                         else
739                                 compose->references =
740                                         g_strconcat("<", msginfo->msgid, ">",
741                                                     NULL);
742                 }
743         }
744
745         return 0;
746 }
747
748 static gchar *compose_parse_references(const gchar *ref, const gchar *msgid)
749 {
750         GSList *ref_id_list, *cur;
751         GString *new_ref;
752         gchar *new_ref_str;
753
754         ref_id_list = references_list_append(NULL, ref);
755         if (!ref_id_list) return NULL;
756         if (msgid && *msgid)
757                 ref_id_list = g_slist_append(ref_id_list, g_strdup(msgid));
758
759         for (;;) {
760                 gint len = 0;
761
762                 for (cur = ref_id_list; cur != NULL; cur = cur->next)
763                         /* "<" + Message-ID + ">" + CR+LF+TAB */
764                         len += strlen((gchar *)cur->data) + 5;
765
766                 if (len > MAX_REFERENCES_LEN) {
767                         /* remove second message-ID */
768                         if (ref_id_list && ref_id_list->next &&
769                             ref_id_list->next->next) {
770                                 g_free(ref_id_list->next->data);
771                                 ref_id_list = g_slist_remove
772                                         (ref_id_list, ref_id_list->next->data);
773                         } else {
774                                 slist_free_strings(ref_id_list);
775                                 g_slist_free(ref_id_list);
776                                 return NULL;
777                         }
778                 } else
779                         break;
780         }
781
782         new_ref = g_string_new("");
783         for (cur = ref_id_list; cur != NULL; cur = cur->next) {
784                 if (new_ref->len > 0)
785                         g_string_append(new_ref, "\n\t");
786                 g_string_sprintfa(new_ref, "<%s>", (gchar *)cur->data);
787         }
788
789         slist_free_strings(ref_id_list);
790         g_slist_free(ref_id_list);
791
792         new_ref_str = new_ref->str;
793         g_string_free(new_ref, FALSE);
794
795         return new_ref_str;
796 }
797
798 static void compose_quote_file(Compose *compose, MsgInfo *msginfo, FILE *fp)
799 {
800         GtkSText *text = GTK_STEXT(compose->text);
801         gchar *qmark;
802         gchar *quote_str;
803         GdkColor *qcolor = NULL;
804         gchar buf[BUFFSIZE];
805         gint qlen;
806         gchar *linep, *cur, *leftp;
807         gint line_len, cur_len;
808         gint wrap_len;
809         gint str_len;
810         gint ch_len;
811
812         /* if (prefs_common.enable_color) qcolor = &quote_color; */
813         if (prefs_common.quotemark && *prefs_common.quotemark)
814                 qmark = prefs_common.quotemark;
815         else
816                 qmark = "> ";
817         quote_str = compose_quote_parse_fmt(compose, msginfo, qmark);
818         g_return_if_fail(quote_str != NULL);
819         qlen = strlen(quote_str);
820
821         if (!prefs_common.linewrap_quote ||
822             prefs_common.linewrap_len <= qlen) {
823                 while (fgets(buf, sizeof(buf), fp) != NULL) {
824                         gtk_stext_insert(text, NULL, qcolor, NULL,
825                                         quote_str, -1);
826                         gtk_stext_insert(text, NULL, qcolor, NULL, buf, -1);
827                 }
828                 g_free(quote_str);
829                 return;
830         }
831
832         wrap_len = prefs_common.linewrap_len - qlen;
833
834         while (fgets(buf, sizeof(buf), fp) != NULL) {
835                 strretchomp(buf);
836                 str_len = strlen(buf);
837
838                 if (str_len <= wrap_len) {
839                         gtk_stext_insert(text, NULL, qcolor, NULL,
840                                         quote_str, -1);
841                         gtk_stext_insert(text, NULL, qcolor, NULL, buf, -1);
842                         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1);
843                         continue;
844                 }
845
846                 linep = cur = leftp = buf;
847                 line_len = cur_len = 0;
848
849                 while (*cur != '\0') {
850                         ch_len = mblen(cur, MB_CUR_MAX);
851                         if (ch_len < 0) ch_len = 1;
852
853                         if (ch_len == 1 && isspace(*cur)) {
854                                 linep = cur + ch_len;
855                                 line_len = cur_len + ch_len;
856                         }
857
858                         if (cur_len + ch_len > wrap_len && line_len > 0) {
859                                 gtk_stext_insert(text, NULL, qcolor, NULL,
860                                                 quote_str, -1);
861
862                                 if (isspace(*(linep - 1)))
863                                         gtk_stext_insert(text, NULL,
864                                                         qcolor, NULL,
865                                                         leftp, line_len - 1);
866                                 else
867                                         gtk_stext_insert(text, NULL,
868                                                         qcolor, NULL,
869                                                         leftp, line_len);
870                                 gtk_stext_insert(text, NULL, NULL, NULL,
871                                                 "\n", 1);
872
873                                 leftp = linep;
874                                 cur_len = cur_len - line_len + ch_len;
875                                 line_len = 0;
876                                 cur += ch_len;
877                                 continue;
878                         }
879
880                         if (ch_len > 1) {
881                                 linep = cur + ch_len;
882                                 line_len = cur_len + ch_len;
883                         }
884                         cur_len += ch_len;
885                         cur += ch_len;
886                 }
887
888                 if (*leftp) {
889                         gtk_stext_insert(text, NULL, qcolor, NULL,
890                                         quote_str, -1);
891                         gtk_stext_insert(text, NULL, qcolor, NULL, leftp, -1);
892                         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1);
893                 }
894         }
895
896         g_free(quote_str);
897 }
898
899 static gchar *compose_quote_parse_fmt(Compose *compose, MsgInfo *msginfo,
900                                       const gchar *fmt)
901 {
902         gchar *ext_str;
903         size_t buf_len = 1024;
904         size_t ext_len = 0;
905         gchar *str;
906         gchar *mbs;
907         wchar_t *wcsfmt;
908         wchar_t *sp;
909         gchar tmp[3];
910
911         if (!fmt || *fmt == '\0') return 0;
912
913         Xalloca(mbs, sizeof(wchar_t) + 1, return 0);
914         Xalloca(wcsfmt, (strlen(fmt) + 1) * sizeof(wchar_t), return 0);
915         mbstowcs(wcsfmt, fmt, strlen(fmt) + 1);
916         sp = wcsfmt;
917
918         ext_str = g_malloc(sizeof(gchar) * buf_len);
919         g_return_val_if_fail(ext_str != NULL, NULL);
920
921         while (*sp) {
922                 gint len;
923
924                 len = wctomb(mbs, *sp);
925                 mbs[len] = '\0';
926
927                 if (*mbs == '%') {
928                         gchar *p;
929
930                         wctomb(mbs, *(++sp));
931                         str = NULL;
932
933                         switch (*mbs) {
934                         case 'd':
935                                 str = msginfo->date;
936                                 sp++;
937                                 break;
938                         case 'f':
939                                 str = msginfo->from;
940                                 sp++;
941                                 break;
942                         case 'I':       /* initial */
943                                 if (!msginfo->fromname) {sp++; break;}
944                                 p = msginfo->fromname;
945                                 tmp[0] = tmp[1] = tmp[2] = '\0';
946
947                                 if (*p && isalnum(*p))
948                                         tmp[0] = toupper(*p);
949                                 else {
950                                         sp++;
951                                         break;
952                                 }
953
954                                 while (*p) {
955                                         while (*p && !isspace(*p)) p++;
956                                         while (*p && isspace(*p)) p++;
957                                         if (*p && isalnum(*p))
958                                                 tmp[1] = toupper(*p);
959                                 }
960
961                                 if (tmp[1]) str = tmp;
962                                 sp++;
963                                 break;
964                         case 'n':
965                                 str = msginfo->fromname;
966                                 sp++;
967                                 break;
968                         case 'N':
969                                 if (!msginfo->fromname) {sp++; break;}
970                                 Xstrdup_a(str, msginfo->fromname,
971                                           {sp++; break;});
972                                 p = str;
973                                 while (*p && !isspace(*p)) p++;
974                                 *p = '\0';
975                                 sp++;
976                                 break;
977                         case 's':
978                                 str = msginfo->subject;
979                                 sp++;
980                                 break;
981                         case 't':
982                                 str = msginfo->to;
983                                 sp++;
984                                 break;
985                         case 'i':
986                                 if (!msginfo->msgid) {sp++; break;}
987                                 Xalloca(str, strlen(msginfo->msgid) + 3,
988                                         {sp++; break;});
989                                 g_snprintf(str, strlen(msginfo->msgid) + 3,
990                                            "<%s>", msginfo->msgid);
991                                 sp++;
992                                 break;
993                         case '%':
994                                 str = "%";
995                                 sp++;
996                                 break;
997                         default:
998                                 break;
999                         }
1000
1001                         if (str) {
1002                                 while (ext_len + strlen(str) + 1 > buf_len)
1003                                         buf_len += 1024;
1004                                 ext_str = g_realloc(ext_str,
1005                                                     sizeof(gchar) * buf_len);
1006                                 g_return_val_if_fail(ext_str != NULL, NULL);
1007                                 strcpy(ext_str + ext_len, str);
1008                                 ext_len += strlen(str);
1009                         }
1010                 } else if (*mbs == '\\') {
1011                         wctomb(mbs, *(++sp));
1012                         str = NULL;
1013
1014                         switch (*mbs) {
1015                         case 'n':
1016                                 str = "\n";
1017                                 break;
1018                         case 't':
1019                                 str = "\t";
1020                                 break;
1021                         case '\\':
1022                                 str = "\\";
1023                                 break;
1024                         default:
1025                                 break;
1026                         }
1027
1028                         if (str) {
1029                                 while (ext_len + strlen(str) + 1 > buf_len)
1030                                         buf_len += 1024;
1031                                 ext_str = g_realloc(ext_str,
1032                                                     sizeof(gchar) * buf_len);
1033                                 g_return_val_if_fail(ext_str != NULL, NULL);
1034                                 strcpy(ext_str + ext_len, str);
1035                                 ext_len += strlen(str);
1036                                 sp++;
1037                         }
1038                 } else {
1039                         while (ext_len + len + 1 > buf_len) buf_len += 1024;
1040                         ext_str = g_realloc(ext_str, sizeof(gchar) * buf_len);
1041                         g_return_val_if_fail(ext_str != NULL, NULL);
1042                         strcpy(ext_str + ext_len, mbs);
1043                         ext_len += len;
1044                         sp++;
1045                 }
1046         }
1047
1048         if (ext_str)
1049                 ext_str = g_realloc(ext_str, strlen(ext_str) + 1);
1050
1051         return ext_str;
1052 }
1053
1054 static void compose_reply_set_entry(Compose *compose, MsgInfo *msginfo,
1055                                     gboolean to_all)
1056 {
1057         GSList *cc_list;
1058         GSList *cur;
1059         gchar *from;
1060         GHashTable *to_table;
1061
1062         g_return_if_fail(compose->account != NULL);
1063         g_return_if_fail(msginfo != NULL);
1064
1065         if (compose->account->protocol != A_NNTP)
1066                 gtk_entry_set_text(GTK_ENTRY(compose->to_entry),
1067                                    compose->replyto ? compose->replyto
1068                                    : msginfo->from ? msginfo->from : "");
1069         if (compose->account->protocol == A_NNTP)
1070                 gtk_entry_set_text(GTK_ENTRY(compose->newsgroups_entry),
1071                                    compose->followup_to ? compose->followup_to
1072                                    : compose->newsgroups ? compose->newsgroups
1073                                    : "");
1074
1075         if (msginfo->subject && *msginfo->subject) {
1076                 gchar *buf, *buf2, *p;
1077
1078                 buf = g_strdup(msginfo->subject);
1079                 while (!strncasecmp(buf, "Re:", 3)) {
1080                         p = buf + 3;
1081                         while (isspace(*p)) p++;
1082                         memmove(buf, p, strlen(p) + 1);
1083                 }
1084
1085                 buf2 = g_strdup_printf("Re: %s", buf);
1086                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), buf2);
1087                 g_free(buf2);
1088                 g_free(buf);
1089         } else
1090                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), "Re: ");
1091
1092         if (!to_all || compose->account->protocol == A_NNTP) return;
1093
1094         from = g_strdup(compose->replyto ? compose->replyto :
1095                         msginfo->from ? msginfo->from : "");
1096         extract_address(from);
1097
1098         cc_list = address_list_append(NULL, msginfo->to);
1099         cc_list = address_list_append(cc_list, compose->cc);
1100
1101         to_table = g_hash_table_new(g_str_hash, g_str_equal);
1102         g_hash_table_insert(to_table, from, GINT_TO_POINTER(1));
1103         if (compose->account)
1104                 g_hash_table_insert(to_table, compose->account->address,
1105                                     GINT_TO_POINTER(1));
1106
1107         /* remove address on To: and that of current account */
1108         for (cur = cc_list; cur != NULL; ) {
1109                 GSList *next = cur->next;
1110
1111                 if (g_hash_table_lookup(to_table, cur->data) != NULL)
1112                         cc_list = g_slist_remove(cc_list, cur->data);
1113                 else
1114                         g_hash_table_insert(to_table, cur->data, cur);
1115
1116                 cur = next;
1117         }
1118         g_hash_table_destroy(to_table);
1119         g_free(from);
1120
1121         if (cc_list) {
1122                 for (cur = cc_list; cur != NULL; cur = cur->next)
1123                         compose_entry_append(compose, (gchar *)cur->data,
1124                                              COMPOSE_CC);
1125                 slist_free_strings(cc_list);
1126                 g_slist_free(cc_list);
1127         }
1128 }
1129
1130 #define SET_ENTRY(entry, str) \
1131 { \
1132         if (str && *str) \
1133                 gtk_entry_set_text(GTK_ENTRY(compose->entry), str); \
1134 }
1135
1136 static void compose_reedit_set_entry(Compose *compose, MsgInfo *msginfo)
1137 {
1138         g_return_if_fail(msginfo != NULL);
1139
1140         SET_ENTRY(to_entry, msginfo->to);
1141         SET_ENTRY(subject_entry, msginfo->subject);
1142         SET_ENTRY(cc_entry, compose->cc);
1143         SET_ENTRY(bcc_entry, compose->bcc);
1144         SET_ENTRY(reply_entry, compose->replyto);
1145
1146         if (compose->bcc) {
1147                 GtkItemFactory *ifactory;
1148                 GtkWidget *menuitem;
1149
1150                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1151                 menuitem = gtk_item_factory_get_item(ifactory, "/Message/Bcc");
1152                 gtk_check_menu_item_set_active
1153                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
1154         }
1155         if (compose->replyto) {
1156                 GtkItemFactory *ifactory;
1157                 GtkWidget *menuitem;
1158
1159                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1160                 menuitem = gtk_item_factory_get_item
1161                         (ifactory, "/Message/Reply to");
1162                 gtk_check_menu_item_set_active
1163                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
1164         }
1165 }
1166
1167 static void compose_insert_sig(Compose *compose)
1168 {
1169         gchar *sigfile;
1170
1171         if (compose->account && compose->account->sig_path)
1172                 sigfile = g_strdup(compose->account->sig_path);
1173         else {
1174                 sigfile = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1175                                       DEFAULT_SIGNATURE, NULL);
1176         }
1177
1178         if (!is_file_or_fifo_exist(sigfile)) {
1179                 g_free(sigfile);
1180                 return;
1181         }
1182
1183         gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, "\n\n", 2);
1184         if (prefs_common.sig_sep) {
1185                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL,
1186                                 prefs_common.sig_sep, -1);
1187                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL,
1188                                 "\n", 1);
1189         }
1190
1191         compose_insert_file(compose, sigfile);
1192         g_free(sigfile);
1193 }
1194
1195 static void compose_insert_file(Compose *compose, const gchar *file)
1196 {
1197         GtkSText *text = GTK_STEXT(compose->text);
1198         gchar buf[BUFFSIZE];
1199         FILE *fp;
1200
1201         g_return_if_fail(file != NULL);
1202
1203         if ((fp = fopen(file, "r")) == NULL) {
1204                 FILE_OP_ERROR(file, "fopen");
1205                 return;
1206         }
1207
1208         gtk_stext_freeze(text);
1209
1210         while (fgets(buf, sizeof(buf), fp) != NULL)
1211                 gtk_stext_insert(text, NULL, NULL, NULL, buf, -1);
1212
1213         gtk_stext_thaw(text);
1214
1215         fclose(fp);
1216 }
1217
1218 static void compose_attach_append(Compose *compose, const gchar *file,
1219                                   ContentType cnttype)
1220 {
1221         AttachInfo *ainfo;
1222         gchar *text[N_ATTACH_COLS];
1223         off_t size;
1224         gint row;
1225
1226         if (!is_file_exist(file)) {
1227                 g_warning(_("File %s doesn't exist\n"), file);
1228                 return;
1229         }
1230         if ((size = get_file_size(file)) < 0) {
1231                 g_warning(_("Can't get file size of %s\n"), file);
1232                 return;
1233         }
1234         if (size == 0) {
1235                 alertpanel_notice(_("File %s is empty\n"), file);
1236                 return;
1237         }
1238
1239         if (!compose->use_attach) {
1240                 GtkItemFactory *ifactory;
1241                 GtkWidget *menuitem;
1242
1243                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1244                 menuitem = gtk_item_factory_get_item(ifactory,
1245                                                      "/Message/Attach");
1246                 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
1247                                                TRUE);
1248         }
1249
1250         ainfo = g_new0(AttachInfo, 1);
1251         ainfo->file = g_strdup(file);
1252
1253         if (cnttype == MIME_MESSAGE_RFC822) {
1254                 ainfo->content_type = g_strdup("message/rfc822");
1255                 ainfo->encoding = ENC_7BIT;
1256                 ainfo->name = g_strdup_printf(_("Message: %s"),
1257                                               g_basename(file));
1258         } else {
1259                 ainfo->content_type = procmime_get_mime_type(file);
1260                 if (!ainfo->content_type)
1261                         ainfo->content_type =
1262                                 g_strdup("application/octet-stream");
1263                 ainfo->encoding = ENC_BASE64;
1264                 ainfo->name = g_strdup(g_basename(file));
1265         }
1266         ainfo->size = size;
1267
1268         text[COL_MIMETYPE] = ainfo->content_type;
1269         text[COL_SIZE] = to_human_readable(size);
1270         text[COL_NAME] = ainfo->name;
1271
1272         row = gtk_clist_append(GTK_CLIST(compose->attach_clist), text);
1273         gtk_clist_set_row_data(GTK_CLIST(compose->attach_clist), row, ainfo);
1274
1275         if (cnttype != MIME_MESSAGE_RFC822)
1276                 compose_changed_cb(NULL, compose);
1277 }
1278
1279 static void compose_wrap_line(Compose *compose)
1280 {
1281         GtkSText *text = GTK_STEXT(compose->text);
1282         guint text_len;
1283         guint line_pos = 0, cur_pos = 0;
1284         gint line_len = 0, cur_len = 0;
1285         gint ch_len;
1286         gchar cbuf[MB_CUR_MAX];
1287
1288         gtk_stext_freeze(text);
1289
1290         text_len = gtk_stext_get_length(text);
1291
1292         for (; cur_pos < text_len; cur_pos++) {
1293                 if (text->use_wchar)
1294                         ch_len = wctomb
1295                                 (cbuf, (wchar_t)GTK_STEXT_INDEX(text, cur_pos));
1296                 else {
1297                         cbuf[0] = GTK_STEXT_INDEX(text, cur_pos);
1298                         ch_len = 1;
1299                 }
1300
1301                 if (ch_len == 1 && *cbuf == '\n') {
1302                         line_pos = cur_pos + 1;
1303                         line_len = cur_len = 0;
1304                         continue;
1305                 }
1306
1307                 if (ch_len < 0) {
1308                         cbuf[0] = '\0';
1309                         ch_len = 1;
1310                 }
1311
1312                 if (ch_len == 1 && isspace(*cbuf)) {
1313                         line_pos = cur_pos + 1;
1314                         line_len = cur_len + ch_len;
1315                 }
1316
1317                 if (cur_len + ch_len > prefs_common.linewrap_len &&
1318                     line_len > 0) {
1319                         gint tlen;
1320
1321                         if (text->use_wchar)
1322                                 tlen = wctomb(cbuf, (wchar_t)GTK_STEXT_INDEX(text, line_pos - 1));
1323                         else {
1324                                 cbuf[0] = GTK_STEXT_INDEX(text, line_pos - 1);
1325                                 tlen = 1;
1326                         }
1327                         if (tlen == 1 && isspace(*cbuf)) {
1328                                 gtk_stext_set_point(text, line_pos);
1329                                 gtk_stext_backward_delete(text, 1);
1330                                 text_len--;
1331                                 cur_pos--;
1332                                 line_pos--;
1333                                 cur_len--;
1334                                 line_len--;
1335                         }
1336
1337                         gtk_stext_set_point(text, line_pos);
1338                         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1);
1339                         text_len++;
1340                         cur_pos++;
1341                         line_pos++;
1342                         cur_len = cur_len - line_len + ch_len;
1343                         line_len = 0;
1344                         continue;
1345                 }
1346
1347                 if (ch_len > 1) {
1348                         line_pos = cur_pos + 1;
1349                         line_len = cur_len + ch_len;
1350                 }
1351                 cur_len += ch_len;
1352         }
1353
1354         gtk_stext_thaw(text);
1355 }
1356
1357 static void compose_set_title(Compose *compose)
1358 {
1359         gchar *str;
1360         gchar *edited;
1361
1362         edited = compose->modified ? _(" [Edited]") : "";
1363         if (compose->account && compose->account->address)
1364                 str = g_strdup_printf(_("%s - Compose message%s"),
1365                                       compose->account->address, edited);
1366         else
1367                 str = g_strdup_printf(_("Compose message%s"), edited);
1368         gtk_window_set_title(GTK_WINDOW(compose->window), str);
1369         g_free(str);
1370 }
1371
1372 static gint compose_send(Compose *compose)
1373 {
1374         gchar tmp[MAXPATHLEN + 1];
1375         gchar *to, *newsgroups;
1376         gint ok = 0;
1377         static gboolean lock = FALSE;
1378
1379         if (lock) return 1;
1380
1381         g_return_val_if_fail(compose->account != NULL, -1);
1382         g_return_val_if_fail(compose->orig_account != NULL, -1);
1383
1384         lock = TRUE;
1385
1386         to = gtk_entry_get_text(GTK_ENTRY(compose->to_entry));
1387         newsgroups = gtk_entry_get_text(GTK_ENTRY(compose->newsgroups_entry));
1388         if (*to == '\0' && *newsgroups == '\0') {
1389                 alertpanel_error(_("Recipient is not specified."));
1390                 lock = FALSE;
1391                 return 1;
1392         }
1393
1394         /* write to temporary file */
1395         g_snprintf(tmp, sizeof(tmp), "%s%ctmpmsg%d",
1396                    get_rc_dir(), G_DIR_SEPARATOR, (gint)compose);
1397
1398         if (prefs_common.linewrap_at_send)
1399                 compose_wrap_line(compose);
1400
1401         if (compose_write_to_file(compose, tmp, FALSE) < 0) {
1402                 lock = FALSE;
1403                 return -1;
1404         }
1405
1406         if (!compose->to_list && !compose->newsgroup_list) {
1407                 g_warning(_("can't get recipient list."));
1408                 unlink(tmp);
1409                 lock = FALSE;
1410                 return -1;
1411         }
1412
1413         if (compose->to_list) {
1414                 PrefsAccount *ac;
1415
1416                 if (compose->account->protocol != A_NNTP)
1417                         ac = compose->account;
1418                 else if (compose->orig_account->protocol != A_NNTP)
1419                         ac = compose->orig_account;
1420                 else if (cur_account && cur_account->protocol != A_NNTP)
1421                         ac = cur_account;
1422                 else {
1423                         ac = account_get_default();
1424                         if (!ac || ac->protocol == A_NNTP) {
1425                                 alertpanel_error(_("Account for sending mail is not specified.\n"
1426                                                    "Please select a mail account before sending."));
1427                                 unlink(tmp);
1428                                 lock = FALSE;
1429                                 return -1;
1430                         }
1431                 }
1432                 ok = send_message(tmp, ac, compose->to_list);
1433                 statusbar_pop_all();
1434         }
1435
1436         if (ok == 0 && compose->newsgroup_list) {
1437                 Folder *folder;
1438
1439                 if (compose->account->protocol == A_NNTP)
1440                         folder = FOLDER(compose->account->folder);
1441                 else
1442                         folder = FOLDER(compose->orig_account->folder);
1443
1444                 ok = news_post(folder, tmp);
1445                 if (ok < 0) {
1446                         alertpanel_error(_("Error occurred while posting the message to %s ."),
1447                                          compose->account->nntp_server);
1448                         unlink(tmp);
1449                         lock = FALSE;
1450                         return -1;
1451                 }
1452         }
1453
1454         /* queue message if failed to send */
1455         if (ok < 0) {
1456                 if (prefs_common.queue_msg) {
1457                         AlertValue val;
1458
1459                         val = alertpanel
1460                                 (_("Queueing"),
1461                                  _("Error occurred while sending the message.\n"
1462                                    "Put this message into queue folder?"),
1463                                  _("OK"), _("Cancel"), NULL);
1464                         if (G_ALERTDEFAULT == val) {
1465                                 ok = compose_queue(compose, tmp);
1466                                 if (ok < 0)
1467                                         alertpanel_error(_("Can't queue the message."));
1468                         }
1469                 } else
1470                         alertpanel_error(_("Error occurred while sending the message."));
1471         }
1472
1473         /* save message to outbox */
1474         if (ok == 0 && prefs_common.savemsg) {
1475                 if (compose_save_to_outbox(compose, tmp) < 0)
1476                         alertpanel_error
1477                                 (_("Can't save the message to outbox."));
1478         }
1479
1480         if (unlink(tmp) < 0) FILE_OP_ERROR(tmp, "unlink");
1481         lock = FALSE;
1482         return ok;
1483 }
1484
1485 static gint compose_write_to_file(Compose *compose, const gchar *file,
1486                                   gboolean is_draft)
1487 {
1488         FILE *fp;
1489         size_t len;
1490         gchar *chars;
1491         gchar *buf;
1492         const gchar *out_codeset;
1493         EncodingType encoding;
1494
1495         if ((fp = fopen(file, "w")) == NULL) {
1496                 FILE_OP_ERROR(file, "fopen");
1497                 return -1;
1498         }
1499
1500         /* chmod for security */
1501         if (change_file_mode_rw(fp, file) < 0) {
1502                 FILE_OP_ERROR(file, "chmod");
1503                 g_warning(_("can't change file mode\n"));
1504         }
1505
1506         /* get all composed text */
1507         chars = gtk_editable_get_chars(GTK_EDITABLE(compose->text), 0, -1);
1508         len = strlen(chars);
1509         if (is_ascii_str(chars)) {
1510                 buf = g_strdup(chars);
1511                 out_codeset = "US-ASCII";
1512                 encoding = ENC_7BIT;
1513         } else {
1514                 const gchar *src_codeset;
1515
1516                 out_codeset = conv_get_outgoing_charset_str();
1517                 if (!strcasecmp(out_codeset, "US-ASCII"))
1518                         out_codeset = "ISO-8859-1";
1519                 encoding = procmime_get_encoding_for_charset(out_codeset);
1520                 debug_print("charset = %s, encoding = %s\n",
1521                             out_codeset, procmime_get_encoding_str(encoding));
1522
1523                 src_codeset = conv_get_current_charset_str();
1524                 buf = conv_codeset_strdup(chars, src_codeset, out_codeset);
1525                 if (!buf) {
1526                         g_free(chars);
1527                         fclose(fp);
1528                         unlink(file);
1529                         alertpanel_error(_("Can't convert the codeset of the message."));
1530                         return -1;
1531                 }
1532         }
1533         g_free(chars);
1534
1535         /* write headers */
1536         if (compose_write_headers
1537                 (compose, fp, out_codeset, encoding, is_draft) < 0) {
1538                 g_warning(_("can't write headers\n"));
1539                 fclose(fp);
1540                 unlink(file);
1541                 g_free(buf);
1542                 return -1;
1543         }
1544
1545         if (compose->use_attach) {
1546 #if USE_GPGME
1547             /* This prolog message is ignored by mime software and
1548              * because it would make our signing/encryption task
1549              * tougher, we don't emit it in that case */
1550             if (!compose->use_signing && !compose->use_encryption)
1551 #endif
1552                 fputs("This is a multi-part message in MIME format.\n", fp);
1553
1554                 fprintf(fp, "\n--%s\n", compose->boundary);
1555                 fprintf(fp, "Content-Type: text/plain; charset=%s\n",
1556                         out_codeset);
1557                 fprintf(fp, "Content-Transfer-Encoding: %s\n",
1558                         procmime_get_encoding_str(encoding));
1559                 fputc('\n', fp);
1560         }
1561
1562         /* write body */
1563         len = strlen(buf);
1564         if (encoding == ENC_BASE64) {
1565                 gchar outbuf[B64_BUFFSIZE];
1566                 gint i, l;
1567
1568                 for (i = 0; i < len; i += B64_LINE_SIZE) {
1569                         l = MIN(B64_LINE_SIZE, len - i);
1570                         to64frombits(outbuf, buf + i, l);
1571                         fputs(outbuf, fp);
1572                         fputc('\n', fp);
1573                 }
1574         } else if (fwrite(buf, sizeof(gchar), len, fp) != len) {
1575                 FILE_OP_ERROR(file, "fwrite");
1576                 fclose(fp);
1577                 unlink(file);
1578                 g_free(buf);
1579                 return -1;
1580         }
1581         g_free(buf);
1582
1583         if (compose->use_attach)
1584                 compose_write_attach(compose, fp);
1585
1586         if (fclose(fp) == EOF) {
1587                 FILE_OP_ERROR(file, "fclose");
1588                 unlink(file);
1589                 return -1;
1590         }
1591
1592 #if USE_GPGME
1593         if (compose->use_signing) {
1594                 if (rfc2015_sign(file, compose->account) < 0) {
1595                         unlink(file);
1596                         return -1;
1597                 }
1598         }
1599         if (compose->use_encryption) {
1600                 if (rfc2015_encrypt(file, compose->to_list) < 0) {
1601                         unlink(file);
1602                         return -1;
1603                 }
1604         }
1605 #endif /* USE_GPGME */
1606
1607         return 0;
1608 }
1609
1610 static gint compose_write_body_to_file(Compose *compose, const gchar *file)
1611 {
1612         FILE *fp;
1613         size_t len;
1614         gchar *chars;
1615
1616         if ((fp = fopen(file, "w")) == NULL) {
1617                 FILE_OP_ERROR(file, "fopen");
1618                 return -1;
1619         }
1620
1621         /* chmod for security */
1622         if (change_file_mode_rw(fp, file) < 0) {
1623                 FILE_OP_ERROR(file, "chmod");
1624                 g_warning(_("can't change file mode\n"));
1625         }
1626
1627         chars = gtk_editable_get_chars(GTK_EDITABLE(compose->text), 0, -1);
1628
1629         /* write body */
1630         len = strlen(chars);
1631         if (fwrite(chars, sizeof(gchar), len, fp) != len) {
1632                 FILE_OP_ERROR(file, "fwrite");
1633                 g_free(chars);
1634                 fclose(fp);
1635                 unlink(file);
1636                 return -1;
1637         }
1638
1639         g_free(chars);
1640
1641         if (fclose(fp) == EOF) {
1642                 FILE_OP_ERROR(file, "fclose");
1643                 unlink(file);
1644                 return -1;
1645         }
1646         return 0;
1647 }
1648
1649 static gint compose_save_to_outbox(Compose *compose, const gchar *file)
1650 {
1651         FolderItem *outbox;
1652         gchar *path;
1653         gint num;
1654         FILE *fp;
1655
1656         debug_print(_("saving sent message...\n"));
1657
1658         outbox = folder_get_default_outbox();
1659         folder_item_scan(outbox);
1660         if ((num = folder_item_add_msg(outbox, file)) < 0) {
1661                 g_warning(_("can't save message\n"));
1662                 return -1;
1663         }
1664
1665         path = folder_item_get_path(outbox);
1666         if ((fp = procmsg_open_mark_file(path, TRUE)) == NULL)
1667                 g_warning(_("can't open mark file\n"));
1668         else {
1669                 MsgInfo newmsginfo;
1670
1671                 newmsginfo.msgnum = num;
1672                 newmsginfo.flags = 0;
1673                 procmsg_write_flags(&newmsginfo, fp);
1674                 fclose(fp);
1675         }
1676         g_free(path);
1677
1678         return 0;
1679 }
1680
1681 static gint compose_queue(Compose *compose, const gchar *file)
1682 {
1683         FolderItem *queue;
1684         gchar *tmp, *queue_path;
1685         FILE *fp, *src_fp;
1686         GSList *cur;
1687         gchar buf[BUFFSIZE];
1688         gint num;
1689
1690         debug_print(_("queueing message...\n"));
1691         g_return_val_if_fail(compose->to_list != NULL, -1);
1692         g_return_val_if_fail(compose->account != NULL, -1);
1693
1694         tmp = g_strdup_printf("%s%cqueue.%d", g_get_tmp_dir(),
1695                               G_DIR_SEPARATOR, (gint)compose);
1696         if ((fp = fopen(tmp, "w")) == NULL) {
1697                 FILE_OP_ERROR(tmp, "fopen");
1698                 g_free(tmp);
1699                 return -1;
1700         }
1701         if ((src_fp = fopen(file, "r")) == NULL) {
1702                 FILE_OP_ERROR(file, "fopen");
1703                 fclose(fp);
1704                 unlink(tmp);
1705                 g_free(tmp);
1706                 return -1;
1707         }
1708         if (change_file_mode_rw(fp, tmp) < 0) {
1709                 FILE_OP_ERROR(tmp, "chmod");
1710                 g_warning(_("can't change file mode\n"));
1711         }
1712
1713         /* queueing variables */
1714         fprintf(fp, "AF:\n");
1715         fprintf(fp, "NF:0\n");
1716         fprintf(fp, "PS:10\n");
1717         fprintf(fp, "SRH:1\n");
1718         fprintf(fp, "SFN:\n");
1719         fprintf(fp, "DSR:\n");
1720         if (compose->msgid)
1721                 fprintf(fp, "MID:<%s>\n", compose->msgid);
1722         else
1723                 fprintf(fp, "MID:\n");
1724         fprintf(fp, "CFG:\n");
1725         fprintf(fp, "PT:0\n");
1726         fprintf(fp, "S:%s\n", compose->account->address);
1727         fprintf(fp, "RQ:\n");
1728         if (compose->account->smtp_server)
1729                 fprintf(fp, "SSV:%s\n", compose->account->smtp_server);
1730         else
1731                 fprintf(fp, "SSV:\n");
1732         if (compose->account->nntp_server)
1733                 fprintf(fp, "NSV:%s\n", compose->account->nntp_server);
1734         else
1735                 fprintf(fp, "NSV:\n");
1736         fprintf(fp, "SSH:\n");
1737         fprintf(fp, "R:<%s>", (gchar *)compose->to_list->data);
1738         for (cur = compose->to_list->next; cur != NULL; cur = cur->next)
1739                 fprintf(fp, ",<%s>", (gchar *)cur->data);
1740         fprintf(fp, "\n");
1741         fprintf(fp, "\n");
1742
1743         while (fgets(buf, sizeof(buf), src_fp) != NULL) {
1744                 if (fputs(buf, fp) == EOF) {
1745                         FILE_OP_ERROR(tmp, "fputs");
1746                         fclose(fp);
1747                         fclose(src_fp);
1748                         unlink(tmp);
1749                         g_free(tmp);
1750                         return -1;
1751                 }
1752         }
1753
1754         fclose(src_fp);
1755         if (fclose(fp) == EOF) {
1756                 FILE_OP_ERROR(tmp, "fclose");
1757                 unlink(tmp);
1758                 g_free(tmp);
1759                 return -1;
1760         }
1761
1762         queue = folder_get_default_queue();
1763         folder_item_scan(queue);
1764         if ((num = folder_item_add_msg(queue, tmp)) < 0) {
1765                 g_warning(_("can't queue the message\n"));
1766                 unlink(tmp);
1767                 g_free(tmp);
1768                 return -1;
1769         }
1770         unlink(tmp);
1771         g_free(tmp);
1772
1773         queue_path = folder_item_get_path(queue);
1774         if ((fp = procmsg_open_mark_file(queue_path, TRUE)) == NULL)
1775                 g_warning(_("can't open mark file\n"));
1776         else {
1777                 MsgInfo newmsginfo;
1778
1779                 newmsginfo.msgnum = num;
1780                 newmsginfo.flags = 0;
1781                 procmsg_write_flags(&newmsginfo, fp);
1782                 fclose(fp);
1783         }
1784         g_free(queue_path);
1785
1786         folder_item_scan(queue);
1787         folderview_update_item(queue, TRUE);
1788
1789         return 0;
1790 }
1791
1792 static void compose_write_attach(Compose *compose, FILE *fp)
1793 {
1794         AttachInfo *ainfo;
1795         GtkCList *clist = GTK_CLIST(compose->attach_clist);
1796         gint row;
1797         FILE *attach_fp;
1798         gchar filename[BUFFSIZE];
1799         gint len;
1800
1801         for (row = 0; (ainfo = gtk_clist_get_row_data(clist, row)) != NULL;
1802              row++) {
1803                 if ((attach_fp = fopen(ainfo->file, "r")) == NULL) {
1804                         g_warning(_("Can't open file %s\n"), ainfo->file);
1805                         continue;
1806                 }
1807
1808                 fprintf(fp, "\n--%s\n", compose->boundary);
1809
1810                 if (!strcmp2(ainfo->content_type, "message/rfc822")) {
1811                         fprintf(fp, "Content-Type: %s\n", ainfo->content_type);
1812                         fprintf(fp, "Content-Disposition: inline\n");
1813                 } else {
1814                         conv_encode_header(filename, sizeof(filename),
1815                                            ainfo->name, 12);
1816                         fprintf(fp, "Content-Type: %s;\n"
1817                                     " name=\"%s\"\n",
1818                                 ainfo->content_type, filename);
1819                         fprintf(fp, "Content-Disposition: attachment;\n"
1820                                     " filename=\"%s\"\n", filename);
1821                 }
1822
1823                 fprintf(fp, "Content-Transfer-Encoding: %s\n\n",
1824                         procmime_get_encoding_str(ainfo->encoding));
1825
1826                 if (ainfo->encoding == ENC_7BIT) {
1827                         gchar buf[BUFFSIZE];
1828
1829                         while (fgets(buf, sizeof(buf), attach_fp) != NULL) {
1830                                 len = strlen(buf);
1831                                 if (len > 1 && buf[len - 1] == '\n' &&
1832                                     buf[len - 2] == '\r') {
1833                                         buf[len - 2] = '\n';
1834                                         buf[len - 1] = '\0';
1835                                 }
1836                                 fputs(buf, fp);
1837                         }
1838                 } else {
1839                         gchar inbuf[B64_LINE_SIZE], outbuf[B64_BUFFSIZE];
1840
1841                         while ((len = fread(inbuf, sizeof(gchar),
1842                                             B64_LINE_SIZE, attach_fp))
1843                                == B64_LINE_SIZE) {
1844                                 to64frombits(outbuf, inbuf, B64_LINE_SIZE);
1845                                 fputs(outbuf, fp);
1846                                 fputc('\n', fp);
1847                         }
1848                         if (len > 0 && feof(attach_fp)) {
1849                                 to64frombits(outbuf, inbuf, len);
1850                                 fputs(outbuf, fp);
1851                                 fputc('\n', fp);
1852                         }
1853                 }
1854
1855                 fclose(attach_fp);
1856         }
1857
1858         fprintf(fp, "\n--%s--\n", compose->boundary);
1859 }
1860
1861 static gint is_in_custom_headers(Compose *compose, gchar * header)
1862 {
1863         GSList * cur;
1864
1865         if (compose->account->add_customhdr) {
1866                 for (cur = compose->account->customhdr_list;
1867                      cur != NULL; cur = cur->next) {
1868                         CustomHeader * ch = (CustomHeader *) cur->data;
1869                         if (strcasecmp(ch->name, header) == 0)
1870                                 return 1;
1871                 }
1872         }
1873         return 0;
1874 }
1875
1876 static gint compose_write_headers(Compose *compose, FILE *fp,
1877                                   const gchar *charset, EncodingType encoding,
1878                                   gboolean is_draft)
1879 {
1880         gchar buf[BUFFSIZE];
1881         gchar *str;
1882         /* struct utsname utsbuf; */
1883         GSList * cur;
1884
1885         g_return_val_if_fail(fp != NULL, -1);
1886         g_return_val_if_fail(charset != NULL, -1);
1887         g_return_val_if_fail(compose->account != NULL, -1);
1888         g_return_val_if_fail(compose->account->address != NULL, -1);
1889
1890         /* Date */
1891         if (!is_in_custom_headers(compose, "Date")) {
1892                 if (compose->account->add_date) {
1893                         get_rfc822_date(buf, sizeof(buf));
1894                         fprintf(fp, "Date: %s\n", buf);
1895                 }
1896         }
1897
1898         /* From */
1899         if (!is_in_custom_headers(compose, "From")) {
1900                 if (compose->account->name && *compose->account->name) {
1901                         compose_convert_header
1902                                 (buf, sizeof(buf), compose->account->name,
1903                                  strlen("From: "));
1904                         fprintf(fp, "From: %s <%s>\n", buf, compose->account->address);
1905                 } else
1906                         fprintf(fp, "From: %s\n", compose->account->address);
1907         }
1908
1909         slist_free_strings(compose->to_list);
1910         g_slist_free(compose->to_list);
1911         compose->to_list = NULL;
1912
1913         /* To */
1914         if (compose->use_to) {
1915                 str = gtk_entry_get_text(GTK_ENTRY(compose->to_entry));
1916                 if (*str != '\0') {
1917                         Xstrdup_a(str, str, return -1);
1918                         g_strstrip(str);
1919                         if (*str != '\0') {
1920                                 compose->to_list = address_list_append
1921                                         (compose->to_list, str);
1922                                 compose_convert_header(buf, sizeof(buf), str,
1923                                                        strlen("To: "));
1924                                 if (!is_in_custom_headers(compose, "To")) {
1925                                         fprintf(fp, "To: %s\n", buf);
1926                                 }
1927                         }
1928                 }
1929         }
1930
1931         slist_free_strings(compose->newsgroup_list);
1932         g_slist_free(compose->newsgroup_list);
1933         compose->newsgroup_list = NULL;
1934
1935         /* Newsgroups */
1936         str = gtk_entry_get_text(GTK_ENTRY(compose->newsgroups_entry));
1937         if (*str != '\0') {
1938                 Xstrdup_a(str, str, return -1);
1939                 g_strstrip(str);
1940                 remove_space(str);
1941                 if (*str != '\0') {
1942                         compose->newsgroup_list =
1943                                 newsgroup_list_append(compose->newsgroup_list,
1944                                                       str);
1945                         compose_convert_header(buf, sizeof(buf), str,
1946                                                strlen("Newsgroups: "));
1947                         if (!is_in_custom_headers(compose, "Newsgroups")) {
1948                                 fprintf(fp, "Newsgroups: %s\n", buf);
1949                         }
1950                 }
1951         }
1952
1953         if (!is_draft && !compose->to_list && !compose->newsgroup_list)
1954                 return -1;
1955
1956         /* Cc */
1957         if (compose->use_cc) {
1958                 str = gtk_entry_get_text(GTK_ENTRY(compose->cc_entry));
1959                 if (*str != '\0') {
1960                         Xstrdup_a(str, str, return -1);
1961                         g_strstrip(str);
1962                         if (*str != '\0') {
1963                                 compose->to_list = address_list_append
1964                                         (compose->to_list, str);
1965                                 compose_convert_header(buf, sizeof(buf), str,
1966                                                        strlen("Cc: "));
1967                                 if (!is_in_custom_headers(compose, "Cc")) {
1968                                         fprintf(fp, "Cc: %s\n", buf);
1969                                 }
1970                         }
1971                 }
1972         }
1973
1974         /* Bcc */
1975         if (compose->use_bcc) {
1976                 str = gtk_entry_get_text(GTK_ENTRY(compose->bcc_entry));
1977                 if (*str != '\0') {
1978                         Xstrdup_a(str, str, return -1);
1979                         g_strstrip(str);
1980                         if (*str != '\0') {
1981                                 compose->to_list = address_list_append
1982                                         (compose->to_list, str);
1983                                 if (is_draft) {
1984                                         compose_convert_header
1985                                                 (buf, sizeof(buf), str,
1986                                                  strlen("Bcc: "));
1987                                         if (!is_in_custom_headers(compose,
1988                                                                   "Bcc")) {
1989                                                 fprintf(fp, "Bcc: %s\n", buf);
1990                                         }
1991                                 }
1992                         }
1993                 }
1994         }
1995
1996         /* Subject */
1997         if (!is_in_custom_headers(compose, "Subject")) {
1998                 str = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
1999                 if (*str != '\0') {
2000                         Xstrdup_a(str, str, return -1);
2001                         g_strstrip(str);
2002                         if (*str != '\0') {
2003                                 compose_convert_header(buf, sizeof(buf), str,
2004                                                        strlen("Subject: "));
2005                                 fprintf(fp, "Subject: %s\n", buf);
2006                         }
2007                 }
2008         }
2009
2010         /* Message-ID */
2011         if (!is_in_custom_headers(compose, "Message-Id")) {
2012                 if (compose->account->gen_msgid) {
2013                         compose_generate_msgid(compose, buf, sizeof(buf));
2014                         fprintf(fp, "Message-Id: <%s>\n", buf);
2015                         compose->msgid = g_strdup(buf);
2016                 }
2017         }
2018
2019         /* In-Reply-To */
2020         if (!is_in_custom_headers(compose, "In-Reply-To")) {
2021                 if (compose->inreplyto && compose->to_list)
2022                         fprintf(fp, "In-Reply-To: <%s>\n", compose->inreplyto);
2023         }
2024
2025         /* References */
2026         if (!is_in_custom_headers(compose, "References")) {
2027                 if (compose->references)
2028                         fprintf(fp, "References: %s\n", compose->references);
2029         }
2030
2031         /* Followup-To */
2032         if (!is_in_custom_headers(compose, "Followup-To")) {
2033                 if (compose->use_followupto) {
2034                         str = gtk_entry_get_text(GTK_ENTRY(compose->followup_entry));
2035                         if (*str != '\0') {
2036                                 Xstrdup_a(str, str, return -1);
2037                                 g_strstrip(str);
2038                                 remove_space(str);
2039                                 if (*str != '\0') {
2040                                         compose_convert_header(buf, sizeof(buf), str,
2041                                                                strlen("Followup-To: "));
2042                                         fprintf(fp, "Followup-To: %s\n", buf);
2043                                 }
2044                         }
2045                 }
2046         }
2047
2048         /* Reply-To */
2049         if (!is_in_custom_headers(compose, "Reply-To")) {
2050                 if (compose->use_replyto) {
2051                         str = gtk_entry_get_text(GTK_ENTRY(compose->reply_entry));
2052                         if (*str != '\0') {
2053                                 Xstrdup_a(str, str, return -1);
2054                                 g_strstrip(str);
2055                                 if (*str != '\0') {
2056                                         compose_convert_header(buf, sizeof(buf), str,
2057                                                                strlen("Reply-To: "));
2058                                         fprintf(fp, "Reply-To: %s\n", buf);
2059                                 }
2060                         }
2061                 }
2062         }
2063
2064         /* Program version and system info */
2065         /* uname(&utsbuf); */
2066         if (!is_in_custom_headers(compose, "X-Mailer")) {
2067                 str = gtk_entry_get_text(GTK_ENTRY(compose->to_entry));
2068                 if (*str != '\0') {
2069                         fprintf(fp, "X-Mailer: %s (GTK+ %d.%d.%d; %s)\n",
2070                                 prog_version,
2071                                 gtk_major_version, gtk_minor_version, gtk_micro_version,
2072                                 HOST_ALIAS);
2073                         /* utsbuf.sysname, utsbuf.release, utsbuf.machine); */
2074                 }
2075         }
2076
2077         if (!is_in_custom_headers(compose, "X-Newsreader")) {
2078                 str = gtk_entry_get_text(GTK_ENTRY(compose->newsgroups_entry));
2079                 if (*str != '\0') {
2080                 fprintf(fp, "X-Newsreader: %s (GTK+ %d.%d.%d; %s)\n",
2081                         prog_version,
2082                         gtk_major_version, gtk_minor_version, gtk_micro_version,
2083                         HOST_ALIAS);
2084                         /* utsbuf.sysname, utsbuf.release, utsbuf.machine); */
2085                 }
2086         }
2087
2088         /* Organization */
2089         if (!is_in_custom_headers(compose, "Organization")) {
2090                 if (compose->account->organization) {
2091                         compose_convert_header(buf, sizeof(buf),
2092                                                compose->account->organization,
2093                                                strlen("Organization: "));
2094                         fprintf(fp, "Organization: %s\n", buf);
2095                 }
2096         }
2097
2098         /* MIME */
2099         if (!is_in_custom_headers(compose, "Mime-Version")) {
2100                 fprintf(fp, "Mime-Version: 1.0\n");
2101         }
2102
2103         if (compose->use_attach) {
2104                 get_rfc822_date(buf, sizeof(buf));
2105                 subst_char(buf, ' ', '_');
2106                 subst_char(buf, ',', '_');
2107                 compose->boundary = g_strdup_printf("Multipart_%s_%08x",
2108                                                     buf, (guint)compose);
2109                 if (!is_in_custom_headers(compose, "Content-Type")) {
2110                         fprintf(fp,
2111                                 "Content-Type: multipart/mixed;\n"
2112                                 " boundary=\"%s\"\n", compose->boundary);
2113                 }
2114         } else {
2115                 if (!is_in_custom_headers(compose, "Content-Type")) {
2116                         fprintf(fp, "Content-Type: text/plain; charset=%s\n", charset);
2117                 }
2118                 if (!is_in_custom_headers(compose,
2119                                           "Content-Transfer-Encoding")) {
2120                         fprintf(fp, "Content-Transfer-Encoding: %s\n",
2121                                 procmime_get_encoding_str(encoding));
2122                 }
2123         }
2124
2125         /* Custom Headers */
2126         if (compose->account->add_customhdr) {
2127                 for (cur = compose->account->customhdr_list; cur != NULL;
2128                      cur = cur->next) {
2129                         CustomHeader * ch = (CustomHeader *) cur->data;
2130                         fprintf(fp, "%s: %s\n", ch->name, ch->value);
2131                 }
2132         }
2133
2134         /* separator between header and body */
2135         fputs("\n", fp);
2136
2137         return 0;
2138 }
2139
2140 static void compose_convert_header(gchar *dest, gint len, gchar *src,
2141                                    gint header_len)
2142 {
2143         g_return_if_fail(src != NULL);
2144         g_return_if_fail(dest != NULL);
2145
2146         if (len < 1) return;
2147
2148         remove_return(src);
2149
2150         if (is_ascii_str(src)) {
2151                 strncpy2(dest, src, len);
2152                 dest[len - 1] = '\0';
2153                 return;
2154         } else
2155                 conv_encode_header(dest, len, src, header_len);
2156 }
2157
2158 static void compose_generate_msgid(Compose *compose, gchar *buf, gint len)
2159 {
2160         struct tm *lt;
2161         time_t t;
2162         gchar *addr;
2163
2164         t = time(NULL);
2165         lt = localtime(&t);
2166
2167         if (compose->account && compose->account->address &&
2168             *compose->account->address) {
2169                 if (strchr(compose->account->address, '@'))
2170                         addr = g_strdup(compose->account->address);
2171                 else
2172                         addr = g_strconcat(compose->account->address, "@",
2173                                            get_domain_name(), NULL);
2174         } else
2175                 addr = g_strconcat(g_get_user_name(), "@", get_domain_name(),
2176                                    NULL);
2177
2178         g_snprintf(buf, len, "%04d%02d%02d%02d%02d%02d.%08x.%s",
2179                    lt->tm_year + 1900, lt->tm_mon + 1,
2180                    lt->tm_mday, lt->tm_hour,
2181                    lt->tm_min, lt->tm_sec,
2182                    (guint)random(), addr);
2183
2184         debug_print(_("generated Message-ID: %s\n"), buf);
2185
2186         g_free(addr);
2187 }
2188
2189 static void compose_add_entry_field(GtkWidget *table, GtkWidget **hbox,
2190                                     GtkWidget **entry, gint *count,
2191                                     const gchar *label_str,
2192                                     gboolean is_addr_entry)
2193 {
2194         GtkWidget *label;
2195
2196         if (GTK_TABLE(table)->nrows < (*count) + 1)
2197                 gtk_table_resize(GTK_TABLE(table), (*count) + 1, 2);
2198
2199         *hbox = gtk_hbox_new(FALSE, 0);
2200         label = gtk_label_new
2201                 (prefs_common.trans_hdr ? gettext(label_str) : label_str);
2202         gtk_box_pack_end(GTK_BOX(*hbox), label, FALSE, FALSE, 0);
2203         gtk_table_attach(GTK_TABLE(table), *hbox, 0, 1, *count, (*count) + 1,
2204                          GTK_FILL, 0, 2, 0);
2205         *entry = gtk_entry_new();
2206         gtk_table_attach_defaults
2207                 (GTK_TABLE(table), *entry, 1, 2, *count, (*count) + 1);
2208         if (GTK_TABLE(table)->nrows > (*count) + 1)
2209                 gtk_table_set_row_spacing(GTK_TABLE(table), *count, 4);
2210
2211         if (is_addr_entry)
2212                 address_completion_register_entry(GTK_ENTRY(*entry));
2213
2214         (*count)++;
2215 }
2216
2217 static Compose *compose_create(PrefsAccount *account)
2218 {
2219         Compose   *compose;
2220         GtkWidget *window;
2221         GtkWidget *vbox;
2222         GtkWidget *menubar;
2223         GtkWidget *handlebox;
2224
2225         GtkWidget *vbox2;
2226
2227         GtkWidget *table_vbox;
2228         GtkWidget *label;
2229         GtkWidget *from_optmenu_hbox;
2230         GtkWidget *to_entry;
2231         GtkWidget *to_hbox;
2232         GtkWidget *newsgroups_entry;
2233         GtkWidget *newsgroups_hbox;
2234         GtkWidget *subject_entry;
2235         GtkWidget *cc_entry;
2236         GtkWidget *cc_hbox;
2237         GtkWidget *bcc_entry;
2238         GtkWidget *bcc_hbox;
2239         GtkWidget *reply_entry;
2240         GtkWidget *reply_hbox;
2241         GtkWidget *followup_entry;
2242         GtkWidget *followup_hbox;
2243
2244         GtkWidget *paned;
2245
2246         GtkWidget *attach_scrwin;
2247         GtkWidget *attach_clist;
2248
2249         GtkWidget *edit_vbox;
2250         GtkWidget *ruler_hbox;
2251         GtkWidget *ruler;
2252         GtkWidget *scrolledwin;
2253         GtkWidget *text;
2254
2255         GtkWidget *table;
2256         GtkWidget *hbox;
2257
2258         gchar *titles[] = {_("MIME type"), _("Size"), _("Name")};
2259         guint n_menu_entries;
2260         GtkStyle  *style, *new_style;
2261         GdkColormap *cmap;
2262         GdkColor color[1];
2263         gboolean success[1];
2264         GdkFont   *font;
2265         GtkWidget *popupmenu;
2266         GtkWidget *menuitem;
2267         GtkItemFactory *popupfactory;
2268         GtkItemFactory *ifactory;
2269         gint n_entries;
2270         gint count = 0;
2271         gint i;
2272
2273         g_return_val_if_fail(account != NULL, NULL);
2274
2275         debug_print(_("Creating compose window...\n"));
2276         compose = g_new0(Compose, 1);
2277
2278         compose->account = account;
2279         compose->orig_account = account;
2280
2281         window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
2282         gtk_window_set_policy(GTK_WINDOW(window), TRUE, TRUE, FALSE);
2283         gtk_widget_set_usize(window, -1, prefs_common.compose_height);
2284         gtk_signal_connect(GTK_OBJECT(window), "delete_event",
2285                            GTK_SIGNAL_FUNC(compose_delete_cb), compose);
2286         gtk_signal_connect(GTK_OBJECT(window), "destroy",
2287                            GTK_SIGNAL_FUNC(compose_destroy_cb), compose);
2288         gtk_signal_connect(GTK_OBJECT(window), "focus_in_event",
2289                            GTK_SIGNAL_FUNC(manage_window_focus_in), NULL);
2290         gtk_signal_connect(GTK_OBJECT(window), "focus_out_event",
2291                            GTK_SIGNAL_FUNC(manage_window_focus_out), NULL);
2292         gtk_widget_realize(window);
2293
2294         vbox = gtk_vbox_new(FALSE, 0);
2295         gtk_container_add(GTK_CONTAINER(window), vbox);
2296
2297         n_menu_entries = sizeof(compose_entries) / sizeof(compose_entries[0]);
2298         menubar = menubar_create(window, compose_entries,
2299                                  n_menu_entries, "<Compose>", compose);
2300         gtk_box_pack_start(GTK_BOX(vbox), menubar, FALSE, TRUE, 0);
2301
2302         handlebox = gtk_handle_box_new();
2303         gtk_box_pack_start(GTK_BOX(vbox), handlebox, FALSE, FALSE, 0);
2304
2305         compose_toolbar_create(compose, handlebox);
2306
2307         vbox2 = gtk_vbox_new(FALSE, 2);
2308         gtk_box_pack_start(GTK_BOX(vbox), vbox2, TRUE, TRUE, 0);
2309         gtk_container_set_border_width(GTK_CONTAINER(vbox2), BORDER_WIDTH);
2310
2311         table_vbox = gtk_vbox_new(FALSE, 0);
2312         gtk_box_pack_start(GTK_BOX(vbox2), table_vbox, FALSE, TRUE, 0);
2313         gtk_container_set_border_width(GTK_CONTAINER(table_vbox),
2314                                        BORDER_WIDTH * 2);
2315
2316         table = gtk_table_new(8, 2, FALSE);
2317         gtk_box_pack_start(GTK_BOX(table_vbox), table, FALSE, TRUE, 0);
2318
2319         /* option menu for selecting accounts */
2320         hbox = gtk_hbox_new(FALSE, 0);
2321         label = gtk_label_new(prefs_common.trans_hdr ? _("From:") : "From:");
2322         gtk_box_pack_end(GTK_BOX(hbox), label, FALSE, FALSE, 0);
2323         gtk_table_attach(GTK_TABLE(table), hbox, 0, 1, count, count + 1,
2324                          GTK_FILL, 0, 2, 0);
2325         from_optmenu_hbox = compose_account_option_menu_create(compose);
2326         gtk_table_attach_defaults(GTK_TABLE(table), from_optmenu_hbox,
2327                                   1, 2, count, count + 1);
2328         gtk_table_set_row_spacing(GTK_TABLE(table), 0, 4);
2329         count++;
2330
2331         /* header labels and entries */
2332         compose_add_entry_field(table, &to_hbox, &to_entry, &count,
2333                                 "To:", TRUE); 
2334         compose_add_entry_field(table, &newsgroups_hbox, &newsgroups_entry,
2335                                 &count, "Newsgroups:", FALSE);
2336         compose_add_entry_field(table, &hbox, &subject_entry, &count,
2337                                 "Subject:", FALSE);
2338         compose_add_entry_field(table, &cc_hbox, &cc_entry, &count,
2339                                 "Cc:", TRUE);
2340         compose_add_entry_field(table, &bcc_hbox, &bcc_entry, &count,
2341                                 "Bcc:", TRUE);
2342         compose_add_entry_field(table, &reply_hbox, &reply_entry, &count,
2343                                 "Reply-To:", TRUE);
2344         compose_add_entry_field(table, &followup_hbox, &followup_entry, &count,
2345                                 "Followup-To:", FALSE);
2346
2347         gtk_table_set_col_spacings(GTK_TABLE(table), 4);
2348
2349         gtk_signal_connect(GTK_OBJECT(to_entry), "activate",
2350                            GTK_SIGNAL_FUNC(to_activated), compose);
2351         gtk_signal_connect(GTK_OBJECT(newsgroups_entry), "activate",
2352                            GTK_SIGNAL_FUNC(newsgroups_activated), compose);
2353         gtk_signal_connect(GTK_OBJECT(subject_entry), "activate",
2354                            GTK_SIGNAL_FUNC(subject_activated), compose);
2355         gtk_signal_connect(GTK_OBJECT(cc_entry), "activate",
2356                            GTK_SIGNAL_FUNC(cc_activated), compose);
2357         gtk_signal_connect(GTK_OBJECT(bcc_entry), "activate",
2358                            GTK_SIGNAL_FUNC(bcc_activated), compose);
2359         gtk_signal_connect(GTK_OBJECT(reply_entry), "activate",
2360                            GTK_SIGNAL_FUNC(replyto_activated), compose);
2361         gtk_signal_connect(GTK_OBJECT(followup_entry), "activate",
2362                            GTK_SIGNAL_FUNC(followupto_activated), compose);
2363
2364         gtk_signal_connect(GTK_OBJECT(subject_entry), "grab_focus",
2365                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
2366         gtk_signal_connect(GTK_OBJECT(to_entry), "grab_focus",
2367                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
2368         gtk_signal_connect(GTK_OBJECT(newsgroups_entry), "grab_focus",
2369                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
2370         gtk_signal_connect(GTK_OBJECT(cc_entry), "grab_focus",
2371                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
2372         gtk_signal_connect(GTK_OBJECT(bcc_entry), "grab_focus",
2373                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
2374         gtk_signal_connect(GTK_OBJECT(reply_entry), "grab_focus",
2375                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
2376         gtk_signal_connect(GTK_OBJECT(followup_entry), "grab_focus",
2377                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
2378
2379         /* attachment list */
2380         attach_scrwin = gtk_scrolled_window_new(NULL, NULL);
2381         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(attach_scrwin),
2382                                        GTK_POLICY_AUTOMATIC,
2383                                        GTK_POLICY_ALWAYS);
2384         gtk_widget_set_usize(attach_scrwin, -1, 80);
2385
2386         attach_clist = gtk_clist_new_with_titles(N_ATTACH_COLS, titles);
2387         gtk_clist_set_column_justification(GTK_CLIST(attach_clist), COL_SIZE,
2388                                            GTK_JUSTIFY_RIGHT);
2389         gtk_clist_set_column_width(GTK_CLIST(attach_clist), COL_MIMETYPE, 240);
2390         gtk_clist_set_column_width(GTK_CLIST(attach_clist), COL_SIZE, 64);
2391         gtk_clist_set_selection_mode(GTK_CLIST(attach_clist),
2392                                      GTK_SELECTION_EXTENDED);
2393         for (i = 0; i < N_ATTACH_COLS; i++)
2394                 GTK_WIDGET_UNSET_FLAGS
2395                         (GTK_CLIST(attach_clist)->column[i].button,
2396                          GTK_CAN_FOCUS);
2397         gtk_container_add(GTK_CONTAINER(attach_scrwin), attach_clist);
2398
2399         gtk_signal_connect(GTK_OBJECT(attach_clist), "select_row",
2400                            GTK_SIGNAL_FUNC(attach_selected), compose);
2401         gtk_signal_connect(GTK_OBJECT(attach_clist), "button_press_event",
2402                            GTK_SIGNAL_FUNC(attach_button_pressed), compose);
2403         gtk_signal_connect(GTK_OBJECT(attach_clist), "key_press_event",
2404                            GTK_SIGNAL_FUNC(attach_key_pressed), compose);
2405
2406         /* drag and drop */
2407         gtk_drag_dest_set(attach_clist,
2408                           GTK_DEST_DEFAULT_ALL, compose_mime_types, 1,
2409                           GDK_ACTION_COPY);
2410         gtk_signal_connect(GTK_OBJECT(attach_clist), "drag_data_received",
2411                            GTK_SIGNAL_FUNC(compose_attach_drag_received_cb),
2412                            compose);
2413
2414         /* pane between attach clist and text */
2415         paned = gtk_vpaned_new();
2416         gtk_paned_add1(GTK_PANED(paned), attach_scrwin);
2417         gtk_widget_ref(paned);
2418         gtk_widget_show_all(paned);
2419
2420         edit_vbox = gtk_vbox_new(FALSE, 0);
2421         gtk_box_pack_start(GTK_BOX(vbox2), edit_vbox, TRUE, TRUE, 0);
2422
2423         /* ruler */
2424         ruler_hbox = gtk_hbox_new(FALSE, 0);
2425         gtk_box_pack_start(GTK_BOX(edit_vbox), ruler_hbox, FALSE, FALSE, 0);
2426
2427         ruler = gtk_shruler_new();
2428         gtk_ruler_set_range(GTK_RULER(ruler), 0.0, 100.0, 1.0, 100.0);
2429         gtk_box_pack_start(GTK_BOX(ruler_hbox), ruler, TRUE, TRUE,
2430                            BORDER_WIDTH + 1);
2431         gtk_widget_set_usize(ruler_hbox, 1, -1);
2432
2433         /* text widget */
2434         scrolledwin = gtk_scrolled_window_new(NULL, NULL);
2435         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin),
2436                                        GTK_POLICY_NEVER, GTK_POLICY_ALWAYS);
2437         gtk_box_pack_start(GTK_BOX(edit_vbox), scrolledwin, TRUE, TRUE, 0);
2438         gtk_widget_set_usize(scrolledwin, prefs_common.compose_width, -1);
2439
2440         text = gtk_stext_new(gtk_scrolled_window_get_hadjustment
2441                             (GTK_SCROLLED_WINDOW(scrolledwin)),
2442                             gtk_scrolled_window_get_vadjustment
2443                             (GTK_SCROLLED_WINDOW(scrolledwin)));
2444         gtk_stext_set_editable(GTK_STEXT(text), TRUE);
2445         gtk_stext_set_word_wrap(GTK_STEXT(text), TRUE);
2446         gtk_stext_set_wrap_rmargin(GTK_STEXT(text), prefs_common.linewrap_len);
2447
2448         gtk_container_add(GTK_CONTAINER(scrolledwin), text);
2449
2450         gtk_signal_connect(GTK_OBJECT(text), "changed",
2451                            GTK_SIGNAL_FUNC(compose_changed_cb), compose);
2452         gtk_signal_connect(GTK_OBJECT(text), "grab_focus",
2453                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
2454         gtk_signal_connect_after(GTK_OBJECT(text), "button_press_event",
2455                                  GTK_SIGNAL_FUNC(compose_button_press_cb),
2456                                  compose);
2457 #if 0
2458         gtk_signal_connect_after(GTK_OBJECT(text), "key_press_event",
2459                                  GTK_SIGNAL_FUNC(compose_key_press_cb),
2460                                  compose);
2461 #endif
2462         gtk_signal_connect_after(GTK_OBJECT(text), "size_allocate",
2463                                  GTK_SIGNAL_FUNC(compose_edit_size_alloc),
2464                                  ruler);
2465
2466         /* drag and drop */
2467         gtk_drag_dest_set(text, GTK_DEST_DEFAULT_ALL, compose_mime_types, 1,
2468                           GDK_ACTION_COPY);
2469         gtk_signal_connect(GTK_OBJECT(text), "drag_data_received",
2470                            GTK_SIGNAL_FUNC(compose_insert_drag_received_cb),
2471                            compose);
2472
2473         gtk_widget_show_all(vbox);
2474
2475         style = gtk_widget_get_style(text);
2476
2477         /* workaround for the slow down of GtkSText when using Pixmap theme */
2478         if (style->engine) {
2479                 GtkThemeEngine *engine;
2480
2481                 engine = style->engine;
2482                 style->engine = NULL;
2483                 new_style = gtk_style_copy(style);
2484                 style->engine = engine;
2485         } else
2486                 new_style = gtk_style_copy(style);
2487
2488         if (prefs_common.textfont) {
2489                 CharSet charset;
2490
2491                 charset = conv_get_current_charset();
2492                 if (MB_CUR_MAX == 1) {
2493                         gchar *fontstr, *p;
2494
2495                         Xstrdup_a(fontstr, prefs_common.textfont, );
2496                         if (fontstr && (p = strchr(fontstr, ',')) != NULL)
2497                                 *p = '\0';
2498                         font = gdk_font_load(fontstr);
2499                 } else
2500                         font = gdk_fontset_load(prefs_common.textfont);
2501                 if (font) {
2502                         gdk_font_unref(new_style->font);
2503                         new_style->font = font;
2504                 }
2505         }
2506
2507         gtk_widget_set_style(text, new_style);
2508
2509         color[0] = quote_color;
2510         cmap = gdk_window_get_colormap(window->window);
2511         gdk_colormap_alloc_colors(cmap, color, 1, FALSE, TRUE, success);
2512         if (success[0] == FALSE) {
2513                 g_warning("Compose: color allocation failed.\n");
2514                 style = gtk_widget_get_style(text);
2515                 quote_color = style->black;
2516         }
2517
2518         n_entries = sizeof(compose_popup_entries) /
2519                 sizeof(compose_popup_entries[0]);
2520         popupmenu = menu_create_items(compose_popup_entries, n_entries,
2521                                       "<Compose>", &popupfactory,
2522                                       compose);
2523
2524         ifactory = gtk_item_factory_from_widget(menubar);
2525         menu_set_sensitive(ifactory, "/Edit/Undo", FALSE);
2526         menu_set_sensitive(ifactory, "/Edit/Redo", FALSE);
2527
2528         gtk_widget_hide(bcc_hbox);
2529         gtk_widget_hide(bcc_entry);
2530         gtk_widget_hide(reply_hbox);
2531         gtk_widget_hide(reply_entry);
2532         gtk_widget_hide(followup_hbox);
2533         gtk_widget_hide(followup_entry);
2534         gtk_widget_hide(ruler_hbox);
2535         gtk_table_set_row_spacing(GTK_TABLE(table), 4, 0);
2536         gtk_table_set_row_spacing(GTK_TABLE(table), 5, 0);
2537         gtk_table_set_row_spacing(GTK_TABLE(table), 6, 0);
2538
2539         if (account->protocol == A_NNTP) {
2540                 gtk_widget_hide(to_hbox);
2541                 gtk_widget_hide(to_entry);
2542                 gtk_widget_hide(cc_hbox);
2543                 gtk_widget_hide(cc_entry);
2544                 gtk_table_set_row_spacing(GTK_TABLE(table), 1, 0);
2545                 gtk_table_set_row_spacing(GTK_TABLE(table), 3, 0);
2546         } else {
2547                 gtk_widget_hide(newsgroups_hbox);
2548                 gtk_widget_hide(newsgroups_entry);
2549                 gtk_table_set_row_spacing(GTK_TABLE(table), 2, 0);
2550                 menu_set_sensitive(ifactory, "/Message/Followup to", FALSE);
2551         }
2552
2553         switch (prefs_common.toolbar_style) {
2554         case TOOLBAR_NONE:
2555                 gtk_widget_hide(handlebox);
2556                 break;
2557         case TOOLBAR_ICON:
2558                 gtk_toolbar_set_style(GTK_TOOLBAR(compose->toolbar),
2559                                       GTK_TOOLBAR_ICONS);
2560                 break;
2561         case TOOLBAR_TEXT:
2562                 gtk_toolbar_set_style(GTK_TOOLBAR(compose->toolbar),
2563                                       GTK_TOOLBAR_TEXT);
2564                 break;
2565         case TOOLBAR_BOTH:
2566                 gtk_toolbar_set_style(GTK_TOOLBAR(compose->toolbar),
2567                                       GTK_TOOLBAR_BOTH);
2568                 break;
2569         }
2570
2571         gtk_widget_show(window);
2572
2573         address_completion_start(window);
2574
2575         compose->window        = window;
2576         compose->vbox          = vbox;
2577         compose->menubar       = menubar;
2578         compose->handlebox     = handlebox;
2579
2580         compose->vbox2         = vbox2;
2581
2582         compose->table_vbox       = table_vbox;
2583         compose->table            = table;
2584         compose->to_hbox          = to_hbox;
2585         compose->to_entry         = to_entry;
2586         compose->newsgroups_hbox  = newsgroups_hbox;
2587         compose->newsgroups_entry = newsgroups_entry;
2588         compose->subject_entry    = subject_entry;
2589         compose->cc_hbox          = cc_hbox;
2590         compose->cc_entry         = cc_entry;
2591         compose->bcc_hbox         = bcc_hbox;
2592         compose->bcc_entry        = bcc_entry;
2593         compose->reply_hbox       = reply_hbox;
2594         compose->reply_entry      = reply_entry;
2595         compose->followup_hbox    = followup_hbox;
2596         compose->followup_entry   = followup_entry;
2597
2598         compose->paned = paned;
2599
2600         compose->attach_scrwin = attach_scrwin;
2601         compose->attach_clist  = attach_clist;
2602
2603         compose->edit_vbox     = edit_vbox;
2604         compose->ruler_hbox    = ruler_hbox;
2605         compose->ruler         = ruler;
2606         compose->scrolledwin   = scrolledwin;
2607         compose->text          = text;
2608
2609         compose->focused_editable = NULL;
2610
2611         compose->popupmenu    = popupmenu;
2612         compose->popupfactory = popupfactory;
2613
2614         compose->mode = COMPOSE_NEW;
2615
2616         compose->replyto     = NULL;
2617         compose->cc          = NULL;
2618         compose->bcc         = NULL;
2619         compose->followup_to = NULL;
2620         compose->inreplyto   = NULL;
2621         compose->references  = NULL;
2622         compose->msgid       = NULL;
2623         compose->boundary    = NULL;
2624
2625         compose->use_to         = FALSE;
2626         compose->use_cc         = FALSE;
2627         compose->use_bcc        = FALSE;
2628         compose->use_replyto    = FALSE;
2629         compose->use_followupto = FALSE;
2630         compose->use_attach     = FALSE;
2631
2632 #if USE_GPGME
2633         compose->use_signing    = FALSE;
2634         compose->use_encryption = FALSE;
2635 #endif /* USE_GPGME */
2636
2637         compose->modified = FALSE;
2638
2639         compose->to_list        = NULL;
2640         compose->newsgroup_list = NULL;
2641
2642         compose->exteditor_file    = NULL;
2643         compose->exteditor_pid     = -1;
2644         compose->exteditor_readdes = -1;
2645         compose->exteditor_tag     = -1;
2646
2647         compose_set_title(compose);
2648
2649         if (account->protocol != A_NNTP) {
2650                 menuitem = gtk_item_factory_get_item(ifactory, "/Message/To");
2651                 gtk_check_menu_item_set_active
2652                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
2653                 gtk_widget_set_sensitive(menuitem, FALSE);
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                 gtk_widget_set_sensitive(menuitem, FALSE);
2658         }
2659         if (account->set_autocc && account->auto_cc) {
2660                 gtk_entry_set_text(GTK_ENTRY(cc_entry), account->auto_cc);
2661                 menuitem = gtk_item_factory_get_item(ifactory, "/Message/Cc");
2662                 gtk_check_menu_item_set_active
2663                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
2664         }
2665         if (account->set_autobcc && account->auto_bcc) {
2666                 gtk_entry_set_text(GTK_ENTRY(bcc_entry), account->auto_bcc);
2667                 menuitem = gtk_item_factory_get_item(ifactory, "/Message/Bcc");
2668                 gtk_check_menu_item_set_active
2669                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
2670         }
2671         if (account->set_autoreplyto && account->auto_replyto) {
2672                 gtk_entry_set_text(GTK_ENTRY(reply_entry),
2673                                    account->auto_replyto);
2674                 menuitem = gtk_item_factory_get_item(ifactory,
2675                                                      "/Message/Reply to");
2676                 gtk_check_menu_item_set_active
2677                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
2678         }
2679
2680         menuitem = gtk_item_factory_get_item(ifactory, "/Tool/Show ruler");
2681         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
2682                                        prefs_common.show_ruler);
2683
2684 #if USE_GPGME
2685         menuitem = gtk_item_factory_get_item(ifactory, "/Message/Sign");
2686         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
2687                                        prefs_common.default_sign);
2688         menuitem = gtk_item_factory_get_item(ifactory, "/Message/Encrypt");
2689         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
2690                                        prefs_common.default_encrypt);
2691 #endif /* USE_GPGME */
2692
2693         addressbook_set_target_compose(compose);
2694
2695         compose_list = g_list_append(compose_list, compose);
2696
2697         return compose;
2698 }
2699
2700 #include "pixmaps/stock_mail_send.xpm"
2701 #include "pixmaps/stock_mail.xpm"
2702 #include "pixmaps/stock_paste.xpm"
2703 #include "pixmaps/stock_mail_attach.xpm"
2704 #include "pixmaps/stock_mail_compose.xpm"
2705 #include "pixmaps/linewrap.xpm"
2706 //#include "pixmaps/tb_mail_queue_send.xpm"
2707 #include "pixmaps/tb_address_book.xpm"
2708
2709 #define CREATE_TOOLBAR_ICON(xpm_d) \
2710 { \
2711         icon = gdk_pixmap_create_from_xpm_d(container->window, &mask, \
2712                                             &container->style->white, \
2713                                             xpm_d); \
2714         icon_wid = gtk_pixmap_new(icon, mask); \
2715 }
2716
2717 static void compose_toolbar_create(Compose *compose, GtkWidget *container)
2718 {
2719         GtkWidget *toolbar;
2720         GdkPixmap *icon;
2721         GdkBitmap *mask;
2722         GtkWidget *icon_wid;
2723         GtkWidget *send_btn;
2724         GtkWidget *sendl_btn;
2725         GtkWidget *draft_btn;
2726         GtkWidget *insert_btn;
2727         GtkWidget *attach_btn;
2728         GtkWidget *sig_btn;
2729         GtkWidget *exteditor_btn;
2730         GtkWidget *linewrap_btn;
2731         GtkWidget *addrbook_btn;
2732
2733         toolbar = gtk_toolbar_new(GTK_ORIENTATION_HORIZONTAL,
2734                                   GTK_TOOLBAR_BOTH);
2735         gtk_container_add(GTK_CONTAINER(container), toolbar);
2736         gtk_container_set_border_width(GTK_CONTAINER(container), 2);
2737         gtk_toolbar_set_button_relief(GTK_TOOLBAR(toolbar), GTK_RELIEF_NONE);
2738         gtk_toolbar_set_space_style(GTK_TOOLBAR(toolbar),
2739                                     GTK_TOOLBAR_SPACE_LINE);
2740
2741         CREATE_TOOLBAR_ICON(stock_mail_send_xpm);
2742         send_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
2743                                            _("Send"),
2744                                            _("Send message"),
2745                                            "Send",
2746                                            icon_wid, toolbar_send_cb, compose);
2747
2748         CREATE_TOOLBAR_ICON(stock_mail_send_xpm);
2749         //CREATE_TOOLBAR_ICON(tb_mail_queue_send_xpm);
2750         sendl_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
2751                                            _("Send later"),
2752                                            _("Put into queue folder and send later"),
2753                                            "Send later",
2754                                            icon_wid, toolbar_send_later_cb,
2755                                            compose);
2756
2757         CREATE_TOOLBAR_ICON(stock_mail_xpm);
2758         draft_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
2759                                             _("Draft"),
2760                                             _("Save to draft folder"),
2761                                             "Draft",
2762                                             icon_wid, toolbar_draft_cb,
2763                                             compose);
2764
2765         gtk_toolbar_append_space(GTK_TOOLBAR(toolbar));
2766
2767         CREATE_TOOLBAR_ICON(stock_paste_xpm);
2768         insert_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
2769                                              _("Insert"),
2770                                              _("Insert file"),
2771                                              "Insert",
2772                                              icon_wid, toolbar_insert_cb,
2773                                              compose);
2774
2775         CREATE_TOOLBAR_ICON(stock_mail_attach_xpm);
2776         attach_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
2777                                              _("Attach"),
2778                                              _("Attach file"),
2779                                              "Attach",
2780                                              icon_wid, toolbar_attach_cb,
2781                                              compose);
2782
2783         gtk_toolbar_append_space(GTK_TOOLBAR(toolbar));
2784
2785         CREATE_TOOLBAR_ICON(stock_mail_xpm);
2786         sig_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
2787                                           _("Signature"),
2788                                           _("Insert signature"),
2789                                           "Signature",
2790                                           icon_wid, toolbar_sig_cb, compose);
2791
2792         gtk_toolbar_append_space(GTK_TOOLBAR(toolbar));
2793
2794         CREATE_TOOLBAR_ICON(stock_mail_compose_xpm);
2795         exteditor_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
2796                                                 _("Editor"),
2797                                                 _("Edit with external editor"),
2798                                                 "Editor",
2799                                                 icon_wid,
2800                                                 toolbar_ext_editor_cb,
2801                                                 compose);
2802
2803         CREATE_TOOLBAR_ICON(linewrap_xpm);
2804         linewrap_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
2805                                                _("Linewrap"),
2806                                                _("Wrap long lines"),
2807                                                "Linewrap",
2808                                                icon_wid,
2809                                                toolbar_linewrap_cb,
2810                                                compose);
2811
2812         gtk_toolbar_append_space(GTK_TOOLBAR(toolbar));
2813
2814         CREATE_TOOLBAR_ICON(tb_address_book_xpm);
2815         addrbook_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
2816                                                _("Address"),
2817                                                _("Address book"),
2818                                                "Address",
2819                                                icon_wid, toolbar_address_cb,
2820                                                compose);
2821
2822         compose->toolbar       = toolbar;
2823         compose->send_btn      = send_btn;
2824         compose->sendl_btn     = sendl_btn;
2825         compose->draft_btn     = draft_btn;
2826         compose->insert_btn    = insert_btn;
2827         compose->attach_btn    = attach_btn;
2828         compose->sig_btn       = sig_btn;
2829         compose->exteditor_btn = exteditor_btn;
2830         compose->linewrap_btn  = linewrap_btn;
2831         compose->addrbook_btn  = addrbook_btn;
2832
2833         gtk_widget_show_all(toolbar);
2834 }
2835
2836 static GtkWidget *compose_account_option_menu_create(Compose *compose)
2837 {
2838         GList *accounts;
2839         GtkWidget *hbox;
2840         GtkWidget *optmenu;
2841         GtkWidget *menu;
2842         gint num = 0, def_menu = 0;
2843
2844         accounts = account_get_list();
2845         g_return_val_if_fail(accounts != NULL, NULL);
2846
2847         hbox = gtk_hbox_new(FALSE, 0);
2848         optmenu = gtk_option_menu_new();
2849         gtk_box_pack_start(GTK_BOX(hbox), optmenu, FALSE, FALSE, 0);
2850         menu = gtk_menu_new();
2851
2852         for (; accounts != NULL; accounts = accounts->next, num++) {
2853                 PrefsAccount *ac = (PrefsAccount *)accounts->data;
2854                 GtkWidget *menuitem;
2855                 gchar *name;
2856
2857                 if (ac == compose->account) def_menu = num;
2858
2859                 name = g_strdup_printf("%s <%s> (%s)",
2860                                        ac->name, ac->address, ac->account_name);
2861                 MENUITEM_ADD(menu, menuitem, name, ac);
2862                 g_free(name);
2863                 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
2864                                    GTK_SIGNAL_FUNC(account_activated),
2865                                    compose);
2866         }
2867
2868         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), menu);
2869         gtk_option_menu_set_history(GTK_OPTION_MENU(optmenu), def_menu);
2870
2871         return hbox;
2872 }
2873
2874 static void compose_destroy(Compose *compose)
2875 {
2876         gint row;
2877         GtkCList *clist = GTK_CLIST(compose->attach_clist);
2878         AttachInfo *ainfo;
2879
2880         /* NOTE: address_completion_end() does nothing with the window
2881          * however this may change. */
2882         address_completion_end(compose->window);
2883
2884         slist_free_strings(compose->to_list);
2885         g_slist_free(compose->to_list);
2886         slist_free_strings(compose->newsgroup_list);
2887         g_slist_free(compose->newsgroup_list);
2888
2889         procmsg_msginfo_free(compose->targetinfo);
2890
2891         g_free(compose->replyto);
2892         g_free(compose->cc);
2893         g_free(compose->bcc);
2894         g_free(compose->newsgroups);
2895         g_free(compose->followup_to);
2896
2897         g_free(compose->inreplyto);
2898         g_free(compose->references);
2899         g_free(compose->msgid);
2900         g_free(compose->boundary);
2901
2902         g_free(compose->exteditor_file);
2903
2904         for (row = 0; (ainfo = gtk_clist_get_row_data(clist, row)) != NULL;
2905              row++)
2906                 compose_attach_info_free(ainfo);
2907
2908         if (addressbook_get_target_compose() == compose)
2909                 addressbook_set_target_compose(NULL);
2910
2911         prefs_common.compose_width = compose->scrolledwin->allocation.width;
2912         prefs_common.compose_height = compose->window->allocation.height;
2913
2914         gtk_widget_destroy(compose->paned);
2915
2916         g_free(compose);
2917
2918         compose_list = g_list_remove(compose_list, compose);
2919 }
2920
2921 static void compose_attach_info_free(AttachInfo *ainfo)
2922 {
2923         g_free(ainfo->file);
2924         g_free(ainfo->content_type);
2925         g_free(ainfo->name);
2926         g_free(ainfo);
2927 }
2928
2929 static void compose_attach_remove_selected(Compose *compose)
2930 {
2931         GtkCList *clist = GTK_CLIST(compose->attach_clist);
2932         AttachInfo *ainfo;
2933         gint row;
2934
2935         while (clist->selection != NULL) {
2936                 row = GPOINTER_TO_INT(clist->selection->data);
2937                 ainfo = gtk_clist_get_row_data(clist, row);
2938                 compose_attach_info_free(ainfo);
2939                 gtk_clist_remove(clist, row);
2940         }
2941 }
2942
2943 static struct _AttachProperty
2944 {
2945         GtkWidget *window;
2946         GtkWidget *mimetype_entry;
2947         GtkWidget *encoding_optmenu;
2948         GtkWidget *path_entry;
2949         GtkWidget *filename_entry;
2950         GtkWidget *ok_btn;
2951         GtkWidget *cancel_btn;
2952 } attach_prop;
2953
2954 static void compose_attach_property(Compose *compose)
2955 {
2956         GtkCList *clist = GTK_CLIST(compose->attach_clist);
2957         AttachInfo *ainfo;
2958         gint row;
2959         gboolean cancelled;
2960         GtkOptionMenu *optmenu;
2961
2962         if (!clist->selection) return;
2963         row = GPOINTER_TO_INT(clist->selection->data);
2964
2965         ainfo = gtk_clist_get_row_data(clist, row);
2966         if (!ainfo) return;
2967
2968         if (!attach_prop.window)
2969                 compose_attach_property_create(&cancelled);
2970         gtk_widget_grab_focus(attach_prop.ok_btn);
2971         gtk_widget_show(attach_prop.window);
2972         manage_window_set_transient(GTK_WINDOW(attach_prop.window));
2973
2974         optmenu = GTK_OPTION_MENU(attach_prop.encoding_optmenu);
2975         if (ainfo->encoding == ENC_UNKNOWN)
2976                 gtk_option_menu_set_history(optmenu, ENC_BASE64);
2977         else
2978                 gtk_option_menu_set_history(optmenu, ainfo->encoding);
2979
2980         gtk_entry_set_text(GTK_ENTRY(attach_prop.mimetype_entry),
2981                            ainfo->content_type ? ainfo->content_type : "");
2982         gtk_entry_set_text(GTK_ENTRY(attach_prop.path_entry),
2983                            ainfo->file ? ainfo->file : "");
2984         gtk_entry_set_text(GTK_ENTRY(attach_prop.filename_entry),
2985                            ainfo->name ? ainfo->name : "");
2986
2987         for (;;) {
2988                 gchar *text;
2989                 gchar *cnttype = NULL;
2990                 gchar *file = NULL;
2991                 off_t size = 0;
2992                 GtkWidget *menu;
2993                 GtkWidget *menuitem;
2994
2995                 gtk_main();
2996
2997                 if (cancelled == TRUE) {
2998                         gtk_widget_hide(attach_prop.window);
2999                         break;
3000                 }
3001
3002                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.mimetype_entry));
3003                 if (*text != '\0') {
3004                         gchar *p;
3005
3006                         text = g_strstrip(g_strdup(text));
3007                         if ((p = strchr(text, '/')) && !strchr(p + 1, '/')) {
3008                                 cnttype = g_strdup(text);
3009                                 g_free(text);
3010                         } else {
3011                                 alertpanel_error(_("Invalid MIME type."));
3012                                 g_free(text);
3013                                 continue;
3014                         }
3015                 }
3016
3017                 menu = gtk_option_menu_get_menu(optmenu);
3018                 menuitem = gtk_menu_get_active(GTK_MENU(menu));
3019                 ainfo->encoding = GPOINTER_TO_INT
3020                         (gtk_object_get_user_data(GTK_OBJECT(menuitem)));
3021
3022                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.path_entry));
3023                 if (*text != '\0') {
3024                         if (is_file_exist(text) &&
3025                             (size = get_file_size(text)) > 0)
3026                                 file = g_strdup(text);
3027                         else {
3028                                 alertpanel_error
3029                                         (_("File doesn't exist or is empty."));
3030                                 g_free(cnttype);
3031                                 continue;
3032                         }
3033                 }
3034
3035                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.filename_entry));
3036                 if (*text != '\0') {
3037                         g_free(ainfo->name);
3038                         ainfo->name = g_strdup(text);
3039                 }
3040
3041                 if (cnttype) {
3042                         g_free(ainfo->content_type);
3043                         ainfo->content_type = cnttype;
3044                 }
3045                 if (file) {
3046                         g_free(ainfo->file);
3047                         ainfo->file = file;
3048                 }
3049                 if (size)
3050                         ainfo->size = size;
3051
3052                 gtk_clist_set_text(clist, row, COL_MIMETYPE,
3053                                    ainfo->content_type);
3054                 gtk_clist_set_text(clist, row, COL_SIZE,
3055                                    to_human_readable(ainfo->size));
3056                 gtk_clist_set_text(clist, row, COL_NAME, ainfo->name);
3057
3058                 gtk_widget_hide(attach_prop.window);
3059                 break;
3060         }
3061 }
3062
3063 #define SET_LABEL_AND_ENTRY(str, entry, top) \
3064 { \
3065         label = gtk_label_new(str); \
3066         gtk_table_attach(GTK_TABLE(table), label, 0, 1, top, (top + 1), \
3067                          GTK_FILL, 0, 0, 0); \
3068         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); \
3069  \
3070         entry = gtk_entry_new(); \
3071         gtk_table_attach(GTK_TABLE(table), entry, 1, 2, top, (top + 1), \
3072                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0); \
3073 }
3074
3075 static void compose_attach_property_create(gboolean *cancelled)
3076 {
3077         GtkWidget *window;
3078         GtkWidget *vbox;
3079         GtkWidget *table;
3080         GtkWidget *label;
3081         GtkWidget *mimetype_entry;
3082         GtkWidget *hbox;
3083         GtkWidget *optmenu;
3084         GtkWidget *optmenu_menu;
3085         GtkWidget *menuitem;
3086         GtkWidget *path_entry;
3087         GtkWidget *filename_entry;
3088         GtkWidget *hbbox;
3089         GtkWidget *ok_btn;
3090         GtkWidget *cancel_btn;
3091
3092         debug_print("Creating attach_property window...\n");
3093
3094         window = gtk_window_new(GTK_WINDOW_DIALOG);
3095         gtk_widget_set_usize(window, 480, -1);
3096         gtk_container_set_border_width(GTK_CONTAINER(window), 8);
3097         gtk_window_set_title(GTK_WINDOW(window), _("Property"));
3098         gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
3099         gtk_window_set_modal(GTK_WINDOW(window), TRUE);
3100         gtk_signal_connect(GTK_OBJECT(window), "delete_event",
3101                            GTK_SIGNAL_FUNC(attach_property_delete_event),
3102                            cancelled);
3103         gtk_signal_connect(GTK_OBJECT(window), "key_press_event",
3104                            GTK_SIGNAL_FUNC(attach_property_key_pressed),
3105                            cancelled);
3106
3107         vbox = gtk_vbox_new(FALSE, 8);
3108         gtk_container_add(GTK_CONTAINER(window), vbox);
3109
3110         table = gtk_table_new(4, 2, FALSE);
3111         gtk_box_pack_start(GTK_BOX(vbox), table, FALSE, FALSE, 0);
3112         gtk_table_set_row_spacings(GTK_TABLE(table), 8);
3113         gtk_table_set_col_spacings(GTK_TABLE(table), 8);
3114
3115         SET_LABEL_AND_ENTRY(_("MIME type"), mimetype_entry, 0);
3116
3117         label = gtk_label_new(_("Encoding"));
3118         gtk_table_attach(GTK_TABLE(table), label, 0, 1, 1, 2,
3119                          GTK_FILL, 0, 0, 0);
3120         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5);
3121
3122         hbox = gtk_hbox_new(FALSE, 0);
3123         gtk_table_attach(GTK_TABLE(table), hbox, 1, 2, 1, 2,
3124                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0);
3125
3126         optmenu = gtk_option_menu_new();
3127         gtk_box_pack_start(GTK_BOX(hbox), optmenu, FALSE, FALSE, 0);
3128
3129         optmenu_menu = gtk_menu_new();
3130         MENUITEM_ADD(optmenu_menu, menuitem, "7bit", ENC_7BIT);
3131         gtk_widget_set_sensitive(menuitem, FALSE);
3132         MENUITEM_ADD(optmenu_menu, menuitem, "8bit", ENC_8BIT);
3133         gtk_widget_set_sensitive(menuitem, FALSE);
3134         MENUITEM_ADD(optmenu_menu, menuitem, "quoted-printable", ENC_QUOTED_PRINTABLE);
3135         gtk_widget_set_sensitive(menuitem, FALSE);
3136         MENUITEM_ADD(optmenu_menu, menuitem, "base64", ENC_BASE64);
3137
3138         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
3139
3140         SET_LABEL_AND_ENTRY(_("Path"),      path_entry,     2);
3141         SET_LABEL_AND_ENTRY(_("File name"), filename_entry, 3);
3142
3143         gtkut_button_set_create(&hbbox, &ok_btn, _("OK"),
3144                                 &cancel_btn, _("Cancel"), NULL, NULL);
3145         gtk_box_pack_end(GTK_BOX(vbox), hbbox, FALSE, FALSE, 0);
3146         gtk_widget_grab_default(ok_btn);
3147
3148         gtk_signal_connect(GTK_OBJECT(ok_btn), "clicked",
3149                            GTK_SIGNAL_FUNC(attach_property_ok),
3150                            cancelled);
3151         gtk_signal_connect(GTK_OBJECT(cancel_btn), "clicked",
3152                            GTK_SIGNAL_FUNC(attach_property_cancel),
3153                            cancelled);
3154
3155         gtk_widget_show_all(vbox);
3156
3157         attach_prop.window           = window;
3158         attach_prop.mimetype_entry   = mimetype_entry;
3159         attach_prop.encoding_optmenu = optmenu;
3160         attach_prop.path_entry       = path_entry;
3161         attach_prop.filename_entry   = filename_entry;
3162         attach_prop.ok_btn           = ok_btn;
3163         attach_prop.cancel_btn       = cancel_btn;
3164 }
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 }