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