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