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 std::string Settings::sanitizeString(const std::string &value)
68 std::string str = value;
69 for (const char *s = "\t\n\v\f\r\b =\""; *s; s++)
70 str.erase(std::remove(str.begin(), str.end(), *s), str.end());
76 std::string Settings::getMultiline(std::istream &is, size_t *num_lines)
84 std::getline(is, line);
88 value.push_back('\n');
91 size_t len = value.size();
102 bool Settings::readConfigFile(const char *filename)
104 std::ifstream is(filename);
108 return parseConfigLines(is, "");
112 bool Settings::parseConfigLines(std::istream &is, const std::string &end)
114 JMutexAutoLock lock(m_mutex);
116 std::string line, name, value;
119 std::getline(is, line);
120 SettingsParseEvent event = parseConfigObject(line, end, name, value);
128 m_settings[name] = SettingsEntry(value);
133 Settings *group = new Settings;
134 if (!group->parseConfigLines(is, "}")) {
138 m_settings[name] = SettingsEntry(group);
142 m_settings[name] = SettingsEntry(getMultiline(is));
151 void Settings::writeLines(std::ostream &os, u32 tab_depth) const
153 JMutexAutoLock lock(m_mutex);
155 for (std::map<std::string, SettingsEntry>::const_iterator
156 it = m_settings.begin();
157 it != m_settings.end(); ++it)
158 printEntry(os, it->first, it->second, tab_depth);
162 void Settings::printEntry(std::ostream &os, const std::string &name,
163 const SettingsEntry &entry, u32 tab_depth)
165 for (u32 i = 0; i != tab_depth; i++)
168 if (entry.is_group) {
169 os << name << " = {\n";
171 entry.group->writeLines(os, tab_depth + 1);
173 for (u32 i = 0; i != tab_depth; i++)
179 if (entry.value.find('\n') != std::string::npos)
180 os << "\"\"\"\n" << entry.value << "\n\"\"\"\n";
182 os << entry.value << "\n";
187 bool Settings::updateConfigObject(std::istream &is, std::ostream &os,
188 const std::string &end, u32 tab_depth)
190 std::map<std::string, SettingsEntry>::const_iterator it;
191 std::set<std::string> present_entries;
192 std::string line, name, value;
193 bool was_modified = false;
194 bool end_found = false;
196 // Add any settings that exist in the config file with the current value
197 // in the object if existing
198 while (is.good() && !end_found) {
199 std::getline(is, line);
200 SettingsParseEvent event = parseConfigObject(line, end, name, value);
204 os << line << (is.eof() ? "" : "\n");
208 value = getMultiline(is);
211 it = m_settings.find(name);
212 if (it != m_settings.end() &&
213 (it->second.is_group || it->second.value != value)) {
214 printEntry(os, name, it->second, tab_depth);
217 assert(it->second.group == NULL);
219 if (event == SPE_MULTILINE)
220 os << value << "\n\"\"\"\n";
222 present_entries.insert(name);
225 it = m_settings.find(name);
226 if (it != m_settings.end() && it->second.is_group) {
228 assert(it->second.group != NULL);
229 was_modified |= it->second.group->updateConfigObject(is, os,
232 printEntry(os, name, it->second, tab_depth);
235 present_entries.insert(name);
238 os << line << (is.eof() ? "" : "\n");
243 // Add any settings in the object that don't exist in the config file yet
244 for (it = m_settings.begin(); it != m_settings.end(); ++it) {
245 if (present_entries.find(it->first) != present_entries.end())
248 printEntry(os, it->first, it->second, tab_depth);
256 bool Settings::updateConfigFile(const char *filename)
258 JMutexAutoLock lock(m_mutex);
260 std::ifstream is(filename);
261 std::ostringstream os(std::ios_base::binary);
263 bool was_modified = updateConfigObject(is, os, "");
269 if (!fs::safeWriteToFile(filename, os.str())) {
270 errorstream << "Error writing configuration file: \""
271 << filename << "\"" << std::endl;
279 bool Settings::parseCommandLine(int argc, char *argv[],
280 std::map<std::string, ValueSpec> &allowed_options)
282 int nonopt_index = 0;
283 for (int i = 1; i < argc; i++) {
284 std::string arg_name = argv[i];
285 if (arg_name.substr(0, 2) != "--") {
286 // If option doesn't start with -, read it in as nonoptX
287 if (arg_name[0] != '-'){
288 std::string name = "nonopt";
289 name += itos(nonopt_index);
294 errorstream << "Invalid command-line parameter \""
295 << arg_name << "\": --<option> expected." << std::endl;
299 std::string name = arg_name.substr(2);
301 std::map<std::string, ValueSpec>::iterator n;
302 n = allowed_options.find(name);
303 if (n == allowed_options.end()) {
304 errorstream << "Unknown command-line parameter \""
305 << arg_name << "\"" << std::endl;
309 ValueType type = n->second.type;
311 std::string value = "";
313 if (type == VALUETYPE_FLAG) {
316 if ((i + 1) >= argc) {
317 errorstream << "Invalid command-line parameter \""
318 << name << "\": missing value" << std::endl;
337 const SettingsEntry &Settings::getEntry(const std::string &name) const
339 JMutexAutoLock lock(m_mutex);
341 std::map<std::string, SettingsEntry>::const_iterator n;
342 if ((n = m_settings.find(name)) == m_settings.end()) {
343 if ((n = m_defaults.find(name)) == m_defaults.end())
344 throw SettingNotFoundException("Setting [" + name + "] not found.");
350 Settings *Settings::getGroup(const std::string &name) const
352 const SettingsEntry &entry = getEntry(name);
354 throw SettingNotFoundException("Setting [" + name + "] is not a group.");
359 std::string Settings::get(const std::string &name) const
361 const SettingsEntry &entry = getEntry(name);
363 throw SettingNotFoundException("Setting [" + name + "] is a group.");
368 bool Settings::getBool(const std::string &name) const
370 return is_yes(get(name));
374 u16 Settings::getU16(const std::string &name) const
376 return stoi(get(name), 0, 65535);
380 s16 Settings::getS16(const std::string &name) const
382 return stoi(get(name), -32768, 32767);
386 s32 Settings::getS32(const std::string &name) const
388 return stoi(get(name));
392 float Settings::getFloat(const std::string &name) const
394 return stof(get(name));
398 u64 Settings::getU64(const std::string &name) const
401 std::string s = get(name);
402 std::istringstream ss(s);
408 v2f Settings::getV2F(const std::string &name) const
413 value.X = stof(f.next(","));
414 value.Y = stof(f.next(")"));
419 v3f Settings::getV3F(const std::string &name) const
424 value.X = stof(f.next(","));
425 value.Y = stof(f.next(","));
426 value.Z = stof(f.next(")"));
431 u32 Settings::getFlagStr(const std::string &name, const FlagDesc *flagdesc,
434 std::string val = get(name);
435 return std::isdigit(val[0])
437 : readFlagString(val, flagdesc, flagmask);
441 // N.B. if getStruct() is used to read a non-POD aggregate type,
442 // the behavior is undefined.
443 bool Settings::getStruct(const std::string &name, const std::string &format,
444 void *out, size_t olen) const
450 } catch (SettingNotFoundException &e) {
454 if (!deSerializeStringToStruct(valstr, format, out, olen))
461 bool Settings::getNoiseParams(const std::string &name, NoiseParams &np) const
463 return getNoiseParamsFromGroup(name, np) || getNoiseParamsFromValue(name, np);
467 bool Settings::getNoiseParamsFromValue(const std::string &name,
468 NoiseParams &np) const
472 if (!getNoEx(name, value))
477 np.offset = stof(f.next(","));
478 np.scale = stof(f.next(","));
480 np.spread.X = stof(f.next(","));
481 np.spread.Y = stof(f.next(","));
482 np.spread.Z = stof(f.next(")"));
484 np.seed = stoi(f.next(","));
485 np.octaves = stoi(f.next(","));
486 np.persist = stof(f.next(""));
492 bool Settings::getNoiseParamsFromGroup(const std::string &name,
493 NoiseParams &np) const
495 Settings *group = NULL;
497 if (!getGroupNoEx(name, group))
500 group->getFloatNoEx("offset", np.offset);
501 group->getFloatNoEx("scale", np.scale);
502 group->getV3FNoEx("spread", np.spread);
503 group->getS32NoEx("seed", np.seed);
504 group->getU16NoEx("octaves", np.octaves);
505 group->getFloatNoEx("persistence", np.persist);
506 group->getFloatNoEx("lacunarity", np.lacunarity);
509 if (!group->getFlagStrNoEx("flags", np.flags, flagdesc_noiseparams))
510 np.flags = NOISE_FLAG_DEFAULTS;
516 bool Settings::exists(const std::string &name) const
518 JMutexAutoLock lock(m_mutex);
520 return (m_settings.find(name) != m_settings.end() ||
521 m_defaults.find(name) != m_defaults.end());
525 std::vector<std::string> Settings::getNames() const
527 std::vector<std::string> names;
528 for (std::map<std::string, SettingsEntry>::const_iterator
529 i = m_settings.begin();
530 i != m_settings.end(); ++i) {
531 names.push_back(i->first);
538 /***************************************
539 * Getters that don't throw exceptions *
540 ***************************************/
542 bool Settings::getEntryNoEx(const std::string &name, SettingsEntry &val) const
545 val = getEntry(name);
547 } catch (SettingNotFoundException &e) {
553 bool Settings::getGroupNoEx(const std::string &name, Settings *&val) const
556 val = getGroup(name);
558 } catch (SettingNotFoundException &e) {
564 bool Settings::getNoEx(const std::string &name, std::string &val) const
569 } catch (SettingNotFoundException &e) {
575 bool Settings::getFlag(const std::string &name) const
578 return getBool(name);
579 } catch(SettingNotFoundException &e) {
585 bool Settings::getFloatNoEx(const std::string &name, float &val) const
588 val = getFloat(name);
590 } catch (SettingNotFoundException &e) {
596 bool Settings::getU16NoEx(const std::string &name, u16 &val) const
601 } catch (SettingNotFoundException &e) {
607 bool Settings::getS16NoEx(const std::string &name, s16 &val) const
612 } catch (SettingNotFoundException &e) {
618 bool Settings::getS32NoEx(const std::string &name, s32 &val) const
623 } catch (SettingNotFoundException &e) {
629 bool Settings::getU64NoEx(const std::string &name, u64 &val) const
634 } catch (SettingNotFoundException &e) {
640 bool Settings::getV2FNoEx(const std::string &name, v2f &val) const
645 } catch (SettingNotFoundException &e) {
651 bool Settings::getV3FNoEx(const std::string &name, v3f &val) const
656 } catch (SettingNotFoundException &e) {
662 // N.B. getFlagStrNoEx() does not set val, but merely modifies it. Thus,
663 // val must be initialized before using getFlagStrNoEx(). The intention of
664 // this is to simplify modifying a flags field from a default value.
665 bool Settings::getFlagStrNoEx(const std::string &name, u32 &val,
666 FlagDesc *flagdesc) const
671 flags = getFlagStr(name, flagdesc, &flagmask);
677 } catch (SettingNotFoundException &e) {
687 void Settings::setEntry(const std::string &name, const void *data,
688 bool set_group, bool set_default)
690 Settings *old_group = NULL;
693 JMutexAutoLock lock(m_mutex);
695 SettingsEntry &entry = set_default ? m_defaults[name] : m_settings[name];
696 old_group = entry.group;
698 entry.value = set_group ? "" : *(const std::string *)data;
699 entry.group = set_group ? *(Settings **)data : NULL;
700 entry.is_group = set_group;
707 void Settings::set(const std::string &name, const std::string &value)
709 setEntry(name, &value, false, false);
715 void Settings::setDefault(const std::string &name, const std::string &value)
717 setEntry(name, &value, false, true);
721 void Settings::setGroup(const std::string &name, Settings *group)
723 setEntry(name, &group, true, false);
727 void Settings::setGroupDefault(const std::string &name, Settings *group)
729 setEntry(name, &group, true, true);
733 void Settings::setBool(const std::string &name, bool value)
735 set(name, value ? "true" : "false");
739 void Settings::setS16(const std::string &name, s16 value)
741 set(name, itos(value));
745 void Settings::setU16(const std::string &name, u16 value)
747 set(name, itos(value));
751 void Settings::setS32(const std::string &name, s32 value)
753 set(name, itos(value));
757 void Settings::setU64(const std::string &name, u64 value)
759 std::ostringstream os;
765 void Settings::setFloat(const std::string &name, float value)
767 set(name, ftos(value));
771 void Settings::setV2F(const std::string &name, v2f value)
773 std::ostringstream os;
774 os << "(" << value.X << "," << value.Y << ")";
779 void Settings::setV3F(const std::string &name, v3f value)
781 std::ostringstream os;
782 os << "(" << value.X << "," << value.Y << "," << value.Z << ")";
787 void Settings::setFlagStr(const std::string &name, u32 flags,
788 const FlagDesc *flagdesc, u32 flagmask)
790 set(name, writeFlagString(flags, flagdesc, flagmask));
794 bool Settings::setStruct(const std::string &name, const std::string &format,
797 std::string structstr;
798 if (!serializeStructToString(&structstr, format, value))
801 set(name, structstr);
806 void Settings::setNoiseParams(const std::string &name,
807 const NoiseParams &np, bool set_default)
809 Settings *group = new Settings;
811 group->setFloat("offset", np.offset);
812 group->setFloat("scale", np.scale);
813 group->setV3F("spread", np.spread);
814 group->setS32("seed", np.seed);
815 group->setU16("octaves", np.octaves);
816 group->setFloat("persistence", np.persist);
817 group->setFloat("lacunarity", np.lacunarity);
818 group->setFlagStr("flags", np.flags, flagdesc_noiseparams, np.flags);
820 setEntry(name, &group, true, set_default);
824 bool Settings::remove(const std::string &name)
826 JMutexAutoLock lock(m_mutex);
828 delete m_settings[name].group;
829 return m_settings.erase(name);
833 void Settings::clear()
835 JMutexAutoLock lock(m_mutex);
840 void Settings::updateValue(const Settings &other, const std::string &name)
845 JMutexAutoLock lock(m_mutex);
848 std::string val = other.get(name);
850 m_settings[name] = val;
851 } catch (SettingNotFoundException &e) {
856 void Settings::update(const Settings &other)
861 JMutexAutoLock lock(m_mutex);
862 JMutexAutoLock lock2(other.m_mutex);
868 SettingsParseEvent Settings::parseConfigObject(const std::string &line,
869 const std::string &end, std::string &name, std::string &value)
871 std::string trimmed_line = trim(line);
873 if (trimmed_line.empty())
875 if (trimmed_line[0] == '#')
877 if (trimmed_line == end)
880 size_t pos = trimmed_line.find('=');
881 if (pos == std::string::npos)
884 name = trim(trimmed_line.substr(0, pos));
885 value = trim(trimmed_line.substr(pos + 1));
889 if (value == "\"\"\"")
890 return SPE_MULTILINE;
896 void Settings::updateNoLock(const Settings &other)
898 m_settings.insert(other.m_settings.begin(), other.m_settings.end());
899 m_defaults.insert(other.m_defaults.begin(), other.m_defaults.end());
903 void Settings::clearNoLock()
905 std::map<std::string, SettingsEntry>::const_iterator it;
906 for (it = m_settings.begin(); it != m_settings.end(); ++it)
907 delete it->second.group;
910 for (it = m_defaults.begin(); it != m_defaults.end(); ++it)
911 delete it->second.group;
916 void Settings::registerChangedCallback(std::string name,
917 setting_changed_callback cbf)
919 m_callbacks[name].push_back(cbf);
923 void Settings::doCallbacks(const std::string name)
925 std::vector<setting_changed_callback> tempvector;
927 JMutexAutoLock lock(m_mutex);
928 if (m_callbacks.find(name) != m_callbacks.end())
930 tempvector = m_callbacks[name];
934 std::vector<setting_changed_callback>::iterator iter;
935 for (iter = tempvector.begin(); iter != tempvector.end(); iter++)