9485c7d74fa6414090978faa131dfb654e3cdf4a
[oweals/minetest.git] / src / settings.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser 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 "settings.h"
21 #include "irrlichttypes_bloated.h"
22 #include "exceptions.h"
23 #include "jthread/jmutexautolock.h"
24 #include "strfnd.h"
25 #include <iostream>
26 #include <fstream>
27 #include <sstream>
28 #include "debug.h"
29 #include "log.h"
30 #include "util/serialize.h"
31 #include "filesys.h"
32 #include <cctype>
33
34
35 Settings::~Settings()
36 {
37         std::map<std::string, SettingsEntry>::const_iterator it;
38         for (it = m_settings.begin(); it != m_settings.end(); ++it)
39                 delete it->second.group;
40 }
41
42
43 Settings & Settings::operator += (const Settings &other)
44 {
45         update(other);
46
47         return *this;
48 }
49
50
51 Settings & Settings::operator = (const Settings &other)
52 {
53         if (&other == this)
54                 return *this;
55
56         JMutexAutoLock lock(m_mutex);
57         JMutexAutoLock lock2(other.m_mutex);
58
59         clearNoLock();
60         updateNoLock(other);
61
62         return *this;
63 }
64
65
66 std::string Settings::getMultiline(std::istream &is)
67 {
68         std::string value;
69         std::string line;
70
71         while (is.good()) {
72                 std::getline(is, line);
73                 if (line == "\"\"\"")
74                         break;
75                 value += line;
76                 value.push_back('\n');
77         }
78
79         size_t len = value.size();
80         if (len)
81                 value.erase(len - 1);
82
83         return value;
84 }
85
86
87 bool Settings::parseConfigLines(std::istream &is, const std::string &end)
88 {
89         JMutexAutoLock lock(m_mutex);
90
91         std::string line, name, value;
92
93         while (is.good()) {
94                 std::getline(is, line);
95                 SettingsParseEvent event = parseConfigObject(line, end, name, value);
96
97                 switch (event) {
98                 case SPE_NONE:
99                 case SPE_INVALID:
100                 case SPE_COMMENT:
101                         break;
102                 case SPE_KVPAIR:
103                         m_settings[name] = SettingsEntry(value);
104                         break;
105                 case SPE_END:
106                         return true;
107                 case SPE_GROUP: {
108                         Settings *branch = new Settings;
109                         if (!branch->parseConfigLines(is, "}"))
110                                 return false;
111
112                         m_settings[name] = SettingsEntry(branch);
113                         break;
114                 }
115                 case SPE_MULTILINE:
116                         m_settings[name] = SettingsEntry(getMultiline(is));
117                         break;
118                 }
119         }
120
121         return end.empty();
122 }
123
124
125 bool Settings::readConfigFile(const char *filename)
126 {
127         std::ifstream is(filename);
128         if (!is.good())
129                 return false;
130
131         return parseConfigLines(is, "");
132 }
133
134
135 void Settings::writeLines(std::ostream &os, u32 tab_depth) const
136 {
137         JMutexAutoLock lock(m_mutex);
138
139         for (std::map<std::string, SettingsEntry>::const_iterator
140                         it = m_settings.begin();
141                         it != m_settings.end(); ++it) {
142                 bool is_multiline = it->second.value.find('\n') != std::string::npos;
143                 printValue(os, it->first, it->second, is_multiline, tab_depth);
144         }
145 }
146
147
148 void Settings::printValue(std::ostream &os, const std::string &name,
149         const SettingsEntry &entry, bool is_value_multiline, u32 tab_depth)
150 {
151         for (u32 i = 0; i != tab_depth; i++)
152                 os << "\t";
153         os << name << " = ";
154
155         if (is_value_multiline)
156                 os << "\"\"\"\n" << entry.value << "\n\"\"\"\n";
157         else
158                 os << entry.value << "\n";
159
160         Settings *group = entry.group;
161         if (group) {
162                 for (u32 i = 0; i != tab_depth; i++)
163                         os << "\t";
164
165                 os << name << " = {\n";
166                 group->writeLines(os, tab_depth + 1);
167
168                 for (u32 i = 0; i != tab_depth; i++)
169                         os << "\t";
170
171                 os << "}\n";
172         }
173 }
174
175
176 bool Settings::updateConfigObject(std::istream &is, std::ostream &os,
177         const std::string &end, u32 tab_depth)
178 {
179         std::map<std::string, SettingsEntry>::const_iterator it;
180         std::set<std::string> settings_in_config;
181         bool was_modified = false;
182         bool end_found = false;
183         std::string line, name, value;
184
185         // Add any settings that exist in the config file with the current value
186         // in the object if existing
187         while (is.good() && !end_found) {
188                 std::getline(is, line);
189                 SettingsParseEvent event = parseConfigObject(line, end, name, value);
190
191                 switch (event) {
192                 case SPE_END:
193                         end_found = true;
194                         break;
195                 case SPE_KVPAIR:
196                 case SPE_MULTILINE:
197                         it = m_settings.find(name);
198                         if (it != m_settings.end()) {
199                                 if (event == SPE_MULTILINE)
200                                         value = getMultiline(is);
201
202                                 if (value != it->second.value) {
203                                         value = it->second.value;
204                                         was_modified = true;
205                                 }
206                         }
207
208                         settings_in_config.insert(name);
209
210                         printValue(os, name, SettingsEntry(value),
211                                 event == SPE_MULTILINE, tab_depth);
212
213                         break;
214                 case SPE_GROUP: {
215                         Settings *group = NULL;
216                         it = m_settings.find(name);
217                         if (it != m_settings.end())
218                                 group = it->second.group;
219
220                         settings_in_config.insert(name);
221
222                         os << name << " = {\n";
223
224                         if (group) {
225                                 was_modified |= group->updateConfigObject(is, os, "}", tab_depth + 1);
226                         } else {
227                                 Settings dummy_settings;
228                                 dummy_settings.updateConfigObject(is, os, "}", tab_depth + 1);
229                         }
230
231                         for (u32 i = 0; i != tab_depth; i++)
232                                 os << "\t";
233                         os << "}\n";
234                         break;
235                 }
236                 default:
237                         os << line << (is.eof() ? "" : "\n");
238                         break;
239                 }
240         }
241
242         // Add any settings in the object that don't exist in the config file yet
243         for (it = m_settings.begin(); it != m_settings.end(); ++it) {
244                 if (settings_in_config.find(it->first) != settings_in_config.end())
245                         continue;
246
247                 was_modified = true;
248
249                 bool is_multiline = it->second.value.find('\n') != std::string::npos;
250                 printValue(os, it->first, it->second, is_multiline, tab_depth);
251         }
252
253         return was_modified;
254 }
255
256
257 bool Settings::updateConfigFile(const char *filename)
258 {
259         JMutexAutoLock lock(m_mutex);
260
261         std::ifstream is(filename);
262         std::ostringstream os(std::ios_base::binary);
263
264         if (!updateConfigObject(is, os, ""))
265                 return true;
266
267         if (!fs::safeWriteToFile(filename, os.str())) {
268                 errorstream << "Error writing configuration file: \""
269                         << filename << "\"" << std::endl;
270                 return false;
271         }
272
273         return true;
274 }
275
276
277 bool Settings::parseCommandLine(int argc, char *argv[],
278                 std::map<std::string, ValueSpec> &allowed_options)
279 {
280         int nonopt_index = 0;
281         for (int i = 1; i < argc; i++) {
282                 std::string arg_name = argv[i];
283                 if (arg_name.substr(0, 2) != "--") {
284                         // If option doesn't start with -, read it in as nonoptX
285                         if (arg_name[0] != '-'){
286                                 std::string name = "nonopt";
287                                 name += itos(nonopt_index);
288                                 set(name, arg_name);
289                                 nonopt_index++;
290                                 continue;
291                         }
292                         errorstream << "Invalid command-line parameter \""
293                                         << arg_name << "\": --<option> expected." << std::endl;
294                         return false;
295                 }
296
297                 std::string name = arg_name.substr(2);
298
299                 std::map<std::string, ValueSpec>::iterator n;
300                 n = allowed_options.find(name);
301                 if (n == allowed_options.end()) {
302                         errorstream << "Unknown command-line parameter \""
303                                         << arg_name << "\"" << std::endl;
304                         return false;
305                 }
306
307                 ValueType type = n->second.type;
308
309                 std::string value = "";
310
311                 if (type == VALUETYPE_FLAG) {
312                         value = "true";
313                 } else {
314                         if ((i + 1) >= argc) {
315                                 errorstream << "Invalid command-line parameter \""
316                                                 << name << "\": missing value" << std::endl;
317                                 return false;
318                         }
319                         value = argv[++i];
320                 }
321
322                 set(name, value);
323         }
324
325         return true;
326 }
327
328
329
330 /***********
331  * Getters *
332  ***********/
333
334
335 const SettingsEntry &Settings::getEntry(const std::string &name) const
336 {
337         JMutexAutoLock lock(m_mutex);
338
339         std::map<std::string, SettingsEntry>::const_iterator n;
340         if ((n = m_settings.find(name)) == m_settings.end()) {
341                 if ((n = m_defaults.find(name)) == m_defaults.end())
342                         throw SettingNotFoundException("Setting [" + name + "] not found.");
343         }
344         return n->second;
345 }
346
347
348 Settings *Settings::getGroup(const std::string &name) const
349 {
350         return getEntry(name).group;
351 }
352
353
354 std::string Settings::get(const std::string &name) const
355 {
356         return getEntry(name).value;
357 }
358
359
360 bool Settings::getBool(const std::string &name) const
361 {
362         return is_yes(get(name));
363 }
364
365
366 u16 Settings::getU16(const std::string &name) const
367 {
368         return stoi(get(name), 0, 65535);
369 }
370
371
372 s16 Settings::getS16(const std::string &name) const
373 {
374         return stoi(get(name), -32768, 32767);
375 }
376
377
378 s32 Settings::getS32(const std::string &name) const
379 {
380         return stoi(get(name));
381 }
382
383
384 float Settings::getFloat(const std::string &name) const
385 {
386         return stof(get(name));
387 }
388
389
390 u64 Settings::getU64(const std::string &name) const
391 {
392         u64 value = 0;
393         std::string s = get(name);
394         std::istringstream ss(s);
395         ss >> value;
396         return value;
397 }
398
399
400 v2f Settings::getV2F(const std::string &name) const
401 {
402         v2f value;
403         Strfnd f(get(name));
404         f.next("(");
405         value.X = stof(f.next(","));
406         value.Y = stof(f.next(")"));
407         return value;
408 }
409
410
411 v3f Settings::getV3F(const std::string &name) const
412 {
413         v3f value;
414         Strfnd f(get(name));
415         f.next("(");
416         value.X = stof(f.next(","));
417         value.Y = stof(f.next(","));
418         value.Z = stof(f.next(")"));
419         return value;
420 }
421
422
423 u32 Settings::getFlagStr(const std::string &name, const FlagDesc *flagdesc,
424         u32 *flagmask) const
425 {
426         std::string val = get(name);
427         return std::isdigit(val[0])
428                 ? stoi(val)
429                 : readFlagString(val, flagdesc, flagmask);
430 }
431
432
433 // N.B. if getStruct() is used to read a non-POD aggregate type,
434 // the behavior is undefined.
435 bool Settings::getStruct(const std::string &name, const std::string &format,
436         void *out, size_t olen) const
437 {
438         std::string valstr;
439
440         try {
441                 valstr = get(name);
442         } catch (SettingNotFoundException &e) {
443                 return false;
444         }
445
446         if (!deSerializeStringToStruct(valstr, format, out, olen))
447                 return false;
448
449         return true;
450 }
451
452
453 bool Settings::exists(const std::string &name) const
454 {
455         JMutexAutoLock lock(m_mutex);
456
457         return (m_settings.find(name) != m_settings.end() ||
458                 m_defaults.find(name) != m_defaults.end());
459 }
460
461
462 std::vector<std::string> Settings::getNames() const
463 {
464         std::vector<std::string> names;
465         for (std::map<std::string, SettingsEntry>::const_iterator
466                         i = m_settings.begin();
467                         i != m_settings.end(); ++i) {
468                 names.push_back(i->first);
469         }
470         return names;
471 }
472
473
474
475 /***************************************
476  * Getters that don't throw exceptions *
477  ***************************************/
478
479 bool Settings::getEntryNoEx(const std::string &name, SettingsEntry &val) const
480 {
481         try {
482                 val = getEntry(name);
483                 return true;
484         } catch (SettingNotFoundException &e) {
485                 return false;
486         }
487 }
488
489
490 bool Settings::getGroupNoEx(const std::string &name, Settings *&val) const
491 {
492         try {
493                 val = getGroup(name);
494                 return true;
495         } catch (SettingNotFoundException &e) {
496                 return false;
497         }
498 }
499
500
501 bool Settings::getNoEx(const std::string &name, std::string &val) const
502 {
503         try {
504                 val = get(name);
505                 return true;
506         } catch (SettingNotFoundException &e) {
507                 return false;
508         }
509 }
510
511
512 bool Settings::getFlag(const std::string &name) const
513 {
514         try {
515                 return getBool(name);
516         } catch(SettingNotFoundException &e) {
517                 return false;
518         }
519 }
520
521
522 bool Settings::getFloatNoEx(const std::string &name, float &val) const
523 {
524         try {
525                 val = getFloat(name);
526                 return true;
527         } catch (SettingNotFoundException &e) {
528                 return false;
529         }
530 }
531
532
533 bool Settings::getU16NoEx(const std::string &name, u16 &val) const
534 {
535         try {
536                 val = getU16(name);
537                 return true;
538         } catch (SettingNotFoundException &e) {
539                 return false;
540         }
541 }
542
543
544 bool Settings::getS16NoEx(const std::string &name, s16 &val) const
545 {
546         try {
547                 val = getS16(name);
548                 return true;
549         } catch (SettingNotFoundException &e) {
550                 return false;
551         }
552 }
553
554
555 bool Settings::getS32NoEx(const std::string &name, s32 &val) const
556 {
557         try {
558                 val = getS32(name);
559                 return true;
560         } catch (SettingNotFoundException &e) {
561                 return false;
562         }
563 }
564
565
566 bool Settings::getU64NoEx(const std::string &name, u64 &val) const
567 {
568         try {
569                 val = getU64(name);
570                 return true;
571         } catch (SettingNotFoundException &e) {
572                 return false;
573         }
574 }
575
576
577 bool Settings::getV2FNoEx(const std::string &name, v2f &val) const
578 {
579         try {
580                 val = getV2F(name);
581                 return true;
582         } catch (SettingNotFoundException &e) {
583                 return false;
584         }
585 }
586
587
588 bool Settings::getV3FNoEx(const std::string &name, v3f &val) const
589 {
590         try {
591                 val = getV3F(name);
592                 return true;
593         } catch (SettingNotFoundException &e) {
594                 return false;
595         }
596 }
597
598
599 // N.B. getFlagStrNoEx() does not set val, but merely modifies it.  Thus,
600 // val must be initialized before using getFlagStrNoEx().  The intention of
601 // this is to simplify modifying a flags field from a default value.
602 bool Settings::getFlagStrNoEx(const std::string &name, u32 &val,
603         FlagDesc *flagdesc) const
604 {
605         try {
606                 u32 flags, flagmask;
607
608                 flags = getFlagStr(name, flagdesc, &flagmask);
609
610                 val &= ~flagmask;
611                 val |=  flags;
612
613                 return true;
614         } catch (SettingNotFoundException &e) {
615                 return false;
616         }
617 }
618
619
620 /***********
621  * Setters *
622  ***********/
623
624
625 void Settings::set(const std::string &name, const std::string &value)
626 {
627         JMutexAutoLock lock(m_mutex);
628
629         m_settings[name].value = value;
630 }
631
632
633 void Settings::setGroup(const std::string &name, Settings *group)
634 {
635         JMutexAutoLock lock(m_mutex);
636
637         delete m_settings[name].group;
638         m_settings[name].group = group;
639 }
640
641
642 void Settings::setDefault(const std::string &name, const std::string &value)
643 {
644         JMutexAutoLock lock(m_mutex);
645
646         m_defaults[name].value = value;
647 }
648
649
650 void Settings::setGroupDefault(const std::string &name, Settings *group)
651 {
652         JMutexAutoLock lock(m_mutex);
653
654         delete m_defaults[name].group;
655         m_defaults[name].group = group;
656 }
657
658
659 void Settings::setBool(const std::string &name, bool value)
660 {
661         set(name, value ? "true" : "false");
662 }
663
664
665 void Settings::setS16(const std::string &name, s16 value)
666 {
667         set(name, itos(value));
668 }
669
670
671 void Settings::setS32(const std::string &name, s32 value)
672 {
673         set(name, itos(value));
674 }
675
676
677 void Settings::setU64(const std::string &name, u64 value)
678 {
679         std::ostringstream os;
680         os << value;
681         set(name, os.str());
682 }
683
684
685 void Settings::setFloat(const std::string &name, float value)
686 {
687         set(name, ftos(value));
688 }
689
690
691 void Settings::setV2F(const std::string &name, v2f value)
692 {
693         std::ostringstream os;
694         os << "(" << value.X << "," << value.Y << ")";
695         set(name, os.str());
696 }
697
698
699 void Settings::setV3F(const std::string &name, v3f value)
700 {
701         std::ostringstream os;
702         os << "(" << value.X << "," << value.Y << "," << value.Z << ")";
703         set(name, os.str());
704 }
705
706
707 void Settings::setFlagStr(const std::string &name, u32 flags,
708         const FlagDesc *flagdesc, u32 flagmask)
709 {
710         set(name, writeFlagString(flags, flagdesc, flagmask));
711 }
712
713
714 bool Settings::setStruct(const std::string &name, const std::string &format,
715         void *value)
716 {
717         std::string structstr;
718         if (!serializeStructToString(&structstr, format, value))
719                 return false;
720
721         set(name, structstr);
722         return true;
723 }
724
725
726 bool Settings::remove(const std::string &name)
727 {
728         JMutexAutoLock lock(m_mutex);
729         return m_settings.erase(name);
730 }
731
732
733 void Settings::clear()
734 {
735         JMutexAutoLock lock(m_mutex);
736         clearNoLock();
737 }
738
739
740 void Settings::updateValue(const Settings &other, const std::string &name)
741 {
742         if (&other == this)
743                 return;
744
745         JMutexAutoLock lock(m_mutex);
746
747         try {
748                 std::string val = other.get(name);
749
750                 m_settings[name] = val;
751         } catch (SettingNotFoundException &e) {
752         }
753 }
754
755
756 void Settings::update(const Settings &other)
757 {
758         if (&other == this)
759                 return;
760
761         JMutexAutoLock lock(m_mutex);
762         JMutexAutoLock lock2(other.m_mutex);
763
764         updateNoLock(other);
765 }
766
767
768 SettingsParseEvent Settings::parseConfigObject(const std::string &line,
769         const std::string &end, std::string &name, std::string &value)
770 {
771         std::string trimmed_line = trim(line);
772
773         if (trimmed_line.empty())
774                 return SPE_NONE;
775         if (trimmed_line[0] == '#')
776                 return SPE_COMMENT;
777         if (trimmed_line == end)
778                 return SPE_END;
779
780         size_t pos = trimmed_line.find('=');
781         if (pos == std::string::npos)
782                 return SPE_INVALID;
783
784         name  = trim(trimmed_line.substr(0, pos));
785         value = trim(trimmed_line.substr(pos + 1));
786
787         if (value == "{")
788                 return SPE_GROUP;
789         if (value == "\"\"\"")
790                 return SPE_MULTILINE;
791
792         return SPE_KVPAIR;
793 }
794
795
796 void Settings::updateNoLock(const Settings &other)
797 {
798         m_settings.insert(other.m_settings.begin(), other.m_settings.end());
799         m_defaults.insert(other.m_defaults.begin(), other.m_defaults.end());
800 }
801
802
803 void Settings::clearNoLock()
804 {
805         m_settings.clear();
806         m_defaults.clear();
807 }
808
809
810 void Settings::registerChangedCallback(std::string name,
811         setting_changed_callback cbf)
812 {
813         m_callbacks[name].push_back(cbf);
814 }
815
816
817 void Settings::doCallbacks(const std::string name)
818 {
819         std::vector<setting_changed_callback> tempvector;
820         {
821                 JMutexAutoLock lock(m_mutex);
822                 if (m_callbacks.find(name) != m_callbacks.end())
823                 {
824                         tempvector = m_callbacks[name];
825                 }
826         }
827
828         for (std::vector<setting_changed_callback>::iterator iter = tempvector.begin();
829                         iter != tempvector.end(); iter ++)
830         {
831                 (*iter)(name);
832         }
833 }