settings.cpp 23 KB

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