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