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