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 (SettingEntries::const_iterator it = m_settings.begin();
173 it != m_settings.end(); ++it)
174 printEntry(os, it->first, it->second, tab_depth);
178 void Settings::printEntry(std::ostream &os, const std::string &name,
179 const SettingsEntry &entry, u32 tab_depth)
181 for (u32 i = 0; i != tab_depth; i++)
184 if (entry.is_group) {
185 os << name << " = {\n";
187 entry.group->writeLines(os, tab_depth + 1);
189 for (u32 i = 0; i != tab_depth; i++)
195 if (entry.value.find('\n') != std::string::npos)
196 os << "\"\"\"\n" << entry.value << "\n\"\"\"\n";
198 os << entry.value << "\n";
203 bool Settings::updateConfigObject(std::istream &is, std::ostream &os,
204 const std::string &end, u32 tab_depth)
206 SettingEntries::const_iterator it;
207 std::set<std::string> present_entries;
208 std::string line, name, value;
209 bool was_modified = false;
210 bool end_found = false;
212 // Add any settings that exist in the config file with the current value
213 // in the object if existing
214 while (is.good() && !end_found) {
215 std::getline(is, line);
216 SettingsParseEvent event = parseConfigObject(line, end, name, value);
220 os << line << (is.eof() ? "" : "\n");
224 value = getMultiline(is);
227 it = m_settings.find(name);
228 if (it != m_settings.end() &&
229 (it->second.is_group || it->second.value != value)) {
230 printEntry(os, name, it->second, tab_depth);
234 if (event == SPE_MULTILINE)
235 os << value << "\n\"\"\"\n";
237 present_entries.insert(name);
240 it = m_settings.find(name);
241 if (it != m_settings.end() && it->second.is_group) {
243 sanity_check(it->second.group != NULL);
244 was_modified |= it->second.group->updateConfigObject(is, os,
247 printEntry(os, name, it->second, tab_depth);
250 present_entries.insert(name);
253 os << line << (is.eof() ? "" : "\n");
258 // Add any settings in the object that don't exist in the config file yet
259 for (it = m_settings.begin(); it != m_settings.end(); ++it) {
260 if (present_entries.find(it->first) != present_entries.end())
263 printEntry(os, it->first, it->second, tab_depth);
271 bool Settings::updateConfigFile(const char *filename)
273 MutexAutoLock lock(m_mutex);
275 std::ifstream is(filename);
276 std::ostringstream os(std::ios_base::binary);
278 bool was_modified = updateConfigObject(is, os, "");
284 if (!fs::safeWriteToFile(filename, os.str())) {
285 errorstream << "Error writing configuration file: \""
286 << filename << "\"" << std::endl;
294 bool Settings::parseCommandLine(int argc, char *argv[],
295 std::map<std::string, ValueSpec> &allowed_options)
297 int nonopt_index = 0;
298 for (int i = 1; i < argc; i++) {
299 std::string arg_name = argv[i];
300 if (arg_name.substr(0, 2) != "--") {
301 // If option doesn't start with -, read it in as nonoptX
302 if (arg_name[0] != '-'){
303 std::string name = "nonopt";
304 name += itos(nonopt_index);
309 errorstream << "Invalid command-line parameter \""
310 << arg_name << "\": --<option> expected." << std::endl;
314 std::string name = arg_name.substr(2);
316 std::map<std::string, ValueSpec>::iterator n;
317 n = allowed_options.find(name);
318 if (n == allowed_options.end()) {
319 errorstream << "Unknown command-line parameter \""
320 << arg_name << "\"" << std::endl;
324 ValueType type = n->second.type;
326 std::string value = "";
328 if (type == VALUETYPE_FLAG) {
331 if ((i + 1) >= argc) {
332 errorstream << "Invalid command-line parameter \""
333 << name << "\": missing value" << std::endl;
352 const SettingsEntry &Settings::getEntry(const std::string &name) const
354 MutexAutoLock lock(m_mutex);
356 SettingEntries::const_iterator n;
357 if ((n = m_settings.find(name)) == m_settings.end()) {
358 if ((n = m_defaults.find(name)) == m_defaults.end())
359 throw SettingNotFoundException("Setting [" + name + "] not found.");
365 Settings *Settings::getGroup(const std::string &name) const
367 const SettingsEntry &entry = getEntry(name);
369 throw SettingNotFoundException("Setting [" + name + "] is not a group.");
374 const std::string &Settings::get(const std::string &name) const
376 const SettingsEntry &entry = getEntry(name);
378 throw SettingNotFoundException("Setting [" + name + "] is a group.");
383 bool Settings::getBool(const std::string &name) const
385 return is_yes(get(name));
389 u16 Settings::getU16(const std::string &name) const
391 return stoi(get(name), 0, 65535);
395 s16 Settings::getS16(const std::string &name) const
397 return stoi(get(name), -32768, 32767);
401 s32 Settings::getS32(const std::string &name) const
403 return stoi(get(name));
407 float Settings::getFloat(const std::string &name) const
409 return stof(get(name));
413 u64 Settings::getU64(const std::string &name) const
416 std::string s = get(name);
417 std::istringstream ss(s);
423 v2f Settings::getV2F(const std::string &name) const
428 value.X = stof(f.next(","));
429 value.Y = stof(f.next(")"));
434 v3f Settings::getV3F(const std::string &name) const
439 value.X = stof(f.next(","));
440 value.Y = stof(f.next(","));
441 value.Z = stof(f.next(")"));
446 u32 Settings::getFlagStr(const std::string &name, const FlagDesc *flagdesc,
449 std::string val = get(name);
450 return std::isdigit(val[0])
452 : readFlagString(val, flagdesc, flagmask);
456 // N.B. if getStruct() is used to read a non-POD aggregate type,
457 // the behavior is undefined.
458 bool Settings::getStruct(const std::string &name, const std::string &format,
459 void *out, size_t olen) const
465 } catch (SettingNotFoundException &e) {
469 if (!deSerializeStringToStruct(valstr, format, out, olen))
476 bool Settings::getNoiseParams(const std::string &name, NoiseParams &np) const
478 return getNoiseParamsFromGroup(name, np) || getNoiseParamsFromValue(name, np);
482 bool Settings::getNoiseParamsFromValue(const std::string &name,
483 NoiseParams &np) const
487 if (!getNoEx(name, value))
492 np.offset = stof(f.next(","));
493 np.scale = stof(f.next(","));
495 np.spread.X = stof(f.next(","));
496 np.spread.Y = stof(f.next(","));
497 np.spread.Z = stof(f.next(")"));
499 np.seed = stoi(f.next(","));
500 np.octaves = stoi(f.next(","));
501 np.persist = stof(f.next(","));
503 std::string optional_params = f.next("");
504 if (optional_params != "")
505 np.lacunarity = stof(optional_params);
511 bool Settings::getNoiseParamsFromGroup(const std::string &name,
512 NoiseParams &np) const
514 Settings *group = NULL;
516 if (!getGroupNoEx(name, group))
519 group->getFloatNoEx("offset", np.offset);
520 group->getFloatNoEx("scale", np.scale);
521 group->getV3FNoEx("spread", np.spread);
522 group->getS32NoEx("seed", np.seed);
523 group->getU16NoEx("octaves", np.octaves);
524 group->getFloatNoEx("persistence", np.persist);
525 group->getFloatNoEx("lacunarity", np.lacunarity);
528 if (!group->getFlagStrNoEx("flags", np.flags, flagdesc_noiseparams))
529 np.flags = NOISE_FLAG_DEFAULTS;
535 bool Settings::exists(const std::string &name) const
537 MutexAutoLock lock(m_mutex);
539 return (m_settings.find(name) != m_settings.end() ||
540 m_defaults.find(name) != m_defaults.end());
544 std::vector<std::string> Settings::getNames() const
546 std::vector<std::string> names;
547 for (SettingEntries::const_iterator i = m_settings.begin();
548 i != m_settings.end(); ++i) {
549 names.push_back(i->first);
556 /***************************************
557 * Getters that don't throw exceptions *
558 ***************************************/
560 bool Settings::getEntryNoEx(const std::string &name, SettingsEntry &val) const
563 val = getEntry(name);
565 } catch (SettingNotFoundException &e) {
571 bool Settings::getGroupNoEx(const std::string &name, Settings *&val) const
574 val = getGroup(name);
576 } catch (SettingNotFoundException &e) {
582 bool Settings::getNoEx(const std::string &name, std::string &val) const
587 } catch (SettingNotFoundException &e) {
593 bool Settings::getFlag(const std::string &name) const
596 return getBool(name);
597 } catch(SettingNotFoundException &e) {
603 bool Settings::getFloatNoEx(const std::string &name, float &val) const
606 val = getFloat(name);
608 } catch (SettingNotFoundException &e) {
614 bool Settings::getU16NoEx(const std::string &name, u16 &val) const
619 } catch (SettingNotFoundException &e) {
625 bool Settings::getS16NoEx(const std::string &name, s16 &val) const
630 } catch (SettingNotFoundException &e) {
636 bool Settings::getS32NoEx(const std::string &name, s32 &val) const
641 } catch (SettingNotFoundException &e) {
647 bool Settings::getU64NoEx(const std::string &name, u64 &val) const
652 } catch (SettingNotFoundException &e) {
658 bool Settings::getV2FNoEx(const std::string &name, v2f &val) const
663 } catch (SettingNotFoundException &e) {
669 bool Settings::getV3FNoEx(const std::string &name, v3f &val) const
674 } catch (SettingNotFoundException &e) {
680 // N.B. getFlagStrNoEx() does not set val, but merely modifies it. Thus,
681 // val must be initialized before using getFlagStrNoEx(). The intention of
682 // this is to simplify modifying a flags field from a default value.
683 bool Settings::getFlagStrNoEx(const std::string &name, u32 &val,
684 FlagDesc *flagdesc) const
689 flags = getFlagStr(name, flagdesc, &flagmask);
695 } catch (SettingNotFoundException &e) {
705 bool Settings::setEntry(const std::string &name, const void *data,
706 bool set_group, bool set_default)
708 Settings *old_group = NULL;
710 if (!checkNameValid(name))
712 if (!set_group && !checkValueValid(*(const std::string *)data))
716 MutexAutoLock lock(m_mutex);
718 SettingsEntry &entry = set_default ? m_defaults[name] : m_settings[name];
719 old_group = entry.group;
721 entry.value = set_group ? "" : *(const std::string *)data;
722 entry.group = set_group ? *(Settings **)data : NULL;
723 entry.is_group = set_group;
732 bool Settings::set(const std::string &name, const std::string &value)
734 if (!setEntry(name, &value, false, false))
742 bool Settings::setDefault(const std::string &name, const std::string &value)
744 return setEntry(name, &value, false, true);
748 bool Settings::setGroup(const std::string &name, Settings *group)
750 return setEntry(name, &group, true, false);
754 bool Settings::setGroupDefault(const std::string &name, Settings *group)
756 return setEntry(name, &group, true, true);
760 bool Settings::setBool(const std::string &name, bool value)
762 return set(name, value ? "true" : "false");
766 bool Settings::setS16(const std::string &name, s16 value)
768 return set(name, itos(value));
772 bool Settings::setU16(const std::string &name, u16 value)
774 return set(name, itos(value));
778 bool Settings::setS32(const std::string &name, s32 value)
780 return set(name, itos(value));
784 bool Settings::setU64(const std::string &name, u64 value)
786 std::ostringstream os;
788 return set(name, os.str());
792 bool Settings::setFloat(const std::string &name, float value)
794 return set(name, ftos(value));
798 bool Settings::setV2F(const std::string &name, v2f value)
800 std::ostringstream os;
801 os << "(" << value.X << "," << value.Y << ")";
802 return set(name, os.str());
806 bool Settings::setV3F(const std::string &name, v3f value)
808 std::ostringstream os;
809 os << "(" << value.X << "," << value.Y << "," << value.Z << ")";
810 return set(name, os.str());
814 bool Settings::setFlagStr(const std::string &name, u32 flags,
815 const FlagDesc *flagdesc, u32 flagmask)
817 return set(name, writeFlagString(flags, flagdesc, flagmask));
821 bool Settings::setStruct(const std::string &name, const std::string &format,
824 std::string structstr;
825 if (!serializeStructToString(&structstr, format, value))
828 return set(name, structstr);
832 bool Settings::setNoiseParams(const std::string &name,
833 const NoiseParams &np, bool set_default)
835 Settings *group = new Settings;
837 group->setFloat("offset", np.offset);
838 group->setFloat("scale", np.scale);
839 group->setV3F("spread", np.spread);
840 group->setS32("seed", np.seed);
841 group->setU16("octaves", np.octaves);
842 group->setFloat("persistence", np.persist);
843 group->setFloat("lacunarity", np.lacunarity);
844 group->setFlagStr("flags", np.flags, flagdesc_noiseparams, np.flags);
846 return setEntry(name, &group, true, set_default);
850 bool Settings::remove(const std::string &name)
852 MutexAutoLock lock(m_mutex);
854 SettingEntries::iterator it = m_settings.find(name);
855 if (it != m_settings.end()) {
856 delete it->second.group;
857 m_settings.erase(it);
865 void Settings::clear()
867 MutexAutoLock lock(m_mutex);
871 void Settings::clearDefaults()
873 MutexAutoLock lock(m_mutex);
874 clearDefaultsNoLock();
877 void Settings::updateValue(const Settings &other, const std::string &name)
882 MutexAutoLock lock(m_mutex);
885 std::string val = other.get(name);
886 m_settings[name] = val;
887 } catch (SettingNotFoundException &e) {
892 void Settings::update(const Settings &other)
897 MutexAutoLock lock(m_mutex);
898 MutexAutoLock lock2(other.m_mutex);
904 SettingsParseEvent Settings::parseConfigObject(const std::string &line,
905 const std::string &end, std::string &name, std::string &value)
907 std::string trimmed_line = trim(line);
909 if (trimmed_line.empty())
911 if (trimmed_line[0] == '#')
913 if (trimmed_line == end)
916 size_t pos = trimmed_line.find('=');
917 if (pos == std::string::npos)
920 name = trim(trimmed_line.substr(0, pos));
921 value = trim(trimmed_line.substr(pos + 1));
925 if (value == "\"\"\"")
926 return SPE_MULTILINE;
932 void Settings::updateNoLock(const Settings &other)
934 m_settings.insert(other.m_settings.begin(), other.m_settings.end());
935 m_defaults.insert(other.m_defaults.begin(), other.m_defaults.end());
939 void Settings::clearNoLock()
942 for (SettingEntries::const_iterator it = m_settings.begin();
943 it != m_settings.end(); ++it)
944 delete it->second.group;
947 clearDefaultsNoLock();
950 void Settings::clearDefaultsNoLock()
952 for (SettingEntries::const_iterator it = m_defaults.begin();
953 it != m_defaults.end(); ++it)
954 delete it->second.group;
959 void Settings::registerChangedCallback(const std::string &name,
960 SettingsChangedCallback cbf, void *userdata)
962 MutexAutoLock lock(m_callback_mutex);
963 m_callbacks[name].push_back(std::make_pair(cbf, userdata));
966 void Settings::deregisterChangedCallback(const std::string &name,
967 SettingsChangedCallback cbf, void *userdata)
969 MutexAutoLock lock(m_callback_mutex);
970 SettingsCallbackMap::iterator it_cbks = m_callbacks.find(name);
972 if (it_cbks != m_callbacks.end()) {
973 SettingsCallbackList &cbks = it_cbks->second;
975 SettingsCallbackList::iterator position =
976 std::find(cbks.begin(), cbks.end(), std::make_pair(cbf, userdata));
978 if (position != cbks.end())
979 cbks.erase(position);
983 void Settings::doCallbacks(const std::string &name) const
985 MutexAutoLock lock(m_callback_mutex);
987 SettingsCallbackMap::const_iterator it_cbks = m_callbacks.find(name);
988 if (it_cbks != m_callbacks.end()) {
989 SettingsCallbackList::const_iterator it;
990 for (it = it_cbks->second.begin(); it != it_cbks->second.end(); ++it)
991 (it->first)(name, it->second);