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 size_t pos = name.find_first_of("\t\n\v\f\r\b =\"{}#");
72 if (pos != std::string::npos) {
73 errorstream << "Invalid character '" << name[pos]
74 << "' found in setting name" << std::endl;
81 bool Settings::checkValueValid(const std::string &value)
83 if (value.substr(0, 3) == "\"\"\"" ||
84 value.find("\n\"\"\"") != std::string::npos) {
85 errorstream << "Invalid character sequence '\"\"\"' found in"
86 " setting value" << std::endl;
93 std::string Settings::sanitizeName(const std::string &name)
97 for (const char *s = "\t\n\v\f\r\b =\"{}#"; *s; s++)
98 n.erase(std::remove(n.begin(), n.end(), *s), n.end());
104 std::string Settings::sanitizeValue(const std::string &value)
106 std::string v(value);
109 if (v.substr(0, 3) == "\"\"\"")
112 while ((p = v.find("\n\"\"\"")) != std::string::npos)
119 std::string Settings::getMultiline(std::istream &is, size_t *num_lines)
127 std::getline(is, line);
128 if (line == "\"\"\"")
131 value.push_back('\n');
134 size_t len = value.size();
136 value.erase(len - 1);
145 bool Settings::readConfigFile(const char *filename)
147 std::ifstream is(filename);
151 return parseConfigLines(is, "");
155 bool Settings::parseConfigLines(std::istream &is, const std::string &end)
157 JMutexAutoLock lock(m_mutex);
159 std::string line, name, value;
162 std::getline(is, line);
163 SettingsParseEvent event = parseConfigObject(line, end, name, value);
171 m_settings[name] = SettingsEntry(value);
176 Settings *group = new Settings;
177 if (!group->parseConfigLines(is, "}")) {
181 m_settings[name] = SettingsEntry(group);
185 m_settings[name] = SettingsEntry(getMultiline(is));
194 void Settings::writeLines(std::ostream &os, u32 tab_depth) const
196 JMutexAutoLock lock(m_mutex);
198 for (std::map<std::string, SettingsEntry>::const_iterator
199 it = m_settings.begin();
200 it != m_settings.end(); ++it)
201 printEntry(os, it->first, it->second, tab_depth);
205 void Settings::printEntry(std::ostream &os, const std::string &name,
206 const SettingsEntry &entry, u32 tab_depth)
208 for (u32 i = 0; i != tab_depth; i++)
211 if (entry.is_group) {
212 os << name << " = {\n";
214 entry.group->writeLines(os, tab_depth + 1);
216 for (u32 i = 0; i != tab_depth; i++)
222 if (entry.value.find('\n') != std::string::npos)
223 os << "\"\"\"\n" << entry.value << "\n\"\"\"\n";
225 os << entry.value << "\n";
230 bool Settings::updateConfigObject(std::istream &is, std::ostream &os,
231 const std::string &end, u32 tab_depth)
233 std::map<std::string, SettingsEntry>::const_iterator it;
234 std::set<std::string> present_entries;
235 std::string line, name, value;
236 bool was_modified = false;
237 bool end_found = false;
239 // Add any settings that exist in the config file with the current value
240 // in the object if existing
241 while (is.good() && !end_found) {
242 std::getline(is, line);
243 SettingsParseEvent event = parseConfigObject(line, end, name, value);
247 os << line << (is.eof() ? "" : "\n");
251 value = getMultiline(is);
254 it = m_settings.find(name);
255 if (it != m_settings.end() &&
256 (it->second.is_group || it->second.value != value)) {
257 printEntry(os, name, it->second, tab_depth);
261 if (event == SPE_MULTILINE)
262 os << value << "\n\"\"\"\n";
264 present_entries.insert(name);
267 it = m_settings.find(name);
268 if (it != m_settings.end() && it->second.is_group) {
270 sanity_check(it->second.group != NULL);
271 was_modified |= it->second.group->updateConfigObject(is, os,
274 printEntry(os, name, it->second, tab_depth);
277 present_entries.insert(name);
280 os << line << (is.eof() ? "" : "\n");
285 // Add any settings in the object that don't exist in the config file yet
286 for (it = m_settings.begin(); it != m_settings.end(); ++it) {
287 if (present_entries.find(it->first) != present_entries.end())
290 printEntry(os, it->first, it->second, tab_depth);
298 bool Settings::updateConfigFile(const char *filename)
300 JMutexAutoLock lock(m_mutex);
302 std::ifstream is(filename);
303 std::ostringstream os(std::ios_base::binary);
305 bool was_modified = updateConfigObject(is, os, "");
311 if (!fs::safeWriteToFile(filename, os.str())) {
312 errorstream << "Error writing configuration file: \""
313 << filename << "\"" << std::endl;
321 bool Settings::parseCommandLine(int argc, char *argv[],
322 std::map<std::string, ValueSpec> &allowed_options)
324 int nonopt_index = 0;
325 for (int i = 1; i < argc; i++) {
326 std::string arg_name = argv[i];
327 if (arg_name.substr(0, 2) != "--") {
328 // If option doesn't start with -, read it in as nonoptX
329 if (arg_name[0] != '-'){
330 std::string name = "nonopt";
331 name += itos(nonopt_index);
336 errorstream << "Invalid command-line parameter \""
337 << arg_name << "\": --<option> expected." << std::endl;
341 std::string name = arg_name.substr(2);
343 std::map<std::string, ValueSpec>::iterator n;
344 n = allowed_options.find(name);
345 if (n == allowed_options.end()) {
346 errorstream << "Unknown command-line parameter \""
347 << arg_name << "\"" << std::endl;
351 ValueType type = n->second.type;
353 std::string value = "";
355 if (type == VALUETYPE_FLAG) {
358 if ((i + 1) >= argc) {
359 errorstream << "Invalid command-line parameter \""
360 << name << "\": missing value" << std::endl;
379 const SettingsEntry &Settings::getEntry(const std::string &name) const
381 JMutexAutoLock lock(m_mutex);
383 std::map<std::string, SettingsEntry>::const_iterator n;
384 if ((n = m_settings.find(name)) == m_settings.end()) {
385 if ((n = m_defaults.find(name)) == m_defaults.end())
386 throw SettingNotFoundException("Setting [" + name + "] not found.");
392 Settings *Settings::getGroup(const std::string &name) const
394 const SettingsEntry &entry = getEntry(name);
396 throw SettingNotFoundException("Setting [" + name + "] is not a group.");
401 std::string Settings::get(const std::string &name) const
403 const SettingsEntry &entry = getEntry(name);
405 throw SettingNotFoundException("Setting [" + name + "] is a group.");
410 bool Settings::getBool(const std::string &name) const
412 return is_yes(get(name));
416 u16 Settings::getU16(const std::string &name) const
418 return stoi(get(name), 0, 65535);
422 s16 Settings::getS16(const std::string &name) const
424 return stoi(get(name), -32768, 32767);
428 s32 Settings::getS32(const std::string &name) const
430 return stoi(get(name));
434 float Settings::getFloat(const std::string &name) const
436 return stof(get(name));
440 u64 Settings::getU64(const std::string &name) const
443 std::string s = get(name);
444 std::istringstream ss(s);
450 v2f Settings::getV2F(const std::string &name) const
455 value.X = stof(f.next(","));
456 value.Y = stof(f.next(")"));
461 v3f Settings::getV3F(const std::string &name) const
466 value.X = stof(f.next(","));
467 value.Y = stof(f.next(","));
468 value.Z = stof(f.next(")"));
473 u32 Settings::getFlagStr(const std::string &name, const FlagDesc *flagdesc,
476 std::string val = get(name);
477 return std::isdigit(val[0])
479 : readFlagString(val, flagdesc, flagmask);
483 // N.B. if getStruct() is used to read a non-POD aggregate type,
484 // the behavior is undefined.
485 bool Settings::getStruct(const std::string &name, const std::string &format,
486 void *out, size_t olen) const
492 } catch (SettingNotFoundException &e) {
496 if (!deSerializeStringToStruct(valstr, format, out, olen))
503 bool Settings::getNoiseParams(const std::string &name, NoiseParams &np) const
505 return getNoiseParamsFromGroup(name, np) || getNoiseParamsFromValue(name, np);
509 bool Settings::getNoiseParamsFromValue(const std::string &name,
510 NoiseParams &np) const
514 if (!getNoEx(name, value))
519 np.offset = stof(f.next(","));
520 np.scale = stof(f.next(","));
522 np.spread.X = stof(f.next(","));
523 np.spread.Y = stof(f.next(","));
524 np.spread.Z = stof(f.next(")"));
526 np.seed = stoi(f.next(","));
527 np.octaves = stoi(f.next(","));
528 np.persist = stof(f.next(","));
530 std::string optional_params = f.next("");
531 if (optional_params != "")
532 np.lacunarity = stof(optional_params);
538 bool Settings::getNoiseParamsFromGroup(const std::string &name,
539 NoiseParams &np) const
541 Settings *group = NULL;
543 if (!getGroupNoEx(name, group))
546 group->getFloatNoEx("offset", np.offset);
547 group->getFloatNoEx("scale", np.scale);
548 group->getV3FNoEx("spread", np.spread);
549 group->getS32NoEx("seed", np.seed);
550 group->getU16NoEx("octaves", np.octaves);
551 group->getFloatNoEx("persistence", np.persist);
552 group->getFloatNoEx("lacunarity", np.lacunarity);
555 if (!group->getFlagStrNoEx("flags", np.flags, flagdesc_noiseparams))
556 np.flags = NOISE_FLAG_DEFAULTS;
562 bool Settings::exists(const std::string &name) const
564 JMutexAutoLock lock(m_mutex);
566 return (m_settings.find(name) != m_settings.end() ||
567 m_defaults.find(name) != m_defaults.end());
571 std::vector<std::string> Settings::getNames() const
573 std::vector<std::string> names;
574 for (std::map<std::string, SettingsEntry>::const_iterator
575 i = m_settings.begin();
576 i != m_settings.end(); ++i) {
577 names.push_back(i->first);
584 /***************************************
585 * Getters that don't throw exceptions *
586 ***************************************/
588 bool Settings::getEntryNoEx(const std::string &name, SettingsEntry &val) const
591 val = getEntry(name);
593 } catch (SettingNotFoundException &e) {
599 bool Settings::getGroupNoEx(const std::string &name, Settings *&val) const
602 val = getGroup(name);
604 } catch (SettingNotFoundException &e) {
610 bool Settings::getNoEx(const std::string &name, std::string &val) const
615 } catch (SettingNotFoundException &e) {
621 bool Settings::getFlag(const std::string &name) const
624 return getBool(name);
625 } catch(SettingNotFoundException &e) {
631 bool Settings::getFloatNoEx(const std::string &name, float &val) const
634 val = getFloat(name);
636 } catch (SettingNotFoundException &e) {
642 bool Settings::getU16NoEx(const std::string &name, u16 &val) const
647 } catch (SettingNotFoundException &e) {
653 bool Settings::getS16NoEx(const std::string &name, s16 &val) const
658 } catch (SettingNotFoundException &e) {
664 bool Settings::getS32NoEx(const std::string &name, s32 &val) const
669 } catch (SettingNotFoundException &e) {
675 bool Settings::getU64NoEx(const std::string &name, u64 &val) const
680 } catch (SettingNotFoundException &e) {
686 bool Settings::getV2FNoEx(const std::string &name, v2f &val) const
691 } catch (SettingNotFoundException &e) {
697 bool Settings::getV3FNoEx(const std::string &name, v3f &val) const
702 } catch (SettingNotFoundException &e) {
708 // N.B. getFlagStrNoEx() does not set val, but merely modifies it. Thus,
709 // val must be initialized before using getFlagStrNoEx(). The intention of
710 // this is to simplify modifying a flags field from a default value.
711 bool Settings::getFlagStrNoEx(const std::string &name, u32 &val,
712 FlagDesc *flagdesc) const
717 flags = getFlagStr(name, flagdesc, &flagmask);
723 } catch (SettingNotFoundException &e) {
733 bool Settings::setEntry(const std::string &name, const void *data,
734 bool set_group, bool set_default)
736 Settings *old_group = NULL;
738 if (!checkNameValid(name))
740 if (!set_group && !checkValueValid(*(const std::string *)data))
744 JMutexAutoLock lock(m_mutex);
746 SettingsEntry &entry = set_default ? m_defaults[name] : m_settings[name];
747 old_group = entry.group;
749 entry.value = set_group ? "" : *(const std::string *)data;
750 entry.group = set_group ? *(Settings **)data : NULL;
751 entry.is_group = set_group;
760 bool Settings::set(const std::string &name, const std::string &value)
762 if (!setEntry(name, &value, false, false))
770 bool Settings::setDefault(const std::string &name, const std::string &value)
772 return setEntry(name, &value, false, true);
776 bool Settings::setGroup(const std::string &name, Settings *group)
778 return setEntry(name, &group, true, false);
782 bool Settings::setGroupDefault(const std::string &name, Settings *group)
784 return setEntry(name, &group, true, true);
788 bool Settings::setBool(const std::string &name, bool value)
790 return set(name, value ? "true" : "false");
794 bool Settings::setS16(const std::string &name, s16 value)
796 return set(name, itos(value));
800 bool Settings::setU16(const std::string &name, u16 value)
802 return set(name, itos(value));
806 bool Settings::setS32(const std::string &name, s32 value)
808 return set(name, itos(value));
812 bool Settings::setU64(const std::string &name, u64 value)
814 std::ostringstream os;
816 return set(name, os.str());
820 bool Settings::setFloat(const std::string &name, float value)
822 return set(name, ftos(value));
826 bool Settings::setV2F(const std::string &name, v2f value)
828 std::ostringstream os;
829 os << "(" << value.X << "," << value.Y << ")";
830 return set(name, os.str());
834 bool Settings::setV3F(const std::string &name, v3f value)
836 std::ostringstream os;
837 os << "(" << value.X << "," << value.Y << "," << value.Z << ")";
838 return set(name, os.str());
842 bool Settings::setFlagStr(const std::string &name, u32 flags,
843 const FlagDesc *flagdesc, u32 flagmask)
845 return set(name, writeFlagString(flags, flagdesc, flagmask));
849 bool Settings::setStruct(const std::string &name, const std::string &format,
852 std::string structstr;
853 if (!serializeStructToString(&structstr, format, value))
856 return set(name, structstr);
860 bool Settings::setNoiseParams(const std::string &name,
861 const NoiseParams &np, bool set_default)
863 Settings *group = new Settings;
865 group->setFloat("offset", np.offset);
866 group->setFloat("scale", np.scale);
867 group->setV3F("spread", np.spread);
868 group->setS32("seed", np.seed);
869 group->setU16("octaves", np.octaves);
870 group->setFloat("persistence", np.persist);
871 group->setFloat("lacunarity", np.lacunarity);
872 group->setFlagStr("flags", np.flags, flagdesc_noiseparams, np.flags);
874 return setEntry(name, &group, true, set_default);
878 bool Settings::remove(const std::string &name)
880 JMutexAutoLock lock(m_mutex);
882 delete m_settings[name].group;
883 return m_settings.erase(name);
887 void Settings::clear()
889 JMutexAutoLock lock(m_mutex);
893 void Settings::clearDefaults()
895 JMutexAutoLock lock(m_mutex);
896 clearDefaultsNoLock();
899 void Settings::updateValue(const Settings &other, const std::string &name)
904 JMutexAutoLock lock(m_mutex);
907 std::string val = other.get(name);
909 m_settings[name] = val;
910 } catch (SettingNotFoundException &e) {
915 void Settings::update(const Settings &other)
920 JMutexAutoLock lock(m_mutex);
921 JMutexAutoLock lock2(other.m_mutex);
927 SettingsParseEvent Settings::parseConfigObject(const std::string &line,
928 const std::string &end, std::string &name, std::string &value)
930 std::string trimmed_line = trim(line);
932 if (trimmed_line.empty())
934 if (trimmed_line[0] == '#')
936 if (trimmed_line == end)
939 size_t pos = trimmed_line.find('=');
940 if (pos == std::string::npos)
943 name = trim(trimmed_line.substr(0, pos));
944 value = trim(trimmed_line.substr(pos + 1));
948 if (value == "\"\"\"")
949 return SPE_MULTILINE;
955 void Settings::updateNoLock(const Settings &other)
957 m_settings.insert(other.m_settings.begin(), other.m_settings.end());
958 m_defaults.insert(other.m_defaults.begin(), other.m_defaults.end());
962 void Settings::clearNoLock()
964 std::map<std::string, SettingsEntry>::const_iterator it;
965 for (it = m_settings.begin(); it != m_settings.end(); ++it)
966 delete it->second.group;
969 clearDefaultsNoLock();
972 void Settings::clearDefaultsNoLock()
974 std::map<std::string, SettingsEntry>::const_iterator it;
975 for (it = m_defaults.begin(); it != m_defaults.end(); ++it)
976 delete it->second.group;
981 void Settings::registerChangedCallback(std::string name,
982 setting_changed_callback cbf, void *userdata)
984 JMutexAutoLock lock(m_callbackMutex);
985 m_callbacks[name].push_back(std::make_pair(cbf, userdata));
988 void Settings::deregisterChangedCallback(std::string name, setting_changed_callback cbf, void *userdata)
990 JMutexAutoLock lock(m_callbackMutex);
991 std::map<std::string, std::vector<std::pair<setting_changed_callback, void*> > >::iterator iterToVector = m_callbacks.find(name);
992 if (iterToVector != m_callbacks.end())
994 std::vector<std::pair<setting_changed_callback, void*> > &vector = iterToVector->second;
996 std::vector<std::pair<setting_changed_callback, void*> >::iterator position =
997 std::find(vector.begin(), vector.end(), std::make_pair(cbf, userdata));
999 if (position != vector.end())
1000 vector.erase(position);
1004 void Settings::doCallbacks(const std::string name)
1006 JMutexAutoLock lock(m_callbackMutex);
1007 std::map<std::string, std::vector<std::pair<setting_changed_callback, void*> > >::iterator iterToVector = m_callbacks.find(name);
1008 if (iterToVector != m_callbacks.end())
1010 std::vector<std::pair<setting_changed_callback, void*> >::iterator iter;
1011 for (iter = iterToVector->second.begin(); iter != iterToVector->second.end(); iter++)
1013 (iter->first)(name, iter->second);