2006-11-18 [paul] 2.6.0cvs55
[claws.git] / src / prefs_template.c
1 /*
2  * Sylpheed templates subsystem 
3  * Copyright (C) 2001 Alexander Barinov
4  * Copyright (C) 2001-2006 Hiroyuki Yamamoto and the Claws Mail team
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  */
20
21 #include "defs.h"
22
23 #include <glib.h>
24 #include <glib/gi18n.h>
25 #include <gtk/gtk.h>
26 #include <gdk/gdkkeysyms.h>
27 #include <string.h>
28 #include <dirent.h>
29 #include <sys/stat.h>
30
31 #include "template.h"
32 #include "main.h"
33 #include "prefs_gtk.h"
34 #include "inc.h"
35 #include "utils.h"
36 #include "gtkutils.h"
37 #include "alertpanel.h"
38 #include "manage_window.h"
39 #include "compose.h"
40 #include "addr_compl.h"
41 #include "quote_fmt.h"
42 #include "prefs_common.h"
43 #include "manual.h"
44
45 enum {
46         TEMPL_TEXT,
47         TEMPL_DATA,
48         TEMPL_AUTO_DATA,        /*!< auto pointer */
49         N_TEMPL_COLUMNS
50 };
51
52 static struct Templates {
53         GtkWidget *window;
54         GtkWidget *ok_btn;
55         GtkWidget *list_view;
56         GtkWidget *entry_name;
57         GtkWidget *entry_subject;
58         GtkWidget *entry_to;
59         GtkWidget *entry_cc;    
60         GtkWidget *entry_bcc;
61         GtkWidget *text_value;
62 } templates;
63
64 static int modified = FALSE;
65
66 /* widget creating functions */
67 static void prefs_template_window_create        (void);
68 static void prefs_template_window_setup         (void);
69 static void prefs_template_clear                (void);
70
71 static GSList *prefs_template_get_list          (void);
72
73 /* callbacks */
74 static gint prefs_template_deleted_cb           (GtkWidget      *widget,
75                                                  GdkEventAny    *event,
76                                                  gpointer        data);
77 static gboolean prefs_template_key_pressed_cb   (GtkWidget      *widget,
78                                                  GdkEventKey    *event,
79                                                  gpointer        data);
80 static void prefs_template_cancel_cb            (void);
81 static void prefs_template_ok_cb                (void);
82 static void prefs_template_register_cb          (void);
83 static void prefs_template_substitute_cb        (void);
84 static void prefs_template_delete_cb            (void);
85
86 static GtkListStore* prefs_template_create_data_store   (void);
87 static void prefs_template_list_view_insert_template    (GtkWidget *list_view,
88                                                          GtkTreeIter *row_iter,
89                                                          const gchar *template,
90                                                          Template *data,
91                                                          gboolean sorted);
92 static GtkWidget *prefs_template_list_view_create       (void);
93 static void prefs_template_create_list_view_columns     (GtkWidget *list_view);
94 static gboolean prefs_template_selected                 (GtkTreeSelection *selector,
95                                                          GtkTreeModel *model, 
96                                                          GtkTreePath *path,
97                                                          gboolean currently_selected,
98                                                          gpointer data);
99
100 /* Called from mainwindow.c */
101 void prefs_template_open(void)
102 {
103         inc_lock();
104
105         if (!templates.window)
106                 prefs_template_window_create();
107
108         prefs_template_window_setup();
109         gtk_widget_show(templates.window);
110 }
111
112 /*!
113  *\brief        Save Gtk object size to prefs dataset
114  */
115 static void prefs_template_size_allocate_cb(GtkWidget *widget,
116                                          GtkAllocation *allocation)
117 {
118         g_return_if_fail(allocation != NULL);
119
120         prefs_common.templateswin_width = allocation->width;
121         prefs_common.templateswin_height = allocation->height;
122 }
123
124 static void prefs_template_window_create(void)
125 {
126         /* window structure ;) */
127         GtkWidget *window;
128         GtkWidget   *vpaned;
129         GtkWidget     *vbox1;
130         GtkWidget       *table; /* including : entry_[name|to|cc|bcc|subject] */
131         GtkWidget       *scroll2;
132         GtkWidget         *text_value;
133         GtkWidget     *vbox2;
134         GtkWidget       *hbox2;
135         GtkWidget         *arrow1;
136         GtkWidget         *hbox3;
137         GtkWidget           *reg_btn;
138         GtkWidget           *subst_btn;
139         GtkWidget           *del_btn;
140         GtkWidget         *desc_btn;
141         GtkWidget       *scroll1;
142         GtkWidget         *list_view;
143         GtkWidget       *confirm_area;
144         GtkWidget         *help_btn;
145         GtkWidget         *cancel_btn;
146         GtkWidget         *ok_btn;
147         static GdkGeometry geometry;
148         gint i;
149         GtkTooltips *tooltips;
150
151         debug_print("Creating templates configuration window...\n");
152
153         /* main window */
154         window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
155         gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
156         gtk_window_set_modal(GTK_WINDOW(window), TRUE);
157         gtk_window_set_resizable(GTK_WINDOW(window), TRUE);
158
159         /* vpaned to separate template settings from templates list */
160         vpaned = gtk_vpaned_new();
161         gtk_widget_show(vpaned);
162         gtk_container_add(GTK_CONTAINER(window), vpaned);
163
164         /* vbox to handle template name and content */
165         vbox1 = gtk_vbox_new(FALSE, 6);
166         gtk_widget_show(vbox1);
167         gtk_container_set_border_width(GTK_CONTAINER(vbox1), 8);
168         gtk_paned_pack1(GTK_PANED(vpaned), vbox1, FALSE, FALSE);
169
170         table = gtk_table_new(5, 2, FALSE);
171         gtk_table_set_row_spacings (GTK_TABLE (table), VSPACING_NARROW_2);
172         gtk_table_set_col_spacings (GTK_TABLE (table), 4);
173         gtk_widget_show(table);
174         gtk_box_pack_start (GTK_BOX (vbox1), table, FALSE, FALSE, 0);
175
176         tooltips = gtk_tooltips_new();
177
178         struct
179         {
180                 gchar *label;
181                 GtkWidget **entry;
182                 gboolean compl;
183                 gchar *tooltips;
184         } tab[] = {
185                 {_("Name"),     &templates.entry_name,          FALSE,
186                         _("This name is used as the Menu item")},
187                 {_("To"),       &templates.entry_to,            TRUE,   NULL},
188                 {_("Cc"),       &templates.entry_cc,            TRUE,   NULL},
189                 {_("Bcc"),      &templates.entry_bcc,           TRUE,   NULL},
190                 {_("Subject"),  &templates.entry_subject,       FALSE,  NULL},
191                 {NULL,          NULL,                           FALSE,  NULL}
192         };
193
194         for (i=0; tab[i].label; i++) {
195
196                 GtkWidget *label;
197
198                 label = gtk_label_new(tab[i].label);
199                 gtk_widget_show(label);
200                 gtk_table_attach(GTK_TABLE(table), label, 0, 1, i, (i + 1),
201                                 (GtkAttachOptions) (GTK_FILL),
202                                 (GtkAttachOptions) 0, 0, 0);
203                 gtk_misc_set_alignment(GTK_MISC(label), 1, 0.5);
204
205                 *(tab[i].entry) = gtk_entry_new();
206                 gtk_widget_show(*(tab[i].entry));
207                 gtk_table_attach(GTK_TABLE(table), *(tab[i].entry), 1, 2, i, (i + 1),
208                                 (GtkAttachOptions) (GTK_EXPAND|GTK_SHRINK|GTK_FILL),
209                                 (GtkAttachOptions) 0, 0, 0);
210                 gtk_tooltips_set_tip(tooltips, *(tab[i].entry), tab[i].tooltips, NULL);
211
212                 if (tab[i].compl)
213                         address_completion_register_entry(
214                                 GTK_ENTRY(*(tab[i].entry)), TRUE);
215         }
216
217         /* template content */
218         scroll2 = gtk_scrolled_window_new(NULL, NULL);
219         gtk_widget_show(scroll2);
220         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll2),
221                                        GTK_POLICY_AUTOMATIC,
222                                        GTK_POLICY_AUTOMATIC);
223         gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll2),
224                                             GTK_SHADOW_IN);
225         gtk_box_pack_start(GTK_BOX(vbox1), scroll2, TRUE, TRUE, 0);
226
227         text_value = gtk_text_view_new();
228         gtk_widget_show(text_value);
229         gtk_widget_set_size_request(text_value, -1, 120);
230         gtk_container_add(GTK_CONTAINER(scroll2), text_value);
231         gtk_text_view_set_editable(GTK_TEXT_VIEW(text_value), TRUE);
232         gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(text_value), GTK_WRAP_WORD);
233
234         /* vbox for buttons and templates list */
235         vbox2 = gtk_vbox_new(FALSE, 6);
236         gtk_widget_show(vbox2);
237         gtk_container_set_border_width(GTK_CONTAINER(vbox2), 8);
238         gtk_paned_pack2(GTK_PANED(vpaned), vbox2, TRUE, FALSE);
239
240         /* register | substitute | delete */
241         hbox2 = gtk_hbox_new(FALSE, 4);
242         gtk_widget_show(hbox2);
243         gtk_box_pack_start(GTK_BOX(vbox2), hbox2, FALSE, FALSE, 0);
244
245         arrow1 = gtk_arrow_new(GTK_ARROW_DOWN, GTK_SHADOW_OUT);
246         gtk_widget_show(arrow1);
247         gtk_box_pack_start(GTK_BOX(hbox2), arrow1, FALSE, FALSE, 0);
248         gtk_widget_set_size_request(arrow1, -1, 16);
249
250         hbox3 = gtk_hbox_new(TRUE, 4);
251         gtk_widget_show(hbox3);
252         gtk_box_pack_start(GTK_BOX(hbox2), hbox3, FALSE, FALSE, 0);
253
254         reg_btn = gtk_button_new_from_stock(GTK_STOCK_ADD);
255         gtk_widget_show(reg_btn);
256         gtk_box_pack_start(GTK_BOX(hbox3), reg_btn, FALSE, TRUE, 0);
257         g_signal_connect(G_OBJECT (reg_btn), "clicked",
258                          G_CALLBACK (prefs_template_register_cb), NULL);
259
260         subst_btn = gtkut_get_replace_btn(_("Replace"));
261         gtk_widget_show(subst_btn);
262         gtk_box_pack_start(GTK_BOX(hbox3), subst_btn, FALSE, TRUE, 0);
263         g_signal_connect(G_OBJECT(subst_btn), "clicked",
264                          G_CALLBACK(prefs_template_substitute_cb),
265                          NULL);
266
267         del_btn = gtk_button_new_from_stock(GTK_STOCK_DELETE);
268         gtk_widget_show(del_btn);
269         gtk_box_pack_start(GTK_BOX(hbox3), del_btn, FALSE, TRUE, 0);
270         g_signal_connect(G_OBJECT(del_btn), "clicked",
271                          G_CALLBACK(prefs_template_delete_cb), NULL);
272
273 #if GTK_CHECK_VERSION(2, 8, 0)
274         desc_btn = gtk_button_new_from_stock(GTK_STOCK_INFO);
275 #else
276         desc_btn = gtk_button_new_with_label(_(" Symbols... "));
277 #endif
278         gtk_widget_show(desc_btn);
279         gtk_box_pack_end(GTK_BOX(hbox2), desc_btn, FALSE, FALSE, 0);
280         g_signal_connect(G_OBJECT(desc_btn), "clicked",
281                          G_CALLBACK(quote_fmt_quote_description), NULL);
282
283         /* templates list */
284         scroll1 = gtk_scrolled_window_new(NULL, NULL);
285         gtk_widget_show(scroll1);
286         gtk_box_pack_start(GTK_BOX(vbox2), scroll1, TRUE, TRUE, 0);
287         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll1),
288                                        GTK_POLICY_AUTOMATIC,
289                                        GTK_POLICY_AUTOMATIC);
290                                        
291         list_view = prefs_template_list_view_create();
292         gtk_widget_show(list_view);
293         gtk_widget_set_size_request(scroll1, -1, 140);
294         gtk_container_add(GTK_CONTAINER(scroll1), list_view);
295
296         /* help | cancel | ok */
297         gtkut_stock_button_set_create_with_help(&confirm_area, &help_btn,
298                         &cancel_btn, GTK_STOCK_CANCEL,
299                         &ok_btn, GTK_STOCK_OK,
300                         NULL, NULL);
301         gtk_widget_show(confirm_area);
302         gtk_box_pack_end(GTK_BOX(vbox2), confirm_area, FALSE, FALSE, 0);
303         gtk_widget_grab_default(ok_btn);
304
305         gtk_window_set_title(GTK_WINDOW(window), _("Template configuration"));
306
307         g_signal_connect(G_OBJECT(window), "delete_event",
308                          G_CALLBACK(prefs_template_deleted_cb), NULL);
309         g_signal_connect(G_OBJECT(window), "size_allocate",
310                          G_CALLBACK(prefs_template_size_allocate_cb), NULL);
311         g_signal_connect(G_OBJECT(window), "key_press_event",
312                          G_CALLBACK(prefs_template_key_pressed_cb), NULL);
313         MANAGE_WINDOW_SIGNALS_CONNECT(window);
314         g_signal_connect(G_OBJECT(ok_btn), "clicked",
315                          G_CALLBACK(prefs_template_ok_cb), NULL);
316         g_signal_connect(G_OBJECT(cancel_btn), "clicked",
317                          G_CALLBACK(prefs_template_cancel_cb), NULL);
318         g_signal_connect(G_OBJECT(help_btn), "clicked",
319                          G_CALLBACK(manual_open_with_anchor_cb),
320                          MANUAL_ANCHOR_TEMPLATES);
321
322         address_completion_start(window);
323
324         if (!geometry.min_height) {
325                 geometry.min_width = 440;
326                 geometry.min_height = 500;
327         }
328
329         gtk_window_set_geometry_hints(GTK_WINDOW(window), NULL, &geometry,
330                                       GDK_HINT_MIN_SIZE);
331         gtk_widget_set_size_request(window, prefs_common.templateswin_width,
332                                     prefs_common.templateswin_height);
333
334         templates.window = window;
335         templates.ok_btn = ok_btn;
336         templates.list_view = list_view;
337         templates.text_value = text_value;
338 }
339
340 static void prefs_template_window_setup(void)
341 {
342         GSList *tmpl_list;
343         GSList *cur;
344         Template *tmpl;
345         GtkListStore *store;
346         GtkTextBuffer *buffer;
347         
348         store = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW
349                                 (templates.list_view)));
350
351         manage_window_set_transient(GTK_WINDOW(templates.window));
352         gtk_widget_grab_focus(templates.ok_btn);
353
354         gtk_list_store_clear(store);
355
356         prefs_template_list_view_insert_template(templates.list_view,
357                                                  NULL, _("(New)"),
358                                                  NULL, FALSE);
359         
360         tmpl_list = template_read_config();
361
362         for (cur = tmpl_list; cur != NULL; cur = cur->next) {
363                 tmpl = (Template *)cur->data;
364                 prefs_template_list_view_insert_template(templates.list_view,
365                                                          NULL, tmpl->name, 
366                                                          tmpl, FALSE);
367         }
368
369         gtk_entry_set_text(GTK_ENTRY(templates.entry_name), "");
370         gtk_entry_set_text(GTK_ENTRY(templates.entry_to), "");
371         gtk_entry_set_text(GTK_ENTRY(templates.entry_cc), "");
372         gtk_entry_set_text(GTK_ENTRY(templates.entry_bcc), "");                 
373         gtk_entry_set_text(GTK_ENTRY(templates.entry_subject), "");
374         
375         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(templates.text_value));
376         gtk_text_buffer_set_text(buffer, "", -1);
377
378         g_slist_free(tmpl_list);
379 }
380
381 static void prefs_template_clear(void)
382 {
383         GtkListStore *store;
384
385         store = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW
386                                 (templates.list_view)));
387         gtk_list_store_clear(store);
388 }
389
390 static gint prefs_template_deleted_cb(GtkWidget *widget, GdkEventAny *event,
391                                       gpointer data)
392 {
393         prefs_template_cancel_cb();
394         return TRUE;
395 }
396
397 static gboolean prefs_template_key_pressed_cb(GtkWidget *widget,
398                                               GdkEventKey *event, gpointer data)
399 {
400         if (event && event->keyval == GDK_Escape)
401                 prefs_template_cancel_cb();
402         else {
403                 GtkWidget *focused = gtkut_get_focused_child(
404                                         GTK_CONTAINER(widget));
405                 if (focused && GTK_IS_EDITABLE(focused)) {
406                         modified = TRUE;
407                 }
408         }
409         return FALSE;
410 }
411
412 static void prefs_template_ok_cb(void)
413 {
414         GSList *tmpl_list;
415
416         if (modified && alertpanel(_("Entry not saved"),
417                                  _("The entry was not saved. Close anyway?"),
418                                  GTK_STOCK_CLOSE, _("+_Continue editing"), 
419                                  NULL) != G_ALERTDEFAULT) {
420                 return;
421         }
422         modified = FALSE;
423         tmpl_list = prefs_template_get_list();
424         template_set_config(tmpl_list);
425         compose_reflect_prefs_all();
426         prefs_template_clear();
427         gtk_widget_hide(templates.window);
428         inc_unlock();
429 }
430
431 static void prefs_template_cancel_cb(void)
432 {
433         if (modified && alertpanel(_("Entry not saved"),
434                                  _("The entry was not saved. Close anyway?"),
435                                  GTK_STOCK_CLOSE, _("+_Continue editing"),
436                                  NULL) != G_ALERTDEFAULT) {
437                 return;
438         }
439         modified = FALSE;
440         prefs_template_clear();
441         gtk_widget_hide(templates.window);
442         inc_unlock();
443 }
444
445 /*!
446  *\brief        Request list for storage. New list is owned
447  *              by template.c...
448  */
449 static GSList *prefs_template_get_list(void)
450 {
451         GSList *tmpl_list = NULL;
452         Template *tmpl;
453         GtkTreeModel *model;
454         GtkTreeIter iter;
455
456         model = gtk_tree_view_get_model(GTK_TREE_VIEW(templates.list_view));
457         if (!gtk_tree_model_get_iter_first(model, &iter))
458                 return NULL;
459
460         do {
461                 gtk_tree_model_get(model, &iter,
462                                    TEMPL_DATA, &tmpl,
463                                    -1);
464                 
465                 if (tmpl) {
466                         Template *ntmpl;
467                         
468                         ntmpl = g_new(Template, 1);
469                         ntmpl->name    = tmpl->name && *(tmpl->name) 
470                                          ? g_strdup(tmpl->name) 
471                                          : NULL;
472                         ntmpl->subject = tmpl->subject && *(tmpl->subject) 
473                                          ? g_strdup(tmpl->subject) 
474                                          : NULL;
475                         ntmpl->to      = tmpl->to && *(tmpl->to)
476                                          ? g_strdup(tmpl->to)
477                                          : NULL;
478                         ntmpl->cc      = tmpl->cc && *(tmpl->cc)
479                                          ? g_strdup(tmpl->cc)
480                                          : NULL;
481                         ntmpl->bcc     = tmpl->bcc && *(tmpl->bcc)
482                                          ? g_strdup(tmpl->bcc)
483                                          : NULL;        
484                         ntmpl->value   = tmpl->value && *(tmpl->value)
485                                          ? g_strdup(tmpl->value)
486                                          : NULL;
487                         tmpl_list = g_slist_append(tmpl_list, ntmpl);
488                 }                       
489         
490         } while (gtk_tree_model_iter_next(model, &iter)); 
491
492         return tmpl_list;
493 }
494
495 gboolean prefs_template_string_is_valid(gchar *string)
496 {
497         if (string && *string != '\0') {
498                 gchar *parsed_buf;
499                 MsgInfo dummyinfo;
500
501                 memset(&dummyinfo, 0, sizeof(MsgInfo));
502                 quote_fmt_init(&dummyinfo, NULL, NULL, TRUE, NULL);
503                 quote_fmt_scan_string(string);
504                 quote_fmt_parse();
505                 parsed_buf = quote_fmt_get_buffer();
506                 if (!parsed_buf)
507                         return FALSE;
508                 quote_fmt_reset_vartable();
509         }
510         return TRUE;
511 }
512
513 static gboolean prefs_template_list_view_set_row(GtkTreeIter *row)
514 /* return TRUE if the row could be modified */
515 {
516         Template *tmpl;
517         gchar *name;
518         gchar *subject;
519         gchar *to;
520         gchar *cc;
521         gchar *bcc;     
522         gchar *value;
523         GtkTextBuffer *buffer;
524         GtkTextIter start, end;
525         GtkTreeModel *model;
526
527         model = gtk_tree_view_get_model(GTK_TREE_VIEW(templates.list_view));
528
529         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(templates.text_value));
530         gtk_text_buffer_get_start_iter(buffer, &start);
531         gtk_text_buffer_get_iter_at_offset(buffer, &end, -1);
532         value = gtk_text_buffer_get_text(buffer, &start, &end, FALSE);
533
534         if (value && *value == '\0') {
535                         g_free(value);
536                 value = NULL;
537                 }
538         if (!prefs_template_string_is_valid(value)) {
539                 alertpanel_error(_("Template body format error."));     
540                 g_free(value);
541                 return FALSE;
542         }
543
544         name = gtk_editable_get_chars(GTK_EDITABLE(templates.entry_name),
545                                       0, -1);
546         if (*name == '\0') {
547                 alertpanel_error(_("Template name is not set."));
548                 return FALSE;
549         }
550         to = gtk_editable_get_chars(GTK_EDITABLE(templates.entry_to),
551                                     0, -1);
552         cc = gtk_editable_get_chars(GTK_EDITABLE(templates.entry_cc),
553                                     0, -1);
554         bcc = gtk_editable_get_chars(GTK_EDITABLE(templates.entry_bcc),
555                                     0, -1);
556         subject = gtk_editable_get_chars(GTK_EDITABLE(templates.entry_subject),
557                                          0, -1);
558
559         if (to && *to == '\0') {
560                 g_free(to);
561                 to = NULL;
562         }
563         if (cc && *cc == '\0') {
564                 g_free(cc);
565                 cc = NULL;
566         }
567         if (bcc && *bcc == '\0') {
568                 g_free(bcc);
569                 bcc = NULL;
570         }
571         if (subject && *subject == '\0') {
572                 g_free(subject);
573                 subject = NULL;
574         }
575
576         if (!prefs_template_string_is_valid(to)) {
577                 alertpanel_error(_("Template To format error."));
578                 g_free(to);
579                 return FALSE;
580         }
581         if (!prefs_template_string_is_valid(cc)) {
582                 alertpanel_error(_("Template Cc format error."));       
583                 g_free(cc);
584                 return FALSE;
585         }
586         if (!prefs_template_string_is_valid(bcc)) {
587                 alertpanel_error(_("Template Bcc format error."));      
588                 g_free(bcc);
589                 return FALSE;
590         }
591         if (!prefs_template_string_is_valid(subject)) {
592                 alertpanel_error(_("Template subject format error."));  
593                 g_free(subject);
594                 return FALSE;
595         }
596         
597         tmpl = g_new(Template, 1);
598         tmpl->name = name;
599         tmpl->subject = subject;
600         tmpl->to = to;
601         tmpl->cc = cc;
602         tmpl->bcc = bcc;        
603         tmpl->value = value;
604
605         prefs_template_list_view_insert_template(templates.list_view,
606                                                  row, tmpl->name, tmpl, TRUE);
607         return TRUE;
608 }
609
610 static void prefs_template_register_cb(void)
611 {
612         modified = !prefs_template_list_view_set_row(NULL);
613 }
614
615 static void prefs_template_substitute_cb(void)
616 {
617         Template *tmpl;
618         GtkTreeIter row;
619         GtkTreeSelection *selection;
620         GtkTreeModel *model;
621
622         selection = gtk_tree_view_get_selection
623                         (GTK_TREE_VIEW(templates.list_view));
624         
625         if (!gtk_tree_selection_get_selected(selection, &model, &row))
626                 return;
627
628         gtk_tree_model_get(model, &row, 
629                            TEMPL_DATA, &tmpl,
630                            -1);
631
632         if (!tmpl) return;
633
634         modified = !prefs_template_list_view_set_row(&row);
635 }
636
637 static void prefs_template_delete_cb(void)
638 {
639         Template *tmpl;
640         GtkTreeIter row;
641         GtkTreeSelection *selection;
642         GtkTreeModel *model;
643
644         selection = gtk_tree_view_get_selection
645                         (GTK_TREE_VIEW(templates.list_view));
646         
647         if (!gtk_tree_selection_get_selected(selection, &model, &row))
648                 return;
649
650         gtk_tree_model_get(model, &row, 
651                            TEMPL_DATA, &tmpl,
652                            -1);
653
654         if (!tmpl) 
655                 return;
656
657         if (alertpanel(_("Delete template"),
658                        _("Do you really want to delete this template?"),
659                        GTK_STOCK_CANCEL, GTK_STOCK_DELETE,
660                        NULL) != G_ALERTALTERNATE)
661                 return;
662
663         gtk_list_store_remove(GTK_LIST_STORE(model), &row);             
664 }
665
666 static GtkListStore* prefs_template_create_data_store(void)
667 {
668         return gtk_list_store_new(N_TEMPL_COLUMNS,
669                                   G_TYPE_STRING,        
670                                   G_TYPE_POINTER,
671                                   G_TYPE_AUTO_POINTER,
672                                   -1);
673 }
674
675 static gboolean prefs_template_list_view_find_insertion_point(GtkTreeModel* model,
676                                                         const gchar* template,
677                                                         GtkTreeIter* iter)
678 {
679         GtkTreeIter i;
680         gchar *text = NULL;
681
682         if ((gtk_tree_model_get_iter_first(model, &i))) {
683                 for ( ; gtk_tree_model_iter_next(model, &i); ) {
684                         gtk_tree_model_get(model, &i, TEMPL_TEXT, &text, -1);
685                         if (strcmp(text, template) >= 0) {
686                                 g_free(text);
687                                 *iter = i;
688                                 return TRUE;
689                         }
690                         g_free(text);
691                 }
692         }
693         /* cannot add before (need to append) */
694         return FALSE;
695 }
696
697 static void prefs_template_list_view_insert_template(GtkWidget *list_view,
698                                                      GtkTreeIter *row_iter,
699                                                      const gchar *template,
700                                                      Template *data,
701                                                          gboolean sorted)
702 {
703         GtkTreeIter iter;
704         GtkTreeModel *model = gtk_tree_view_get_model
705                                         (GTK_TREE_VIEW(list_view));
706         GtkListStore *list_store = GTK_LIST_STORE(model);
707         GAuto *auto_data;                                       
708
709         if (row_iter == NULL) {
710                 if (sorted) {
711                         GtkTreeIter insertion_point;
712
713                         /* insert sorted */
714                         if (prefs_template_list_view_find_insertion_point(model,
715                                         template, &insertion_point)) {
716                                 gtk_list_store_insert_before(list_store, &iter,
717                                                 &insertion_point);
718                         } else {
719                                 gtk_list_store_append(list_store, &iter);
720                         }
721                 } else {
722                         /* append new */
723                         gtk_list_store_append(list_store, &iter);
724                 }
725         } else {
726                 /* modify the existing */
727                 iter = *row_iter;
728
729                 if (sorted) {
730                         GtkTreeIter insertion_point;
731                         gchar *text = NULL;
732
733                         /* force re-sorting if template's name changed */
734                         gtk_tree_model_get(model, row_iter, TEMPL_TEXT, &text, -1);
735                         if (strcmp(text, template) != 0) {
736
737                                 /* move the modified template */
738                                 if (prefs_template_list_view_find_insertion_point(model,
739                                                 template, &insertion_point)) {
740                                         gtk_list_store_move_before(list_store, row_iter,
741                                                         &insertion_point);
742                                 } else {
743                                         /* move to the end */
744                                         gtk_list_store_move_before(list_store, row_iter,
745                                                         NULL);
746                                 }
747                         }
748                         g_free(text);
749                 }
750         }
751                 
752         auto_data = g_auto_pointer_new_with_free(data, (GFreeFunc) template_free);  
753
754         /* if replacing data in an existing row, the auto pointer takes care
755          * of destroying the Template data */
756         gtk_list_store_set(list_store, &iter,
757                            TEMPL_TEXT, template,
758                            TEMPL_DATA, data,
759                            TEMPL_AUTO_DATA, auto_data,
760                            -1);
761
762         g_auto_pointer_free(auto_data);                    
763 }
764
765 static GtkWidget *prefs_template_list_view_create(void)
766 {
767         GtkTreeView *list_view;
768         GtkTreeSelection *selector;
769         GtkTreeModel *model;
770
771         model = GTK_TREE_MODEL(prefs_template_create_data_store());
772         list_view = GTK_TREE_VIEW(gtk_tree_view_new_with_model(model));
773         g_object_unref(model);  
774         
775         gtk_tree_view_set_rules_hint(list_view, prefs_common.use_stripes_everywhere);
776         
777         selector = gtk_tree_view_get_selection(list_view);
778         gtk_tree_selection_set_mode(selector, GTK_SELECTION_BROWSE);
779         gtk_tree_selection_set_select_function(selector, prefs_template_selected,
780                                                NULL, NULL);
781
782         /* create the columns */
783         prefs_template_create_list_view_columns(GTK_WIDGET(list_view));
784
785         return GTK_WIDGET(list_view);
786 }
787
788 static void prefs_template_create_list_view_columns(GtkWidget *list_view)
789 {
790         GtkTreeViewColumn *column;
791         GtkCellRenderer *renderer;
792
793         renderer = gtk_cell_renderer_text_new();
794         column = gtk_tree_view_column_new_with_attributes
795                         (_("Current templates"),
796                          renderer,
797                          "text", TEMPL_TEXT,
798                          NULL);
799         gtk_tree_view_append_column(GTK_TREE_VIEW(list_view), column);          
800 }
801
802 static gboolean prefs_template_selected(GtkTreeSelection *selector,
803                                         GtkTreeModel *model, 
804                                         GtkTreePath *path,
805                                         gboolean currently_selected,
806                                         gpointer data)
807 {
808         Template *tmpl;
809         Template tmpl_def;
810         GtkTextBuffer *buffer;
811         GtkTextIter iter;
812         GtkTreeIter titer;
813
814         if (currently_selected)
815                 return TRUE;
816
817         if (!gtk_tree_model_get_iter(model, &titer, path))
818                 return TRUE;
819
820         tmpl_def.name = _("Template");
821         tmpl_def.subject = "";
822         tmpl_def.to = "";
823         tmpl_def.cc = "";
824         tmpl_def.bcc = "";      
825         tmpl_def.value = "";
826
827         gtk_tree_model_get(model, &titer,
828                            TEMPL_DATA, &tmpl,
829                            -1);
830
831         if (!tmpl) 
832                 tmpl = &tmpl_def;
833
834         gtk_entry_set_text(GTK_ENTRY(templates.entry_name), tmpl->name);
835         gtk_entry_set_text(GTK_ENTRY(templates.entry_to),
836                            tmpl->to ? tmpl->to : "");
837         gtk_entry_set_text(GTK_ENTRY(templates.entry_cc),
838                            tmpl->cc ? tmpl->cc : "");
839         gtk_entry_set_text(GTK_ENTRY(templates.entry_bcc),
840                            tmpl->bcc ? tmpl->bcc : "");                 
841         gtk_entry_set_text(GTK_ENTRY(templates.entry_subject),
842                            tmpl->subject ? tmpl->subject : "");
843         
844         buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(templates.text_value));
845         gtk_text_buffer_set_text(buffer, "", -1);
846         gtk_text_buffer_get_start_iter(buffer, &iter);
847         gtk_text_buffer_insert(buffer, &iter, tmpl->value, -1);
848
849         return TRUE;
850 }