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