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