8b434f89a23534ef287765e8d5d74cc1ab13778b
[ncmpc-debian.git] / src / ConfigParser.cxx
1 /* ncmpc (Ncurses MPD Client)
2  * (c) 2004-2019 The Music Player Daemon Project
3  * Project homepage: http://musicpd.org
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  */
19
20 #include "ConfigParser.hxx"
21 #include "config.h"
22 #include "Bindings.hxx"
23 #include "GlobalBindings.hxx"
24 #include "defaults.hxx"
25 #include "i18n.h"
26 #include "Command.hxx"
27 #include "Styles.hxx"
28 #include "BasicColors.hxx"
29 #include "CustomColors.hxx"
30 #include "screen_list.hxx"
31 #include "PageMeta.hxx"
32 #include "Options.hxx"
33 #include "util/CharUtil.hxx"
34 #include "util/Compiler.h"
35 #include "util/PrintException.hxx"
36 #include "util/RuntimeError.hxx"
37 #include "util/StringStrip.hxx"
38
39 #include <algorithm>
40 #include <array>
41
42 #include <assert.h>
43 #include <ctype.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <strings.h>
48
49 #define MAX_LINE_LENGTH 1024
50 #define COMMENT_TOKEN '#'
51
52 /* configuration field names */
53 #define CONF_ENABLE_COLORS "enable-colors"
54 #define CONF_SCROLL_OFFSET "scroll-offset"
55 #define CONF_AUTO_CENTER "auto-center"
56 #define CONF_WIDE_CURSOR "wide-cursor"
57 #define CONF_KEY_DEFINITION "key"
58 #define CONF_COLOR "color"
59 #define CONF_COLOR_DEFINITION "colordef"
60 #define CONF_LIST_FORMAT "list-format"
61 #define CONF_SEARCH_FORMAT "search-format"
62 #define CONF_STATUS_FORMAT "status-format"
63 #define CONF_XTERM_TITLE_FORMAT "xterm-title-format"
64 #define CONF_LIST_WRAP "wrap-around"
65 #define CONF_FIND_WRAP "find-wrap"
66 #define CONF_FIND_SHOW_LAST "find-show-last"
67 #define CONF_AUDIBLE_BELL "audible-bell"
68 #define CONF_VISIBLE_BELL "visible-bell"
69 #define CONF_BELL_ON_WRAP "bell-on-wrap"
70 #define CONF_STATUS_MESSAGE_TIME "status-message-time"
71 #define CONF_XTERM_TITLE "set-xterm-title"
72 #define CONF_ENABLE_MOUSE "enable-mouse"
73 #define CONF_CROSSFADE_TIME "crossfade-time"
74 #define CONF_SEARCH_MODE "search-mode"
75 #define CONF_HIDE_CURSOR "hide-cursor"
76 #define CONF_SEEK_TIME "seek-time"
77 #define CONF_LIBRARY_PAGE_TAGS "library-page-tags"
78 #define CONF_SCREEN_LIST "screen-list"
79 #define CONF_TIMEDISPLAY_TYPE "timedisplay-type"
80 #define CONF_HOST "host"
81 #define CONF_PORT "port"
82 #define CONF_PASSWORD "password"
83 #define CONF_TIMEOUT "timeout"
84 #define CONF_LYRICS_TIMEOUT "lyrics-timeout"
85 #define CONF_SCROLL "scroll"
86 #define CONF_SCROLL_SEP "scroll-sep"
87 #define CONF_VISIBLE_BITRATE "visible-bitrate"
88 #define CONF_HARDWARE_CURSOR "hardware-cursor"
89 #define CONF_WELCOME_SCREEN_LIST "welcome-screen-list"
90 #define CONF_DISPLAY_TIME "display-time"
91 #define CONF_JUMP_PREFIX_ONLY "jump-prefix-only"
92 #define CONF_LYRICS_AUTOSAVE "lyrics-autosave"
93 #define CONF_LYRICS_SHOW_PLUGIN "lyrics-show-plugin"
94 #define CONF_TEXT_EDITOR "text-editor"
95 #define CONF_TEXT_EDITOR_ASK "text-editor-ask"
96 #define CONF_CHAT_PREFIX "chat-prefix"
97 #define CONF_SECOND_COLUMN "second-column"
98
99 gcc_pure
100 static bool
101 str2bool(char *str) noexcept
102 {
103         return strcasecmp(str, "yes") == 0 || strcasecmp(str, "true") == 0 ||
104                 strcasecmp(str, "on") == 0 || strcasecmp(str, "1") == 0;
105 }
106
107 static constexpr bool
108 is_word_char(char ch) noexcept
109 {
110         return IsAlphaNumericASCII(ch) || ch == '-' || ch == '_';
111 }
112
113 static char *
114 after_unquoted_word(char *p)
115 {
116         if (!is_word_char(*p))
117                 throw FormatRuntimeError("%s: %s",
118                                          _("Word expected"), p);
119
120         ++p;
121
122         while (is_word_char(*p))
123                 ++p;
124
125         return p;
126 }
127
128 /**
129  * Throws on error.
130  */
131 static int
132 parse_key_value(char *str, char **end)
133 {
134         if (*str == '\'') {
135                 if (str[1] == '\\' && str[2] == '\'' && str[3] == '\'') {
136                         /* the single quote can be escaped with a
137                            backslash */
138                         *end = str + 4;
139                         return str[2];
140                 }
141
142                 if (str[1] == '\'' || str[2] != '\'')
143                         throw FormatRuntimeError("%s: %s",
144                                                  _("Malformed hotkey definition"),
145                                                  str);
146
147                 *end = str + 3;
148                 return str[1];
149         } else {
150                 long value = strtol(str, end, 0);
151                 if (*end == str)
152                         throw FormatRuntimeError("%s: %s",
153                                                  _("Malformed hotkey definition"),
154                                                  str);
155
156                 return (int)value;
157         }
158 }
159
160 /**
161  * Throws on error.
162  */
163 static void
164 parse_key_definition(char *str)
165 {
166         /* get the command name */
167         char *eq = strchr(str, '=');
168         if (eq == nullptr)
169                 throw FormatRuntimeError("%s: %s",
170                                          /* the hotkey configuration
171                                             line is incomplete */
172                                          _("Incomplete hotkey configuration"),
173                                          str);
174
175         char *command_name = str;
176         str = StripLeft(eq + 1);
177
178         *eq = '\0';
179         StripRight(command_name);
180         const auto cmd = get_key_command_from_name(command_name);
181         if (cmd == Command::NONE)
182                 throw FormatRuntimeError("%s: %s",
183                                          /* the hotkey configuration
184                                             contains an unknown
185                                             command */
186                                          _("Unknown command"), command_name);
187
188         /* parse key values */
189         size_t i = 0;
190         char *p = str;
191
192         std::array<int, MAX_COMMAND_KEYS> keys{0};
193         while (i < MAX_COMMAND_KEYS && *p != 0) {
194                 keys[i++] = parse_key_value(p, &p);
195                 while (*p==',' || *p==' ' || *p=='\t')
196                         p++;
197         }
198
199         GetGlobalKeyBindings().SetKey(cmd, keys);
200 }
201
202 /**
203  * Throws on error.
204  */
205 static bool
206 parse_timedisplay_type(const char *str)
207 {
208         if (strcmp(str, "elapsed") == 0)
209                 return false;
210         else if (strcmp(str, "remaining") == 0)
211                 return true;
212         else {
213                 throw FormatRuntimeError("%s: %s",
214                                          /* translators: ncmpc
215                                             supports displaying the
216                                             "elapsed" or "remaining"
217                                             time of a song being
218                                             played; in this case, the
219                                             configuration file
220                                             contained an invalid
221                                             setting */
222                                          _("Bad time display type"), str);
223                 return false;
224         }
225 }
226
227 #ifdef ENABLE_COLORS
228 /**
229  * Throws on error.
230  */
231 static char *
232 separate_value(char *p)
233 {
234         char *value = strchr(p, '=');
235         if (value == nullptr)
236                 /* an equals sign '=' was expected while parsing a
237                    configuration file line */
238                 throw std::runtime_error(_("Missing '='"));
239
240         *StripRight(p, value++) = '\0';
241
242         return Strip(value);
243 }
244
245 /**
246  * Throws on error.
247  */
248 static void
249 parse_color(char *str)
250 {
251         char *value = separate_value(str);
252         ModifyStyle(str, value);
253 }
254
255 /**
256  * Returns the first non-whitespace character after the next comma
257  * character, or the end of the string.  This is used to parse comma
258  * separated values.
259  */
260 static char *
261 after_comma(char *p) noexcept
262 {
263         char *comma = strchr(p, ',');
264
265         if (comma != nullptr) {
266                 *comma++ = 0;
267                 comma = StripLeft(comma);
268         } else
269                 comma = p + strlen(p);
270
271         StripRight(p);
272         return comma;
273 }
274
275 /**
276  * Throws on error.
277  */
278 static void
279 parse_color_definition(char *str)
280 {
281         char *value = separate_value(str);
282
283         /* get the command name */
284         short color = ParseColorNameOrNumber(str);
285         if (color < 0)
286                 throw FormatRuntimeError("%s: %s",
287                                          _("Bad color name"), str);
288
289         /* parse r,g,b values */
290
291         short rgb[3];
292         for (unsigned i = 0; i < 3; ++i) {
293                 char *next = after_comma(value), *endptr;
294                 if (*value == 0)
295                         throw FormatRuntimeError("%s: %s",
296                                                  _("Incomplete color definition"),
297                                                  str);
298
299                 rgb[i] = strtol(value, &endptr, 0);
300                 if (endptr == value || *endptr != 0)
301                         throw FormatRuntimeError("%s: %s",
302                                                  _("Invalid number"), value);
303
304                 value = next;
305         }
306
307         if (*value != 0)
308                 throw FormatRuntimeError("%s: %s",
309                                          _("Malformed color definition"), str);
310
311         colors_define(color, rgb[0], rgb[1], rgb[2]);
312 }
313 #endif
314
315 static std::string
316 GetStringValue(const char *s) noexcept
317 {
318         size_t length = strlen(s);
319
320         if (s[0] == '\"' && s[length - 1] == '\"') {
321                 length -= 2;
322                 ++s;
323         }
324
325         return {s, length};
326 }
327
328 static constexpr bool
329 IsListSeparator(char ch) noexcept
330 {
331         return IsWhitespaceFast(ch) || ch == ',';
332 }
333
334 static char *
335 NextItem(char *&src) noexcept
336 {
337         while (*src && IsListSeparator(*src))
338                 ++src;
339
340         if (!*src)
341                 return nullptr;
342
343         char *value = src;
344
345         while (!IsListSeparator(*src))
346                 ++src;
347
348         if (*src)
349                 *src++ = 0;
350
351         return value;
352 }
353
354 /**
355  * Throws on error.
356  */
357 static std::vector<std::string>
358 check_screen_list(char *value)
359 {
360         std::vector<std::string> screen;
361
362         while (char *name = NextItem(value)) {
363                 std::transform(name, name + strlen(name), name, tolower);
364
365                 const auto *page_meta = screen_lookup_name(name);
366                 if (page_meta == nullptr)
367                         throw FormatRuntimeError("%s: %s",
368                                                  /* an unknown screen
369                                                     name was specified
370                                                     in the
371                                                     configuration
372                                                     file */
373                                                  _("Unknown screen name"),
374                                                  name);
375
376                 /* use PageMeta::name because
377                    screen_lookup_name() may have translated a
378                    deprecated name */
379                 screen.emplace_back(page_meta->name);
380         }
381
382         if (screen.empty())
383                 screen = DEFAULT_SCREEN_LIST;
384
385         return screen;
386 }
387
388 #ifdef ENABLE_LIBRARY_PAGE
389
390 /**
391  * Throws on error.
392  */
393 static auto
394 ParseTagList(char *value)
395 {
396         std::vector<enum mpd_tag_type> result;
397
398         while (char *name = NextItem(value)) {
399                 auto type = mpd_tag_name_iparse(name);
400                 if (type == MPD_TAG_UNKNOWN)
401                         throw FormatRuntimeError("%s: %s",
402                                                  _("Unknown MPD tag"), name);
403
404                 result.emplace_back(type);
405         }
406
407         if (result.empty())
408                 throw std::runtime_error("Empty tag list");
409
410         return result;
411 }
412
413 #endif
414
415 /**
416  * Throws on error.
417  */
418 static int
419 get_search_mode(char *value)
420 {
421         char * test;
422         const int mode = strtol(value, &test, 10);
423         if (*test == '\0')
424         {
425                 if (0 <= mode && mode <= 4)
426                         return mode;
427                 else
428                         throw FormatRuntimeError("%s: %s",
429                                                  _("Invalid search mode"),value);
430         }
431         else
432         {
433                 // TODO: modify screen_search so that its own list of modes can be used
434                 // for comparison instead of specifying them here
435                 if (strcasecmp(value, "title") == 0)
436                         return 0;
437                 else if (strcasecmp(value, "artist") == 0)
438                         return 1;
439                 else if (strcasecmp(value, "album") == 0)
440                         return 2;
441                 else if (strcasecmp(value, "filename") == 0)
442                         return 3;
443                 else if (strcasecmp(value, "artist+album") == 0)
444                         return 4;
445                 else
446                         throw FormatRuntimeError("%s: %s",
447                                                  _("Unknown search mode"),
448                                                  value);
449         }
450 }
451
452 /**
453  * Throws on error.
454  */
455 static void
456 parse_line(char *line)
457 {
458         /* get the name part */
459         char *const name = line;
460         char *const name_end = after_unquoted_word(line);
461
462         line = StripLeft(name_end);
463         if (*line == '=') {
464                 ++line;
465                 line = StripLeft(line);
466         } else if (line == name_end) {
467                 throw FormatRuntimeError("%s: %s",
468                                          _("Missing '='"), name_end);
469         }
470
471         *name_end = 0;
472
473         /* get the value part */
474         char *const value = line;
475
476         /* key definition */
477         if (!strcasecmp(CONF_KEY_DEFINITION, name))
478                 parse_key_definition(value);
479         /* enable colors */
480         else if(!strcasecmp(CONF_ENABLE_COLORS, name))
481 #ifdef ENABLE_COLORS
482                 options.enable_colors = str2bool(value);
483 #else
484         {}
485 #endif
486         else if (!strcasecmp(CONF_SCROLL_OFFSET, name))
487                 options.scroll_offset = atoi(value);
488         /* auto center */
489         else if (!strcasecmp(CONF_AUTO_CENTER, name))
490                 options.auto_center = str2bool(value);
491         /* color assignment */
492         else if (!strcasecmp(CONF_COLOR, name))
493 #ifdef ENABLE_COLORS
494                 parse_color(value);
495 #else
496         {}
497 #endif
498         /* wide cursor */
499         else if (!strcasecmp(CONF_WIDE_CURSOR, name))
500                 options.wide_cursor = str2bool(value);
501         else if (strcasecmp(name, CONF_HARDWARE_CURSOR) == 0)
502                 options.hardware_cursor = str2bool(value);
503         /* welcome screen list */
504         else if (!strcasecmp(CONF_WELCOME_SCREEN_LIST, name))
505                 options.welcome_screen_list = str2bool(value);
506         /* visible bitrate */
507         else if (!strcasecmp(CONF_VISIBLE_BITRATE, name))
508                 options.visible_bitrate = str2bool(value);
509         /* timer display type */
510         else if (!strcasecmp(CONF_TIMEDISPLAY_TYPE, name))
511                 options.display_remaining_time = parse_timedisplay_type(value);
512                 /* color definition */
513         else if (!strcasecmp(CONF_COLOR_DEFINITION, name))
514 #ifdef ENABLE_COLORS
515                 parse_color_definition(value);
516 #else
517         {}
518 #endif
519         /* list format string */
520         else if (!strcasecmp(CONF_LIST_FORMAT, name)) {
521                 options.list_format = GetStringValue(value);
522                 /* search format string */
523         } else if (!strcasecmp(CONF_SEARCH_FORMAT, name)) {
524                 options.search_format = GetStringValue(value);
525                 /* status format string */
526         } else if (!strcasecmp(CONF_STATUS_FORMAT, name)) {
527                 options.status_format = GetStringValue(value);
528                 /* xterm title format string */
529         } else if (!strcasecmp(CONF_XTERM_TITLE_FORMAT, name)) {
530                 options.xterm_title_format = GetStringValue(value);
531         } else if (!strcasecmp(CONF_LIST_WRAP, name))
532                 options.list_wrap = str2bool(value);
533         else if (!strcasecmp(CONF_FIND_WRAP, name))
534                 options.find_wrap = str2bool(value);
535         else if (!strcasecmp(CONF_FIND_SHOW_LAST,name))
536                 options.find_show_last_pattern = str2bool(value);
537         else if (!strcasecmp(CONF_AUDIBLE_BELL, name))
538                 options.audible_bell = str2bool(value);
539         else if (!strcasecmp(CONF_VISIBLE_BELL, name))
540                 options.visible_bell = str2bool(value);
541         else if (!strcasecmp(CONF_BELL_ON_WRAP, name))
542                 options.bell_on_wrap = str2bool(value);
543         else if (!strcasecmp(CONF_STATUS_MESSAGE_TIME, name))
544                 options.status_message_time = std::chrono::seconds(atoi(value));
545         else if (!strcasecmp(CONF_XTERM_TITLE, name))
546                 options.enable_xterm_title = str2bool(value);
547         else if (!strcasecmp(CONF_ENABLE_MOUSE, name))
548 #ifdef HAVE_GETMOUSE
549                 options.enable_mouse = str2bool(value);
550 #else
551         {}
552 #endif
553         else if (!strcasecmp(CONF_CROSSFADE_TIME, name))
554                 options.crossfade_time = atoi(value);
555         else if (!strcasecmp(CONF_SEARCH_MODE, name))
556                 options.search_mode = get_search_mode(value);
557         else if (!strcasecmp(CONF_HIDE_CURSOR, name))
558                 options.hide_cursor = std::chrono::seconds(atoi(value));
559         else if (!strcasecmp(CONF_SEEK_TIME, name))
560                 options.seek_time = atoi(value);
561         else if (!strcasecmp(CONF_LIBRARY_PAGE_TAGS, name)) {
562 #ifdef ENABLE_LIBRARY_PAGE
563                 options.library_page_tags = ParseTagList(value);
564 #endif
565         } else if (!strcasecmp(CONF_SCREEN_LIST, name)) {
566                 options.screen_list = check_screen_list(value);
567         } else if (!strcasecmp(CONF_HOST, name))
568                 options.host = GetStringValue(value);
569         else if (!strcasecmp(CONF_PORT, name))
570                 options.port = atoi(GetStringValue(value).c_str());
571         else if (!strcasecmp(CONF_PASSWORD, name))
572                 options.password = GetStringValue(value);
573         else if (!strcasecmp(CONF_TIMEOUT, name))
574                 options.timeout_ms = atoi(GetStringValue(value).c_str())
575                                      * 1000 /* seconds -> milliseconds */;
576         else if (!strcasecmp(CONF_LYRICS_TIMEOUT, name))
577 #ifdef ENABLE_LYRICS_SCREEN
578                 options.lyrics_timeout = std::chrono::seconds(atoi(GetStringValue(value).c_str()));
579 #else
580         {}
581 #endif
582         else if (!strcasecmp(CONF_SCROLL, name))
583                 options.scroll = str2bool(value);
584         else if (!strcasecmp(CONF_SCROLL_SEP, name)) {
585                 options.scroll_sep = GetStringValue(value);
586         } else if (!strcasecmp(CONF_DISPLAY_TIME, name))
587                 /* obsolete, ignore */
588                 {}
589         else if (!strcasecmp(CONF_JUMP_PREFIX_ONLY, name))
590 #ifdef NCMPC_MINI
591                 {}
592 #else
593                 options.jump_prefix_only = str2bool(value);
594 #endif
595         else if (!strcasecmp(CONF_LYRICS_AUTOSAVE, name))
596 #ifdef ENABLE_LYRICS_SCREEN
597                 options.lyrics_autosave = str2bool(value);
598 #else
599         {}
600 #endif
601         else if (!strcasecmp(CONF_LYRICS_SHOW_PLUGIN, name))
602 #ifdef ENABLE_LYRICS_SCREEN
603                 options.lyrics_show_plugin = str2bool(value);
604 #else
605                 {}
606 #endif
607         else if (!strcasecmp(name, CONF_TEXT_EDITOR))
608 #ifdef ENABLE_LYRICS_SCREEN
609                 {
610                         options.text_editor = GetStringValue(value);
611                 }
612 #else
613                 {}
614 #endif
615         else if (!strcasecmp(name, CONF_TEXT_EDITOR_ASK))
616 #ifdef ENABLE_LYRICS_SCREEN
617                 options.text_editor_ask = str2bool(value);
618 #else
619                 {}
620 #endif
621         else if (!strcasecmp(name, CONF_CHAT_PREFIX))
622 #ifdef ENABLE_CHAT_SCREEN
623                 options.chat_prefix = GetStringValue(value);
624 #else
625                 {}
626 #endif
627         else if (!strcasecmp(CONF_SECOND_COLUMN, name))
628 #ifdef NCMPC_MINI
629                 {}
630 #else
631                 options.second_column = str2bool(value);
632 #endif
633         else
634                 throw FormatRuntimeError("%s: %s",
635                                          _("Unknown configuration parameter"),
636                                          name);
637 }
638
639 bool
640 ReadConfigFile(const char *filename)
641 {
642         assert(filename != nullptr);
643
644         FILE *file = fopen(filename, "r");
645         if (file == nullptr) {
646                 perror(filename);
647                 return false;
648         }
649
650         unsigned no = 0;
651         char line[MAX_LINE_LENGTH];
652         while (fgets(line, sizeof(line), file) != nullptr) {
653                 ++no;
654                 char *p = StripLeft(line);
655
656                 if (*p != 0 && *p != COMMENT_TOKEN) {
657                         StripRight(p);
658
659                         try {
660                                 parse_line(p);
661                         } catch (...) {
662                                 fprintf(stderr,
663                                         "Failed to parse '%s' line %u: ",
664                                         filename, no);
665                                 PrintException(std::current_exception());
666                         }
667                 }
668         }
669
670         fclose(file);
671         return true;
672 }