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::getMultiline(std::istream &is, size_t *num_lines)
74 std::getline(is, line);
78 value.push_back('\n');
81 size_t len = value.size();
92 bool Settings::readConfigFile(const char *filename)
94 std::ifstream is(filename);
98 return parseConfigLines(is, "");
102 bool Settings::parseConfigLines(std::istream &is, const std::string &end)
104 JMutexAutoLock lock(m_mutex);
106 std::string line, name, value;
109 std::getline(is, line);
110 SettingsParseEvent event = parseConfigObject(line, end, name, value);
118 m_settings[name] = SettingsEntry(value);
123 Settings *group = new Settings;
124 if (!group->parseConfigLines(is, "}")) {
128 m_settings[name] = SettingsEntry(group);
132 m_settings[name] = SettingsEntry(getMultiline(is));
141 void Settings::writeLines(std::ostream &os, u32 tab_depth) const
143 JMutexAutoLock lock(m_mutex);
145 for (std::map<std::string, SettingsEntry>::const_iterator
146 it = m_settings.begin();
147 it != m_settings.end(); ++it)
148 printEntry(os, it->first, it->second, tab_depth);
152 void Settings::printEntry(std::ostream &os, const std::string &name,
153 const SettingsEntry &entry, u32 tab_depth)
155 for (u32 i = 0; i != tab_depth; i++)
158 if (entry.is_group) {
159 os << name << " = {\n";
161 entry.group->writeLines(os, tab_depth + 1);
163 for (u32 i = 0; i != tab_depth; i++)
169 if (entry.value.find('\n') != std::string::npos)
170 os << "\"\"\"\n" << entry.value << "\n\"\"\"\n";
172 os << entry.value << "\n";
177 bool Settings::updateConfigObject(std::istream &is, std::ostream &os,
178 const std::string &end, u32 tab_depth)
180 std::map<std::string, SettingsEntry>::const_iterator it;
181 std::set<std::string> present_entries;
182 std::string line, name, value;
183 bool was_modified = false;
184 bool end_found = false;
186 // Add any settings that exist in the config file with the current value
187 // in the object if existing
188 while (is.good() && !end_found) {
189 std::getline(is, line);
190 SettingsParseEvent event = parseConfigObject(line, end, name, value);
194 os << line << (is.eof() ? "" : "\n");
198 value = getMultiline(is);
201 it = m_settings.find(name);
202 if (it != m_settings.end() &&
203 (it->second.is_group || it->second.value != value)) {
204 printEntry(os, name, it->second, tab_depth);
207 assert(it->second.group == NULL);
209 if (event == SPE_MULTILINE)
210 os << value << "\n\"\"\"\n";
212 present_entries.insert(name);
215 it = m_settings.find(name);
216 if (it != m_settings.end() && it->second.is_group) {
218 assert(it->second.group != NULL);
219 was_modified |= it->second.group->updateConfigObject(is, os,
222 printEntry(os, name, it->second, tab_depth);
225 present_entries.insert(name);
228 os << line << (is.eof() ? "" : "\n");
233 // Add any settings in the object that don't exist in the config file yet
234 for (it = m_settings.begin(); it != m_settings.end(); ++it) {
235 if (present_entries.find(it->first) != present_entries.end())
238 printEntry(os, it->first, it->second, tab_depth);
246 bool Settings::updateConfigFile(const char *filename)
248 JMutexAutoLock lock(m_mutex);
250 std::ifstream is(filename);
251 std::ostringstream os(std::ios_base::binary);
253 bool was_modified = updateConfigObject(is, os, "");
259 if (!fs::safeWriteToFile(filename, os.str())) {
260 errorstream << "Error writing configuration file: \""
261 << filename << "\"" << std::endl;
269 bool Settings::parseCommandLine(int argc, char *argv[],
270 std::map<std::string, ValueSpec> &allowed_options)
272 int nonopt_index = 0;
273 for (int i = 1; i < argc; i++) {
274 std::string arg_name = argv[i];
275 if (arg_name.substr(0, 2) != "--") {
276 // If option doesn't start with -, read it in as nonoptX
277 if (arg_name[0] != '-'){
278 std::string name = "nonopt";
279 name += itos(nonopt_index);
284 errorstream << "Invalid command-line parameter \""
285 << arg_name << "\": --<option> expected." << std::endl;
289 std::string name = arg_name.substr(2);
291 std::map<std::string, ValueSpec>::iterator n;
292 n = allowed_options.find(name);
293 if (n == allowed_options.end()) {
294 errorstream << "Unknown command-line parameter \""
295 << arg_name << "\"" << std::endl;
299 ValueType type = n->second.type;
301 std::string value = "";
303 if (type == VALUETYPE_FLAG) {
306 if ((i + 1) >= argc) {
307 errorstream << "Invalid command-line parameter \""
308 << name << "\": missing value" << std::endl;
327 const SettingsEntry &Settings::getEntry(const std::string &name) const
329 JMutexAutoLock lock(m_mutex);
331 std::map<std::string, SettingsEntry>::const_iterator n;
332 if ((n = m_settings.find(name)) == m_settings.end()) {
333 if ((n = m_defaults.find(name)) == m_defaults.end())
334 throw SettingNotFoundException("Setting [" + name + "] not found.");
340 Settings *Settings::getGroup(const std::string &name) const
342 const SettingsEntry &entry = getEntry(name);
344 throw SettingNotFoundException("Setting [" + name + "] is not a group.");
349 std::string Settings::get(const std::string &name) const
351 const SettingsEntry &entry = getEntry(name);
353 throw SettingNotFoundException("Setting [" + name + "] is a group.");
358 bool Settings::getBool(const std::string &name) const
360 return is_yes(get(name));
364 u16 Settings::getU16(const std::string &name) const
366 return stoi(get(name), 0, 65535);
370 s16 Settings::getS16(const std::string &name) const
372 return stoi(get(name), -32768, 32767);
376 s32 Settings::getS32(const std::string &name) const
378 return stoi(get(name));
382 float Settings::getFloat(const std::string &name) const
384 return stof(get(name));
388 u64 Settings::getU64(const std::string &name) const
391 std::string s = get(name);
392 std::istringstream ss(s);
398 v2f Settings::getV2F(const std::string &name) const
403 value.X = stof(f.next(","));
404 value.Y = stof(f.next(")"));
409 v3f Settings::getV3F(const std::string &name) const
414 value.X = stof(f.next(","));
415 value.Y = stof(f.next(","));
416 value.Z = stof(f.next(")"));
421 u32 Settings::getFlagStr(const std::string &name, const FlagDesc *flagdesc,
424 std::string val = get(name);
425 return std::isdigit(val[0])
427 : readFlagString(val, flagdesc, flagmask);
431 // N.B. if getStruct() is used to read a non-POD aggregate type,
432 // the behavior is undefined.
433 bool Settings::getStruct(const std::string &name, const std::string &format,
434 void *out, size_t olen) const
440 } catch (SettingNotFoundException &e) {
444 if (!deSerializeStringToStruct(valstr, format, out, olen))
451 bool Settings::getNoiseParams(const std::string &name, NoiseParams &np) const
453 return getNoiseParamsFromGroup(name, np) || getNoiseParamsFromValue(name, np);
457 bool Settings::getNoiseParamsFromValue(const std::string &name,
458 NoiseParams &np) const
462 if (!getNoEx(name, value))
467 np.offset = stof(f.next(","));
468 np.scale = stof(f.next(","));
470 np.spread.X = stof(f.next(","));
471 np.spread.Y = stof(f.next(","));
472 np.spread.Z = stof(f.next(")"));
474 np.seed = stoi(f.next(","));
475 np.octaves = stoi(f.next(","));
476 np.persist = stof(f.next(","));
478 std::string optional_params = f.next("");
479 if (optional_params != "")
480 np.lacunarity = stof(optional_params);
486 bool Settings::getNoiseParamsFromGroup(const std::string &name,
487 NoiseParams &np) const
489 Settings *group = NULL;
491 if (!getGroupNoEx(name, group))
494 group->getFloatNoEx("offset", np.offset);
495 group->getFloatNoEx("scale", np.scale);
496 group->getV3FNoEx("spread", np.spread);
497 group->getS32NoEx("seed", np.seed);
498 group->getU16NoEx("octaves", np.octaves);
499 group->getFloatNoEx("persistence", np.persist);
500 group->getFloatNoEx("lacunarity", np.lacunarity);
503 if (!group->getFlagStrNoEx("flags", np.flags, flagdesc_noiseparams))
504 np.flags = NOISE_FLAG_DEFAULTS;
510 bool Settings::exists(const std::string &name) const
512 JMutexAutoLock lock(m_mutex);
514 return (m_settings.find(name) != m_settings.end() ||
515 m_defaults.find(name) != m_defaults.end());
519 std::vector<std::string> Settings::getNames() const
521 std::vector<std::string> names;
522 for (std::map<std::string, SettingsEntry>::const_iterator
523 i = m_settings.begin();
524 i != m_settings.end(); ++i) {
525 names.push_back(i->first);
532 /***************************************
533 * Getters that don't throw exceptions *
534 ***************************************/
536 bool Settings::getEntryNoEx(const std::string &name, SettingsEntry &val) const
539 val = getEntry(name);
541 } catch (SettingNotFoundException &e) {
547 bool Settings::getGroupNoEx(const std::string &name, Settings *&val) const
550 val = getGroup(name);
552 } catch (SettingNotFoundException &e) {
558 bool Settings::getNoEx(const std::string &name, std::string &val) const
563 } catch (SettingNotFoundException &e) {
569 bool Settings::getFlag(const std::string &name) const
572 return getBool(name);
573 } catch(SettingNotFoundException &e) {
579 bool Settings::getFloatNoEx(const std::string &name, float &val) const
582 val = getFloat(name);
584 } catch (SettingNotFoundException &e) {
590 bool Settings::getU16NoEx(const std::string &name, u16 &val) const
595 } catch (SettingNotFoundException &e) {
601 bool Settings::getS16NoEx(const std::string &name, s16 &val) const
606 } catch (SettingNotFoundException &e) {
612 bool Settings::getS32NoEx(const std::string &name, s32 &val) const
617 } catch (SettingNotFoundException &e) {
623 bool Settings::getU64NoEx(const std::string &name, u64 &val) const
628 } catch (SettingNotFoundException &e) {
634 bool Settings::getV2FNoEx(const std::string &name, v2f &val) const
639 } catch (SettingNotFoundException &e) {
645 bool Settings::getV3FNoEx(const std::string &name, v3f &val) const
650 } catch (SettingNotFoundException &e) {
656 // N.B. getFlagStrNoEx() does not set val, but merely modifies it. Thus,
657 // val must be initialized before using getFlagStrNoEx(). The intention of
658 // this is to simplify modifying a flags field from a default value.
659 bool Settings::getFlagStrNoEx(const std::string &name, u32 &val,
660 FlagDesc *flagdesc) const
665 flags = getFlagStr(name, flagdesc, &flagmask);
671 } catch (SettingNotFoundException &e) {
681 void Settings::setEntry(const std::string &name, const void *data,
682 bool set_group, bool set_default)
684 Settings *old_group = NULL;
686 // Strip any potentially dangerous characters from the name (note the value
687 // has no such restrictions)
689 for (const char *s = "\t\n\v\f\r\b =\""; *s; s++)
690 n.erase(std::remove(n.begin(), n.end(), *s), n.end());
693 JMutexAutoLock lock(m_mutex);
695 SettingsEntry &entry = set_default ? m_defaults[n] : m_settings[n];
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++)