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 "threading/mutex_auto_lock.h"
24 #include "util/strfnd.h"
30 #include "util/serialize.h"
36 static Settings main_settings;
37 Settings *g_settings = &main_settings;
38 std::string g_settings_path;
46 Settings & Settings::operator += (const Settings &other)
54 Settings & Settings::operator = (const Settings &other)
59 MutexAutoLock lock(m_mutex);
60 MutexAutoLock lock2(other.m_mutex);
69 bool Settings::checkNameValid(const std::string &name)
71 bool valid = name.find_first_of("=\"{}#") == std::string::npos;
72 if (valid) valid = trim(name) == name;
74 errorstream << "Invalid setting name \"" << name << "\""
82 bool Settings::checkValueValid(const std::string &value)
84 if (value.substr(0, 3) == "\"\"\"" ||
85 value.find("\n\"\"\"") != std::string::npos) {
86 errorstream << "Invalid character sequence '\"\"\"' found in"
87 " setting value!" << std::endl;
93 std::string Settings::getMultiline(std::istream &is, size_t *num_lines)
101 std::getline(is, line);
102 if (line == "\"\"\"")
105 value.push_back('\n');
108 size_t len = value.size();
110 value.erase(len - 1);
119 bool Settings::readConfigFile(const char *filename)
121 std::ifstream is(filename);
125 return parseConfigLines(is, "");
129 bool Settings::parseConfigLines(std::istream &is, const std::string &end)
131 MutexAutoLock lock(m_mutex);
133 std::string line, name, value;
136 std::getline(is, line);
137 SettingsParseEvent event = parseConfigObject(line, end, name, value);
145 m_settings[name] = SettingsEntry(value);
150 Settings *group = new Settings;
151 if (!group->parseConfigLines(is, "}")) {
155 m_settings[name] = SettingsEntry(group);
159 m_settings[name] = SettingsEntry(getMultiline(is));
168 void Settings::writeLines(std::ostream &os, u32 tab_depth) const
170 MutexAutoLock lock(m_mutex);
172 for (const auto &setting_it : m_settings)
173 printEntry(os, setting_it.first, setting_it.second, tab_depth);
177 void Settings::printEntry(std::ostream &os, const std::string &name,
178 const SettingsEntry &entry, u32 tab_depth)
180 for (u32 i = 0; i != tab_depth; i++)
183 if (entry.is_group) {
184 os << name << " = {\n";
186 entry.group->writeLines(os, tab_depth + 1);
188 for (u32 i = 0; i != tab_depth; i++)
194 if (entry.value.find('\n') != std::string::npos)
195 os << "\"\"\"\n" << entry.value << "\n\"\"\"\n";
197 os << entry.value << "\n";
202 bool Settings::updateConfigObject(std::istream &is, std::ostream &os,
203 const std::string &end, u32 tab_depth)
205 SettingEntries::const_iterator it;
206 std::set<std::string> present_entries;
207 std::string line, name, value;
208 bool was_modified = false;
209 bool end_found = false;
211 // Add any settings that exist in the config file with the current value
212 // in the object if existing
213 while (is.good() && !end_found) {
214 std::getline(is, line);
215 SettingsParseEvent event = parseConfigObject(line, end, name, value);
219 os << line << (is.eof() ? "" : "\n");
223 value = getMultiline(is);
226 it = m_settings.find(name);
227 if (it != m_settings.end() &&
228 (it->second.is_group || it->second.value != value)) {
229 printEntry(os, name, it->second, tab_depth);
233 if (event == SPE_MULTILINE)
234 os << value << "\n\"\"\"\n";
236 present_entries.insert(name);
239 it = m_settings.find(name);
240 if (it != m_settings.end() && it->second.is_group) {
242 sanity_check(it->second.group != NULL);
243 was_modified |= it->second.group->updateConfigObject(is, os,
246 printEntry(os, name, it->second, tab_depth);
249 present_entries.insert(name);
252 os << line << (is.eof() ? "" : "\n");
257 // Add any settings in the object that don't exist in the config file yet
258 for (it = m_settings.begin(); it != m_settings.end(); ++it) {
259 if (present_entries.find(it->first) != present_entries.end())
262 printEntry(os, it->first, it->second, tab_depth);
270 bool Settings::updateConfigFile(const char *filename)
272 MutexAutoLock lock(m_mutex);
274 std::ifstream is(filename);
275 std::ostringstream os(std::ios_base::binary);
277 bool was_modified = updateConfigObject(is, os, "");
283 if (!fs::safeWriteToFile(filename, os.str())) {
284 errorstream << "Error writing configuration file: \""
285 << filename << "\"" << std::endl;
293 bool Settings::parseCommandLine(int argc, char *argv[],
294 std::map<std::string, ValueSpec> &allowed_options)
296 int nonopt_index = 0;
297 for (int i = 1; i < argc; i++) {
298 std::string arg_name = argv[i];
299 if (arg_name.substr(0, 2) != "--") {
300 // If option doesn't start with -, read it in as nonoptX
301 if (arg_name[0] != '-'){
302 std::string name = "nonopt";
303 name += itos(nonopt_index);
308 errorstream << "Invalid command-line parameter \""
309 << arg_name << "\": --<option> expected." << std::endl;
313 std::string name = arg_name.substr(2);
315 std::map<std::string, ValueSpec>::iterator n;
316 n = allowed_options.find(name);
317 if (n == allowed_options.end()) {
318 errorstream << "Unknown command-line parameter \""
319 << arg_name << "\"" << std::endl;
323 ValueType type = n->second.type;
327 if (type == VALUETYPE_FLAG) {
330 if ((i + 1) >= argc) {
331 errorstream << "Invalid command-line parameter \""
332 << name << "\": missing value" << std::endl;
351 const SettingsEntry &Settings::getEntry(const std::string &name) const
353 MutexAutoLock lock(m_mutex);
355 SettingEntries::const_iterator n;
356 if ((n = m_settings.find(name)) == m_settings.end()) {
357 if ((n = m_defaults.find(name)) == m_defaults.end())
358 throw SettingNotFoundException("Setting [" + name + "] not found.");
364 Settings *Settings::getGroup(const std::string &name) const
366 const SettingsEntry &entry = getEntry(name);
368 throw SettingNotFoundException("Setting [" + name + "] is not a group.");
373 const std::string &Settings::get(const std::string &name) const
375 const SettingsEntry &entry = getEntry(name);
377 throw SettingNotFoundException("Setting [" + name + "] is a group.");
382 bool Settings::getBool(const std::string &name) const
384 return is_yes(get(name));
388 u16 Settings::getU16(const std::string &name) const
390 return stoi(get(name), 0, 65535);
394 s16 Settings::getS16(const std::string &name) const
396 return stoi(get(name), -32768, 32767);
400 u32 Settings::getU32(const std::string &name) const
402 return (u32) stoi(get(name));
405 s32 Settings::getS32(const std::string &name) const
407 return stoi(get(name));
411 float Settings::getFloat(const std::string &name) const
413 return stof(get(name));
417 u64 Settings::getU64(const std::string &name) const
420 std::string s = get(name);
421 std::istringstream ss(s);
427 v2f Settings::getV2F(const std::string &name) const
432 value.X = stof(f.next(","));
433 value.Y = stof(f.next(")"));
438 v3f Settings::getV3F(const std::string &name) const
443 value.X = stof(f.next(","));
444 value.Y = stof(f.next(","));
445 value.Z = stof(f.next(")"));
450 u32 Settings::getFlagStr(const std::string &name, const FlagDesc *flagdesc,
453 std::string val = get(name);
454 return std::isdigit(val[0])
456 : readFlagString(val, flagdesc, flagmask);
460 // N.B. if getStruct() is used to read a non-POD aggregate type,
461 // the behavior is undefined.
462 bool Settings::getStruct(const std::string &name, const std::string &format,
463 void *out, size_t olen) const
469 } catch (SettingNotFoundException &e) {
473 if (!deSerializeStringToStruct(valstr, format, out, olen))
480 bool Settings::getNoiseParams(const std::string &name, NoiseParams &np) const
482 return getNoiseParamsFromGroup(name, np) || getNoiseParamsFromValue(name, np);
486 bool Settings::getNoiseParamsFromValue(const std::string &name,
487 NoiseParams &np) const
491 if (!getNoEx(name, value))
496 np.offset = stof(f.next(","));
497 np.scale = stof(f.next(","));
499 np.spread.X = stof(f.next(","));
500 np.spread.Y = stof(f.next(","));
501 np.spread.Z = stof(f.next(")"));
503 np.seed = stoi(f.next(","));
504 np.octaves = stoi(f.next(","));
505 np.persist = stof(f.next(","));
507 std::string optional_params = f.next("");
508 if (!optional_params.empty())
509 np.lacunarity = stof(optional_params);
515 bool Settings::getNoiseParamsFromGroup(const std::string &name,
516 NoiseParams &np) const
518 Settings *group = NULL;
520 if (!getGroupNoEx(name, group))
523 group->getFloatNoEx("offset", np.offset);
524 group->getFloatNoEx("scale", np.scale);
525 group->getV3FNoEx("spread", np.spread);
526 group->getS32NoEx("seed", np.seed);
527 group->getU16NoEx("octaves", np.octaves);
528 group->getFloatNoEx("persistence", np.persist);
529 group->getFloatNoEx("lacunarity", np.lacunarity);
532 if (!group->getFlagStrNoEx("flags", np.flags, flagdesc_noiseparams))
533 np.flags = NOISE_FLAG_DEFAULTS;
539 bool Settings::exists(const std::string &name) const
541 MutexAutoLock lock(m_mutex);
543 return (m_settings.find(name) != m_settings.end() ||
544 m_defaults.find(name) != m_defaults.end());
548 std::vector<std::string> Settings::getNames() const
550 std::vector<std::string> names;
551 for (const auto &settings_it : m_settings) {
552 names.push_back(settings_it.first);
559 /***************************************
560 * Getters that don't throw exceptions *
561 ***************************************/
563 bool Settings::getEntryNoEx(const std::string &name, SettingsEntry &val) const
566 val = getEntry(name);
568 } catch (SettingNotFoundException &e) {
574 bool Settings::getGroupNoEx(const std::string &name, Settings *&val) const
577 val = getGroup(name);
579 } catch (SettingNotFoundException &e) {
585 bool Settings::getNoEx(const std::string &name, std::string &val) const
590 } catch (SettingNotFoundException &e) {
596 bool Settings::getFlag(const std::string &name) const
599 return getBool(name);
600 } catch(SettingNotFoundException &e) {
606 bool Settings::getFloatNoEx(const std::string &name, float &val) const
609 val = getFloat(name);
611 } catch (SettingNotFoundException &e) {
617 bool Settings::getU16NoEx(const std::string &name, u16 &val) const
622 } catch (SettingNotFoundException &e) {
628 bool Settings::getS16NoEx(const std::string &name, s16 &val) const
633 } catch (SettingNotFoundException &e) {
639 bool Settings::getS32NoEx(const std::string &name, s32 &val) const
644 } catch (SettingNotFoundException &e) {
650 bool Settings::getU64NoEx(const std::string &name, u64 &val) const
655 } catch (SettingNotFoundException &e) {
661 bool Settings::getV2FNoEx(const std::string &name, v2f &val) const
666 } catch (SettingNotFoundException &e) {
672 bool Settings::getV3FNoEx(const std::string &name, v3f &val) const
677 } catch (SettingNotFoundException &e) {
683 // N.B. getFlagStrNoEx() does not set val, but merely modifies it. Thus,
684 // val must be initialized before using getFlagStrNoEx(). The intention of
685 // this is to simplify modifying a flags field from a default value.
686 bool Settings::getFlagStrNoEx(const std::string &name, u32 &val,
687 FlagDesc *flagdesc) const
692 flags = getFlagStr(name, flagdesc, &flagmask);
698 } catch (SettingNotFoundException &e) {
708 bool Settings::setEntry(const std::string &name, const void *data,
709 bool set_group, bool set_default)
711 Settings *old_group = NULL;
713 if (!checkNameValid(name))
715 if (!set_group && !checkValueValid(*(const std::string *)data))
719 MutexAutoLock lock(m_mutex);
721 SettingsEntry &entry = set_default ? m_defaults[name] : m_settings[name];
722 old_group = entry.group;
724 entry.value = set_group ? "" : *(const std::string *)data;
725 entry.group = set_group ? *(Settings **)data : NULL;
726 entry.is_group = set_group;
735 bool Settings::set(const std::string &name, const std::string &value)
737 if (!setEntry(name, &value, false, false))
745 bool Settings::setDefault(const std::string &name, const std::string &value)
747 return setEntry(name, &value, false, true);
751 bool Settings::setGroup(const std::string &name, Settings *group)
753 return setEntry(name, &group, true, false);
757 bool Settings::setGroupDefault(const std::string &name, Settings *group)
759 return setEntry(name, &group, true, true);
763 bool Settings::setBool(const std::string &name, bool value)
765 return set(name, value ? "true" : "false");
769 bool Settings::setS16(const std::string &name, s16 value)
771 return set(name, itos(value));
775 bool Settings::setU16(const std::string &name, u16 value)
777 return set(name, itos(value));
781 bool Settings::setS32(const std::string &name, s32 value)
783 return set(name, itos(value));
787 bool Settings::setU64(const std::string &name, u64 value)
789 std::ostringstream os;
791 return set(name, os.str());
795 bool Settings::setFloat(const std::string &name, float value)
797 return set(name, ftos(value));
801 bool Settings::setV2F(const std::string &name, v2f value)
803 std::ostringstream os;
804 os << "(" << value.X << "," << value.Y << ")";
805 return set(name, os.str());
809 bool Settings::setV3F(const std::string &name, v3f value)
811 std::ostringstream os;
812 os << "(" << value.X << "," << value.Y << "," << value.Z << ")";
813 return set(name, os.str());
817 bool Settings::setFlagStr(const std::string &name, u32 flags,
818 const FlagDesc *flagdesc, u32 flagmask)
820 return set(name, writeFlagString(flags, flagdesc, flagmask));
824 bool Settings::setStruct(const std::string &name, const std::string &format,
827 std::string structstr;
828 if (!serializeStructToString(&structstr, format, value))
831 return set(name, structstr);
835 bool Settings::setNoiseParams(const std::string &name,
836 const NoiseParams &np, bool set_default)
838 Settings *group = new Settings;
840 group->setFloat("offset", np.offset);
841 group->setFloat("scale", np.scale);
842 group->setV3F("spread", np.spread);
843 group->setS32("seed", np.seed);
844 group->setU16("octaves", np.octaves);
845 group->setFloat("persistence", np.persist);
846 group->setFloat("lacunarity", np.lacunarity);
847 group->setFlagStr("flags", np.flags, flagdesc_noiseparams, np.flags);
849 return setEntry(name, &group, true, set_default);
853 bool Settings::remove(const std::string &name)
855 MutexAutoLock lock(m_mutex);
857 SettingEntries::iterator it = m_settings.find(name);
858 if (it != m_settings.end()) {
859 delete it->second.group;
860 m_settings.erase(it);
868 void Settings::clear()
870 MutexAutoLock lock(m_mutex);
874 void Settings::clearDefaults()
876 MutexAutoLock lock(m_mutex);
877 clearDefaultsNoLock();
880 void Settings::updateValue(const Settings &other, const std::string &name)
885 MutexAutoLock lock(m_mutex);
888 m_settings[name] = other.get(name);
889 } catch (SettingNotFoundException &e) {
894 void Settings::update(const Settings &other)
899 MutexAutoLock lock(m_mutex);
900 MutexAutoLock lock2(other.m_mutex);
906 SettingsParseEvent Settings::parseConfigObject(const std::string &line,
907 const std::string &end, std::string &name, std::string &value)
909 std::string trimmed_line = trim(line);
911 if (trimmed_line.empty())
913 if (trimmed_line[0] == '#')
915 if (trimmed_line == end)
918 size_t pos = trimmed_line.find('=');
919 if (pos == std::string::npos)
922 name = trim(trimmed_line.substr(0, pos));
923 value = trim(trimmed_line.substr(pos + 1));
927 if (value == "\"\"\"")
928 return SPE_MULTILINE;
934 void Settings::updateNoLock(const Settings &other)
936 m_settings.insert(other.m_settings.begin(), other.m_settings.end());
937 m_defaults.insert(other.m_defaults.begin(), other.m_defaults.end());
941 void Settings::clearNoLock()
944 for (SettingEntries::const_iterator it = m_settings.begin();
945 it != m_settings.end(); ++it)
946 delete it->second.group;
949 clearDefaultsNoLock();
952 void Settings::clearDefaultsNoLock()
954 for (SettingEntries::const_iterator it = m_defaults.begin();
955 it != m_defaults.end(); ++it)
956 delete it->second.group;
961 void Settings::registerChangedCallback(const std::string &name,
962 SettingsChangedCallback cbf, void *userdata)
964 MutexAutoLock lock(m_callback_mutex);
965 m_callbacks[name].emplace_back(cbf, userdata);
968 void Settings::deregisterChangedCallback(const std::string &name,
969 SettingsChangedCallback cbf, void *userdata)
971 MutexAutoLock lock(m_callback_mutex);
972 SettingsCallbackMap::iterator it_cbks = m_callbacks.find(name);
974 if (it_cbks != m_callbacks.end()) {
975 SettingsCallbackList &cbks = it_cbks->second;
977 SettingsCallbackList::iterator position =
978 std::find(cbks.begin(), cbks.end(), std::make_pair(cbf, userdata));
980 if (position != cbks.end())
981 cbks.erase(position);
985 void Settings::doCallbacks(const std::string &name) const
987 MutexAutoLock lock(m_callback_mutex);
989 SettingsCallbackMap::const_iterator it_cbks = m_callbacks.find(name);
990 if (it_cbks != m_callbacks.end()) {
991 SettingsCallbackList::const_iterator it;
992 for (it = it_cbks->second.begin(); it != it_cbks->second.end(); ++it)
993 (it->first)(name, it->second);