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)
84 std::getline(is, line);
88 value.push_back('\n');
91 size_t len = value.size();
99 bool Settings::parseConfigLines(std::istream &is, const std::string &end)
101 JMutexAutoLock lock(m_mutex);
103 std::string line, name, value;
106 std::getline(is, line);
107 SettingsParseEvent event = parseConfigObject(line, end, name, value);
115 m_settings[name] = SettingsEntry(value);
120 Settings *branch = new Settings;
121 if (!branch->parseConfigLines(is, "}"))
124 m_settings[name] = SettingsEntry(branch);
128 m_settings[name] = SettingsEntry(getMultiline(is));
137 bool Settings::readConfigFile(const char *filename)
139 std::ifstream is(filename);
143 return parseConfigLines(is, "");
147 void Settings::writeLines(std::ostream &os, u32 tab_depth) const
149 JMutexAutoLock lock(m_mutex);
151 for (std::map<std::string, SettingsEntry>::const_iterator
152 it = m_settings.begin();
153 it != m_settings.end(); ++it) {
154 bool is_multiline = it->second.value.find('\n') != std::string::npos;
155 printValue(os, it->first, it->second, is_multiline, tab_depth);
160 void Settings::printValue(std::ostream &os, const std::string &name,
161 const SettingsEntry &entry, bool is_value_multiline, u32 tab_depth)
163 for (u32 i = 0; i != tab_depth; i++)
167 if (is_value_multiline)
168 os << "\"\"\"\n" << entry.value << "\n\"\"\"\n";
170 os << entry.value << "\n";
172 Settings *group = entry.group;
174 for (u32 i = 0; i != tab_depth; i++)
177 os << name << " = {\n";
178 group->writeLines(os, tab_depth + 1);
180 for (u32 i = 0; i != tab_depth; i++)
188 bool Settings::updateConfigObject(std::istream &is, std::ostream &os,
189 const std::string &end, u32 tab_depth)
191 std::map<std::string, SettingsEntry>::const_iterator it;
192 std::set<std::string> settings_in_config;
193 bool was_modified = false;
194 bool end_found = false;
195 std::string line, name, value;
197 // Add any settings that exist in the config file with the current value
198 // in the object if existing
199 while (is.good() && !end_found) {
200 std::getline(is, line);
201 SettingsParseEvent event = parseConfigObject(line, end, name, value);
209 it = m_settings.find(name);
210 if (it != m_settings.end()) {
211 if (event == SPE_MULTILINE)
212 value = getMultiline(is);
214 if (value != it->second.value) {
215 value = it->second.value;
220 settings_in_config.insert(name);
222 printValue(os, name, SettingsEntry(value),
223 event == SPE_MULTILINE, tab_depth);
227 Settings *group = NULL;
228 it = m_settings.find(name);
229 if (it != m_settings.end())
230 group = it->second.group;
232 settings_in_config.insert(name);
234 os << name << " = {\n";
237 was_modified |= group->updateConfigObject(is, os, "}", tab_depth + 1);
239 Settings dummy_settings;
240 dummy_settings.updateConfigObject(is, os, "}", tab_depth + 1);
243 for (u32 i = 0; i != tab_depth; i++)
249 os << line << (is.eof() ? "" : "\n");
254 // Add any settings in the object that don't exist in the config file yet
255 for (it = m_settings.begin(); it != m_settings.end(); ++it) {
256 if (settings_in_config.find(it->first) != settings_in_config.end())
261 bool is_multiline = it->second.value.find('\n') != std::string::npos;
262 printValue(os, it->first, it->second, is_multiline, tab_depth);
269 bool Settings::updateConfigFile(const char *filename)
271 JMutexAutoLock lock(m_mutex);
273 std::ifstream is(filename);
274 std::ostringstream os(std::ios_base::binary);
276 if (!updateConfigObject(is, os, ""))
279 if (!fs::safeWriteToFile(filename, os.str())) {
280 errorstream << "Error writing configuration file: \""
281 << filename << "\"" << std::endl;
289 bool Settings::parseCommandLine(int argc, char *argv[],
290 std::map<std::string, ValueSpec> &allowed_options)
292 int nonopt_index = 0;
293 for (int i = 1; i < argc; i++) {
294 std::string arg_name = argv[i];
295 if (arg_name.substr(0, 2) != "--") {
296 // If option doesn't start with -, read it in as nonoptX
297 if (arg_name[0] != '-'){
298 std::string name = "nonopt";
299 name += itos(nonopt_index);
304 errorstream << "Invalid command-line parameter \""
305 << arg_name << "\": --<option> expected." << std::endl;
309 std::string name = arg_name.substr(2);
311 std::map<std::string, ValueSpec>::iterator n;
312 n = allowed_options.find(name);
313 if (n == allowed_options.end()) {
314 errorstream << "Unknown command-line parameter \""
315 << arg_name << "\"" << std::endl;
319 ValueType type = n->second.type;
321 std::string value = "";
323 if (type == VALUETYPE_FLAG) {
326 if ((i + 1) >= argc) {
327 errorstream << "Invalid command-line parameter \""
328 << name << "\": missing value" << std::endl;
347 const SettingsEntry &Settings::getEntry(const std::string &name) const
349 JMutexAutoLock lock(m_mutex);
351 std::map<std::string, SettingsEntry>::const_iterator n;
352 if ((n = m_settings.find(name)) == m_settings.end()) {
353 if ((n = m_defaults.find(name)) == m_defaults.end())
354 throw SettingNotFoundException("Setting [" + name + "] not found.");
360 Settings *Settings::getGroup(const std::string &name) const
362 Settings *group = getEntry(name).group;
364 throw SettingNotFoundException("Setting [" + name + "] is not a group.");
369 std::string Settings::get(const std::string &name) const
371 return getEntry(name).value;
375 bool Settings::getBool(const std::string &name) const
377 return is_yes(get(name));
381 u16 Settings::getU16(const std::string &name) const
383 return stoi(get(name), 0, 65535);
387 s16 Settings::getS16(const std::string &name) const
389 return stoi(get(name), -32768, 32767);
393 s32 Settings::getS32(const std::string &name) const
395 return stoi(get(name));
399 float Settings::getFloat(const std::string &name) const
401 return stof(get(name));
405 u64 Settings::getU64(const std::string &name) const
408 std::string s = get(name);
409 std::istringstream ss(s);
415 v2f Settings::getV2F(const std::string &name) const
420 value.X = stof(f.next(","));
421 value.Y = stof(f.next(")"));
426 v3f Settings::getV3F(const std::string &name) const
431 value.X = stof(f.next(","));
432 value.Y = stof(f.next(","));
433 value.Z = stof(f.next(")"));
438 u32 Settings::getFlagStr(const std::string &name, const FlagDesc *flagdesc,
441 std::string val = get(name);
442 return std::isdigit(val[0])
444 : readFlagString(val, flagdesc, flagmask);
448 // N.B. if getStruct() is used to read a non-POD aggregate type,
449 // the behavior is undefined.
450 bool Settings::getStruct(const std::string &name, const std::string &format,
451 void *out, size_t olen) const
457 } catch (SettingNotFoundException &e) {
461 if (!deSerializeStringToStruct(valstr, format, out, olen))
468 bool Settings::getNoiseParams(const std::string &name, NoiseParams &np) const
470 return getNoiseParamsFromGroup(name, np) || getNoiseParamsFromValue(name, np);
474 bool Settings::getNoiseParamsFromValue(const std::string &name,
475 NoiseParams &np) const
479 if (!getNoEx(name, value))
484 np.offset = stof(f.next(","));
485 np.scale = stof(f.next(","));
487 np.spread.X = stof(f.next(","));
488 np.spread.Y = stof(f.next(","));
489 np.spread.Z = stof(f.next(")"));
490 np.seed = stoi(f.next(","));
491 np.octaves = stoi(f.next(","));
492 np.persist = stof(f.next(""));
498 bool Settings::getNoiseParamsFromGroup(const std::string &name,
499 NoiseParams &np) const
501 Settings *group = NULL;
503 if (!getGroupNoEx(name, group))
506 group->getFloatNoEx("offset", np.offset);
507 group->getFloatNoEx("scale", np.scale);
508 group->getV3FNoEx("spread", np.spread);
509 group->getS32NoEx("seed", np.seed);
510 group->getU16NoEx("octaves", np.octaves);
511 group->getFloatNoEx("persistence", np.persist);
517 bool Settings::exists(const std::string &name) const
519 JMutexAutoLock lock(m_mutex);
521 return (m_settings.find(name) != m_settings.end() ||
522 m_defaults.find(name) != m_defaults.end());
526 std::vector<std::string> Settings::getNames() const
528 std::vector<std::string> names;
529 for (std::map<std::string, SettingsEntry>::const_iterator
530 i = m_settings.begin();
531 i != m_settings.end(); ++i) {
532 names.push_back(i->first);
539 /***************************************
540 * Getters that don't throw exceptions *
541 ***************************************/
543 bool Settings::getEntryNoEx(const std::string &name, SettingsEntry &val) const
546 val = getEntry(name);
548 } catch (SettingNotFoundException &e) {
554 bool Settings::getGroupNoEx(const std::string &name, Settings *&val) const
557 val = getGroup(name);
559 } catch (SettingNotFoundException &e) {
565 bool Settings::getNoEx(const std::string &name, std::string &val) const
570 } catch (SettingNotFoundException &e) {
576 bool Settings::getFlag(const std::string &name) const
579 return getBool(name);
580 } catch(SettingNotFoundException &e) {
586 bool Settings::getFloatNoEx(const std::string &name, float &val) const
589 val = getFloat(name);
591 } catch (SettingNotFoundException &e) {
597 bool Settings::getU16NoEx(const std::string &name, u16 &val) const
602 } catch (SettingNotFoundException &e) {
608 bool Settings::getS16NoEx(const std::string &name, s16 &val) const
613 } catch (SettingNotFoundException &e) {
619 bool Settings::getS32NoEx(const std::string &name, s32 &val) const
624 } catch (SettingNotFoundException &e) {
630 bool Settings::getU64NoEx(const std::string &name, u64 &val) const
635 } catch (SettingNotFoundException &e) {
641 bool Settings::getV2FNoEx(const std::string &name, v2f &val) const
646 } catch (SettingNotFoundException &e) {
652 bool Settings::getV3FNoEx(const std::string &name, v3f &val) const
657 } catch (SettingNotFoundException &e) {
663 // N.B. getFlagStrNoEx() does not set val, but merely modifies it. Thus,
664 // val must be initialized before using getFlagStrNoEx(). The intention of
665 // this is to simplify modifying a flags field from a default value.
666 bool Settings::getFlagStrNoEx(const std::string &name, u32 &val,
667 FlagDesc *flagdesc) const
672 flags = getFlagStr(name, flagdesc, &flagmask);
678 } catch (SettingNotFoundException &e) {
689 void Settings::set(const std::string &name, const std::string &value)
692 JMutexAutoLock lock(m_mutex);
694 m_settings[name].value = value;
700 void Settings::setGroup(const std::string &name, Settings *group)
702 JMutexAutoLock lock(m_mutex);
704 delete m_settings[name].group;
705 m_settings[name].group = group;
709 void Settings::setDefault(const std::string &name, const std::string &value)
711 JMutexAutoLock lock(m_mutex);
713 m_defaults[name].value = value;
717 void Settings::setGroupDefault(const std::string &name, Settings *group)
719 JMutexAutoLock lock(m_mutex);
721 delete m_defaults[name].group;
722 m_defaults[name].group = group;
726 void Settings::setBool(const std::string &name, bool value)
728 set(name, value ? "true" : "false");
732 void Settings::setS16(const std::string &name, s16 value)
734 set(name, itos(value));
738 void Settings::setU16(const std::string &name, u16 value)
740 set(name, itos(value));
744 void Settings::setS32(const std::string &name, s32 value)
746 set(name, itos(value));
750 void Settings::setU64(const std::string &name, u64 value)
752 std::ostringstream os;
758 void Settings::setFloat(const std::string &name, float value)
760 set(name, ftos(value));
764 void Settings::setV2F(const std::string &name, v2f value)
766 std::ostringstream os;
767 os << "(" << value.X << "," << value.Y << ")";
772 void Settings::setV3F(const std::string &name, v3f value)
774 std::ostringstream os;
775 os << "(" << value.X << "," << value.Y << "," << value.Z << ")";
780 void Settings::setFlagStr(const std::string &name, u32 flags,
781 const FlagDesc *flagdesc, u32 flagmask)
783 set(name, writeFlagString(flags, flagdesc, flagmask));
787 bool Settings::setStruct(const std::string &name, const std::string &format,
790 std::string structstr;
791 if (!serializeStructToString(&structstr, format, value))
794 set(name, structstr);
799 void Settings::setNoiseParams(const std::string &name, const NoiseParams &np)
801 Settings *group = new Settings;
803 group->setFloat("offset", np.offset);
804 group->setFloat("scale", np.scale);
805 group->setV3F("spread", np.spread);
806 group->setS32("seed", np.seed);
807 group->setU16("octaves", np.octaves);
808 group->setFloat("persistence", np.persist);
810 setGroup(name, group);
814 bool Settings::remove(const std::string &name)
816 JMutexAutoLock lock(m_mutex);
817 return m_settings.erase(name);
821 void Settings::clear()
823 JMutexAutoLock lock(m_mutex);
828 void Settings::updateValue(const Settings &other, const std::string &name)
833 JMutexAutoLock lock(m_mutex);
836 std::string val = other.get(name);
838 m_settings[name] = val;
839 } catch (SettingNotFoundException &e) {
844 void Settings::update(const Settings &other)
849 JMutexAutoLock lock(m_mutex);
850 JMutexAutoLock lock2(other.m_mutex);
856 SettingsParseEvent Settings::parseConfigObject(const std::string &line,
857 const std::string &end, std::string &name, std::string &value)
859 std::string trimmed_line = trim(line);
861 if (trimmed_line.empty())
863 if (trimmed_line[0] == '#')
865 if (trimmed_line == end)
868 size_t pos = trimmed_line.find('=');
869 if (pos == std::string::npos)
872 name = trim(trimmed_line.substr(0, pos));
873 value = trim(trimmed_line.substr(pos + 1));
877 if (value == "\"\"\"")
878 return SPE_MULTILINE;
884 void Settings::updateNoLock(const Settings &other)
886 m_settings.insert(other.m_settings.begin(), other.m_settings.end());
887 m_defaults.insert(other.m_defaults.begin(), other.m_defaults.end());
891 void Settings::clearNoLock()
898 void Settings::registerChangedCallback(std::string name,
899 setting_changed_callback cbf)
901 m_callbacks[name].push_back(cbf);
905 void Settings::doCallbacks(const std::string name)
907 std::vector<setting_changed_callback> tempvector;
909 JMutexAutoLock lock(m_mutex);
910 if (m_callbacks.find(name) != m_callbacks.end())
912 tempvector = m_callbacks[name];
916 for (std::vector<setting_changed_callback>::iterator iter = tempvector.begin();
917 iter != tempvector.end(); iter ++)