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