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