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