]> git.lizzy.rs Git - dragonfireclient.git/blob - src/settings.cpp
Improve LBMManager::applyLBMs() code
[dragonfireclient.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 "threading/mutex_auto_lock.h"
24 #include "util/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 Settings *g_settings = nullptr;
37 static SettingsHierarchy g_hierarchy;
38 std::string g_settings_path;
39
40 std::unordered_map<std::string, const FlagDesc *> Settings::s_flags;
41
42 /* Settings hierarchy implementation */
43
44 SettingsHierarchy::SettingsHierarchy(Settings *fallback)
45 {
46         layers.push_back(fallback);
47 }
48
49
50 Settings *SettingsHierarchy::getLayer(int layer) const
51 {
52         if (layer < 0 || layer >= (int)layers.size())
53                 throw BaseException("Invalid settings layer");
54         return layers[layer];
55 }
56
57
58 Settings *SettingsHierarchy::getParent(int layer) const
59 {
60         assert(layer >= 0 && layer < (int)layers.size());
61         // iterate towards the origin (0) to find the next fallback layer
62         for (int i = layer - 1; i >= 0; --i) {
63                 if (layers[i])
64                         return layers[i];
65         }
66
67         return nullptr;
68 }
69
70
71 void SettingsHierarchy::onLayerCreated(int layer, Settings *obj)
72 {
73         if (layer < 0)
74                 throw BaseException("Invalid settings layer");
75         if ((int)layers.size() < layer + 1)
76                 layers.resize(layer + 1);
77
78         Settings *&pos = layers[layer];
79         if (pos)
80                 throw BaseException("Setting layer " + itos(layer) + " already exists");
81
82         pos = obj;
83         // This feels bad
84         if (this == &g_hierarchy && layer == (int)SL_GLOBAL)
85                 g_settings = obj;
86 }
87
88
89 void SettingsHierarchy::onLayerRemoved(int layer)
90 {
91         assert(layer >= 0 && layer < (int)layers.size());
92         layers[layer] = nullptr;
93         if (this == &g_hierarchy && layer == (int)SL_GLOBAL)
94                 g_settings = nullptr;
95 }
96
97 /* Settings implementation */
98
99 Settings *Settings::createLayer(SettingsLayer sl, const std::string &end_tag)
100 {
101         return new Settings(end_tag, &g_hierarchy, (int)sl);
102 }
103
104
105 Settings *Settings::getLayer(SettingsLayer sl)
106 {
107         return g_hierarchy.getLayer(sl);
108 }
109
110
111 Settings::Settings(const std::string &end_tag, SettingsHierarchy *h,
112                 int settings_layer) :
113         m_end_tag(end_tag),
114         m_hierarchy(h),
115         m_settingslayer(settings_layer)
116 {
117         if (m_hierarchy)
118                 m_hierarchy->onLayerCreated(m_settingslayer, this);
119 }
120
121
122 Settings::~Settings()
123 {
124         MutexAutoLock lock(m_mutex);
125
126         if (m_hierarchy)
127                 m_hierarchy->onLayerRemoved(m_settingslayer);
128
129         clearNoLock();
130 }
131
132
133 Settings & Settings::operator = (const Settings &other)
134 {
135         if (&other == this)
136                 return *this;
137
138         // TODO: Avoid copying Settings objects. Make this private.
139         FATAL_ERROR_IF(m_hierarchy || other.m_hierarchy,
140                 "Cannot copy or overwrite Settings object that belongs to a hierarchy");
141
142         MutexAutoLock lock(m_mutex);
143         MutexAutoLock lock2(other.m_mutex);
144
145         clearNoLock();
146         m_settings = other.m_settings;
147         m_callbacks = other.m_callbacks;
148
149         return *this;
150 }
151
152
153 bool Settings::checkNameValid(const std::string &name)
154 {
155         bool valid = name.find_first_of("=\"{}#") == std::string::npos;
156         if (valid)
157                 valid = std::find_if(name.begin(), name.end(), ::isspace) == name.end();
158
159         if (!valid) {
160                 errorstream << "Invalid setting name \"" << name << "\""
161                         << std::endl;
162                 return false;
163         }
164         return true;
165 }
166
167
168 bool Settings::checkValueValid(const std::string &value)
169 {
170         if (value.substr(0, 3) == "\"\"\"" ||
171                 value.find("\n\"\"\"") != std::string::npos) {
172                 errorstream << "Invalid character sequence '\"\"\"' found in"
173                         " setting value!" << std::endl;
174                 return false;
175         }
176         return true;
177 }
178
179 std::string Settings::getMultiline(std::istream &is, size_t *num_lines)
180 {
181         size_t lines = 1;
182         std::string value;
183         std::string line;
184
185         while (is.good()) {
186                 lines++;
187                 std::getline(is, line);
188                 if (line == "\"\"\"")
189                         break;
190                 value += line;
191                 value.push_back('\n');
192         }
193
194         size_t len = value.size();
195         if (len)
196                 value.erase(len - 1);
197
198         if (num_lines)
199                 *num_lines = lines;
200
201         return value;
202 }
203
204
205 bool Settings::readConfigFile(const char *filename)
206 {
207         std::ifstream is(filename);
208         if (!is.good())
209                 return false;
210
211         return parseConfigLines(is);
212 }
213
214
215 bool Settings::parseConfigLines(std::istream &is)
216 {
217         MutexAutoLock lock(m_mutex);
218
219         std::string line, name, value;
220
221         while (is.good()) {
222                 std::getline(is, line);
223                 SettingsParseEvent event = parseConfigObject(line, name, value);
224
225                 switch (event) {
226                 case SPE_NONE:
227                 case SPE_INVALID:
228                 case SPE_COMMENT:
229                         break;
230                 case SPE_KVPAIR:
231                         m_settings[name] = SettingsEntry(value);
232                         break;
233                 case SPE_END:
234                         return true;
235                 case SPE_GROUP: {
236                         Settings *group = new Settings("}");
237                         if (!group->parseConfigLines(is)) {
238                                 delete group;
239                                 return false;
240                         }
241                         m_settings[name] = SettingsEntry(group);
242                         break;
243                 }
244                 case SPE_MULTILINE:
245                         m_settings[name] = SettingsEntry(getMultiline(is));
246                         break;
247                 }
248         }
249
250         // false (failure) if end tag not found
251         return m_end_tag.empty();
252 }
253
254
255 void Settings::writeLines(std::ostream &os, u32 tab_depth) const
256 {
257         MutexAutoLock lock(m_mutex);
258
259         for (const auto &setting_it : m_settings)
260                 printEntry(os, setting_it.first, setting_it.second, tab_depth);
261
262         // For groups this must be "}" !
263         if (!m_end_tag.empty()) {
264                 for (u32 i = 0; i < tab_depth; i++)
265                         os << "\t";
266
267                 os << m_end_tag << "\n";
268         }
269 }
270
271
272 void Settings::printEntry(std::ostream &os, const std::string &name,
273         const SettingsEntry &entry, u32 tab_depth)
274 {
275         for (u32 i = 0; i != tab_depth; i++)
276                 os << "\t";
277
278         if (entry.is_group) {
279                 os << name << " = {\n";
280
281                 entry.group->writeLines(os, tab_depth + 1);
282
283                 // Closing bracket handled by writeLines
284         } else {
285                 os << name << " = ";
286
287                 if (entry.value.find('\n') != std::string::npos)
288                         os << "\"\"\"\n" << entry.value << "\n\"\"\"\n";
289                 else
290                         os << entry.value << "\n";
291         }
292 }
293
294
295 bool Settings::updateConfigObject(std::istream &is, std::ostream &os, u32 tab_depth)
296 {
297         SettingEntries::const_iterator it;
298         std::set<std::string> present_entries;
299         std::string line, name, value;
300         bool was_modified = false;
301         bool end_found = false;
302
303         // Add any settings that exist in the config file with the current value
304         // in the object if existing
305         while (is.good() && !end_found) {
306                 std::getline(is, line);
307                 SettingsParseEvent event = parseConfigObject(line, name, value);
308
309                 switch (event) {
310                 case SPE_END:
311                         // Skip end tag. Append later.
312                         end_found = true;
313                         break;
314                 case SPE_MULTILINE:
315                         value = getMultiline(is);
316                         /* FALLTHROUGH */
317                 case SPE_KVPAIR:
318                         it = m_settings.find(name);
319                         if (it != m_settings.end() &&
320                                         (it->second.is_group || it->second.value != value)) {
321                                 printEntry(os, name, it->second, tab_depth);
322                                 was_modified = true;
323                         } else if (it == m_settings.end()) {
324                                 // Remove by skipping
325                                 was_modified = true;
326                                 break;
327                         } else {
328                                 os << line << "\n";
329                                 if (event == SPE_MULTILINE)
330                                         os << value << "\n\"\"\"\n";
331                         }
332                         present_entries.insert(name);
333                         break;
334                 case SPE_GROUP:
335                         it = m_settings.find(name);
336                         if (it != m_settings.end() && it->second.is_group) {
337                                 os << line << "\n";
338                                 sanity_check(it->second.group != NULL);
339                                 was_modified |= it->second.group->updateConfigObject(is, os, tab_depth + 1);
340                         } else if (it == m_settings.end()) {
341                                 // Remove by skipping
342                                 was_modified = true;
343                                 Settings removed_group("}"); // Move 'is' to group end
344                                 std::stringstream ss;
345                                 removed_group.updateConfigObject(is, ss, tab_depth + 1);
346                                 break;
347                         } else {
348                                 printEntry(os, name, it->second, tab_depth);
349                                 was_modified = true;
350                         }
351                         present_entries.insert(name);
352                         break;
353                 default:
354                         os << line << (is.eof() ? "" : "\n");
355                         break;
356                 }
357         }
358
359         if (!line.empty() && is.eof())
360                 os << "\n";
361
362         // Add any settings in the object that don't exist in the config file yet
363         for (it = m_settings.begin(); it != m_settings.end(); ++it) {
364                 if (present_entries.find(it->first) != present_entries.end())
365                         continue;
366
367                 printEntry(os, it->first, it->second, tab_depth);
368                 was_modified = true;
369         }
370
371         // Append ending tag
372         if (!m_end_tag.empty()) {
373                 os << m_end_tag << "\n";
374                 was_modified |= !end_found;
375         }
376
377         return was_modified;
378 }
379
380
381 bool Settings::updateConfigFile(const char *filename)
382 {
383         MutexAutoLock lock(m_mutex);
384
385         std::ifstream is(filename);
386         std::ostringstream os(std::ios_base::binary);
387
388         bool was_modified = updateConfigObject(is, os);
389         is.close();
390
391         if (!was_modified)
392                 return true;
393
394         if (!fs::safeWriteToFile(filename, os.str())) {
395                 errorstream << "Error writing configuration file: \""
396                         << filename << "\"" << std::endl;
397                 return false;
398         }
399
400         return true;
401 }
402
403
404 bool Settings::parseCommandLine(int argc, char *argv[],
405                 std::map<std::string, ValueSpec> &allowed_options)
406 {
407         int nonopt_index = 0;
408         for (int i = 1; i < argc; i++) {
409                 std::string arg_name = argv[i];
410                 if (arg_name.substr(0, 2) != "--") {
411                         // If option doesn't start with -, read it in as nonoptX
412                         if (arg_name[0] != '-'){
413                                 std::string name = "nonopt";
414                                 name += itos(nonopt_index);
415                                 set(name, arg_name);
416                                 nonopt_index++;
417                                 continue;
418                         }
419                         errorstream << "Invalid command-line parameter \""
420                                         << arg_name << "\": --<option> expected." << std::endl;
421                         return false;
422                 }
423
424                 std::string name = arg_name.substr(2);
425
426                 std::map<std::string, ValueSpec>::iterator n;
427                 n = allowed_options.find(name);
428                 if (n == allowed_options.end()) {
429                         errorstream << "Unknown command-line parameter \""
430                                         << arg_name << "\"" << std::endl;
431                         return false;
432                 }
433
434                 ValueType type = n->second.type;
435
436                 std::string value;
437
438                 if (type == VALUETYPE_FLAG) {
439                         value = "true";
440                 } else {
441                         if ((i + 1) >= argc) {
442                                 errorstream << "Invalid command-line parameter \""
443                                                 << name << "\": missing value" << std::endl;
444                                 return false;
445                         }
446                         value = argv[++i];
447                 }
448
449                 set(name, value);
450         }
451
452         return true;
453 }
454
455
456
457 /***********
458  * Getters *
459  ***********/
460
461 Settings *Settings::getParent() const
462 {
463         return m_hierarchy ? m_hierarchy->getParent(m_settingslayer) : nullptr;
464 }
465
466
467 const SettingsEntry &Settings::getEntry(const std::string &name) const
468 {
469         {
470                 MutexAutoLock lock(m_mutex);
471
472                 SettingEntries::const_iterator n;
473                 if ((n = m_settings.find(name)) != m_settings.end())
474                         return n->second;
475         }
476
477         if (auto parent = getParent())
478                 return parent->getEntry(name);
479
480         throw SettingNotFoundException("Setting [" + name + "] not found.");
481 }
482
483
484 Settings *Settings::getGroup(const std::string &name) const
485 {
486         const SettingsEntry &entry = getEntry(name);
487         if (!entry.is_group)
488                 throw SettingNotFoundException("Setting [" + name + "] is not a group.");
489         return entry.group;
490 }
491
492
493 const std::string &Settings::get(const std::string &name) const
494 {
495         const SettingsEntry &entry = getEntry(name);
496         if (entry.is_group)
497                 throw SettingNotFoundException("Setting [" + name + "] is a group.");
498         return entry.value;
499 }
500
501
502 bool Settings::getBool(const std::string &name) const
503 {
504         return is_yes(get(name));
505 }
506
507
508 u16 Settings::getU16(const std::string &name) const
509 {
510         return stoi(get(name), 0, 65535);
511 }
512
513
514 s16 Settings::getS16(const std::string &name) const
515 {
516         return stoi(get(name), -32768, 32767);
517 }
518
519
520 u32 Settings::getU32(const std::string &name) const
521 {
522         return (u32) stoi(get(name));
523 }
524
525 s32 Settings::getS32(const std::string &name) const
526 {
527         return stoi(get(name));
528 }
529
530
531 float Settings::getFloat(const std::string &name) const
532 {
533         return stof(get(name));
534 }
535
536
537 u64 Settings::getU64(const std::string &name) const
538 {
539         std::string s = get(name);
540         return from_string<u64>(s);
541 }
542
543
544 v2f Settings::getV2F(const std::string &name) const
545 {
546         v2f value;
547         Strfnd f(get(name));
548         f.next("(");
549         value.X = stof(f.next(","));
550         value.Y = stof(f.next(")"));
551         return value;
552 }
553
554
555 v3f Settings::getV3F(const std::string &name) const
556 {
557         v3f value;
558         Strfnd f(get(name));
559         f.next("(");
560         value.X = stof(f.next(","));
561         value.Y = stof(f.next(","));
562         value.Z = stof(f.next(")"));
563         return value;
564 }
565
566
567 u32 Settings::getFlagStr(const std::string &name, const FlagDesc *flagdesc,
568         u32 *flagmask) const
569 {
570         u32 flags = 0;
571
572         // Read default value (if there is any)
573         if (auto parent = getParent())
574                 flags = parent->getFlagStr(name, flagdesc, flagmask);
575
576         // Apply custom flags "on top"
577         if (m_settings.find(name) != m_settings.end()) {
578                 std::string value = get(name);
579                 u32 flags_user;
580                 u32 mask_user = U32_MAX;
581                 flags_user = std::isdigit(value[0])
582                         ? stoi(value) // Override default
583                         : readFlagString(value, flagdesc, &mask_user);
584
585                 flags &= ~mask_user;
586                 flags |=  flags_user;
587                 if (flagmask)
588                         *flagmask |= mask_user;
589         }
590
591         return flags;
592 }
593
594
595 bool Settings::getNoiseParams(const std::string &name, NoiseParams &np) const
596 {
597         if (getNoiseParamsFromGroup(name, np) || getNoiseParamsFromValue(name, np))
598                 return true;
599         if (auto parent = getParent())
600                 return parent->getNoiseParams(name, np);
601
602         return false;
603 }
604
605
606 bool Settings::getNoiseParamsFromValue(const std::string &name,
607         NoiseParams &np) const
608 {
609         std::string value;
610
611         if (!getNoEx(name, value))
612                 return false;
613
614         // Format: f32,f32,(f32,f32,f32),s32,s32,f32[,f32]
615         Strfnd f(value);
616
617         np.offset   = stof(f.next(","));
618         np.scale    = stof(f.next(","));
619         f.next("(");
620         np.spread.X = stof(f.next(","));
621         np.spread.Y = stof(f.next(","));
622         np.spread.Z = stof(f.next(")"));
623         f.next(",");
624         np.seed     = stoi(f.next(","));
625         np.octaves  = stoi(f.next(","));
626         np.persist  = stof(f.next(","));
627
628         std::string optional_params = f.next("");
629         if (!optional_params.empty())
630                 np.lacunarity = stof(optional_params);
631
632         return true;
633 }
634
635
636 bool Settings::getNoiseParamsFromGroup(const std::string &name,
637         NoiseParams &np) const
638 {
639         Settings *group = NULL;
640
641         if (!getGroupNoEx(name, group))
642                 return false;
643
644         group->getFloatNoEx("offset",      np.offset);
645         group->getFloatNoEx("scale",       np.scale);
646         group->getV3FNoEx("spread",        np.spread);
647         group->getS32NoEx("seed",          np.seed);
648         group->getU16NoEx("octaves",       np.octaves);
649         group->getFloatNoEx("persistence", np.persist);
650         group->getFloatNoEx("lacunarity",  np.lacunarity);
651
652         np.flags = 0;
653         if (!group->getFlagStrNoEx("flags", np.flags, flagdesc_noiseparams))
654                 np.flags = NOISE_FLAG_DEFAULTS;
655
656         return true;
657 }
658
659
660 bool Settings::exists(const std::string &name) const
661 {
662         if (existsLocal(name))
663                 return true;
664         if (auto parent = getParent())
665                 return parent->exists(name);
666         return false;
667 }
668
669
670 bool Settings::existsLocal(const std::string &name) const
671 {
672         MutexAutoLock lock(m_mutex);
673
674         return m_settings.find(name) != m_settings.end();
675 }
676
677
678 std::vector<std::string> Settings::getNames() const
679 {
680         MutexAutoLock lock(m_mutex);
681
682         std::vector<std::string> names;
683         names.reserve(m_settings.size());
684         for (const auto &settings_it : m_settings) {
685                 names.push_back(settings_it.first);
686         }
687         return names;
688 }
689
690
691
692 /***************************************
693  * Getters that don't throw exceptions *
694  ***************************************/
695
696 bool Settings::getGroupNoEx(const std::string &name, Settings *&val) const
697 {
698         try {
699                 val = getGroup(name);
700                 return true;
701         } catch (SettingNotFoundException &e) {
702                 return false;
703         }
704 }
705
706
707 bool Settings::getNoEx(const std::string &name, std::string &val) const
708 {
709         try {
710                 val = get(name);
711                 return true;
712         } catch (SettingNotFoundException &e) {
713                 return false;
714         }
715 }
716
717
718 bool Settings::getFlag(const std::string &name) const
719 {
720         try {
721                 return getBool(name);
722         } catch(SettingNotFoundException &e) {
723                 return false;
724         }
725 }
726
727
728 bool Settings::getFloatNoEx(const std::string &name, float &val) const
729 {
730         try {
731                 val = getFloat(name);
732                 return true;
733         } catch (SettingNotFoundException &e) {
734                 return false;
735         }
736 }
737
738
739 bool Settings::getU16NoEx(const std::string &name, u16 &val) const
740 {
741         try {
742                 val = getU16(name);
743                 return true;
744         } catch (SettingNotFoundException &e) {
745                 return false;
746         }
747 }
748
749
750 bool Settings::getS16NoEx(const std::string &name, s16 &val) const
751 {
752         try {
753                 val = getS16(name);
754                 return true;
755         } catch (SettingNotFoundException &e) {
756                 return false;
757         }
758 }
759
760 bool Settings::getU32NoEx(const std::string &name, u32 &val) const
761 {
762         try {
763                 val = getU32(name);
764                 return true;
765         } catch (SettingNotFoundException &e) {
766                 return false;
767         }
768 }
769
770 bool Settings::getS32NoEx(const std::string &name, s32 &val) const
771 {
772         try {
773                 val = getS32(name);
774                 return true;
775         } catch (SettingNotFoundException &e) {
776                 return false;
777         }
778 }
779
780
781 bool Settings::getU64NoEx(const std::string &name, u64 &val) const
782 {
783         try {
784                 val = getU64(name);
785                 return true;
786         } catch (SettingNotFoundException &e) {
787                 return false;
788         }
789 }
790
791
792 bool Settings::getV2FNoEx(const std::string &name, v2f &val) const
793 {
794         try {
795                 val = getV2F(name);
796                 return true;
797         } catch (SettingNotFoundException &e) {
798                 return false;
799         }
800 }
801
802
803 bool Settings::getV3FNoEx(const std::string &name, v3f &val) const
804 {
805         try {
806                 val = getV3F(name);
807                 return true;
808         } catch (SettingNotFoundException &e) {
809                 return false;
810         }
811 }
812
813
814 bool Settings::getFlagStrNoEx(const std::string &name, u32 &val,
815         const FlagDesc *flagdesc) const
816 {
817         if (!flagdesc) {
818                 if (!(flagdesc = getFlagDescFallback(name)))
819                         return false; // Not found
820         }
821
822         try {
823                 val = getFlagStr(name, flagdesc, nullptr);
824
825                 return true;
826         } catch (SettingNotFoundException &e) {
827                 return false;
828         }
829 }
830
831
832 /***********
833  * Setters *
834  ***********/
835
836 bool Settings::setEntry(const std::string &name, const void *data,
837         bool set_group)
838 {
839         if (!checkNameValid(name))
840                 return false;
841         if (!set_group && !checkValueValid(*(const std::string *)data))
842                 return false;
843
844         Settings *old_group = NULL;
845         {
846                 MutexAutoLock lock(m_mutex);
847
848                 SettingsEntry &entry = m_settings[name];
849                 old_group = entry.group;
850
851                 entry.value    = set_group ? "" : *(const std::string *)data;
852                 entry.group    = set_group ? *(Settings **)data : NULL;
853                 entry.is_group = set_group;
854                 if (set_group)
855                         entry.group->m_end_tag = "}";
856         }
857
858         delete old_group;
859
860         return true;
861 }
862
863
864 bool Settings::set(const std::string &name, const std::string &value)
865 {
866         if (!setEntry(name, &value, false))
867                 return false;
868
869         doCallbacks(name);
870         return true;
871 }
872
873
874 // TODO: Remove this function
875 bool Settings::setDefault(const std::string &name, const std::string &value)
876 {
877         FATAL_ERROR_IF(m_hierarchy != &g_hierarchy, "setDefault is only valid on "
878                 "global settings");
879         return getLayer(SL_DEFAULTS)->set(name, value);
880 }
881
882
883 bool Settings::setGroup(const std::string &name, const Settings &group)
884 {
885         // Settings must own the group pointer
886         // avoid double-free by copying the source
887         Settings *copy = new Settings();
888         *copy = group;
889         return setEntry(name, &copy, true);
890 }
891
892
893 bool Settings::setBool(const std::string &name, bool value)
894 {
895         return set(name, value ? "true" : "false");
896 }
897
898
899 bool Settings::setS16(const std::string &name, s16 value)
900 {
901         return set(name, itos(value));
902 }
903
904
905 bool Settings::setU16(const std::string &name, u16 value)
906 {
907         return set(name, itos(value));
908 }
909
910
911 bool Settings::setS32(const std::string &name, s32 value)
912 {
913         return set(name, itos(value));
914 }
915
916
917 bool Settings::setU64(const std::string &name, u64 value)
918 {
919         std::ostringstream os;
920         os << value;
921         return set(name, os.str());
922 }
923
924
925 bool Settings::setFloat(const std::string &name, float value)
926 {
927         return set(name, ftos(value));
928 }
929
930
931 bool Settings::setV2F(const std::string &name, v2f value)
932 {
933         std::ostringstream os;
934         os << "(" << value.X << "," << value.Y << ")";
935         return set(name, os.str());
936 }
937
938
939 bool Settings::setV3F(const std::string &name, v3f value)
940 {
941         std::ostringstream os;
942         os << "(" << value.X << "," << value.Y << "," << value.Z << ")";
943         return set(name, os.str());
944 }
945
946
947 bool Settings::setFlagStr(const std::string &name, u32 flags,
948         const FlagDesc *flagdesc, u32 flagmask)
949 {
950         if (!flagdesc) {
951                 if (!(flagdesc = getFlagDescFallback(name)))
952                         return false; // Not found
953         }
954
955         return set(name, writeFlagString(flags, flagdesc, flagmask));
956 }
957
958
959 bool Settings::setNoiseParams(const std::string &name, const NoiseParams &np)
960 {
961         Settings *group = new Settings;
962
963         group->setFloat("offset",      np.offset);
964         group->setFloat("scale",       np.scale);
965         group->setV3F("spread",        np.spread);
966         group->setS32("seed",          np.seed);
967         group->setU16("octaves",       np.octaves);
968         group->setFloat("persistence", np.persist);
969         group->setFloat("lacunarity",  np.lacunarity);
970         group->setFlagStr("flags",     np.flags, flagdesc_noiseparams, np.flags);
971
972         return setEntry(name, &group, true);
973 }
974
975
976 bool Settings::remove(const std::string &name)
977 {
978         // Lock as short as possible, unlock before doCallbacks()
979         m_mutex.lock();
980
981         SettingEntries::iterator it = m_settings.find(name);
982         if (it != m_settings.end()) {
983                 delete it->second.group;
984                 m_settings.erase(it);
985                 m_mutex.unlock();
986
987                 doCallbacks(name);
988                 return true;
989         }
990
991         m_mutex.unlock();
992         return false;
993 }
994
995
996 SettingsParseEvent Settings::parseConfigObject(const std::string &line,
997         std::string &name, std::string &value)
998 {
999         std::string trimmed_line = trim(line);
1000
1001         if (trimmed_line.empty())
1002                 return SPE_NONE;
1003         if (trimmed_line[0] == '#')
1004                 return SPE_COMMENT;
1005         if (trimmed_line == m_end_tag)
1006                 return SPE_END;
1007
1008         size_t pos = trimmed_line.find('=');
1009         if (pos == std::string::npos)
1010                 return SPE_INVALID;
1011
1012         name  = trim(trimmed_line.substr(0, pos));
1013         value = trim(trimmed_line.substr(pos + 1));
1014
1015         if (value == "{")
1016                 return SPE_GROUP;
1017         if (value == "\"\"\"")
1018                 return SPE_MULTILINE;
1019
1020         return SPE_KVPAIR;
1021 }
1022
1023
1024 void Settings::clearNoLock()
1025 {
1026         for (SettingEntries::const_iterator it = m_settings.begin();
1027                         it != m_settings.end(); ++it)
1028                 delete it->second.group;
1029         m_settings.clear();
1030 }
1031
1032
1033 void Settings::setDefault(const std::string &name, const FlagDesc *flagdesc,
1034         u32 flags)
1035 {
1036         s_flags[name] = flagdesc;
1037         setDefault(name, writeFlagString(flags, flagdesc, U32_MAX));
1038 }
1039
1040 const FlagDesc *Settings::getFlagDescFallback(const std::string &name) const
1041 {
1042         auto it = s_flags.find(name);
1043         return it == s_flags.end() ? nullptr : it->second;
1044 }
1045
1046 void Settings::registerChangedCallback(const std::string &name,
1047         SettingsChangedCallback cbf, void *userdata)
1048 {
1049         MutexAutoLock lock(m_callback_mutex);
1050         m_callbacks[name].emplace_back(cbf, userdata);
1051 }
1052
1053 void Settings::deregisterChangedCallback(const std::string &name,
1054         SettingsChangedCallback cbf, void *userdata)
1055 {
1056         MutexAutoLock lock(m_callback_mutex);
1057         SettingsCallbackMap::iterator it_cbks = m_callbacks.find(name);
1058
1059         if (it_cbks != m_callbacks.end()) {
1060                 SettingsCallbackList &cbks = it_cbks->second;
1061
1062                 SettingsCallbackList::iterator position =
1063                         std::find(cbks.begin(), cbks.end(), std::make_pair(cbf, userdata));
1064
1065                 if (position != cbks.end())
1066                         cbks.erase(position);
1067         }
1068 }
1069
1070 void Settings::removeSecureSettings()
1071 {
1072         for (const auto &name : getNames()) {
1073                 if (name.compare(0, 7, "secure.") != 0)
1074                         continue;
1075
1076                 errorstream << "Secure setting " << name
1077                                 << " isn't allowed, so was ignored."
1078                                 << std::endl;
1079                 remove(name);
1080         }
1081 }
1082
1083 void Settings::doCallbacks(const std::string &name) const
1084 {
1085         MutexAutoLock lock(m_callback_mutex);
1086
1087         SettingsCallbackMap::const_iterator it_cbks = m_callbacks.find(name);
1088         if (it_cbks != m_callbacks.end()) {
1089                 SettingsCallbackList::const_iterator it;
1090                 for (it = it_cbks->second.begin(); it != it_cbks->second.end(); ++it)
1091                         (it->first)(name, it->second);
1092         }
1093 }