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"
43 Settings & Settings::operator += (const Settings &other)
51 Settings & Settings::operator = (const Settings &other)
56 JMutexAutoLock lock(m_mutex);
57 JMutexAutoLock lock2(other.m_mutex);
66 bool Settings::checkNameValid(const std::string &name)
68 size_t pos = name.find_first_of("\t\n\v\f\r\b =\"{}#");
69 if (pos != std::string::npos) {
70 errorstream << "Invalid character '" << name[pos]
71 << "' found in setting name" << std::endl;
78 bool Settings::checkValueValid(const std::string &value)
80 if (value.substr(0, 3) == "\"\"\"" ||
81 value.find("\n\"\"\"") != std::string::npos) {
82 errorstream << "Invalid character sequence '\"\"\"' found in"
83 " setting value" << std::endl;
90 std::string Settings::sanitizeName(const std::string &name)
94 for (const char *s = "\t\n\v\f\r\b =\"{}#"; *s; s++)
95 n.erase(std::remove(n.begin(), n.end(), *s), n.end());
101 std::string Settings::sanitizeValue(const std::string &value)
103 std::string v(value);
106 if (v.substr(0, 3) == "\"\"\"")
109 while ((p = v.find("\n\"\"\"")) != std::string::npos)
116 std::string Settings::getMultiline(std::istream &is, size_t *num_lines)
124 std::getline(is, line);
125 if (line == "\"\"\"")
128 value.push_back('\n');
131 size_t len = value.size();
133 value.erase(len - 1);
142 bool Settings::readConfigFile(const char *filename)
144 std::ifstream is(filename);
148 return parseConfigLines(is, "");
152 bool Settings::parseConfigLines(std::istream &is, const std::string &end)
154 JMutexAutoLock lock(m_mutex);
156 std::string line, name, value;
159 std::getline(is, line);
160 SettingsParseEvent event = parseConfigObject(line, end, name, value);
168 m_settings[name] = SettingsEntry(value);
173 Settings *group = new Settings;
174 if (!group->parseConfigLines(is, "}")) {
178 m_settings[name] = SettingsEntry(group);
182 m_settings[name] = SettingsEntry(getMultiline(is));
191 void Settings::writeLines(std::ostream &os, u32 tab_depth) const
193 JMutexAutoLock lock(m_mutex);
195 for (std::map<std::string, SettingsEntry>::const_iterator
196 it = m_settings.begin();
197 it != m_settings.end(); ++it)
198 printEntry(os, it->first, it->second, tab_depth);
202 void Settings::printEntry(std::ostream &os, const std::string &name,
203 const SettingsEntry &entry, u32 tab_depth)
205 for (u32 i = 0; i != tab_depth; i++)
208 if (entry.is_group) {
209 os << name << " = {\n";
211 entry.group->writeLines(os, tab_depth + 1);
213 for (u32 i = 0; i != tab_depth; i++)
219 if (entry.value.find('\n') != std::string::npos)
220 os << "\"\"\"\n" << entry.value << "\n\"\"\"\n";
222 os << entry.value << "\n";
227 bool Settings::updateConfigObject(std::istream &is, std::ostream &os,
228 const std::string &end, u32 tab_depth)
230 std::map<std::string, SettingsEntry>::const_iterator it;
231 std::set<std::string> present_entries;
232 std::string line, name, value;
233 bool was_modified = false;
234 bool end_found = false;
236 // Add any settings that exist in the config file with the current value
237 // in the object if existing
238 while (is.good() && !end_found) {
239 std::getline(is, line);
240 SettingsParseEvent event = parseConfigObject(line, end, name, value);
244 os << line << (is.eof() ? "" : "\n");
248 value = getMultiline(is);
251 it = m_settings.find(name);
252 if (it != m_settings.end() &&
253 (it->second.is_group || it->second.value != value)) {
254 printEntry(os, name, it->second, tab_depth);
258 if (event == SPE_MULTILINE)
259 os << value << "\n\"\"\"\n";
261 present_entries.insert(name);
264 it = m_settings.find(name);
265 if (it != m_settings.end() && it->second.is_group) {
267 assert(it->second.group != NULL);
268 was_modified |= it->second.group->updateConfigObject(is, os,
271 printEntry(os, name, it->second, tab_depth);
274 present_entries.insert(name);
277 os << line << (is.eof() ? "" : "\n");
282 // Add any settings in the object that don't exist in the config file yet
283 for (it = m_settings.begin(); it != m_settings.end(); ++it) {
284 if (present_entries.find(it->first) != present_entries.end())
287 printEntry(os, it->first, it->second, tab_depth);
295 bool Settings::updateConfigFile(const char *filename)
297 JMutexAutoLock lock(m_mutex);
299 std::ifstream is(filename);
300 std::ostringstream os(std::ios_base::binary);
302 bool was_modified = updateConfigObject(is, os, "");
308 if (!fs::safeWriteToFile(filename, os.str())) {
309 errorstream << "Error writing configuration file: \""
310 << filename << "\"" << std::endl;
318 bool Settings::parseCommandLine(int argc, char *argv[],
319 std::map<std::string, ValueSpec> &allowed_options)
321 int nonopt_index = 0;
322 for (int i = 1; i < argc; i++) {
323 std::string arg_name = argv[i];
324 if (arg_name.substr(0, 2) != "--") {
325 // If option doesn't start with -, read it in as nonoptX
326 if (arg_name[0] != '-'){
327 std::string name = "nonopt";
328 name += itos(nonopt_index);
333 errorstream << "Invalid command-line parameter \""
334 << arg_name << "\": --<option> expected." << std::endl;
338 std::string name = arg_name.substr(2);
340 std::map<std::string, ValueSpec>::iterator n;
341 n = allowed_options.find(name);
342 if (n == allowed_options.end()) {
343 errorstream << "Unknown command-line parameter \""
344 << arg_name << "\"" << std::endl;
348 ValueType type = n->second.type;
350 std::string value = "";
352 if (type == VALUETYPE_FLAG) {
355 if ((i + 1) >= argc) {
356 errorstream << "Invalid command-line parameter \""
357 << name << "\": missing value" << std::endl;
376 const SettingsEntry &Settings::getEntry(const std::string &name) const
378 JMutexAutoLock lock(m_mutex);
380 std::map<std::string, SettingsEntry>::const_iterator n;
381 if ((n = m_settings.find(name)) == m_settings.end()) {
382 if ((n = m_defaults.find(name)) == m_defaults.end())
383 throw SettingNotFoundException("Setting [" + name + "] not found.");
389 Settings *Settings::getGroup(const std::string &name) const
391 const SettingsEntry &entry = getEntry(name);
393 throw SettingNotFoundException("Setting [" + name + "] is not a group.");
398 std::string Settings::get(const std::string &name) const
400 const SettingsEntry &entry = getEntry(name);
402 throw SettingNotFoundException("Setting [" + name + "] is a group.");
407 bool Settings::getBool(const std::string &name) const
409 return is_yes(get(name));
413 u16 Settings::getU16(const std::string &name) const
415 return stoi(get(name), 0, 65535);
419 s16 Settings::getS16(const std::string &name) const
421 return stoi(get(name), -32768, 32767);
425 s32 Settings::getS32(const std::string &name) const
427 return stoi(get(name));
431 float Settings::getFloat(const std::string &name) const
433 return stof(get(name));
437 u64 Settings::getU64(const std::string &name) const
440 std::string s = get(name);
441 std::istringstream ss(s);
447 v2f Settings::getV2F(const std::string &name) const
452 value.X = stof(f.next(","));
453 value.Y = stof(f.next(")"));
458 v3f Settings::getV3F(const std::string &name) const
463 value.X = stof(f.next(","));
464 value.Y = stof(f.next(","));
465 value.Z = stof(f.next(")"));
470 u32 Settings::getFlagStr(const std::string &name, const FlagDesc *flagdesc,
473 std::string val = get(name);
474 return std::isdigit(val[0])
476 : readFlagString(val, flagdesc, flagmask);
480 // N.B. if getStruct() is used to read a non-POD aggregate type,
481 // the behavior is undefined.
482 bool Settings::getStruct(const std::string &name, const std::string &format,
483 void *out, size_t olen) const
489 } catch (SettingNotFoundException &e) {
493 if (!deSerializeStringToStruct(valstr, format, out, olen))
500 bool Settings::getNoiseParams(const std::string &name, NoiseParams &np) const
502 return getNoiseParamsFromGroup(name, np) || getNoiseParamsFromValue(name, np);
506 bool Settings::getNoiseParamsFromValue(const std::string &name,
507 NoiseParams &np) const
511 if (!getNoEx(name, value))
516 np.offset = stof(f.next(","));
517 np.scale = stof(f.next(","));
519 np.spread.X = stof(f.next(","));
520 np.spread.Y = stof(f.next(","));
521 np.spread.Z = stof(f.next(")"));
523 np.seed = stoi(f.next(","));
524 np.octaves = stoi(f.next(","));
525 np.persist = stof(f.next(","));
527 std::string optional_params = f.next("");
528 if (optional_params != "")
529 np.lacunarity = stof(optional_params);
535 bool Settings::getNoiseParamsFromGroup(const std::string &name,
536 NoiseParams &np) const
538 Settings *group = NULL;
540 if (!getGroupNoEx(name, group))
543 group->getFloatNoEx("offset", np.offset);
544 group->getFloatNoEx("scale", np.scale);
545 group->getV3FNoEx("spread", np.spread);
546 group->getS32NoEx("seed", np.seed);
547 group->getU16NoEx("octaves", np.octaves);
548 group->getFloatNoEx("persistence", np.persist);
549 group->getFloatNoEx("lacunarity", np.lacunarity);
552 if (!group->getFlagStrNoEx("flags", np.flags, flagdesc_noiseparams))
553 np.flags = NOISE_FLAG_DEFAULTS;
559 bool Settings::exists(const std::string &name) const
561 JMutexAutoLock lock(m_mutex);
563 return (m_settings.find(name) != m_settings.end() ||
564 m_defaults.find(name) != m_defaults.end());
568 std::vector<std::string> Settings::getNames() const
570 std::vector<std::string> names;
571 for (std::map<std::string, SettingsEntry>::const_iterator
572 i = m_settings.begin();
573 i != m_settings.end(); ++i) {
574 names.push_back(i->first);
581 /***************************************
582 * Getters that don't throw exceptions *
583 ***************************************/
585 bool Settings::getEntryNoEx(const std::string &name, SettingsEntry &val) const
588 val = getEntry(name);
590 } catch (SettingNotFoundException &e) {
596 bool Settings::getGroupNoEx(const std::string &name, Settings *&val) const
599 val = getGroup(name);
601 } catch (SettingNotFoundException &e) {
607 bool Settings::getNoEx(const std::string &name, std::string &val) const
612 } catch (SettingNotFoundException &e) {
618 bool Settings::getFlag(const std::string &name) const
621 return getBool(name);
622 } catch(SettingNotFoundException &e) {
628 bool Settings::getFloatNoEx(const std::string &name, float &val) const
631 val = getFloat(name);
633 } catch (SettingNotFoundException &e) {
639 bool Settings::getU16NoEx(const std::string &name, u16 &val) const
644 } catch (SettingNotFoundException &e) {
650 bool Settings::getS16NoEx(const std::string &name, s16 &val) const
655 } catch (SettingNotFoundException &e) {
661 bool Settings::getS32NoEx(const std::string &name, s32 &val) const
666 } catch (SettingNotFoundException &e) {
672 bool Settings::getU64NoEx(const std::string &name, u64 &val) const
677 } catch (SettingNotFoundException &e) {
683 bool Settings::getV2FNoEx(const std::string &name, v2f &val) const
688 } catch (SettingNotFoundException &e) {
694 bool Settings::getV3FNoEx(const std::string &name, v3f &val) const
699 } catch (SettingNotFoundException &e) {
705 // N.B. getFlagStrNoEx() does not set val, but merely modifies it. Thus,
706 // val must be initialized before using getFlagStrNoEx(). The intention of
707 // this is to simplify modifying a flags field from a default value.
708 bool Settings::getFlagStrNoEx(const std::string &name, u32 &val,
709 FlagDesc *flagdesc) const
714 flags = getFlagStr(name, flagdesc, &flagmask);
720 } catch (SettingNotFoundException &e) {
730 bool Settings::setEntry(const std::string &name, const void *data,
731 bool set_group, bool set_default)
733 Settings *old_group = NULL;
735 if (!checkNameValid(name))
737 if (!set_group && !checkValueValid(*(const std::string *)data))
741 JMutexAutoLock lock(m_mutex);
743 SettingsEntry &entry = set_default ? m_defaults[name] : m_settings[name];
744 old_group = entry.group;
746 entry.value = set_group ? "" : *(const std::string *)data;
747 entry.group = set_group ? *(Settings **)data : NULL;
748 entry.is_group = set_group;
757 bool Settings::set(const std::string &name, const std::string &value)
759 if (!setEntry(name, &value, false, false))
767 bool Settings::setDefault(const std::string &name, const std::string &value)
769 return setEntry(name, &value, false, true);
773 bool Settings::setGroup(const std::string &name, Settings *group)
775 return setEntry(name, &group, true, false);
779 bool Settings::setGroupDefault(const std::string &name, Settings *group)
781 return setEntry(name, &group, true, true);
785 bool Settings::setBool(const std::string &name, bool value)
787 return set(name, value ? "true" : "false");
791 bool Settings::setS16(const std::string &name, s16 value)
793 return set(name, itos(value));
797 bool Settings::setU16(const std::string &name, u16 value)
799 return set(name, itos(value));
803 bool Settings::setS32(const std::string &name, s32 value)
805 return set(name, itos(value));
809 bool Settings::setU64(const std::string &name, u64 value)
811 std::ostringstream os;
813 return set(name, os.str());
817 bool Settings::setFloat(const std::string &name, float value)
819 return set(name, ftos(value));
823 bool Settings::setV2F(const std::string &name, v2f value)
825 std::ostringstream os;
826 os << "(" << value.X << "," << value.Y << ")";
827 return set(name, os.str());
831 bool Settings::setV3F(const std::string &name, v3f value)
833 std::ostringstream os;
834 os << "(" << value.X << "," << value.Y << "," << value.Z << ")";
835 return set(name, os.str());
839 bool Settings::setFlagStr(const std::string &name, u32 flags,
840 const FlagDesc *flagdesc, u32 flagmask)
842 return set(name, writeFlagString(flags, flagdesc, flagmask));
846 bool Settings::setStruct(const std::string &name, const std::string &format,
849 std::string structstr;
850 if (!serializeStructToString(&structstr, format, value))
853 return set(name, structstr);
857 bool Settings::setNoiseParams(const std::string &name,
858 const NoiseParams &np, bool set_default)
860 Settings *group = new Settings;
862 group->setFloat("offset", np.offset);
863 group->setFloat("scale", np.scale);
864 group->setV3F("spread", np.spread);
865 group->setS32("seed", np.seed);
866 group->setU16("octaves", np.octaves);
867 group->setFloat("persistence", np.persist);
868 group->setFloat("lacunarity", np.lacunarity);
869 group->setFlagStr("flags", np.flags, flagdesc_noiseparams, np.flags);
871 return setEntry(name, &group, true, set_default);
875 bool Settings::remove(const std::string &name)
877 JMutexAutoLock lock(m_mutex);
879 delete m_settings[name].group;
880 return m_settings.erase(name);
884 void Settings::clear()
886 JMutexAutoLock lock(m_mutex);
891 void Settings::updateValue(const Settings &other, const std::string &name)
896 JMutexAutoLock lock(m_mutex);
899 std::string val = other.get(name);
901 m_settings[name] = val;
902 } catch (SettingNotFoundException &e) {
907 void Settings::update(const Settings &other)
912 JMutexAutoLock lock(m_mutex);
913 JMutexAutoLock lock2(other.m_mutex);
919 SettingsParseEvent Settings::parseConfigObject(const std::string &line,
920 const std::string &end, std::string &name, std::string &value)
922 std::string trimmed_line = trim(line);
924 if (trimmed_line.empty())
926 if (trimmed_line[0] == '#')
928 if (trimmed_line == end)
931 size_t pos = trimmed_line.find('=');
932 if (pos == std::string::npos)
935 name = trim(trimmed_line.substr(0, pos));
936 value = trim(trimmed_line.substr(pos + 1));
940 if (value == "\"\"\"")
941 return SPE_MULTILINE;
947 void Settings::updateNoLock(const Settings &other)
949 m_settings.insert(other.m_settings.begin(), other.m_settings.end());
950 m_defaults.insert(other.m_defaults.begin(), other.m_defaults.end());
954 void Settings::clearNoLock()
956 std::map<std::string, SettingsEntry>::const_iterator it;
957 for (it = m_settings.begin(); it != m_settings.end(); ++it)
958 delete it->second.group;
961 for (it = m_defaults.begin(); it != m_defaults.end(); ++it)
962 delete it->second.group;
966 void Settings::registerChangedCallback(std::string name,
967 setting_changed_callback cbf, void *userdata)
969 JMutexAutoLock lock(m_callbackMutex);
970 m_callbacks[name].push_back(std::make_pair(cbf, userdata));
973 void Settings::deregisterChangedCallback(std::string name, setting_changed_callback cbf, void *userdata)
975 JMutexAutoLock lock(m_callbackMutex);
976 std::map<std::string, std::vector<std::pair<setting_changed_callback, void*> > >::iterator iterToVector = m_callbacks.find(name);
977 if (iterToVector != m_callbacks.end())
979 std::vector<std::pair<setting_changed_callback, void*> > &vector = iterToVector->second;
981 std::vector<std::pair<setting_changed_callback, void*> >::iterator position =
982 std::find(vector.begin(), vector.end(), std::make_pair(cbf, userdata));
984 if (position != vector.end())
985 vector.erase(position);
989 void Settings::doCallbacks(const std::string name)
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*> >::iterator iter;
996 for (iter = iterToVector->second.begin(); iter != iterToVector->second.end(); iter++)
998 (iter->first)(name, iter->second);