updates.
[silc.git] / apps / irssi / src / fe-common / core / themes.c
1 /*
2  themes.c : irssi
3
4     Copyright (C) 1999-2000 Timo Sirainen
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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19 */
20
21 #include "module.h"
22 #include "module-formats.h"
23 #include "signals.h"
24 #include "commands.h"
25 #include "levels.h"
26 #include "misc.h"
27 #include "special-vars.h"
28 #include "lib-config/iconfig.h"
29 #include "settings.h"
30
31 #include "themes.h"
32 #include "printtext.h"
33
34 #include "default-theme.h"
35
36 GSList *themes;
37 THEME_REC *current_theme;
38 GHashTable *default_formats;
39
40 static int init_finished;
41 static char *init_errors;
42
43 static int theme_read(THEME_REC *theme, const char *path, const char *data);
44
45 THEME_REC *theme_create(const char *path, const char *name)
46 {
47         THEME_REC *rec;
48
49         g_return_val_if_fail(path != NULL, NULL);
50         g_return_val_if_fail(name != NULL, NULL);
51
52         rec = g_new0(THEME_REC, 1);
53         rec->path = g_strdup(path);
54         rec->name = g_strdup(name);
55         rec->abstracts = g_hash_table_new((GHashFunc) g_str_hash,
56                                           (GCompareFunc) g_str_equal);
57         rec->modules = g_hash_table_new((GHashFunc) g_istr_hash,
58                                         (GCompareFunc) g_istr_equal);
59         themes = g_slist_append(themes, rec);
60         signal_emit("theme created", 1, rec);
61
62         return rec;
63 }
64
65 static void theme_abstract_destroy(char *key, char *value)
66 {
67         g_free(key);
68         g_free(value);
69 }
70
71 static void theme_module_destroy(const char *key, MODULE_THEME_REC *rec)
72 {
73         int n;
74
75         for (n = 0; n < rec->count; n++) {
76                 g_free_not_null(rec->formats[n]);
77                 g_free_not_null(rec->expanded_formats[n]);
78         }
79         g_free(rec->formats);
80         g_free(rec->expanded_formats);
81
82         g_free(rec->name);
83         g_free(rec);
84 }
85
86 void theme_destroy(THEME_REC *rec)
87 {
88         themes = g_slist_remove(themes, rec);
89
90         signal_emit("theme destroyed", 1, rec);
91
92         g_hash_table_foreach(rec->abstracts, (GHFunc) theme_abstract_destroy, NULL);
93         g_hash_table_destroy(rec->abstracts);
94         g_hash_table_foreach(rec->modules, (GHFunc) theme_module_destroy, NULL);
95         g_hash_table_destroy(rec->modules);
96
97         g_slist_foreach(rec->replace_values, (GFunc) g_free, NULL);
98         g_slist_free(rec->replace_values);
99
100         g_free(rec->path);
101         g_free(rec->name);
102         g_free(rec);
103 }
104
105 static char *theme_replace_expand(THEME_REC *theme, int index,
106                                   char default_fg, char default_bg,
107                                   char *last_fg, char *last_bg,
108                                   char chr, int flags)
109 {
110         GSList *rec;
111         char *ret, *abstract, data[2];
112
113         rec = g_slist_nth(theme->replace_values, index);
114         g_return_val_if_fail(rec != NULL, NULL);
115
116         data[0] = chr; data[1] = '\0';
117
118         abstract = rec->data;
119         abstract = theme_format_expand_data(theme, (const char **) &abstract,
120                                             default_fg, default_bg,
121                                             last_fg, last_bg, flags);
122         ret = parse_special_string(abstract, NULL, NULL, data, NULL,
123                                    PARSE_FLAG_ONLY_ARGS);
124         g_free(abstract);
125         return ret;
126 }
127
128 static const char *fgcolorformats = "nkrgybmpcwKRGYBMPCW";
129 static const char *bgcolorformats = "n01234567";
130
131 #define IS_FGCOLOR_FORMAT(c) \
132         ((c) != '\0' && strchr(fgcolorformats, c) != NULL)
133 #define IS_BGCOLOR_FORMAT(c) \
134         ((c) != '\0' && strchr(bgcolorformats, c) != NULL)
135
136 /* append "variable" part in $variable, ie. not the contents of the variable */
137 static void theme_format_append_variable(GString *str, const char **format)
138 {
139         const char *orig;
140         char *value, *args[1] = { NULL };
141         int free_ret;
142
143         orig = *format;
144         (*format)++;
145
146         value = parse_special((char **) format, NULL, NULL,
147                               args, &free_ret, NULL, PARSE_FLAG_ONLY_ARGS);
148         if (free_ret) g_free(value);
149
150         if (**format != '\0')
151                 (*format)++;
152
153         /* append the variable name */
154         value = g_strndup(orig, (int) (*format-orig));
155         g_string_append(str, value);
156         g_free(value);
157 }
158
159 /* append next "item", either a character, $variable or %format */
160 static void theme_format_append_next(THEME_REC *theme, GString *str,
161                                      const char **format,
162                                      char default_fg, char default_bg,
163                                      char *last_fg, char *last_bg,
164                                      int flags)
165 {
166         int index;
167         unsigned char chr;
168
169         chr = **format;
170         if ((chr == '$' || chr == '%') &&
171             (*format)[1] == '\0') {
172                 /* last char, always append */
173                 g_string_append_c(str, chr);
174                 (*format)++;
175                 return;
176         }
177
178         if (chr == '$') {
179                 /* $variable .. we'll always need to skip this, since it
180                    may contain characters that are in replace chars. */
181                 theme_format_append_variable(str, format);
182                 return;
183         }
184
185         if (**format == '%') {
186                 /* format */
187                 (*format)++;
188                 if (**format != '{' && **format != '}') {
189                         chr = **format;
190                         if (**format == 'n') {
191                                 /* %n = change to default color */
192                                 g_string_append(str, "%n");
193
194                                 if (default_bg != 'n') {
195                                         g_string_append_c(str, '%');
196                                         g_string_append_c(str, default_bg);
197                                 }
198                                 if (default_fg != 'n') {
199                                         g_string_append_c(str, '%');
200                                         g_string_append_c(str, default_fg);
201                                 }
202
203                                 *last_fg = default_fg;
204                                 *last_bg = default_bg;
205                         } else {
206                                 if (IS_FGCOLOR_FORMAT(chr))
207                                         *last_fg = chr;
208                                 if (IS_BGCOLOR_FORMAT(chr))
209                                         *last_bg = chr;
210                                 g_string_append_c(str, '%');
211                                 g_string_append_c(str, chr);
212                         }
213                         (*format)++;
214                         return;
215                 }
216
217                 /* %{ or %} gives us { or } char - keep the % char
218                    though to make sure {} isn't treated as abstract */
219                 g_string_append_c(str, '%');
220                 chr = **format;
221         }
222
223         index = (flags & EXPAND_FLAG_IGNORE_REPLACES) ? -1 :
224                 theme->replace_keys[(int) chr];
225         if (index == -1)
226                 g_string_append_c(str, chr);
227         else {
228                 char *value;
229
230                 value = theme_replace_expand(theme, index,
231                                              default_fg, default_bg,
232                                              last_fg, last_bg, chr, flags);
233                 g_string_append(str, value);
234                 g_free(value);
235         }
236
237         (*format)++;
238 }
239
240 /* returns TRUE if data is empty, or the data is a $variable which is empty */
241 static int data_is_empty(const char **data)
242 {
243         /* since we don't know the real argument list, assume there's always
244            an argument in them */
245         char *arglist[] = {
246                 "x", "x", "x", "x", "x", "x","x", "x", "x", "x",
247                 NULL
248         };
249         const char *p;
250         char *ret;
251         int free_ret, empty;
252
253         p = *data;
254         while (*p == ' ') p++;
255
256         if (*p == '}') {
257                 /* empty */
258                 *data = p+1;
259                 return TRUE;
260         }
261
262         if (*p != '$') {
263                 /* not empty */
264                 return FALSE;
265         }
266
267         /* variable - check if it's empty */
268         p++;
269         ret = parse_special((char **) &p,
270                             active_win == NULL ? NULL : active_win->active_server,
271                             active_win == NULL ? NULL : active_win->active,
272                             arglist, &free_ret, NULL, 0);
273         p++;
274
275         while (*p == ' ') p++;
276         empty = *p == '}' && (ret == NULL || *ret == '\0');
277         if (free_ret) g_free(ret);
278
279         if (empty) {
280                 /* empty */
281                 *data = p+1;
282                 return TRUE;
283         }
284
285         return FALSE;
286 }
287
288 /* expand a single {abstract ...data... } */
289 static char *theme_format_expand_abstract(THEME_REC *theme,
290                                           const char **formatp,
291                                           char default_fg, char default_bg,
292                                           int flags)
293 {
294         const char *p, *format;
295         char *abstract, *data, *ret;
296         int len;
297
298         format = *formatp;
299
300         /* get abstract name first */
301         p = format;
302         while (*p != '\0' && *p != ' ' &&
303                *p != '{' && *p != '}') p++;
304         if (*p == '\0' || p == format)
305                 return NULL; /* error */
306
307         len = (int) (p-format);
308         abstract = g_strndup(format, len);
309
310         /* skip the following space, if there's any more spaces they're
311            treated as arguments */
312         if (*p == ' ') {
313                 len++;
314                 if ((flags & EXPAND_FLAG_IGNORE_EMPTY) && data_is_empty(&p)) {
315                         *formatp = p;
316                         g_free(abstract);
317                         return NULL;
318                 }
319         }
320         *formatp = format+len;
321
322         /* get the abstract data */
323         data = g_hash_table_lookup(theme->abstracts, abstract);
324         g_free(abstract);
325         if (data == NULL) {
326                 /* unknown abstract, just display the data */
327                 data = "$0-";
328         }
329         abstract = g_strdup(data);
330
331         /* we'll need to get the data part. it may contain
332            more abstracts, they are automatically expanded. */
333         data = theme_format_expand_data(theme, formatp, default_fg, default_bg,
334                                         NULL, NULL, flags);
335         len = strlen(data);
336
337         if (len > 1 && i_isdigit(data[len-1]) && data[len-2] == '$') {
338                 /* ends with $<digit> .. this breaks things if next
339                    character is digit or '-' */
340                 char digit, *tmp;
341
342                 tmp = data;
343                 digit = tmp[len-1];
344                 tmp[len-1] = '\0';
345
346                 data = g_strdup_printf("%s{%c}", tmp, digit);
347                 g_free(tmp);
348         }
349
350         ret = parse_special_string(abstract, NULL, NULL, data, NULL,
351                                    PARSE_FLAG_ONLY_ARGS);
352         g_free(abstract);
353         g_free(data);
354         abstract = ret;
355
356         /* abstract may itself contain abstracts or replaces */
357         p = abstract;
358         ret = theme_format_expand_data(theme, &p, default_fg, default_bg,
359                                        &default_fg, &default_bg,
360                                        flags | EXPAND_FLAG_LASTCOLOR_ARG);
361         g_free(abstract);
362         return ret;
363 }
364
365 /* expand the data part in {abstract data} */
366 char *theme_format_expand_data(THEME_REC *theme, const char **format,
367                                char default_fg, char default_bg,
368                                char *save_last_fg, char *save_last_bg,
369                                int flags)
370 {
371         GString *str;
372         char *ret, *abstract;
373         char last_fg, last_bg;
374         int recurse_flags;
375
376         last_fg = default_fg;
377         last_bg = default_bg;
378         recurse_flags = flags & EXPAND_FLAG_RECURSIVE_MASK;
379
380         str = g_string_new(NULL);
381         while (**format != '\0') {
382                 if ((flags & EXPAND_FLAG_ROOT) == 0 && **format == '}') {
383                         /* ignore } if we're expanding original string */
384                         (*format)++;
385                         break;
386                 }
387
388                 if (**format != '{') {
389                         if ((flags & EXPAND_FLAG_LASTCOLOR_ARG) &&
390                             **format == '$' && (*format)[1] == '0') {
391                                 /* save the color before $0 ..
392                                    this is for the %n replacing */
393                                 if (save_last_fg != NULL) {
394                                         *save_last_fg = last_fg;
395                                         save_last_fg = NULL;
396                                 }
397                                 if (save_last_bg != NULL) {
398                                         *save_last_bg = last_bg;
399                                         save_last_bg = NULL;
400                                 }
401                         }
402
403                         theme_format_append_next(theme, str, format,
404                                                  default_fg, default_bg,
405                                                  &last_fg, &last_bg,
406                                                  recurse_flags);
407                         continue;
408                 }
409
410                 (*format)++;
411                 if (**format == '\0' || **format == '}')
412                         break; /* error */
413
414                 /* get a single {...} */
415                 abstract = theme_format_expand_abstract(theme, format,
416                                                         last_fg, last_bg,
417                                                         recurse_flags);
418                 if (abstract != NULL) {
419                         g_string_append(str, abstract);
420                         g_free(abstract);
421                 }
422         }
423
424         if ((flags & EXPAND_FLAG_LASTCOLOR_ARG) == 0) {
425                 /* save the last color */
426                 if (save_last_fg != NULL)
427                         *save_last_fg = last_fg;
428                 if (save_last_bg != NULL)
429                         *save_last_bg = last_bg;
430         }
431
432         ret = str->str;
433         g_string_free(str, FALSE);
434         return ret;
435 }
436
437 #define IS_OLD_FORMAT(code, last_fg, last_bg) \
438         (((code) == 'n' && (last_fg) == 'n' && (last_bg) == 'n') || \
439         ((code) != 'n' && ((code) == (last_fg) || (code) == (last_bg))))
440
441 static char *theme_format_compress_colors(THEME_REC *theme, const char *format)
442 {
443         GString *str;
444         char *ret, last_fg, last_bg;
445
446         str = g_string_new(NULL);
447
448         last_fg = last_bg = '\0';
449         while (*format != '\0') {
450                 if (*format == '$') {
451                         /* $variable, skrip it entirely */
452                         theme_format_append_variable(str, &format);
453                         last_fg = last_bg = '\0';
454                 } else if (*format != '%') {
455                         /* a normal character */
456                         g_string_append_c(str, *format);
457                         format++;
458                 } else {
459                         /* %format */
460                         format++;
461                         if (IS_OLD_FORMAT(*format, last_fg, last_bg)) {
462                                 /* active color set again */
463                         } else if (IS_FGCOLOR_FORMAT(*format) &&
464                                    format[1] == '%' &&
465                                    IS_FGCOLOR_FORMAT(format[2]) &&
466                                    (*format != 'n' || format[2] == 'n')) {
467                                 /* two fg colors in a row. bg colors are
468                                    so rare that we don't bother checking
469                                    them */
470                         } else {
471                                 /* some format, add it */
472                                 g_string_append_c(str, '%');
473                                 g_string_append_c(str, *format);
474
475                                 if (IS_FGCOLOR_FORMAT(*format))
476                                         last_fg = *format;
477                                 if (IS_BGCOLOR_FORMAT(*format))
478                                         last_bg = *format;
479                         }
480                         format++;
481                 }
482         }
483
484         ret = str->str;
485         g_string_free(str, FALSE);
486         return ret;
487 }
488
489 char *theme_format_expand(THEME_REC *theme, const char *format)
490 {
491         char *data, *ret;
492
493         g_return_val_if_fail(theme != NULL, NULL);
494         g_return_val_if_fail(format != NULL, NULL);
495
496         data = theme_format_expand_data(theme, &format, 'n', 'n', NULL, NULL,
497                                         EXPAND_FLAG_ROOT);
498         ret = theme_format_compress_colors(theme, data);
499         g_free(data);
500         return ret;
501 }
502
503 static MODULE_THEME_REC *theme_module_create(THEME_REC *theme, const char *module)
504 {
505         MODULE_THEME_REC *rec;
506         FORMAT_REC *formats;
507
508         rec = g_hash_table_lookup(theme->modules, module);
509         if (rec != NULL) return rec;
510
511         formats = g_hash_table_lookup(default_formats, module);
512         g_return_val_if_fail(formats != NULL, NULL);
513
514         rec = g_new0(MODULE_THEME_REC, 1);
515         rec->name = g_strdup(module);
516
517         for (rec->count = 0; formats[rec->count].def != NULL; rec->count++) ;
518         rec->formats = g_new0(char *, rec->count);
519         rec->expanded_formats = g_new0(char *, rec->count);
520
521         g_hash_table_insert(theme->modules, rec->name, rec);
522         return rec;
523 }
524
525 static void theme_read_replaces(CONFIG_REC *config, THEME_REC *theme)
526 {
527         GSList *tmp;
528         CONFIG_NODE *node;
529         const char *p;
530         int index;
531
532         /* reset replace keys */
533         for (index = 0; index < 256; index++)
534                 theme->replace_keys[index] = -1;
535         index = 0;
536
537         node = config_node_traverse(config, "replaces", FALSE);
538         if (node == NULL || node->type !=  NODE_TYPE_BLOCK) return;
539
540         for (tmp = node->value; tmp != NULL; tmp = tmp->next) {
541                 node = tmp->data;
542
543                 if (node->key != NULL && node->value != NULL) {
544                         for (p = node->key; *p != '\0'; p++)
545                                 theme->replace_keys[(int) *p] = index;
546
547                         theme->replace_values =
548                                 g_slist_append(theme->replace_values,
549                                                g_strdup(node->value));
550                         index++;
551                 }
552         }
553 }
554
555 static void theme_read_abstracts(CONFIG_REC *config, THEME_REC *theme)
556 {
557         GSList *tmp;
558         CONFIG_NODE *node;
559         gpointer oldkey, oldvalue;
560
561         node = config_node_traverse(config, "abstracts", FALSE);
562         if (node == NULL || node->type !=  NODE_TYPE_BLOCK) return;
563
564         for (tmp = node->value; tmp != NULL; tmp = tmp->next) {
565                 node = tmp->data;
566
567                 if (node->key == NULL || node->value == NULL)
568                         continue;
569
570                 if (g_hash_table_lookup_extended(theme->abstracts, node->key,
571                                                  &oldkey, &oldvalue)) {
572                         /* new values override old ones */
573                         g_hash_table_remove(theme->abstracts, oldkey);
574                         g_free(oldkey);
575                         g_free(oldvalue);
576                 }
577
578                 g_hash_table_insert(theme->abstracts, g_strdup(node->key),
579                                     g_strdup(node->value));
580         }
581 }
582
583 static void theme_set_format(THEME_REC *theme, MODULE_THEME_REC *rec,
584                              const char *module,
585                              const char *key, const char *value)
586 {
587         int num;
588
589         num = format_find_tag(module, key);
590         if (num != -1) {
591                 rec->formats[num] = g_strdup(value);
592                 rec->expanded_formats[num] = theme_format_expand(theme, value);
593         }
594 }
595
596 static void theme_read_formats(THEME_REC *theme, const char *module,
597                                CONFIG_REC *config, MODULE_THEME_REC *rec)
598 {
599         CONFIG_NODE *node;
600         GSList *tmp;
601
602         node = config_node_traverse(config, "formats", FALSE);
603         if (node == NULL) return;
604         node = config_node_section(node, module, -1);
605         if (node == NULL) return;
606
607         for (tmp = node->value; tmp != NULL; tmp = tmp->next) {
608                 node = tmp->data;
609
610                 if (node->key != NULL && node->value != NULL) {
611                         theme_set_format(theme, rec, module,
612                                          node->key, node->value);
613                 }
614         }
615 }
616
617 static void theme_init_module(THEME_REC *theme, const char *module,
618                               CONFIG_REC *config)
619 {
620         MODULE_THEME_REC *rec;
621         FORMAT_REC *formats;
622         int n;
623
624         formats = g_hash_table_lookup(default_formats, module);
625         g_return_if_fail(formats != NULL);
626
627         rec = theme_module_create(theme, module);
628
629         if (config != NULL)
630                 theme_read_formats(theme, module, config, rec);
631
632         /* expand the remaining formats */
633         for (n = 0; n < rec->count; n++) {
634                 if (rec->expanded_formats[n] == NULL) {
635                         rec->expanded_formats[n] =
636                                 theme_format_expand(theme, formats[n].def);
637                 }
638         }
639 }
640
641 static void sig_print_errors(void)
642 {
643         init_finished = TRUE;
644
645         if (init_errors != NULL) {
646                 signal_emit("gui dialog", 2, "error", init_errors);
647                 g_free(init_errors);
648         }
649 }
650
651 static void theme_read_module(THEME_REC *theme, const char *module)
652 {
653         CONFIG_REC *config;
654
655         config = config_open(theme->path, -1);
656         if (config != NULL)
657                 config_parse(config);
658
659         theme_init_module(theme, module, config);
660
661         if (config != NULL) config_close(config);
662 }
663
664 static void themes_read_module(const char *module)
665 {
666         g_slist_foreach(themes, (GFunc) theme_read_module, (void *) module);
667 }
668
669 static void theme_remove_module(THEME_REC *theme, const char *module)
670 {
671         MODULE_THEME_REC *rec;
672
673         rec = g_hash_table_lookup(theme->modules, module);
674         if (rec == NULL) return;
675
676         g_hash_table_remove(theme->modules, module);
677         theme_module_destroy(module, rec);
678 }
679
680 static void themes_remove_module(const char *module)
681 {
682         g_slist_foreach(themes, (GFunc) theme_remove_module, (void *) module);
683 }
684
685 void theme_register_module(const char *module, FORMAT_REC *formats)
686 {
687         if (g_hash_table_lookup(default_formats, module) != NULL)
688                 return;
689
690         g_hash_table_insert(default_formats, g_strdup(module), formats);
691         themes_read_module(module);
692 }
693
694 void theme_unregister_module(const char *module)
695 {
696         gpointer key, value;
697
698         if (default_formats == NULL)
699                 return; /* already uninitialized */
700
701         if (!g_hash_table_lookup_extended(default_formats, module, &key, &value))
702                 return;
703
704         g_hash_table_remove(default_formats, key);
705         g_free(key);
706
707         themes_remove_module(module);
708 }
709
710 static THEME_REC *theme_find(const char *name)
711 {
712         GSList *tmp;
713
714         for (tmp = themes; tmp != NULL; tmp = tmp->next) {
715                 THEME_REC *rec = tmp->data;
716
717                 if (g_strcasecmp(rec->name, name) == 0)
718                         return rec;
719         }
720
721         return NULL;
722 }
723
724 static void window_themes_update(void)
725 {
726         GSList *tmp;
727
728         for (tmp = windows; tmp != NULL; tmp = tmp->next) {
729                 WINDOW_REC *rec = tmp->data;
730
731                 if (rec->theme_name != NULL)
732                         rec->theme = theme_load(rec->theme_name);
733         }
734 }
735
736 THEME_REC *theme_load(const char *setname)
737 {
738         THEME_REC *theme, *oldtheme;
739         struct stat statbuf;
740         char *fname, *name, *p;
741
742         name = g_strdup(setname);
743         p = strrchr(name, '.');
744         if (p != NULL && strcmp(p, ".theme") == 0) {
745                 /* remove the trailing .theme */
746                 *p = '\0';
747         }
748
749         theme = theme_find(name);
750
751         /* check home dir */
752         fname = g_strdup_printf("%s/%s.theme", get_irssi_dir(), name);
753         if (stat(fname, &statbuf) != 0) {
754                 /* check global config dir */
755                 g_free(fname);
756                 fname = g_strdup_printf(THEMESDIR"/%s.theme", name);
757                 if (stat(fname, &statbuf) != 0) {
758                         /* theme not found */
759                         g_free(fname);
760                         g_free(name);
761                         return theme; /* use the one in memory if possible */
762                 }
763         }
764
765         if (theme != NULL && theme->last_modify == statbuf.st_mtime) {
766                 /* theme not modified, use the one already in memory */
767                 g_free(fname);
768                 g_free(name);
769                 return theme;
770         }
771
772         oldtheme = theme;
773         theme = theme_create(fname, name);
774         theme->last_modify = statbuf.st_mtime;
775         if (!theme_read(theme, theme->path, NULL)) {
776                 /* error reading .theme file */
777                 theme_destroy(theme);
778                 theme = NULL;
779         }
780
781         if (oldtheme != NULL && theme != NULL) {
782                 theme_destroy(oldtheme);
783                 window_themes_update();
784         }
785
786         g_free(fname);
787         g_free(name);
788         return theme;
789 }
790
791 typedef struct {
792         THEME_REC *theme;
793         CONFIG_REC *config;
794 } THEME_READ_REC;
795
796 static void theme_read_modules(const char *module, void *value,
797                                THEME_READ_REC *rec)
798 {
799         theme_init_module(rec->theme, module, rec->config);
800 }
801
802 static void read_error(const char *str)
803 {
804         char *old;
805
806         if (init_finished)
807                 printtext(NULL, NULL, MSGLEVEL_CLIENTERROR, "%s", str);
808         else if (init_errors == NULL)
809                 init_errors = g_strdup(str);
810         else {
811                 old = init_errors;
812                 init_errors = g_strconcat(init_errors, "\n", str, NULL);
813                 g_free(old);
814         }
815 }
816
817 static int theme_read(THEME_REC *theme, const char *path, const char *data)
818 {
819         CONFIG_REC *config;
820         THEME_READ_REC rec;
821         char *str;
822
823         config = config_open(data == NULL ? path : NULL, -1) ;
824         if (config == NULL) {
825                 /* didn't exist or no access? */
826                 str = g_strdup_printf("Error reading theme file %s: %s",
827                                       path, g_strerror(errno));
828                 read_error(str);
829                 g_free(str);
830                 return FALSE;
831         }
832
833         if (data != NULL)
834                 config_parse_data(config, data, "internal");
835         else
836                 config_parse(config);
837
838         if (config_last_error(config) != NULL) {
839                 str = g_strdup_printf("Ignored errors in theme %s:\n%s",
840                                       theme->name, config_last_error(config));
841                 read_error(str);
842                 g_free(str);
843         }
844
845         theme->default_color =
846                 config_get_int(config, NULL, "default_color", -1);
847         /* FIXME: remove after 0.7.99 */
848         if (theme->default_color == 0 &&
849             config_get_int(config, NULL, "default_real_color", -1) != -1)
850                 theme->default_color = -1;
851         theme_read_replaces(config, theme);
852
853         if (data == NULL) {
854                 /* get the default abstracts from default theme. */
855                 CONFIG_REC *default_config;
856
857                 default_config = config_open(NULL, -1);
858                 config_parse_data(default_config, default_theme, "internal");
859                 theme_read_abstracts(default_config, theme);
860                 config_close(default_config);
861         }
862         theme_read_abstracts(config, theme);
863
864         rec.theme = theme;
865         rec.config = config;
866         g_hash_table_foreach(default_formats,
867                              (GHFunc) theme_read_modules, &rec);
868         config_close(config);
869
870         return TRUE;
871 }
872
873 typedef struct {
874         char *name;
875         char *short_name;
876 } THEME_SEARCH_REC;
877
878 static int theme_search_equal(THEME_SEARCH_REC *r1, THEME_SEARCH_REC *r2)
879 {
880         return g_strcasecmp(r1->short_name, r2->short_name);
881 }
882
883 static void theme_get_modules(char *module, FORMAT_REC *formats, GSList **list)
884 {
885         THEME_SEARCH_REC *rec;
886
887         rec = g_new(THEME_SEARCH_REC, 1);
888         rec->name = module;
889         rec->short_name = strrchr(module, '/');
890         if (rec->short_name != NULL)
891                 rec->short_name++; else rec->short_name = module;
892         *list = g_slist_insert_sorted(*list, rec, (GCompareFunc) theme_search_equal);
893 }
894
895 static GSList *get_sorted_modules(void)
896 {
897         GSList *list;
898
899         list = NULL;
900         g_hash_table_foreach(default_formats, (GHFunc) theme_get_modules, &list);
901         return list;
902 }
903
904 static THEME_SEARCH_REC *theme_search(GSList *list, const char *module)
905 {
906         THEME_SEARCH_REC *rec;
907
908         while (list != NULL) {
909                 rec = list->data;
910
911                 if (g_strcasecmp(rec->short_name, module) == 0)
912                         return rec;
913                 list = list->next;
914         }
915
916         return NULL;
917 }
918
919 static void theme_show(THEME_SEARCH_REC *rec, const char *key, const char *value, int reset)
920 {
921         MODULE_THEME_REC *theme;
922         FORMAT_REC *formats;
923         const char *text, *last_title;
924         int n, first;
925
926         formats = g_hash_table_lookup(default_formats, rec->name);
927         theme = g_hash_table_lookup(current_theme->modules, rec->name);
928
929         last_title = NULL; first = TRUE;
930         for (n = 1; formats[n].def != NULL; n++) {
931                 text = theme != NULL && theme->formats[n] != NULL ?
932                         theme->formats[n] : formats[n].def;
933
934                 if (formats[n].tag == NULL)
935                         last_title = text;
936                 else if ((value != NULL && key != NULL && g_strcasecmp(formats[n].tag, key) == 0) ||
937                          (value == NULL && (key == NULL || stristr(formats[n].tag, key) != NULL))) {
938                         if (first) {
939                                 printformat(NULL, NULL, MSGLEVEL_CLIENTCRAP, TXT_FORMAT_TITLE, rec->short_name, formats[0].def);
940                                 first = FALSE;
941                         }
942                         if (last_title != NULL)
943                                 printformat(NULL, NULL, MSGLEVEL_CLIENTCRAP, TXT_FORMAT_SUBTITLE, last_title);
944                         if (reset || value != NULL) {
945                                 theme = theme_module_create(current_theme, rec->name);
946                                 g_free_not_null(theme->formats[n]);
947                                 g_free_not_null(theme->expanded_formats[n]);
948
949                                 text = reset ? formats[n].def : value;
950                                 theme->formats[n] = reset ? NULL : g_strdup(value);
951                                 theme->expanded_formats[n] = theme_format_expand(current_theme, text);
952                         }
953                         printformat(NULL, NULL, MSGLEVEL_CLIENTCRAP, TXT_FORMAT_ITEM, formats[n].tag, text);
954                         last_title = NULL;
955                 }
956         }
957 }
958
959 /* SYNTAX: FORMAT [-delete | -reset] [<module>] [<key> [<value>]] */
960 static void cmd_format(const char *data)
961 {
962         GHashTable *optlist;
963         GSList *tmp, *modules;
964         char *module, *key, *value;
965         void *free_arg;
966         int reset;
967
968         if (!cmd_get_params(data, &free_arg, 3 | PARAM_FLAG_GETREST | PARAM_FLAG_OPTIONS,
969                             "format", &optlist, &module, &key, &value))
970                 return;
971
972         modules = get_sorted_modules();
973         if (*module == '\0')
974                 module = NULL;
975         else if (theme_search(modules, module) == NULL) {
976                 /* first argument isn't module.. */
977                 cmd_params_free(free_arg);
978                 if (!cmd_get_params(data, &free_arg, 2 | PARAM_FLAG_GETREST | PARAM_FLAG_OPTIONS,
979                                     "format", &optlist, &key, &value))
980                         return;
981                 module = NULL;
982         }
983
984         reset = FALSE;
985         if (*key == '\0') key = NULL;
986         if (g_hash_table_lookup(optlist, "reset"))
987                 reset = TRUE;
988         else if (g_hash_table_lookup(optlist, "delete"))
989                 value = "";
990         else if (*value == '\0')
991                 value = NULL;
992
993         for (tmp = modules; tmp != NULL; tmp = tmp->next) {
994                 THEME_SEARCH_REC *rec = tmp->data;
995
996                 if (module == NULL || g_strcasecmp(rec->short_name, module) == 0)
997                         theme_show(rec, key, value, reset);
998         }
999         g_slist_foreach(modules, (GFunc) g_free, NULL);
1000         g_slist_free(modules);
1001
1002         cmd_params_free(free_arg);
1003 }
1004
1005 typedef struct {
1006         CONFIG_REC *config;
1007         int save_all;
1008 } THEME_SAVE_REC;
1009
1010 static void module_save(const char *module, MODULE_THEME_REC *rec,
1011                         THEME_SAVE_REC *data)
1012 {
1013         CONFIG_NODE *fnode, *node;
1014         FORMAT_REC *formats;
1015         int n;
1016
1017         formats = g_hash_table_lookup(default_formats, rec->name);
1018         if (formats == NULL) return;
1019
1020         fnode = config_node_traverse(data->config, "formats", TRUE);
1021
1022         node = config_node_section(fnode, rec->name, NODE_TYPE_BLOCK);
1023         for (n = 1; formats[n].def != NULL; n++) {
1024                 if (rec->formats[n] != NULL) {
1025                         config_node_set_str(data->config, node, formats[n].tag,
1026                                             rec->formats[n]);
1027                 } else if (data->save_all && formats[n].tag != NULL) {
1028                         config_node_set_str(data->config, node, formats[n].tag,
1029                                             formats[n].def);
1030                 }
1031         }
1032
1033         if (node->value == NULL) {
1034                 /* not modified, don't keep the empty section */
1035                 config_node_remove(data->config, fnode, node);
1036                 if (fnode->value == NULL) {
1037                         config_node_remove(data->config,
1038                                            data->config->mainnode, fnode);
1039                 }
1040         }
1041 }
1042
1043 static void theme_save(THEME_REC *theme, int save_all)
1044 {
1045         CONFIG_REC *config;
1046         THEME_SAVE_REC data;
1047         char *path;
1048         int ok;
1049
1050         config = config_open(theme->path, -1);
1051         if (config != NULL)
1052                 config_parse(config);
1053         else {
1054                 if (g_strcasecmp(theme->name, "default") == 0) {
1055                         config = config_open(NULL, -1);
1056                         config_parse_data(config, default_theme, "internal");
1057                         config_change_file_name(config, theme->path, 0660);
1058                 } else {
1059                         config = config_open(theme->path, 0660);
1060                         if (config == NULL)
1061                                 return;
1062                         config_parse(config);
1063                 }
1064         }
1065
1066         data.config = config;
1067         data.save_all = save_all;
1068         g_hash_table_foreach(theme->modules, (GHFunc) module_save, &data);
1069
1070         /* always save the theme to ~/.irssi/ */
1071         path = g_strdup_printf("%s/%s", get_irssi_dir(),
1072                                g_basename(theme->path));
1073         ok = config_write(config, path, 0660) == 0;
1074
1075         printformat(NULL, NULL, MSGLEVEL_CLIENTNOTICE,
1076                     ok ? TXT_THEME_SAVED : TXT_THEME_SAVE_FAILED,
1077                     path, config_last_error(config));
1078
1079         g_free(path);
1080         config_close(config);
1081 }
1082
1083 /* save changed formats, -format saves all */
1084 static void cmd_save(const char *data)
1085 {
1086         GSList *tmp;
1087         GHashTable *optlist;
1088         void *free_arg;
1089         char *fname;
1090         int saveall;
1091
1092         if (!cmd_get_params(data, &free_arg, 1 | PARAM_FLAG_OPTIONS,
1093                             "save", &optlist, &fname))
1094                 return;
1095
1096         saveall = g_hash_table_lookup(optlist, "formats") != NULL;
1097         for (tmp = themes; tmp != NULL; tmp = tmp->next) {
1098                 THEME_REC *theme = tmp->data;
1099
1100                 theme_save(theme, saveall);
1101         }
1102
1103         cmd_params_free(free_arg);
1104 }
1105
1106 static void complete_format_list(THEME_SEARCH_REC *rec, const char *key, GList **list)
1107 {
1108         FORMAT_REC *formats;
1109         int n, len;
1110
1111         formats = g_hash_table_lookup(default_formats, rec->name);
1112
1113         len = strlen(key);
1114         for (n = 1; formats[n].def != NULL; n++) {
1115                 const char *item = formats[n].tag;
1116
1117                 if (item != NULL && g_strncasecmp(item, key, len) == 0)
1118                         *list = g_list_append(*list, g_strdup(item));
1119         }
1120 }
1121
1122 static GList *completion_get_formats(const char *module, const char *key)
1123 {
1124         GSList *modules, *tmp;
1125         GList *list;
1126
1127         g_return_val_if_fail(key != NULL, NULL);
1128
1129         list = NULL;
1130
1131         modules = get_sorted_modules();
1132         if (*module == '\0' || theme_search(modules, module) != NULL) {
1133                 for (tmp = modules; tmp != NULL; tmp = tmp->next) {
1134                         THEME_SEARCH_REC *rec = tmp->data;
1135
1136                         if (*module == '\0' || g_strcasecmp(rec->short_name, module) == 0)
1137                                 complete_format_list(rec, key, &list);
1138                 }
1139         }
1140         g_slist_foreach(modules, (GFunc) g_free, NULL);
1141         g_slist_free(modules);
1142
1143         return list;
1144 }
1145
1146 static void sig_complete_format(GList **list, WINDOW_REC *window,
1147                                 const char *word, const char *line, int *want_space)
1148 {
1149         const char *ptr;
1150         int words;
1151
1152         g_return_if_fail(list != NULL);
1153         g_return_if_fail(word != NULL);
1154         g_return_if_fail(line != NULL);
1155
1156         ptr = line;
1157
1158         words = 0;
1159         do {
1160                 words++;
1161                 ptr = strchr(ptr, ' ');
1162         } while (ptr != NULL);
1163
1164         if (words > 2)
1165                 return;
1166
1167         *list = completion_get_formats(line, word);
1168         if (*list != NULL) signal_stop();
1169 }
1170
1171 static void change_theme(const char *name, int verbose)
1172 {
1173         THEME_REC *rec;
1174
1175         rec = theme_load(name);
1176         if (rec != NULL) {
1177                 current_theme = rec;
1178                 signal_emit("theme changed", 1, rec);
1179
1180                 if (verbose) {
1181                         printformat(NULL, NULL, MSGLEVEL_CLIENTNOTICE,
1182                                     TXT_THEME_CHANGED,
1183                                     rec->name, rec->path);
1184                 }
1185         } else if (verbose) {
1186                 printformat(NULL, NULL, MSGLEVEL_CLIENTERROR,
1187                             TXT_THEME_NOT_FOUND, name);
1188         }
1189 }
1190
1191 static void read_settings(void)
1192 {
1193         const char *theme;
1194         int len;
1195
1196         theme = settings_get_str("theme");
1197         len = strlen(current_theme->name);
1198         if (strcmp(current_theme->name, theme) != 0 &&
1199             (strncmp(current_theme->name, theme, len) != 0 ||
1200              strcmp(theme+len, ".theme") != 0))
1201                 change_theme(theme, TRUE);
1202 }
1203
1204 static void themes_read(void)
1205 {
1206         char *fname;
1207
1208         while (themes != NULL)
1209                 theme_destroy(themes->data);
1210
1211         /* first there's default theme.. */
1212         current_theme = theme_load("default");
1213         if (current_theme == NULL) {
1214                 fname = g_strdup_printf("%s/default.theme", get_irssi_dir());
1215                 current_theme = theme_create(fname, "default");
1216                 current_theme->default_color = -1;
1217                 theme_read(current_theme, NULL, default_theme);
1218                 g_free(fname);
1219         }
1220
1221         window_themes_update();
1222         change_theme(settings_get_str("theme"), FALSE);
1223 }
1224
1225 void themes_init(void)
1226 {
1227         settings_add_str("lookandfeel", "theme", "default");
1228
1229         default_formats = g_hash_table_new((GHashFunc) g_str_hash,
1230                                            (GCompareFunc) g_str_equal);
1231
1232         init_finished = FALSE;
1233         init_errors = NULL;
1234
1235         themes = NULL;
1236         themes_read();
1237
1238         command_bind("format", NULL, (SIGNAL_FUNC) cmd_format);
1239         command_bind("save", NULL, (SIGNAL_FUNC) cmd_save);
1240         signal_add("complete command format", (SIGNAL_FUNC) sig_complete_format);
1241         signal_add("irssi init finished", (SIGNAL_FUNC) sig_print_errors);
1242         signal_add("setup changed", (SIGNAL_FUNC) read_settings);
1243         signal_add("setup reread", (SIGNAL_FUNC) themes_read);
1244
1245         command_set_options("format", "delete reset");
1246         command_set_options("save", "formats");
1247 }
1248
1249 void themes_deinit(void)
1250 {
1251         while (themes != NULL)
1252                 theme_destroy(themes->data);
1253
1254         g_hash_table_destroy(default_formats);
1255         default_formats = NULL;
1256
1257         command_unbind("format", (SIGNAL_FUNC) cmd_format);
1258         command_unbind("save", (SIGNAL_FUNC) cmd_save);
1259         signal_remove("complete command format", (SIGNAL_FUNC) sig_complete_format);
1260         signal_remove("irssi init finished", (SIGNAL_FUNC) sig_print_errors);
1261         signal_remove("setup changed", (SIGNAL_FUNC) read_settings);
1262         signal_remove("setup reread", (SIGNAL_FUNC) themes_read);
1263 }