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