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"
39 std::map<std::string, SettingsEntry>::const_iterator it;
40 for (it = m_settings.begin(); it != m_settings.end(); ++it)
41 delete it->second.group;
45 Settings & Settings::operator += (const Settings &other)
53 Settings & Settings::operator = (const Settings &other)
58 JMutexAutoLock lock(m_mutex);
59 JMutexAutoLock lock2(other.m_mutex);
68 std::string Settings::sanitizeString(const std::string &value)
70 std::string str = value;
71 for (const char *s = "\t\n\v\f\r\b =\""; *s; s++)
72 str.erase(std::remove(str.begin(), str.end(), *s), str.end());
78 std::string Settings::getMultiline(std::istream &is, size_t *num_lines)
86 std::getline(is, line);
90 value.push_back('\n');
93 size_t len = value.size();
104 bool Settings::parseConfigLines(std::istream &is, const std::string &end)
106 JMutexAutoLock lock(m_mutex);
108 std::string line, name, value;
111 std::getline(is, line);
112 SettingsParseEvent event = parseConfigObject(line, end, name, value);
120 m_settings[name] = SettingsEntry(value);
125 Settings *branch = new Settings;
126 if (!branch->parseConfigLines(is, "}"))
129 m_settings[name] = SettingsEntry(branch);
133 m_settings[name] = SettingsEntry(getMultiline(is));
142 bool Settings::readConfigFile(const char *filename)
144 std::ifstream is(filename);
148 return parseConfigLines(is, "");
152 void Settings::writeLines(std::ostream &os, u32 tab_depth) const
154 JMutexAutoLock lock(m_mutex);
156 for (std::map<std::string, SettingsEntry>::const_iterator
157 it = m_settings.begin();
158 it != m_settings.end(); ++it)
159 printEntry(os, it->first, it->second, tab_depth);
163 bool Settings::printEntry(std::ostream &os, const std::string &name,
164 const SettingsEntry &entry, u32 tab_depth)
166 bool printed = false;
168 if (!entry.group || entry.value != "") {
169 printValue(os, name, entry.value, tab_depth);
174 printGroup(os, name, entry.group, tab_depth);
183 void Settings::printValue(std::ostream &os, const std::string &name,
184 const std::string &value, u32 tab_depth)
186 for (u32 i = 0; i != tab_depth; i++)
190 if (value.find('\n') != std::string::npos)
191 os << "\"\"\"\n" << value << "\n\"\"\"\n";
197 void Settings::printGroup(std::ostream &os, const std::string &name,
198 const Settings *group, u32 tab_depth)
200 // Recursively write group contents
201 for (u32 i = 0; i != tab_depth; i++)
204 os << name << " = {\n";
205 group->writeLines(os, tab_depth + 1);
207 for (u32 i = 0; i != tab_depth; i++)
214 void Settings::getNamesPresent(std::istream &is, const std::string &end,
215 std::set<std::string> &present_values, std::set<std::string> &present_groups)
217 std::string name, value, line;
218 bool end_found = false;
220 size_t old_pos = is.tellg();
222 while (is.good() && !end_found) {
223 std::getline(is, line);
224 SettingsParseEvent event = parseConfigObject(line,
225 depth ? "}" : end, name, value);
235 while (is.good() && line != "\"\"\"")
236 std::getline(is, line);
240 present_values.insert(name);
244 present_groups.insert(name);
259 bool Settings::updateConfigObject(std::istream &is, std::ostream &os,
260 const std::string &end, u32 tab_depth)
262 std::map<std::string, SettingsEntry>::const_iterator it;
263 std::set<std::string> present_values, present_groups;
264 std::string line, name, value;
265 bool was_modified = false;
266 bool end_found = false;
268 getNamesPresent(is, end, present_values, present_groups);
270 // Add any settings that exist in the config file with the current value
271 // in the object if existing
272 while (is.good() && !end_found) {
273 std::getline(is, line);
274 SettingsParseEvent event = parseConfigObject(line, end, name, value);
278 os << line << (is.eof() ? "" : "\n");
282 value = getMultiline(is);
285 it = m_settings.find(name);
286 if (it != m_settings.end() && value != it->second.value) {
287 if (!it->second.group || it->second.value != "")
288 printValue(os, name, it->second.value, tab_depth);
292 if (event == SPE_MULTILINE)
293 os << value << "\n\"\"\"\n";
296 // If this value name has a group not in the file, print it
297 if (it != m_settings.end() && it->second.group &&
298 present_groups.find(name) == present_groups.end()) {
299 printGroup(os, name, it->second.group, tab_depth);
305 Settings *group = NULL;
306 it = m_settings.find(name);
307 if (it != m_settings.end())
308 group = it->second.group;
310 // If this group name has a non-blank value not in the file, print it
311 if (it != m_settings.end() && it->second.value != "" &&
312 present_values.find(name) == present_values.end()) {
313 printValue(os, name, it->second.value, tab_depth);
320 was_modified |= group->updateConfigObject(is, os, "}", tab_depth + 1);
322 // If a group exists in the file but not memory, don't touch it
323 Settings dummy_settings;
324 dummy_settings.updateConfigObject(is, os, "}", tab_depth + 1);
329 os << line << (is.eof() ? "" : "\n");
334 // Add any settings in the object that don't exist in the config file yet
335 for (it = m_settings.begin(); it != m_settings.end(); ++it) {
336 if (present_values.find(it->first) != present_values.end() ||
337 present_groups.find(it->first) != present_groups.end())
340 was_modified |= printEntry(os, it->first, it->second, tab_depth);
347 bool Settings::updateConfigFile(const char *filename)
349 JMutexAutoLock lock(m_mutex);
351 std::ifstream is(filename);
352 std::ostringstream os(std::ios_base::binary);
354 if (!updateConfigObject(is, os, ""))
357 if (!fs::safeWriteToFile(filename, os.str())) {
358 errorstream << "Error writing configuration file: \""
359 << filename << "\"" << std::endl;
367 bool Settings::parseCommandLine(int argc, char *argv[],
368 std::map<std::string, ValueSpec> &allowed_options)
370 int nonopt_index = 0;
371 for (int i = 1; i < argc; i++) {
372 std::string arg_name = argv[i];
373 if (arg_name.substr(0, 2) != "--") {
374 // If option doesn't start with -, read it in as nonoptX
375 if (arg_name[0] != '-'){
376 std::string name = "nonopt";
377 name += itos(nonopt_index);
382 errorstream << "Invalid command-line parameter \""
383 << arg_name << "\": --<option> expected." << std::endl;
387 std::string name = arg_name.substr(2);
389 std::map<std::string, ValueSpec>::iterator n;
390 n = allowed_options.find(name);
391 if (n == allowed_options.end()) {
392 errorstream << "Unknown command-line parameter \""
393 << arg_name << "\"" << std::endl;
397 ValueType type = n->second.type;
399 std::string value = "";
401 if (type == VALUETYPE_FLAG) {
404 if ((i + 1) >= argc) {
405 errorstream << "Invalid command-line parameter \""
406 << name << "\": missing value" << std::endl;
425 const SettingsEntry &Settings::getEntry(const std::string &name) const
427 JMutexAutoLock lock(m_mutex);
429 std::map<std::string, SettingsEntry>::const_iterator n;
430 if ((n = m_settings.find(name)) == m_settings.end()) {
431 if ((n = m_defaults.find(name)) == m_defaults.end())
432 throw SettingNotFoundException("Setting [" + name + "] not found.");
438 Settings *Settings::getGroup(const std::string &name) const
440 Settings *group = getEntry(name).group;
442 throw SettingNotFoundException("Setting [" + name + "] is not a group.");
447 std::string Settings::get(const std::string &name) const
449 return getEntry(name).value;
453 bool Settings::getBool(const std::string &name) const
455 return is_yes(get(name));
459 u16 Settings::getU16(const std::string &name) const
461 return stoi(get(name), 0, 65535);
465 s16 Settings::getS16(const std::string &name) const
467 return stoi(get(name), -32768, 32767);
471 s32 Settings::getS32(const std::string &name) const
473 return stoi(get(name));
477 float Settings::getFloat(const std::string &name) const
479 return stof(get(name));
483 u64 Settings::getU64(const std::string &name) const
486 std::string s = get(name);
487 std::istringstream ss(s);
493 v2f Settings::getV2F(const std::string &name) const
498 value.X = stof(f.next(","));
499 value.Y = stof(f.next(")"));
504 v3f Settings::getV3F(const std::string &name) const
509 value.X = stof(f.next(","));
510 value.Y = stof(f.next(","));
511 value.Z = stof(f.next(")"));
516 u32 Settings::getFlagStr(const std::string &name, const FlagDesc *flagdesc,
519 std::string val = get(name);
520 return std::isdigit(val[0])
522 : readFlagString(val, flagdesc, flagmask);
526 // N.B. if getStruct() is used to read a non-POD aggregate type,
527 // the behavior is undefined.
528 bool Settings::getStruct(const std::string &name, const std::string &format,
529 void *out, size_t olen) const
535 } catch (SettingNotFoundException &e) {
539 if (!deSerializeStringToStruct(valstr, format, out, olen))
546 bool Settings::getNoiseParams(const std::string &name, NoiseParams &np) const
548 return getNoiseParamsFromGroup(name, np) || getNoiseParamsFromValue(name, np);
552 bool Settings::getNoiseParamsFromValue(const std::string &name,
553 NoiseParams &np) const
557 if (!getNoEx(name, value))
562 np.offset = stof(f.next(","));
563 np.scale = stof(f.next(","));
565 np.spread.X = stof(f.next(","));
566 np.spread.Y = stof(f.next(","));
567 np.spread.Z = stof(f.next(")"));
569 np.seed = stoi(f.next(","));
570 np.octaves = stoi(f.next(","));
571 np.persist = stof(f.next(""));
577 bool Settings::getNoiseParamsFromGroup(const std::string &name,
578 NoiseParams &np) const
580 Settings *group = NULL;
582 if (!getGroupNoEx(name, group))
585 group->getFloatNoEx("offset", np.offset);
586 group->getFloatNoEx("scale", np.scale);
587 group->getV3FNoEx("spread", np.spread);
588 group->getS32NoEx("seed", np.seed);
589 group->getU16NoEx("octaves", np.octaves);
590 group->getFloatNoEx("persistence", np.persist);
596 bool Settings::exists(const std::string &name) const
598 JMutexAutoLock lock(m_mutex);
600 return (m_settings.find(name) != m_settings.end() ||
601 m_defaults.find(name) != m_defaults.end());
605 std::vector<std::string> Settings::getNames() const
607 std::vector<std::string> names;
608 for (std::map<std::string, SettingsEntry>::const_iterator
609 i = m_settings.begin();
610 i != m_settings.end(); ++i) {
611 names.push_back(i->first);
618 /***************************************
619 * Getters that don't throw exceptions *
620 ***************************************/
622 bool Settings::getEntryNoEx(const std::string &name, SettingsEntry &val) const
625 val = getEntry(name);
627 } catch (SettingNotFoundException &e) {
633 bool Settings::getGroupNoEx(const std::string &name, Settings *&val) const
636 val = getGroup(name);
638 } catch (SettingNotFoundException &e) {
644 bool Settings::getNoEx(const std::string &name, std::string &val) const
649 } catch (SettingNotFoundException &e) {
655 bool Settings::getFlag(const std::string &name) const
658 return getBool(name);
659 } catch(SettingNotFoundException &e) {
665 bool Settings::getFloatNoEx(const std::string &name, float &val) const
668 val = getFloat(name);
670 } catch (SettingNotFoundException &e) {
676 bool Settings::getU16NoEx(const std::string &name, u16 &val) const
681 } catch (SettingNotFoundException &e) {
687 bool Settings::getS16NoEx(const std::string &name, s16 &val) const
692 } catch (SettingNotFoundException &e) {
698 bool Settings::getS32NoEx(const std::string &name, s32 &val) const
703 } catch (SettingNotFoundException &e) {
709 bool Settings::getU64NoEx(const std::string &name, u64 &val) const
714 } catch (SettingNotFoundException &e) {
720 bool Settings::getV2FNoEx(const std::string &name, v2f &val) const
725 } catch (SettingNotFoundException &e) {
731 bool Settings::getV3FNoEx(const std::string &name, v3f &val) const
736 } catch (SettingNotFoundException &e) {
742 // N.B. getFlagStrNoEx() does not set val, but merely modifies it. Thus,
743 // val must be initialized before using getFlagStrNoEx(). The intention of
744 // this is to simplify modifying a flags field from a default value.
745 bool Settings::getFlagStrNoEx(const std::string &name, u32 &val,
746 FlagDesc *flagdesc) const
751 flags = getFlagStr(name, flagdesc, &flagmask);
757 } catch (SettingNotFoundException &e) {
768 void Settings::set(const std::string &name, const std::string &value)
771 JMutexAutoLock lock(m_mutex);
773 m_settings[name].value = value;
779 void Settings::setGroup(const std::string &name, Settings *group)
781 Settings *old_group = NULL;
783 JMutexAutoLock lock(m_mutex);
785 old_group = m_settings[name].group;
786 m_settings[name].group = group;
792 void Settings::setDefault(const std::string &name, const std::string &value)
794 JMutexAutoLock lock(m_mutex);
796 m_defaults[name].value = value;
800 void Settings::setGroupDefault(const std::string &name, Settings *group)
802 Settings *old_group = NULL;
804 JMutexAutoLock lock(m_mutex);
806 old_group = m_defaults[name].group;
807 m_defaults[name].group = group;
813 void Settings::setBool(const std::string &name, bool value)
815 set(name, value ? "true" : "false");
819 void Settings::setS16(const std::string &name, s16 value)
821 set(name, itos(value));
825 void Settings::setU16(const std::string &name, u16 value)
827 set(name, itos(value));
831 void Settings::setS32(const std::string &name, s32 value)
833 set(name, itos(value));
837 void Settings::setU64(const std::string &name, u64 value)
839 std::ostringstream os;
845 void Settings::setFloat(const std::string &name, float value)
847 set(name, ftos(value));
851 void Settings::setV2F(const std::string &name, v2f value)
853 std::ostringstream os;
854 os << "(" << value.X << "," << value.Y << ")";
859 void Settings::setV3F(const std::string &name, v3f value)
861 std::ostringstream os;
862 os << "(" << value.X << "," << value.Y << "," << value.Z << ")";
867 void Settings::setFlagStr(const std::string &name, u32 flags,
868 const FlagDesc *flagdesc, u32 flagmask)
870 set(name, writeFlagString(flags, flagdesc, flagmask));
874 bool Settings::setStruct(const std::string &name, const std::string &format,
877 std::string structstr;
878 if (!serializeStructToString(&structstr, format, value))
881 set(name, structstr);
886 void Settings::setNoiseParams(const std::string &name, const NoiseParams &np)
888 Settings *group = new Settings;
890 group->setFloat("offset", np.offset);
891 group->setFloat("scale", np.scale);
892 group->setV3F("spread", np.spread);
893 group->setS32("seed", np.seed);
894 group->setU16("octaves", np.octaves);
895 group->setFloat("persistence", np.persist);
899 JMutexAutoLock lock(m_mutex);
901 old_group = m_settings[name].group;
902 m_settings[name].group = group;
903 m_settings[name].value = "";
909 bool Settings::remove(const std::string &name)
911 JMutexAutoLock lock(m_mutex);
912 return m_settings.erase(name);
916 void Settings::clear()
918 JMutexAutoLock lock(m_mutex);
923 void Settings::updateValue(const Settings &other, const std::string &name)
928 JMutexAutoLock lock(m_mutex);
931 std::string val = other.get(name);
933 m_settings[name] = val;
934 } catch (SettingNotFoundException &e) {
939 void Settings::update(const Settings &other)
944 JMutexAutoLock lock(m_mutex);
945 JMutexAutoLock lock2(other.m_mutex);
951 SettingsParseEvent Settings::parseConfigObject(const std::string &line,
952 const std::string &end, std::string &name, std::string &value)
954 std::string trimmed_line = trim(line);
956 if (trimmed_line.empty())
958 if (trimmed_line[0] == '#')
960 if (trimmed_line == end)
963 size_t pos = trimmed_line.find('=');
964 if (pos == std::string::npos)
967 name = trim(trimmed_line.substr(0, pos));
968 value = trim(trimmed_line.substr(pos + 1));
972 if (value == "\"\"\"")
973 return SPE_MULTILINE;
979 void Settings::updateNoLock(const Settings &other)
981 m_settings.insert(other.m_settings.begin(), other.m_settings.end());
982 m_defaults.insert(other.m_defaults.begin(), other.m_defaults.end());
986 void Settings::clearNoLock()
993 void Settings::registerChangedCallback(std::string name,
994 setting_changed_callback cbf)
996 m_callbacks[name].push_back(cbf);
1000 void Settings::doCallbacks(const std::string name)
1002 std::vector<setting_changed_callback> tempvector;
1004 JMutexAutoLock lock(m_mutex);
1005 if (m_callbacks.find(name) != m_callbacks.end())
1007 tempvector = m_callbacks[name];
1011 for (std::vector<setting_changed_callback>::iterator iter = tempvector.begin();
1012 iter != tempvector.end(); iter ++)