3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
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.
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.
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.
21 #include "irrlichttypes_bloated.h"
22 #include "exceptions.h"
23 #include "threading/mutex_auto_lock.h"
24 #include "util/strfnd.h"
30 #include "util/serialize.h"
36 static Settings main_settings;
37 Settings *g_settings = &main_settings;
38 std::string g_settings_path;
46 Settings & Settings::operator += (const Settings &other)
54 Settings & Settings::operator = (const Settings &other)
59 MutexAutoLock lock(m_mutex);
60 MutexAutoLock lock2(other.m_mutex);
69 bool Settings::checkNameValid(const std::string &name)
71 bool valid = name.find_first_of("=\"{}#") == std::string::npos;
72 if (valid) valid = trim(name) == name;
74 errorstream << "Invalid setting name \"" << name << "\""
82 bool Settings::checkValueValid(const std::string &value)
84 if (value.substr(0, 3) == "\"\"\"" ||
85 value.find("\n\"\"\"") != std::string::npos) {
86 errorstream << "Invalid character sequence '\"\"\"' found in"
87 " setting value!" << std::endl;
93 std::string Settings::getMultiline(std::istream &is, size_t *num_lines)
101 std::getline(is, line);
102 if (line == "\"\"\"")
105 value.push_back('\n');
108 size_t len = value.size();
110 value.erase(len - 1);
119 bool Settings::readConfigFile(const char *filename)
121 std::ifstream is(filename);
125 return parseConfigLines(is, "");
129 bool Settings::parseConfigLines(std::istream &is, const std::string &end)
131 MutexAutoLock lock(m_mutex);
133 std::string line, name, value;
136 std::getline(is, line);
137 SettingsParseEvent event = parseConfigObject(line, end, name, value);
145 m_settings[name] = SettingsEntry(value);
150 Settings *group = new Settings;
151 if (!group->parseConfigLines(is, "}")) {
155 m_settings[name] = SettingsEntry(group);
159 m_settings[name] = SettingsEntry(getMultiline(is));
168 void Settings::writeLines(std::ostream &os, u32 tab_depth) const
170 MutexAutoLock lock(m_mutex);
172 for (const auto &setting_it : m_settings)
173 printEntry(os, setting_it.first, setting_it.second, tab_depth);
177 void Settings::printEntry(std::ostream &os, const std::string &name,
178 const SettingsEntry &entry, u32 tab_depth)
180 for (u32 i = 0; i != tab_depth; i++)
183 if (entry.is_group) {
184 os << name << " = {\n";
186 entry.group->writeLines(os, tab_depth + 1);
188 for (u32 i = 0; i != tab_depth; i++)
194 if (entry.value.find('\n') != std::string::npos)
195 os << "\"\"\"\n" << entry.value << "\n\"\"\"\n";
197 os << entry.value << "\n";
202 bool Settings::updateConfigObject(std::istream &is, std::ostream &os,
203 const std::string &end, u32 tab_depth)
205 SettingEntries::const_iterator it;
206 std::set<std::string> present_entries;
207 std::string line, name, value;
208 bool was_modified = false;
209 bool end_found = false;
211 // Add any settings that exist in the config file with the current value
212 // in the object if existing
213 while (is.good() && !end_found) {
214 std::getline(is, line);
215 SettingsParseEvent event = parseConfigObject(line, end, name, value);
219 os << line << (is.eof() ? "" : "\n");
223 value = getMultiline(is);
226 it = m_settings.find(name);
227 if (it != m_settings.end() &&
228 (it->second.is_group || it->second.value != value)) {
229 printEntry(os, name, it->second, tab_depth);
231 } else if (it == m_settings.end()) {
232 // Remove by skipping
237 if (event == SPE_MULTILINE)
238 os << value << "\n\"\"\"\n";
240 present_entries.insert(name);
243 it = m_settings.find(name);
244 if (it != m_settings.end() && it->second.is_group) {
246 sanity_check(it->second.group != NULL);
247 was_modified |= it->second.group->updateConfigObject(is, os,
249 } else if (it == m_settings.end()) {
250 // Remove by skipping
252 Settings removed_group; // Move 'is' to group end
253 std::stringstream ss;
254 removed_group.updateConfigObject(is, ss, "}", tab_depth + 1);
257 printEntry(os, name, it->second, tab_depth);
260 present_entries.insert(name);
263 os << line << (is.eof() ? "" : "\n");
268 // Add any settings in the object that don't exist in the config file yet
269 for (it = m_settings.begin(); it != m_settings.end(); ++it) {
270 if (present_entries.find(it->first) != present_entries.end())
273 printEntry(os, it->first, it->second, tab_depth);
281 bool Settings::updateConfigFile(const char *filename)
283 MutexAutoLock lock(m_mutex);
285 std::ifstream is(filename);
286 std::ostringstream os(std::ios_base::binary);
288 bool was_modified = updateConfigObject(is, os, "");
294 if (!fs::safeWriteToFile(filename, os.str())) {
295 errorstream << "Error writing configuration file: \""
296 << filename << "\"" << std::endl;
304 bool Settings::parseCommandLine(int argc, char *argv[],
305 std::map<std::string, ValueSpec> &allowed_options)
307 int nonopt_index = 0;
308 for (int i = 1; i < argc; i++) {
309 std::string arg_name = argv[i];
310 if (arg_name.substr(0, 2) != "--") {
311 // If option doesn't start with -, read it in as nonoptX
312 if (arg_name[0] != '-'){
313 std::string name = "nonopt";
314 name += itos(nonopt_index);
319 errorstream << "Invalid command-line parameter \""
320 << arg_name << "\": --<option> expected." << std::endl;
324 std::string name = arg_name.substr(2);
326 std::map<std::string, ValueSpec>::iterator n;
327 n = allowed_options.find(name);
328 if (n == allowed_options.end()) {
329 errorstream << "Unknown command-line parameter \""
330 << arg_name << "\"" << std::endl;
334 ValueType type = n->second.type;
338 if (type == VALUETYPE_FLAG) {
341 if ((i + 1) >= argc) {
342 errorstream << "Invalid command-line parameter \""
343 << name << "\": missing value" << std::endl;
362 const SettingsEntry &Settings::getEntry(const std::string &name) const
364 MutexAutoLock lock(m_mutex);
366 SettingEntries::const_iterator n;
367 if ((n = m_settings.find(name)) == m_settings.end()) {
368 if ((n = m_defaults.find(name)) == m_defaults.end())
369 throw SettingNotFoundException("Setting [" + name + "] not found.");
375 const SettingsEntry &Settings::getEntryDefault(const std::string &name) const
377 MutexAutoLock lock(m_mutex);
379 SettingEntries::const_iterator n;
380 if ((n = m_defaults.find(name)) == m_defaults.end()) {
381 throw SettingNotFoundException("Setting [" + name + "] not found.");
387 Settings *Settings::getGroup(const std::string &name) const
389 const SettingsEntry &entry = getEntry(name);
391 throw SettingNotFoundException("Setting [" + name + "] is not a group.");
396 const std::string &Settings::get(const std::string &name) const
398 const SettingsEntry &entry = getEntry(name);
400 throw SettingNotFoundException("Setting [" + name + "] is a group.");
405 const std::string &Settings::getDefault(const std::string &name) const
407 const SettingsEntry &entry = getEntryDefault(name);
409 throw SettingNotFoundException("Setting [" + name + "] is a group.");
414 bool Settings::getBool(const std::string &name) const
416 return is_yes(get(name));
420 u16 Settings::getU16(const std::string &name) const
422 return stoi(get(name), 0, 65535);
426 s16 Settings::getS16(const std::string &name) const
428 return stoi(get(name), -32768, 32767);
432 u32 Settings::getU32(const std::string &name) const
434 return (u32) stoi(get(name));
437 s32 Settings::getS32(const std::string &name) const
439 return stoi(get(name));
443 float Settings::getFloat(const std::string &name) const
445 return stof(get(name));
449 u64 Settings::getU64(const std::string &name) const
452 std::string s = get(name);
453 std::istringstream ss(s);
459 v2f Settings::getV2F(const std::string &name) const
464 value.X = stof(f.next(","));
465 value.Y = stof(f.next(")"));
470 v3f Settings::getV3F(const std::string &name) const
475 value.X = stof(f.next(","));
476 value.Y = stof(f.next(","));
477 value.Z = stof(f.next(")"));
482 u32 Settings::getFlagStr(const std::string &name, const FlagDesc *flagdesc,
485 std::string val = get(name);
486 return std::isdigit(val[0])
488 : readFlagString(val, flagdesc, flagmask);
492 // N.B. if getStruct() is used to read a non-POD aggregate type,
493 // the behavior is undefined.
494 bool Settings::getStruct(const std::string &name, const std::string &format,
495 void *out, size_t olen) const
501 } catch (SettingNotFoundException &e) {
505 if (!deSerializeStringToStruct(valstr, format, out, olen))
512 bool Settings::getNoiseParams(const std::string &name, NoiseParams &np) const
514 return getNoiseParamsFromGroup(name, np) || getNoiseParamsFromValue(name, np);
518 bool Settings::getNoiseParamsFromValue(const std::string &name,
519 NoiseParams &np) const
523 if (!getNoEx(name, value))
528 np.offset = stof(f.next(","));
529 np.scale = stof(f.next(","));
531 np.spread.X = stof(f.next(","));
532 np.spread.Y = stof(f.next(","));
533 np.spread.Z = stof(f.next(")"));
535 np.seed = stoi(f.next(","));
536 np.octaves = stoi(f.next(","));
537 np.persist = stof(f.next(","));
539 std::string optional_params = f.next("");
540 if (!optional_params.empty())
541 np.lacunarity = stof(optional_params);
547 bool Settings::getNoiseParamsFromGroup(const std::string &name,
548 NoiseParams &np) const
550 Settings *group = NULL;
552 if (!getGroupNoEx(name, group))
555 group->getFloatNoEx("offset", np.offset);
556 group->getFloatNoEx("scale", np.scale);
557 group->getV3FNoEx("spread", np.spread);
558 group->getS32NoEx("seed", np.seed);
559 group->getU16NoEx("octaves", np.octaves);
560 group->getFloatNoEx("persistence", np.persist);
561 group->getFloatNoEx("lacunarity", np.lacunarity);
564 if (!group->getFlagStrNoEx("flags", np.flags, flagdesc_noiseparams))
565 np.flags = NOISE_FLAG_DEFAULTS;
571 bool Settings::exists(const std::string &name) const
573 MutexAutoLock lock(m_mutex);
575 return (m_settings.find(name) != m_settings.end() ||
576 m_defaults.find(name) != m_defaults.end());
580 std::vector<std::string> Settings::getNames() const
582 std::vector<std::string> names;
583 for (const auto &settings_it : m_settings) {
584 names.push_back(settings_it.first);
591 /***************************************
592 * Getters that don't throw exceptions *
593 ***************************************/
595 bool Settings::getEntryNoEx(const std::string &name, SettingsEntry &val) const
598 val = getEntry(name);
600 } catch (SettingNotFoundException &e) {
606 bool Settings::getEntryDefaultNoEx(const std::string &name, SettingsEntry &val) const
609 val = getEntryDefault(name);
611 } catch (SettingNotFoundException &e) {
617 bool Settings::getGroupNoEx(const std::string &name, Settings *&val) const
620 val = getGroup(name);
622 } catch (SettingNotFoundException &e) {
628 bool Settings::getNoEx(const std::string &name, std::string &val) const
633 } catch (SettingNotFoundException &e) {
639 bool Settings::getDefaultNoEx(const std::string &name, std::string &val) const
642 val = getDefault(name);
644 } catch (SettingNotFoundException &e) {
650 bool Settings::getFlag(const std::string &name) const
653 return getBool(name);
654 } catch(SettingNotFoundException &e) {
660 bool Settings::getFloatNoEx(const std::string &name, float &val) const
663 val = getFloat(name);
665 } catch (SettingNotFoundException &e) {
671 bool Settings::getU16NoEx(const std::string &name, u16 &val) const
676 } catch (SettingNotFoundException &e) {
682 bool Settings::getS16NoEx(const std::string &name, s16 &val) const
687 } catch (SettingNotFoundException &e) {
693 bool Settings::getS32NoEx(const std::string &name, s32 &val) const
698 } catch (SettingNotFoundException &e) {
704 bool Settings::getU64NoEx(const std::string &name, u64 &val) const
709 } catch (SettingNotFoundException &e) {
715 bool Settings::getV2FNoEx(const std::string &name, v2f &val) const
720 } catch (SettingNotFoundException &e) {
726 bool Settings::getV3FNoEx(const std::string &name, v3f &val) const
731 } catch (SettingNotFoundException &e) {
737 // N.B. getFlagStrNoEx() does not set val, but merely modifies it. Thus,
738 // val must be initialized before using getFlagStrNoEx(). The intention of
739 // this is to simplify modifying a flags field from a default value.
740 bool Settings::getFlagStrNoEx(const std::string &name, u32 &val,
741 FlagDesc *flagdesc) const
746 flags = getFlagStr(name, flagdesc, &flagmask);
752 } catch (SettingNotFoundException &e) {
762 bool Settings::setEntry(const std::string &name, const void *data,
763 bool set_group, bool set_default)
765 Settings *old_group = NULL;
767 if (!checkNameValid(name))
769 if (!set_group && !checkValueValid(*(const std::string *)data))
773 MutexAutoLock lock(m_mutex);
775 SettingsEntry &entry = set_default ? m_defaults[name] : m_settings[name];
776 old_group = entry.group;
778 entry.value = set_group ? "" : *(const std::string *)data;
779 entry.group = set_group ? *(Settings **)data : NULL;
780 entry.is_group = set_group;
789 bool Settings::set(const std::string &name, const std::string &value)
791 if (!setEntry(name, &value, false, false))
799 bool Settings::setDefault(const std::string &name, const std::string &value)
801 return setEntry(name, &value, false, true);
805 bool Settings::setGroup(const std::string &name, Settings *group)
807 return setEntry(name, &group, true, false);
811 bool Settings::setGroupDefault(const std::string &name, Settings *group)
813 return setEntry(name, &group, true, true);
817 bool Settings::setBool(const std::string &name, bool value)
819 return set(name, value ? "true" : "false");
823 bool Settings::setS16(const std::string &name, s16 value)
825 return set(name, itos(value));
829 bool Settings::setU16(const std::string &name, u16 value)
831 return set(name, itos(value));
835 bool Settings::setS32(const std::string &name, s32 value)
837 return set(name, itos(value));
841 bool Settings::setU64(const std::string &name, u64 value)
843 std::ostringstream os;
845 return set(name, os.str());
849 bool Settings::setFloat(const std::string &name, float value)
851 return set(name, ftos(value));
855 bool Settings::setV2F(const std::string &name, v2f value)
857 std::ostringstream os;
858 os << "(" << value.X << "," << value.Y << ")";
859 return set(name, os.str());
863 bool Settings::setV3F(const std::string &name, v3f value)
865 std::ostringstream os;
866 os << "(" << value.X << "," << value.Y << "," << value.Z << ")";
867 return set(name, os.str());
871 bool Settings::setFlagStr(const std::string &name, u32 flags,
872 const FlagDesc *flagdesc, u32 flagmask)
874 return set(name, writeFlagString(flags, flagdesc, flagmask));
878 bool Settings::setStruct(const std::string &name, const std::string &format,
881 std::string structstr;
882 if (!serializeStructToString(&structstr, format, value))
885 return set(name, structstr);
889 bool Settings::setNoiseParams(const std::string &name,
890 const NoiseParams &np, bool set_default)
892 Settings *group = new Settings;
894 group->setFloat("offset", np.offset);
895 group->setFloat("scale", np.scale);
896 group->setV3F("spread", np.spread);
897 group->setS32("seed", np.seed);
898 group->setU16("octaves", np.octaves);
899 group->setFloat("persistence", np.persist);
900 group->setFloat("lacunarity", np.lacunarity);
901 group->setFlagStr("flags", np.flags, flagdesc_noiseparams, np.flags);
903 return setEntry(name, &group, true, set_default);
907 bool Settings::remove(const std::string &name)
909 MutexAutoLock lock(m_mutex);
911 SettingEntries::iterator it = m_settings.find(name);
912 if (it != m_settings.end()) {
913 delete it->second.group;
914 m_settings.erase(it);
924 void Settings::clear()
926 MutexAutoLock lock(m_mutex);
930 void Settings::clearDefaults()
932 MutexAutoLock lock(m_mutex);
933 clearDefaultsNoLock();
936 void Settings::updateValue(const Settings &other, const std::string &name)
941 MutexAutoLock lock(m_mutex);
944 m_settings[name] = other.get(name);
945 } catch (SettingNotFoundException &e) {
950 void Settings::update(const Settings &other)
955 MutexAutoLock lock(m_mutex);
956 MutexAutoLock lock2(other.m_mutex);
962 SettingsParseEvent Settings::parseConfigObject(const std::string &line,
963 const std::string &end, std::string &name, std::string &value)
965 std::string trimmed_line = trim(line);
967 if (trimmed_line.empty())
969 if (trimmed_line[0] == '#')
971 if (trimmed_line == end)
974 size_t pos = trimmed_line.find('=');
975 if (pos == std::string::npos)
978 name = trim(trimmed_line.substr(0, pos));
979 value = trim(trimmed_line.substr(pos + 1));
983 if (value == "\"\"\"")
984 return SPE_MULTILINE;
990 void Settings::updateNoLock(const Settings &other)
992 m_settings.insert(other.m_settings.begin(), other.m_settings.end());
993 m_defaults.insert(other.m_defaults.begin(), other.m_defaults.end());
997 void Settings::clearNoLock()
1000 for (SettingEntries::const_iterator it = m_settings.begin();
1001 it != m_settings.end(); ++it)
1002 delete it->second.group;
1005 clearDefaultsNoLock();
1008 void Settings::clearDefaultsNoLock()
1010 for (SettingEntries::const_iterator it = m_defaults.begin();
1011 it != m_defaults.end(); ++it)
1012 delete it->second.group;
1017 void Settings::registerChangedCallback(const std::string &name,
1018 SettingsChangedCallback cbf, void *userdata)
1020 MutexAutoLock lock(m_callback_mutex);
1021 m_callbacks[name].emplace_back(cbf, userdata);
1024 void Settings::deregisterChangedCallback(const std::string &name,
1025 SettingsChangedCallback cbf, void *userdata)
1027 MutexAutoLock lock(m_callback_mutex);
1028 SettingsCallbackMap::iterator it_cbks = m_callbacks.find(name);
1030 if (it_cbks != m_callbacks.end()) {
1031 SettingsCallbackList &cbks = it_cbks->second;
1033 SettingsCallbackList::iterator position =
1034 std::find(cbks.begin(), cbks.end(), std::make_pair(cbf, userdata));
1036 if (position != cbks.end())
1037 cbks.erase(position);
1041 void Settings::doCallbacks(const std::string &name) const
1043 MutexAutoLock lock(m_callback_mutex);
1045 SettingsCallbackMap::const_iterator it_cbks = m_callbacks.find(name);
1046 if (it_cbks != m_callbacks.end()) {
1047 SettingsCallbackList::const_iterator it;
1048 for (it = it_cbks->second.begin(); it != it_cbks->second.end(); ++it)
1049 (it->first)(name, it->second);