* src/imap.c
[claws.git] / src / compose.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2002 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 <sys/types.h>
57 #include <sys/stat.h>
58 #include <unistd.h>
59 #include <time.h>
60 /* #include <sys/utsname.h> */
61 #include <stdlib.h>
62 #include <sys/wait.h>
63 #include <signal.h>
64 #include <errno.h>
65
66 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
67 #  include <wchar.h>
68 #  include <wctype.h>
69 #endif
70
71 #include "intl.h"
72 #include "main.h"
73 #include "mainwindow.h"
74 #include "compose.h"
75 #include "gtkstext.h"
76 #include "addressbook.h"
77 #include "folderview.h"
78 #include "procmsg.h"
79 #include "menu.h"
80 #include "stock_pixmap.h"
81 #include "send.h"
82 #include "imap.h"
83 #include "news.h"
84 #include "customheader.h"
85 #include "prefs_common.h"
86 #include "prefs_account.h"
87 #include "account.h"
88 #include "filesel.h"
89 #include "procheader.h"
90 #include "procmime.h"
91 #include "statusbar.h"
92 #include "about.h"
93 #include "base64.h"
94 #include "codeconv.h"
95 #include "utils.h"
96 #include "gtkutils.h"
97 #include "socket.h"
98 #include "alertpanel.h"
99 #include "manage_window.h"
100 #include "gtkshruler.h"
101 #include "folder.h"
102 #include "addr_compl.h"
103 #include "quote_fmt.h"
104 #include "template.h"
105 #include "undo.h"
106 #include "foldersel.h"
107 #include "prefs_actions.h"
108
109 #if USE_GPGME
110 #  include "rfc2015.h"
111 #endif
112
113 typedef enum
114 {
115         COL_MIMETYPE = 0,
116         COL_SIZE     = 1,
117         COL_NAME     = 2
118 } AttachColumnPos;
119
120 #define N_ATTACH_COLS           3
121
122 typedef enum
123 {
124         COMPOSE_CALL_GTK_STEXT_MOVE_BEGINNING_OF_LINE,
125         COMPOSE_CALL_GTK_STEXT_MOVE_FORWARD_CHARACTER,
126         COMPOSE_CALL_GTK_STEXT_MOVE_BACKWARD_CHARACTER,
127         COMPOSE_CALL_GTK_STEXT_MOVE_FORWARD_WORD,
128         COMPOSE_CALL_GTK_STEXT_MOVE_BACKWARD_WORD,
129         COMPOSE_CALL_GTK_STEXT_MOVE_END_OF_LINE,
130         COMPOSE_CALL_GTK_STEXT_MOVE_NEXT_LINE,
131         COMPOSE_CALL_GTK_STEXT_MOVE_PREVIOUS_LINE,
132         COMPOSE_CALL_GTK_STEXT_DELETE_FORWARD_CHARACTER,
133         COMPOSE_CALL_GTK_STEXT_DELETE_BACKWARD_CHARACTER,
134         COMPOSE_CALL_GTK_STEXT_DELETE_FORWARD_WORD,
135         COMPOSE_CALL_GTK_STEXT_DELETE_BACKWARD_WORD,
136         COMPOSE_CALL_GTK_STEXT_DELETE_LINE,
137         COMPOSE_CALL_GTK_STEXT_DELETE_LINE_N,
138         COMPOSE_CALL_GTK_STEXT_DELETE_TO_LINE_END
139 } ComposeCallGtkSTextAction;
140
141 typedef enum
142 {
143         PRIORITY_HIGHEST = 1,
144         PRIORITY_HIGH,
145         PRIORITY_NORMAL,
146         PRIORITY_LOW,
147         PRIORITY_LOWEST
148 } PriorityLevel;
149
150 #define B64_LINE_SIZE           57
151 #define B64_BUFFSIZE            77
152
153 #define MAX_REFERENCES_LEN      999
154
155 static GdkColor quote_color = {0, 0, 0, 0xbfff};
156
157 static GList *compose_list = NULL;
158
159 Compose *compose_generic_new                    (PrefsAccount   *account,
160                                                  const gchar    *to,
161                                                  FolderItem     *item);
162
163 static Compose *compose_create                  (PrefsAccount   *account,
164                                                  ComposeMode     mode);
165 static void compose_toolbar_create              (Compose        *compose,
166                                                  GtkWidget      *container);
167 static GtkWidget *compose_account_option_menu_create
168                                                 (Compose        *compose);
169 static void compose_set_template_menu           (Compose        *compose);
170 static void compose_template_apply              (Compose        *compose,
171                                                  Template       *tmpl,
172                                                  gboolean        replace);
173 static void compose_destroy                     (Compose        *compose);
174
175 static void compose_entries_set                 (Compose        *compose,
176                                                  const gchar    *mailto);
177 static gint compose_parse_header                (Compose        *compose,
178                                                  MsgInfo        *msginfo);
179 static gchar *compose_parse_references          (const gchar    *ref,
180                                                  const gchar    *msgid);
181
182 static gchar *compose_quote_fmt                 (Compose        *compose,
183                                                  MsgInfo        *msginfo,
184                                                  const gchar    *fmt,
185                                                  const gchar    *qmark,
186                                                  const gchar    *body);
187
188 static void compose_reply_set_entry             (Compose        *compose,
189                                                  MsgInfo        *msginfo,
190                                                  gboolean        to_all,
191                                                  gboolean        to_sender,
192                                                  gboolean
193                                                  followup_and_reply_to);
194 static void compose_reedit_set_entry            (Compose        *compose,
195                                                  MsgInfo        *msginfo);
196 static void compose_insert_sig                  (Compose        *compose);
197 static void compose_insert_file                 (Compose        *compose,
198                                                  const gchar    *file);
199 static void compose_attach_append               (Compose        *compose,
200                                                  const gchar    *file,
201                                                  const gchar    *type,
202                                                  const gchar    *content_type);
203 static void compose_attach_parts                (Compose        *compose,
204                                                  MsgInfo        *msginfo);
205 static void compose_wrap_line                   (Compose        *compose);
206 static void compose_wrap_line_all               (Compose        *compose);
207 static void compose_set_title                   (Compose        *compose);
208
209 static PrefsAccount *compose_current_mail_account(void);
210 /* static gint compose_send                     (Compose        *compose); */
211 static gboolean compose_check_for_valid_recipient
212                                                 (Compose        *compose);
213 static gboolean compose_check_entries           (Compose        *compose,
214                                                  gboolean       check_subject);
215 static gint compose_write_to_file               (Compose        *compose,
216                                                  const gchar    *file,
217                                                  gboolean        is_draft);
218 static gint compose_write_body_to_file          (Compose        *compose,
219                                                  const gchar    *file);
220 static gint compose_remove_reedit_target        (Compose        *compose);
221 static gint compose_queue                       (Compose        *compose,
222                                                  gint           *msgnum,
223                                                  FolderItem     **item);
224 static gint compose_queue_sub                   (Compose        *compose,
225                                                  gint           *msgnum,
226                                                  FolderItem     **item,
227                                                  gboolean       check_subject);
228 static void compose_write_attach                (Compose        *compose,
229                                                  FILE           *fp);
230 static gint compose_write_headers               (Compose        *compose,
231                                                  FILE           *fp,
232                                                  const gchar    *charset,
233                                                  EncodingType    encoding,
234                                                  gboolean        is_draft);
235
236 static void compose_convert_header              (gchar          *dest,
237                                                  gint            len,
238                                                  gchar          *src,
239                                                  gint            header_len);
240 static void compose_generate_msgid              (Compose        *compose,
241                                                  gchar          *buf,
242                                                  gint            len);
243
244 static void compose_attach_info_free            (AttachInfo     *ainfo);
245 static void compose_attach_remove_selected      (Compose        *compose);
246
247 static void compose_attach_property             (Compose        *compose);
248 static void compose_attach_property_create      (gboolean       *cancelled);
249 static void attach_property_ok                  (GtkWidget      *widget,
250                                                  gboolean       *cancelled);
251 static void attach_property_cancel              (GtkWidget      *widget,
252                                                  gboolean       *cancelled);
253 static gint attach_property_delete_event        (GtkWidget      *widget,
254                                                  GdkEventAny    *event,
255                                                  gboolean       *cancelled);
256 static void attach_property_key_pressed         (GtkWidget      *widget,
257                                                  GdkEventKey    *event,
258                                                  gboolean       *cancelled);
259
260 static void compose_exec_ext_editor             (Compose           *compose);
261 static gint compose_exec_ext_editor_real        (const gchar       *file);
262 static gboolean compose_ext_editor_kill         (Compose           *compose);
263 static void compose_input_cb                    (gpointer           data,
264                                                  gint               source,
265                                                  GdkInputCondition  condition);
266 static void compose_set_ext_editor_sensitive    (Compose           *compose,
267                                                  gboolean           sensitive);
268
269 static void compose_undo_state_changed          (UndoMain       *undostruct,
270                                                  gint            undo_state,
271                                                  gint            redo_state,
272                                                  gpointer        data);
273
274 static gint calc_cursor_xpos    (GtkSText       *text,
275                                  gint            extra,
276                                  gint            char_width);
277
278 static void compose_create_header_entry (Compose *compose);
279 static void compose_add_header_entry    (Compose *compose, gchar *header, gchar *text);
280 static void compose_update_priority_menu_item(Compose * compose);
281
282 /* callback functions */
283
284 static gboolean compose_edit_size_alloc (GtkEditable    *widget,
285                                          GtkAllocation  *allocation,
286                                          GtkSHRuler     *shruler);
287
288 static void toolbar_send_cb             (GtkWidget      *widget,
289                                          gpointer        data);
290 static void toolbar_send_later_cb       (GtkWidget      *widget,
291                                          gpointer        data);
292 static void toolbar_draft_cb            (GtkWidget      *widget,
293                                          gpointer        data);
294 static void toolbar_insert_cb           (GtkWidget      *widget,
295                                          gpointer        data);
296 static void toolbar_attach_cb           (GtkWidget      *widget,
297                                          gpointer        data);
298 static void toolbar_sig_cb              (GtkWidget      *widget,
299                                          gpointer        data);
300 static void toolbar_ext_editor_cb       (GtkWidget      *widget,
301                                          gpointer        data);
302 static void toolbar_linewrap_cb         (GtkWidget      *widget,
303                                          gpointer        data);
304 static void toolbar_address_cb          (GtkWidget      *widget,
305                                          gpointer        data);
306
307 static void select_account              (Compose        *compose,
308                                          PrefsAccount   *ac);
309
310 static void account_activated           (GtkMenuItem    *menuitem,
311                                          gpointer        data);
312
313 static void attach_selected             (GtkCList       *clist,
314                                          gint            row,
315                                          gint            column,
316                                          GdkEvent       *event,
317                                          gpointer        data);
318 static void attach_button_pressed       (GtkWidget      *widget,
319                                          GdkEventButton *event,
320                                          gpointer        data);
321 static void attach_key_pressed          (GtkWidget      *widget,
322                                          GdkEventKey    *event,
323                                          gpointer        data);
324
325 static void compose_send_cb             (gpointer        data,
326                                          guint           action,
327                                          GtkWidget      *widget);
328 static void compose_send_later_cb       (gpointer        data,
329                                          guint           action,
330                                          GtkWidget      *widget);
331
332 static void compose_draft_cb            (gpointer        data,
333                                          guint           action,
334                                          GtkWidget      *widget);
335
336 static void compose_attach_cb           (gpointer        data,
337                                          guint           action,
338                                          GtkWidget      *widget);
339 static void compose_insert_file_cb      (gpointer        data,
340                                          guint           action,
341                                          GtkWidget      *widget);
342
343 static void compose_close_cb            (gpointer        data,
344                                          guint           action,
345                                          GtkWidget      *widget);
346
347 static void compose_address_cb          (gpointer        data,
348                                          guint           action,
349                                          GtkWidget      *widget);
350 static void compose_template_activate_cb(GtkWidget      *widget,
351                                          gpointer        data);
352
353 static void compose_ext_editor_cb       (gpointer        data,
354                                          guint           action,
355                                          GtkWidget      *widget);
356
357 static gint compose_delete_cb           (GtkWidget      *widget,
358                                          GdkEventAny    *event,
359                                          gpointer        data);
360 static void compose_destroy_cb          (GtkWidget      *widget,
361                                          Compose        *compose);
362
363 static void compose_undo_cb             (Compose        *compose);
364 static void compose_redo_cb             (Compose        *compose);
365 static void compose_cut_cb              (Compose        *compose);
366 static void compose_copy_cb             (Compose        *compose);
367 static void compose_paste_cb            (Compose        *compose);
368 static void compose_paste_as_quote_cb   (Compose        *compose);
369 static void compose_allsel_cb           (Compose        *compose);
370
371 static void compose_gtk_stext_action_cb (Compose                   *compose,
372                                          ComposeCallGtkSTextAction  action);
373
374 static void compose_grab_focus_cb       (GtkWidget      *widget,
375                                          Compose        *compose);
376
377 static void compose_changed_cb          (GtkEditable    *editable,
378                                          Compose        *compose);
379 static void compose_button_press_cb     (GtkWidget      *widget,
380                                          GdkEventButton *event,
381                                          Compose        *compose);
382 #if 0
383 static void compose_key_press_cb        (GtkWidget      *widget,
384                                          GdkEventKey    *event,
385                                          Compose        *compose);
386 #endif
387
388 #if 0
389 static void compose_toggle_to_cb        (gpointer        data,
390                                          guint           action,
391                                          GtkWidget      *widget);
392 static void compose_toggle_cc_cb        (gpointer        data,
393                                          guint           action,
394                                          GtkWidget      *widget);
395 static void compose_toggle_bcc_cb       (gpointer        data,
396                                          guint           action,
397                                          GtkWidget      *widget);
398 static void compose_toggle_replyto_cb   (gpointer        data,
399                                          guint           action,
400                                          GtkWidget      *widget);
401 static void compose_toggle_followupto_cb(gpointer        data,
402                                          guint           action,
403                                          GtkWidget      *widget);
404 static void compose_toggle_attach_cb    (gpointer        data,
405                                          guint           action,
406                                          GtkWidget      *widget);
407 #endif
408 static void compose_toggle_ruler_cb     (gpointer        data,
409                                          guint           action,
410                                          GtkWidget      *widget);
411 #if USE_GPGME
412 static void compose_toggle_sign_cb      (gpointer        data,
413                                          guint           action,
414                                          GtkWidget      *widget);
415 static void compose_toggle_encrypt_cb   (gpointer        data,
416                                          guint           action,
417                                          GtkWidget      *widget);
418 #endif
419 static void compose_toggle_return_receipt_cb(gpointer data, guint action,
420                                              GtkWidget *widget);
421 static void compose_set_priority_cb     (gpointer        data,
422                                          guint           action,
423                                          GtkWidget      *widget);
424
425 static void compose_attach_drag_received_cb (GtkWidget          *widget,
426                                              GdkDragContext     *drag_context,
427                                              gint                x,
428                                              gint                y,
429                                              GtkSelectionData   *data,
430                                              guint               info,
431                                              guint               time,
432                                              gpointer            user_data);
433 static void compose_insert_drag_received_cb (GtkWidget          *widget,
434                                              GdkDragContext     *drag_context,
435                                              gint                x,
436                                              gint                y,
437                                              GtkSelectionData   *data,
438                                              guint               info,
439                                              guint               time,
440                                              gpointer            user_data);
441
442 #if 0
443 static void to_activated                (GtkWidget      *widget,
444                                          Compose        *compose);
445 static void newsgroups_activated        (GtkWidget      *widget,
446                                          Compose        *compose);
447 static void cc_activated                (GtkWidget      *widget,
448                                          Compose        *compose);
449 static void bcc_activated               (GtkWidget      *widget,
450                                          Compose        *compose);
451 static void replyto_activated           (GtkWidget      *widget,
452                                          Compose        *compose);
453 static void followupto_activated        (GtkWidget      *widget,
454                                          Compose        *compose);
455 static void subject_activated           (GtkWidget      *widget,
456                                          Compose        *compose);
457 #endif
458
459 static void text_activated              (GtkWidget      *widget,
460                                          Compose        *compose);
461 static void text_inserted               (GtkWidget      *widget,
462                                          const gchar    *text,
463                                          gint            length,
464                                          gint           *position,
465                                          Compose        *compose);
466 static void compose_generic_reply(MsgInfo *msginfo, gboolean quote,
467                                   gboolean to_all,
468                                   gboolean ignore_replyto,
469                                   gboolean followup_and_reply_to,
470                                   const gchar *body);
471
472 void compose_headerentry_changed_cb        (GtkWidget          *entry,
473                                             ComposeHeaderEntry *headerentry);
474 void compose_headerentry_key_press_event_cb(GtkWidget          *entry,
475                                             GdkEventKey        *event,
476                                             ComposeHeaderEntry *headerentry);
477
478 static void compose_show_first_last_header (Compose *compose, gboolean show_first);
479
480 #if USE_PSPELL
481 static void compose_check_all              (Compose *compose);
482 static void compose_highlight_all          (Compose *compose);
483 static void compose_check_backwards        (Compose *compose);
484 static void compose_check_forwards_go      (Compose *compose);
485 #endif
486
487 static gboolean compose_send_control_enter      (Compose        *compose);
488
489 static GtkItemFactoryEntry compose_popup_entries[] =
490 {
491         {N_("/_Add..."),        NULL, compose_attach_cb, 0, NULL},
492         {N_("/_Remove"),        NULL, compose_attach_remove_selected, 0, NULL},
493         {N_("/---"),            NULL, NULL, 0, "<Separator>"},
494         {N_("/_Property..."),   NULL, compose_attach_property, 0, NULL}
495 };
496
497 static GtkItemFactoryEntry compose_entries[] =
498 {
499         {N_("/_File"),                          NULL, NULL, 0, "<Branch>"},
500         {N_("/_File/_Attach file"),             "<control>M", compose_attach_cb,      0, NULL},
501         {N_("/_File/_Insert file"),             "<control>I", compose_insert_file_cb, 0, NULL},
502         {N_("/_File/Insert si_gnature"),        "<control>G", compose_insert_sig,     0, NULL},
503         {N_("/_File/---"),                      NULL, NULL, 0, "<Separator>"},
504         {N_("/_File/_Close"),                   "<control>W", compose_close_cb, 0, NULL},
505
506         {N_("/_Edit"),                  NULL, NULL, 0, "<Branch>"},
507         {N_("/_Edit/_Undo"),            "<control>Z", compose_undo_cb, 0, NULL},
508         {N_("/_Edit/_Redo"),            "<control>Y", compose_redo_cb, 0, NULL},
509         {N_("/_Edit/---"),              NULL, NULL, 0, "<Separator>"},
510         {N_("/_Edit/Cu_t"),             "<control>X", compose_cut_cb,    0, NULL},
511         {N_("/_Edit/_Copy"),            "<control>C", compose_copy_cb,   0, NULL},
512         {N_("/_Edit/_Paste"),           "<control>V", compose_paste_cb,  0, NULL},
513         {N_("/_Edit/Paste as _quotation"),
514                                         NULL, compose_paste_as_quote_cb, 0, NULL},
515         {N_("/_Edit/Select _all"),      "<control>A", compose_allsel_cb, 0, NULL},
516         {N_("/_Edit/A_dvanced"),        NULL, NULL, 0, "<Branch>"},
517         {N_("/_Edit/A_dvanced/Move a character backward"),
518                                         "<control>B",
519                                         compose_gtk_stext_action_cb,
520                                         COMPOSE_CALL_GTK_STEXT_MOVE_BACKWARD_CHARACTER,
521                                         NULL},
522         {N_("/_Edit/A_dvanced/Move a character forward"),
523                                         "<control>F",
524                                         compose_gtk_stext_action_cb,
525                                         COMPOSE_CALL_GTK_STEXT_MOVE_FORWARD_CHARACTER,
526                                         NULL},
527         {N_("/_Edit/A_dvanced/Move a word backward"),
528                                         NULL, /* "<alt>B" */
529                                         compose_gtk_stext_action_cb,
530                                         COMPOSE_CALL_GTK_STEXT_MOVE_BACKWARD_WORD,
531                                         NULL},
532         {N_("/_Edit/A_dvanced/Move a word forward"),
533                                         NULL, /* "<alt>F" */
534                                         compose_gtk_stext_action_cb,
535                                         COMPOSE_CALL_GTK_STEXT_MOVE_FORWARD_WORD,
536                                         NULL},
537         {N_("/_Edit/A_dvanced/Move to beginning of line"),
538                                         NULL, /* "<control>A" */
539                                         compose_gtk_stext_action_cb,
540                                         COMPOSE_CALL_GTK_STEXT_MOVE_BEGINNING_OF_LINE,
541                                         NULL},
542         {N_("/_Edit/A_dvanced/Move to end of line"),
543                                         "<control>E",
544                                         compose_gtk_stext_action_cb,
545                                         COMPOSE_CALL_GTK_STEXT_MOVE_END_OF_LINE,
546                                         NULL},
547         {N_("/_Edit/A_dvanced/Move to previous line"),
548                                         "<control>P",
549                                         compose_gtk_stext_action_cb,
550                                         COMPOSE_CALL_GTK_STEXT_MOVE_PREVIOUS_LINE,
551                                         NULL},
552         {N_("/_Edit/A_dvanced/Move to next line"),
553                                         "<control>N",
554                                         compose_gtk_stext_action_cb,
555                                         COMPOSE_CALL_GTK_STEXT_MOVE_NEXT_LINE,
556                                         NULL},
557         {N_("/_Edit/A_dvanced/Delete a character backward"),
558                                         "<control>H",
559                                         compose_gtk_stext_action_cb,
560                                         COMPOSE_CALL_GTK_STEXT_DELETE_BACKWARD_CHARACTER,
561                                         NULL},
562         {N_("/_Edit/A_dvanced/Delete a character forward"),
563                                         "<control>D",
564                                         compose_gtk_stext_action_cb,
565                                         COMPOSE_CALL_GTK_STEXT_DELETE_FORWARD_CHARACTER,
566                                         NULL},
567         {N_("/_Edit/A_dvanced/Delete a word backward"),
568                                         NULL, /* "<control>W" */
569                                         compose_gtk_stext_action_cb,
570                                         COMPOSE_CALL_GTK_STEXT_DELETE_BACKWARD_WORD,
571                                         NULL},
572         {N_("/_Edit/A_dvanced/Delete a word forward"),
573                                         NULL, /* "<alt>D", */
574                                         compose_gtk_stext_action_cb,
575                                         COMPOSE_CALL_GTK_STEXT_DELETE_FORWARD_WORD,
576                                         NULL},
577         {N_("/_Edit/A_dvanced/Delete line"),
578                                         "<control>U",
579                                         compose_gtk_stext_action_cb,
580                                         COMPOSE_CALL_GTK_STEXT_DELETE_LINE,
581                                         NULL},
582         {N_("/_Edit/A_dvanced/Delete entire line"),
583                                         NULL,
584                                         compose_gtk_stext_action_cb,
585                                         COMPOSE_CALL_GTK_STEXT_DELETE_LINE_N,
586                                         NULL},
587         {N_("/_Edit/A_dvanced/Delete to end of line"),
588                                         "<control>K",
589                                         compose_gtk_stext_action_cb,
590                                         COMPOSE_CALL_GTK_STEXT_DELETE_TO_LINE_END,
591                                         NULL},
592         {N_("/_Edit/---"),              NULL, NULL, 0, "<Separator>"},
593         {N_("/_Edit/_Wrap current paragraph"),
594                                         "<control>L", compose_wrap_line, 0, NULL},
595         {N_("/_Edit/Wrap all long _lines"),
596                                         "<control><alt>L", compose_wrap_line_all, 0, NULL},
597         {N_("/_Edit/Edit with e_xternal editor"),
598                                         "<shift><control>X", compose_ext_editor_cb, 0, NULL},
599 #if USE_PSPELL
600         {N_("/_Spelling"),              NULL, NULL, 0, "<Branch>"},
601         {N_("/_Spelling/_Check all or check selection"),
602                                         NULL, compose_check_all, 0, NULL},
603         {N_("/_Spelling/_Highlight all misspelled words"),
604                                         NULL, compose_highlight_all, 0, NULL},
605         {N_("/_Spelling/Check _backwards misspelled word"),
606                                         NULL, compose_check_backwards , 0, NULL},
607         {N_("/_Spelling/_Forward to next misspelled word"),
608                                         NULL, compose_check_forwards_go, 0, NULL},
609         {N_("/_Spelling/---"),          NULL, NULL, 0, "<Separator>"},
610         {N_("/_Spelling/_Spelling Configuration"),
611                                         NULL, NULL, 0, "<Branch>"},
612 #endif
613 #if 0 /* NEW COMPOSE GUI */
614         {N_("/_View"),                  NULL, NULL, 0, "<Branch>"},
615         {N_("/_View/_To"),              NULL, compose_toggle_to_cb     , 0, "<ToggleItem>"},
616         {N_("/_View/_Cc"),              NULL, compose_toggle_cc_cb     , 0, "<ToggleItem>"},
617         {N_("/_View/_Bcc"),             NULL, compose_toggle_bcc_cb    , 0, "<ToggleItem>"},
618         {N_("/_View/_Reply to"),        NULL, compose_toggle_replyto_cb, 0, "<ToggleItem>"},
619         {N_("/_View/---"),              NULL, NULL, 0, "<Separator>"},
620         {N_("/_View/_Followup to"),     NULL, compose_toggle_followupto_cb, 0, "<ToggleItem>"},
621         {N_("/_View/---"),              NULL, NULL, 0, "<Separator>"},
622         {N_("/_View/R_uler"),           NULL, compose_toggle_ruler_cb, 0, "<ToggleItem>"},
623         {N_("/_View/---"),              NULL, NULL, 0, "<Separator>"},
624         {N_("/_View/_Attachment"),      NULL, compose_toggle_attach_cb, 0, "<ToggleItem>"},
625 #endif
626         {N_("/_Message"),               NULL, NULL, 0, "<Branch>"},
627         {N_("/_Message/_Send"),         "<control>Return",
628                                         compose_send_cb, 0, NULL},
629         {N_("/_Message/Send _later"),   "<shift><control>S",
630                                         compose_send_later_cb,  0, NULL},
631         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
632         {N_("/_Message/Save to _draft folder"),
633                                         "<shift><control>D", compose_draft_cb, 0, NULL},
634         {N_("/_Message/Save and _keep editing"),
635                                         "<control>S", compose_draft_cb, 1, NULL},
636 #if 0 /* NEW COMPOSE GUI */
637         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
638         {N_("/_Message/_To"),           NULL, compose_toggle_to_cb     , 0, "<ToggleItem>"},
639         {N_("/_Message/_Cc"),           NULL, compose_toggle_cc_cb     , 0, "<ToggleItem>"},
640         {N_("/_Message/_Bcc"),          NULL, compose_toggle_bcc_cb    , 0, "<ToggleItem>"},
641         {N_("/_Message/_Reply to"),     NULL, compose_toggle_replyto_cb, 0, "<ToggleItem>"},
642         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
643         {N_("/_Message/_Followup to"),  NULL, compose_toggle_followupto_cb, 0, "<ToggleItem>"},
644         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
645         {N_("/_Message/_Attach"),       NULL, compose_toggle_attach_cb, 0, "<ToggleItem>"},
646 #endif
647 #if USE_GPGME
648         {N_("/_Message/---"),           NULL, NULL, 0, "<Separator>"},
649         {N_("/_Message/Si_gn"),         NULL, compose_toggle_sign_cb   , 0, "<ToggleItem>"},
650         {N_("/_Message/_Encrypt"),      NULL, compose_toggle_encrypt_cb, 0, "<ToggleItem>"},
651 #endif /* USE_GPGME */
652         {N_("/_Message/---"),           NULL,           NULL,   0, "<Separator>"},
653         {N_("/_Message/Priority"),      NULL,           NULL,   0, "<Branch>"},
654         {N_("/_Message/Priority/Highest"), NULL, compose_set_priority_cb, PRIORITY_HIGHEST, "<RadioItem>"},
655         {N_("/_Message/Priority/High"),    NULL, compose_set_priority_cb, PRIORITY_HIGH, "/Message/Priority/Highest"},
656         {N_("/_Message/Priority/Normal"),  NULL, compose_set_priority_cb, PRIORITY_NORMAL, "/Message/Priority/Highest"},
657         {N_("/_Message/Priority/Low"),     NULL, compose_set_priority_cb, PRIORITY_LOW, "/Message/Priority/Highest"},
658         {N_("/_Message/Priority/Lowest"),  NULL, compose_set_priority_cb, PRIORITY_LOWEST, "/Message/Priority/Highest"},
659         {N_("/_Message/---"),           NULL,           NULL,   0, "<Separator>"},
660         {N_("/_Message/_Request Return Receipt"),       NULL, compose_toggle_return_receipt_cb, 0, "<ToggleItem>"},
661         {N_("/_Tools"),                 NULL, NULL, 0, "<Branch>"},
662         {N_("/_Tools/Show _ruler"),     NULL, compose_toggle_ruler_cb, 0, "<ToggleItem>"},
663         {N_("/_Tools/_Address book"),   "<shift><control>A", compose_address_cb , 0, NULL},
664         {N_("/_Tools/_Template"),       NULL, NULL, 0, "<Branch>"},
665         {N_("/_Tools/Actio_ns"),        NULL, NULL, 0, "<Branch>"},
666         {N_("/_Help"),                  NULL, NULL, 0, "<Branch>"},
667         {N_("/_Help/_About"),           NULL, about_show, 0, NULL}
668 };
669
670 static GtkTargetEntry compose_mime_types[] =
671 {
672         {"text/uri-list", 0, 0}
673 };
674
675 Compose *compose_new(PrefsAccount *account)
676 {
677         return compose_generic_new(account, NULL, NULL);
678 }
679
680 Compose *compose_redirect(PrefsAccount *account, MsgInfo *msginfo)
681 {
682         Compose *c;
683         gchar *filename;
684         GtkItemFactory *ifactory;
685         
686         c = compose_generic_new(account, NULL, NULL);
687
688         filename = procmsg_get_message_file(msginfo);
689         if (filename == NULL)
690                 return NULL;
691
692         c->redirect_filename = filename;
693
694         if (msginfo->subject)
695                 gtk_entry_set_text(GTK_ENTRY(c->subject_entry),
696                                    msginfo->subject);
697         gtk_editable_set_editable(GTK_EDITABLE(c->subject_entry), FALSE);
698
699         compose_quote_fmt(c, msginfo, "%M", NULL, NULL);
700         gtk_editable_set_editable(GTK_EDITABLE(c->text), FALSE);
701
702         ifactory = gtk_item_factory_from_widget(c->popupmenu);
703         menu_set_sensitive(ifactory, "/Add...", FALSE);
704         menu_set_sensitive(ifactory, "/Remove", FALSE);
705         menu_set_sensitive(ifactory, "/Property...", FALSE);
706
707         ifactory = gtk_item_factory_from_widget(c->menubar);
708         menu_set_sensitive(ifactory, "/File/Insert file", FALSE);
709         menu_set_sensitive(ifactory, "/File/Attach file", FALSE);
710         menu_set_sensitive(ifactory, "/File/Insert signature", FALSE);
711         menu_set_sensitive(ifactory, "/Edit/Paste", FALSE);
712         menu_set_sensitive(ifactory, "/Edit/Wrap current paragraph", FALSE);
713         menu_set_sensitive(ifactory, "/Edit/Wrap all long lines", FALSE);
714         menu_set_sensitive(ifactory, "/Edit/Edit with external editor", FALSE);
715         menu_set_sensitive(ifactory, "/Message/Attach", FALSE);
716 #if USE_GPGME
717         menu_set_sensitive(ifactory, "/Message/Sign", FALSE);
718         menu_set_sensitive(ifactory, "/Message/Encrypt", FALSE);
719 #endif
720         menu_set_sensitive(ifactory, "/Message/Request Return Receipt", FALSE);
721         menu_set_sensitive(ifactory, "/Tools/Template", FALSE);
722         
723         gtk_widget_set_sensitive(c->insert_btn, FALSE);
724         gtk_widget_set_sensitive(c->attach_btn, FALSE);
725         gtk_widget_set_sensitive(c->sig_btn, FALSE);
726         gtk_widget_set_sensitive(c->exteditor_btn, FALSE);
727         gtk_widget_set_sensitive(c->linewrap_btn, FALSE);
728
729         return c;
730 }
731
732 Compose *compose_new_with_recipient(PrefsAccount *account, const gchar *mailto)
733 {
734         return compose_generic_new(account, mailto, NULL);
735 }
736
737 Compose *compose_new_with_folderitem(PrefsAccount *account, FolderItem *item)
738 {
739         return compose_generic_new(account, NULL, item);
740 }
741
742 Compose *compose_generic_new(PrefsAccount *account, const gchar *mailto, FolderItem *item)
743 {
744         Compose *compose;
745         GtkSText *text;
746         GtkItemFactory *ifactory;
747         gboolean grab_focus_on_last = TRUE;
748
749         if (item && item->prefs && item->prefs->enable_default_account)
750                 account = account_find_from_id(item->prefs->default_account);
751
752         if (!account) account = cur_account;
753         g_return_val_if_fail(account != NULL, NULL);
754
755         compose = compose_create(account, COMPOSE_NEW);
756         ifactory = gtk_item_factory_from_widget(compose->menubar);
757
758         compose->replyinfo = NULL;
759
760         text = GTK_STEXT(compose->text);
761         gtk_stext_freeze(text);
762
763         if (prefs_common.auto_sig)
764                 compose_insert_sig(compose);
765         gtk_editable_set_position(GTK_EDITABLE(text), 0);
766         gtk_stext_set_point(text, 0);
767
768         gtk_stext_thaw(text);
769
770         /* workaround for initial XIM problem */
771         gtk_widget_grab_focus(compose->text);
772         gtkut_widget_wait_for_draw(compose->text);
773
774
775         if (account->protocol != A_NNTP) {
776                 if (mailto) {
777                         compose_entries_set(compose, mailto);
778
779                 } else if(item && item->prefs->enable_default_to) {
780                         compose_entry_append(compose, item->prefs->default_to, COMPOSE_TO);
781                         compose_entry_select(compose, item->prefs->default_to);
782                         grab_focus_on_last = FALSE;
783                 }
784                 if (item && item->ret_rcpt) {
785                         menu_set_toggle(ifactory, "/Message/Request Return Receipt", TRUE);
786                 }
787         } else {
788                 if (mailto) {
789                         compose_entry_append(compose, mailto, COMPOSE_NEWSGROUPS);
790                 }
791                 /*
792                  * CLAWS: just don't allow return receipt request, even if the user
793                  * may want to send an email. simple but foolproof.
794                  */
795                 menu_set_sensitive(ifactory, "/Message/Request Return Receipt", FALSE); 
796         }
797         compose_show_first_last_header(compose, TRUE);
798
799         /* Set save folder */
800         if(item && item->prefs && item->prefs->save_copy_to_folder) {
801                 gchar *folderidentifier;
802
803                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), prefs_common.savemsg);
804                 folderidentifier = folder_item_get_identifier(item);
805                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
806                 g_free(folderidentifier);
807         }
808         
809         /* Grab focus on last header only if no default_to was set */
810         if(grab_focus_on_last)
811                 gtk_widget_grab_focus(compose->header_last->entry);
812
813         if (prefs_common.auto_exteditor)
814                 compose_exec_ext_editor(compose);
815
816         return compose;
817 }
818
819 #define CHANGE_FLAGS(msginfo) \
820 { \
821 if (msginfo->folder->folder->change_flags != NULL) \
822 msginfo->folder->folder->change_flags(msginfo->folder->folder, \
823                                       msginfo->folder, \
824                                       msginfo); \
825 }
826
827 /*
828 Compose *compose_new_followup_and_replyto(PrefsAccount *account,
829                                            const gchar *followupto, gchar * to)
830 {
831         Compose *compose;
832
833         if (!account) account = cur_account;
834         g_return_val_if_fail(account != NULL, NULL);
835         g_return_val_if_fail(account->protocol != A_NNTP, NULL);
836
837         compose = compose_create(account, COMPOSE_NEW);
838
839         if (prefs_common.auto_sig)
840                 compose_insert_sig(compose);
841         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
842         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
843
844         compose_entry_append(compose, to, COMPOSE_TO);
845         compose_entry_append(compose, followupto, COMPOSE_NEWSGROUPS);
846         gtk_widget_grab_focus(compose->subject_entry);
847
848         return compose;
849 }
850 */
851
852 void compose_reply(MsgInfo *msginfo, gboolean quote, gboolean to_all,
853                    gboolean ignore_replyto, const gchar *body)
854 {
855         compose_generic_reply(msginfo, quote, to_all, ignore_replyto, FALSE,
856                               body);
857 }
858
859 void compose_followup_and_reply_to(MsgInfo *msginfo, gboolean quote,
860                                    gboolean to_all,
861                                    gboolean ignore_replyto,
862                                    const gchar *body)
863 {
864         compose_generic_reply(msginfo, quote, to_all, ignore_replyto, TRUE,
865                               body);
866 }
867
868 static void compose_generic_reply(MsgInfo *msginfo, gboolean quote,
869                                   gboolean to_all,
870                                   gboolean ignore_replyto,
871                                   gboolean followup_and_reply_to,
872                                   const gchar *body)
873 {
874         Compose *compose;
875         PrefsAccount *account;
876         PrefsAccount *reply_account;
877         GtkSText *text;
878
879         g_return_if_fail(msginfo != NULL);
880         g_return_if_fail(msginfo->folder != NULL);
881
882         account = NULL;
883         /* select the account set in folderitem's property (if enabled) */
884         if (msginfo->folder->prefs && msginfo->folder->prefs->enable_default_account)
885                 account = account_find_from_id(msginfo->folder->prefs->default_account);
886         
887         /* select the account for the whole folder (IMAP / NNTP) */
888         if (!account)
889                 /* FIXME: this is not right, because folder may be nested. we should
890                  * ascend the tree until we find a parent with proper account 
891                  * information */
892                 account = msginfo->folder->folder->account;
893
894         /* select account by to: and cc: header if enabled */
895         if (prefs_common.reply_account_autosel) {
896                 if (!account && msginfo->to) {
897                         gchar *to;
898                         Xstrdup_a(to, msginfo->to, return);
899                         extract_address(to);
900                         account = account_find_from_address(to);
901                 }
902                 if (!account) {
903                         gchar cc[BUFFSIZE];
904                         if(!get_header_from_msginfo(msginfo, cc, sizeof(cc), "CC:")) { /* Found a CC header */
905                                 extract_address(cc);
906                                 account = account_find_from_address(cc);
907                         }        
908                 }
909         }
910
911         /* select current account */
912         if (!account) account = cur_account;
913         g_return_if_fail(account != NULL);
914
915         if (ignore_replyto && account->protocol == A_NNTP &&
916             !followup_and_reply_to) {
917                 reply_account =
918                         account_find_from_address(account->address);
919                 if (!reply_account)
920                         reply_account = compose_current_mail_account();
921                 if (!reply_account)
922                         return;
923         } else
924                 reply_account = account;
925
926         MSG_UNSET_PERM_FLAGS(msginfo->flags, MSG_FORWARDED);
927         MSG_SET_PERM_FLAGS(msginfo->flags, MSG_REPLIED);
928         if (MSG_IS_IMAP(msginfo->flags))
929                 imap_msg_set_perm_flags(msginfo, MSG_REPLIED);
930         CHANGE_FLAGS(msginfo);
931
932         compose = compose_create(account, COMPOSE_REPLY);
933         compose->replyinfo = procmsg_msginfo_copy(msginfo);
934
935 #if 0 /* NEW COMPOSE GUI */
936         if (followup_and_reply_to) {
937                 gtk_widget_show(compose->to_hbox);
938                 gtk_widget_show(compose->to_entry);
939                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 1, 4);
940                 compose->use_to = TRUE;
941         }
942 #endif
943         if (msginfo->folder && msginfo->folder->ret_rcpt) {
944                 GtkItemFactory *ifactory;
945         
946                 ifactory = gtk_item_factory_from_widget(compose->menubar);
947                 menu_set_toggle(ifactory, "/Message/Request Return Receipt", TRUE);
948         }
949
950         /* Set save folder */
951         if(msginfo->folder && msginfo->folder->prefs && msginfo->folder->prefs->save_copy_to_folder) {
952                 gchar *folderidentifier;
953
954                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), TRUE);
955                 folderidentifier = folder_item_get_identifier(msginfo->folder);
956                 gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), folderidentifier);
957                 g_free(folderidentifier);
958         }
959
960         if (compose_parse_header(compose, msginfo) < 0) return;
961         compose_reply_set_entry(compose, msginfo, to_all, ignore_replyto,
962                                 followup_and_reply_to);
963         compose_show_first_last_header(compose, TRUE);
964
965         text = GTK_STEXT(compose->text);
966         gtk_stext_freeze(text);
967
968         if (quote) {
969                 gchar *qmark;
970                 gchar *quote_str;
971
972                 if (prefs_common.quotemark && *prefs_common.quotemark)
973                         qmark = prefs_common.quotemark;
974                 else
975                         qmark = "> ";
976
977                 quote_str = compose_quote_fmt(compose, msginfo,
978                                               prefs_common.quotefmt,
979                                               qmark, body);
980         }
981
982         if (prefs_common.auto_sig)
983                 compose_insert_sig(compose);
984
985         if (quote && prefs_common.linewrap_quote)
986                 compose_wrap_line_all(compose);
987
988         gtk_editable_set_position(GTK_EDITABLE(text), 0);
989         gtk_stext_set_point(text, 0);
990
991         gtk_stext_thaw(text);
992         gtk_widget_grab_focus(compose->text);
993
994         if (prefs_common.auto_exteditor)
995                 compose_exec_ext_editor(compose);
996 }
997
998 static void set_toolbar_style(Compose *compose);
999
1000 #define INSERT_FW_HEADER(var, hdr) \
1001 if (msginfo->var && *msginfo->var) { \
1002         gtk_stext_insert(text, NULL, NULL, NULL, hdr, -1); \
1003         gtk_stext_insert(text, NULL, NULL, NULL, msginfo->var, -1); \
1004         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1); \
1005 }
1006
1007 Compose *compose_forward(PrefsAccount *account, MsgInfo *msginfo,
1008                          gboolean as_attach, const gchar *body)
1009 {
1010         Compose *compose;
1011         /*      PrefsAccount *account; */
1012         GtkSText *text;
1013
1014         g_return_val_if_fail(msginfo != NULL, NULL);
1015         g_return_val_if_fail(msginfo->folder != NULL, NULL);
1016
1017         account = msginfo->folder->folder->account;
1018         if (!account && msginfo->to && prefs_common.forward_account_autosel) {
1019                 gchar *to;
1020                 Xstrdup_a(to, msginfo->to, return NULL);
1021                 extract_address(to);
1022                 account = account_find_from_address(to);
1023         }
1024
1025         if(!account && prefs_common.forward_account_autosel) {
1026                 gchar cc[BUFFSIZE];
1027                 if(!get_header_from_msginfo(msginfo,cc,sizeof(cc),"CC:")){ /* Found a CC header */
1028                         extract_address(cc);
1029                         account = account_find_from_address(cc);
1030                 }
1031         }
1032
1033         if (account == NULL) {
1034                 account = cur_account;
1035                 /*
1036                 account = msginfo->folder->folder->account;
1037                 if (!account) account = cur_account;
1038                 */
1039         }
1040         g_return_val_if_fail(account != NULL, NULL);
1041
1042         MSG_UNSET_PERM_FLAGS(msginfo->flags, MSG_REPLIED);
1043         MSG_SET_PERM_FLAGS(msginfo->flags, MSG_FORWARDED);
1044         if (MSG_IS_IMAP(msginfo->flags))
1045                 imap_msg_unset_perm_flags(msginfo, MSG_REPLIED);
1046         CHANGE_FLAGS(msginfo);
1047
1048         compose = compose_create(account, COMPOSE_FORWARD);
1049
1050         if (msginfo->subject && *msginfo->subject) {
1051                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), "Fw: ");
1052                 gtk_entry_append_text(GTK_ENTRY(compose->subject_entry),
1053                                       msginfo->subject);
1054         }
1055
1056         text = GTK_STEXT(compose->text);
1057         gtk_stext_freeze(text);
1058
1059
1060                 if (as_attach) {
1061                         gchar *msgfile;
1062
1063                         msgfile = procmsg_get_message_file_path(msginfo);
1064                         if (!is_file_exist(msgfile))
1065                                 g_warning(_("%s: file not exist\n"), msgfile);
1066                         else
1067                                 compose_attach_append(compose, msgfile, msgfile,
1068                                                       "message/rfc822");
1069
1070                         g_free(msgfile);
1071                 } else {
1072                         gchar *qmark;
1073                         gchar *quote_str;
1074
1075                         if (prefs_common.fw_quotemark &&
1076                             *prefs_common.fw_quotemark)
1077                                 qmark = prefs_common.fw_quotemark;
1078                         else
1079                                 qmark = "> ";
1080
1081                         quote_str = compose_quote_fmt(compose, msginfo,
1082                                                       prefs_common.fw_quotefmt,
1083                                                       qmark, body);
1084                         compose_attach_parts(compose, msginfo);
1085                 }
1086
1087         if (prefs_common.auto_sig)
1088                 compose_insert_sig(compose);
1089
1090         if (prefs_common.linewrap_quote)
1091                 compose_wrap_line_all(compose);
1092
1093         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
1094         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
1095
1096         gtk_stext_thaw(text);
1097 #if 0 /* NEW COMPOSE GUI */
1098         if (account->protocol != A_NNTP)
1099                 gtk_widget_grab_focus(compose->to_entry);
1100         else
1101                 gtk_widget_grab_focus(compose->newsgroups_entry);
1102 #endif
1103         gtk_widget_grab_focus(compose->header_last->entry);
1104
1105         if (prefs_common.auto_exteditor)
1106                 compose_exec_ext_editor(compose);
1107
1108         return compose;
1109 }
1110
1111 #undef INSERT_FW_HEADER
1112
1113 Compose *compose_forward_multiple(PrefsAccount *account, GSList *msginfo_list)
1114 {
1115         Compose *compose;
1116         GtkSText *text;
1117         GSList *msginfo;
1118         gchar *msgfile;
1119
1120         g_return_val_if_fail(msginfo_list != NULL, NULL);
1121         
1122         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1123                 if ( ((MsgInfo *)msginfo->data)->folder == NULL )
1124                         return NULL;
1125         }
1126
1127         if (account == NULL) {
1128                 account = cur_account;
1129                 /*
1130                 account = msginfo->folder->folder->account;
1131                 if (!account) account = cur_account;
1132                 */
1133         }
1134         g_return_val_if_fail(account != NULL, NULL);
1135
1136         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1137                 MSG_UNSET_PERM_FLAGS(((MsgInfo *)msginfo->data)->flags, MSG_REPLIED);
1138                 MSG_SET_PERM_FLAGS(((MsgInfo *)msginfo->data)->flags, MSG_FORWARDED);
1139                 CHANGE_FLAGS(((MsgInfo *)msginfo->data));
1140         }
1141
1142         compose = compose_create(account, COMPOSE_FORWARD);
1143
1144         text = GTK_STEXT(compose->text);
1145         gtk_stext_freeze(text);
1146
1147         for (msginfo = msginfo_list; msginfo != NULL; msginfo = msginfo->next) {
1148                 msgfile = procmsg_get_message_file_path((MsgInfo *)msginfo->data);
1149                 if (!is_file_exist(msgfile))
1150                         g_warning(_("%s: file not exist\n"), msgfile);
1151                 else
1152                         compose_attach_append(compose, msgfile, msgfile,
1153                                 "message/rfc822");
1154                 g_free(msgfile);
1155         }
1156
1157         if (prefs_common.auto_sig)
1158                 compose_insert_sig(compose);
1159
1160         if (prefs_common.linewrap_quote)
1161                 compose_wrap_line_all(compose);
1162
1163         gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
1164         gtk_stext_set_point(GTK_STEXT(compose->text), 0);
1165
1166         gtk_stext_thaw(text);
1167 #if 0 /* NEW COMPOSE GUI */
1168         if (account->protocol != A_NNTP)
1169                 gtk_widget_grab_focus(compose->to_entry);
1170         else
1171                 gtk_widget_grab_focus(compose->newsgroups_entry);
1172 #endif
1173
1174         return compose;
1175 }
1176
1177 void compose_reedit(MsgInfo *msginfo)
1178 {
1179         Compose *compose;
1180         PrefsAccount *account = NULL;
1181         GtkSText *text;
1182         FILE *fp;
1183         gchar buf[BUFFSIZE];
1184
1185         g_return_if_fail(msginfo != NULL);
1186         g_return_if_fail(msginfo->folder != NULL);
1187
1188         if (msginfo->folder->stype == F_QUEUE) {
1189                 gchar queueheader_buf[BUFFSIZE];
1190                 gint id;
1191
1192                 /* Select Account from queue headers */
1193                 if (!get_header_from_msginfo(msginfo, queueheader_buf, 
1194                                              sizeof(queueheader_buf), "NAID:")) {
1195                         id = atoi(&queueheader_buf[5]);
1196                         account = account_find_from_id(id);
1197                 }
1198                 if (!account && !get_header_from_msginfo(msginfo, queueheader_buf, 
1199                                                     sizeof(queueheader_buf), "MAID:")) {
1200                         id = atoi(&queueheader_buf[5]);
1201                         account = account_find_from_id(id);
1202                 }
1203                 if (!account && !get_header_from_msginfo(msginfo, queueheader_buf, 
1204                                                                 sizeof(queueheader_buf), "S:")) {
1205                         account = account_find_from_address(queueheader_buf);
1206                 }
1207         } else 
1208                 account = msginfo->folder->folder->account;
1209
1210         if (!account && prefs_common.reedit_account_autosel) {
1211                 gchar from[BUFFSIZE];
1212                 if (!get_header_from_msginfo(msginfo, from, sizeof(from), "FROM:")){
1213                         extract_address(from);
1214                         account = account_find_from_address(from);
1215                 }
1216         }
1217         if (!account) account = cur_account;
1218         g_return_if_fail(account != NULL);
1219
1220         compose = compose_create(account, COMPOSE_REEDIT);
1221         compose->targetinfo = procmsg_msginfo_copy(msginfo);
1222
1223         if (msginfo->folder->stype == F_QUEUE) {
1224                 gchar queueheader_buf[BUFFSIZE];
1225
1226                 /* Set message save folder */
1227                 if (!get_header_from_msginfo(msginfo, queueheader_buf, sizeof(queueheader_buf), "SCF:")) {
1228                         gint startpos = 0;
1229
1230                         gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn), TRUE);
1231                         gtk_editable_delete_text(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
1232                         gtk_editable_insert_text(GTK_EDITABLE(compose->savemsg_entry), &queueheader_buf[4], strlen(&queueheader_buf[4]), &startpos);
1233                 }
1234         }
1235         
1236         if (compose_parse_header(compose, msginfo) < 0) return;
1237         compose_reedit_set_entry(compose, msginfo);
1238
1239         text = GTK_STEXT(compose->text);
1240         gtk_stext_freeze(text);
1241
1242         if ((fp = procmime_get_first_text_content(msginfo)) == NULL)
1243                 g_warning(_("Can't get text part\n"));
1244         else {
1245                 while (fgets(buf, sizeof(buf), fp) != NULL)
1246                         gtk_stext_insert(text, NULL, NULL, NULL, buf, -1);
1247                 fclose(fp);
1248         }
1249         compose_attach_parts(compose, msginfo);
1250
1251         gtk_stext_thaw(text);
1252         gtk_widget_grab_focus(compose->text);
1253
1254         if (prefs_common.auto_exteditor)
1255                 compose_exec_ext_editor(compose);
1256 }
1257
1258 GList *compose_get_compose_list(void)
1259 {
1260         return compose_list;
1261 }
1262
1263 void compose_entry_append(Compose *compose, const gchar *address,
1264                           ComposeEntryType type)
1265 {
1266         gchar *header;
1267
1268         if (!address || *address == '\0') return;
1269
1270 #if 0 /* NEW COMPOSE GUI */
1271         switch (type) {
1272         case COMPOSE_CC:
1273                 entry = GTK_ENTRY(compose->cc_entry);
1274                 break;
1275         case COMPOSE_BCC:
1276                 entry = GTK_ENTRY(compose->bcc_entry);
1277                 break;
1278         case COMPOSE_NEWSGROUPS:
1279                 entry = GTK_ENTRY(compose->newsgroups_entry);
1280                 break;
1281         case COMPOSE_TO:
1282         default:
1283                 entry = GTK_ENTRY(compose->to_entry);
1284                 break;
1285         }
1286
1287         text = gtk_entry_get_text(entry);
1288         if (*text != '\0')
1289                 gtk_entry_append_text(entry, ", ");
1290         gtk_entry_append_text(entry, address);
1291 #endif
1292
1293         switch (type) {
1294         case COMPOSE_CC:
1295                 header = N_("Cc:");
1296                 break;
1297         case COMPOSE_BCC:
1298                 header = N_("Bcc:");
1299                 break;
1300         case COMPOSE_REPLYTO:
1301                 header = N_("Reply-To:");
1302                 break;
1303         case COMPOSE_NEWSGROUPS:
1304                 header = N_("Newsgroups:");
1305                 break;
1306         case COMPOSE_FOLLOWUPTO:
1307                 header = N_( "Followup-To:");
1308                 break;
1309         case COMPOSE_TO:
1310         default:
1311                 header = N_("To:");
1312                 break;
1313         }
1314         header = prefs_common.trans_hdr ? gettext(header) : header;
1315
1316         compose_add_header_entry(compose, header, (gchar *)address);
1317 }
1318
1319 void compose_entry_select (Compose *compose, const gchar *mailto)
1320 {
1321         GSList *header_list;
1322                 
1323         for (header_list = compose->header_list; header_list != NULL; header_list = header_list->next) {
1324                 GtkEntry * entry = GTK_ENTRY(((ComposeHeaderEntry *)header_list->data)->entry);
1325
1326                 if (gtk_entry_get_text(entry) && !g_strcasecmp(gtk_entry_get_text(entry), mailto)) {
1327                         gtk_entry_select_region(entry, 0, -1);
1328                         gtk_widget_grab_focus(GTK_WIDGET(entry));
1329                 }
1330         }
1331 }
1332
1333 static void compose_entries_set(Compose *compose, const gchar *mailto)
1334 {
1335         gchar *subject = NULL;
1336         gchar *to = NULL;
1337         gchar *cc = NULL;
1338         gchar *bcc = NULL;
1339         gchar *body = NULL;
1340         gchar *p;
1341         gchar *tmp_mailto;
1342
1343         Xstrdup_a(tmp_mailto, mailto, return);
1344
1345         to = tmp_mailto;
1346
1347         p = strchr(tmp_mailto, '?');
1348         if (p) {
1349                 *p = '\0';
1350                 p++;
1351         }
1352
1353         while (p) {
1354                 gchar *field, *value;
1355
1356                 field = p;
1357
1358                 p = strchr(p, '=');
1359                 if (!p) break;
1360                 *p = '\0';
1361                 p++;
1362
1363                 value = p;
1364
1365                 p = strchr(p, '&');
1366                 if (p) {
1367                         *p = '\0';
1368                         p++;
1369                 }
1370
1371                 if (*value == '\0') continue;
1372
1373                 if (!g_strcasecmp(field, "subject")) {
1374                         Xalloca(subject, strlen(value) + 1, return);
1375                         decode_uri(subject, value);
1376                 } else if (!g_strcasecmp(field, "cc")) {
1377                         cc = value;
1378                 } else if (!g_strcasecmp(field, "bcc")) {
1379                         bcc = value;
1380                 } else if (!g_strcasecmp(field, "body")) {
1381                         Xalloca(body, strlen(value) + 1, return);
1382                         decode_uri(body, value);
1383                 }
1384         }
1385
1386         if (to)
1387                 compose_entry_append(compose, to, COMPOSE_TO);
1388         if (subject)
1389                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), subject);
1390         if (cc)
1391                 compose_entry_append(compose, cc, COMPOSE_CC);
1392         if (bcc)
1393                 compose_entry_append(compose, bcc, COMPOSE_BCC);
1394         if (body) {
1395                 gtk_stext_insert(GTK_STEXT(compose->text),
1396                                 NULL, NULL, NULL, body, -1);
1397                 gtk_stext_insert(GTK_STEXT(compose->text),
1398                                 NULL, NULL, NULL, "\n", 1);
1399         }
1400 }
1401
1402 static gint compose_parse_header(Compose *compose, MsgInfo *msginfo)
1403 {
1404         static HeaderEntry hentry[] = {{"Reply-To:",       NULL, TRUE},
1405                                        {"Cc:",             NULL, FALSE},
1406                                        {"References:",     NULL, FALSE},
1407                                        {"Bcc:",            NULL, FALSE},
1408                                        {"Newsgroups:",     NULL, FALSE},
1409                                        {"Followup-To:",    NULL, FALSE},
1410                                        {"X-Mailing-List:", NULL, FALSE},
1411                                        {"X-BeenThere:",    NULL, FALSE},
1412                                        {"X-Priority:",     NULL, FALSE},
1413                                        {NULL,              NULL, FALSE}};
1414
1415         enum
1416         {
1417                 H_REPLY_TO       = 0,
1418                 H_CC             = 1,
1419                 H_REFERENCES     = 2,
1420                 H_BCC            = 3,
1421                 H_NEWSGROUPS     = 4,
1422                 H_FOLLOWUP_TO    = 5,
1423                 H_X_MAILING_LIST = 6,
1424                 H_X_BEENTHERE    = 7,
1425                 H_X_PRIORITY     = 8
1426         };
1427
1428         FILE *fp;
1429
1430         g_return_val_if_fail(msginfo != NULL, -1);
1431
1432         if ((fp = procmsg_open_message(msginfo)) == NULL) return -1;
1433         procheader_get_header_fields(fp, hentry);
1434         fclose(fp);
1435
1436         if (hentry[H_REPLY_TO].body != NULL) {
1437                 conv_unmime_header_overwrite(hentry[H_REPLY_TO].body);
1438                 compose->replyto = hentry[H_REPLY_TO].body;
1439                 hentry[H_REPLY_TO].body = NULL;
1440         }
1441         if (hentry[H_CC].body != NULL) {
1442                 conv_unmime_header_overwrite(hentry[H_CC].body);
1443                 compose->cc = hentry[H_CC].body;
1444                 hentry[H_CC].body = NULL;
1445         }
1446         if (hentry[H_X_MAILING_LIST].body != NULL) {
1447                 /* this is good enough to parse debian-devel */
1448                 gchar *buf = g_malloc(strlen(hentry[H_X_MAILING_LIST].body) + 1);
1449                 g_return_val_if_fail(buf != NULL, -1 );
1450                 if (1 == sscanf(hentry[H_X_MAILING_LIST].body, "<%[^>]>", buf))
1451                         compose->mailinglist = g_strdup(buf);
1452                 g_free(buf);
1453                 g_free(hentry[H_X_MAILING_LIST].body);
1454                 hentry[H_X_MAILING_LIST].body = NULL ;
1455         }
1456         if (hentry[H_X_BEENTHERE].body != NULL) {
1457                 /* this is good enough to parse the sylpheed-claws lists */
1458                 gchar *buf = g_malloc(strlen(hentry[H_X_BEENTHERE].body) + 1);
1459                 g_return_val_if_fail(buf != NULL, -1 );
1460                 if (1 == sscanf(hentry[H_X_BEENTHERE].body, "%[^>]", buf))
1461                         compose->mailinglist = g_strdup(buf);
1462                 g_free(buf);
1463                 g_free(hentry[H_X_BEENTHERE].body);
1464                 hentry[H_X_BEENTHERE].body = NULL ;
1465         }
1466         if (hentry[H_REFERENCES].body != NULL) {
1467                 if (compose->mode == COMPOSE_REEDIT)
1468                         compose->references = hentry[H_REFERENCES].body;
1469                 else {
1470                         compose->references = compose_parse_references
1471                                 (hentry[H_REFERENCES].body, msginfo->msgid);
1472                         g_free(hentry[H_REFERENCES].body);
1473                 }
1474                 hentry[H_REFERENCES].body = NULL;
1475         }
1476         if (hentry[H_BCC].body != NULL) {
1477                 if (compose->mode == COMPOSE_REEDIT) {
1478                         conv_unmime_header_overwrite(hentry[H_BCC].body);
1479                         compose->bcc = hentry[H_BCC].body;
1480                 } else
1481                         g_free(hentry[H_BCC].body);
1482                 hentry[H_BCC].body = NULL;
1483         }
1484         if (hentry[H_NEWSGROUPS].body != NULL) {
1485                 compose->newsgroups = hentry[H_NEWSGROUPS].body;
1486                 hentry[H_NEWSGROUPS].body = NULL;
1487         }
1488         if (hentry[H_FOLLOWUP_TO].body != NULL) {
1489                 conv_unmime_header_overwrite(hentry[H_FOLLOWUP_TO].body);
1490                 compose->followup_to = hentry[H_FOLLOWUP_TO].body;
1491                 hentry[H_FOLLOWUP_TO].body = NULL;
1492         }
1493
1494         if (compose->mode == COMPOSE_REEDIT)
1495                 if (hentry[H_X_PRIORITY].body != NULL) {
1496                         gint priority;
1497                         
1498                         priority = atoi(hentry[H_X_PRIORITY].body);
1499                         g_free(hentry[H_X_PRIORITY].body);
1500                         
1501                         hentry[H_X_PRIORITY].body = NULL;
1502                         
1503                         if (priority < PRIORITY_HIGHEST || 
1504                             priority > PRIORITY_LOWEST)
1505                                 priority = PRIORITY_NORMAL;
1506                         
1507                         compose->priority =  priority;
1508                 }
1509  
1510         if (compose->mode == COMPOSE_REEDIT && msginfo->inreplyto)
1511                 compose->inreplyto = g_strdup(msginfo->inreplyto);
1512         else if (compose->mode != COMPOSE_REEDIT &&
1513                  msginfo->msgid && *msginfo->msgid) {
1514                 compose->inreplyto = g_strdup(msginfo->msgid);
1515
1516                 if (!compose->references) {
1517                         if (msginfo->inreplyto && *msginfo->inreplyto)
1518                                 compose->references =
1519                                         g_strdup_printf("<%s>\n\t<%s>",
1520                                                         msginfo->inreplyto,
1521                                                         msginfo->msgid);
1522                         else
1523                                 compose->references =
1524                                         g_strconcat("<", msginfo->msgid, ">",
1525                                                     NULL);
1526                 }
1527         }
1528
1529         return 0;
1530 }
1531
1532 static gchar *compose_parse_references(const gchar *ref, const gchar *msgid)
1533 {
1534         GSList *ref_id_list, *cur;
1535         GString *new_ref;
1536         gchar *new_ref_str;
1537
1538         ref_id_list = references_list_append(NULL, ref);
1539         if (!ref_id_list) return NULL;
1540         if (msgid && *msgid)
1541                 ref_id_list = g_slist_append(ref_id_list, g_strdup(msgid));
1542
1543         for (;;) {
1544                 gint len = 0;
1545
1546                 for (cur = ref_id_list; cur != NULL; cur = cur->next)
1547                         /* "<" + Message-ID + ">" + CR+LF+TAB */
1548                         len += strlen((gchar *)cur->data) + 5;
1549
1550                 if (len > MAX_REFERENCES_LEN) {
1551                         /* remove second message-ID */
1552                         if (ref_id_list && ref_id_list->next &&
1553                             ref_id_list->next->next) {
1554                                 g_free(ref_id_list->next->data);
1555                                 ref_id_list = g_slist_remove
1556                                         (ref_id_list, ref_id_list->next->data);
1557                         } else {
1558                                 slist_free_strings(ref_id_list);
1559                                 g_slist_free(ref_id_list);
1560                                 return NULL;
1561                         }
1562                 } else
1563                         break;
1564         }
1565
1566         new_ref = g_string_new("");
1567         for (cur = ref_id_list; cur != NULL; cur = cur->next) {
1568                 if (new_ref->len > 0)
1569                         g_string_append(new_ref, "\n\t");
1570                 g_string_sprintfa(new_ref, "<%s>", (gchar *)cur->data);
1571         }
1572
1573         slist_free_strings(ref_id_list);
1574         g_slist_free(ref_id_list);
1575
1576         new_ref_str = new_ref->str;
1577         g_string_free(new_ref, FALSE);
1578
1579         return new_ref_str;
1580 }
1581
1582 static gchar *compose_quote_fmt(Compose *compose, MsgInfo *msginfo,
1583                                 const gchar *fmt, const gchar *qmark,
1584                                 const gchar *body)
1585 {
1586         GtkSText *text = GTK_STEXT(compose->text);
1587         static MsgInfo dummyinfo;
1588         gchar *quote_str = NULL;
1589         gchar *buf;
1590         gchar *p, *lastp;
1591         gint len;
1592
1593         if (!msginfo)
1594                 msginfo = &dummyinfo;
1595
1596         if (qmark != NULL) {
1597                 quote_fmt_init(msginfo, NULL, NULL);
1598                 quote_fmt_scan_string(qmark);
1599                 quote_fmt_parse();
1600
1601                 buf = quote_fmt_get_buffer();
1602                 if (buf == NULL)
1603                         alertpanel_error(_("Quote mark format error."));
1604                 else
1605                         Xstrdup_a(quote_str, buf, return NULL)
1606         }
1607
1608         if (fmt && *fmt != '\0') {
1609                 quote_fmt_init(msginfo, quote_str, body);
1610                 quote_fmt_scan_string(fmt);
1611                 quote_fmt_parse();
1612
1613                 buf = quote_fmt_get_buffer();
1614                 if (buf == NULL) {
1615                         alertpanel_error(_("Message reply/forward format error."));
1616                         return NULL;
1617                 }
1618         } else
1619                 buf = "";
1620
1621         gtk_stext_freeze(text);
1622
1623         for (p = buf; *p != '\0'; ) {
1624                 lastp = strchr(p, '\n');
1625                 len = lastp ? lastp - p + 1 : -1;
1626                 gtk_stext_insert(text, NULL, NULL, NULL, p, len);
1627                 if (lastp)
1628                         p = lastp + 1;
1629                 else
1630                         break;
1631         }
1632
1633         gtk_stext_thaw(text);
1634
1635         return buf;
1636 }
1637
1638 static void compose_reply_set_entry(Compose *compose, MsgInfo *msginfo,
1639                                     gboolean to_all, gboolean ignore_replyto,
1640                                     gboolean followup_and_reply_to)
1641 {
1642         GSList *cc_list = NULL;
1643         GSList *cur;
1644         gchar *from = NULL;
1645         gchar *replyto = NULL;
1646         GHashTable *to_table;
1647
1648         g_return_if_fail(compose->account != NULL);
1649         g_return_if_fail(msginfo != NULL);
1650
1651         if ((compose->account->protocol != A_NNTP) || followup_and_reply_to)
1652                 compose_entry_append(compose,
1653                                     ((compose->replyto && !ignore_replyto)
1654                                      ? compose->replyto
1655                                      : (compose->mailinglist && !ignore_replyto)
1656                                      ? compose->mailinglist
1657                                      : msginfo->from ? msginfo->from : ""),
1658                                      COMPOSE_TO);
1659
1660         if (compose->account->protocol == A_NNTP) {
1661                 if (ignore_replyto)
1662                         compose_entry_append
1663                                 (compose, msginfo->from ? msginfo->from : "",
1664                                  COMPOSE_TO);
1665                 else
1666                         compose_entry_append
1667                                 (compose,
1668                                  compose->followup_to ? compose->followup_to
1669                                  : compose->newsgroups ? compose->newsgroups
1670                                  : "",
1671                                  COMPOSE_NEWSGROUPS);
1672         }
1673
1674         if (msginfo->subject && *msginfo->subject) {
1675                 gchar *buf, *buf2, *p;
1676
1677                 buf = g_strdup(msginfo->subject);
1678                 while (!strncasecmp(buf, "Re:", 3)) {
1679                         p = buf + 3;
1680                         while (isspace(*p)) p++;
1681                         memmove(buf, p, strlen(p) + 1);
1682                 }
1683
1684                 buf2 = g_strdup_printf("Re: %s", buf);
1685                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), buf2);
1686                 g_free(buf2);
1687                 g_free(buf);
1688         } else
1689                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry), "Re: ");
1690
1691         if (!to_all || compose->account->protocol == A_NNTP) return;
1692
1693         if (compose->replyto) {
1694                 Xstrdup_a(replyto, compose->replyto, return);
1695                 extract_address(replyto);
1696         }
1697         if (msginfo->from) {
1698                 Xstrdup_a(from, msginfo->from, return);
1699                 extract_address(from);
1700         }
1701
1702         if (compose->mailinglist && from) {
1703                 cc_list = address_list_append(cc_list, from);
1704         }
1705
1706         if (replyto && from)
1707                 cc_list = address_list_append(cc_list, from);
1708
1709         if (!compose->mailinglist)
1710                 cc_list = address_list_append(cc_list, msginfo->to);
1711
1712         cc_list = address_list_append(cc_list, compose->cc);
1713
1714         to_table = g_hash_table_new(g_str_hash, g_str_equal);
1715         if (replyto)
1716                 g_hash_table_insert(to_table, replyto, GINT_TO_POINTER(1));
1717         if (compose->account)
1718                 g_hash_table_insert(to_table, compose->account->address,
1719                                     GINT_TO_POINTER(1));
1720
1721         /* remove address on To: and that of current account */
1722         for (cur = cc_list; cur != NULL; ) {
1723                 GSList *next = cur->next;
1724
1725                 if (g_hash_table_lookup(to_table, cur->data) != NULL)
1726                         cc_list = g_slist_remove(cc_list, cur->data);
1727                 else
1728                         g_hash_table_insert(to_table, cur->data, cur);
1729
1730                 cur = next;
1731         }
1732         g_hash_table_destroy(to_table);
1733
1734         if (cc_list) {
1735                 for (cur = cc_list; cur != NULL; cur = cur->next)
1736                         compose_entry_append(compose, (gchar *)cur->data,
1737                                              COMPOSE_CC);
1738                 slist_free_strings(cc_list);
1739                 g_slist_free(cc_list);
1740         }
1741 }
1742
1743 #define SET_ENTRY(entry, str) \
1744 { \
1745         if (str && *str) \
1746                 gtk_entry_set_text(GTK_ENTRY(compose->entry), str); \
1747 }
1748
1749 #define SET_ADDRESS(type, str) \
1750 { \
1751         if (str && *str) \
1752                 compose_entry_append(compose, str, type); \
1753 }
1754
1755 static void compose_reedit_set_entry(Compose *compose, MsgInfo *msginfo)
1756 {
1757         g_return_if_fail(msginfo != NULL);
1758
1759         SET_ENTRY(subject_entry, msginfo->subject);
1760         SET_ADDRESS(COMPOSE_TO, msginfo->to);
1761         SET_ADDRESS(COMPOSE_CC, compose->cc);
1762         SET_ADDRESS(COMPOSE_BCC, compose->bcc);
1763         SET_ADDRESS(COMPOSE_REPLYTO, compose->replyto);
1764
1765         compose_update_priority_menu_item(compose);
1766
1767         compose_show_first_last_header(compose, TRUE);
1768
1769 #if 0 /* NEW COMPOSE GUI */
1770         if (compose->bcc) {
1771                 GtkItemFactory *ifactory;
1772                 GtkWidget *menuitem;
1773
1774                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1775                 menuitem = gtk_item_factory_get_item(ifactory, "/View/Bcc");
1776                 gtk_check_menu_item_set_active
1777                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
1778         }
1779         if (compose->replyto) {
1780                 GtkItemFactory *ifactory;
1781                 GtkWidget *menuitem;
1782
1783                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1784                 menuitem = gtk_item_factory_get_item
1785                         (ifactory, "/View/Reply to");
1786                 gtk_check_menu_item_set_active
1787                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
1788         }
1789 #endif
1790 }
1791
1792 #undef SET_ENTRY
1793 #undef SET_ADDRESS
1794
1795 static void compose_exec_sig(Compose *compose, gchar *sigfile)
1796 {
1797         FILE  *sigprg;
1798         gchar  *buf;
1799         size_t buf_len = 128;
1800  
1801         if (strlen(sigfile) < 2)
1802           return;
1803  
1804         sigprg = popen(sigfile+1, "r");
1805         if (sigprg) {
1806
1807                 buf = g_malloc(buf_len);
1808
1809                 if (!buf) {
1810                         gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, \
1811                         "Unable to insert signature (malloc failed)\n", -1);
1812
1813                         pclose(sigprg);
1814                         return;
1815                 }
1816
1817                 while (!feof(sigprg)) {
1818                         bzero(buf, buf_len);
1819                         fread(buf, buf_len-1, 1, sigprg);
1820                         gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, buf, -1);
1821                 }
1822
1823                 g_free(buf);
1824                 pclose(sigprg);
1825         }
1826         else
1827         {
1828                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, \
1829                 "Can't exec file: ", -1);
1830                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, \
1831                 sigfile+1, -1);
1832         }
1833 }
1834
1835 static void compose_insert_sig(Compose *compose)
1836 {
1837         gchar *sigfile;
1838
1839         if (compose->account && compose->account->sig_path)
1840                 sigfile = g_strdup(compose->account->sig_path);
1841         else
1842                 sigfile = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1843                                       DEFAULT_SIGNATURE, NULL);
1844
1845         if (!is_file_or_fifo_exist(sigfile) && sigfile[0] != '|') {
1846                 g_free(sigfile);
1847                 return;
1848         }
1849
1850         gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL, "\n\n", 2);
1851         if (prefs_common.sig_sep) {
1852                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL,
1853                                 prefs_common.sig_sep, -1);
1854                 gtk_stext_insert(GTK_STEXT(compose->text), NULL, NULL, NULL,
1855                                 "\n", 1);
1856         }
1857
1858         if (sigfile[0] == '|')
1859                 compose_exec_sig(compose, sigfile);
1860         else
1861                 compose_insert_file(compose, sigfile);
1862         g_free(sigfile);
1863 }
1864
1865 static void compose_insert_file(Compose *compose, const gchar *file)
1866 {
1867         GtkSText *text = GTK_STEXT(compose->text);
1868         gchar buf[BUFFSIZE];
1869         gint len;
1870         FILE *fp;
1871
1872         g_return_if_fail(file != NULL);
1873
1874         if ((fp = fopen(file, "rb")) == NULL) {
1875                 FILE_OP_ERROR(file, "fopen");
1876                 return;
1877         }
1878
1879         gtk_stext_freeze(text);
1880
1881         while (fgets(buf, sizeof(buf), fp) != NULL) {
1882                 /* strip <CR> if DOS/Windows file,
1883                    replace <CR> with <LF> if Macintosh file. */
1884                 strcrchomp(buf);
1885                 len = strlen(buf);
1886                 if (len > 0 && buf[len - 1] != '\n') {
1887                         while (--len >= 0)
1888                                 if (buf[len] == '\r') buf[len] = '\n';
1889                 }
1890                 gtk_stext_insert(text, NULL, NULL, NULL, buf, -1);
1891         }
1892
1893         gtk_stext_thaw(text);
1894
1895         fclose(fp);
1896 }
1897
1898 static void compose_attach_append(Compose *compose, const gchar *file,
1899                                   const gchar *filename,
1900                                   const gchar *content_type)
1901 {
1902         AttachInfo *ainfo;
1903         gchar *text[N_ATTACH_COLS];
1904         FILE *fp;
1905         off_t size;
1906         gint row;
1907
1908         if (!is_file_exist(file)) {
1909                 g_warning(_("File %s doesn't exist\n"), file);
1910                 return;
1911         }
1912         if ((size = get_file_size(file)) < 0) {
1913                 g_warning(_("Can't get file size of %s\n"), file);
1914                 return;
1915         }
1916         if (size == 0) {
1917                 alertpanel_notice(_("File %s is empty."), file);
1918                 return;
1919         }
1920         if ((fp = fopen(file, "rb")) == NULL) {
1921                 alertpanel_error(_("Can't read %s."), file);
1922                 return;
1923         }
1924         fclose(fp);
1925
1926 #if 0 /* NEW COMPOSE GUI */
1927         if (!compose->use_attach) {
1928                 GtkItemFactory *ifactory;
1929                 GtkWidget *menuitem;
1930
1931                 ifactory = gtk_item_factory_from_widget(compose->menubar);
1932                 menuitem = gtk_item_factory_get_item(ifactory,
1933                                                      "/View/Attachment");
1934                 gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
1935                                                TRUE);
1936         }
1937 #endif
1938         ainfo = g_new0(AttachInfo, 1);
1939         ainfo->file = g_strdup(file);
1940
1941         if (content_type) {
1942                 ainfo->content_type = g_strdup(content_type);
1943                 if (!strcasecmp(content_type, "message/rfc822")) {
1944                         ainfo->encoding = ENC_7BIT;
1945                         ainfo->name = g_strdup_printf
1946                                 (_("Message: %s"),
1947                                  g_basename(filename ? filename : file));
1948                 } else {
1949                         if (!g_strncasecmp(content_type, "text", 4))
1950                                 ainfo->encoding =
1951                                         procmime_get_encoding_for_file(file);
1952                         else
1953                                 ainfo->encoding = ENC_BASE64;
1954                         ainfo->name = g_strdup
1955                                 (g_basename(filename ? filename : file));
1956                 }
1957         } else {
1958                 ainfo->content_type = procmime_get_mime_type(file);
1959                 if (!ainfo->content_type) {
1960                         ainfo->content_type =
1961                                 g_strdup("application/octet-stream");
1962                         ainfo->encoding = ENC_BASE64;
1963                 } else if (!g_strncasecmp(ainfo->content_type, "text", 4))
1964                         ainfo->encoding = procmime_get_encoding_for_file(file);
1965                 else
1966                         ainfo->encoding = ENC_BASE64;
1967                 ainfo->name = g_strdup(g_basename(filename ? filename : file)); 
1968         }
1969         ainfo->size = size;
1970
1971         text[COL_MIMETYPE] = ainfo->content_type;
1972         text[COL_SIZE] = to_human_readable(size);
1973         text[COL_NAME] = ainfo->name;
1974
1975         row = gtk_clist_append(GTK_CLIST(compose->attach_clist), text);
1976         gtk_clist_set_row_data(GTK_CLIST(compose->attach_clist), row, ainfo);
1977 }
1978
1979 #define IS_FIRST_PART_TEXT(info) \
1980         ((info->mime_type == MIME_TEXT || info->mime_type == MIME_TEXT_HTML || \
1981           info->mime_type == MIME_TEXT_ENRICHED) || \
1982          (info->mime_type == MIME_MULTIPART && info->content_type && \
1983           !strcasecmp(info->content_type, "multipart/alternative") && \
1984           (info->children && \
1985            (info->children->mime_type == MIME_TEXT || \
1986             info->children->mime_type == MIME_TEXT_HTML || \
1987             info->children->mime_type == MIME_TEXT_ENRICHED))))
1988
1989 static void compose_attach_parts(Compose *compose, MsgInfo *msginfo)
1990 {
1991         MimeInfo *mimeinfo;
1992         MimeInfo *child;
1993         gchar *infile;
1994         gchar *outfile;
1995
1996         mimeinfo = procmime_scan_message(msginfo);
1997         if (!mimeinfo) return;
1998
1999         /* skip first text (presumably message body) */
2000         child = mimeinfo->children;
2001         if (!child || IS_FIRST_PART_TEXT(mimeinfo)) {
2002                 procmime_mimeinfo_free_all(mimeinfo);
2003                 return;
2004         }
2005         if (IS_FIRST_PART_TEXT(child))
2006                 child = child->next;
2007
2008         infile = procmsg_get_message_file_path(msginfo);
2009
2010         while (child != NULL) {
2011                 if (child->children || child->mime_type == MIME_MULTIPART) {
2012                         child = procmime_mimeinfo_next(child);
2013                         continue;
2014                 }
2015
2016                 outfile = procmime_get_tmp_file_name(child);
2017                 if (procmime_get_part(outfile, infile, child) < 0)
2018                         g_warning(_("Can't get the part of multipart message."));
2019                 else
2020                         compose_attach_append
2021                                 (compose, outfile,
2022                                  child->filename ? child->filename : child->name,
2023                                  child->content_type);
2024
2025                 child = child->next;
2026         }
2027
2028         g_free(infile);
2029         procmime_mimeinfo_free_all(mimeinfo);
2030 }
2031
2032 #undef IS_FIRST_PART_TEXT
2033
2034 #define GET_CHAR(pos, buf, len)                                              \
2035 {                                                                            \
2036         if (text->use_wchar)                                                 \
2037                 len = wctomb(buf, (wchar_t)GTK_STEXT_INDEX(text, (pos)));    \
2038         else {                                                               \
2039                 buf[0] = GTK_STEXT_INDEX(text, (pos));                       \
2040                 len = 1;                                                     \
2041         }                                                                    \
2042 }
2043
2044 #define INDENT_CHARS    ">|#"
2045 #define SPACE_CHARS     " \t"
2046
2047 static void compose_wrap_line(Compose *compose)
2048 {
2049         GtkSText *text = GTK_STEXT(compose->text);
2050         gint ch_len, last_ch_len;
2051         gchar cbuf[MB_LEN_MAX], last_ch;
2052         guint text_len;
2053         guint line_end;
2054         guint quoted;
2055         gint p_start, p_end;
2056         gint line_pos, cur_pos;
2057         gint line_len, cur_len;
2058
2059         gtk_stext_freeze(text);
2060
2061         text_len = gtk_stext_get_length(text);
2062
2063         /* check to see if the point is on the paragraph mark (empty line). */
2064         cur_pos = gtk_stext_get_point(text);
2065         GET_CHAR(cur_pos, cbuf, ch_len);
2066         if ((ch_len == 1 && *cbuf == '\n') || cur_pos == text_len) {
2067                 if (cur_pos == 0)
2068                         goto compose_end; /* on the paragraph mark */
2069                 GET_CHAR(cur_pos - 1, cbuf, ch_len);
2070                 if (ch_len == 1 && *cbuf == '\n')
2071                         goto compose_end; /* on the paragraph mark */
2072         }
2073
2074         /* find paragraph start. */
2075         line_end = quoted = 0;
2076         for (p_start = cur_pos; p_start >= 0; --p_start) {
2077                 GET_CHAR(p_start, cbuf, ch_len);
2078                 if (ch_len == 1 && *cbuf == '\n') {
2079                         if (quoted)
2080                                 goto compose_end; /* quoted part */
2081                         if (line_end) {
2082                                 p_start += 2;
2083                                 break;
2084                         }
2085                         line_end = 1;
2086                 } else {
2087                         if (ch_len == 1 
2088                             && strchr(prefs_common.quote_chars, *cbuf))
2089                                 quoted = 1;
2090                         else if (ch_len != 1 || !isspace(*cbuf))
2091                                 quoted = 0;
2092
2093                         line_end = 0;
2094                 }
2095         }
2096         if (p_start < 0)
2097                 p_start = 0;
2098
2099         /* find paragraph end. */
2100         line_end = 0;
2101         for (p_end = cur_pos; p_end < text_len; p_end++) {
2102                 GET_CHAR(p_end, cbuf, ch_len);
2103                 if (ch_len == 1 && *cbuf == '\n') {
2104                         if (line_end) {
2105                                 p_end -= 1;
2106                                 break;
2107                         }
2108                         line_end = 1;
2109                 } else {
2110                         if (line_end && ch_len == 1 &&
2111                             strchr(prefs_common.quote_chars, *cbuf))
2112                                 goto compose_end; /* quoted part */
2113
2114                         line_end = 0;
2115                 }
2116         }
2117         if (p_end >= text_len)
2118                 p_end = text_len;
2119
2120         if (p_start >= p_end)
2121                 goto compose_end;
2122
2123         line_len = cur_len = 0;
2124         last_ch_len = 0;
2125         last_ch = '\0';
2126         line_pos = p_start;
2127         for (cur_pos = p_start; cur_pos < p_end; cur_pos++) {
2128                 guint space = 0;
2129
2130                 GET_CHAR(cur_pos, cbuf, ch_len);
2131
2132                 if (ch_len < 0) {
2133                         cbuf[0] = '\0';
2134                         ch_len = 1;
2135                 }
2136
2137                 if (ch_len == 1 && isspace(*cbuf))
2138                         space = 1;
2139
2140                 if (ch_len == 1 && *cbuf == '\n') {
2141                         guint replace = 0;
2142                         if (last_ch_len == 1 && !isspace(last_ch)) {
2143                                 if (cur_pos + 1 < p_end) {
2144                                         GET_CHAR(cur_pos + 1, cbuf, ch_len);
2145                                         if (ch_len == 1 && !isspace(*cbuf))
2146                                                 replace = 1;
2147                                 }
2148                         }
2149                         gtk_stext_set_point(text, cur_pos + 1);
2150                         gtk_stext_backward_delete(text, 1);
2151                         if (replace) {
2152                                 gtk_stext_set_point(text, cur_pos);
2153                                 gtk_stext_insert(text, NULL, NULL, NULL, " ", 1);
2154                                 space = 1;
2155                         }
2156                         else {
2157                                 p_end--;
2158                                 cur_pos--;
2159                                 continue;
2160                         }
2161                 }
2162
2163                 last_ch_len = ch_len;
2164                 last_ch = *cbuf;
2165
2166                 if (space) {
2167                         line_pos = cur_pos + 1;
2168                         line_len = cur_len + ch_len;
2169                 }
2170
2171                 if (cur_len + ch_len > prefs_common.linewrap_len &&
2172                     line_len > 0) {
2173                         gint tlen = ch_len;
2174
2175                         GET_CHAR(line_pos - 1, cbuf, ch_len);
2176                         if (ch_len == 1 && isspace(*cbuf)) {
2177                                 gtk_stext_set_point(text, line_pos);
2178                                 gtk_stext_backward_delete(text, 1);
2179                                 p_end--;
2180                                 cur_pos--;
2181                                 line_pos--;
2182                                 cur_len--;
2183                                 line_len--;
2184                         }
2185                         ch_len = tlen;
2186
2187                         gtk_stext_set_point(text, line_pos);
2188                         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1);
2189                         p_end++;
2190                         cur_pos++;
2191                         line_pos++;
2192                         cur_len = cur_len - line_len + ch_len;
2193                         line_len = 0;
2194                         continue;
2195                 }
2196
2197                 if (ch_len > 1) {
2198                         line_pos = cur_pos + 1;
2199                         line_len = cur_len + ch_len;
2200                 }
2201                 cur_len += ch_len;
2202         }
2203
2204 compose_end:
2205         gtk_stext_thaw(text);
2206 }
2207
2208 #undef WRAP_DEBUG
2209 #ifdef WRAP_DEBUG
2210 /* Darko: used when I debug wrapping */
2211 void dump_text(GtkSText *text, int pos, int tlen, int breakoncr)
2212 {
2213         gint i;
2214         gchar ch;
2215
2216         printf("%d [", pos);
2217         for (i = pos; i < tlen; i++) {
2218                 ch = GTK_STEXT_INDEX(text, i);
2219                 if (breakoncr && ch == '\n')
2220                         break;
2221                 printf("%c", ch);
2222         }
2223         printf("]\n");
2224 }
2225 #endif
2226
2227 typedef enum {
2228         WAIT_FOR_SPACE,
2229         WAIT_FOR_INDENT_CHAR,
2230         WAIT_FOR_INDENT_CHAR_OR_SPACE
2231 } IndentState;
2232
2233 /* return indent length, we allow:
2234    > followed by spaces/tabs
2235    | followed by spaces/tabs
2236    uppercase characters immediately followed by >,
2237    and the repeating sequences of the above */
2238 /* return indent length */
2239 static guint get_indent_length(GtkSText *text, guint start_pos, guint text_len)
2240 {
2241         guint i_len = 0;
2242         guint i, ch_len, alnum_cnt = 0;
2243         IndentState state = WAIT_FOR_INDENT_CHAR;
2244         gchar cbuf[MB_LEN_MAX];
2245         gboolean is_space;
2246         gboolean is_indent;
2247
2248         for (i = start_pos; i < text_len; i++) {
2249                 GET_CHAR(i, cbuf, ch_len);
2250                 if (ch_len > 1)
2251                         break;
2252
2253                 if (cbuf[0] == '\n')
2254                         break;
2255
2256                 is_indent = strchr(prefs_common.quote_chars, cbuf[0]) ? TRUE : FALSE;
2257                 is_space = strchr(SPACE_CHARS, cbuf[0]) ? TRUE : FALSE;
2258
2259                 switch (state) {
2260                 case WAIT_FOR_SPACE:
2261                         if (is_space == FALSE)
2262                                 goto out;
2263                         state = WAIT_FOR_INDENT_CHAR_OR_SPACE;
2264                         break;
2265                 case WAIT_FOR_INDENT_CHAR_OR_SPACE:
2266                         if (is_indent == FALSE && is_space == FALSE &&
2267                             !isupper(cbuf[0]))
2268                                 goto out;
2269                         if (is_space == TRUE) {
2270                                 alnum_cnt = 0;
2271                                 state = WAIT_FOR_INDENT_CHAR_OR_SPACE;
2272                         } else if (is_indent == TRUE) {
2273                                 alnum_cnt = 0;
2274                                 state = WAIT_FOR_SPACE;
2275                         } else {
2276                                 alnum_cnt++;
2277                                 state = WAIT_FOR_INDENT_CHAR;
2278                         }
2279                         break;
2280                 case WAIT_FOR_INDENT_CHAR:
2281                         if (is_indent == FALSE && !isupper(cbuf[0]))
2282                                 goto out;
2283                         if (is_indent == TRUE) {
2284                                 if (alnum_cnt > 0 
2285                                     && !strchr(prefs_common.quote_chars, cbuf[0]))
2286                                         goto out;
2287                                 alnum_cnt = 0;
2288                                 state = WAIT_FOR_SPACE;
2289                         } else {
2290                                 alnum_cnt++;
2291                         }
2292                         break;
2293                 }
2294
2295                 i_len++;
2296         }
2297
2298 out:
2299         if ((i_len > 0) && (state == WAIT_FOR_INDENT_CHAR))
2300                 i_len -= alnum_cnt;
2301
2302         return i_len;
2303 }
2304
2305 /* insert quotation string when line was wrapped */
2306 static guint ins_quote(GtkSText *text, guint indent_len,
2307                        guint prev_line_pos, guint text_len,
2308                        gchar *quote_fmt)
2309 {
2310         guint i, ins_len = 0;
2311         gchar ch;
2312
2313         if (indent_len) {
2314                 for (i = 0; i < indent_len; i++) {
2315                         ch = GTK_STEXT_INDEX(text, prev_line_pos + i);
2316                         gtk_stext_insert(text, NULL, NULL, NULL, &ch, 1);
2317                 }
2318                 ins_len = indent_len;
2319         }
2320
2321         return ins_len;
2322 }
2323
2324 /* check if we should join the next line */
2325 static gboolean join_next_line(GtkSText *text, guint start_pos, guint tlen,
2326                                guint prev_ilen)
2327 {
2328         guint indent_len, ch_len;
2329         gboolean do_join = FALSE;
2330         gchar cbuf[MB_LEN_MAX];
2331
2332         indent_len = get_indent_length(text, start_pos, tlen);
2333
2334         if ((indent_len > 0) && (indent_len == prev_ilen)) {
2335                 GET_CHAR(start_pos + indent_len, cbuf, ch_len);
2336                 if (ch_len > 0 && (cbuf[0] != '\n'))
2337                         do_join = TRUE;
2338         }
2339
2340         return do_join;
2341 }
2342
2343 static void compose_wrap_line_all(Compose *compose)
2344 {
2345         GtkSText *text = GTK_STEXT(compose->text);
2346         guint tlen;
2347         guint line_pos = 0, cur_pos = 0, p_pos = 0;
2348         gint line_len = 0, cur_len = 0;
2349         gint ch_len;
2350         gboolean is_new_line = TRUE, do_delete = FALSE;
2351         guint i_len = 0;
2352         gboolean linewrap_quote = TRUE;
2353         guint linewrap_len = prefs_common.linewrap_len;
2354         gchar *qfmt = prefs_common.quotemark;
2355         gchar cbuf[MB_LEN_MAX];
2356
2357         gtk_stext_freeze(text);
2358
2359         /* make text buffer contiguous */
2360         /* gtk_stext_compact_buffer(text); */
2361
2362         tlen = gtk_stext_get_length(text);
2363
2364         for (; cur_pos < tlen; cur_pos++) {
2365                 /* mark position of new line - needed for quotation wrap */
2366                 if (is_new_line) {
2367                         if (linewrap_quote)
2368                                 i_len = get_indent_length(text, cur_pos, tlen);
2369
2370                         is_new_line = FALSE;
2371                         p_pos = cur_pos;
2372 #ifdef WRAP_DEBUG
2373                         printf("new line i_len=%d p_pos=", i_len);
2374                         dump_text(text, p_pos, tlen, 1);
2375 #endif
2376                 }
2377
2378                 GET_CHAR(cur_pos, cbuf, ch_len);
2379
2380                 /* fix line length for tabs */
2381                 if (ch_len == 1 && *cbuf == '\t') {
2382                         guint tab_width = text->default_tab_width;
2383                         guint tab_offset = line_len % tab_width;
2384
2385 #ifdef WRAP_DEBUG
2386                         printf("found tab at pos=%d line_len=%d ", cur_pos,
2387                                 line_len);
2388 #endif
2389                         if (tab_offset) {
2390                                 line_len += tab_width - tab_offset - 1;
2391                                 cur_len = line_len;
2392                         }
2393 #ifdef WRAP_DEBUG
2394                         printf("new_len=%d\n", line_len);
2395 #endif
2396                 }
2397
2398                 /* we have encountered line break */
2399                 if (ch_len == 1 && *cbuf == '\n') {
2400                         gint clen;
2401                         gchar cb[MB_CUR_MAX];
2402
2403                         /* should we join the next line */
2404                         if ((i_len != cur_len) && do_delete &&
2405                             join_next_line(text, cur_pos + 1, tlen, i_len))
2406                                 do_delete = TRUE;
2407                         else
2408                                 do_delete = FALSE;
2409
2410 #ifdef WRAP_DEBUG
2411                         printf("found CR at %d do_del is %d next line is ",
2412                                cur_pos, do_delete);
2413                         dump_text(text, cur_pos + 1, tlen, 1);
2414 #endif
2415
2416                         /* skip delete if it is continuous URL */
2417                         if (do_delete && (line_pos - p_pos <= i_len) &&
2418                             gtkut_stext_is_uri_string(text, line_pos, tlen))
2419                                 do_delete = FALSE;
2420
2421 #ifdef WRAP_DEBUG
2422                         printf("l_len=%d wrap_len=%d do_del=%d\n",
2423                                 line_len, linewrap_len, do_delete);
2424 #endif
2425                         /* should we delete to perform smart wrapping */
2426                         if (line_len < linewrap_len && do_delete) {
2427                                 /* get rid of newline */
2428                                 gtk_stext_set_point(text, cur_pos);
2429                                 gtk_stext_forward_delete(text, 1);
2430                                 tlen--;
2431
2432                                 /* if text starts with quote fmt or with
2433                                    indent string, delete them */
2434                                 if (i_len) {
2435                                         guint ilen;
2436                                         ilen =  gtkut_stext_str_compare_n
2437                                                 (text, cur_pos, p_pos, i_len,
2438                                                  tlen);
2439                                         if (ilen) {
2440                                                 gtk_stext_forward_delete
2441                                                         (text, ilen);
2442                                                 tlen -= ilen;
2443                                         }
2444                                 }
2445
2446                                 GET_CHAR(cur_pos, cb, clen);
2447
2448                                 /* insert space if it's alphanumeric */
2449                                 if ((cur_pos != line_pos) &&
2450                                     ((clen > 1) || isalnum(cb[0]))) {
2451                                         gtk_stext_insert(text, NULL, NULL,
2452                                                         NULL, " ", 1);
2453                                         /* gtk_stext_compact_buffer(text); */
2454                                         tlen++;
2455                                 }
2456
2457                                 /* and start over with current line */
2458                                 cur_pos = p_pos - 1;
2459                                 line_pos = cur_pos;
2460                                 line_len = cur_len = 0;
2461                                 do_delete = FALSE;
2462                                 is_new_line = TRUE;
2463 #ifdef WRAP_DEBUG
2464                                 printf("after delete l_pos=");
2465                                 dump_text(text, line_pos, tlen, 1);
2466 #endif
2467                                 continue;
2468                         }
2469
2470                         /* mark new line beginning */
2471                         line_pos = cur_pos + 1;
2472                         line_len = cur_len = 0;
2473                         do_delete = FALSE;
2474                         is_new_line = TRUE;
2475                         continue;
2476                 }
2477
2478                 if (ch_len < 0) {
2479                         cbuf[0] = '\0';
2480                         ch_len = 1;
2481                 }
2482
2483                 /* possible line break */
2484                 if (ch_len == 1 && isspace(*cbuf)) {
2485                         line_pos = cur_pos + 1;
2486                         line_len = cur_len + ch_len;
2487                 }
2488
2489                 /* are we over wrapping length set in preferences ? */
2490                 if (cur_len + ch_len > linewrap_len) {
2491                         gint clen;
2492
2493 #ifdef WRAP_DEBUG
2494                         printf("should wrap cur_pos=%d ", cur_pos);
2495                         dump_text(text, p_pos, tlen, 1);
2496                         dump_text(text, line_pos, tlen, 1);
2497 #endif
2498                         /* force wrapping if it is one long word but not URL */
2499                         if (line_pos - p_pos <= i_len)
2500                                 if (!gtkut_stext_is_uri_string
2501                                     (text, line_pos, tlen))
2502                                         line_pos = cur_pos - 1;
2503 #ifdef WRAP_DEBUG
2504                         printf("new line_pos=%d\n", line_pos);
2505 #endif
2506
2507                         GET_CHAR(line_pos - 1, cbuf, clen);
2508
2509                         /* if next character is space delete it */
2510                         if (clen == 1 && isspace(*cbuf)) {
2511                                 if (p_pos + i_len != line_pos ||
2512                                     !gtkut_stext_is_uri_string
2513                                         (text, line_pos, tlen)) {
2514                                         gtk_stext_set_point(text, line_pos);
2515                                         gtk_stext_backward_delete(text, 1);
2516                                         tlen--;
2517                                         cur_pos--;
2518                                         line_pos--;
2519                                         cur_len--;
2520                                         line_len--;
2521                                 }
2522                         }
2523
2524                         /* if it is URL at beginning of line don't wrap */
2525                         if (p_pos + i_len == line_pos &&
2526                             gtkut_stext_is_uri_string(text, line_pos, tlen)) {
2527 #ifdef WRAP_DEBUG
2528                                 printf("found URL at ");
2529                                 dump_text(text, line_pos, tlen, 1);
2530 #endif
2531                                 continue;
2532                         }
2533
2534                         /* insert CR */
2535                         gtk_stext_set_point(text, line_pos);
2536                         gtk_stext_insert(text, NULL, NULL, NULL, "\n", 1);
2537                         /* gtk_stext_compact_buffer(text); */
2538                         tlen++;
2539                         line_pos++;
2540                         /* for loop will increase it */
2541                         cur_pos = line_pos - 1;
2542                         /* start over with current line */
2543                         is_new_line = TRUE;
2544                         line_len = 0;
2545                         cur_len = 0;
2546                         if (i_len)
2547                                 do_delete = TRUE;
2548                         else
2549                                 do_delete = FALSE;
2550 #ifdef WRAP_DEBUG
2551                         printf("after CR insert ");
2552                         dump_text(text, line_pos, tlen, 1);
2553                         dump_text(text, cur_pos, tlen, 1);
2554 #endif
2555
2556                         /* should we insert quotation ? */
2557                         if (linewrap_quote && i_len) {
2558                                 /* only if line is not already quoted  */
2559                                 if (!gtkut_stext_str_compare
2560                                         (text, line_pos, tlen, qfmt)) {
2561                                         guint ins_len;
2562
2563                                         if (line_pos - p_pos > i_len) {
2564                                                 ins_len = ins_quote
2565                                                         (text, i_len, p_pos,
2566                                                          tlen, qfmt);
2567
2568                                                 /* gtk_stext_compact_buffer(text); */
2569                                                 tlen += ins_len;
2570                                         }
2571 #ifdef WRAP_DEBUG
2572                                         printf("after quote insert ");
2573                                         dump_text(text, line_pos, tlen, 1);
2574 #endif
2575                                 }
2576                         }
2577                         continue;
2578                 }
2579
2580                 if (ch_len > 1) {
2581                         line_pos = cur_pos + 1;
2582                         line_len = cur_len + ch_len;
2583                 }
2584                 /* advance to next character in buffer */
2585                 cur_len += ch_len;
2586         }
2587
2588         gtk_stext_thaw(text);
2589 }
2590
2591 #undef GET_CHAR
2592
2593 static void compose_set_title(Compose *compose)
2594 {
2595         gchar *str;
2596         gchar *edited;
2597
2598         edited = compose->modified ? _(" [Edited]") : "";
2599         if (compose->account && compose->account->address)
2600                 str = g_strdup_printf(_("%s - Compose message%s"),
2601                                       compose->account->address, edited);
2602         else
2603                 str = g_strdup_printf(_("Compose message%s"), edited);
2604         gtk_window_set_title(GTK_WINDOW(compose->window), str);
2605         g_free(str);
2606 }
2607
2608 /**
2609  * compose_current_mail_account:
2610  * 
2611  * Find a current mail account (the currently selected account, or the
2612  * default account, if a news account is currently selected).  If a
2613  * mail account cannot be found, display an error message.
2614  * 
2615  * Return value: Mail account, or NULL if not found.
2616  **/
2617 static PrefsAccount *
2618 compose_current_mail_account(void)
2619 {
2620         PrefsAccount *ac;
2621
2622         if (cur_account && cur_account->protocol != A_NNTP)
2623                 ac = cur_account;
2624         else {
2625                 ac = account_get_default();
2626                 if (!ac || ac->protocol == A_NNTP) {
2627                         alertpanel_error(_("Account for sending mail is not specified.\n"
2628                                            "Please select a mail account before sending."));
2629                         return NULL;
2630                 }
2631         }
2632         return ac;
2633 }
2634
2635 gboolean compose_check_for_valid_recipient(Compose *compose) {
2636         gchar *recipient_headers_mail[] = {"To:", "Cc:", "Bcc:", NULL};
2637         gchar *recipient_headers_news[] = {"Newsgroups:", NULL};
2638         gboolean recipient_found = FALSE;
2639         GSList *list;
2640         gchar **strptr;
2641
2642         /* free to and newsgroup list */
2643         slist_free_strings(compose->to_list);
2644         g_slist_free(compose->to_list);
2645         compose->to_list = NULL;
2646                         
2647         slist_free_strings(compose->newsgroup_list);
2648         g_slist_free(compose->newsgroup_list);
2649         compose->newsgroup_list = NULL;
2650
2651         /* search header entries for to and newsgroup entries */
2652         for(list = compose->header_list; list; list = list->next) {
2653                 gchar *header;
2654                 gchar *entry;
2655                 header = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(((ComposeHeaderEntry *)list->data)->combo)->entry));
2656                 entry = gtk_editable_get_chars(GTK_EDITABLE(((ComposeHeaderEntry *)list->data)->entry), 0, -1);
2657                 g_strstrip(entry);
2658                 if(entry[0] != '\0') {
2659                         for(strptr = recipient_headers_mail; *strptr != NULL; strptr++) {
2660                                 if(!strcmp(header, (prefs_common.trans_hdr ? gettext(*strptr) : *strptr))) {
2661                                         compose->to_list = address_list_append(compose->to_list, entry);
2662                                         recipient_found = TRUE;
2663                                 }
2664                         }
2665                         for(strptr = recipient_headers_news; *strptr != NULL; strptr++) {
2666                                 if(!strcmp(header, (prefs_common.trans_hdr ? gettext(*strptr) : *strptr))) {
2667                                         compose->newsgroup_list = newsgroup_list_append(compose->newsgroup_list, entry);
2668                                         recipient_found = TRUE;
2669                                 }
2670                         }
2671                 }
2672                 g_free(entry);
2673         }
2674         return recipient_found;
2675 }
2676
2677 static gboolean compose_check_entries(Compose *compose, gboolean check_subject)
2678 {
2679         gchar *str;
2680
2681         if (compose_check_for_valid_recipient(compose) == FALSE) {
2682                 alertpanel_error(_("Recipient is not specified."));
2683                 return FALSE;
2684         }
2685
2686         str = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
2687         if (*str == '\0' && check_subject == TRUE) {
2688                 AlertValue aval;
2689
2690                 aval = alertpanel(_("Send"),
2691                                   _("Subject is empty. Send it anyway?"),
2692                                   _("Yes"), _("No"), NULL);
2693                 if (aval != G_ALERTDEFAULT)
2694                         return FALSE;
2695         }
2696
2697         return TRUE;
2698 }
2699
2700 gint compose_send(Compose *compose)
2701 {
2702         gint msgnum;
2703         FolderItem *folder;
2704         gint val;
2705
2706         if (compose_check_entries(compose, TRUE) == FALSE)
2707                 return -1;
2708
2709         val = compose_queue(compose, &msgnum, &folder);
2710         if (val) {
2711                 alertpanel_error(_("Could not queue message for sending"));
2712                 return -1;
2713         }
2714         
2715         val = procmsg_send_message_queue(folder_item_fetch_msg(folder, msgnum));
2716
2717         folder_item_remove_msg(folder, msgnum);
2718         folderview_update_item(folder, TRUE);
2719
2720         return val;
2721 }
2722
2723 #if 0 /* compose restructure */
2724 gint compose_send(Compose *compose)
2725 {
2726         gchar tmp[MAXPATHLEN + 1];
2727         gint ok = 0;
2728         static gboolean lock = FALSE;
2729
2730         if (lock) return 1;
2731
2732         g_return_val_if_fail(compose->account != NULL, -1);
2733         g_return_val_if_fail(compose->orig_account != NULL, -1);
2734
2735         lock = TRUE;
2736
2737         if (compose_check_entries(compose, TRUE) == FALSE) {
2738                 lock = FALSE;
2739                 return 1;
2740         }
2741
2742         /* write to temporary file */
2743         g_snprintf(tmp, sizeof(tmp), "%s%ctmpmsg%d",
2744                    get_rc_dir(), G_DIR_SEPARATOR, (gint)compose);
2745
2746         if (prefs_common.linewrap_at_send)
2747                 compose_wrap_line_all(compose);
2748
2749         if (compose_write_to_file(compose, tmp, FALSE) < 0) {
2750                 lock = FALSE;
2751                 return -1;
2752         }
2753
2754         if (!compose->to_list && !compose->newsgroup_list) {
2755                 g_warning(_("can't get recipient list."));
2756                 unlink(tmp);
2757                 lock = FALSE;
2758                 return -1;
2759         }
2760
2761         if (compose->to_list) {
2762                 PrefsAccount *ac;
2763
2764 #if 0 /* NEW COMPOSE GUI */
2765                 if (compose->account->protocol != A_NNTP)
2766                         ac = compose->account;
2767                 else if (compose->orig_account->protocol != A_NNTP)
2768                         ac = compose->orig_account;
2769                 else if (cur_account && cur_account->protocol != A_NNTP)
2770                         ac = cur_account;
2771                 else {
2772                         ac = compose_current_mail_account();
2773                         if (!ac) {
2774                                 unlink(tmp);
2775                                 lock = FALSE;
2776                                 return -1;
2777                         }
2778                 }
2779 #endif
2780                 ac = compose->account;
2781
2782                 ok = send_message(tmp, ac, compose->to_list);
2783                 statusbar_pop_all();
2784         }
2785
2786         if (ok == 0 && compose->newsgroup_list) {
2787                 Folder *folder;
2788
2789                 if (compose->account->protocol == A_NNTP)
2790                         folder = FOLDER(compose->account->folder);
2791                 else
2792                         folder = FOLDER(compose->orig_account->folder);
2793
2794                 ok = news_post(folder, tmp);
2795                 if (ok < 0) {
2796                         alertpanel_error(_("Error occurred while posting the message to %s ."),
2797                                          compose->account->nntp_server);
2798                         unlink(tmp);
2799                         lock = FALSE;
2800                         return -1;
2801                 }
2802         }
2803
2804         /* queue message if failed to send */
2805         if (ok < 0) {
2806                 if (prefs_common.queue_msg) {
2807                         AlertValue val;
2808
2809                         val = alertpanel
2810                                 (_("Queueing"),
2811                                  _("Error occurred while sending the message.\n"
2812                                    "Put this message into queue folder?"),
2813                                  _("OK"), _("Cancel"), NULL);
2814                         if (G_ALERTDEFAULT == val) {
2815                                 ok = compose_queue(compose, tmp);
2816                                 if (ok < 0)
2817                                         alertpanel_error(_("Can't queue the message."));
2818                         }
2819                 } else
2820                         alertpanel_error(_("Error occurred while sending the message."));
2821         } else {
2822                 if (compose->mode == COMPOSE_REEDIT) {
2823                         compose_remove_reedit_target(compose);
2824                         if (compose->targetinfo)
2825                                 folderview_update_item
2826                                         (compose->targetinfo->folder, TRUE);
2827                 }
2828                 /* save message to outbox */
2829                 if (prefs_common.savemsg) {
2830                         FolderItem *outbox;
2831
2832                         outbox = account_get_special_folder
2833                                 (compose->account, F_OUTBOX);
2834                         if (procmsg_save_to_outbox(outbox, tmp, FALSE) < 0)
2835                                 alertpanel_error
2836                                         (_("Can't save the message to Sent."));
2837                         else
2838                                 folderview_update_item(outbox, TRUE);
2839                 }
2840         }
2841
2842         unlink(tmp);
2843         lock = FALSE;
2844         return ok;
2845 }
2846 #endif
2847
2848 static gboolean compose_use_attach(Compose *compose) {
2849     return(gtk_clist_get_row_data(GTK_CLIST(compose->attach_clist), 0) != NULL);
2850 }
2851
2852 static gint compose_redirect_write_headers_from_headerlist(Compose *compose, 
2853                                                            FILE *fp)
2854 {
2855         gchar buf[BUFFSIZE];
2856         gchar *str;
2857         gboolean first_address;
2858         GSList *list;
2859         ComposeHeaderEntry *headerentry;
2860         gchar *headerentryname;
2861         gchar *cc_hdr;
2862         gchar *to_hdr;
2863
2864         debug_print(_("Writing redirect header\n"));
2865
2866         cc_hdr = prefs_common.trans_hdr ? _("Cc:") : "Cc:";
2867         to_hdr = prefs_common.trans_hdr ? _("To:") : "To:";
2868
2869         first_address = TRUE;
2870         for(list = compose->header_list; list; list = list->next) {
2871                 headerentry = ((ComposeHeaderEntry *)list->data);
2872                 headerentryname = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry));
2873
2874                 if(g_strcasecmp(headerentryname, cc_hdr) == 0 
2875                    || g_strcasecmp(headerentryname, to_hdr) == 0) {
2876                         str = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
2877                         Xstrdup_a(str, str, return -1);
2878                         g_strstrip(str);
2879                         if(str[0] != '\0') {
2880                                 compose_convert_header
2881                                         (buf, sizeof(buf), str,
2882                                         strlen("Resent-To") + 2);
2883                                 if(first_address) {
2884                                         fprintf(fp, "Resent-To: ");
2885                                         first_address = FALSE;
2886                                 } else {
2887                                         fprintf(fp, ",");
2888                                 }
2889                                 fprintf(fp, "%s", buf);
2890                         }
2891                 }
2892         }
2893         /* if(!first_address) { */
2894         fprintf(fp, "\n");
2895         /* } */
2896
2897         return(0);
2898 }
2899
2900 static gint compose_redirect_write_headers(Compose *compose, FILE *fp)
2901 {
2902         gchar buf[BUFFSIZE];
2903         gchar *str;
2904         /* struct utsname utsbuf; */
2905
2906         g_return_val_if_fail(fp != NULL, -1);
2907         g_return_val_if_fail(compose->account != NULL, -1);
2908         g_return_val_if_fail(compose->account->address != NULL, -1);
2909
2910         /* Resent-Date */
2911         get_rfc822_date(buf, sizeof(buf));
2912         fprintf(fp, "Resent-Date: %s\n", buf);
2913
2914         /* Resent-From */
2915         if (compose->account->name && *compose->account->name) {
2916                 compose_convert_header
2917                         (buf, sizeof(buf), compose->account->name,
2918                          strlen("From: "));
2919                 fprintf(fp, "Resent-From: %s <%s>\n",
2920                         buf, compose->account->address);
2921         } else
2922                 fprintf(fp, "Resent-From: %s\n", compose->account->address);
2923
2924         /* Subject */
2925         str = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
2926         if (*str != '\0') {
2927                 Xstrdup_a(str, str, return -1);
2928                 g_strstrip(str);
2929                 if (*str != '\0') {
2930                         compose_convert_header(buf, sizeof(buf), str,
2931                                                strlen("Subject: "));
2932                         fprintf(fp, "Subject: %s\n", buf);
2933                 }
2934         }
2935
2936         /* Resent-Message-ID */
2937         if (compose->account->gen_msgid) {
2938                 compose_generate_msgid(compose, buf, sizeof(buf));
2939                 fprintf(fp, "Resent-Message-Id: <%s>\n", buf);
2940                 compose->msgid = g_strdup(buf);
2941         }
2942
2943         compose_redirect_write_headers_from_headerlist(compose, fp);
2944
2945         /* separator between header and body */
2946         fputs("\n", fp);
2947
2948         return 0;
2949 }
2950
2951 static gint compose_redirect_write_to_file(Compose *compose, const gchar *file)
2952 {
2953         FILE *fp;
2954         FILE *fdest;
2955         size_t len;
2956         gchar buf[BUFFSIZE];
2957
2958         if ((fp = fopen(compose->redirect_filename, "rb")) == NULL) {
2959                 FILE_OP_ERROR(file, "fopen");
2960                 return -1;
2961         }
2962
2963         if ((fdest = fopen(file, "wb")) == NULL) {
2964                 FILE_OP_ERROR(file, "fopen");
2965                 fclose(fp);
2966                 return -1;
2967         }
2968
2969         /* chmod for security */
2970         if (change_file_mode_rw(fdest, file) < 0) {
2971                 FILE_OP_ERROR(file, "chmod");
2972                 g_warning(_("can't change file mode\n"));
2973         }
2974
2975         while (procheader_get_unfolded_line(buf, sizeof(buf), fp)) {
2976                 /* should filter returnpath, delivered-to */
2977                 if (g_strncasecmp(buf, "Return-Path:",
2978                                    strlen("Return-Path:")) == 0 ||
2979                     g_strncasecmp(buf, "Delivered-To:",
2980                                   strlen("Delivered-To:")) == 0 ||
2981                     g_strncasecmp(buf, "Received:",
2982                                   strlen("Received:")) == 0 ||
2983                     g_strncasecmp(buf, "Subject:",
2984                                   strlen("Subject:")) == 0 ||
2985                     g_strncasecmp(buf, "X-UIDL:",
2986                                   strlen("X-UIDL:")) == 0)
2987                         continue;
2988
2989                 if (fputs(buf, fdest) == -1)
2990                         goto error;
2991
2992                 if (!prefs_common.redirect_keep_from) {
2993                         if (g_strncasecmp(buf, "From:",
2994                                           strlen("From:")) == 0) {
2995                                 fputs(" (by way of ", fdest);
2996                                 if (compose->account->name
2997                                     && *compose->account->name) {
2998                                         compose_convert_header
2999                                                 (buf, sizeof(buf),
3000                                                  compose->account->name,
3001                                                  strlen("From: "));
3002                                         fprintf(fdest, "%s <%s>",
3003                                                 buf,
3004                                                 compose->account->address);
3005                                 } else
3006                                         fprintf(fdest, "%s",
3007                                                 compose->account->address);
3008                                 fputs(")", fdest);
3009                         }
3010                 }
3011
3012                 if (fputs("\n", fdest) == -1)
3013                         goto error;
3014         }
3015
3016         compose_redirect_write_headers(compose, fdest);
3017
3018         while ((len = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
3019                 if (fwrite(buf, sizeof(gchar), len, fdest) != len) {
3020                         FILE_OP_ERROR(file, "fwrite");
3021                         goto error;
3022                 }
3023         }
3024
3025         fclose(fp);
3026         if (fclose(fdest) == EOF) {
3027                 FILE_OP_ERROR(file, "fclose");
3028                 unlink(file);
3029                 return -1;
3030         }
3031
3032         return 0;
3033  error:
3034         fclose(fp);
3035         fclose(fdest);
3036         unlink(file);
3037
3038         return -1;
3039 }
3040
3041
3042 #ifdef USE_GPGME
3043 /*
3044  * interfaces to rfc2015 to keep out the prefs stuff there.
3045  * returns 0 on success and -1 on error. */
3046 static int compose_create_signers_list (Compose *compose, GSList **pkey_list)
3047 {
3048         const char *keyid = NULL;
3049         GSList *key_list;
3050
3051         switch (compose->account->sign_key) {
3052         case SIGN_KEY_DEFAULT:
3053                 *pkey_list = NULL;
3054                 return 0;               /* nothing to do */
3055
3056         case SIGN_KEY_BY_FROM:
3057                 keyid = compose->account->address;
3058                 break;
3059
3060         case SIGN_KEY_CUSTOM:
3061                 keyid = compose->account->sign_key_id;
3062                 break;
3063
3064         default:
3065                 g_assert_not_reached ();
3066         }
3067
3068         key_list = rfc2015_create_signers_list(keyid);
3069
3070         if (!key_list) {
3071             alertpanel_error("Could not find any key associated with currently "
3072                                 "selected keyid `%s'!", keyid);
3073             return -1;
3074         }
3075         
3076         *pkey_list = key_list;
3077         return 0;
3078 }
3079 #endif /* USE_GPGME */
3080
3081 static gint compose_write_to_file(Compose *compose, const gchar *file,
3082                                   gboolean is_draft)
3083 {
3084         FILE *fp;
3085         size_t len;
3086         gchar *chars;
3087         gchar *buf;
3088         const gchar *out_codeset;
3089         EncodingType encoding;
3090
3091         if ((fp = fopen(file, "wb")) == NULL) {
3092                 FILE_OP_ERROR(file, "fopen");
3093                 return -1;
3094         }
3095
3096         /* chmod for security */
3097         if (change_file_mode_rw(fp, file) < 0) {
3098                 FILE_OP_ERROR(file, "chmod");
3099                 g_warning(_("can't change file mode\n"));
3100         }
3101
3102         /* get all composed text */
3103         chars = gtk_editable_get_chars(GTK_EDITABLE(compose->text), 0, -1);
3104         len = strlen(chars);
3105         if (is_ascii_str(chars)) {
3106                 buf = g_strdup(chars);
3107                 out_codeset = CS_US_ASCII;
3108                 encoding = ENC_7BIT;
3109         } else {
3110                 const gchar *src_codeset;
3111
3112                 out_codeset = conv_get_outgoing_charset_str();
3113                 if (!strcasecmp(out_codeset, CS_US_ASCII))
3114                         out_codeset = CS_ISO_8859_1;
3115                 encoding = procmime_get_encoding_for_charset(out_codeset);
3116
3117                 src_codeset = conv_get_current_charset_str();
3118                 /* if current encoding is US-ASCII, set it the same as
3119                    outgoing one to prevent code conversion failure */
3120                 if (!strcasecmp(src_codeset, CS_US_ASCII))
3121                         src_codeset = out_codeset;
3122
3123                 debug_print("src encoding = %s, out encoding = %s, transfer encoding = %s\n",
3124                             src_codeset, out_codeset, procmime_get_encoding_str(encoding));
3125
3126                 buf = conv_codeset_strdup(chars, src_codeset, out_codeset);
3127                 if (!buf) {
3128                         AlertValue aval;
3129
3130                         aval = alertpanel
3131                                 (_("Error"),
3132                                  _("Can't convert the character encoding of the message.\n"
3133                                    "Send it anyway?"), _("Yes"), _("+No"), NULL);
3134                         if (aval != G_ALERTDEFAULT) {
3135                                 g_free(chars);
3136                                 fclose(fp);
3137                                 unlink(file);
3138                                 return -1;
3139                         } else {
3140                                 buf = g_strdup(chars);
3141                         }
3142                 }
3143         }
3144         g_free(chars);
3145
3146         /* write headers */
3147         if (compose_write_headers
3148                 (compose, fp, out_codeset, encoding, is_draft) < 0) {
3149                 g_warning(_("can't write headers\n"));
3150                 fclose(fp);
3151                 /* unlink(file); */
3152                 g_free(buf);
3153                 return -1;
3154         }
3155
3156         if (compose_use_attach(compose)) {
3157 #if USE_GPGME
3158             /* This prolog message is ignored by mime software and
3159              * because it would make our signing/encryption task
3160              * tougher, we don't emit it in that case */
3161             if (!compose->use_signing && !compose->use_encryption)
3162 #endif
3163                 fputs("This is a multi-part message in MIME format.\n", fp);
3164
3165                 fprintf(fp, "\n--%s\n", compose->boundary);
3166                 fprintf(fp, "Content-Type: text/plain; charset=%s\n",
3167                         out_codeset);
3168                 fprintf(fp, "Content-Transfer-Encoding: %s\n",
3169                         procmime_get_encoding_str(encoding));
3170                 fputc('\n', fp);
3171         }
3172
3173         /* write body */
3174         len = strlen(buf);
3175         if (encoding == ENC_BASE64) {
3176                 gchar outbuf[B64_BUFFSIZE];
3177                 gint i, l;
3178
3179                 for (i = 0; i < len; i += B64_LINE_SIZE) {
3180                         l = MIN(B64_LINE_SIZE, len - i);
3181                         to64frombits(outbuf, buf + i, l);
3182                         fputs(outbuf, fp);
3183                         fputc('\n', fp);
3184                 }
3185         } else if (fwrite(buf, sizeof(gchar), len, fp) != len) {
3186                 FILE_OP_ERROR(file, "fwrite");
3187                 fclose(fp);
3188                 unlink(file);
3189                 g_free(buf);
3190                 return -1;
3191         }
3192         g_free(buf);
3193
3194         if (compose_use_attach(compose))
3195                 compose_write_attach(compose, fp);
3196
3197         if (fclose(fp) == EOF) {
3198                 FILE_OP_ERROR(file, "fclose");
3199                 unlink(file);
3200                 return -1;
3201         }
3202
3203 #if USE_GPGME
3204         if (compose->use_signing) {
3205                 GSList *key_list;
3206                 
3207                 if (compose_create_signers_list(compose, &key_list) == -1 ||
3208                         rfc2015_sign(file, key_list) < 0) {
3209                     
3210                         unlink(file);
3211                         return -1;
3212                 }
3213         }
3214         if (compose->use_encryption) {
3215                 if (rfc2015_encrypt(file, compose->to_list, compose->account->ascii_armored) < 0) {
3216                         unlink(file);
3217                         return -1;
3218                 }
3219         }
3220 #endif /* USE_GPGME */
3221
3222         return 0;
3223 }
3224
3225 static gint compose_write_body_to_file(Compose *compose, const gchar *file)
3226 {
3227         FILE *fp;
3228         size_t len;
3229         gchar *chars;
3230
3231         if ((fp = fopen(file, "wb")) == NULL) {
3232                 FILE_OP_ERROR(file, "fopen");
3233                 return -1;
3234         }
3235
3236         /* chmod for security */
3237         if (change_file_mode_rw(fp, file) < 0) {
3238                 FILE_OP_ERROR(file, "chmod");
3239                 g_warning(_("can't change file mode\n"));
3240         }
3241
3242         chars = gtk_editable_get_chars(GTK_EDITABLE(compose->text), 0, -1);
3243
3244         /* write body */
3245         len = strlen(chars);
3246         if (fwrite(chars, sizeof(gchar), len, fp) != len) {
3247                 FILE_OP_ERROR(file, "fwrite");
3248                 g_free(chars);
3249                 fclose(fp);
3250                 unlink(file);
3251                 return -1;
3252         }
3253
3254         g_free(chars);
3255
3256         if (fclose(fp) == EOF) {
3257                 FILE_OP_ERROR(file, "fclose");
3258                 unlink(file);
3259                 return -1;
3260         }
3261         return 0;
3262 }
3263
3264 static gint compose_remove_reedit_target(Compose *compose)
3265 {
3266         FolderItem *item;
3267         MsgInfo *msginfo = compose->targetinfo;
3268
3269         g_return_val_if_fail(compose->mode == COMPOSE_REEDIT, -1);
3270         if (!msginfo) return -1;
3271
3272         item = msginfo->folder;
3273         g_return_val_if_fail(item != NULL, -1);
3274
3275         if (procmsg_msg_exist(msginfo) &&
3276             (item->stype == F_DRAFT || item->stype == F_QUEUE)) {
3277                 if (folder_item_remove_msg(item, msginfo->msgnum) < 0) {
3278                         g_warning(_("can't remove the old message\n"));
3279                         return -1;
3280                 }
3281         }
3282
3283         return 0;
3284 }
3285
3286 static gint compose_queue(Compose *compose, gint *msgnum, FolderItem **item)
3287 {
3288         return compose_queue_sub (compose, msgnum, item, FALSE);
3289 }
3290 static gint compose_queue_sub(Compose *compose, gint *msgnum, FolderItem **item, gboolean check_subject)
3291 {
3292         FolderItem *queue;
3293         gchar *tmp, *tmp2;
3294         FILE *fp, *src_fp;
3295         GSList *cur;
3296         gchar buf[BUFFSIZE];
3297         gint num;
3298         static gboolean lock = FALSE;
3299         PrefsAccount *mailac = NULL, *newsac = NULL;
3300         
3301         debug_print(_("queueing message...\n"));
3302         g_return_val_if_fail(compose->account != NULL, -1);
3303         g_return_val_if_fail(compose->orig_account != NULL, -1);
3304
3305         lock = TRUE;
3306         
3307         if (compose_check_entries(compose, check_subject) == FALSE) {
3308                 lock = FALSE;
3309                 return -1;
3310         }
3311
3312         if (!compose->to_list && !compose->newsgroup_list) {
3313                 g_warning(_("can't get recipient list."));
3314                 lock = FALSE;
3315                 return -1;
3316         }
3317
3318         if(compose->to_list) {
3319                 if (compose->account->protocol != A_NNTP)
3320                         mailac = compose->account;
3321                 else if (compose->orig_account->protocol != A_NNTP)
3322                         mailac = compose->orig_account;
3323                 else if (cur_account && cur_account->protocol != A_NNTP)
3324                         mailac = cur_account;
3325                 else if (!(mailac = compose_current_mail_account())) {
3326                         lock = FALSE;
3327                         alertpanel_error(_("No account for sending mails available!"));
3328                         return -1;
3329                 }
3330         }
3331
3332         if(compose->newsgroup_list) {
3333                 if (compose->account->protocol == A_NNTP)
3334                         newsac = compose->account;
3335                 else if(!(newsac = compose->orig_account) || (newsac->protocol != A_NNTP)) {
3336                         lock = FALSE;
3337                         alertpanel_error(_("No account for posting news available!"));
3338                         return -1;
3339                 }                       
3340         }
3341
3342         if (prefs_common.linewrap_at_send)
3343                 compose_wrap_line_all(compose);
3344                         
3345         /* write to temporary file */
3346         tmp2 = g_strdup_printf("%s%ctmp%d", g_get_tmp_dir(),
3347                                       G_DIR_SEPARATOR, (gint)compose);
3348
3349         if (compose->redirect_filename != NULL) {
3350                 if (compose_redirect_write_to_file(compose, tmp2) < 0) {
3351                         unlink(tmp2);
3352                         lock = FALSE;
3353                         return -1;
3354                 }
3355         }
3356         else {
3357                 if (compose_write_to_file(compose, tmp2, FALSE) < 0) {
3358                         unlink(tmp2);
3359                         lock = FALSE;
3360                         return -1;
3361                 }
3362         }
3363
3364         /* add queue header */
3365         tmp = g_strdup_printf("%s%cqueue.%d", g_get_tmp_dir(),
3366                               G_DIR_SEPARATOR, (gint)compose);
3367         if ((fp = fopen(tmp, "wb")) == NULL) {
3368                 FILE_OP_ERROR(tmp, "fopen");
3369                 g_free(tmp);
3370                 return -1;
3371         }
3372         if ((src_fp = fopen(tmp2, "rb")) == NULL) {
3373                 FILE_OP_ERROR(tmp2, "fopen");
3374                 fclose(fp);
3375                 unlink(tmp);
3376                 g_free(tmp);
3377                 unlink(tmp2);
3378                 g_free(tmp2);
3379                 return -1;
3380         }
3381         if (change_file_mode_rw(fp, tmp) < 0) {
3382                 FILE_OP_ERROR(tmp, "chmod");
3383                 g_warning(_("can't change file mode\n"));
3384         }
3385
3386         /* queueing variables */
3387         fprintf(fp, "AF:\n");
3388         fprintf(fp, "NF:0\n");
3389         fprintf(fp, "PS:10\n");
3390         fprintf(fp, "SRH:1\n");
3391         fprintf(fp, "SFN:\n");
3392         fprintf(fp, "DSR:\n");
3393         if (compose->msgid)
3394                 fprintf(fp, "MID:<%s>\n", compose->msgid);
3395         else
3396                 fprintf(fp, "MID:\n");
3397         fprintf(fp, "CFG:\n");
3398         fprintf(fp, "PT:0\n");
3399         fprintf(fp, "S:%s\n", compose->account->address);
3400         fprintf(fp, "RQ:\n");
3401         if (mailac)
3402                 fprintf(fp, "SSV:%s\n", mailac->smtp_server);
3403         else
3404                 fprintf(fp, "SSV:\n");
3405         if (newsac)
3406                 fprintf(fp, "NSV:%s\n", newsac->nntp_server);
3407         else
3408                 fprintf(fp, "NSV:\n");
3409         fprintf(fp, "SSH:\n");
3410         /* write recepient list */
3411         fprintf(fp, "R:");
3412         if(compose->to_list) {
3413                 fprintf(fp, "<%s>", (gchar *)compose->to_list->data);
3414                 for (cur = compose->to_list->next; cur != NULL; cur = cur->next)
3415                         fprintf(fp, ",<%s>", (gchar *)cur->data);
3416         }
3417         fprintf(fp, "\n");
3418         /* write newsgroup list */
3419         fprintf(fp, "NG:");
3420         if(compose->newsgroup_list) {
3421                 fprintf(fp, "%s", (gchar *)compose->newsgroup_list->data);
3422                 for (cur = compose->newsgroup_list->next; cur != NULL; cur = cur->next)
3423                         fprintf(fp, ",%s", (gchar *)cur->data);
3424         }
3425         fprintf(fp, "\n");
3426         /* Sylpheed account IDs */
3427         if(mailac) {
3428                 fprintf(fp, "MAID:%d\n", mailac->account_id);
3429         }
3430         if(newsac) {
3431                 fprintf(fp, "NAID:%d\n", newsac->account_id);
3432         }
3433         /* Save copy folder */
3434         if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn))) {
3435                 gchar *str;
3436                 
3437                 str = gtk_editable_get_chars(GTK_EDITABLE(compose->savemsg_entry), 0, -1);
3438                 fprintf(fp, "SCF:%s\n", str);
3439                 g_free(str);
3440         }
3441         fprintf(fp, "\n");
3442
3443         while (fgets(buf, sizeof(buf), src_fp) != NULL) {
3444                 if (fputs(buf, fp) == EOF) {
3445                         FILE_OP_ERROR(tmp, "fputs");
3446                         fclose(fp);
3447                         fclose(src_fp);
3448                         unlink(tmp);
3449                         g_free(tmp);
3450                         unlink(tmp2);
3451                         g_free(tmp2);
3452                         return -1;
3453                 }
3454         }
3455         fclose(src_fp);
3456         if (fclose(fp) == EOF) {
3457                 FILE_OP_ERROR(tmp, "fclose");
3458                 unlink(tmp);
3459                 g_free(tmp);
3460                 unlink(tmp2);
3461                 g_free(tmp2);
3462                 return -1;
3463         }
3464
3465         queue = account_get_special_folder(compose->account, F_QUEUE);
3466         if (!queue) {
3467                 g_warning(_("can't find queue folder\n"));
3468                 unlink(tmp);
3469                 g_free(tmp);
3470                 return -1;
3471         }
3472         folder_item_scan(queue);
3473         if ((num = folder_item_add_msg(queue, tmp, TRUE)) < 0) {
3474                 g_warning(_("can't queue the message\n"));
3475                 unlink(tmp);
3476                 g_free(tmp);
3477                 return -1;
3478         }
3479         unlink(tmp);
3480         g_free(tmp);
3481         unlink(tmp2);
3482         g_free(tmp2);
3483
3484         if (compose->mode == COMPOSE_REEDIT) {
3485                 compose_remove_reedit_target(compose);
3486                 if (compose->targetinfo &&
3487                     compose->targetinfo->folder != queue)
3488                         folderview_update_item
3489                                 (compose->targetinfo->folder, TRUE);
3490         }
3491
3492         folderview_update_item(queue, TRUE);
3493
3494         if((msgnum != NULL) && (item != NULL)) {
3495                 *msgnum = num;
3496                 *item = queue;
3497         }
3498
3499         return 0;
3500 }
3501
3502 static void compose_write_attach(Compose *compose, FILE *fp)
3503 {
3504         AttachInfo *ainfo;
3505         GtkCList *clist = GTK_CLIST(compose->attach_clist);
3506         gint row;
3507         FILE *attach_fp;
3508         gchar filename[BUFFSIZE];
3509         gint len;
3510
3511         for (row = 0; (ainfo = gtk_clist_get_row_data(clist, row)) != NULL;
3512              row++) {
3513                 gchar buf[BUFFSIZE];
3514                 gchar inbuf[B64_LINE_SIZE], outbuf[B64_BUFFSIZE];
3515
3516                 if ((attach_fp = fopen(ainfo->file, "rb")) == NULL) {
3517                         g_warning(_("Can't open file %s\n"), ainfo->file);
3518                         continue;
3519                 }
3520
3521                 fprintf(fp, "\n--%s\n", compose->boundary);
3522
3523                 if (!strcmp2(ainfo->content_type, "message/rfc822")) {
3524                         fprintf(fp, "Content-Type: %s\n", ainfo->content_type);
3525                         fprintf(fp, "Content-Disposition: inline\n");
3526                 } else {
3527                         conv_encode_header(filename, sizeof(filename),
3528                                            ainfo->name, 12);
3529                         fprintf(fp, "Content-Type: %s;\n"
3530                                     " name=\"%s\"\n",
3531                                 ainfo->content_type, filename);
3532                         fprintf(fp, "Content-Disposition: attachment;\n"
3533                                     " filename=\"%s\"\n", filename);
3534                 }
3535
3536                 fprintf(fp, "Content-Transfer-Encoding: %s\n\n",
3537                         procmime_get_encoding_str(ainfo->encoding));
3538
3539                 switch (ainfo->encoding) {
3540
3541                 case ENC_7BIT:
3542                 case ENC_8BIT:
3543                         /* if (ainfo->encoding == ENC_7BIT) { */
3544
3545                         while (fgets(buf, sizeof(buf), attach_fp) != NULL) {
3546                                 strcrchomp(buf);
3547                                 fputs(buf, fp);
3548                         }
3549                         break;
3550                         /* } else { */
3551                 case ENC_BASE64:
3552
3553                         while ((len = fread(inbuf, sizeof(gchar),
3554                                             B64_LINE_SIZE, attach_fp))
3555                                == B64_LINE_SIZE) {
3556                                 to64frombits(outbuf, inbuf, B64_LINE_SIZE);
3557                                 fputs(outbuf, fp);
3558                                 fputc('\n', fp);
3559                         }
3560                         if (len > 0 && feof(attach_fp)) {
3561                                 to64frombits(outbuf, inbuf, len);
3562                                 fputs(outbuf, fp);
3563                                 fputc('\n', fp);
3564                         }
3565                         break;
3566                 }
3567
3568                 fclose(attach_fp);
3569         }
3570
3571         fprintf(fp, "\n--%s--\n", compose->boundary);
3572 }
3573
3574 #define QUOTE_IF_REQUIRED(out, str)                     \
3575 {                                                       \
3576         if (*str != '"' && strchr(str, ',')) {          \
3577                 gchar *__tmp;                           \
3578                 gint len;                               \
3579                                                         \
3580                 len = strlen(str) + 3;                  \
3581                 Xalloca(__tmp, len, return -1);         \
3582                 g_snprintf(__tmp, len, "\"%s\"", str);  \
3583                 out = __tmp;                            \
3584         } else {                                        \
3585                 Xstrdup_a(out, str, return -1);         \
3586         }                                               \
3587 }
3588
3589 #define PUT_RECIPIENT_HEADER(header, str)                                    \
3590 {                                                                            \
3591         if (*str != '\0') {                                                  \
3592                 Xstrdup_a(str, str, return -1);                              \
3593                 g_strstrip(str);                                             \
3594                 if (*str != '\0') {                                          \
3595                         compose->to_list = address_list_append               \
3596                                 (compose->to_list, str);                     \
3597                         compose_convert_header                               \
3598                                 (buf, sizeof(buf), str, strlen(header) + 2); \
3599                         fprintf(fp, "%s: %s\n", header, buf);                \
3600                 }                                                            \
3601         }                                                                    \
3602 }
3603
3604 #define IS_IN_CUSTOM_HEADER(header) \
3605         (compose->account->add_customhdr && \
3606          custom_header_find(compose->account->customhdr_list, header) != NULL)
3607
3608 static gint compose_write_headers_from_headerlist(Compose *compose, 
3609                                                   FILE *fp, 
3610                                                   gchar *header)
3611 {
3612         gchar buf[BUFFSIZE];
3613         gchar *str, *header_w_colon, *trans_hdr;
3614         gboolean first_address;
3615         GSList *list;
3616         ComposeHeaderEntry *headerentry;
3617         gchar * headerentryname;
3618
3619         if (IS_IN_CUSTOM_HEADER(header)) {
3620                 return 0;
3621         }
3622
3623         debug_print(_("Writing %s-header\n"), header);
3624
3625         header_w_colon = g_strconcat(header, ":", NULL);
3626         trans_hdr = (prefs_common.trans_hdr ? gettext(header_w_colon) : header_w_colon);
3627
3628         first_address = TRUE;
3629         for(list = compose->header_list; list; list = list->next) {
3630                 headerentry = ((ComposeHeaderEntry *)list->data);
3631                 headerentryname = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(headerentry->combo)->entry));
3632
3633                 if(!g_strcasecmp(trans_hdr, headerentryname)) {
3634                         str = gtk_entry_get_text(GTK_ENTRY(headerentry->entry));
3635                         Xstrdup_a(str, str, return -1);
3636                         g_strstrip(str);
3637                         if(str[0] != '\0') {
3638                                 compose_convert_header
3639                                         (buf, sizeof(buf), str,
3640                                         strlen(header) + 2);
3641                                 if(first_address) {
3642                                         fprintf(fp, "%s: ", header);
3643                                         first_address = FALSE;
3644                                 } else {
3645                                         fprintf(fp, ",");
3646                                 }
3647                                 fprintf(fp, "%s", buf);
3648                         }
3649                 }
3650         }
3651         if(!first_address) {
3652                 fprintf(fp, "\n");
3653         }
3654
3655         g_free(header_w_colon);
3656
3657         return(0);
3658 }
3659
3660 static gint compose_write_headers(Compose *compose, FILE *fp,
3661                                   const gchar *charset, EncodingType encoding,
3662                                   gboolean is_draft)
3663 {
3664         gchar buf[BUFFSIZE];
3665         gchar *str;
3666         gchar *name;
3667         /* struct utsname utsbuf; */
3668
3669         g_return_val_if_fail(fp != NULL, -1);
3670         g_return_val_if_fail(charset != NULL, -1);
3671         g_return_val_if_fail(compose->account != NULL, -1);
3672         g_return_val_if_fail(compose->account->address != NULL, -1);
3673
3674         /* Date */
3675         if (compose->account->add_date) {
3676                 get_rfc822_date(buf, sizeof(buf));
3677                 fprintf(fp, "Date: %s\n", buf);
3678         }
3679
3680         /* From */
3681         if (!IS_IN_CUSTOM_HEADER("From")) {
3682                 if (compose->account->name && *compose->account->name) {
3683                         compose_convert_header
3684                                 (buf, sizeof(buf), compose->account->name,
3685                                  strlen("From: "));
3686                         QUOTE_IF_REQUIRED(name, buf);
3687                         fprintf(fp, "From: %s <%s>\n",
3688                                 name, compose->account->address);
3689                 } else
3690                         fprintf(fp, "From: %s\n", compose->account->address);
3691         }
3692         
3693         /* To */
3694         compose_write_headers_from_headerlist(compose, fp, "To");
3695 #if 0 /* NEW COMPOSE GUI */
3696         if (compose->use_to) {
3697                 str = gtk_entry_get_text(GTK_ENTRY(compose->to_entry));
3698                 PUT_RECIPIENT_HEADER("To", str);
3699         }
3700 #endif
3701
3702         /* Newsgroups */
3703         compose_write_headers_from_headerlist(compose, fp, "Newsgroups");
3704 #if 0 /* NEW COMPOSE GUI */
3705         str = gtk_entry_get_text(GTK_ENTRY(compose->newsgroups_entry));
3706         if (*str != '\0') {
3707                 Xstrdup_a(str, str, return -1);
3708                 g_strstrip(str);
3709                 remove_space(str);
3710                 if (*str != '\0') {
3711                         compose->newsgroup_list =
3712                                 newsgroup_list_append(compose->newsgroup_list,
3713                                                       str);
3714                         compose_convert_header(buf, sizeof(buf), str,
3715                                                strlen("Newsgroups: "));
3716                         fprintf(fp, "Newsgroups: %s\n", buf);
3717                 }
3718         }
3719 #endif
3720         /* Cc */
3721         compose_write_headers_from_headerlist(compose, fp, "Cc");
3722 #if 0 /* NEW COMPOSE GUI */
3723         if (compose->use_cc) {
3724                 str = gtk_entry_get_text(GTK_ENTRY(compose->cc_entry));
3725                 PUT_RECIPIENT_HEADER("Cc", str);
3726         }
3727 #endif
3728         /* Bcc */
3729         compose_write_headers_from_headerlist(compose, fp, "Bcc");
3730 #if 0 /* NEW COMPOSE GUI */
3731         if (compose->use_bcc) {
3732                 str = gtk_entry_get_text(GTK_ENTRY(compose->bcc_entry));
3733                 PUT_RECIPIENT_HEADER("Bcc", str);
3734         }
3735 #endif
3736
3737         /* Subject */
3738         str = gtk_entry_get_text(GTK_ENTRY(compose->subject_entry));
3739         if (*str != '\0' && !IS_IN_CUSTOM_HEADER("Subject")) {
3740                 Xstrdup_a(str, str, return -1);
3741                 g_strstrip(str);
3742                 if (*str != '\0') {
3743                         compose_convert_header(buf, sizeof(buf), str,
3744                                                strlen("Subject: "));
3745                         fprintf(fp, "Subject: %s\n", buf);
3746                 }
3747         }
3748
3749         /* Message-ID */
3750         if (compose->account->gen_msgid) {
3751                 compose_generate_msgid(compose, buf, sizeof(buf));
3752                 fprintf(fp, "Message-Id: <%s>\n", buf);
3753                 compose->msgid = g_strdup(buf);
3754         }
3755
3756         /* In-Reply-To */
3757         if (compose->inreplyto && compose->to_list)
3758                 fprintf(fp, "In-Reply-To: <%s>\n", compose->inreplyto);
3759
3760         /* References */
3761         if (compose->references)
3762                 fprintf(fp, "References: %s\n", compose->references);
3763
3764         /* Followup-To */
3765         compose_write_headers_from_headerlist(compose, fp, "Followup-To");
3766 #if 0 /* NEW COMPOSE GUI */
3767         if (compose->use_followupto && !IS_IN_CUSTOM_HEADER("Followup-To")) {
3768                 str = gtk_entry_get_text(GTK_ENTRY(compose->followup_entry));
3769                 if (*str != '\0') {
3770                         Xstrdup_a(str, str, return -1);
3771                         g_strstrip(str);
3772                         remove_space(str);
3773                         if (*str != '\0') {
3774                                 compose_convert_header(buf, sizeof(buf), str,
3775                                                        strlen("Followup-To: "));
3776                                 fprintf(fp, "Followup-To: %s\n", buf);
3777                         }
3778                 }
3779         }
3780 #endif
3781         /* Reply-To */
3782         compose_write_headers_from_headerlist(compose, fp, "Reply-To");
3783 #if 0 /* NEW COMPOSE GUI */
3784         if (compose->use_replyto && !IS_IN_CUSTOM_HEADER("Reply-To")) {
3785                 str = gtk_entry_get_text(GTK_ENTRY(compose->reply_entry));
3786                 if (*str != '\0') {
3787                         Xstrdup_a(str, str, return -1);
3788                         g_strstrip(str);
3789                         if (*str != '\0') {
3790                                 compose_convert_header(buf, sizeof(buf), str,
3791                                                        strlen("Reply-To: "));
3792                                 fprintf(fp, "Reply-To: %s\n", buf);
3793                         }
3794                 }
3795         }
3796 #endif
3797         /* Organization */
3798         if (compose->account->organization &&
3799             !IS_IN_CUSTOM_HEADER("Organization")) {
3800                 compose_convert_header(buf, sizeof(buf),
3801                                        compose->account->organization,
3802                                        strlen("Organization: "));
3803                 fprintf(fp, "Organization: %s\n", buf);
3804         }
3805
3806         /* Program version and system info */
3807         /* uname(&utsbuf); */
3808         if (g_slist_length(compose->to_list) && !IS_IN_CUSTOM_HEADER("X-Mailer")) {
3809                 fprintf(fp, "X-Mailer: %s (GTK+ %d.%d.%d; %s)\n",
3810                         prog_version,
3811                         gtk_major_version, gtk_minor_version, gtk_micro_version,
3812                         TARGET_ALIAS);
3813                         /* utsbuf.sysname, utsbuf.release, utsbuf.machine); */
3814         }
3815         if (g_slist_length(compose->newsgroup_list) && !IS_IN_CUSTOM_HEADER("X-Newsreader")) {
3816                 fprintf(fp, "X-Newsreader: %s (GTK+ %d.%d.%d; %s)\n",
3817                         prog_version,
3818                         gtk_major_version, gtk_minor_version, gtk_micro_version,
3819                         TARGET_ALIAS);
3820                         /* utsbuf.sysname, utsbuf.release, utsbuf.machine); */
3821         }
3822
3823         /* custom headers */
3824         if (compose->account->add_customhdr) {
3825                 GSList *cur;
3826
3827                 for (cur = compose->account->customhdr_list; cur != NULL;
3828                      cur = cur->next) {
3829                         CustomHeader *chdr = (CustomHeader *)cur->data;
3830
3831                         if (strcasecmp(chdr->name, "Date")         != 0 &&
3832                             strcasecmp(chdr->name, "From")         != 0 &&
3833                             strcasecmp(chdr->name, "To")           != 0 &&
3834                          /* strcasecmp(chdr->name, "Sender")       != 0 && */
3835                             strcasecmp(chdr->name, "Message-Id")   != 0 &&
3836                             strcasecmp(chdr->name, "In-Reply-To")  != 0 &&
3837                             strcasecmp(chdr->name, "References")   != 0 &&
3838                             strcasecmp(chdr->name, "Mime-Version") != 0 &&
3839                             strcasecmp(chdr->name, "Content-Type") != 0 &&
3840                             strcasecmp(chdr->name, "Content-Transfer-Encoding")
3841                             != 0) {
3842                                 compose_convert_header
3843                                         (buf, sizeof(buf),
3844                                          chdr->value ? chdr->value : "",
3845                                          strlen(chdr->name) + 2);
3846                                 fprintf(fp, "%s: %s\n", chdr->name, buf);
3847                         }
3848                 }
3849         }
3850
3851         /* MIME */
3852         fprintf(fp, "Mime-Version: 1.0\n");
3853         if (compose_use_attach(compose)) {
3854                 get_rfc822_date(buf, sizeof(buf));
3855                 subst_char(buf, ' ', '_');
3856                 subst_char(buf, ',', '_');
3857                 compose->boundary = g_strdup_printf("Multipart_%s_%08x",
3858                                                     buf, (guint)compose);
3859                 fprintf(fp,
3860                         "Content-Type: multipart/mixed;\n"
3861                         " boundary=\"%s\"\n", compose->boundary);
3862         } else {
3863                 fprintf(fp, "Content-Type: text/plain; charset=%s\n", charset);
3864                 fprintf(fp, "Content-Transfer-Encoding: %s\n",
3865                         procmime_get_encoding_str(encoding));
3866         }
3867
3868         /* PRIORITY */
3869         switch (compose->priority) {
3870                 case PRIORITY_HIGHEST: fprintf(fp, "Importance: high\n"
3871                                                    "X-Priority: 1 (Highest)\n");
3872                         break;
3873                 case PRIORITY_HIGH: fprintf(fp, "Importance: high\n"
3874                                                 "X-Priority: 2 (High)\n");
3875                         break;
3876                 case PRIORITY_NORMAL: break;
3877                 case PRIORITY_LOW: fprintf(fp, "Importance: low\n"
3878                                                "X-Priority: 4 (Low)\n");
3879                         break;
3880                 case PRIORITY_LOWEST: fprintf(fp, "Importance: low\n"
3881                                                   "X-Priority: 5 (Lowest)\n");
3882                         break;
3883                 default: debug_print(_("compose: priority unknown : %d\n"),
3884                                      compose->priority);
3885         }
3886
3887         /* Request Return Receipt */
3888         if (!IS_IN_CUSTOM_HEADER("Disposition-Notification-To")) {
3889                 if (compose->return_receipt) {
3890                         if (compose->account->name
3891                             && *compose->account->name) {
3892                                 compose_convert_header(buf, sizeof(buf), compose->account->name, strlen("Disposition-Notification-To: "));
3893                                 fprintf(fp, "Disposition-Notification-To: %s <%s>\n", buf, compose->account->address);
3894                         } else
3895                                 fprintf(fp, "Disposition-Notification-To: %s\n", compose->account->address);
3896                 }
3897         }
3898
3899         /* separator between header and body */
3900         fputs("\n", fp);
3901
3902         return 0;
3903 }
3904
3905 #undef IS_IN_CUSTOM_HEADER
3906
3907 static void compose_convert_header(gchar *dest, gint len, gchar *src,
3908                                    gint header_len)
3909 {
3910         g_return_if_fail(src != NULL);
3911         g_return_if_fail(dest != NULL);
3912
3913         if (len < 1) return;
3914
3915         remove_return(src);
3916
3917         if (is_ascii_str(src)) {
3918                 strncpy2(dest, src, len);
3919                 dest[len - 1] = '\0';
3920                 return;
3921         } else
3922                 conv_encode_header(dest, len, src, header_len);
3923 }
3924
3925 static void compose_generate_msgid(Compose *compose, gchar *buf, gint len)
3926 {
3927         struct tm *lt;
3928         time_t t;
3929         gchar *addr;
3930
3931         t = time(NULL);
3932         lt = localtime(&t);
3933
3934         if (compose->account && compose->account->address &&
3935             *compose->account->address) {
3936                 if (strchr(compose->account->address, '@'))
3937                         addr = g_strdup(compose->account->address);
3938                 else
3939                         addr = g_strconcat(compose->account->address, "@",
3940                                            get_domain_name(), NULL);
3941         } else
3942                 addr = g_strconcat(g_get_user_name(), "@", get_domain_name(),
3943                                    NULL);
3944
3945         g_snprintf(buf, len, "%04d%02d%02d%02d%02d%02d.%08x.%s",
3946                    lt->tm_year + 1900, lt->tm_mon + 1,
3947                    lt->tm_mday, lt->tm_hour,
3948                    lt->tm_min, lt->tm_sec,
3949                    (guint)random(), addr);
3950
3951         debug_print(_("generated Message-ID: %s\n"), buf);
3952
3953         g_free(addr);
3954 }
3955
3956 static void compose_create_header_entry(Compose *compose) 
3957 {
3958         gchar *headers[] = {"To:", "Cc:", "Bcc:", "Newsgroups:", "Reply-To:", "Followup-To:", NULL};
3959
3960         GtkWidget *combo;
3961         GtkWidget *entry;
3962         GList *combo_list = NULL;
3963         gchar **string, *header;
3964         ComposeHeaderEntry *headerentry;
3965
3966         headerentry = g_new0(ComposeHeaderEntry, 1);
3967
3968         /* Combo box */
3969         combo = gtk_combo_new();
3970         string = headers; 
3971         while(*string != NULL) {
3972             combo_list = g_list_append(combo_list, (prefs_common.trans_hdr ? gettext(*string) : *string));
3973             string++;
3974         }
3975         gtk_combo_set_popdown_strings(GTK_COMBO(combo), combo_list);
3976         g_list_free(combo_list);
3977         gtk_editable_set_editable(GTK_EDITABLE(GTK_COMBO(combo)->entry), FALSE);
3978         gtk_widget_show(combo);
3979         gtk_table_attach(GTK_TABLE(compose->header_table), combo, 0, 1, compose->header_nextrow, compose->header_nextrow+1, GTK_SHRINK, GTK_FILL, 0, 0);
3980         if(compose->header_last) {      
3981                 header = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry));
3982         } else {
3983                 switch(compose->account->protocol) {
3984                         case A_NNTP:
3985                                 header = prefs_common.trans_hdr ? _("Newsgroups:") : "Newsgroups:";
3986                                 break;
3987                         default:
3988                                 header = prefs_common.trans_hdr ? _("To:") : "To:";
3989                                 break;
3990                 }                                                                   
3991         }
3992         gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(combo)->entry), header);
3993
3994         /* Entry field */
3995         entry = gtk_entry_new(); 
3996         gtk_widget_show(entry);
3997         gtk_table_attach(GTK_TABLE(compose->header_table), entry, 1, 2, compose->header_nextrow, compose->header_nextrow+1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
3998
3999         gtk_signal_connect(GTK_OBJECT(entry), "key-press-event", GTK_SIGNAL_FUNC(compose_headerentry_key_press_event_cb), headerentry);
4000         gtk_signal_connect(GTK_OBJECT(entry), "changed", GTK_SIGNAL_FUNC(compose_headerentry_changed_cb), headerentry);
4001         gtk_signal_connect(GTK_OBJECT(entry), "activate", GTK_SIGNAL_FUNC(text_activated), compose);
4002
4003         address_completion_register_entry(GTK_ENTRY(entry));
4004
4005         headerentry->compose = compose;
4006         headerentry->combo = combo;
4007         headerentry->entry = entry;
4008         headerentry->headernum = compose->header_nextrow;
4009
4010         compose->header_nextrow++;
4011         compose->header_last = headerentry;
4012 }
4013
4014 static void compose_add_header_entry(Compose *compose, gchar *header, gchar *text) 
4015 {
4016         ComposeHeaderEntry *last_header;
4017         
4018         last_header = compose->header_last;
4019         
4020         gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(last_header->combo)->entry), header);
4021         gtk_entry_set_text(GTK_ENTRY(last_header->entry), text);
4022 }
4023
4024 static GtkWidget *compose_create_header(Compose *compose) 
4025 {
4026         GtkWidget *label;
4027         GtkWidget *hbox;
4028         GtkWidget *from_optmenu_hbox;
4029 #if 0 /* NEW COMPOSE GUI */
4030         GtkWidget *to_entry;
4031         GtkWidget *to_hbox;
4032         GtkWidget *newsgroups_entry;
4033         GtkWidget *newsgroups_hbox;
4034 #endif
4035         GtkWidget *header_scrolledwin;
4036         GtkWidget *header_table;
4037 #if 0 /* NEW COMPOSE GUI */
4038         GtkWidget *cc_entry;
4039         GtkWidget *cc_hbox;
4040         GtkWidget *bcc_entry;
4041         GtkWidget *bcc_hbox;
4042         GtkWidget *reply_entry;
4043         GtkWidget *reply_hbox;
4044         GtkWidget *followup_entry;
4045         GtkWidget *followup_hbox;
4046 #endif
4047
4048         gint count = 0;
4049
4050         /* header labels and entries */
4051         header_scrolledwin = gtk_scrolled_window_new(NULL, NULL);
4052         gtk_widget_show(header_scrolledwin);
4053         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(header_scrolledwin), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
4054
4055         header_table = gtk_table_new(2, 2, FALSE);
4056         gtk_widget_show(header_table);
4057         gtk_container_set_border_width(GTK_CONTAINER(header_table), 2);
4058         gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(header_scrolledwin), header_table);
4059         gtk_viewport_set_shadow_type(GTK_VIEWPORT(GTK_BIN(header_scrolledwin)->child), GTK_SHADOW_ETCHED_IN);
4060         count = 0;
4061
4062         /* option menu for selecting accounts */
4063         hbox = gtk_hbox_new(FALSE, 0);
4064         label = gtk_label_new(prefs_common.trans_hdr ? _("From:") : "From:");
4065         gtk_box_pack_end(GTK_BOX(hbox), label, FALSE, FALSE, 0);
4066         gtk_table_attach(GTK_TABLE(header_table), hbox, 0, 1, count, count + 1,
4067                          GTK_FILL, 0, 2, 0);
4068         from_optmenu_hbox = compose_account_option_menu_create(compose);
4069         gtk_table_attach(GTK_TABLE(header_table), from_optmenu_hbox,
4070                                   1, 2, count, count + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
4071 #if 0 /* NEW COMPOSE GUI */
4072         gtk_table_set_row_spacing(GTK_TABLE(table), 0, 4);
4073 #endif
4074         count++;
4075
4076         compose->header_table = header_table;
4077         compose->header_list = NULL;
4078         compose->header_nextrow = count;
4079
4080         compose_create_header_entry(compose);
4081
4082 #if 0 /* NEW COMPOSE GUI */
4083         compose_add_entry_field(table, &to_hbox, &to_entry, &count,
4084                                 "To:", TRUE); 
4085         gtk_table_set_row_spacing(GTK_TABLE(table), 0, 4);
4086         compose_add_entry_field(table, &newsgroups_hbox, &newsgroups_entry,
4087                                 &count, "Newsgroups:", FALSE);
4088         gtk_table_set_row_spacing(GTK_TABLE(table), 1, 4);
4089
4090         gtk_table_set_row_spacing(GTK_TABLE(table), 2, 4);
4091
4092         compose_add_entry_field(table, &cc_hbox, &cc_entry, &count,
4093                                 "Cc:", TRUE);
4094         gtk_table_set_row_spacing(GTK_TABLE(table), 3, 4);
4095         compose_add_entry_field(table, &bcc_hbox, &bcc_entry, &count,
4096                                 "Bcc:", TRUE);
4097         gtk_table_set_row_spacing(GTK_TABLE(table), 4, 4);
4098         compose_add_entry_field(table, &reply_hbox, &reply_entry, &count,
4099                                 "Reply-To:", TRUE);
4100         gtk_table_set_row_spacing(GTK_TABLE(table), 5, 4);
4101         compose_add_entry_field(table, &followup_hbox, &followup_entry, &count,
4102                                 "Followup-To:", FALSE);
4103         gtk_table_set_row_spacing(GTK_TABLE(table), 6, 4);
4104
4105         gtk_table_set_col_spacings(GTK_TABLE(table), 4);
4106
4107         gtk_signal_connect(GTK_OBJECT(to_entry), "activate",
4108                            GTK_SIGNAL_FUNC(to_activated), compose);
4109         gtk_signal_connect(GTK_OBJECT(newsgroups_entry), "activate",
4110                            GTK_SIGNAL_FUNC(newsgroups_activated), compose);
4111         gtk_signal_connect(GTK_OBJECT(subject_entry), "activate",
4112                            GTK_SIGNAL_FUNC(subject_activated), compose);
4113         gtk_signal_connect(GTK_OBJECT(cc_entry), "activate",
4114                            GTK_SIGNAL_FUNC(cc_activated), compose);
4115         gtk_signal_connect(GTK_OBJECT(bcc_entry), "activate",
4116                            GTK_SIGNAL_FUNC(bcc_activated), compose);
4117         gtk_signal_connect(GTK_OBJECT(reply_entry), "activate",
4118                            GTK_SIGNAL_FUNC(replyto_activated), compose);
4119         gtk_signal_connect(GTK_OBJECT(followup_entry), "activate",
4120                            GTK_SIGNAL_FUNC(followupto_activated), compose);
4121
4122         gtk_signal_connect(GTK_OBJECT(subject_entry), "grab_focus",
4123                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4124         gtk_signal_connect(GTK_OBJECT(to_entry), "grab_focus",
4125                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4126         gtk_signal_connect(GTK_OBJECT(newsgroups_entry), "grab_focus",
4127                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4128         gtk_signal_connect(GTK_OBJECT(cc_entry), "grab_focus",
4129                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4130         gtk_signal_connect(GTK_OBJECT(bcc_entry), "grab_focus",
4131                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4132         gtk_signal_connect(GTK_OBJECT(reply_entry), "grab_focus",
4133                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4134         gtk_signal_connect(GTK_OBJECT(followup_entry), "grab_focus",
4135                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4136 #endif
4137
4138         compose->table            = NULL;
4139 #if 0 /* NEW COMPOSE GUI */
4140         compose->table            = table;
4141         compose->to_hbox          = to_hbox;
4142         compose->to_entry         = to_entry;
4143         compose->newsgroups_hbox  = newsgroups_hbox;
4144         compose->newsgroups_entry = newsgroups_entry;
4145 #endif
4146 #if 0 /* NEW COMPOSE GUI */
4147         compose->cc_hbox          = cc_hbox;
4148         compose->cc_entry         = cc_entry;
4149         compose->bcc_hbox         = bcc_hbox;
4150         compose->bcc_entry        = bcc_entry;
4151         compose->reply_hbox       = reply_hbox;
4152         compose->reply_entry      = reply_entry;
4153         compose->followup_hbox    = followup_hbox;
4154         compose->followup_entry   = followup_entry;
4155 #endif
4156
4157         return header_scrolledwin ;
4158 }
4159
4160 GtkWidget *compose_create_attach(Compose *compose)
4161 {
4162         gchar *titles[N_ATTACH_COLS];
4163         gint i;
4164
4165         GtkWidget *attach_scrwin;
4166         GtkWidget *attach_clist;
4167
4168         titles[COL_MIMETYPE] = _("MIME type");
4169         titles[COL_SIZE]     = _("Size");
4170         titles[COL_NAME]     = _("Name");
4171
4172         /* attachment list */
4173         attach_scrwin = gtk_scrolled_window_new(NULL, NULL);
4174         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(attach_scrwin),
4175                                        GTK_POLICY_AUTOMATIC,
4176                                        GTK_POLICY_ALWAYS);
4177         gtk_widget_set_usize(attach_scrwin, -1, 80);
4178
4179         attach_clist = gtk_clist_new_with_titles(N_ATTACH_COLS, titles);
4180         gtk_clist_set_column_justification(GTK_CLIST(attach_clist), COL_SIZE,
4181                                            GTK_JUSTIFY_RIGHT);
4182         gtk_clist_set_column_width(GTK_CLIST(attach_clist), COL_MIMETYPE, 240);
4183         gtk_clist_set_column_width(GTK_CLIST(attach_clist), COL_SIZE, 64);
4184         gtk_clist_set_selection_mode(GTK_CLIST(attach_clist),
4185                                      GTK_SELECTION_EXTENDED);
4186         for (i = 0; i < N_ATTACH_COLS; i++)
4187                 GTK_WIDGET_UNSET_FLAGS
4188                         (GTK_CLIST(attach_clist)->column[i].button,
4189                          GTK_CAN_FOCUS);
4190         gtk_container_add(GTK_CONTAINER(attach_scrwin), attach_clist);
4191
4192         gtk_signal_connect(GTK_OBJECT(attach_clist), "select_row",
4193                            GTK_SIGNAL_FUNC(attach_selected), compose);
4194         gtk_signal_connect(GTK_OBJECT(attach_clist), "button_press_event",
4195                            GTK_SIGNAL_FUNC(attach_button_pressed), compose);
4196         gtk_signal_connect(GTK_OBJECT(attach_clist), "key_press_event",
4197                            GTK_SIGNAL_FUNC(attach_key_pressed), compose);
4198
4199         /* drag and drop */
4200         gtk_drag_dest_set(attach_clist,
4201                           GTK_DEST_DEFAULT_ALL, compose_mime_types, 1,
4202                           GDK_ACTION_COPY);
4203         gtk_signal_connect(GTK_OBJECT(attach_clist), "drag_data_received",
4204                            GTK_SIGNAL_FUNC(compose_attach_drag_received_cb),
4205                            compose);
4206
4207         compose->attach_scrwin = attach_scrwin;
4208         compose->attach_clist  = attach_clist;
4209
4210         return attach_scrwin;
4211 }
4212
4213 static void compose_savemsg_checkbtn_cb(GtkWidget *widget, Compose *compose);
4214 static void compose_savemsg_select_cb(GtkWidget *widget, Compose *compose);
4215
4216 static GtkWidget *compose_create_others(Compose *compose)
4217 {
4218         GtkWidget *table;
4219         GtkWidget *savemsg_checkbtn;
4220         GtkWidget *savemsg_entry;
4221         GtkWidget *savemsg_select;
4222         
4223         guint rowcount = 0;
4224         gchar *folderidentifier;
4225
4226         /* Table for settings */
4227         table = gtk_table_new(3, 1, FALSE);
4228         gtk_widget_show(table);
4229         gtk_table_set_row_spacings(GTK_TABLE(table), VSPACING_NARROW);
4230         rowcount = 0;
4231
4232         /* Save Message to folder */
4233         savemsg_checkbtn = gtk_check_button_new_with_label(_("Save Message to "));
4234         gtk_widget_show(savemsg_checkbtn);
4235         gtk_table_attach(GTK_TABLE(table), savemsg_checkbtn, 0, 1, rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
4236         if(account_get_special_folder(compose->account, F_OUTBOX)) {
4237                 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(savemsg_checkbtn), prefs_common.savemsg);
4238         }
4239         gtk_signal_connect(GTK_OBJECT(savemsg_checkbtn), "toggled",
4240                             GTK_SIGNAL_FUNC(compose_savemsg_checkbtn_cb), compose);
4241
4242         savemsg_entry = gtk_entry_new();
4243         gtk_widget_show(savemsg_entry);
4244         gtk_table_attach_defaults(GTK_TABLE(table), savemsg_entry, 1, 2, rowcount, rowcount + 1);
4245         gtk_editable_set_editable(GTK_EDITABLE(savemsg_entry), prefs_common.savemsg);
4246         if(account_get_special_folder(compose->account, F_OUTBOX)) {
4247                 folderidentifier = folder_item_get_identifier(account_get_special_folder
4248                                   (compose->account, F_OUTBOX));
4249                 gtk_entry_set_text(GTK_ENTRY(savemsg_entry), folderidentifier);
4250                 g_free(folderidentifier);
4251         }
4252
4253         savemsg_select = gtk_button_new_with_label (_("Select ..."));
4254         gtk_widget_show (savemsg_select);
4255         gtk_table_attach(GTK_TABLE(table), savemsg_select, 2, 3, rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
4256         gtk_signal_connect (GTK_OBJECT (savemsg_select), "clicked",
4257                             GTK_SIGNAL_FUNC (compose_savemsg_select_cb),
4258                             compose);
4259
4260         rowcount++;
4261
4262         compose->savemsg_checkbtn = savemsg_checkbtn;
4263         compose->savemsg_entry = savemsg_entry;
4264
4265         return table;   
4266 }
4267
4268 static void compose_savemsg_checkbtn_cb(GtkWidget *widget, Compose *compose) 
4269 {
4270         gtk_editable_set_editable(GTK_EDITABLE(compose->savemsg_entry),
4271                 gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(compose->savemsg_checkbtn)));
4272 }
4273
4274 static void compose_savemsg_select_cb(GtkWidget *widget, Compose *compose)
4275 {
4276         FolderItem *dest;
4277         gchar * path;
4278
4279         dest = foldersel_folder_sel(NULL, FOLDER_SEL_COPY, NULL);
4280         if (!dest) return;
4281
4282         path = folder_item_get_identifier(dest);
4283
4284         gtk_entry_set_text(GTK_ENTRY(compose->savemsg_entry), path);
4285         g_free(path);
4286 }
4287
4288 static Compose *compose_create(PrefsAccount *account, ComposeMode mode)
4289 {
4290         Compose   *compose;
4291         GtkWidget *window;
4292         GtkWidget *vbox;
4293         GtkWidget *menubar;
4294         GtkWidget *handlebox;
4295
4296         GtkWidget *notebook;
4297
4298         GtkWidget *vbox2;
4299
4300         GtkWidget *label;
4301         GtkWidget *subject_hbox;
4302         GtkWidget *subject_frame;
4303         GtkWidget *subject_entry;
4304         GtkWidget *subject;
4305         GtkWidget *paned;
4306
4307         GtkWidget *edit_vbox;
4308         GtkWidget *ruler_hbox;
4309         GtkWidget *ruler;
4310         GtkWidget *scrolledwin;
4311         GtkWidget *text;
4312
4313         UndoMain *undostruct;
4314
4315         gchar *titles[N_ATTACH_COLS];
4316         guint n_menu_entries;
4317         GtkStyle  *style, *new_style;
4318         GdkColormap *cmap;
4319         GdkColor color[1];
4320         gboolean success[1];
4321         GdkFont   *font;
4322         GtkWidget *popupmenu;
4323         GtkWidget *menuitem;
4324         GtkItemFactory *popupfactory;
4325         GtkItemFactory *ifactory;
4326         GtkWidget *tmpl_menu;
4327         gint n_entries;
4328
4329 #if USE_PSPELL
4330         GtkPspell * gtkpspell = NULL;
4331 #endif
4332
4333         static GdkGeometry geometry;
4334
4335         g_return_val_if_fail(account != NULL, NULL);
4336
4337         debug_print(_("Creating compose window...\n"));
4338         compose = g_new0(Compose, 1);
4339
4340         titles[COL_MIMETYPE] = _("MIME type");
4341         titles[COL_SIZE]     = _("Size");
4342         titles[COL_NAME]     = _("Name");
4343
4344         compose->account = account;
4345         compose->orig_account = account;
4346
4347         window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
4348         gtk_window_set_policy(GTK_WINDOW(window), TRUE, TRUE, FALSE);
4349         gtk_widget_set_usize(window, -1, prefs_common.compose_height);
4350         gtk_window_set_wmclass(GTK_WINDOW(window), "compose window", "Sylpheed");
4351
4352         if (!geometry.max_width) {
4353                 geometry.max_width = gdk_screen_width();
4354                 geometry.max_height = gdk_screen_height();
4355         }
4356         gtk_window_set_geometry_hints(GTK_WINDOW(window), NULL,
4357                                       &geometry, GDK_HINT_MAX_SIZE);
4358
4359         gtk_signal_connect(GTK_OBJECT(window), "delete_event",
4360                            GTK_SIGNAL_FUNC(compose_delete_cb), compose);
4361         gtk_signal_connect(GTK_OBJECT(window), "destroy",
4362                            GTK_SIGNAL_FUNC(compose_destroy_cb), compose);
4363         MANAGE_WINDOW_SIGNALS_CONNECT(window);
4364         gtk_widget_realize(window);
4365
4366         gtkut_widget_set_composer_icon(window);
4367
4368         vbox = gtk_vbox_new(FALSE, 0);
4369         gtk_container_add(GTK_CONTAINER(window), vbox);
4370
4371         n_menu_entries = sizeof(compose_entries) / sizeof(compose_entries[0]);
4372         menubar = menubar_create(window, compose_entries,
4373                                  n_menu_entries, "<Compose>", compose);
4374         gtk_box_pack_start(GTK_BOX(vbox), menubar, FALSE, TRUE, 0);
4375
4376         handlebox = gtk_handle_box_new();
4377         gtk_box_pack_start(GTK_BOX(vbox), handlebox, FALSE, FALSE, 0);
4378
4379         compose_toolbar_create(compose, handlebox);
4380
4381         vbox2 = gtk_vbox_new(FALSE, 2);
4382         gtk_box_pack_start(GTK_BOX(vbox), vbox2, TRUE, TRUE, 0);
4383         gtk_container_set_border_width(GTK_CONTAINER(vbox2), BORDER_WIDTH);
4384         
4385         /* Notebook */
4386         notebook = gtk_notebook_new();
4387         gtk_widget_set_usize(notebook, -1, 130);
4388         gtk_widget_show(notebook);
4389
4390         /* header labels and entries */
4391         gtk_notebook_append_page(GTK_NOTEBOOK(notebook), compose_create_header(compose), gtk_label_new(_("Header")));
4392         /* attachment list */
4393         gtk_notebook_append_page(GTK_NOTEBOOK(notebook), compose_create_attach(compose), gtk_label_new(_("Attachments")));
4394         /* Others Tab */
4395         gtk_notebook_append_page(GTK_NOTEBOOK(notebook), compose_create_others(compose), gtk_label_new(_("Others")));
4396
4397         /* Subject */
4398         subject_hbox = gtk_hbox_new(FALSE, 0);
4399         gtk_widget_show(subject_hbox);
4400
4401         subject_frame = gtk_frame_new(NULL);
4402         gtk_frame_set_shadow_type(GTK_FRAME(subject_frame), GTK_SHADOW_OUT);
4403         gtk_box_pack_start(GTK_BOX(subject_hbox), subject_frame, TRUE, TRUE, BORDER_WIDTH+1);
4404         gtk_widget_show(subject_frame);
4405
4406         subject = gtk_hbox_new(FALSE, 0);
4407         gtk_container_set_border_width(GTK_CONTAINER(subject), BORDER_WIDTH);
4408         gtk_widget_show(subject);
4409
4410         label = gtk_label_new(_("Subject:"));
4411         gtk_box_pack_start(GTK_BOX(subject), label, FALSE, FALSE, 4);
4412         gtk_widget_show(label);
4413
4414         subject_entry = gtk_entry_new();
4415         gtk_box_pack_start(GTK_BOX(subject), subject_entry, TRUE, TRUE, 2);
4416         gtk_signal_connect(GTK_OBJECT(subject_entry), "activate", GTK_SIGNAL_FUNC(text_activated), compose);
4417         gtk_widget_show(subject_entry);
4418         compose->subject_entry = subject_entry;
4419         gtk_container_add(GTK_CONTAINER(subject_frame), subject);
4420         
4421         edit_vbox = gtk_vbox_new(FALSE, 0);
4422 #if 0 /* NEW COMPOSE GUI */
4423         gtk_box_pack_start(GTK_BOX(vbox2), edit_vbox, TRUE, TRUE, 0);
4424 #endif
4425
4426         gtk_box_pack_start(GTK_BOX(edit_vbox), subject_hbox, FALSE, FALSE, 0);
4427
4428         /* ruler */
4429         ruler_hbox = gtk_hbox_new(FALSE, 0);
4430         gtk_box_pack_start(GTK_BOX(edit_vbox), ruler_hbox, FALSE, FALSE, 0);
4431
4432         ruler = gtk_shruler_new();
4433         gtk_ruler_set_range(GTK_RULER(ruler), 0.0, 100.0, 1.0, 100.0);
4434         gtk_box_pack_start(GTK_BOX(ruler_hbox), ruler, TRUE, TRUE,
4435                            BORDER_WIDTH + 1);
4436         gtk_widget_set_usize(ruler_hbox, 1, -1);
4437
4438         /* text widget */
4439         scrolledwin = gtk_scrolled_window_new(NULL, NULL);
4440         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwin),
4441                                        GTK_POLICY_NEVER, GTK_POLICY_ALWAYS);
4442         gtk_box_pack_start(GTK_BOX(edit_vbox), scrolledwin, TRUE, TRUE, 0);
4443         gtk_widget_set_usize(scrolledwin, prefs_common.compose_width, -1);
4444
4445         text = gtk_stext_new(gtk_scrolled_window_get_hadjustment
4446                             (GTK_SCROLLED_WINDOW(scrolledwin)),
4447                             gtk_scrolled_window_get_vadjustment
4448                             (GTK_SCROLLED_WINDOW(scrolledwin)));
4449         GTK_STEXT(text)->default_tab_width = 8;
4450         gtk_stext_set_editable(GTK_STEXT(text), TRUE);
4451
4452         if (prefs_common.block_cursor) {
4453                 GTK_STEXT(text)->cursor_type = GTK_STEXT_CURSOR_BLOCK;
4454         }
4455         
4456         if (prefs_common.smart_wrapping) {      
4457                 gtk_stext_set_word_wrap(GTK_STEXT(text), TRUE);
4458                 gtk_stext_set_wrap_rmargin(GTK_STEXT(text), prefs_common.linewrap_len);
4459         }               
4460
4461         gtk_container_add(GTK_CONTAINER(scrolledwin), text);
4462
4463         gtk_signal_connect(GTK_OBJECT(text), "changed",
4464                            GTK_SIGNAL_FUNC(compose_changed_cb), compose);
4465         gtk_signal_connect(GTK_OBJECT(text), "grab_focus",
4466                            GTK_SIGNAL_FUNC(compose_grab_focus_cb), compose);
4467         gtk_signal_connect(GTK_OBJECT(text), "activate",
4468                            GTK_SIGNAL_FUNC(text_activated), compose);
4469         gtk_signal_connect(GTK_OBJECT(text), "insert_text",
4470                            GTK_SIGNAL_FUNC(text_inserted), compose);
4471         gtk_signal_connect_after(GTK_OBJECT(text), "button_press_event",
4472                                  GTK_SIGNAL_FUNC(compose_button_press_cb),
4473                                  edit_vbox);
4474 #if 0
4475         gtk_signal_connect_after(GTK_OBJECT(text), "key_press_event",
4476                                  GTK_SIGNAL_FUNC(compose_key_press_cb),
4477                                  compose);
4478 #endif
4479         gtk_signal_connect_after(GTK_OBJECT(text), "size_allocate",
4480                                  GTK_SIGNAL_FUNC(compose_edit_size_alloc),
4481                                  ruler);
4482
4483         /* drag and drop */
4484         gtk_drag_dest_set(text, GTK_DEST_DEFAULT_ALL, compose_mime_types, 1,
4485                           GDK_ACTION_COPY);
4486         gtk_signal_connect(GTK_OBJECT(text), "drag_data_received",
4487                            GTK_SIGNAL_FUNC(compose_insert_drag_received_cb),
4488                            compose);
4489         gtk_widget_show_all(vbox);
4490
4491         /* pane between attach clist and text */
4492         paned = gtk_vpaned_new();
4493         gtk_paned_set_gutter_size(GTK_PANED(paned), 12);
4494         gtk_paned_set_handle_size(GTK_PANED(paned), 12);
4495         gtk_container_add(GTK_CONTAINER(vbox2), paned);
4496         gtk_paned_add1(GTK_PANED(paned), notebook);
4497         gtk_paned_add2(GTK_PANED(paned), edit_vbox);
4498         gtk_widget_show_all(paned);
4499
4500         style = gtk_widget_get_style(text);
4501
4502         /* workaround for the slow down of GtkSText when using Pixmap theme */
4503         if (style->engine) {
4504                 GtkThemeEngine *engine;
4505
4506                 engine = style->engine;
4507                 style->engine = NULL;
4508                 new_style = gtk_style_copy(style);
4509                 style->engine = engine;
4510         } else
4511                 new_style = gtk_style_copy(style);
4512
4513         if (prefs_common.textfont) {
4514                 if (MB_CUR_MAX == 1) {
4515                         gchar *fontstr, *p;
4516
4517                         Xstrdup_a(fontstr, prefs_common.textfont, );
4518                         if (fontstr && (p = strchr(fontstr, ',')) != NULL)
4519                                 *p = '\0';
4520                         font = gdk_font_load(fontstr);
4521                 } else
4522                         font = gdk_fontset_load(prefs_common.textfont);
4523                 if (font) {
4524                         gdk_font_unref(new_style->font);
4525                         new_style->font = font;
4526                 }
4527         }
4528
4529         gtk_widget_set_style(text, new_style);
4530
4531         color[0] = quote_color;
4532         cmap = gdk_window_get_colormap(window->window);
4533         gdk_colormap_alloc_colors(cmap, color, 1, FALSE, TRUE, success);
4534         if (success[0] == FALSE) {
4535                 g_warning("Compose: color allocation failed.\n");
4536                 style = gtk_widget_get_style(text);
4537                 quote_color = style->black;
4538         }
4539
4540         n_entries = sizeof(compose_popup_entries) /
4541                 sizeof(compose_popup_entries[0]);
4542         popupmenu = menu_create_items(compose_popup_entries, n_entries,
4543                                       "<Compose>", &popupfactory,
4544                                       compose);
4545
4546         ifactory = gtk_item_factory_from_widget(menubar);
4547         menu_set_sensitive(ifactory, "/Edit/Undo", FALSE);
4548         menu_set_sensitive(ifactory, "/Edit/Redo", FALSE);
4549
4550         tmpl_menu = gtk_item_factory_get_item(ifactory, "/Tools/Template");
4551 #if 0 /* NEW COMPOSE GUI */
4552         gtk_widget_hide(bcc_hbox);
4553         gtk_widget_hide(bcc_entry);
4554         gtk_widget_hide(reply_hbox);
4555         gtk_widget_hide(reply_entry);
4556         gtk_widget_hide(followup_hbox);
4557         gtk_widget_hide(followup_entry);
4558         gtk_widget_hide(ruler_hbox);
4559         gtk_table_set_row_spacing(GTK_TABLE(table), 4, 0);
4560         gtk_table_set_row_spacing(GTK_TABLE(table), 5, 0);
4561         gtk_table_set_row_spacing(GTK_TABLE(table), 6, 0);
4562
4563         if (account->protocol == A_NNTP) {
4564                 gtk_widget_hide(to_hbox);
4565                 gtk_widget_hide(to_entry);
4566                 gtk_widget_hide(cc_hbox);
4567                 gtk_widget_hide(cc_entry);
4568                 gtk_table_set_row_spacing(GTK_TABLE(table), 1, 0);
4569                 gtk_table_set_row_spacing(GTK_TABLE(table), 3, 0);
4570         } else {
4571                 gtk_widget_hide(newsgroups_hbox);
4572                 gtk_widget_hide(newsgroups_entry);
4573                 gtk_table_set_row_spacing(GTK_TABLE(table), 2, 0);
4574                 menu_set_sensitive(ifactory, "/View/Followup to", FALSE);
4575         }
4576 #endif
4577
4578         update_compose_actions_menu(ifactory, "/Tools/Actions", compose);
4579
4580
4581         undostruct = undo_init(text);
4582         undo_set_change_state_func(undostruct, &compose_undo_state_changed,
4583                                    menubar);
4584
4585         gtk_widget_show(window);
4586
4587         address_completion_start(window);
4588
4589         compose->window        = window;
4590         compose->vbox          = vbox;
4591         compose->menubar       = menubar;
4592         compose->handlebox     = handlebox;
4593
4594         compose->vbox2         = vbox2;
4595
4596         compose->paned = paned;
4597
4598         compose->edit_vbox     = edit_vbox;
4599         compose->ruler_hbox    = ruler_hbox;
4600         compose->ruler         = ruler;
4601         compose->scrolledwin   = scrolledwin;
4602         compose->text          = text;
4603
4604         compose->focused_editable = NULL;
4605
4606         compose->popupmenu    = popupmenu;
4607         compose->popupfactory = popupfactory;
4608
4609         compose->tmpl_menu = tmpl_menu;
4610
4611         compose->mode = mode;
4612
4613         compose->targetinfo = NULL;
4614         compose->replyinfo  = NULL;
4615
4616         compose->replyto     = NULL;
4617         compose->mailinglist = NULL;
4618         compose->cc          = NULL;
4619         compose->bcc         = NULL;
4620         compose->followup_to = NULL;
4621         compose->inreplyto   = NULL;
4622         compose->references  = NULL;
4623         compose->msgid       = NULL;
4624         compose->boundary    = NULL;
4625
4626 #if USE_GPGME
4627         compose->use_signing    = FALSE;
4628         compose->use_encryption = FALSE;
4629 #endif /* USE_GPGME */
4630
4631         compose->modified = FALSE;
4632
4633         compose->return_receipt = FALSE;
4634         compose->paste_as_quotation = FALSE;
4635
4636         compose->to_list        = NULL;
4637         compose->newsgroup_list = NULL;
4638
4639         compose->exteditor_file    = NULL;
4640         compose->exteditor_pid     = -1;
4641         compose->exteditor_readdes = -1;
4642         compose->exteditor_tag     = -1;
4643
4644         compose->redirect_filename = NULL;
4645         compose->undostruct = undostruct;
4646 #if USE_PSPELL
4647         
4648         menu_set_sensitive(ifactory, "/Spelling", FALSE);
4649         if (prefs_common.enable_pspell) {
4650                 gtkpspell = gtkpspell_new((const gchar*)prefs_common.dictionary,
4651                                           conv_get_current_charset_str(),
4652                                           prefs_common.misspelled_col,
4653                                           prefs_common.check_while_typing,
4654                                           prefs_common.use_alternate,
4655                                           GTK_STEXT(text));
4656                 if (!gtkpspell) {
4657                         alertpanel_error(_("Spell checker could not be started.\n%s"), gtkpspellcheckers->error_message);
4658                         gtkpspell_checkers_reset_error();
4659                 } else {
4660
4661                         GtkWidget *menuitem;
4662
4663                         if (!gtkpspell_set_sug_mode(gtkpspell, prefs_common.pspell_sugmode)) {
4664                                 debug_print(_("Pspell: could not set suggestion mode %s"),
4665                                     gtkpspellcheckers->error_message);
4666                                 gtkpspell_checkers_reset_error();
4667                         }
4668
4669                         menuitem = gtk_item_factory_get_item(ifactory, "/Spelling/Spelling Configuration");
4670                         gtkpspell_populate_submenu(gtkpspell, menuitem);
4671                         menu_set_sensitive(ifactory, "/Spelling", TRUE);
4672                         }
4673         }
4674 #endif
4675
4676         compose_set_title(compose);
4677
4678 #if 0 /* NEW COMPOSE GUI */
4679         compose->use_bcc        = FALSE;
4680         compose->use_replyto    = FALSE;
4681         compose->use_followupto = FALSE;
4682 #endif
4683
4684 #if USE_PSPELL
4685         compose->gtkpspell      = gtkpspell;
4686 #endif
4687
4688 #if 0 /* NEW COMPOSE GUI */
4689         if (account->protocol != A_NNTP) {
4690                 menuitem = gtk_item_factory_get_item(ifactory, "/View/To");
4691                 gtk_check_menu_item_set_active
4692                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
4693                 gtk_widget_set_sensitive(menuitem, FALSE);
4694                 menuitem = gtk_item_factory_get_item(ifactory, "/View/Cc");
4695                 gtk_check_menu_item_set_active
4696                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
4697                 gtk_widget_set_sensitive(menuitem, FALSE);
4698         }
4699 #endif
4700         if (account->set_autocc && account->auto_cc && mode != COMPOSE_REEDIT) {
4701                 compose_entry_append(compose, account->auto_cc, COMPOSE_CC);
4702 #if 0 /* NEW COMPOSE GUI */
4703                 compose->use_cc = TRUE;
4704                 gtk_entry_set_text(GTK_ENTRY(cc_entry), account->auto_cc);
4705                 menuitem = gtk_item_factory_get_item(ifactory, "/View/Cc");
4706                 gtk_check_menu_item_set_active
4707                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
4708 #endif
4709         }
4710         if (account->set_autobcc) {
4711                 compose_entry_append(compose, account->auto_bcc, COMPOSE_BCC);
4712 #if 0 /* NEW COMPOSE GUI */
4713                 menuitem = gtk_item_factory_get_item(ifactory, "/View/Bcc");
4714                 gtk_check_menu_item_set_active
4715                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
4716                 if (account->auto_bcc && mode != COMPOSE_REEDIT)
4717                         gtk_entry_set_text(GTK_ENTRY(bcc_entry),
4718                                            account->auto_bcc);
4719 #endif
4720         }
4721         if (account->set_autoreplyto && account->auto_replyto && mode != COMPOSE_REEDIT) {
4722                 compose_entry_append(compose, account->auto_replyto, COMPOSE_REPLYTO);
4723 #if 0 /* NEW COMPOSE GUI */
4724                 compose->use_replyto = TRUE;
4725                 menuitem = gtk_item_factory_get_item(ifactory,
4726                                                      "/View/Reply to");
4727                 gtk_check_menu_item_set_active
4728                         (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
4729                 gtk_entry_set_text(GTK_ENTRY(reply_entry),
4730                                    account->auto_replyto);
4731 #endif
4732         }
4733
4734         if (account->protocol != A_NNTP) {
4735                 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry), prefs_common.trans_hdr ? _("To:") : "To:");
4736         } else {
4737                 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(compose->header_last->combo)->entry), prefs_common.trans_hdr ? _("Newsgroups:") : "Newsgroups:");
4738         }
4739
4740 #if 0 /* NEW COMPOSE GUI */
4741         menuitem = gtk_item_factory_get_item(ifactory, "/View/Ruler");
4742         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
4743                                        prefs_common.show_ruler);
4744 #endif                                 
4745
4746 #if USE_GPGME
4747         menuitem = gtk_item_factory_get_item(ifactory, "/Message/Sign");
4748         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
4749                                        account->default_sign);
4750         menuitem = gtk_item_factory_get_item(ifactory, "/Message/Encrypt");
4751         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
4752                                        account->default_encrypt);
4753 #endif /* USE_GPGME */
4754
4755         addressbook_set_target_compose(compose);
4756         compose_set_template_menu(compose);
4757
4758         compose_list = g_list_append(compose_list, compose);
4759
4760 #if 0 /* NEW COMPOSE GUI */
4761         compose->use_to         = FALSE;
4762         compose->use_cc         = FALSE;
4763         compose->use_attach     = TRUE;
4764 #endif
4765
4766 #if 0 /* NEW COMPOSE GUI */
4767         if (!compose->use_bcc) {
4768                 gtk_widget_hide(bcc_hbox);
4769                 gtk_widget_hide(bcc_entry);
4770                 gtk_table_set_row_spacing(GTK_TABLE(table), 4, 0);
4771         }
4772         if (!compose->use_replyto) {
4773                 gtk_widget_hide(reply_hbox);
4774                 gtk_widget_hide(reply_entry);
4775                 gtk_table_set_row_spacing(GTK_TABLE(table), 5, 0);
4776         }
4777         if (!compose->use_followupto) {
4778                 gtk_widget_hide(followup_hbox);
4779                 gtk_widget_hide(followup_entry);
4780                 gtk_table_set_row_spacing(GTK_TABLE(table), 6, 0);
4781         }
4782 #endif
4783         if (!prefs_common.show_ruler)
4784                 gtk_widget_hide(ruler_hbox);
4785
4786         /* Priority */
4787         compose->priority = PRIORITY_NORMAL;
4788         compose_update_priority_menu_item(compose);
4789
4790         select_account(compose, account);
4791         set_toolbar_style(compose);
4792
4793         return compose;
4794 }
4795
4796 static void compose_toolbar_create(Compose *compose, GtkWidget *container)
4797 {
4798         GtkWidget *toolbar;
4799         GtkWidget *icon_wid;
4800         GtkWidget *send_btn;
4801         GtkWidget *sendl_btn;
4802         GtkWidget *draft_btn;
4803         GtkWidget *insert_btn;
4804         GtkWidget *attach_btn;
4805         GtkWidget *sig_btn;
4806         GtkWidget *exteditor_btn;
4807         GtkWidget *linewrap_btn;
4808         GtkWidget *addrbook_btn;
4809
4810         toolbar = gtk_toolbar_new(GTK_ORIENTATION_HORIZONTAL,
4811                                   GTK_TOOLBAR_BOTH);
4812         gtk_container_add(GTK_CONTAINER(container), toolbar);
4813         gtk_container_set_border_width(GTK_CONTAINER(container), 2);
4814         gtk_toolbar_set_button_relief(GTK_TOOLBAR(toolbar), GTK_RELIEF_NONE);
4815         gtk_toolbar_set_space_style(GTK_TOOLBAR(toolbar),
4816                                     GTK_TOOLBAR_SPACE_LINE);
4817
4818         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_MAIL_SEND);
4819         send_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4820                                            _("Send"),
4821                                            _("Send message"),
4822                                            "Send",
4823                                            icon_wid, toolbar_send_cb, compose);
4824
4825         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_MAIL_SEND_QUEUE);
4826         sendl_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4827                                            _("Send later"),
4828                                            _("Put into queue folder and send later"),
4829                                            "Send later",
4830                                            icon_wid, toolbar_send_later_cb,
4831                                            compose);
4832
4833         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_MAIL);
4834         draft_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4835                                             _("Draft"),
4836                                             _("Save to draft folder"),
4837                                             "Draft",
4838                                             icon_wid, toolbar_draft_cb,
4839                                             compose);
4840
4841         gtk_toolbar_append_space(GTK_TOOLBAR(toolbar));
4842
4843         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_INSERT_FILE);
4844         insert_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4845                                              _("Insert"),
4846                                              _("Insert file"),
4847                                              "Insert",
4848                                              icon_wid, toolbar_insert_cb,
4849                                              compose);
4850
4851         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_MAIL_ATTACH);
4852         attach_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4853                                              _("Attach"),
4854                                              _("Attach file"),
4855                                              "Attach",
4856                                              icon_wid, toolbar_attach_cb,
4857                                              compose);
4858
4859         gtk_toolbar_append_space(GTK_TOOLBAR(toolbar));
4860
4861         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_MAIL_SIGN);
4862         sig_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4863                                           _("Signature"),
4864                                           _("Insert signature"),
4865                                           "Signature",
4866                                           icon_wid, toolbar_sig_cb, compose);
4867
4868         gtk_toolbar_append_space(GTK_TOOLBAR(toolbar));
4869
4870         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_EDIT_EXTERN);
4871         exteditor_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4872                                                 _("Editor"),
4873                                                 _("Edit with external editor"),
4874                                                 "Editor",
4875                                                 icon_wid,
4876                                                 toolbar_ext_editor_cb,
4877                                                 compose);
4878
4879         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_LINEWRAP);
4880         linewrap_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4881                                                _("Linewrap"),
4882                                                _("Wrap all long lines"),
4883                                                "Linewrap",
4884                                                icon_wid,
4885                                                toolbar_linewrap_cb,
4886                                                compose);
4887
4888         gtk_toolbar_append_space(GTK_TOOLBAR(toolbar));
4889
4890         icon_wid = stock_pixmap_widget(container, STOCK_PIXMAP_ADDRESS_BOOK);
4891         addrbook_btn = gtk_toolbar_append_item(GTK_TOOLBAR(toolbar),
4892                                                _("Address"),
4893                                                _("Address book"),
4894                                                "Address",
4895                                                icon_wid, toolbar_address_cb,
4896                                                compose);
4897
4898         compose->toolbar       = toolbar;
4899         compose->send_btn      = send_btn;
4900         compose->sendl_btn     = sendl_btn;
4901         compose->draft_btn     = draft_btn;
4902         compose->insert_btn    = insert_btn;
4903         compose->attach_btn    = attach_btn;
4904         compose->sig_btn       = sig_btn;
4905         compose->exteditor_btn = exteditor_btn;
4906         compose->linewrap_btn  = linewrap_btn;
4907         compose->addrbook_btn  = addrbook_btn;
4908
4909         gtk_widget_show_all(toolbar);
4910 }
4911
4912 static GtkWidget *compose_account_option_menu_create(Compose *compose)
4913 {
4914         GList *accounts;
4915         GtkWidget *hbox;
4916         GtkWidget *optmenu;
4917         GtkWidget *menu;
4918         gint num = 0, def_menu = 0;
4919
4920         accounts = account_get_list();
4921         g_return_val_if_fail(accounts != NULL, NULL);
4922
4923         hbox = gtk_hbox_new(FALSE, 0);
4924         optmenu = gtk_option_menu_new();
4925         gtk_box_pack_start(GTK_BOX(hbox), optmenu, FALSE, FALSE, 0);
4926         menu = gtk_menu_new();
4927
4928         for (; accounts != NULL; accounts = accounts->next, num++) {
4929                 PrefsAccount *ac = (PrefsAccount *)accounts->data;
4930                 GtkWidget *menuitem;
4931                 gchar *name;
4932
4933                 if (ac == compose->account) def_menu = num;
4934
4935                 if (ac->name)
4936                         name = g_strdup_printf("%s: %s <%s>",
4937                                                ac->account_name,
4938                                                ac->name, ac->address);
4939                 else
4940                         name = g_strdup_printf("%s: %s",
4941                                                ac->account_name, ac->address);
4942                 MENUITEM_ADD(menu, menuitem, name, ac);
4943                 g_free(name);
4944                 gtk_signal_connect(GTK_OBJECT(menuitem), "activate",
4945                                    GTK_SIGNAL_FUNC(account_activated),
4946                                    compose);
4947         }
4948
4949         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), menu);
4950         gtk_option_menu_set_history(GTK_OPTION_MENU(optmenu), def_menu);
4951
4952         return hbox;
4953 }
4954
4955 static void compose_set_priority_cb(gpointer data,
4956                                     guint action,
4957                                     GtkWidget *widget)
4958 {
4959         Compose *compose = (Compose *) data;
4960         compose->priority = action;
4961 }
4962
4963 static void compose_update_priority_menu_item(Compose * compose)
4964 {
4965         GtkItemFactory *ifactory;
4966         GtkWidget *menuitem = NULL;
4967
4968         ifactory = gtk_item_factory_from_widget(compose->menubar);
4969         
4970         switch (compose->priority) {
4971                 case PRIORITY_HIGHEST:
4972                         menuitem = gtk_item_factory_get_item
4973                                 (ifactory, "/Message/Priority/Highest");
4974                         break;
4975                 case PRIORITY_HIGH:
4976                         menuitem = gtk_item_factory_get_item
4977                                 (ifactory, "/Message/Priority/High");
4978                         break;
4979                 case PRIORITY_NORMAL:
4980                         menuitem = gtk_item_factory_get_item
4981                                 (ifactory, "/Message/Priority/Normal");
4982                         break;
4983                 case PRIORITY_LOW:
4984                         menuitem = gtk_item_factory_get_item
4985                                 (ifactory, "/Message/Priority/Low");
4986                         break;
4987                 case PRIORITY_LOWEST:
4988                         menuitem = gtk_item_factory_get_item
4989                                 (ifactory, "/Message/Priority/Lowest");
4990                         break;
4991         }
4992         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem), TRUE);
4993 }       
4994  
4995 static void compose_set_template_menu(Compose *compose)
4996 {
4997         GSList *tmpl_list, *cur;
4998         GtkWidget *menu;
4999         GtkWidget *item;
5000
5001         tmpl_list = template_get_config();
5002
5003         menu = gtk_menu_new();
5004
5005         for (cur = tmpl_list; cur != NULL; cur = cur->next) {
5006                 Template *tmpl = (Template *)cur->data;
5007
5008                 item = gtk_menu_item_new_with_label(tmpl->name);
5009                 gtk_menu_append(GTK_MENU(menu), item);
5010                 gtk_signal_connect(GTK_OBJECT(item), "activate",
5011                                    GTK_SIGNAL_FUNC(compose_template_activate_cb),
5012                                    compose);
5013                 gtk_object_set_data(GTK_OBJECT(item), "template", tmpl);
5014                 gtk_widget_show(item);
5015         }
5016
5017         gtk_widget_show(menu);
5018         gtk_menu_item_set_submenu(GTK_MENU_ITEM(compose->tmpl_menu), menu);
5019 }
5020
5021 void compose_reflect_prefs_all(void)
5022 {
5023         GList *cur;
5024         Compose *compose;
5025
5026         for (cur = compose_list; cur != NULL; cur = cur->next) {
5027                 compose = (Compose *)cur->data;
5028                 compose_set_template_menu(compose);
5029         }
5030 }
5031
5032 void compose_reflect_prefs_pixmap_theme(void)
5033 {
5034         GList *cur;
5035         Compose *compose;
5036
5037         for (cur = compose_list; cur != NULL; cur = cur->next) {
5038                 compose = (Compose *)cur->data;
5039                 gtk_container_remove(GTK_CONTAINER(compose->handlebox), GTK_WIDGET(compose->toolbar));
5040                 compose->toolbar = NULL;
5041                 compose_toolbar_create(compose, compose->handlebox);
5042                 set_toolbar_style(compose);
5043         }
5044 }
5045
5046 static void compose_template_apply(Compose *compose, Template *tmpl,
5047                                    gboolean replace)
5048 {
5049         gchar *qmark;
5050         gchar *parsed_str;
5051
5052         if (!tmpl || !tmpl->value) return;
5053
5054         gtk_stext_freeze(GTK_STEXT(compose->text));
5055
5056         if (tmpl->subject && *tmpl->subject != '\0')
5057                 gtk_entry_set_text(GTK_ENTRY(compose->subject_entry),
5058                                    tmpl->subject);
5059         if (tmpl->to && *tmpl->to != '\0')
5060                 compose_entry_append(compose, tmpl->to, COMPOSE_TO);
5061
5062         if (replace)
5063                 gtk_stext_clear(GTK_STEXT(compose->text));
5064
5065         if (compose->replyinfo == NULL) {
5066                 parsed_str = compose_quote_fmt(compose, NULL, tmpl->value,
5067                                                NULL, NULL);
5068         } else {
5069                 if (prefs_common.quotemark && *prefs_common.quotemark)
5070                         qmark = prefs_common.quotemark;
5071                 else
5072                         qmark = "> ";
5073
5074                 parsed_str = compose_quote_fmt(compose, compose->replyinfo,
5075                                                tmpl->value, qmark, NULL);
5076         }
5077
5078         if (replace && parsed_str && prefs_common.auto_sig)
5079                 compose_insert_sig(compose);
5080
5081         if (replace && parsed_str) {
5082                 gtk_editable_set_position(GTK_EDITABLE(compose->text), 0);
5083                 gtk_stext_set_point(GTK_STEXT(compose->text), 0);
5084         }
5085
5086         if (parsed_str)
5087                 compose_changed_cb(NULL, compose);
5088
5089         gtk_stext_thaw(GTK_STEXT(compose->text));
5090 }
5091
5092 static void compose_destroy(Compose *compose)
5093 {
5094         gint row;
5095         GtkCList *clist = GTK_CLIST(compose->attach_clist);
5096         AttachInfo *ainfo;
5097
5098         /* NOTE: address_completion_end() does nothing with the window
5099          * however this may change. */
5100         address_completion_end(compose->window);
5101
5102         slist_free_strings(compose->to_list);
5103         g_slist_free(compose->to_list);
5104         slist_free_strings(compose->newsgroup_list);
5105         g_slist_free(compose->newsgroup_list);
5106         slist_free_strings(compose->header_list);
5107         g_slist_free(compose->header_list);
5108
5109         procmsg_msginfo_free(compose->targetinfo);
5110         procmsg_msginfo_free(compose->replyinfo);
5111
5112         g_free(compose->replyto);
5113         g_free(compose->cc);
5114         g_free(compose->bcc);
5115         g_free(compose->newsgroups);
5116         g_free(compose->followup_to);
5117
5118         g_free(compose->inreplyto);
5119         g_free(compose->references);
5120         g_free(compose->msgid);
5121         g_free(compose->boundary);
5122
5123         if (compose->redirect_filename)
5124                 g_free(compose->redirect_filename);
5125
5126         g_free(compose->exteditor_file);
5127
5128         for (row = 0; (ainfo = gtk_clist_get_row_data(clist, row)) != NULL;
5129              row++)
5130                 compose_attach_info_free(ainfo);
5131
5132         if (addressbook_get_target_compose() == compose)
5133                 addressbook_set_target_compose(NULL);
5134
5135 #if USE_PSPELL
5136         if (compose->gtkpspell) {
5137                 gtkpspell_delete(compose->gtkpspell);
5138         }
5139 #endif
5140
5141         prefs_common.compose_width = compose->scrolledwin->allocation.width;
5142         prefs_common.compose_height = compose->window->allocation.height;
5143
5144         gtk_widget_destroy(compose->paned);
5145
5146         g_free(compose);
5147
5148         compose_list = g_list_remove(compose_list, compose);
5149 }
5150
5151 static void compose_attach_info_free(AttachInfo *ainfo)
5152 {
5153         g_free(ainfo->file);
5154         g_free(ainfo->content_type);
5155         g_free(ainfo->name);
5156         g_free(ainfo);
5157 }
5158
5159 static void compose_attach_remove_selected(Compose *compose)
5160 {
5161         GtkCList *clist = GTK_CLIST(compose->attach_clist);
5162         AttachInfo *ainfo;
5163         gint row;
5164
5165         while (clist->selection != NULL) {
5166                 row = GPOINTER_TO_INT(clist->selection->data);
5167                 ainfo = gtk_clist_get_row_data(clist, row);
5168                 compose_attach_info_free(ainfo);
5169                 gtk_clist_remove(clist, row);
5170         }
5171 }
5172
5173 static struct _AttachProperty
5174 {
5175         GtkWidget *window;
5176         GtkWidget *mimetype_entry;
5177         GtkWidget *encoding_optmenu;
5178         GtkWidget *path_entry;
5179         GtkWidget *filename_entry;
5180         GtkWidget *ok_btn;
5181         GtkWidget *cancel_btn;
5182 } attach_prop;
5183
5184 static void compose_attach_property(Compose *compose)
5185 {
5186         GtkCList *clist = GTK_CLIST(compose->attach_clist);
5187         AttachInfo *ainfo;
5188         gint row;
5189         GtkOptionMenu *optmenu;
5190         static gboolean cancelled;
5191
5192         if (!clist->selection) return;
5193         row = GPOINTER_TO_INT(clist->selection->data);
5194
5195         ainfo = gtk_clist_get_row_data(clist, row);
5196         if (!ainfo) return;
5197
5198         if (!attach_prop.window)
5199                 compose_attach_property_create(&cancelled);
5200         gtk_widget_grab_focus(attach_prop.ok_btn);
5201         gtk_widget_show(attach_prop.window);
5202         manage_window_set_transient(GTK_WINDOW(attach_prop.window));
5203
5204         optmenu = GTK_OPTION_MENU(attach_prop.encoding_optmenu);
5205         if (ainfo->encoding == ENC_UNKNOWN)
5206                 gtk_option_menu_set_history(optmenu, ENC_BASE64);
5207         else
5208                 gtk_option_menu_set_history(optmenu, ainfo->encoding);
5209
5210         gtk_entry_set_text(GTK_ENTRY(attach_prop.mimetype_entry),
5211                            ainfo->content_type ? ainfo->content_type : "");
5212         gtk_entry_set_text(GTK_ENTRY(attach_prop.path_entry),
5213                            ainfo->file ? ainfo->file : "");
5214         gtk_entry_set_text(GTK_ENTRY(attach_prop.filename_entry),
5215                            ainfo->name ? ainfo->name : "");
5216
5217         for (;;) {
5218                 gchar *text;
5219                 gchar *cnttype = NULL;
5220                 gchar *file = NULL;
5221                 off_t size = 0;
5222                 GtkWidget *menu;
5223                 GtkWidget *menuitem;
5224
5225                 cancelled = FALSE;
5226                 gtk_main();
5227
5228                 if (cancelled == TRUE) {
5229                         gtk_widget_hide(attach_prop.window);
5230                         break;
5231                 }
5232
5233                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.mimetype_entry));
5234                 if (*text != '\0') {
5235                         gchar *p;
5236
5237                         text = g_strstrip(g_strdup(text));
5238                         if ((p = strchr(text, '/')) && !strchr(p + 1, '/')) {
5239                                 cnttype = g_strdup(text);
5240                                 g_free(text);
5241                         } else {
5242                                 alertpanel_error(_("Invalid MIME type."));
5243                                 g_free(text);
5244                                 continue;
5245                         }
5246                 }
5247
5248                 menu = gtk_option_menu_get_menu(optmenu);
5249                 menuitem = gtk_menu_get_active(GTK_MENU(menu));
5250                 ainfo->encoding = GPOINTER_TO_INT
5251                         (gtk_object_get_user_data(GTK_OBJECT(menuitem)));
5252
5253                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.path_entry));
5254                 if (*text != '\0') {
5255                         if (is_file_exist(text) &&
5256                             (size = get_file_size(text)) > 0)
5257                                 file = g_strdup(text);
5258                         else {
5259                                 alertpanel_error
5260                                         (_("File doesn't exist or is empty."));
5261                                 g_free(cnttype);
5262                                 continue;
5263                         }
5264                 }
5265
5266                 text = gtk_entry_get_text(GTK_ENTRY(attach_prop.filename_entry));
5267                 if (*text != '\0') {
5268                         g_free(ainfo->name);
5269                         ainfo->name = g_strdup(text);
5270                 }
5271
5272                 if (cnttype) {
5273                         g_free(ainfo->content_type);
5274                         ainfo->content_type = cnttype;
5275                 }
5276                 if (file) {
5277                         g_free(ainfo->file);
5278                         ainfo->file = file;
5279                 }
5280                 if (size)
5281                         ainfo->size = size;
5282
5283                 gtk_clist_set_text(clist, row, COL_MIMETYPE,
5284                                    ainfo->content_type);
5285                 gtk_clist_set_text(clist, row, COL_SIZE,
5286                                    to_human_readable(ainfo->size));
5287                 gtk_clist_set_text(clist, row, COL_NAME, ainfo->name);
5288
5289                 gtk_widget_hide(attach_prop.window);
5290                 break;
5291         }
5292 }
5293
5294 #define SET_LABEL_AND_ENTRY(str, entry, top) \
5295 { \
5296         label = gtk_label_new(str); \
5297         gtk_table_attach(GTK_TABLE(table), label, 0, 1, top, (top + 1), \
5298                          GTK_FILL, 0, 0, 0); \
5299         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); \
5300  \
5301         entry = gtk_entry_new(); \
5302         gtk_table_attach(GTK_TABLE(table), entry, 1, 2, top, (top + 1), \
5303                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0); \
5304 }
5305
5306 static void compose_attach_property_create(gboolean *cancelled)
5307 {
5308         GtkWidget *window;
5309         GtkWidget *vbox;
5310         GtkWidget *table;
5311         GtkWidget *label;
5312         GtkWidget *mimetype_entry;
5313         GtkWidget *hbox;
5314         GtkWidget *optmenu;
5315         GtkWidget *optmenu_menu;
5316         GtkWidget *menuitem;
5317         GtkWidget *path_entry;
5318         GtkWidget *filename_entry;
5319         GtkWidget *hbbox;
5320         GtkWidget *ok_btn;
5321         GtkWidget *cancel_btn;
5322         GList     *mime_type_list, *strlist;
5323
5324         debug_print("Creating attach_property window...\n");
5325
5326         window = gtk_window_new(GTK_WINDOW_DIALOG);
5327         gtk_widget_set_usize(window, 480, -1);
5328         gtk_container_set_border_width(GTK_CONTAINER(window), 8);
5329         gtk_window_set_title(GTK_WINDOW(window), _("Property"));
5330         gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
5331         gtk_window_set_modal(GTK_WINDOW(window), TRUE);
5332         gtk_signal_connect(GTK_OBJECT(window), "delete_event",
5333                            GTK_SIGNAL_FUNC(attach_property_delete_event),
5334                            cancelled);
5335         gtk_signal_connect(GTK_OBJECT(window), "key_press_event",
5336                            GTK_SIGNAL_FUNC(attach_property_key_pressed),
5337                            cancelled);
5338
5339         vbox = gtk_vbox_new(FALSE, 8);
5340         gtk_container_add(GTK_CONTAINER(window), vbox);
5341
5342         table = gtk_table_new(4, 2, FALSE);
5343         gtk_box_pack_start(GTK_BOX(vbox), table, FALSE, FALSE, 0);
5344         gtk_table_set_row_spacings(GTK_TABLE(table), 8);
5345         gtk_table_set_col_spacings(GTK_TABLE(table), 8);
5346
5347         label = gtk_label_new(_("MIME type")); 
5348         gtk_table_attach(GTK_TABLE(table), label, 0, 1, 0, (0 + 1), 
5349                          GTK_FILL, 0, 0, 0); 
5350         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); 
5351         mimetype_entry = gtk_combo_new(); 
5352         gtk_table_attach(GTK_TABLE(table), mimetype_entry, 1, 2, 0, (0 + 1), 
5353                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0);
5354                          
5355         /* stuff with list */
5356         mime_type_list = procmime_get_mime_type_list();
5357         strlist = NULL;
5358         for (; mime_type_list != NULL; mime_type_list = mime_type_list->next) {
5359                 MimeType *type = (MimeType *) mime_type_list->data;
5360                 strlist = g_list_append(strlist, 
5361                                 g_strdup_printf("%s/%s",
5362                                         type->type, type->sub_type));
5363         }
5364         
5365         gtk_combo_set_popdown_strings(GTK_COMBO(mimetype_entry), strlist);
5366
5367         for (mime_type_list = strlist; mime_type_list != NULL; 
5368                 mime_type_list = mime_type_list->next)
5369                 g_free(mime_type_list->data);
5370         g_list_free(strlist);
5371                          
5372         mimetype_entry = GTK_COMBO(mimetype_entry)->entry;                       
5373
5374         label = gtk_label_new(_("Encoding"));
5375         gtk_table_attach(GTK_TABLE(table), label, 0, 1, 1, 2,
5376                          GTK_FILL, 0, 0, 0);
5377         gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5);
5378
5379         hbox = gtk_hbox_new(FALSE, 0);
5380         gtk_table_attach(GTK_TABLE(table), hbox, 1, 2, 1, 2,
5381                          GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0, 0);
5382
5383         optmenu = gtk_option_menu_new();
5384         gtk_box_pack_start(GTK_BOX(hbox), optmenu, TRUE, TRUE, 0);
5385
5386         optmenu_menu = gtk_menu_new();
5387         MENUITEM_ADD(optmenu_menu, menuitem, "7bit", ENC_7BIT);
5388         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
5389 #if 0
5390         gtk_widget_set_sensitive(menuitem, FALSE);
5391 #endif
5392         MENUITEM_ADD(optmenu_menu, menuitem, "8bit", ENC_8BIT);
5393         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
5394 #if 0
5395         gtk_widget_set_sensitive(menuitem, FALSE);
5396 #endif
5397         MENUITEM_ADD(optmenu_menu, menuitem, "quoted-printable", ENC_QUOTED_PRINTABLE);
5398         gtk_widget_set_sensitive(menuitem, FALSE);
5399         MENUITEM_ADD(optmenu_menu, menuitem, "base64", ENC_BASE64);
5400
5401         gtk_option_menu_set_menu(GTK_OPTION_MENU(optmenu), optmenu_menu);
5402
5403         SET_LABEL_AND_ENTRY(_("Path"),      path_entry,     2);
5404         SET_LABEL_AND_ENTRY(_("File name"), filename_entry, 3);
5405
5406         gtkut_button_set_create(&hbbox, &ok_btn, _("OK"),
5407                                 &cancel_btn, _("Cancel"), NULL, NULL);
5408         gtk_box_pack_end(GTK_BOX(vbox), hbbox, FALSE, FALSE, 0);
5409         gtk_widget_grab_default(ok_btn);
5410
5411         gtk_signal_connect(GTK_OBJECT(ok_btn), "clicked",
5412                            GTK_SIGNAL_FUNC(attach_property_ok),
5413                            cancelled);
5414         gtk_signal_connect(GTK_OBJECT(cancel_btn), "clicked",
5415                            GTK_SIGNAL_FUNC(attach_property_cancel),
5416                            cancelled);
5417
5418         gtk_widget_show_all(vbox);
5419
5420         attach_prop.window           = window;
5421         attach_prop.mimetype_entry   = mimetype_entry;
5422         attach_prop.encoding_optmenu = optmenu;
5423         attach_prop.path_entry       = path_entry;
5424         attach_prop.filename_entry   = filename_entry;
5425         attach_prop.ok_btn           = ok_btn;
5426         attach_prop.cancel_btn       = cancel_btn;
5427 }
5428
5429 #undef SET_LABEL_AND_ENTRY
5430
5431 static void attach_property_ok(GtkWidget *widget, gboolean *cancelled)
5432 {
5433         *cancelled = FALSE;
5434         gtk_main_quit();
5435 }
5436
5437 static void attach_property_cancel(GtkWidget *widget, gboolean *cancelled)
5438 {
5439         *cancelled = TRUE;
5440         gtk_main_quit();
5441 }
5442
5443 static gint attach_property_delete_event(GtkWidget *widget, GdkEventAny *event,
5444                                          gboolean *cancelled)
5445 {
5446         *cancelled = TRUE;
5447         gtk_main_quit();
5448
5449         return TRUE;
5450 }
5451
5452 static void attach_property_key_pressed(GtkWidget *widget, GdkEventKey *event,
5453                                         gboolean *cancelled)
5454 {
5455         if (event && event->keyval == GDK_Escape) {
5456                 *cancelled = TRUE;
5457                 gtk_main_quit();
5458         }
5459 }
5460
5461 static void compose_exec_ext_editor(Compose *compose)
5462 {
5463         gchar tmp[64];
5464         pid_t pid;
5465         gint pipe_fds[2];
5466
5467         g_snprintf(tmp, sizeof(tmp), "%s%ctmpmsg.%08x",
5468                    g_get_tmp_dir(), G_DIR_SEPARATOR, (gint)compose);
5469
5470         if (pipe(pipe_fds) < 0) {
5471                 perror("pipe");
5472                 return;
5473         }
5474
5475         if ((pid = fork()) < 0) {
5476                 perror("fork");
5477                 return;
5478         }
5479
5480         if (pid != 0) {
5481                 /* close the write side of the pipe */
5482                 close(pipe_fds[1]);
5483
5484                 compose->exteditor_file    = g_strdup(tmp);
5485                 compose->exteditor_pid     = pid;
5486                 compose->exteditor_readdes = pipe_fds[0];
5487
5488                 compose_set_ext_editor_sensitive(compose, FALSE);
5489
5490                 compose->exteditor_tag =
5491                         gdk_input_add(pipe_fds[0], GDK_INPUT_READ,
5492                                       compose_input_cb, compose);
5493         } else {        /* process-monitoring process */
5494                 pid_t pid_ed;
5495
5496                 if (setpgid(0, 0))
5497                         perror("setpgid");
5498
5499                 /* close the read side of the pipe */
5500                 close(pipe_fds[0]);
5501
5502                 if (compose_write_body_to_file(compose, tmp) < 0) {
5503                         fd_write(pipe_fds[1], "2\n", 2);
5504                         _exit(1);
5505                 }
5506
5507                 pid_ed = compose_exec_ext_editor_real(tmp);
5508                 if (pid_ed < 0) {
5509                         fd_write(pipe_fds[1], "1\n", 2);
5510                         _exit(1);
5511                 }
5512
5513                 /* wait until editor is terminated */
5514                 waitpid(pid_ed, NULL, 0);
5515
5516                 fd_write(pipe_fds[1], "0\n", 2);
5517
5518                 close(pipe_fds[1]);
5519                 _exit(0);
5520         }
5521 }
5522
5523 static gint compose_exec_ext_editor_real(const gchar *file)
5524 {
5525         static gchar *def_cmd = "emacs %s";
5526         gchar buf[1024];
5527         gchar *p;
5528         gchar **cmdline;
5529         pid_t pid;
5530
5531         g_return_val_if_fail(file != NULL, -1);
5532
5533         if ((pid = fork()) < 0) {
5534                 perror("fork");
5535                 return -1;
5536         }
5537
5538         if (pid != 0) return pid;
5539
5540         /* grandchild process */
5541
5542         if (setpgid(0, getppid()))
5543                 perror("setpgid");
5544
5545         if (prefs_common.ext_editor_cmd &&
5546             (p = strchr(prefs_common.ext_editor_cmd, '%')) &&
5547             *(p + 1) == 's' && !strchr(p + 2, '%')) {
5548                 g_snprintf(buf, sizeof(buf), prefs_common.ext_editor_cmd, file);
5549         } else {
5550                 if (prefs_common.ext_editor_cmd)
5551                         g_warning(_("External editor command line is invalid: `%s'\n"),
5552                                   prefs_common.ext_editor_cmd);
5553                 g_snprintf(buf, sizeof(buf), def_cmd, file);
5554         }
5555
5556         cmdline = strsplit_with_quote(buf, " ", 1024);
5557         execvp(cmdline[0], cmdline);
5558
5559         perror("execvp");
5560         g_strfreev(cmdline);
5561
5562         _exit(1);
5563 }
5564
5565 static gboolean compose_ext_editor_kill(Compose *compose)
5566 {
5567         pid_t pgid = compose->exteditor_pid * -1;
5568         gint ret;
5569
5570         ret = kill(pgid, 0);
5571
5572         if (ret == 0 || (ret == -1 && EPERM == errno)) {
5573                 AlertValue val;
5574                 gchar *msg;
5575
5576                 msg = g_strdup_printf
5577                         (_("The external editor is still working.\n"
5578                            "Force terminating the process?\n"
5579                            "process group id: %d"), -pgid);
5580                 val = alertpanel(_("Notice"), msg, _("Yes"), _("+No"), NULL);
5581                 g_free(msg);
5582
5583                 if (val == G_ALERTDEFAULT) {
5584                         gdk_input_remove(compose->exteditor_tag);
5585                         close(compose->exteditor_readdes);
5586
5587                         if (kill(pgid, SIGTERM) < 0) perror("kill");
5588                         waitpid(compose->exteditor_pid, NULL, 0);
5589
5590                         g_warning(_("Terminated process group id: %d"), -pgid);
5591                         g_warning(_("Temporary file: %s"),
5592                                   compose->exteditor_file);
5593
5594                         compose_set_ext_editor_sensitive(compose, TRUE);
5595
5596                         g_free(compose->exteditor_file);
5597                         compose->exteditor_file    = NULL;
5598                         compose->exteditor_pid     = -1;
5599                         compose->exteditor_readdes = -1;
5600                         compose->exteditor_tag     = -1;
5601                 } else
5602                         return FALSE;
5603         }
5604
5605         return TRUE;
5606 }
5607
5608 static void compose_input_cb(gpointer data, gint source,
5609                              GdkInputCondition condition)
5610 {
5611         gchar buf[3];
5612         Compose *compose = (Compose *)data;
5613         gint i = 0;
5614
5615         debug_print(_("Compose: input from monitoring process\n"));
5616
5617         gdk_input_remove(compose->exteditor_tag);
5618
5619         for (;;) {
5620                 if (read(source, &buf[i], 1) < 1) {
5621                         buf[0] = '3';
5622                         break;
5623                 }
5624                 if (buf[i] == '\n') {
5625                         buf[i] = '\0';
5626                         break;
5627                 }
5628                 i++;
5629                 if (i == sizeof(buf) - 1)
5630                         break;
5631         }
5632
5633         waitpid(compose->exteditor_pid, NULL, 0);
5634
5635         if (buf[0] == '0') {            /* success */
5636                 GtkSText *text = GTK_STEXT(compose->text);
5637
5638                 gtk_stext_freeze(text);
5639                 gtk_stext_set_point(text, 0);
5640                 gtk_stext_forward_delete(text, gtk_stext_get_length(text));
5641                 compose_insert_file(compose, compose->exteditor_file);
5642                 compose_changed_cb(NULL, compose);
5643                 gtk_stext_thaw(text);
5644
5645                 if (unlink(compose->exteditor_file) < 0)
5646                         FILE_OP_ERROR(compose->exteditor_file, "unlink");
5647         } else if (buf[0] == '1') {     /* failed */
5648                 g_warning(_("Couldn't exec external editor\n"));
5649                 if (unlink(compose->exteditor_file) < 0)
5650                         FILE_OP_ERROR(compose->exteditor_file, "unlink");
5651         } else if (buf[0] == '2') {
5652                 g_warning(_("Couldn't write to file\n"));
5653         } else if (buf[0] == '3') {
5654                 g_warning(_("Pipe read failed\n"));
5655         }
5656
5657         close(source);
5658
5659         compose_set_ext_editor_sensitive(compose, TRUE);
5660
5661         g_free(compose->exteditor_file);
5662         compose->exteditor_file    = NULL;
5663         compose->exteditor_pid     = -1;
5664         compose->exteditor_readdes = -1;
5665         compose->exteditor_tag     = -1;
5666 }
5667
5668 static void compose_set_ext_editor_sensitive(Compose *compose,
5669                                              gboolean sensitive)
5670 {
5671         GtkItemFactory *ifactory;
5672
5673         ifactory = gtk_item_factory_from_widget(compose->menubar);
5674
5675         menu_set_sensitive(ifactory, "/Message/Send", sensitive);
5676         menu_set_sensitive(ifactory, "/Message/Send later", sensitive);
5677         menu_set_sensitive(ifactory, "/Message/Save to draft folder",
5678                            sensitive);
5679         menu_set_sensitive(ifactory, "/File/Insert file", sensitive);
5680         menu_set_sensitive(ifactory, "/File/Insert signature", sensitive);
5681         menu_set_sensitive(ifactory, "/Edit/Wrap current paragraph", sensitive);
5682         menu_set_sensitive(ifactory, "/Edit/Wrap all long lines", sensitive);
5683         menu_set_sensitive(ifactory, "/Edit/Edit with external editor",
5684                            sensitive);
5685
5686         gtk_widget_set_sensitive(compose->text,          sensitive);
5687         gtk_widget_set_sensitive(compose->send_btn,      sensitive);
5688         gtk_widget_set_sensitive(compose->sendl_btn,     sensitive);
5689         gtk_widget_set_sensitive(compose->draft_btn,     sensitive);
5690         gtk_widget_set_sensitive(compose->insert_btn,    sensitive);
5691         gtk_widget_set_sensitive(compose->sig_btn,       sensitive);
5692         gtk_widget_set_sensitive(compose->exteditor_btn, sensitive);
5693         gtk_widget_set_sensitive(compose->linewrap_btn,  sensitive);
5694 }
5695
5696 /**
5697  * compose_undo_state_changed:
5698  *
5699  * Change the sensivity of the menuentries undo and redo
5700  **/
5701 static void compose_undo_state_changed(UndoMain *undostruct, gint undo_state,
5702                                        gint redo_state, gpointer data)
5703 {
5704         GtkWidget *widget = GTK_WIDGET(data);
5705         GtkItemFactory *ifactory;
5706
5707         g_return_if_fail(widget != NULL);
5708
5709         debug_print("Set_undo.  UNDO:%i  REDO:%i\n", undo_state, redo_state);
5710
5711         ifactory = gtk_item_factory_from_widget(widget);
5712
5713         switch (undo_state) {
5714         case UNDO_STATE_TRUE:
5715                 if (!undostruct->undo_state) {
5716                         debug_print ("Set_undo - Testpoint\n");
5717                         undostruct->undo_state = TRUE;
5718                         menu_set_sensitive(ifactory, "/Edit/Undo", TRUE);
5719                 }
5720                 break;
5721         case UNDO_STATE_FALSE:
5722                 if (undostruct->undo_state) {
5723                         undostruct->undo_state = FALSE;
5724                         menu_set_sensitive(ifactory, "/Edit/Undo", FALSE);
5725                 }
5726                 break;
5727         case UNDO_STATE_UNCHANGED:
5728                 break;
5729         case UNDO_STATE_REFRESH:
5730                 menu_set_sensitive(ifactory, "/Edit/Undo",
5731                                    undostruct->undo_state);
5732                 break;
5733         default:
5734                 g_warning("Undo state not recognized");
5735                 break;
5736         }
5737
5738         switch (redo_state) {
5739         case UNDO_STATE_TRUE:
5740                 if (!undostruct->redo_state) {
5741                         undostruct->redo_state = TRUE;
5742                         menu_set_sensitive(ifactory, "/Edit/Redo", TRUE);
5743                 }
5744                 break;
5745         case UNDO_STATE_FALSE:
5746                 if (undostruct->redo_state) {
5747                         undostruct->redo_state = FALSE;
5748                         menu_set_sensitive(ifactory, "/Edit/Redo", FALSE);
5749                 }
5750                 break;
5751         case UNDO_STATE_UNCHANGED:
5752                 break;
5753         case UNDO_STATE_REFRESH:
5754                 menu_set_sensitive(ifactory, "/Edit/Redo",
5755                                    undostruct->redo_state);
5756                 break;
5757         default:
5758                 g_warning("Redo state not recognized");
5759                 break;
5760         }
5761 }
5762
5763 static gint calc_cursor_xpos(GtkSText *text, gint extra, gint char_width)
5764 {
5765         gint cursor_pos;
5766
5767         cursor_pos = (text->cursor_pos_x - extra) / char_width;
5768         cursor_pos = MAX(cursor_pos, 0);
5769
5770         return cursor_pos;
5771 }
5772
5773 /* callback functions */
5774
5775 /* compose_edit_size_alloc() - called when resized. don't know whether Gtk
5776  * includes "non-client" (windows-izm) in calculation, so this calculation
5777  * may not be accurate.
5778  */
5779 static gboolean compose_edit_size_alloc(GtkEditable *widget,
5780                                         GtkAllocation *allocation,
5781                                         GtkSHRuler *shruler)
5782 {
5783         if (prefs_common.show_ruler) {
5784                 gint char_width;
5785                 gint line_width_in_chars;
5786
5787                 char_width = gtkut_get_font_width
5788                         (GTK_WIDGET(widget)->style->font);
5789                 line_width_in_chars =
5790                         (allocation->width - allocation->x) / char_width;
5791
5792                 /* got the maximum */
5793                 gtk_ruler_set_range(GTK_RULER(shruler),
5794                                     0.0, line_width_in_chars,
5795                                     calc_cursor_xpos(GTK_STEXT(widget),
5796                                                      allocation->x,
5797                                                      char_width),
5798                                     /*line_width_in_chars*/ char_width);
5799         }
5800
5801         return TRUE;
5802 }
5803
5804 static void toolbar_send_cb(GtkWidget *widget, gpointer data)
5805 {
5806         compose_send_cb(data, 0, NULL);
5807 }
5808
5809 static void toolbar_send_later_cb(GtkWidget *widget, gpointer data)
5810 {
5811         compose_send_later_cb(data, 0, NULL);
5812 }
5813
5814 static void toolbar_draft_cb(GtkWidget *widget, gpointer data)
5815 {
5816         compose_draft_cb(data, 0, NULL);
5817 }
5818
5819 static void toolbar_insert_cb(GtkWidget *widget, gpointer data)
5820 {
5821         compose_insert_file_cb(data, 0, NULL);
5822 }
5823
5824 static void toolbar_attach_cb(GtkWidget *widget, gpointer data)
5825 {
5826         compose_attach_cb(data, 0, NULL);
5827 }
5828
5829 static void toolbar_sig_cb(GtkWidget *widget, gpointer data)
5830 {
5831         Compose *compose = (Compose *)data;
5832
5833         compose_insert_sig(compose);
5834 }
5835
5836 static void toolbar_ext_editor_cb(GtkWidget *widget, gpointer data)
5837 {
5838         Compose *compose = (Compose *)data;
5839
5840         compose_exec_ext_editor(compose);
5841 }
5842
5843 static void toolbar_linewrap_cb(GtkWidget *widget, gpointer data)
5844 {
5845         Compose *compose = (Compose *)data;
5846
5847         compose_wrap_line(compose);
5848 }
5849
5850 static void toolbar_address_cb(GtkWidget *widget, gpointer data)
5851 {
5852         compose_address_cb(data, 0, NULL);
5853 }
5854
5855 static void select_account(Compose * compose, PrefsAccount * ac)
5856 {
5857 #if USE_GPGME
5858         GtkItemFactory *ifactory;
5859         GtkWidget *menuitem;
5860 #endif /* USE_GPGME */
5861         compose->account = ac;
5862         compose_set_title(compose);
5863
5864 #if 0 /* NEW COMPOSE GUI */
5865                 if (ac->protocol == A_NNTP) {
5866                         GtkItemFactory *ifactory;
5867                         GtkWidget *menuitem;
5868
5869                         ifactory = gtk_item_factory_from_widget(compose->menubar);
5870                         menu_set_sensitive(ifactory,
5871                                            "/Message/Followup to", TRUE);
5872                         gtk_widget_show(compose->newsgroups_hbox);
5873                         gtk_widget_show(compose->newsgroups_entry);
5874                         gtk_table_set_row_spacing(GTK_TABLE(compose->table),
5875                                                   1, 4);
5876
5877                         compose->use_to = FALSE;
5878                         compose->use_cc = FALSE;
5879
5880                         menuitem = gtk_item_factory_get_item(ifactory, "/Message/To");
5881                         gtk_check_menu_item_set_active
5882                                 (GTK_CHECK_MENU_ITEM(menuitem), FALSE);
5883
5884                         menu_set_sensitive(ifactory,
5885                                            "/Message/To", TRUE);
5886                         menuitem = gtk_item_factory_get_item(ifactory, "/Message/Cc");
5887                         gtk_check_menu_item_set_active
5888                                 (GTK_CHECK_MENU_ITEM(menuitem), FALSE);
5889
5890                         gtk_widget_hide(compose->to_hbox);
5891                         gtk_widget_hide(compose->to_entry);
5892                         gtk_widget_hide(compose->cc_hbox);
5893                         gtk_widget_hide(compose->cc_entry);
5894                         gtk_table_set_row_spacing(GTK_TABLE(compose->table),
5895                                                   0, 0);
5896                         gtk_table_set_row_spacing(GTK_TABLE(compose->table),
5897                                                   3, 0);
5898                 }
5899                 else {
5900                         GtkItemFactory *ifactory;
5901                         GtkWidget *menuitem;
5902
5903                         ifactory = gtk_item_factory_from_widget(compose->menubar);
5904                         menu_set_sensitive(ifactory,
5905                                            "/Message/Followup to", FALSE);
5906                         gtk_entry_set_text(GTK_ENTRY(compose->newsgroups_entry), "");
5907                         gtk_widget_hide(compose->newsgroups_hbox);
5908                         gtk_widget_hide(compose->newsgroups_entry);
5909                         gtk_table_set_row_spacing(GTK_TABLE(compose->table),
5910                                                   1, 0);
5911
5912                         compose->use_to = TRUE;
5913                         compose->use_cc = TRUE;
5914
5915                         menuitem = gtk_item_factory_get_item(ifactory, "/Message/To");
5916                         gtk_check_menu_item_set_active
5917                                 (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
5918                         menu_set_sensitive(ifactory,
5919                                            "/Message/To", FALSE);
5920                         menuitem = gtk_item_factory_get_item(ifactory, "/Message/Cc");
5921                         gtk_check_menu_item_set_active
5922                                 (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
5923                         gtk_widget_show(compose->to_hbox);
5924                         gtk_widget_show(compose->to_entry);
5925                         gtk_widget_show(compose->cc_hbox);
5926                         gtk_widget_show(compose->cc_entry);
5927
5928                         gtk_table_set_row_spacing(GTK_TABLE(compose->table),
5929                                                   0, 4);
5930                         gtk_table_set_row_spacing(GTK_TABLE(compose->table),
5931                                                   3, 4);
5932                 }
5933                 gtk_widget_queue_resize(compose->table_vbox);
5934 #endif
5935 #if USE_GPGME
5936                 ifactory = gtk_item_factory_from_widget(compose->menubar);
5937                         menu_set_sensitive(ifactory,
5938                                            "/Message/Sign", TRUE);
5939                         menu_set_sensitive(ifactory,
5940                                            "/Message/Encrypt", TRUE);
5941
5942                         menuitem = gtk_item_factory_get_item(ifactory, "/Message/Sign");
5943                 if (ac->default_sign)
5944                         gtk_check_menu_item_set_active
5945                                 (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
5946                 else
5947                         gtk_check_menu_item_set_active
5948                                 (GTK_CHECK_MENU_ITEM(menuitem), FALSE);
5949
5950                         menuitem = gtk_item_factory_get_item(ifactory, "/Message/Encrypt");
5951                 if (ac->default_encrypt)
5952                         gtk_check_menu_item_set_active
5953                                 (GTK_CHECK_MENU_ITEM(menuitem), TRUE);
5954                 else
5955                         gtk_check_menu_item_set_active
5956                                 (GTK_CHECK_MENU_ITEM(menuitem), FALSE);
5957 #endif /* USE_GPGME */
5958
5959 }
5960
5961 static void account_activated(GtkMenuItem *menuitem, gpointer data)
5962 {
5963         Compose *compose = (Compose *)data;
5964
5965         PrefsAccount *ac;
5966
5967         ac = (PrefsAccount *)gtk_object_get_user_data(GTK_OBJECT(menuitem));
5968         g_return_if_fail(ac != NULL);
5969
5970         if (ac != compose->account)
5971                 select_account(compose, ac);
5972 }
5973
5974 static void attach_selected(GtkCList *clist, gint row, gint column,
5975                             GdkEvent *event, gpointer data)
5976 {
5977         Compose *compose = (Compose *)data;
5978
5979         if (event && event->type == GDK_2BUTTON_PRESS)
5980                 compose_attach_property(compose);
5981 }
5982
5983 static void attach_button_pressed(GtkWidget *widget, GdkEventButton *event,
5984                                   gpointer data)
5985 {
5986         Compose *compose = (Compose *)data;
5987         GtkCList *clist = GTK_CLIST(compose->attach_clist);
5988         gint row, column;
5989
5990         if (!event) return;
5991
5992         if (event->button == 3) {
5993                 if ((clist->selection && !clist->selection->next) ||
5994                     !clist->selection) {
5995                         gtk_clist_unselect_all(clist);
5996                         if (gtk_clist_get_selection_info(clist,
5997                                                          event->x, event->y,
5998                                                          &row, &column)) {
5999                                 gtk_clist_select_row(clist, row, column);
6000                                 gtkut_clist_set_focus_row(clist, row);
6001                         }
6002                 }
6003                 gtk_menu_popup(GTK_MENU(compose->popupmenu), NULL, NULL,
6004                                NULL, NULL, event->button, event->time);
6005         }
6006 }
6007
6008 static void attach_key_pressed(GtkWidget *widget, GdkEventKey *event,
6009                                gpointer data)
6010 {
6011         Compose *compose = (Compose *)data;
6012
6013         if (!event) return;
6014
6015         switch (event->keyval) {
6016         case GDK_Delete:
6017                 compose_attach_remove_selected(compose);
6018                 break;
6019         }
6020 }
6021
6022 static void compose_send_cb(gpointer data, guint action, GtkWidget *widget)
6023 {
6024         Compose *compose = (Compose *)data;
6025         gint val;
6026         
6027         if (prefs_common.work_offline)
6028                 if (alertpanel(_("Offline warning"), 
6029                                _("You're working offline. Override?"),
6030                                _("Yes"), _("No"), NULL) != G_ALERTDEFAULT)
6031                 return;
6032
6033         val = compose_send(compose);
6034
6035         if (val == 0) gtk_widget_destroy(compose->window);
6036 }
6037
6038 static void compose_send_later_cb(gpointer data, guint action,
6039                                   GtkWidget *widget)
6040 {
6041         Compose *compose = (Compose *)data;
6042         gint val;
6043
6044         val = compose_queue_sub(compose, NULL, NULL, TRUE);
6045         if (!val) gtk_widget_destroy(compose->window);
6046 }
6047
6048 static void compose_draft_cb(gpointer data, guint action, GtkWidget *widget)
6049 {
6050         Compose *compose = (Compose *)data;
6051         FolderItem *draft;
6052         gchar *tmp;
6053         gint msgnum;
6054         static gboolean lock = FALSE;
6055         MsgInfo *newmsginfo;
6056         
6057         if (lock) return;
6058
6059         draft = account_get_special_folder(compose->account, F_DRAFT);
6060         g_return_if_fail(draft != NULL);
6061
6062         lock = TRUE;
6063
6064         tmp = g_strdup_printf("%s%cdraft.%d", g_get_tmp_dir(),
6065                               G_DIR_SEPARATOR, (gint)compose);
6066
6067         if (compose_write_to_file(compose, tmp, TRUE) < 0) {
6068                 g_free(tmp);
6069                 lock = FALSE;
6070                 return;
6071         }
6072
6073         if ((msgnum = folder_item_add_msg(draft, tmp, TRUE)) < 0) {
6074                 unlink(tmp);
6075                 g_free(tmp);
6076                 lock = FALSE;
6077                 return;
6078         }
6079         g_free(tmp);
6080         draft->mtime = 0;       /* force updating */
6081
6082         if (compose->mode == COMPOSE_REEDIT) {
6083                 compose_remove_reedit_target(compose);
6084                 if (compose->targetinfo &&
6085                     compose->targetinfo->folder != draft)
6086                         folderview_update_item(compose->targetinfo->folder,
6087                                                TRUE);
6088         }
6089
6090         newmsginfo = folder_item_fetch_msginfo(draft, msgnum);
6091         procmsg_msginfo_unset_flags(newmsginfo, ~0, ~0);
6092         folderview_update_item(draft, TRUE);
6093         procmsg_msginfo_free(newmsginfo);
6094         
6095         lock = FALSE;
6096
6097         /* 0: quit editing  1: keep editing */
6098         if (action == 0)
6099                 gtk_widget_destroy(compose->window);
6100         else {
6101                 struct stat s;
6102                 gchar *path;
6103
6104                 path = folder_item_fetch_msg(draft, msgnum);
6105                 g_return_if_fail(path != NULL);
6106                 if (stat(path, &s) < 0) {
6107                         FILE_OP_ERROR(path, "stat");
6108                         g_free(path);
6109                         lock = FALSE;
6110                         return;
6111                 }
6112                 g_free(path);
6113
6114                 procmsg_msginfo_free(compose->targetinfo);
6115                 compose->targetinfo = procmsg_msginfo_new();
6116                 compose->targetinfo->msgnum = msgnum;
6117                 compose->targetinfo->size = s.st_size;
6118                 compose->targetinfo->mtime = s.st_mtime;
6119                 compose->targetinfo->folder = draft;
6120                 compose->mode = COMPOSE_REEDIT;
6121         }
6122 }
6123
6124 static void compose_attach_cb(gpointer data, guint action, GtkWidget *widget)
6125 {
6126         Compose *compose = (Compose *)data;
6127         GList *file_list;
6128
6129         if (compose->redirect_filename != NULL)
6130                 return;
6131
6132         file_list = filesel_select_multiple_files(_("Select file"), NULL);
6133
6134         if (file_list) {
6135                 GList *tmp;
6136
6137                 for ( tmp = file_list; tmp; tmp = tmp->next) {
6138                         gchar *file = (gchar *) tmp->data;
6139                         compose_attach_append(compose, file, file, NULL);
6140                         compose_changed_cb(NULL, compose);
6141                         g_free(file);
6142                 }
6143                 g_list_free(file_list);
6144         }               
6145 }
6146
6147 static void compose_insert_file_cb(gpointer data, guint action,
6148                                    GtkWidget *widget)
6149 {
6150         Compose *compose = (Compose *)data;
6151         GList *file_list;
6152
6153         file_list = filesel_select_multiple_files(_("Select file"), NULL);
6154
6155         if (file_list) {
6156                 GList *tmp;
6157
6158                 for ( tmp = file_list; tmp; tmp = tmp->next) {
6159                         gchar *file = (gchar *) tmp->data;
6160                         compose_insert_file(compose, file);
6161                         g_free(file);
6162                 }
6163                 g_list_free(file_list);
6164         }
6165 }
6166
6167 static gint compose_delete_cb(GtkWidget *widget, GdkEventAny *event,
6168                               gpointer data)
6169 {
6170         compose_close_cb(data, 0, NULL);
6171         return TRUE;
6172 }
6173
6174 static void compose_close_cb(gpointer data, guint action, GtkWidget *widget)
6175 {
6176         Compose *compose = (Compose *)data;
6177         AlertValue val;
6178
6179         if (compose->exteditor_tag != -1) {
6180                 if (!compose_ext_editor_kill(compose))
6181                         return;
6182         }
6183
6184         if (compose->modified) {
6185                 val = alertpanel(_("Discard message"),
6186                                  _("This message has been modified. discard it?"),
6187                                  _("Discard"), _("to Draft"), _("Cancel"));
6188
6189                 switch (val) {
6190                 case G_ALERTDEFAULT:
6191                         break;
6192                 case G_ALERTALTERNATE:
6193                         compose_draft_cb(data, 0, NULL);
6194                         return;
6195                 default:
6196                         return;
6197                 }
6198         }
6199         gtk_widget_destroy(compose->window);
6200 }
6201
6202 static void compose_address_cb(gpointer data, guint action, GtkWidget *widget)
6203 {
6204         Compose *compose = (Compose *)data;
6205
6206         addressbook_open(compose);
6207 }
6208
6209 static void compose_template_activate_cb(GtkWidget *widget, gpointer data)
6210 {
6211         Compose *compose = (Compose *)data;
6212         Template *tmpl;
6213         gchar *msg;
6214         AlertValue val;
6215
6216         tmpl = gtk_object_get_data(GTK_OBJECT(widget), "template");
6217         g_return_if_fail(tmpl != NULL);
6218
6219         msg = g_strdup_printf(_("Do you want to apply the template `%s' ?"),
6220                               tmpl->name);
6221         val = alertpanel(_("Apply template"), msg,
6222                          _("Replace"), _("Insert"), _("Cancel"));
6223         g_free(msg);
6224
6225         if (val == G_ALERTDEFAULT)
6226                 compose_template_apply(compose, tmpl, TRUE);
6227         else if (val == G_ALERTALTERNATE)
6228                 compose_template_apply(compose, tmpl, FALSE);
6229 }
6230
6231 static void compose_ext_editor_cb(gpointer data, guint action,
6232                                   GtkWidget *widget)
6233 {
6234         Compose *compose = (Compose *)data;
6235
6236         compose_exec_ext_editor(compose);
6237 }
6238
6239 static void compose_destroy_cb(GtkWidget *widget, Compose *compose)
6240 {
6241         compose_destroy(compose);
6242 }
6243
6244 static void compose_undo_cb(Compose *compose)
6245 {
6246         undo_undo(compose->undostruct);
6247 }
6248
6249 static void compose_redo_cb(Compose *compose)
6250 {
6251         undo_redo(compose->undostruct);
6252 }
6253
6254 static void compose_cut_cb(Compose *compose)
6255 {
6256         if (compose->focused_editable &&
6257             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
6258                 gtk_editable_cut_clipboard
6259                         (GTK_EDITABLE(compose->focused_editable));
6260 }
6261
6262 static void compose_copy_cb(Compose *compose)
6263 {
6264         if (compose->focused_editable &&
6265             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
6266                 gtk_editable_copy_clipboard
6267                         (GTK_EDITABLE(compose->focused_editable));
6268 }
6269
6270 static void compose_paste_cb(Compose *compose)
6271 {
6272         if (compose->focused_editable &&
6273             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
6274                 gtk_editable_paste_clipboard
6275                         (GTK_EDITABLE(compose->focused_editable));
6276 }
6277
6278 static void compose_paste_as_quote_cb(Compose *compose)
6279 {
6280         if (compose->focused_editable &&
6281             GTK_WIDGET_HAS_FOCUS(compose->focused_editable)) {
6282                 compose->paste_as_quotation = TRUE;
6283                 gtk_editable_paste_clipboard
6284                         (GTK_EDITABLE(compose->focused_editable));
6285                 compose->paste_as_quotation = FALSE;
6286         }
6287 }
6288
6289 static void compose_allsel_cb(Compose *compose)
6290 {
6291         if (compose->focused_editable &&
6292             GTK_WIDGET_HAS_FOCUS(compose->focused_editable))
6293                 gtk_editable_select_region
6294                         (GTK_EDITABLE(compose->focused_editable), 0, -1);
6295 }
6296
6297 static void compose_gtk_stext_action_cb(Compose *compose, ComposeCallGtkSTextAction action)
6298 {
6299         if (!(compose->focused_editable && GTK_WIDGET_HAS_FOCUS(compose->focused_editable))) return;
6300                 
6301         switch (action) {
6302                 case COMPOSE_CALL_GTK_STEXT_MOVE_BEGINNING_OF_LINE:
6303                         gtk_stext_move_beginning_of_line(GTK_STEXT(compose->focused_editable));
6304                         break;
6305                 case COMPOSE_CALL_GTK_STEXT_MOVE_FORWARD_CHARACTER:
6306                         gtk_stext_move_forward_character(GTK_STEXT(compose->focused_editable));
6307                         break;
6308                 case COMPOSE_CALL_GTK_STEXT_MOVE_BACKWARD_CHARACTER:
6309                         gtk_stext_move_backward_character(GTK_STEXT(compose->focused_editable));
6310                         break;
6311                 case COMPOSE_CALL_GTK_STEXT_MOVE_FORWARD_WORD:
6312                         gtk_stext_move_forward_word(GTK_STEXT(compose->focused_editable));
6313                         break;
6314                 case COMPOSE_CALL_GTK_STEXT_MOVE_BACKWARD_WORD:
6315                         gtk_stext_move_backward_word(GTK_STEXT(compose->focused_editable));
6316                         break;
6317                 case COMPOSE_CALL_GTK_STEXT_MOVE_END_OF_LINE:
6318                         gtk_stext_move_end_of_line(GTK_STEXT(compose->focused_editable));
6319                         break;
6320                 case COMPOSE_CALL_GTK_STEXT_MOVE_NEXT_LINE:
6321                         gtk_stext_move_next_line(GTK_STEXT(compose->focused_editable));
6322                         break;
6323                 case COMPOSE_CALL_GTK_STEXT_MOVE_PREVIOUS_LINE:
6324                         gtk_stext_move_previous_line(GTK_STEXT(compose->focused_editable));
6325                         break;
6326                 case COMPOSE_CALL_GTK_STEXT_DELETE_FORWARD_CHARACTER:
6327                         gtk_stext_delete_forward_character(GTK_STEXT(compose->focused_editable));
6328                         break;
6329                 case COMPOSE_CALL_GTK_STEXT_DELETE_BACKWARD_CHARACTER:
6330                         gtk_stext_delete_backward_character(GTK_STEXT(compose->focused_editable));
6331                         break;
6332                 case COMPOSE_CALL_GTK_STEXT_DELETE_FORWARD_WORD:
6333                         gtk_stext_delete_forward_word(GTK_STEXT(compose->focused_editable));
6334                         break;
6335                 case COMPOSE_CALL_GTK_STEXT_DELETE_BACKWARD_WORD:
6336                         gtk_stext_delete_backward_word(GTK_STEXT(compose->focused_editable));
6337                         break;
6338                 case COMPOSE_CALL_GTK_STEXT_DELETE_LINE:
6339                         gtk_stext_delete_line(GTK_STEXT(compose->focused_editable));
6340                         break;
6341                 case COMPOSE_CALL_GTK_STEXT_DELETE_LINE_N:
6342                         gtk_stext_delete_line(GTK_STEXT(compose->focused_editable));
6343                         gtk_stext_delete_forward_character(GTK_STEXT(compose->focused_editable));
6344                         break;
6345                 case COMPOSE_CALL_GTK_STEXT_DELETE_TO_LINE_END:
6346                         gtk_stext_delete_to_line_end(GTK_STEXT(compose->focused_editable));
6347                         break;
6348                 default:
6349                         break;
6350         }
6351 }
6352
6353 static void compose_grab_focus_cb(GtkWidget *widget, Compose *compose)
6354 {
6355         if (GTK_IS_EDITABLE(widget))
6356                 compose->focused_editable = widget;
6357 }
6358
6359 static void compose_changed_cb(GtkEditable *editable, Compose *compose)
6360 {
6361         if (compose->modified == FALSE) {
6362                 compose->modified = TRUE;
6363                 compose_set_title(compose);
6364         }
6365 }
6366
6367 static void compose_button_press_cb(GtkWidget *widget, GdkEventButton *event,
6368                                     Compose *compose)
6369 {
6370         gtk_stext_set_point(GTK_STEXT(widget),
6371                            gtk_editable_get_position(GTK_EDITABLE(widget)));
6372 }
6373
6374 #if 0
6375 static void compose_key_press_cb(GtkWidget *widget, GdkEventKey *event,
6376                                  Compose *compose)
6377 {
6378         gtk_stext_set_point(GTK_STEXT(widget),
6379                            gtk_editable_get_position(GTK_EDITABLE(widget)));
6380 }
6381 #endif
6382
6383 #if 0 /* NEW COMPOSE GUI */
6384 static void compose_toggle_to_cb(gpointer data, guint action,
6385                                  GtkWidget *widget)
6386 {
6387         Compose *compose = (Compose *)data;
6388
6389         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6390                 gtk_widget_show(compose->to_hbox);
6391                 gtk_widget_show(compose->to_entry);
6392                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 1, 4);
6393                 compose->use_to = TRUE;
6394         } else {
6395                 gtk_widget_hide(compose->to_hbox);
6396                 gtk_widget_hide(compose->to_entry);
6397                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 1, 0);
6398                 gtk_widget_queue_resize(compose->table_vbox);
6399                 compose->use_to = FALSE;
6400         }
6401
6402         if (addressbook_get_target_compose() == compose)
6403                 addressbook_set_target_compose(compose);
6404 }
6405
6406 static void compose_toggle_cc_cb(gpointer data, guint action,
6407                                  GtkWidget *widget)
6408 {
6409         Compose *compose = (Compose *)data;
6410
6411         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6412                 gtk_widget_show(compose->cc_hbox);
6413                 gtk_widget_show(compose->cc_entry);
6414                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 3, 4);
6415                 compose->use_cc = TRUE;
6416         } else {
6417                 gtk_widget_hide(compose->cc_hbox);
6418                 gtk_widget_hide(compose->cc_entry);
6419                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 3, 0);
6420                 gtk_widget_queue_resize(compose->table_vbox);
6421                 compose->use_cc = FALSE;
6422         }
6423
6424         if (addressbook_get_target_compose() == compose)
6425                 addressbook_set_target_compose(compose);
6426 }
6427
6428 static void compose_toggle_bcc_cb(gpointer data, guint action,
6429                                   GtkWidget *widget)
6430 {
6431         Compose *compose = (Compose *)data;
6432
6433         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6434                 gtk_widget_show(compose->bcc_hbox);
6435                 gtk_widget_show(compose->bcc_entry);
6436                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 4, 4);
6437                 compose->use_bcc = TRUE;
6438         } else {
6439                 gtk_widget_hide(compose->bcc_hbox);
6440                 gtk_widget_hide(compose->bcc_entry);
6441                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 4, 0);
6442                 gtk_widget_queue_resize(compose->table_vbox);
6443                 compose->use_bcc = FALSE;
6444         }
6445
6446         if (addressbook_get_target_compose() == compose)
6447                 addressbook_set_target_compose(compose);
6448 }
6449
6450 static void compose_toggle_replyto_cb(gpointer data, guint action,
6451                                       GtkWidget *widget)
6452 {
6453         Compose *compose = (Compose *)data;
6454
6455         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6456                 gtk_widget_show(compose->reply_hbox);
6457                 gtk_widget_show(compose->reply_entry);
6458                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 5, 4);
6459                 compose->use_replyto = TRUE;
6460         } else {
6461                 gtk_widget_hide(compose->reply_hbox);
6462                 gtk_widget_hide(compose->reply_entry);
6463                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 5, 0);
6464                 gtk_widget_queue_resize(compose->table_vbox);
6465                 compose->use_replyto = FALSE;
6466         }
6467 }
6468
6469 static void compose_toggle_followupto_cb(gpointer data, guint action,
6470                                          GtkWidget *widget)
6471 {
6472         Compose *compose = (Compose *)data;
6473
6474         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6475                 gtk_widget_show(compose->followup_hbox);
6476                 gtk_widget_show(compose->followup_entry);
6477                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 6, 4);
6478                 compose->use_followupto = TRUE;
6479         } else {
6480                 gtk_widget_hide(compose->followup_hbox);
6481                 gtk_widget_hide(compose->followup_entry);
6482                 gtk_table_set_row_spacing(GTK_TABLE(compose->table), 6, 0);
6483                 gtk_widget_queue_resize(compose->table_vbox);
6484                 compose->use_followupto = FALSE;
6485         }
6486 }
6487
6488 static void compose_toggle_attach_cb(gpointer data, guint action,
6489                                      GtkWidget *widget)
6490 {
6491         Compose *compose = (Compose *)data;
6492
6493         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6494                 gtk_widget_ref(compose->edit_vbox);
6495
6496                 gtkut_container_remove(GTK_CONTAINER(compose->vbox2),
6497                                        compose->edit_vbox);
6498                 gtk_paned_add2(GTK_PANED(compose->paned), compose->edit_vbox);
6499                 gtk_box_pack_start(GTK_BOX(compose->vbox2), compose->paned,
6500                                    TRUE, TRUE, 0);
6501                 gtk_widget_show(compose->paned);
6502
6503                 gtk_widget_unref(compose->edit_vbox);
6504                 gtk_widget_unref(compose->paned);
6505
6506                 compose->use_attach = TRUE;
6507         } else {
6508                 gtk_widget_ref(compose->paned);
6509                 gtk_widget_ref(compose->edit_vbox);
6510
6511                 gtkut_container_remove(GTK_CONTAINER(compose->vbox2),
6512                                        compose->paned);
6513                 gtkut_container_remove(GTK_CONTAINER(compose->paned),
6514                                        compose->edit_vbox);
6515                 gtk_box_pack_start(GTK_BOX(compose->vbox2),
6516                                    compose->edit_vbox, TRUE, TRUE, 0);
6517
6518                 gtk_widget_unref(compose->edit_vbox);
6519
6520                 compose->use_attach = FALSE;
6521         }
6522 }
6523 #endif
6524
6525 #if USE_GPGME
6526 static void compose_toggle_sign_cb(gpointer data, guint action,
6527                                    GtkWidget *widget)
6528 {
6529         Compose *compose = (Compose *)data;
6530
6531         if (GTK_CHECK_MENU_ITEM(widget)->active)
6532                 compose->use_signing = TRUE;
6533         else
6534                 compose->use_signing = FALSE;
6535 }
6536
6537 static void compose_toggle_encrypt_cb(gpointer data, guint action,
6538                                       GtkWidget *widget)
6539 {
6540         Compose *compose = (Compose *)data;
6541
6542         if (GTK_CHECK_MENU_ITEM(widget)->active)
6543                 compose->use_encryption = TRUE;
6544         else
6545                 compose->use_encryption = FALSE;
6546 }
6547 #endif /* USE_GPGME */
6548
6549 static void compose_toggle_ruler_cb(gpointer data, guint action,
6550                                     GtkWidget *widget)
6551 {
6552         Compose *compose = (Compose *)data;
6553
6554         if (GTK_CHECK_MENU_ITEM(widget)->active) {
6555                 gtk_widget_show(compose->ruler_hbox);
6556                 prefs_common.show_ruler = TRUE;
6557         } else {
6558                 gtk_widget_hide(compose->ruler_hbox);
6559                 gtk_widget_queue_resize(compose->edit_vbox);
6560                 prefs_common.show_ruler = FALSE;
6561         }
6562 }
6563
6564 static void compose_attach_drag_received_cb (GtkWidget          *widget,
6565                                              GdkDragContext     *drag_context,
6566                                              gint                x,
6567                                              gint                y,
6568                                              GtkSelectionData   *data,
6569                                              guint               info,
6570                                              guint               time,
6571                                              gpointer            user_data)
6572 {
6573         Compose *compose = (Compose *)user_data;
6574         GList *list, *tmp;
6575
6576         list = uri_list_extract_filenames((const gchar *)data->data);
6577         for (tmp = list; tmp != NULL; tmp = tmp->next)
6578                 compose_attach_append
6579                         (compose, (const gchar *)tmp->data,
6580                          (const gchar *)tmp->data, NULL);
6581         if (list) compose_changed_cb(NULL, compose);
6582         list_free_strings(list);
6583         g_list_free(list);
6584 }
6585
6586 static void compose_insert_drag_received_cb (GtkWidget          *widget,
6587                                              GdkDragContext     *drag_context,
6588                                              gint                x,
6589                                              gint                y,
6590                                              GtkSelectionData   *data,
6591                                              guint               info,
6592                                              guint               time,
6593                                              gpointer            user_data)
6594 {
6595         Compose *compose = (Compose *)user_data;
6596         GList *list, *tmp;
6597
6598         list = uri_list_extract_filenames((const gchar *)data->data);
6599         for (tmp = list; tmp != NULL; tmp = tmp->next)
6600                 compose_insert_file(compose, (const gchar *)tmp->data);
6601         list_free_strings(list);
6602         g_list_free(list);
6603 }
6604
6605 #if 0 /* NEW COMPOSE GUI */
6606 static void to_activated(GtkWidget *widget, Compose *compose)
6607 {
6608         if (GTK_WIDGET_VISIBLE(compose->newsgroups_entry))
6609                 gtk_widget_grab_focus(compose->newsgroups_entry);
6610         else
6611                 gtk_widget_grab_focus(compose->subject_entry);
6612 }
6613
6614 static void newsgroups_activated(GtkWidget *widget, Compose *compose)
6615 {
6616         gtk_widget_grab_focus(compose->subject_entry);
6617 }
6618
6619 static void subject_activated(GtkWidget *widget, Compose *compose)
6620 {
6621         if (GTK_WIDGET_VISIBLE(compose->cc_entry))
6622                 gtk_widget_grab_focus(compose->cc_entry);
6623         else if (GTK_WIDGET_VISIBLE(compose->bcc_entry))
6624                 gtk_widget_grab_focus(compose->bcc_entry);
6625         else if (GTK_WIDGET_VISIBLE(compose->reply_entry))
6626                 gtk_widget_grab_focus(compose->reply_entry);
6627         else if (GTK_WIDGET_VISIBLE(compose->followup_entry))
6628                 gtk_widget_grab_focus(compose->followup_entry);
6629         else
6630                 gtk_widget_grab_focus(compose->text);
6631 }
6632
6633 static void cc_activated(GtkWidget *widget, Compose *compose)
6634 {
6635         if (GTK_WIDGET_VISIBLE(compose->bcc_entry))
6636                 gtk_widget_grab_focus(compose->bcc_entry);
6637         else if (GTK_WIDGET_VISIBLE(compose->reply_entry))
6638                 gtk_widget_grab_focus(compose->reply_entry);
6639         else if (GTK_WIDGET_VISIBLE(compose->followup_entry))
6640                 gtk_widget_grab_focus(compose->followup_entry);
6641         else
6642                 gtk_widget_grab_focus(compose->text);
6643 }
6644
6645 static void bcc_activated(GtkWidget *widget, Compose *compose)
6646 {
6647         if (GTK_WIDGET_VISIBLE(compose->reply_entry))
6648                 gtk_widget_grab_focus(compose->reply_entry);
6649         else if (GTK_WIDGET_VISIBLE(compose->followup_entry))
6650                 gtk_widget_grab_focus(compose->followup_entry);
6651         else
6652                 gtk_widget_grab_focus(compose->text);
6653 }
6654
6655 static void replyto_activated(GtkWidget *widget, Compose *compose)
6656 {
6657         if (GTK_WIDGET_VISIBLE(compose->followup_entry))
6658                 gtk_widget_grab_focus(compose->followup_entry);
6659         else
6660                 gtk_widget_grab_focus(compose->text);
6661 }
6662
6663 static void followupto_activated(GtkWidget *widget, Compose *compose)
6664 {
6665         gtk_widget_grab_focus(compose->text);
6666 }
6667 #endif
6668
6669 static void compose_toggle_return_receipt_cb(gpointer data, guint action,
6670                                              GtkWidget *widget)
6671 {
6672         Compose *compose = (Compose *)data;
6673
6674         if (GTK_CHECK_MENU_ITEM(widget)->active)
6675                 compose->return_receipt = TRUE;
6676         else
6677                 compose->return_receipt = FALSE;
6678 }
6679
6680 void compose_headerentry_key_press_event_cb(GtkWidget *entry,
6681                                             GdkEventKey *event,
6682                                             ComposeHeaderEntry *headerentry)
6683 {
6684         if ((g_slist_length(headerentry->compose->header_list) > 0) &&
6685             ((headerentry->headernum + 1) != headerentry->compose->header_nextrow) &&
6686             !(event->state & GDK_MODIFIER_MASK) &&
6687             (event->keyval == GDK_BackSpace) &&
6688             (strlen(gtk_entry_get_text(GTK_ENTRY(entry))) == 0)) {
6689                 gtk_container_remove
6690                         (GTK_CONTAINER(headerentry->compose->header_table),
6691                          headerentry->combo);
6692                 gtk_container_remove
6693                         (GTK_CONTAINER(headerentry->compose->header_table),
6694                          headerentry->entry);
6695                 headerentry->compose->header_list =
6696                         g_slist_remove(headerentry->compose->header_list,
6697                                        headerentry);
6698                 g_free(headerentry);
6699         } else  if (event->keyval == GDK_Tab) {
6700                 if (headerentry->compose->header_last == headerentry) {
6701                         /* Override default next focus, and give it to subject_entry
6702                          * instead of notebook tabs
6703                          */
6704                         gtk_signal_emit_stop_by_name(GTK_OBJECT(entry), "key-press-event"); 
6705                         gtk_widget_grab_focus(headerentry->compose->subject_entry);
6706                 }
6707         }
6708
6709 }
6710
6711 void compose_headerentry_changed_cb(GtkWidget *entry,
6712                                     ComposeHeaderEntry *headerentry)
6713 {
6714         if (strlen(gtk_entry_get_text(GTK_ENTRY(entry))) != 0) {
6715                 headerentry->compose->header_list =
6716                         g_slist_append(headerentry->compose->header_list,
6717                                        headerentry);
6718                 compose_create_header_entry(headerentry->compose);
6719                 gtk_signal_disconnect_by_func
6720                         (GTK_OBJECT(entry),
6721                          GTK_SIGNAL_FUNC(compose_headerentry_changed_cb),
6722                          headerentry);
6723                 /* Automatically scroll down */
6724                 compose_show_first_last_header(headerentry->compose, FALSE);
6725                 
6726         }
6727 }
6728
6729 static void compose_show_first_last_header(Compose *compose, gboolean show_first)
6730 {
6731         GtkAdjustment *vadj;
6732
6733         g_return_if_fail(compose);
6734         g_return_if_fail(GTK_IS_WIDGET(compose->header_table));
6735         g_return_if_fail(GTK_IS_VIEWPORT(compose->header_table->parent));
6736
6737         vadj = gtk_viewport_get_vadjustment(GTK_VIEWPORT(compose->header_table->parent));
6738         gtk_adjustment_set_value(vadj, (show_first ? vadj->lower : vadj->upper));
6739 }
6740
6741 static void text_activated(GtkWidget *widget, Compose *compose)
6742 {
6743         compose_send_control_enter(compose);
6744 }
6745
6746 static void text_inserted(GtkWidget *widget, const gchar *text,
6747                           gint length, gint *position, Compose *compose)
6748 {
6749         GtkEditable *editable = GTK_EDITABLE(widget);
6750
6751         gtk_signal_handler_block_by_func(GTK_OBJECT(widget),
6752                                          GTK_SIGNAL_FUNC(text_inserted),
6753                                          compose);
6754         if (compose->paste_as_quotation) {
6755                 gchar *new_text;
6756                 gchar *qmark;
6757                 gint pos;
6758
6759                 new_text = g_strndup(text, length);
6760                 if (prefs_common.quotemark && *prefs_common.quotemark)
6761                         qmark = prefs_common.quotemark;
6762                 else
6763                         qmark = "> ";
6764                 gtk_stext_set_point(GTK_STEXT(widget), *position);
6765                 compose_quote_fmt(compose, NULL, "%Q", qmark, new_text);
6766                 pos = gtk_stext_get_point(GTK_STEXT(widget));
6767                 gtk_editable_set_position(editable, pos);
6768                 *position = pos;
6769                 g_free(new_text);
6770         } else
6771                 gtk_editable_insert_text(editable, text, length, position);
6772
6773         if (prefs_common.autowrap)
6774                 compose_wrap_line_all(compose);
6775
6776         gtk_signal_handler_unblock_by_func(GTK_OBJECT(widget),
6777                                            GTK_SIGNAL_FUNC(text_inserted),
6778                                            compose);
6779         gtk_signal_emit_stop_by_name(GTK_OBJECT(editable), "insert_text");
6780 }
6781
6782 static gboolean compose_send_control_enter(Compose *compose)
6783 {
6784         GdkEvent *ev;
6785         GdkEventKey *kev;
6786         GtkItemFactory *ifactory;
6787         GtkAccelEntry *accel;
6788         GtkWidget *send_menu;
6789         GSList *list;
6790         GdkModifierType ignored_mods =
6791                 (GDK_LOCK_MASK | GDK_MOD2_MASK | GDK_MOD3_MASK |
6792                  GDK_MOD4_MASK | GDK_MOD5_MASK);
6793
6794         ev = gtk_get_current_event();
6795         if (ev->type != GDK_KEY_PRESS) return FALSE;
6796
6797         kev = (GdkEventKey *)ev;
6798         if (!(kev->keyval == GDK_Return && (kev->state & GDK_CONTROL_MASK)))
6799                 return FALSE;
6800
6801         ifactory = gtk_item_factory_from_widget(compose->menubar);
6802         send_menu = gtk_item_factory_get_widget(ifactory, "/Message/Send");
6803         list = gtk_accel_group_entries_from_object(GTK_OBJECT(send_menu));
6804         accel = (GtkAccelEntry *)list->data;
6805         if (accel->accelerator_key == kev->keyval &&
6806             (accel->accelerator_mods & ~ignored_mods) ==
6807             (kev->state & ~ignored_mods)) {
6808                 compose_send_cb(compose, 0, NULL);
6809                 return TRUE;
6810         }
6811
6812         return FALSE;
6813 }
6814
6815 #if USE_PSPELL
6816 static void compose_check_all(Compose *compose)
6817 {
6818         if (compose->gtkpspell)
6819                 gtkpspell_check_all(compose->gtkpspell);
6820 }
6821
6822 static void compose_highlight_all(Compose *compose)
6823 {
6824         if (compose->gtkpspell)
6825                 gtkpspell_highlight_all(compose->gtkpspell);
6826 }
6827
6828 static void compose_check_backwards(Compose *compose)
6829 {
6830         if (compose->gtkpspell) 
6831                 gtkpspell_check_backwards(compose->gtkpspell);
6832         else {
6833                 GtkItemFactory *ifactory;
6834                 ifactory = gtk_item_factory_from_widget(compose->popupmenu);
6835                 menu_set_sensitive(ifactory, "/Edit/Check backwards misspelled word", FALSE);
6836                 menu_set_sensitive(ifactory, "/Edit/Forward to next misspelled word", FALSE);
6837         }
6838 }
6839
6840 static void compose_check_forwards_go(Compose *compose)
6841 {
6842         if (compose->gtkpspell) 
6843                 gtkpspell_check_forwards_go(compose->gtkpspell);
6844         else {
6845                 GtkItemFactory *ifactory;
6846                 ifactory = gtk_item_factory_from_widget(compose->popupmenu);
6847                 menu_set_sensitive(ifactory, "/Edit/Check backwards misspelled word", FALSE);
6848                 menu_set_sensitive(ifactory, "/Edit/Forward to next misspelled word", FALSE);
6849         }
6850 }
6851 #endif
6852
6853 static void set_toolbar_style(Compose *compose)
6854 {
6855         switch (prefs_common.toolbar_style) {
6856         case TOOLBAR_NONE:
6857                 gtk_widget_hide(compose->handlebox);
6858                 break;
6859         case TOOLBAR_ICON:
6860                 gtk_toolbar_set_style(GTK_TOOLBAR(compose->toolbar),
6861                                       GTK_TOOLBAR_ICONS);
6862                 break;
6863         case TOOLBAR_TEXT:
6864                 gtk_toolbar_set_style(GTK_TOOLBAR(compose->toolbar),
6865                                       GTK_TOOLBAR_TEXT);
6866                 break;
6867         case TOOLBAR_BOTH:
6868                 gtk_toolbar_set_style(GTK_TOOLBAR(compose->toolbar),
6869                                       GTK_TOOLBAR_BOTH);
6870                 break;
6871         }
6872         
6873         if (prefs_common.toolbar_style != TOOLBAR_NONE) {
6874                 gtk_widget_show(compose->handlebox);
6875                 gtk_widget_queue_resize(compose->handlebox);
6876         }
6877 }