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);
257 assert(it->second.group == NULL);
259 if (event == SPE_MULTILINE)
260 os << value << "\n\"\"\"\n";
262 present_entries.insert(name);
265 it = m_settings.find(name);
266 if (it != m_settings.end() && it->second.is_group) {
268 assert(it->second.group != NULL);
269 was_modified |= it->second.group->updateConfigObject(is, os,
272 printEntry(os, name, it->second, tab_depth);
275 present_entries.insert(name);
278 os << line << (is.eof() ? "" : "\n");
283 // Add any settings in the object that don't exist in the config file yet
284 for (it = m_settings.begin(); it != m_settings.end(); ++it) {
285 if (present_entries.find(it->first) != present_entries.end())
288 printEntry(os, it->first, it->second, tab_depth);
296 bool Settings::updateConfigFile(const char *filename)
298 JMutexAutoLock lock(m_mutex);
300 std::ifstream is(filename);
301 std::ostringstream os(std::ios_base::binary);
303 bool was_modified = updateConfigObject(is, os, "");
309 if (!fs::safeWriteToFile(filename, os.str())) {
310 errorstream << "Error writing configuration file: \""
311 << filename << "\"" << std::endl;
319 bool Settings::parseCommandLine(int argc, char *argv[],
320 std::map<std::string, ValueSpec> &allowed_options)
322 int nonopt_index = 0;
323 for (int i = 1; i < argc; i++) {
324 std::string arg_name = argv[i];
325 if (arg_name.substr(0, 2) != "--") {
326 // If option doesn't start with -, read it in as nonoptX
327 if (arg_name[0] != '-'){
328 std::string name = "nonopt";
329 name += itos(nonopt_index);
334 errorstream << "Invalid command-line parameter \""
335 << arg_name << "\": --<option> expected." << std::endl;
339 std::string name = arg_name.substr(2);
341 std::map<std::string, ValueSpec>::iterator n;
342 n = allowed_options.find(name);
343 if (n == allowed_options.end()) {
344 errorstream << "Unknown command-line parameter \""
345 << arg_name << "\"" << std::endl;
349 ValueType type = n->second.type;
351 std::string value = "";
353 if (type == VALUETYPE_FLAG) {
356 if ((i + 1) >= argc) {
357 errorstream << "Invalid command-line parameter \""
358 << name << "\": missing value" << std::endl;
377 const SettingsEntry &Settings::getEntry(const std::string &name) const
379 JMutexAutoLock lock(m_mutex);
381 std::map<std::string, SettingsEntry>::const_iterator n;
382 if ((n = m_settings.find(name)) == m_settings.end()) {
383 if ((n = m_defaults.find(name)) == m_defaults.end())
384 throw SettingNotFoundException("Setting [" + name + "] not found.");
390 Settings *Settings::getGroup(const std::string &name) const
392 const SettingsEntry &entry = getEntry(name);
394 throw SettingNotFoundException("Setting [" + name + "] is not a group.");
399 std::string Settings::get(const std::string &name) const
401 const SettingsEntry &entry = getEntry(name);
403 throw SettingNotFoundException("Setting [" + name + "] is a group.");
408 bool Settings::getBool(const std::string &name) const
410 return is_yes(get(name));
414 u16 Settings::getU16(const std::string &name) const
416 return stoi(get(name), 0, 65535);
420 s16 Settings::getS16(const std::string &name) const
422 return stoi(get(name), -32768, 32767);
426 s32 Settings::getS32(const std::string &name) const
428 return stoi(get(name));
432 float Settings::getFloat(const std::string &name) const
434 return stof(get(name));
438 u64 Settings::getU64(const std::string &name) const
441 std::string s = get(name);
442 std::istringstream ss(s);
448 v2f Settings::getV2F(const std::string &name) const
453 value.X = stof(f.next(","));
454 value.Y = stof(f.next(")"));
459 v3f Settings::getV3F(const std::string &name) const
464 value.X = stof(f.next(","));
465 value.Y = stof(f.next(","));
466 value.Z = stof(f.next(")"));
471 u32 Settings::getFlagStr(const std::string &name, const FlagDesc *flagdesc,
474 std::string val = get(name);
475 return std::isdigit(val[0])
477 : readFlagString(val, flagdesc, flagmask);
481 // N.B. if getStruct() is used to read a non-POD aggregate type,
482 // the behavior is undefined.
483 bool Settings::getStruct(const std::string &name, const std::string &format,
484 void *out, size_t olen) const
490 } catch (SettingNotFoundException &e) {
494 if (!deSerializeStringToStruct(valstr, format, out, olen))
501 bool Settings::getNoiseParams(const std::string &name, NoiseParams &np) const
503 return getNoiseParamsFromGroup(name, np) || getNoiseParamsFromValue(name, np);
507 bool Settings::getNoiseParamsFromValue(const std::string &name,
508 NoiseParams &np) const
512 if (!getNoEx(name, value))
517 np.offset = stof(f.next(","));
518 np.scale = stof(f.next(","));
520 np.spread.X = stof(f.next(","));
521 np.spread.Y = stof(f.next(","));
522 np.spread.Z = stof(f.next(")"));
524 np.seed = stoi(f.next(","));
525 np.octaves = stoi(f.next(","));
526 np.persist = stof(f.next(","));
528 std::string optional_params = f.next("");
529 if (optional_params != "")
530 np.lacunarity = stof(optional_params);
536 bool Settings::getNoiseParamsFromGroup(const std::string &name,
537 NoiseParams &np) const
539 Settings *group = NULL;
541 if (!getGroupNoEx(name, group))
544 group->getFloatNoEx("offset", np.offset);
545 group->getFloatNoEx("scale", np.scale);
546 group->getV3FNoEx("spread", np.spread);
547 group->getS32NoEx("seed", np.seed);
548 group->getU16NoEx("octaves", np.octaves);
549 group->getFloatNoEx("persistence", np.persist);
550 group->getFloatNoEx("lacunarity", np.lacunarity);
553 if (!group->getFlagStrNoEx("flags", np.flags, flagdesc_noiseparams))
554 np.flags = NOISE_FLAG_DEFAULTS;
560 bool Settings::exists(const std::string &name) const
562 JMutexAutoLock lock(m_mutex);
564 return (m_settings.find(name) != m_settings.end() ||
565 m_defaults.find(name) != m_defaults.end());
569 std::vector<std::string> Settings::getNames() const
571 std::vector<std::string> names;
572 for (std::map<std::string, SettingsEntry>::const_iterator
573 i = m_settings.begin();
574 i != m_settings.end(); ++i) {
575 names.push_back(i->first);
582 /***************************************
583 * Getters that don't throw exceptions *
584 ***************************************/
586 bool Settings::getEntryNoEx(const std::string &name, SettingsEntry &val) const
589 val = getEntry(name);
591 } catch (SettingNotFoundException &e) {
597 bool Settings::getGroupNoEx(const std::string &name, Settings *&val) const
600 val = getGroup(name);
602 } catch (SettingNotFoundException &e) {
608 bool Settings::getNoEx(const std::string &name, std::string &val) const
613 } catch (SettingNotFoundException &e) {
619 bool Settings::getFlag(const std::string &name) const
622 return getBool(name);
623 } catch(SettingNotFoundException &e) {
629 bool Settings::getFloatNoEx(const std::string &name, float &val) const
632 val = getFloat(name);
634 } catch (SettingNotFoundException &e) {
640 bool Settings::getU16NoEx(const std::string &name, u16 &val) const
645 } catch (SettingNotFoundException &e) {
651 bool Settings::getS16NoEx(const std::string &name, s16 &val) const
656 } catch (SettingNotFoundException &e) {
662 bool Settings::getS32NoEx(const std::string &name, s32 &val) const
667 } catch (SettingNotFoundException &e) {
673 bool Settings::getU64NoEx(const std::string &name, u64 &val) const
678 } catch (SettingNotFoundException &e) {
684 bool Settings::getV2FNoEx(const std::string &name, v2f &val) const
689 } catch (SettingNotFoundException &e) {
695 bool Settings::getV3FNoEx(const std::string &name, v3f &val) const
700 } catch (SettingNotFoundException &e) {
706 // N.B. getFlagStrNoEx() does not set val, but merely modifies it. Thus,
707 // val must be initialized before using getFlagStrNoEx(). The intention of
708 // this is to simplify modifying a flags field from a default value.
709 bool Settings::getFlagStrNoEx(const std::string &name, u32 &val,
710 FlagDesc *flagdesc) const
715 flags = getFlagStr(name, flagdesc, &flagmask);
721 } catch (SettingNotFoundException &e) {
731 bool Settings::setEntry(const std::string &name, const void *data,
732 bool set_group, bool set_default)
734 Settings *old_group = NULL;
736 if (!checkNameValid(name))
738 if (!set_group && !checkValueValid(*(const std::string *)data))
742 JMutexAutoLock lock(m_mutex);
744 SettingsEntry &entry = set_default ? m_defaults[name] : m_settings[name];
745 old_group = entry.group;
747 entry.value = set_group ? "" : *(const std::string *)data;
748 entry.group = set_group ? *(Settings **)data : NULL;
749 entry.is_group = set_group;
758 bool Settings::set(const std::string &name, const std::string &value)
760 if (!setEntry(name, &value, false, false))
768 bool Settings::setDefault(const std::string &name, const std::string &value)
770 return setEntry(name, &value, false, true);
774 bool Settings::setGroup(const std::string &name, Settings *group)
776 return setEntry(name, &group, true, false);
780 bool Settings::setGroupDefault(const std::string &name, Settings *group)
782 return setEntry(name, &group, true, true);
786 bool Settings::setBool(const std::string &name, bool value)
788 return set(name, value ? "true" : "false");
792 bool Settings::setS16(const std::string &name, s16 value)
794 return set(name, itos(value));
798 bool Settings::setU16(const std::string &name, u16 value)
800 return set(name, itos(value));
804 bool Settings::setS32(const std::string &name, s32 value)
806 return set(name, itos(value));
810 bool Settings::setU64(const std::string &name, u64 value)
812 std::ostringstream os;
814 return set(name, os.str());
818 bool Settings::setFloat(const std::string &name, float value)
820 return set(name, ftos(value));
824 bool Settings::setV2F(const std::string &name, v2f value)
826 std::ostringstream os;
827 os << "(" << value.X << "," << value.Y << ")";
828 return set(name, os.str());
832 bool Settings::setV3F(const std::string &name, v3f value)
834 std::ostringstream os;
835 os << "(" << value.X << "," << value.Y << "," << value.Z << ")";
836 return set(name, os.str());
840 bool Settings::setFlagStr(const std::string &name, u32 flags,
841 const FlagDesc *flagdesc, u32 flagmask)
843 return set(name, writeFlagString(flags, flagdesc, flagmask));
847 bool Settings::setStruct(const std::string &name, const std::string &format,
850 std::string structstr;
851 if (!serializeStructToString(&structstr, format, value))
854 return set(name, structstr);
858 bool Settings::setNoiseParams(const std::string &name,
859 const NoiseParams &np, bool set_default)
861 Settings *group = new Settings;
863 group->setFloat("offset", np.offset);
864 group->setFloat("scale", np.scale);
865 group->setV3F("spread", np.spread);
866 group->setS32("seed", np.seed);
867 group->setU16("octaves", np.octaves);
868 group->setFloat("persistence", np.persist);
869 group->setFloat("lacunarity", np.lacunarity);
870 group->setFlagStr("flags", np.flags, flagdesc_noiseparams, np.flags);
872 return setEntry(name, &group, true, set_default);
876 bool Settings::remove(const std::string &name)
878 JMutexAutoLock lock(m_mutex);
880 delete m_settings[name].group;
881 return m_settings.erase(name);
885 void Settings::clear()
887 JMutexAutoLock lock(m_mutex);
892 void Settings::updateValue(const Settings &other, const std::string &name)
897 JMutexAutoLock lock(m_mutex);
900 std::string val = other.get(name);
902 m_settings[name] = val;
903 } catch (SettingNotFoundException &e) {
908 void Settings::update(const Settings &other)
913 JMutexAutoLock lock(m_mutex);
914 JMutexAutoLock lock2(other.m_mutex);
920 SettingsParseEvent Settings::parseConfigObject(const std::string &line,
921 const std::string &end, std::string &name, std::string &value)
923 std::string trimmed_line = trim(line);
925 if (trimmed_line.empty())
927 if (trimmed_line[0] == '#')
929 if (trimmed_line == end)
932 size_t pos = trimmed_line.find('=');
933 if (pos == std::string::npos)
936 name = trim(trimmed_line.substr(0, pos));
937 value = trim(trimmed_line.substr(pos + 1));
941 if (value == "\"\"\"")
942 return SPE_MULTILINE;
948 void Settings::updateNoLock(const Settings &other)
950 m_settings.insert(other.m_settings.begin(), other.m_settings.end());
951 m_defaults.insert(other.m_defaults.begin(), other.m_defaults.end());
955 void Settings::clearNoLock()
957 std::map<std::string, SettingsEntry>::const_iterator it;
958 for (it = m_settings.begin(); it != m_settings.end(); ++it)
959 delete it->second.group;
962 for (it = m_defaults.begin(); it != m_defaults.end(); ++it)
963 delete it->second.group;
968 void Settings::registerChangedCallback(std::string name,
969 setting_changed_callback cbf)
971 m_callbacks[name].push_back(cbf);
975 void Settings::doCallbacks(const std::string name)
977 std::vector<setting_changed_callback> tempvector;
979 JMutexAutoLock lock(m_mutex);
980 if (m_callbacks.find(name) != m_callbacks.end())
982 tempvector = m_callbacks[name];
986 std::vector<setting_changed_callback>::iterator iter;
987 for (iter = tempvector.begin(); iter != tempvector.end(); iter++)