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