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 "jthread/jmutexautolock.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 JMutexAutoLock lock(m_mutex);
60 JMutexAutoLock 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;
94 std::string Settings::sanitizeName(const std::string &name)
96 std::string n = trim(name);
98 for (const char *s = "=\"{}#"; *s; s++)
99 n.erase(std::remove(n.begin(), n.end(), *s), n.end());
105 std::string Settings::sanitizeValue(const std::string &value)
107 std::string v(value);
110 if (v.substr(0, 3) == "\"\"\"")
113 while ((p = v.find("\n\"\"\"")) != std::string::npos)
120 std::string Settings::getMultiline(std::istream &is, size_t *num_lines)
128 std::getline(is, line);
129 if (line == "\"\"\"")
132 value.push_back('\n');
135 size_t len = value.size();
137 value.erase(len - 1);
146 bool Settings::readConfigFile(const char *filename)
148 std::ifstream is(filename);
152 return parseConfigLines(is, "");
156 bool Settings::parseConfigLines(std::istream &is, const std::string &end)
158 JMutexAutoLock lock(m_mutex);
160 std::string line, name, value;
163 std::getline(is, line);
164 SettingsParseEvent event = parseConfigObject(line, end, name, value);
172 m_settings[name] = SettingsEntry(value);
177 Settings *group = new Settings;
178 if (!group->parseConfigLines(is, "}")) {
182 m_settings[name] = SettingsEntry(group);
186 m_settings[name] = SettingsEntry(getMultiline(is));
195 void Settings::writeLines(std::ostream &os, u32 tab_depth) const
197 JMutexAutoLock lock(m_mutex);
199 for (std::map<std::string, SettingsEntry>::const_iterator
200 it = m_settings.begin();
201 it != m_settings.end(); ++it)
202 printEntry(os, it->first, it->second, tab_depth);
206 void Settings::printEntry(std::ostream &os, const std::string &name,
207 const SettingsEntry &entry, u32 tab_depth)
209 for (u32 i = 0; i != tab_depth; i++)
212 if (entry.is_group) {
213 os << name << " = {\n";
215 entry.group->writeLines(os, tab_depth + 1);
217 for (u32 i = 0; i != tab_depth; i++)
223 if (entry.value.find('\n') != std::string::npos)
224 os << "\"\"\"\n" << entry.value << "\n\"\"\"\n";
226 os << entry.value << "\n";
231 bool Settings::updateConfigObject(std::istream &is, std::ostream &os,
232 const std::string &end, u32 tab_depth)
234 std::map<std::string, SettingsEntry>::const_iterator it;
235 std::set<std::string> present_entries;
236 std::string line, name, value;
237 bool was_modified = false;
238 bool end_found = false;
240 // Add any settings that exist in the config file with the current value
241 // in the object if existing
242 while (is.good() && !end_found) {
243 std::getline(is, line);
244 SettingsParseEvent event = parseConfigObject(line, end, name, value);
248 os << line << (is.eof() ? "" : "\n");
252 value = getMultiline(is);
255 it = m_settings.find(name);
256 if (it != m_settings.end() &&
257 (it->second.is_group || it->second.value != value)) {
258 printEntry(os, name, it->second, tab_depth);
262 if (event == SPE_MULTILINE)
263 os << value << "\n\"\"\"\n";
265 present_entries.insert(name);
268 it = m_settings.find(name);
269 if (it != m_settings.end() && it->second.is_group) {
271 sanity_check(it->second.group != NULL);
272 was_modified |= it->second.group->updateConfigObject(is, os,
275 printEntry(os, name, it->second, tab_depth);
278 present_entries.insert(name);
281 os << line << (is.eof() ? "" : "\n");
286 // Add any settings in the object that don't exist in the config file yet
287 for (it = m_settings.begin(); it != m_settings.end(); ++it) {
288 if (present_entries.find(it->first) != present_entries.end())
291 printEntry(os, it->first, it->second, tab_depth);
299 bool Settings::updateConfigFile(const char *filename)
301 JMutexAutoLock lock(m_mutex);
303 std::ifstream is(filename);
304 std::ostringstream os(std::ios_base::binary);
306 bool was_modified = updateConfigObject(is, os, "");
312 if (!fs::safeWriteToFile(filename, os.str())) {
313 errorstream << "Error writing configuration file: \""
314 << filename << "\"" << std::endl;
322 bool Settings::parseCommandLine(int argc, char *argv[],
323 std::map<std::string, ValueSpec> &allowed_options)
325 int nonopt_index = 0;
326 for (int i = 1; i < argc; i++) {
327 std::string arg_name = argv[i];
328 if (arg_name.substr(0, 2) != "--") {
329 // If option doesn't start with -, read it in as nonoptX
330 if (arg_name[0] != '-'){
331 std::string name = "nonopt";
332 name += itos(nonopt_index);
337 errorstream << "Invalid command-line parameter \""
338 << arg_name << "\": --<option> expected." << std::endl;
342 std::string name = arg_name.substr(2);
344 std::map<std::string, ValueSpec>::iterator n;
345 n = allowed_options.find(name);
346 if (n == allowed_options.end()) {
347 errorstream << "Unknown command-line parameter \""
348 << arg_name << "\"" << std::endl;
352 ValueType type = n->second.type;
354 std::string value = "";
356 if (type == VALUETYPE_FLAG) {
359 if ((i + 1) >= argc) {
360 errorstream << "Invalid command-line parameter \""
361 << name << "\": missing value" << std::endl;
380 const SettingsEntry &Settings::getEntry(const std::string &name) const
382 JMutexAutoLock lock(m_mutex);
384 std::map<std::string, SettingsEntry>::const_iterator n;
385 if ((n = m_settings.find(name)) == m_settings.end()) {
386 if ((n = m_defaults.find(name)) == m_defaults.end())
387 throw SettingNotFoundException("Setting [" + name + "] not found.");
393 Settings *Settings::getGroup(const std::string &name) const
395 const SettingsEntry &entry = getEntry(name);
397 throw SettingNotFoundException("Setting [" + name + "] is not a group.");
402 std::string Settings::get(const std::string &name) const
404 const SettingsEntry &entry = getEntry(name);
406 throw SettingNotFoundException("Setting [" + name + "] is a group.");
411 bool Settings::getBool(const std::string &name) const
413 return is_yes(get(name));
417 u16 Settings::getU16(const std::string &name) const
419 return stoi(get(name), 0, 65535);
423 s16 Settings::getS16(const std::string &name) const
425 return stoi(get(name), -32768, 32767);
429 s32 Settings::getS32(const std::string &name) const
431 return stoi(get(name));
435 float Settings::getFloat(const std::string &name) const
437 return stof(get(name));
441 u64 Settings::getU64(const std::string &name) const
444 std::string s = get(name);
445 std::istringstream ss(s);
451 v2f Settings::getV2F(const std::string &name) const
456 value.X = stof(f.next(","));
457 value.Y = stof(f.next(")"));
462 v3f Settings::getV3F(const std::string &name) const
467 value.X = stof(f.next(","));
468 value.Y = stof(f.next(","));
469 value.Z = stof(f.next(")"));
474 u32 Settings::getFlagStr(const std::string &name, const FlagDesc *flagdesc,
477 std::string val = get(name);
478 return std::isdigit(val[0])
480 : readFlagString(val, flagdesc, flagmask);
484 // N.B. if getStruct() is used to read a non-POD aggregate type,
485 // the behavior is undefined.
486 bool Settings::getStruct(const std::string &name, const std::string &format,
487 void *out, size_t olen) const
493 } catch (SettingNotFoundException &e) {
497 if (!deSerializeStringToStruct(valstr, format, out, olen))
504 bool Settings::getNoiseParams(const std::string &name, NoiseParams &np) const
506 return getNoiseParamsFromGroup(name, np) || getNoiseParamsFromValue(name, np);
510 bool Settings::getNoiseParamsFromValue(const std::string &name,
511 NoiseParams &np) const
515 if (!getNoEx(name, value))
520 np.offset = stof(f.next(","));
521 np.scale = stof(f.next(","));
523 np.spread.X = stof(f.next(","));
524 np.spread.Y = stof(f.next(","));
525 np.spread.Z = stof(f.next(")"));
527 np.seed = stoi(f.next(","));
528 np.octaves = stoi(f.next(","));
529 np.persist = stof(f.next(","));
531 std::string optional_params = f.next("");
532 if (optional_params != "")
533 np.lacunarity = stof(optional_params);
539 bool Settings::getNoiseParamsFromGroup(const std::string &name,
540 NoiseParams &np) const
542 Settings *group = NULL;
544 if (!getGroupNoEx(name, group))
547 group->getFloatNoEx("offset", np.offset);
548 group->getFloatNoEx("scale", np.scale);
549 group->getV3FNoEx("spread", np.spread);
550 group->getS32NoEx("seed", np.seed);
551 group->getU16NoEx("octaves", np.octaves);
552 group->getFloatNoEx("persistence", np.persist);
553 group->getFloatNoEx("lacunarity", np.lacunarity);
556 if (!group->getFlagStrNoEx("flags", np.flags, flagdesc_noiseparams))
557 np.flags = NOISE_FLAG_DEFAULTS;
563 bool Settings::exists(const std::string &name) const
565 JMutexAutoLock lock(m_mutex);
567 return (m_settings.find(name) != m_settings.end() ||
568 m_defaults.find(name) != m_defaults.end());
572 std::vector<std::string> Settings::getNames() const
574 std::vector<std::string> names;
575 for (std::map<std::string, SettingsEntry>::const_iterator
576 i = m_settings.begin();
577 i != m_settings.end(); ++i) {
578 names.push_back(i->first);
585 /***************************************
586 * Getters that don't throw exceptions *
587 ***************************************/
589 bool Settings::getEntryNoEx(const std::string &name, SettingsEntry &val) const
592 val = getEntry(name);
594 } catch (SettingNotFoundException &e) {
600 bool Settings::getGroupNoEx(const std::string &name, Settings *&val) const
603 val = getGroup(name);
605 } catch (SettingNotFoundException &e) {
611 bool Settings::getNoEx(const std::string &name, std::string &val) const
616 } catch (SettingNotFoundException &e) {
622 bool Settings::getFlag(const std::string &name) const
625 return getBool(name);
626 } catch(SettingNotFoundException &e) {
632 bool Settings::getFloatNoEx(const std::string &name, float &val) const
635 val = getFloat(name);
637 } catch (SettingNotFoundException &e) {
643 bool Settings::getU16NoEx(const std::string &name, u16 &val) const
648 } catch (SettingNotFoundException &e) {
654 bool Settings::getS16NoEx(const std::string &name, s16 &val) const
659 } catch (SettingNotFoundException &e) {
665 bool Settings::getS32NoEx(const std::string &name, s32 &val) const
670 } catch (SettingNotFoundException &e) {
676 bool Settings::getU64NoEx(const std::string &name, u64 &val) const
681 } catch (SettingNotFoundException &e) {
687 bool Settings::getV2FNoEx(const std::string &name, v2f &val) const
692 } catch (SettingNotFoundException &e) {
698 bool Settings::getV3FNoEx(const std::string &name, v3f &val) const
703 } catch (SettingNotFoundException &e) {
709 // N.B. getFlagStrNoEx() does not set val, but merely modifies it. Thus,
710 // val must be initialized before using getFlagStrNoEx(). The intention of
711 // this is to simplify modifying a flags field from a default value.
712 bool Settings::getFlagStrNoEx(const std::string &name, u32 &val,
713 FlagDesc *flagdesc) const
718 flags = getFlagStr(name, flagdesc, &flagmask);
724 } catch (SettingNotFoundException &e) {
734 bool Settings::setEntry(const std::string &name, const void *data,
735 bool set_group, bool set_default)
737 Settings *old_group = NULL;
739 if (!checkNameValid(name))
741 if (!set_group && !checkValueValid(*(const std::string *)data))
745 JMutexAutoLock lock(m_mutex);
747 SettingsEntry &entry = set_default ? m_defaults[name] : m_settings[name];
748 old_group = entry.group;
750 entry.value = set_group ? "" : *(const std::string *)data;
751 entry.group = set_group ? *(Settings **)data : NULL;
752 entry.is_group = set_group;
761 bool Settings::set(const std::string &name, const std::string &value)
763 if (!setEntry(name, &value, false, false))
771 bool Settings::setDefault(const std::string &name, const std::string &value)
773 return setEntry(name, &value, false, true);
777 bool Settings::setGroup(const std::string &name, Settings *group)
779 return setEntry(name, &group, true, false);
783 bool Settings::setGroupDefault(const std::string &name, Settings *group)
785 return setEntry(name, &group, true, true);
789 bool Settings::setBool(const std::string &name, bool value)
791 return set(name, value ? "true" : "false");
795 bool Settings::setS16(const std::string &name, s16 value)
797 return set(name, itos(value));
801 bool Settings::setU16(const std::string &name, u16 value)
803 return set(name, itos(value));
807 bool Settings::setS32(const std::string &name, s32 value)
809 return set(name, itos(value));
813 bool Settings::setU64(const std::string &name, u64 value)
815 std::ostringstream os;
817 return set(name, os.str());
821 bool Settings::setFloat(const std::string &name, float value)
823 return set(name, ftos(value));
827 bool Settings::setV2F(const std::string &name, v2f value)
829 std::ostringstream os;
830 os << "(" << value.X << "," << value.Y << ")";
831 return set(name, os.str());
835 bool Settings::setV3F(const std::string &name, v3f value)
837 std::ostringstream os;
838 os << "(" << value.X << "," << value.Y << "," << value.Z << ")";
839 return set(name, os.str());
843 bool Settings::setFlagStr(const std::string &name, u32 flags,
844 const FlagDesc *flagdesc, u32 flagmask)
846 return set(name, writeFlagString(flags, flagdesc, flagmask));
850 bool Settings::setStruct(const std::string &name, const std::string &format,
853 std::string structstr;
854 if (!serializeStructToString(&structstr, format, value))
857 return set(name, structstr);
861 bool Settings::setNoiseParams(const std::string &name,
862 const NoiseParams &np, bool set_default)
864 Settings *group = new Settings;
866 group->setFloat("offset", np.offset);
867 group->setFloat("scale", np.scale);
868 group->setV3F("spread", np.spread);
869 group->setS32("seed", np.seed);
870 group->setU16("octaves", np.octaves);
871 group->setFloat("persistence", np.persist);
872 group->setFloat("lacunarity", np.lacunarity);
873 group->setFlagStr("flags", np.flags, flagdesc_noiseparams, np.flags);
875 return setEntry(name, &group, true, set_default);
879 bool Settings::remove(const std::string &name)
881 JMutexAutoLock lock(m_mutex);
883 delete m_settings[name].group;
884 return m_settings.erase(name);
888 void Settings::clear()
890 JMutexAutoLock lock(m_mutex);
894 void Settings::clearDefaults()
896 JMutexAutoLock lock(m_mutex);
897 clearDefaultsNoLock();
900 void Settings::updateValue(const Settings &other, const std::string &name)
905 JMutexAutoLock lock(m_mutex);
908 std::string val = other.get(name);
910 m_settings[name] = val;
911 } catch (SettingNotFoundException &e) {
916 void Settings::update(const Settings &other)
921 JMutexAutoLock lock(m_mutex);
922 JMutexAutoLock lock2(other.m_mutex);
928 SettingsParseEvent Settings::parseConfigObject(const std::string &line,
929 const std::string &end, std::string &name, std::string &value)
931 std::string trimmed_line = trim(line);
933 if (trimmed_line.empty())
935 if (trimmed_line[0] == '#')
937 if (trimmed_line == end)
940 size_t pos = trimmed_line.find('=');
941 if (pos == std::string::npos)
944 name = trim(trimmed_line.substr(0, pos));
945 value = trim(trimmed_line.substr(pos + 1));
949 if (value == "\"\"\"")
950 return SPE_MULTILINE;
956 void Settings::updateNoLock(const Settings &other)
958 m_settings.insert(other.m_settings.begin(), other.m_settings.end());
959 m_defaults.insert(other.m_defaults.begin(), other.m_defaults.end());
963 void Settings::clearNoLock()
965 std::map<std::string, SettingsEntry>::const_iterator it;
966 for (it = m_settings.begin(); it != m_settings.end(); ++it)
967 delete it->second.group;
970 clearDefaultsNoLock();
973 void Settings::clearDefaultsNoLock()
975 std::map<std::string, SettingsEntry>::const_iterator it;
976 for (it = m_defaults.begin(); it != m_defaults.end(); ++it)
977 delete it->second.group;
982 void Settings::registerChangedCallback(std::string name,
983 setting_changed_callback cbf, void *userdata)
985 JMutexAutoLock lock(m_callbackMutex);
986 m_callbacks[name].push_back(std::make_pair(cbf, userdata));
989 void Settings::deregisterChangedCallback(std::string name, setting_changed_callback cbf, void *userdata)
991 JMutexAutoLock lock(m_callbackMutex);
992 std::map<std::string, std::vector<std::pair<setting_changed_callback, void*> > >::iterator iterToVector = m_callbacks.find(name);
993 if (iterToVector != m_callbacks.end())
995 std::vector<std::pair<setting_changed_callback, void*> > &vector = iterToVector->second;
997 std::vector<std::pair<setting_changed_callback, void*> >::iterator position =
998 std::find(vector.begin(), vector.end(), std::make_pair(cbf, userdata));
1000 if (position != vector.end())
1001 vector.erase(position);
1005 void Settings::doCallbacks(const std::string name)
1007 JMutexAutoLock lock(m_callbackMutex);
1008 std::map<std::string, std::vector<std::pair<setting_changed_callback, void*> > >::iterator iterToVector = m_callbacks.find(name);
1009 if (iterToVector != m_callbacks.end())
1011 std::vector<std::pair<setting_changed_callback, void*> >::iterator iter;
1012 for (iter = iterToVector->second.begin(); iter != iterToVector->second.end(); iter++)
1014 (iter->first)(name, iter->second);