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