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