]> git.lizzy.rs Git - dragonfireclient.git/blob - src/settings.cpp
Fix various code & correctness issues (#11815)
[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         MutexAutoLock lock(m_mutex);
663
664         if (m_settings.find(name) != m_settings.end())
665                 return true;
666         if (auto parent = getParent())
667                 return parent->exists(name);
668         return false;
669 }
670
671
672 std::vector<std::string> Settings::getNames() const
673 {
674         MutexAutoLock lock(m_mutex);
675
676         std::vector<std::string> names;
677         names.reserve(m_settings.size());
678         for (const auto &settings_it : m_settings) {
679                 names.push_back(settings_it.first);
680         }
681         return names;
682 }
683
684
685
686 /***************************************
687  * Getters that don't throw exceptions *
688  ***************************************/
689
690 bool Settings::getGroupNoEx(const std::string &name, Settings *&val) const
691 {
692         try {
693                 val = getGroup(name);
694                 return true;
695         } catch (SettingNotFoundException &e) {
696                 return false;
697         }
698 }
699
700
701 bool Settings::getNoEx(const std::string &name, std::string &val) const
702 {
703         try {
704                 val = get(name);
705                 return true;
706         } catch (SettingNotFoundException &e) {
707                 return false;
708         }
709 }
710
711
712 bool Settings::getFlag(const std::string &name) const
713 {
714         try {
715                 return getBool(name);
716         } catch(SettingNotFoundException &e) {
717                 return false;
718         }
719 }
720
721
722 bool Settings::getFloatNoEx(const std::string &name, float &val) const
723 {
724         try {
725                 val = getFloat(name);
726                 return true;
727         } catch (SettingNotFoundException &e) {
728                 return false;
729         }
730 }
731
732
733 bool Settings::getU16NoEx(const std::string &name, u16 &val) const
734 {
735         try {
736                 val = getU16(name);
737                 return true;
738         } catch (SettingNotFoundException &e) {
739                 return false;
740         }
741 }
742
743
744 bool Settings::getS16NoEx(const std::string &name, s16 &val) const
745 {
746         try {
747                 val = getS16(name);
748                 return true;
749         } catch (SettingNotFoundException &e) {
750                 return false;
751         }
752 }
753
754 bool Settings::getU32NoEx(const std::string &name, u32 &val) const
755 {
756         try {
757                 val = getU32(name);
758                 return true;
759         } catch (SettingNotFoundException &e) {
760                 return false;
761         }
762 }
763
764 bool Settings::getS32NoEx(const std::string &name, s32 &val) const
765 {
766         try {
767                 val = getS32(name);
768                 return true;
769         } catch (SettingNotFoundException &e) {
770                 return false;
771         }
772 }
773
774
775 bool Settings::getU64NoEx(const std::string &name, u64 &val) const
776 {
777         try {
778                 val = getU64(name);
779                 return true;
780         } catch (SettingNotFoundException &e) {
781                 return false;
782         }
783 }
784
785
786 bool Settings::getV2FNoEx(const std::string &name, v2f &val) const
787 {
788         try {
789                 val = getV2F(name);
790                 return true;
791         } catch (SettingNotFoundException &e) {
792                 return false;
793         }
794 }
795
796
797 bool Settings::getV3FNoEx(const std::string &name, v3f &val) const
798 {
799         try {
800                 val = getV3F(name);
801                 return true;
802         } catch (SettingNotFoundException &e) {
803                 return false;
804         }
805 }
806
807
808 bool Settings::getFlagStrNoEx(const std::string &name, u32 &val,
809         const FlagDesc *flagdesc) const
810 {
811         if (!flagdesc) {
812                 if (!(flagdesc = getFlagDescFallback(name)))
813                         return false; // Not found
814         }
815
816         try {
817                 val = getFlagStr(name, flagdesc, nullptr);
818
819                 return true;
820         } catch (SettingNotFoundException &e) {
821                 return false;
822         }
823 }
824
825
826 /***********
827  * Setters *
828  ***********/
829
830 bool Settings::setEntry(const std::string &name, const void *data,
831         bool set_group)
832 {
833         if (!checkNameValid(name))
834                 return false;
835         if (!set_group && !checkValueValid(*(const std::string *)data))
836                 return false;
837
838         Settings *old_group = NULL;
839         {
840                 MutexAutoLock lock(m_mutex);
841
842                 SettingsEntry &entry = m_settings[name];
843                 old_group = entry.group;
844
845                 entry.value    = set_group ? "" : *(const std::string *)data;
846                 entry.group    = set_group ? *(Settings **)data : NULL;
847                 entry.is_group = set_group;
848                 if (set_group)
849                         entry.group->m_end_tag = "}";
850         }
851
852         delete old_group;
853
854         return true;
855 }
856
857
858 bool Settings::set(const std::string &name, const std::string &value)
859 {
860         if (!setEntry(name, &value, false))
861                 return false;
862
863         doCallbacks(name);
864         return true;
865 }
866
867
868 // TODO: Remove this function
869 bool Settings::setDefault(const std::string &name, const std::string &value)
870 {
871         FATAL_ERROR_IF(m_hierarchy != &g_hierarchy, "setDefault is only valid on "
872                 "global settings");
873         return getLayer(SL_DEFAULTS)->set(name, value);
874 }
875
876
877 bool Settings::setGroup(const std::string &name, const Settings &group)
878 {
879         // Settings must own the group pointer
880         // avoid double-free by copying the source
881         Settings *copy = new Settings();
882         *copy = group;
883         return setEntry(name, &copy, true);
884 }
885
886
887 bool Settings::setBool(const std::string &name, bool value)
888 {
889         return set(name, value ? "true" : "false");
890 }
891
892
893 bool Settings::setS16(const std::string &name, s16 value)
894 {
895         return set(name, itos(value));
896 }
897
898
899 bool Settings::setU16(const std::string &name, u16 value)
900 {
901         return set(name, itos(value));
902 }
903
904
905 bool Settings::setS32(const std::string &name, s32 value)
906 {
907         return set(name, itos(value));
908 }
909
910
911 bool Settings::setU64(const std::string &name, u64 value)
912 {
913         std::ostringstream os;
914         os << value;
915         return set(name, os.str());
916 }
917
918
919 bool Settings::setFloat(const std::string &name, float value)
920 {
921         return set(name, ftos(value));
922 }
923
924
925 bool Settings::setV2F(const std::string &name, v2f value)
926 {
927         std::ostringstream os;
928         os << "(" << value.X << "," << value.Y << ")";
929         return set(name, os.str());
930 }
931
932
933 bool Settings::setV3F(const std::string &name, v3f value)
934 {
935         std::ostringstream os;
936         os << "(" << value.X << "," << value.Y << "," << value.Z << ")";
937         return set(name, os.str());
938 }
939
940
941 bool Settings::setFlagStr(const std::string &name, u32 flags,
942         const FlagDesc *flagdesc, u32 flagmask)
943 {
944         if (!flagdesc) {
945                 if (!(flagdesc = getFlagDescFallback(name)))
946                         return false; // Not found
947         }
948
949         return set(name, writeFlagString(flags, flagdesc, flagmask));
950 }
951
952
953 bool Settings::setNoiseParams(const std::string &name, const NoiseParams &np)
954 {
955         Settings *group = new Settings;
956
957         group->setFloat("offset",      np.offset);
958         group->setFloat("scale",       np.scale);
959         group->setV3F("spread",        np.spread);
960         group->setS32("seed",          np.seed);
961         group->setU16("octaves",       np.octaves);
962         group->setFloat("persistence", np.persist);
963         group->setFloat("lacunarity",  np.lacunarity);
964         group->setFlagStr("flags",     np.flags, flagdesc_noiseparams, np.flags);
965
966         return setEntry(name, &group, true);
967 }
968
969
970 bool Settings::remove(const std::string &name)
971 {
972         // Lock as short as possible, unlock before doCallbacks()
973         m_mutex.lock();
974
975         SettingEntries::iterator it = m_settings.find(name);
976         if (it != m_settings.end()) {
977                 delete it->second.group;
978                 m_settings.erase(it);
979                 m_mutex.unlock();
980
981                 doCallbacks(name);
982                 return true;
983         }
984
985         m_mutex.unlock();
986         return false;
987 }
988
989
990 SettingsParseEvent Settings::parseConfigObject(const std::string &line,
991         std::string &name, std::string &value)
992 {
993         std::string trimmed_line = trim(line);
994
995         if (trimmed_line.empty())
996                 return SPE_NONE;
997         if (trimmed_line[0] == '#')
998                 return SPE_COMMENT;
999         if (trimmed_line == m_end_tag)
1000                 return SPE_END;
1001
1002         size_t pos = trimmed_line.find('=');
1003         if (pos == std::string::npos)
1004                 return SPE_INVALID;
1005
1006         name  = trim(trimmed_line.substr(0, pos));
1007         value = trim(trimmed_line.substr(pos + 1));
1008
1009         if (value == "{")
1010                 return SPE_GROUP;
1011         if (value == "\"\"\"")
1012                 return SPE_MULTILINE;
1013
1014         return SPE_KVPAIR;
1015 }
1016
1017
1018 void Settings::clearNoLock()
1019 {
1020         for (SettingEntries::const_iterator it = m_settings.begin();
1021                         it != m_settings.end(); ++it)
1022                 delete it->second.group;
1023         m_settings.clear();
1024 }
1025
1026
1027 void Settings::setDefault(const std::string &name, const FlagDesc *flagdesc,
1028         u32 flags)
1029 {
1030         s_flags[name] = flagdesc;
1031         setDefault(name, writeFlagString(flags, flagdesc, U32_MAX));
1032 }
1033
1034 const FlagDesc *Settings::getFlagDescFallback(const std::string &name) const
1035 {
1036         auto it = s_flags.find(name);
1037         return it == s_flags.end() ? nullptr : it->second;
1038 }
1039
1040 void Settings::registerChangedCallback(const std::string &name,
1041         SettingsChangedCallback cbf, void *userdata)
1042 {
1043         MutexAutoLock lock(m_callback_mutex);
1044         m_callbacks[name].emplace_back(cbf, userdata);
1045 }
1046
1047 void Settings::deregisterChangedCallback(const std::string &name,
1048         SettingsChangedCallback cbf, void *userdata)
1049 {
1050         MutexAutoLock lock(m_callback_mutex);
1051         SettingsCallbackMap::iterator it_cbks = m_callbacks.find(name);
1052
1053         if (it_cbks != m_callbacks.end()) {
1054                 SettingsCallbackList &cbks = it_cbks->second;
1055
1056                 SettingsCallbackList::iterator position =
1057                         std::find(cbks.begin(), cbks.end(), std::make_pair(cbf, userdata));
1058
1059                 if (position != cbks.end())
1060                         cbks.erase(position);
1061         }
1062 }
1063
1064 void Settings::removeSecureSettings()
1065 {
1066         for (const auto &name : getNames()) {
1067                 if (name.compare(0, 7, "secure.") != 0)
1068                         continue;
1069
1070                 errorstream << "Secure setting " << name
1071                                 << " isn't allowed, so was ignored."
1072                                 << std::endl;
1073                 remove(name);
1074         }
1075 }
1076
1077 void Settings::doCallbacks(const std::string &name) const
1078 {
1079         MutexAutoLock lock(m_callback_mutex);
1080
1081         SettingsCallbackMap::const_iterator it_cbks = m_callbacks.find(name);
1082         if (it_cbks != m_callbacks.end()) {
1083                 SettingsCallbackList::const_iterator it;
1084                 for (it = it_cbks->second.begin(); it != it_cbks->second.end(); ++it)
1085                         (it->first)(name, it->second);
1086         }
1087 }