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