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(")"));
491 np.seed = stoi(f.next(","));
492 np.octaves = stoi(f.next(","));
493 np.persist = stof(f.next(""));
499 bool Settings::getNoiseParamsFromGroup(const std::string &name,
500 NoiseParams &np) const
502 Settings *group = NULL;
504 if (!getGroupNoEx(name, group))
507 group->getFloatNoEx("offset", np.offset);
508 group->getFloatNoEx("scale", np.scale);
509 group->getV3FNoEx("spread", np.spread);
510 group->getS32NoEx("seed", np.seed);
511 group->getU16NoEx("octaves", np.octaves);
512 group->getFloatNoEx("persistence", np.persist);
518 bool Settings::exists(const std::string &name) const
520 JMutexAutoLock lock(m_mutex);
522 return (m_settings.find(name) != m_settings.end() ||
523 m_defaults.find(name) != m_defaults.end());
527 std::vector<std::string> Settings::getNames() const
529 std::vector<std::string> names;
530 for (std::map<std::string, SettingsEntry>::const_iterator
531 i = m_settings.begin();
532 i != m_settings.end(); ++i) {
533 names.push_back(i->first);
540 /***************************************
541 * Getters that don't throw exceptions *
542 ***************************************/
544 bool Settings::getEntryNoEx(const std::string &name, SettingsEntry &val) const
547 val = getEntry(name);
549 } catch (SettingNotFoundException &e) {
555 bool Settings::getGroupNoEx(const std::string &name, Settings *&val) const
558 val = getGroup(name);
560 } catch (SettingNotFoundException &e) {
566 bool Settings::getNoEx(const std::string &name, std::string &val) const
571 } catch (SettingNotFoundException &e) {
577 bool Settings::getFlag(const std::string &name) const
580 return getBool(name);
581 } catch(SettingNotFoundException &e) {
587 bool Settings::getFloatNoEx(const std::string &name, float &val) const
590 val = getFloat(name);
592 } catch (SettingNotFoundException &e) {
598 bool Settings::getU16NoEx(const std::string &name, u16 &val) const
603 } catch (SettingNotFoundException &e) {
609 bool Settings::getS16NoEx(const std::string &name, s16 &val) const
614 } catch (SettingNotFoundException &e) {
620 bool Settings::getS32NoEx(const std::string &name, s32 &val) const
625 } catch (SettingNotFoundException &e) {
631 bool Settings::getU64NoEx(const std::string &name, u64 &val) const
636 } catch (SettingNotFoundException &e) {
642 bool Settings::getV2FNoEx(const std::string &name, v2f &val) const
647 } catch (SettingNotFoundException &e) {
653 bool Settings::getV3FNoEx(const std::string &name, v3f &val) const
658 } catch (SettingNotFoundException &e) {
664 // N.B. getFlagStrNoEx() does not set val, but merely modifies it. Thus,
665 // val must be initialized before using getFlagStrNoEx(). The intention of
666 // this is to simplify modifying a flags field from a default value.
667 bool Settings::getFlagStrNoEx(const std::string &name, u32 &val,
668 FlagDesc *flagdesc) const
673 flags = getFlagStr(name, flagdesc, &flagmask);
679 } catch (SettingNotFoundException &e) {
690 void Settings::set(const std::string &name, const std::string &value)
693 JMutexAutoLock lock(m_mutex);
695 m_settings[name].value = value;
701 void Settings::setGroup(const std::string &name, Settings *group)
703 JMutexAutoLock lock(m_mutex);
705 delete m_settings[name].group;
706 m_settings[name].group = group;
710 void Settings::setDefault(const std::string &name, const std::string &value)
712 JMutexAutoLock lock(m_mutex);
714 m_defaults[name].value = value;
718 void Settings::setGroupDefault(const std::string &name, Settings *group)
720 JMutexAutoLock lock(m_mutex);
722 delete m_defaults[name].group;
723 m_defaults[name].group = group;
727 void Settings::setBool(const std::string &name, bool value)
729 set(name, value ? "true" : "false");
733 void Settings::setS16(const std::string &name, s16 value)
735 set(name, itos(value));
739 void Settings::setU16(const std::string &name, u16 value)
741 set(name, itos(value));
745 void Settings::setS32(const std::string &name, s32 value)
747 set(name, itos(value));
751 void Settings::setU64(const std::string &name, u64 value)
753 std::ostringstream os;
759 void Settings::setFloat(const std::string &name, float value)
761 set(name, ftos(value));
765 void Settings::setV2F(const std::string &name, v2f value)
767 std::ostringstream os;
768 os << "(" << value.X << "," << value.Y << ")";
773 void Settings::setV3F(const std::string &name, v3f value)
775 std::ostringstream os;
776 os << "(" << value.X << "," << value.Y << "," << value.Z << ")";
781 void Settings::setFlagStr(const std::string &name, u32 flags,
782 const FlagDesc *flagdesc, u32 flagmask)
784 set(name, writeFlagString(flags, flagdesc, flagmask));
788 bool Settings::setStruct(const std::string &name, const std::string &format,
791 std::string structstr;
792 if (!serializeStructToString(&structstr, format, value))
795 set(name, structstr);
800 void Settings::setNoiseParams(const std::string &name, const NoiseParams &np)
802 Settings *group = new Settings;
804 group->setFloat("offset", np.offset);
805 group->setFloat("scale", np.scale);
806 group->setV3F("spread", np.spread);
807 group->setS32("seed", np.seed);
808 group->setU16("octaves", np.octaves);
809 group->setFloat("persistence", np.persist);
811 setGroup(name, group);
815 bool Settings::remove(const std::string &name)
817 JMutexAutoLock lock(m_mutex);
818 return m_settings.erase(name);
822 void Settings::clear()
824 JMutexAutoLock lock(m_mutex);
829 void Settings::updateValue(const Settings &other, const std::string &name)
834 JMutexAutoLock lock(m_mutex);
837 std::string val = other.get(name);
839 m_settings[name] = val;
840 } catch (SettingNotFoundException &e) {
845 void Settings::update(const Settings &other)
850 JMutexAutoLock lock(m_mutex);
851 JMutexAutoLock lock2(other.m_mutex);
857 SettingsParseEvent Settings::parseConfigObject(const std::string &line,
858 const std::string &end, std::string &name, std::string &value)
860 std::string trimmed_line = trim(line);
862 if (trimmed_line.empty())
864 if (trimmed_line[0] == '#')
866 if (trimmed_line == end)
869 size_t pos = trimmed_line.find('=');
870 if (pos == std::string::npos)
873 name = trim(trimmed_line.substr(0, pos));
874 value = trim(trimmed_line.substr(pos + 1));
878 if (value == "\"\"\"")
879 return SPE_MULTILINE;
885 void Settings::updateNoLock(const Settings &other)
887 m_settings.insert(other.m_settings.begin(), other.m_settings.end());
888 m_defaults.insert(other.m_defaults.begin(), other.m_defaults.end());
892 void Settings::clearNoLock()
899 void Settings::registerChangedCallback(std::string name,
900 setting_changed_callback cbf)
902 m_callbacks[name].push_back(cbf);
906 void Settings::doCallbacks(const std::string name)
908 std::vector<setting_changed_callback> tempvector;
910 JMutexAutoLock lock(m_mutex);
911 if (m_callbacks.find(name) != m_callbacks.end())
913 tempvector = m_callbacks[name];
917 for (std::vector<setting_changed_callback>::iterator iter = tempvector.begin();
918 iter != tempvector.end(); iter ++)