settings.cpp 23 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  1. /*
  2. Minetest
  3. Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #include "settings.h"
  17. #include "irrlichttypes_bloated.h"
  18. #include "exceptions.h"
  19. #include "threading/mutex_auto_lock.h"
  20. #include "util/numeric.h" // rangelim
  21. #include "util/strfnd.h"
  22. #include <iostream>
  23. #include <fstream>
  24. #include <sstream>
  25. #include "debug.h"
  26. #include "log.h"
  27. #include "util/serialize.h"
  28. #include "filesys.h"
  29. #include "noise.h"
  30. #include <cctype>
  31. #include <algorithm>
  32. Settings *g_settings = nullptr;
  33. static SettingsHierarchy g_hierarchy;
  34. std::string g_settings_path;
  35. std::unordered_map<std::string, const FlagDesc *> Settings::s_flags;
  36. /* Settings hierarchy implementation */
  37. SettingsHierarchy::SettingsHierarchy(Settings *fallback)
  38. {
  39. layers.push_back(fallback);
  40. }
  41. Settings *SettingsHierarchy::getLayer(int layer) const
  42. {
  43. if (layer < 0 || layer >= (int)layers.size())
  44. throw BaseException("Invalid settings layer");
  45. return layers[layer];
  46. }
  47. Settings *SettingsHierarchy::getParent(int layer) const
  48. {
  49. assert(layer >= 0 && layer < (int)layers.size());
  50. // iterate towards the origin (0) to find the next fallback layer
  51. for (int i = layer - 1; i >= 0; --i) {
  52. if (layers[i])
  53. return layers[i];
  54. }
  55. return nullptr;
  56. }
  57. void SettingsHierarchy::onLayerCreated(int layer, Settings *obj)
  58. {
  59. if (layer < 0)
  60. throw BaseException("Invalid settings layer");
  61. if ((int)layers.size() < layer + 1)
  62. layers.resize(layer + 1);
  63. Settings *&pos = layers[layer];
  64. if (pos)
  65. throw BaseException("Setting layer " + itos(layer) + " already exists");
  66. pos = obj;
  67. // This feels bad
  68. if (this == &g_hierarchy && layer == (int)SL_GLOBAL)
  69. g_settings = obj;
  70. }
  71. void SettingsHierarchy::onLayerRemoved(int layer)
  72. {
  73. assert(layer >= 0 && layer < (int)layers.size());
  74. layers[layer] = nullptr;
  75. if (this == &g_hierarchy && layer == (int)SL_GLOBAL)
  76. g_settings = nullptr;
  77. }
  78. /* Settings implementation */
  79. Settings *Settings::createLayer(SettingsLayer sl, std::string_view end_tag)
  80. {
  81. return new Settings(end_tag, &g_hierarchy, (int)sl);
  82. }
  83. Settings *Settings::getLayer(SettingsLayer sl)
  84. {
  85. return g_hierarchy.getLayer(sl);
  86. }
  87. Settings::Settings(std::string_view end_tag, SettingsHierarchy *h,
  88. int settings_layer) :
  89. m_end_tag(end_tag),
  90. m_hierarchy(h),
  91. m_settingslayer(settings_layer)
  92. {
  93. if (m_hierarchy)
  94. m_hierarchy->onLayerCreated(m_settingslayer, this);
  95. }
  96. Settings::~Settings()
  97. {
  98. MutexAutoLock lock(m_mutex);
  99. if (m_hierarchy)
  100. m_hierarchy->onLayerRemoved(m_settingslayer);
  101. clearNoLock();
  102. }
  103. Settings & Settings::operator=(const Settings &other)
  104. {
  105. if (&other == this)
  106. return *this;
  107. // TODO: Avoid copying Settings objects. Make this private.
  108. FATAL_ERROR_IF(m_hierarchy || other.m_hierarchy,
  109. "Cannot copy or overwrite Settings object that belongs to a hierarchy");
  110. MutexAutoLock lock(m_mutex);
  111. MutexAutoLock lock2(other.m_mutex);
  112. clearNoLock();
  113. m_settings = other.m_settings;
  114. m_callbacks = other.m_callbacks;
  115. return *this;
  116. }
  117. bool Settings::checkNameValid(std::string_view name)
  118. {
  119. bool valid = name.find_first_of("=\"{}#") == std::string::npos;
  120. if (valid)
  121. valid = std::find_if(name.begin(), name.end(), ::isspace) == name.end();
  122. if (!valid) {
  123. errorstream << "Invalid setting name \"" << name << "\""
  124. << std::endl;
  125. return false;
  126. }
  127. return true;
  128. }
  129. bool Settings::checkValueValid(std::string_view value)
  130. {
  131. if (value.substr(0, 3) == "\"\"\"" ||
  132. value.find("\n\"\"\"") != std::string::npos) {
  133. errorstream << "Invalid character sequence '\"\"\"' found in"
  134. " setting value!" << std::endl;
  135. return false;
  136. }
  137. return true;
  138. }
  139. std::string Settings::getMultiline(std::istream &is, size_t *num_lines)
  140. {
  141. size_t lines = 1;
  142. std::string value;
  143. std::string line;
  144. while (is.good()) {
  145. lines++;
  146. std::getline(is, line);
  147. if (line == "\"\"\"")
  148. break;
  149. value += line;
  150. value.push_back('\n');
  151. }
  152. size_t len = value.size();
  153. if (len)
  154. value.erase(len - 1);
  155. if (num_lines)
  156. *num_lines = lines;
  157. return value;
  158. }
  159. bool Settings::readConfigFile(const char *filename)
  160. {
  161. std::ifstream is(filename);
  162. if (!is.good())
  163. return false;
  164. return parseConfigLines(is);
  165. }
  166. bool Settings::parseConfigLines(std::istream &is)
  167. {
  168. MutexAutoLock lock(m_mutex);
  169. std::string line, name, value;
  170. while (is.good()) {
  171. std::getline(is, line);
  172. SettingsParseEvent event = parseConfigObject(line, name, value);
  173. switch (event) {
  174. case SPE_NONE:
  175. case SPE_INVALID:
  176. case SPE_COMMENT:
  177. break;
  178. case SPE_KVPAIR:
  179. m_settings[name] = SettingsEntry(value);
  180. break;
  181. case SPE_END:
  182. return true;
  183. case SPE_GROUP: {
  184. Settings *group = new Settings("}");
  185. if (!group->parseConfigLines(is)) {
  186. delete group;
  187. return false;
  188. }
  189. m_settings[name] = SettingsEntry(group);
  190. break;
  191. }
  192. case SPE_MULTILINE:
  193. m_settings[name] = SettingsEntry(getMultiline(is));
  194. break;
  195. }
  196. }
  197. // false (failure) if end tag not found
  198. return m_end_tag.empty();
  199. }
  200. void Settings::writeLines(std::ostream &os, u32 tab_depth) const
  201. {
  202. MutexAutoLock lock(m_mutex);
  203. for (const auto &setting_it : m_settings)
  204. printEntry(os, setting_it.first, setting_it.second, tab_depth);
  205. // For groups this must be "}" !
  206. if (!m_end_tag.empty()) {
  207. for (u32 i = 0; i < tab_depth; i++)
  208. os << "\t";
  209. os << m_end_tag << "\n";
  210. }
  211. }
  212. void Settings::printEntry(std::ostream &os, const std::string &name,
  213. const SettingsEntry &entry, u32 tab_depth)
  214. {
  215. for (u32 i = 0; i != tab_depth; i++)
  216. os << "\t";
  217. if (entry.is_group) {
  218. os << name << " = {\n";
  219. entry.group->writeLines(os, tab_depth + 1);
  220. // Closing bracket handled by writeLines
  221. } else {
  222. os << name << " = ";
  223. if (entry.value.find('\n') != std::string::npos)
  224. os << "\"\"\"\n" << entry.value << "\n\"\"\"\n";
  225. else
  226. os << entry.value << "\n";
  227. }
  228. }
  229. bool Settings::updateConfigObject(std::istream &is, std::ostream &os, u32 tab_depth)
  230. {
  231. SettingEntries::const_iterator it;
  232. std::set<std::string> present_entries;
  233. std::string line, name, value;
  234. bool was_modified = false;
  235. bool end_found = false;
  236. // Add any settings that exist in the config file with the current value
  237. // in the object if existing
  238. while (is.good() && !end_found) {
  239. std::getline(is, line);
  240. SettingsParseEvent event = parseConfigObject(line, name, value);
  241. switch (event) {
  242. case SPE_END:
  243. // Skip end tag. Append later.
  244. end_found = true;
  245. break;
  246. case SPE_MULTILINE:
  247. value = getMultiline(is);
  248. /* FALLTHROUGH */
  249. case SPE_KVPAIR:
  250. it = m_settings.find(name);
  251. if (it != m_settings.end() &&
  252. (it->second.is_group || it->second.value != value)) {
  253. printEntry(os, name, it->second, tab_depth);
  254. was_modified = true;
  255. } else if (it == m_settings.end()) {
  256. // Remove by skipping
  257. was_modified = true;
  258. break;
  259. } else {
  260. os << line << "\n";
  261. if (event == SPE_MULTILINE)
  262. os << value << "\n\"\"\"\n";
  263. }
  264. present_entries.insert(name);
  265. break;
  266. case SPE_GROUP:
  267. it = m_settings.find(name);
  268. if (it != m_settings.end() && it->second.is_group) {
  269. os << line << "\n";
  270. sanity_check(it->second.group != NULL);
  271. was_modified |= it->second.group->updateConfigObject(is, os, tab_depth + 1);
  272. } else if (it == m_settings.end()) {
  273. // Remove by skipping
  274. was_modified = true;
  275. Settings removed_group("}"); // Move 'is' to group end
  276. std::stringstream ss;
  277. removed_group.updateConfigObject(is, ss, tab_depth + 1);
  278. break;
  279. } else {
  280. printEntry(os, name, it->second, tab_depth);
  281. was_modified = true;
  282. }
  283. present_entries.insert(name);
  284. break;
  285. default:
  286. os << line << (is.eof() ? "" : "\n");
  287. break;
  288. }
  289. }
  290. if (!line.empty() && is.eof())
  291. os << "\n";
  292. // Add any settings in the object that don't exist in the config file yet
  293. for (it = m_settings.begin(); it != m_settings.end(); ++it) {
  294. if (present_entries.find(it->first) != present_entries.end())
  295. continue;
  296. printEntry(os, it->first, it->second, tab_depth);
  297. was_modified = true;
  298. }
  299. // Append ending tag
  300. if (!m_end_tag.empty()) {
  301. os << m_end_tag << "\n";
  302. was_modified |= !end_found;
  303. }
  304. return was_modified;
  305. }
  306. bool Settings::updateConfigFile(const char *filename)
  307. {
  308. MutexAutoLock lock(m_mutex);
  309. std::ifstream is(filename);
  310. std::ostringstream os(std::ios_base::binary);
  311. bool was_modified = updateConfigObject(is, os);
  312. is.close();
  313. if (!was_modified)
  314. return true;
  315. if (!fs::safeWriteToFile(filename, os.str())) {
  316. errorstream << "Error writing configuration file: \""
  317. << filename << "\"" << std::endl;
  318. return false;
  319. }
  320. return true;
  321. }
  322. bool Settings::parseCommandLine(int argc, char *argv[],
  323. const std::map<std::string, ValueSpec> &allowed_options)
  324. {
  325. int nonopt_index = 0;
  326. for (int i = 1; i < argc; i++) {
  327. std::string_view arg_name(argv[i]);
  328. if (arg_name.substr(0, 2) != "--") {
  329. // If option doesn't start with -, read it in as nonoptX
  330. if (arg_name[0] != '-') {
  331. std::string name = "nonopt";
  332. name += itos(nonopt_index);
  333. set(name, std::string(arg_name));
  334. nonopt_index++;
  335. continue;
  336. }
  337. errorstream << "Invalid command-line parameter \""
  338. << arg_name << "\": --<option> expected." << std::endl;
  339. return false;
  340. }
  341. std::string name(arg_name.substr(2));
  342. auto n = allowed_options.find(name);
  343. if (n == allowed_options.end()) {
  344. errorstream << "Unknown command-line parameter \""
  345. << arg_name << "\"" << std::endl;
  346. return false;
  347. }
  348. ValueType type = n->second.type;
  349. std::string value;
  350. if (type == VALUETYPE_FLAG) {
  351. value = "true";
  352. } else {
  353. if ((i + 1) >= argc) {
  354. errorstream << "Invalid command-line parameter \""
  355. << name << "\": missing value" << std::endl;
  356. return false;
  357. }
  358. value = argv[++i];
  359. }
  360. set(name, value);
  361. }
  362. return true;
  363. }
  364. /***********
  365. * Getters *
  366. ***********/
  367. Settings *Settings::getParent() const
  368. {
  369. return m_hierarchy ? m_hierarchy->getParent(m_settingslayer) : nullptr;
  370. }
  371. const SettingsEntry &Settings::getEntry(const std::string &name) const
  372. {
  373. {
  374. MutexAutoLock lock(m_mutex);
  375. SettingEntries::const_iterator n;
  376. if ((n = m_settings.find(name)) != m_settings.end())
  377. return n->second;
  378. }
  379. if (auto parent = getParent())
  380. return parent->getEntry(name);
  381. throw SettingNotFoundException("Setting [" + name + "] not found.");
  382. }
  383. Settings *Settings::getGroup(const std::string &name) const
  384. {
  385. const SettingsEntry &entry = getEntry(name);
  386. if (!entry.is_group)
  387. throw SettingNotFoundException("Setting [" + name + "] is not a group.");
  388. return entry.group;
  389. }
  390. const std::string &Settings::get(const std::string &name) const
  391. {
  392. const SettingsEntry &entry = getEntry(name);
  393. if (entry.is_group)
  394. throw SettingNotFoundException("Setting [" + name + "] is a group.");
  395. return entry.value;
  396. }
  397. bool Settings::getBool(const std::string &name) const
  398. {
  399. return is_yes(get(name));
  400. }
  401. u16 Settings::getU16(const std::string &name) const
  402. {
  403. return stoi(get(name), 0, 65535);
  404. }
  405. s16 Settings::getS16(const std::string &name) const
  406. {
  407. return stoi(get(name), -32768, 32767);
  408. }
  409. u32 Settings::getU32(const std::string &name) const
  410. {
  411. return (u32) stoi(get(name));
  412. }
  413. s32 Settings::getS32(const std::string &name) const
  414. {
  415. return stoi(get(name));
  416. }
  417. float Settings::getFloat(const std::string &name) const
  418. {
  419. return stof(get(name));
  420. }
  421. float Settings::getFloat(const std::string &name, float min, float max) const
  422. {
  423. float val = stof(get(name));
  424. return rangelim(val, min, max);
  425. }
  426. u64 Settings::getU64(const std::string &name) const
  427. {
  428. std::string s = get(name);
  429. return from_string<u64>(s);
  430. }
  431. v2f Settings::getV2F(const std::string &name) const
  432. {
  433. v2f value;
  434. Strfnd f(get(name));
  435. f.next("(");
  436. value.X = stof(f.next(","));
  437. value.Y = stof(f.next(")"));
  438. return value;
  439. }
  440. v3f Settings::getV3F(const std::string &name) const
  441. {
  442. return str_to_v3f(get(name));
  443. }
  444. u32 Settings::getFlagStr(const std::string &name, const FlagDesc *flagdesc,
  445. u32 *flagmask) const
  446. {
  447. u32 flags = 0;
  448. // Read default value (if there is any)
  449. if (auto parent = getParent())
  450. flags = parent->getFlagStr(name, flagdesc, flagmask);
  451. // Apply custom flags "on top"
  452. if (m_settings.find(name) != m_settings.end()) {
  453. std::string value = get(name);
  454. u32 flags_user;
  455. u32 mask_user = U32_MAX;
  456. flags_user = std::isdigit(value[0])
  457. ? stoi(value) // Override default
  458. : readFlagString(value, flagdesc, &mask_user);
  459. flags &= ~mask_user;
  460. flags |= flags_user;
  461. if (flagmask)
  462. *flagmask |= mask_user;
  463. }
  464. return flags;
  465. }
  466. bool Settings::getNoiseParams(const std::string &name, NoiseParams &np) const
  467. {
  468. if (getNoiseParamsFromGroup(name, np) || getNoiseParamsFromValue(name, np))
  469. return true;
  470. if (auto parent = getParent())
  471. return parent->getNoiseParams(name, np);
  472. return false;
  473. }
  474. bool Settings::getNoiseParamsFromValue(const std::string &name,
  475. NoiseParams &np) const
  476. {
  477. std::string value;
  478. if (!getNoEx(name, value))
  479. return false;
  480. // Format: f32,f32,(f32,f32,f32),s32,s32,f32[,f32]
  481. Strfnd f(value);
  482. np.offset = stof(f.next(","));
  483. np.scale = stof(f.next(","));
  484. f.next("(");
  485. np.spread.X = stof(f.next(","));
  486. np.spread.Y = stof(f.next(","));
  487. np.spread.Z = stof(f.next(")"));
  488. f.next(",");
  489. np.seed = stoi(f.next(","));
  490. np.octaves = stoi(f.next(","));
  491. np.persist = stof(f.next(","));
  492. std::string optional_params = f.next("");
  493. if (!optional_params.empty())
  494. np.lacunarity = stof(optional_params);
  495. return true;
  496. }
  497. bool Settings::getNoiseParamsFromGroup(const std::string &name,
  498. NoiseParams &np) const
  499. {
  500. Settings *group = NULL;
  501. if (!getGroupNoEx(name, group))
  502. return false;
  503. group->getFloatNoEx("offset", np.offset);
  504. group->getFloatNoEx("scale", np.scale);
  505. group->getV3FNoEx("spread", np.spread);
  506. group->getS32NoEx("seed", np.seed);
  507. group->getU16NoEx("octaves", np.octaves);
  508. group->getFloatNoEx("persistence", np.persist);
  509. group->getFloatNoEx("lacunarity", np.lacunarity);
  510. np.flags = 0;
  511. if (!group->getFlagStrNoEx("flags", np.flags, flagdesc_noiseparams))
  512. np.flags = NOISE_FLAG_DEFAULTS;
  513. return true;
  514. }
  515. bool Settings::exists(const std::string &name) const
  516. {
  517. if (existsLocal(name))
  518. return true;
  519. if (auto parent = getParent())
  520. return parent->exists(name);
  521. return false;
  522. }
  523. bool Settings::existsLocal(const std::string &name) const
  524. {
  525. MutexAutoLock lock(m_mutex);
  526. return m_settings.find(name) != m_settings.end();
  527. }
  528. std::vector<std::string> Settings::getNames() const
  529. {
  530. MutexAutoLock lock(m_mutex);
  531. std::vector<std::string> names;
  532. names.reserve(m_settings.size());
  533. for (const auto &settings_it : m_settings) {
  534. names.push_back(settings_it.first);
  535. }
  536. return names;
  537. }
  538. /***************************************
  539. * Getters that don't throw exceptions *
  540. ***************************************/
  541. bool Settings::getGroupNoEx(const std::string &name, Settings *&val) const
  542. {
  543. try {
  544. val = getGroup(name);
  545. return true;
  546. } catch (SettingNotFoundException &e) {
  547. return false;
  548. }
  549. }
  550. bool Settings::getNoEx(const std::string &name, std::string &val) const
  551. {
  552. try {
  553. val = get(name);
  554. return true;
  555. } catch (SettingNotFoundException &e) {
  556. return false;
  557. }
  558. }
  559. bool Settings::getFlag(const std::string &name) const
  560. {
  561. try {
  562. return getBool(name);
  563. } catch(SettingNotFoundException &e) {
  564. return false;
  565. }
  566. }
  567. bool Settings::getFloatNoEx(const std::string &name, float &val) const
  568. {
  569. try {
  570. val = getFloat(name);
  571. return true;
  572. } catch (SettingNotFoundException &e) {
  573. return false;
  574. }
  575. }
  576. bool Settings::getU16NoEx(const std::string &name, u16 &val) const
  577. {
  578. try {
  579. val = getU16(name);
  580. return true;
  581. } catch (SettingNotFoundException &e) {
  582. return false;
  583. }
  584. }
  585. bool Settings::getS16NoEx(const std::string &name, s16 &val) const
  586. {
  587. try {
  588. val = getS16(name);
  589. return true;
  590. } catch (SettingNotFoundException &e) {
  591. return false;
  592. }
  593. }
  594. bool Settings::getU32NoEx(const std::string &name, u32 &val) const
  595. {
  596. try {
  597. val = getU32(name);
  598. return true;
  599. } catch (SettingNotFoundException &e) {
  600. return false;
  601. }
  602. }
  603. bool Settings::getS32NoEx(const std::string &name, s32 &val) const
  604. {
  605. try {
  606. val = getS32(name);
  607. return true;
  608. } catch (SettingNotFoundException &e) {
  609. return false;
  610. }
  611. }
  612. bool Settings::getU64NoEx(const std::string &name, u64 &val) const
  613. {
  614. try {
  615. val = getU64(name);
  616. return true;
  617. } catch (SettingNotFoundException &e) {
  618. return false;
  619. }
  620. }
  621. bool Settings::getV2FNoEx(const std::string &name, v2f &val) const
  622. {
  623. try {
  624. val = getV2F(name);
  625. return true;
  626. } catch (SettingNotFoundException &e) {
  627. return false;
  628. }
  629. }
  630. bool Settings::getV3FNoEx(const std::string &name, v3f &val) const
  631. {
  632. try {
  633. val = getV3F(name);
  634. return true;
  635. } catch (SettingNotFoundException &e) {
  636. return false;
  637. }
  638. }
  639. bool Settings::getFlagStrNoEx(const std::string &name, u32 &val,
  640. const FlagDesc *flagdesc) const
  641. {
  642. if (!flagdesc) {
  643. if (!(flagdesc = getFlagDescFallback(name)))
  644. return false; // Not found
  645. }
  646. try {
  647. val = getFlagStr(name, flagdesc, nullptr);
  648. return true;
  649. } catch (SettingNotFoundException &e) {
  650. return false;
  651. }
  652. }
  653. /***********
  654. * Setters *
  655. ***********/
  656. bool Settings::setEntry(const std::string &name, const void *data,
  657. bool set_group)
  658. {
  659. if (!checkNameValid(name))
  660. return false;
  661. if (!set_group && !checkValueValid(*(const std::string *)data))
  662. return false;
  663. Settings *old_group = NULL;
  664. {
  665. MutexAutoLock lock(m_mutex);
  666. SettingsEntry &entry = m_settings[name];
  667. old_group = entry.group;
  668. entry.value = set_group ? "" : *(const std::string *)data;
  669. entry.group = set_group ? *(Settings **)data : NULL;
  670. entry.is_group = set_group;
  671. if (set_group)
  672. entry.group->m_end_tag = "}";
  673. }
  674. delete old_group;
  675. return true;
  676. }
  677. bool Settings::set(const std::string &name, const std::string &value)
  678. {
  679. if (!setEntry(name, &value, false))
  680. return false;
  681. doCallbacks(name);
  682. return true;
  683. }
  684. // TODO: Remove this function
  685. bool Settings::setDefault(const std::string &name, const std::string &value)
  686. {
  687. FATAL_ERROR_IF(m_hierarchy != &g_hierarchy, "setDefault is only valid on "
  688. "global settings");
  689. return getLayer(SL_DEFAULTS)->set(name, value);
  690. }
  691. bool Settings::setGroup(const std::string &name, const Settings &group)
  692. {
  693. // Settings must own the group pointer
  694. // avoid double-free by copying the source
  695. Settings *copy = new Settings();
  696. *copy = group;
  697. return setEntry(name, &copy, true);
  698. }
  699. bool Settings::setBool(const std::string &name, bool value)
  700. {
  701. return set(name, value ? "true" : "false");
  702. }
  703. bool Settings::setS16(const std::string &name, s16 value)
  704. {
  705. return set(name, itos(value));
  706. }
  707. bool Settings::setU16(const std::string &name, u16 value)
  708. {
  709. return set(name, itos(value));
  710. }
  711. bool Settings::setS32(const std::string &name, s32 value)
  712. {
  713. return set(name, itos(value));
  714. }
  715. bool Settings::setU64(const std::string &name, u64 value)
  716. {
  717. std::ostringstream os;
  718. os << value;
  719. return set(name, os.str());
  720. }
  721. bool Settings::setFloat(const std::string &name, float value)
  722. {
  723. return set(name, ftos(value));
  724. }
  725. bool Settings::setV2F(const std::string &name, v2f value)
  726. {
  727. std::ostringstream os;
  728. os << "(" << value.X << "," << value.Y << ")";
  729. return set(name, os.str());
  730. }
  731. bool Settings::setV3F(const std::string &name, v3f value)
  732. {
  733. std::ostringstream os;
  734. os << "(" << value.X << "," << value.Y << "," << value.Z << ")";
  735. return set(name, os.str());
  736. }
  737. bool Settings::setFlagStr(const std::string &name, u32 flags,
  738. const FlagDesc *flagdesc, u32 flagmask)
  739. {
  740. if (!flagdesc) {
  741. if (!(flagdesc = getFlagDescFallback(name)))
  742. return false; // Not found
  743. }
  744. return set(name, writeFlagString(flags, flagdesc, flagmask));
  745. }
  746. bool Settings::setNoiseParams(const std::string &name, const NoiseParams &np)
  747. {
  748. Settings *group = new Settings;
  749. group->setFloat("offset", np.offset);
  750. group->setFloat("scale", np.scale);
  751. group->setV3F("spread", np.spread);
  752. group->setS32("seed", np.seed);
  753. group->setU16("octaves", np.octaves);
  754. group->setFloat("persistence", np.persist);
  755. group->setFloat("lacunarity", np.lacunarity);
  756. group->setFlagStr("flags", np.flags, flagdesc_noiseparams, np.flags);
  757. return setEntry(name, &group, true);
  758. }
  759. bool Settings::remove(const std::string &name)
  760. {
  761. // Lock as short as possible, unlock before doCallbacks()
  762. m_mutex.lock();
  763. SettingEntries::iterator it = m_settings.find(name);
  764. if (it != m_settings.end()) {
  765. delete it->second.group;
  766. m_settings.erase(it);
  767. m_mutex.unlock();
  768. doCallbacks(name);
  769. return true;
  770. }
  771. m_mutex.unlock();
  772. return false;
  773. }
  774. SettingsParseEvent Settings::parseConfigObject(const std::string &line,
  775. std::string &name, std::string &value)
  776. {
  777. auto trimmed_line = trim(line);
  778. if (trimmed_line.empty())
  779. return SPE_NONE;
  780. if (trimmed_line[0] == '#')
  781. return SPE_COMMENT;
  782. if (trimmed_line == m_end_tag)
  783. return SPE_END;
  784. size_t pos = trimmed_line.find('=');
  785. if (pos == std::string::npos)
  786. return SPE_INVALID;
  787. name = trim(trimmed_line.substr(0, pos));
  788. value = trim(trimmed_line.substr(pos + 1));
  789. if (value == "{")
  790. return SPE_GROUP;
  791. if (value == "\"\"\"")
  792. return SPE_MULTILINE;
  793. return SPE_KVPAIR;
  794. }
  795. void Settings::clearNoLock()
  796. {
  797. for (SettingEntries::const_iterator it = m_settings.begin();
  798. it != m_settings.end(); ++it)
  799. delete it->second.group;
  800. m_settings.clear();
  801. }
  802. void Settings::setDefault(const std::string &name, const FlagDesc *flagdesc,
  803. u32 flags)
  804. {
  805. s_flags[name] = flagdesc;
  806. setDefault(name, writeFlagString(flags, flagdesc, U32_MAX));
  807. }
  808. const FlagDesc *Settings::getFlagDescFallback(const std::string &name) const
  809. {
  810. auto it = s_flags.find(name);
  811. return it == s_flags.end() ? nullptr : it->second;
  812. }
  813. void Settings::registerChangedCallback(const std::string &name,
  814. SettingsChangedCallback cbf, void *userdata)
  815. {
  816. MutexAutoLock lock(m_callback_mutex);
  817. m_callbacks[name].emplace_back(cbf, userdata);
  818. }
  819. void Settings::deregisterChangedCallback(const std::string &name,
  820. SettingsChangedCallback cbf, void *userdata)
  821. {
  822. MutexAutoLock lock(m_callback_mutex);
  823. SettingsCallbackMap::iterator it_cbks = m_callbacks.find(name);
  824. if (it_cbks != m_callbacks.end()) {
  825. SettingsCallbackList &cbks = it_cbks->second;
  826. SettingsCallbackList::iterator position =
  827. std::find(cbks.begin(), cbks.end(), std::make_pair(cbf, userdata));
  828. if (position != cbks.end())
  829. cbks.erase(position);
  830. }
  831. }
  832. void Settings::removeSecureSettings()
  833. {
  834. for (const auto &name : getNames()) {
  835. if (name.compare(0, 7, "secure.") != 0)
  836. continue;
  837. errorstream << "Secure setting " << name
  838. << " isn't allowed, so was ignored."
  839. << std::endl;
  840. remove(name);
  841. }
  842. }
  843. void Settings::doCallbacks(const std::string &name) const
  844. {
  845. MutexAutoLock lock(m_callback_mutex);
  846. SettingsCallbackMap::const_iterator it_cbks = m_callbacks.find(name);
  847. if (it_cbks != m_callbacks.end()) {
  848. SettingsCallbackList::const_iterator it;
  849. for (it = it_cbks->second.begin(); it != it_cbks->second.end(); ++it)
  850. (it->first)(name, it->second);
  851. }
  852. }