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 bool was_modified = updateConfigObject(is, os, "");
360 if (!fs::safeWriteToFile(filename, os.str())) {
361 errorstream << "Error writing configuration file: \""
362 << filename << "\"" << std::endl;
370 bool Settings::parseCommandLine(int argc, char *argv[],
371 std::map<std::string, ValueSpec> &allowed_options)
373 int nonopt_index = 0;
374 for (int i = 1; i < argc; i++) {
375 std::string arg_name = argv[i];
376 if (arg_name.substr(0, 2) != "--") {
377 // If option doesn't start with -, read it in as nonoptX
378 if (arg_name[0] != '-'){
379 std::string name = "nonopt";
380 name += itos(nonopt_index);
385 errorstream << "Invalid command-line parameter \""
386 << arg_name << "\": --<option> expected." << std::endl;
390 std::string name = arg_name.substr(2);
392 std::map<std::string, ValueSpec>::iterator n;
393 n = allowed_options.find(name);
394 if (n == allowed_options.end()) {
395 errorstream << "Unknown command-line parameter \""
396 << arg_name << "\"" << std::endl;
400 ValueType type = n->second.type;
402 std::string value = "";
404 if (type == VALUETYPE_FLAG) {
407 if ((i + 1) >= argc) {
408 errorstream << "Invalid command-line parameter \""
409 << name << "\": missing value" << std::endl;
428 const SettingsEntry &Settings::getEntry(const std::string &name) const
430 JMutexAutoLock lock(m_mutex);
432 std::map<std::string, SettingsEntry>::const_iterator n;
433 if ((n = m_settings.find(name)) == m_settings.end()) {
434 if ((n = m_defaults.find(name)) == m_defaults.end())
435 throw SettingNotFoundException("Setting [" + name + "] not found.");
441 Settings *Settings::getGroup(const std::string &name) const
443 Settings *group = getEntry(name).group;
445 throw SettingNotFoundException("Setting [" + name + "] is not a group.");
450 std::string Settings::get(const std::string &name) const
452 return getEntry(name).value;
456 bool Settings::getBool(const std::string &name) const
458 return is_yes(get(name));
462 u16 Settings::getU16(const std::string &name) const
464 return stoi(get(name), 0, 65535);
468 s16 Settings::getS16(const std::string &name) const
470 return stoi(get(name), -32768, 32767);
474 s32 Settings::getS32(const std::string &name) const
476 return stoi(get(name));
480 float Settings::getFloat(const std::string &name) const
482 return stof(get(name));
486 u64 Settings::getU64(const std::string &name) const
489 std::string s = get(name);
490 std::istringstream ss(s);
496 v2f Settings::getV2F(const std::string &name) const
501 value.X = stof(f.next(","));
502 value.Y = stof(f.next(")"));
507 v3f Settings::getV3F(const std::string &name) const
512 value.X = stof(f.next(","));
513 value.Y = stof(f.next(","));
514 value.Z = stof(f.next(")"));
519 u32 Settings::getFlagStr(const std::string &name, const FlagDesc *flagdesc,
522 std::string val = get(name);
523 return std::isdigit(val[0])
525 : readFlagString(val, flagdesc, flagmask);
529 // N.B. if getStruct() is used to read a non-POD aggregate type,
530 // the behavior is undefined.
531 bool Settings::getStruct(const std::string &name, const std::string &format,
532 void *out, size_t olen) const
538 } catch (SettingNotFoundException &e) {
542 if (!deSerializeStringToStruct(valstr, format, out, olen))
549 bool Settings::getNoiseParams(const std::string &name, NoiseParams &np) const
551 return getNoiseParamsFromGroup(name, np) || getNoiseParamsFromValue(name, np);
555 bool Settings::getNoiseParamsFromValue(const std::string &name,
556 NoiseParams &np) const
560 if (!getNoEx(name, value))
565 np.offset = stof(f.next(","));
566 np.scale = stof(f.next(","));
568 np.spread.X = stof(f.next(","));
569 np.spread.Y = stof(f.next(","));
570 np.spread.Z = stof(f.next(")"));
572 np.seed = stoi(f.next(","));
573 np.octaves = stoi(f.next(","));
574 np.persist = stof(f.next(""));
580 bool Settings::getNoiseParamsFromGroup(const std::string &name,
581 NoiseParams &np) const
583 Settings *group = NULL;
585 if (!getGroupNoEx(name, group))
588 group->getFloatNoEx("offset", np.offset);
589 group->getFloatNoEx("scale", np.scale);
590 group->getV3FNoEx("spread", np.spread);
591 group->getS32NoEx("seed", np.seed);
592 group->getU16NoEx("octaves", np.octaves);
593 group->getFloatNoEx("persistence", np.persist);
599 bool Settings::exists(const std::string &name) const
601 JMutexAutoLock lock(m_mutex);
603 return (m_settings.find(name) != m_settings.end() ||
604 m_defaults.find(name) != m_defaults.end());
608 std::vector<std::string> Settings::getNames() const
610 std::vector<std::string> names;
611 for (std::map<std::string, SettingsEntry>::const_iterator
612 i = m_settings.begin();
613 i != m_settings.end(); ++i) {
614 names.push_back(i->first);
621 /***************************************
622 * Getters that don't throw exceptions *
623 ***************************************/
625 bool Settings::getEntryNoEx(const std::string &name, SettingsEntry &val) const
628 val = getEntry(name);
630 } catch (SettingNotFoundException &e) {
636 bool Settings::getGroupNoEx(const std::string &name, Settings *&val) const
639 val = getGroup(name);
641 } catch (SettingNotFoundException &e) {
647 bool Settings::getNoEx(const std::string &name, std::string &val) const
652 } catch (SettingNotFoundException &e) {
658 bool Settings::getFlag(const std::string &name) const
661 return getBool(name);
662 } catch(SettingNotFoundException &e) {
668 bool Settings::getFloatNoEx(const std::string &name, float &val) const
671 val = getFloat(name);
673 } catch (SettingNotFoundException &e) {
679 bool Settings::getU16NoEx(const std::string &name, u16 &val) const
684 } catch (SettingNotFoundException &e) {
690 bool Settings::getS16NoEx(const std::string &name, s16 &val) const
695 } catch (SettingNotFoundException &e) {
701 bool Settings::getS32NoEx(const std::string &name, s32 &val) const
706 } catch (SettingNotFoundException &e) {
712 bool Settings::getU64NoEx(const std::string &name, u64 &val) const
717 } catch (SettingNotFoundException &e) {
723 bool Settings::getV2FNoEx(const std::string &name, v2f &val) const
728 } catch (SettingNotFoundException &e) {
734 bool Settings::getV3FNoEx(const std::string &name, v3f &val) const
739 } catch (SettingNotFoundException &e) {
745 // N.B. getFlagStrNoEx() does not set val, but merely modifies it. Thus,
746 // val must be initialized before using getFlagStrNoEx(). The intention of
747 // this is to simplify modifying a flags field from a default value.
748 bool Settings::getFlagStrNoEx(const std::string &name, u32 &val,
749 FlagDesc *flagdesc) const
754 flags = getFlagStr(name, flagdesc, &flagmask);
760 } catch (SettingNotFoundException &e) {
771 void Settings::set(const std::string &name, const std::string &value)
774 JMutexAutoLock lock(m_mutex);
776 m_settings[name].value = value;
782 void Settings::setGroup(const std::string &name, Settings *group)
784 Settings *old_group = NULL;
786 JMutexAutoLock lock(m_mutex);
788 old_group = m_settings[name].group;
789 m_settings[name].group = group;
795 void Settings::setDefault(const std::string &name, const std::string &value)
797 JMutexAutoLock lock(m_mutex);
799 m_defaults[name].value = value;
803 void Settings::setGroupDefault(const std::string &name, Settings *group)
805 Settings *old_group = NULL;
807 JMutexAutoLock lock(m_mutex);
809 old_group = m_defaults[name].group;
810 m_defaults[name].group = group;
816 void Settings::setBool(const std::string &name, bool value)
818 set(name, value ? "true" : "false");
822 void Settings::setS16(const std::string &name, s16 value)
824 set(name, itos(value));
828 void Settings::setU16(const std::string &name, u16 value)
830 set(name, itos(value));
834 void Settings::setS32(const std::string &name, s32 value)
836 set(name, itos(value));
840 void Settings::setU64(const std::string &name, u64 value)
842 std::ostringstream os;
848 void Settings::setFloat(const std::string &name, float value)
850 set(name, ftos(value));
854 void Settings::setV2F(const std::string &name, v2f value)
856 std::ostringstream os;
857 os << "(" << value.X << "," << value.Y << ")";
862 void Settings::setV3F(const std::string &name, v3f value)
864 std::ostringstream os;
865 os << "(" << value.X << "," << value.Y << "," << value.Z << ")";
870 void Settings::setFlagStr(const std::string &name, u32 flags,
871 const FlagDesc *flagdesc, u32 flagmask)
873 set(name, writeFlagString(flags, flagdesc, flagmask));
877 bool Settings::setStruct(const std::string &name, const std::string &format,
880 std::string structstr;
881 if (!serializeStructToString(&structstr, format, value))
884 set(name, structstr);
889 void Settings::setNoiseParams(const std::string &name, const NoiseParams &np)
891 Settings *group = new Settings;
893 group->setFloat("offset", np.offset);
894 group->setFloat("scale", np.scale);
895 group->setV3F("spread", np.spread);
896 group->setS32("seed", np.seed);
897 group->setU16("octaves", np.octaves);
898 group->setFloat("persistence", np.persist);
902 JMutexAutoLock lock(m_mutex);
904 old_group = m_settings[name].group;
905 m_settings[name].group = group;
906 m_settings[name].value = "";
912 bool Settings::remove(const std::string &name)
914 JMutexAutoLock lock(m_mutex);
915 return m_settings.erase(name);
919 void Settings::clear()
921 JMutexAutoLock lock(m_mutex);
926 void Settings::updateValue(const Settings &other, const std::string &name)
931 JMutexAutoLock lock(m_mutex);
934 std::string val = other.get(name);
936 m_settings[name] = val;
937 } catch (SettingNotFoundException &e) {
942 void Settings::update(const Settings &other)
947 JMutexAutoLock lock(m_mutex);
948 JMutexAutoLock lock2(other.m_mutex);
954 SettingsParseEvent Settings::parseConfigObject(const std::string &line,
955 const std::string &end, std::string &name, std::string &value)
957 std::string trimmed_line = trim(line);
959 if (trimmed_line.empty())
961 if (trimmed_line[0] == '#')
963 if (trimmed_line == end)
966 size_t pos = trimmed_line.find('=');
967 if (pos == std::string::npos)
970 name = trim(trimmed_line.substr(0, pos));
971 value = trim(trimmed_line.substr(pos + 1));
975 if (value == "\"\"\"")
976 return SPE_MULTILINE;
982 void Settings::updateNoLock(const Settings &other)
984 m_settings.insert(other.m_settings.begin(), other.m_settings.end());
985 m_defaults.insert(other.m_defaults.begin(), other.m_defaults.end());
989 void Settings::clearNoLock()
996 void Settings::registerChangedCallback(std::string name,
997 setting_changed_callback cbf)
999 m_callbacks[name].push_back(cbf);
1003 void Settings::doCallbacks(const std::string name)
1005 std::vector<setting_changed_callback> tempvector;
1007 JMutexAutoLock lock(m_mutex);
1008 if (m_callbacks.find(name) != m_callbacks.end())
1010 tempvector = m_callbacks[name];
1014 for (std::vector<setting_changed_callback>::iterator iter = tempvector.begin();
1015 iter != tempvector.end(); iter ++)