settings.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  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. #ifndef SETTINGS_HEADER
  17. #define SETTINGS_HEADER
  18. #include "irrlichttypes_bloated.h"
  19. #include "exceptions.h"
  20. #include <string>
  21. #include "jthread/jmutex.h"
  22. #include "jthread/jmutexautolock.h"
  23. #include "strfnd.h"
  24. #include <iostream>
  25. #include <fstream>
  26. #include <sstream>
  27. #include "debug.h"
  28. #include "log.h"
  29. #include "util/string.h"
  30. #include "util/serialize.h"
  31. #include <list>
  32. #include <map>
  33. #include <set>
  34. #include "filesys.h"
  35. #include <cctype>
  36. enum ValueType
  37. {
  38. VALUETYPE_STRING,
  39. VALUETYPE_FLAG // Doesn't take any arguments
  40. };
  41. struct ValueSpec
  42. {
  43. ValueSpec(ValueType a_type, const char *a_help=NULL)
  44. {
  45. type = a_type;
  46. help = a_help;
  47. }
  48. ValueType type;
  49. const char *help;
  50. };
  51. class Settings
  52. {
  53. public:
  54. Settings()
  55. {
  56. }
  57. void writeLines(std::ostream &os)
  58. {
  59. JMutexAutoLock lock(m_mutex);
  60. for(std::map<std::string, std::string>::iterator
  61. i = m_settings.begin();
  62. i != m_settings.end(); ++i)
  63. {
  64. std::string name = i->first;
  65. std::string value = i->second;
  66. os<<name<<" = "<<value<<"\n";
  67. }
  68. }
  69. // return all keys used
  70. std::vector<std::string> getNames(){
  71. std::vector<std::string> names;
  72. for(std::map<std::string, std::string>::iterator
  73. i = m_settings.begin();
  74. i != m_settings.end(); ++i)
  75. {
  76. names.push_back(i->first);
  77. }
  78. return names;
  79. }
  80. // remove a setting
  81. bool remove(const std::string& name)
  82. {
  83. return m_settings.erase(name);
  84. }
  85. bool parseConfigLine(const std::string &line)
  86. {
  87. JMutexAutoLock lock(m_mutex);
  88. std::string trimmedline = trim(line);
  89. // Ignore empty lines and comments
  90. if(trimmedline.size() == 0 || trimmedline[0] == '#')
  91. return true;
  92. //infostream<<"trimmedline=\""<<trimmedline<<"\""<<std::endl;
  93. Strfnd sf(trim(line));
  94. std::string name = sf.next("=");
  95. name = trim(name);
  96. if(name == "")
  97. return true;
  98. std::string value = sf.next("\n");
  99. value = trim(value);
  100. /*infostream<<"Config name=\""<<name<<"\" value=\""
  101. <<value<<"\""<<std::endl;*/
  102. m_settings[name] = value;
  103. return true;
  104. }
  105. void parseConfigLines(std::istream &is, const std::string &endstring)
  106. {
  107. for(;;){
  108. if(is.eof())
  109. break;
  110. std::string line;
  111. std::getline(is, line);
  112. std::string trimmedline = trim(line);
  113. if(endstring != ""){
  114. if(trimmedline == endstring)
  115. break;
  116. }
  117. parseConfigLine(line);
  118. }
  119. }
  120. // Returns false on EOF
  121. bool parseConfigObject(std::istream &is)
  122. {
  123. if(is.eof())
  124. return false;
  125. /*
  126. NOTE: This function might be expanded to allow multi-line
  127. settings.
  128. */
  129. std::string line;
  130. std::getline(is, line);
  131. //infostream<<"got line: \""<<line<<"\""<<std::endl;
  132. return parseConfigLine(line);
  133. }
  134. /*
  135. Read configuration file
  136. Returns true on success
  137. */
  138. bool readConfigFile(const char *filename)
  139. {
  140. std::ifstream is(filename);
  141. if(is.good() == false)
  142. return false;
  143. /*infostream<<"Parsing configuration file: \""
  144. <<filename<<"\""<<std::endl;*/
  145. while(parseConfigObject(is));
  146. return true;
  147. }
  148. /*
  149. Reads a configuration object from stream (usually a single line)
  150. and adds it to dst.
  151. Preserves comments and empty lines.
  152. Settings that were added to dst are also added to updated.
  153. key of updated is setting name, value of updated is dummy.
  154. Returns false on EOF
  155. */
  156. bool getUpdatedConfigObject(std::istream &is,
  157. std::list<std::string> &dst,
  158. std::set<std::string> &updated,
  159. bool &value_changed)
  160. {
  161. JMutexAutoLock lock(m_mutex);
  162. if(is.eof())
  163. return false;
  164. // NOTE: This function will be expanded to allow multi-line settings
  165. std::string line;
  166. std::getline(is, line);
  167. std::string trimmedline = trim(line);
  168. std::string line_end = "";
  169. if(is.eof() == false)
  170. line_end = "\n";
  171. // Ignore empty lines and comments
  172. if(trimmedline.size() == 0 || trimmedline[0] == '#')
  173. {
  174. dst.push_back(line+line_end);
  175. return true;
  176. }
  177. Strfnd sf(trim(line));
  178. std::string name = sf.next("=");
  179. name = trim(name);
  180. if(name == "")
  181. {
  182. dst.push_back(line+line_end);
  183. return true;
  184. }
  185. std::string value = sf.next("\n");
  186. value = trim(value);
  187. if(m_settings.find(name) != m_settings.end())
  188. {
  189. std::string newvalue = m_settings[name];
  190. if(newvalue != value)
  191. {
  192. infostream<<"Changing value of \""<<name<<"\" = \""
  193. <<value<<"\" -> \""<<newvalue<<"\""
  194. <<std::endl;
  195. value_changed = true;
  196. }
  197. dst.push_back(name + " = " + newvalue + line_end);
  198. updated.insert(name);
  199. }
  200. else //file contains a setting which is not in m_settings
  201. value_changed=true;
  202. return true;
  203. }
  204. /*
  205. Updates configuration file
  206. Returns true on success
  207. */
  208. bool updateConfigFile(const char *filename)
  209. {
  210. infostream<<"Updating configuration file: \""
  211. <<filename<<"\""<<std::endl;
  212. std::list<std::string> objects;
  213. std::set<std::string> updated;
  214. bool something_actually_changed = false;
  215. // Read and modify stuff
  216. {
  217. std::ifstream is(filename);
  218. if(is.good() == false)
  219. {
  220. infostream<<"updateConfigFile():"
  221. " Error opening configuration file"
  222. " for reading: \""
  223. <<filename<<"\""<<std::endl;
  224. }
  225. else
  226. {
  227. while(getUpdatedConfigObject(is, objects, updated,
  228. something_actually_changed));
  229. }
  230. }
  231. JMutexAutoLock lock(m_mutex);
  232. // If something not yet determined to have been changed, check if
  233. // any new stuff was added
  234. if(!something_actually_changed){
  235. for(std::map<std::string, std::string>::iterator
  236. i = m_settings.begin();
  237. i != m_settings.end(); ++i)
  238. {
  239. if(updated.find(i->first) != updated.end())
  240. continue;
  241. something_actually_changed = true;
  242. break;
  243. }
  244. }
  245. // If nothing was actually changed, skip writing the file
  246. if(!something_actually_changed){
  247. infostream<<"Skipping writing of "<<filename
  248. <<" because content wouldn't be modified"<<std::endl;
  249. return true;
  250. }
  251. // Write stuff back
  252. {
  253. std::ostringstream ss(std::ios_base::binary);
  254. /*
  255. Write updated stuff
  256. */
  257. for(std::list<std::string>::iterator
  258. i = objects.begin();
  259. i != objects.end(); ++i)
  260. {
  261. ss<<(*i);
  262. }
  263. /*
  264. Write stuff that was not already in the file
  265. */
  266. for(std::map<std::string, std::string>::iterator
  267. i = m_settings.begin();
  268. i != m_settings.end(); ++i)
  269. {
  270. if(updated.find(i->first) != updated.end())
  271. continue;
  272. std::string name = i->first;
  273. std::string value = i->second;
  274. infostream<<"Adding \""<<name<<"\" = \""<<value<<"\""
  275. <<std::endl;
  276. ss<<name<<" = "<<value<<"\n";
  277. }
  278. if(!fs::safeWriteToFile(filename, ss.str()))
  279. {
  280. errorstream<<"Error writing configuration file: \""
  281. <<filename<<"\""<<std::endl;
  282. return false;
  283. }
  284. }
  285. return true;
  286. }
  287. /*
  288. NOTE: Types of allowed_options are ignored
  289. returns true on success
  290. */
  291. bool parseCommandLine(int argc, char *argv[],
  292. std::map<std::string, ValueSpec> &allowed_options)
  293. {
  294. int nonopt_index = 0;
  295. int i=1;
  296. for(;;)
  297. {
  298. if(i >= argc)
  299. break;
  300. std::string argname = argv[i];
  301. if(argname.substr(0, 2) != "--")
  302. {
  303. // If option doesn't start with -, read it in as nonoptX
  304. if(argname[0] != '-'){
  305. std::string name = "nonopt";
  306. name += itos(nonopt_index);
  307. set(name, argname);
  308. nonopt_index++;
  309. i++;
  310. continue;
  311. }
  312. errorstream<<"Invalid command-line parameter \""
  313. <<argname<<"\": --<option> expected."<<std::endl;
  314. return false;
  315. }
  316. i++;
  317. std::string name = argname.substr(2);
  318. std::map<std::string, ValueSpec>::iterator n;
  319. n = allowed_options.find(name);
  320. if(n == allowed_options.end())
  321. {
  322. errorstream<<"Unknown command-line parameter \""
  323. <<argname<<"\""<<std::endl;
  324. return false;
  325. }
  326. ValueType type = n->second.type;
  327. std::string value = "";
  328. if(type == VALUETYPE_FLAG)
  329. {
  330. value = "true";
  331. }
  332. else
  333. {
  334. if(i >= argc)
  335. {
  336. errorstream<<"Invalid command-line parameter \""
  337. <<name<<"\": missing value"<<std::endl;
  338. return false;
  339. }
  340. value = argv[i];
  341. i++;
  342. }
  343. infostream<<"Valid command-line parameter: \""
  344. <<name<<"\" = \""<<value<<"\""
  345. <<std::endl;
  346. set(name, value);
  347. }
  348. return true;
  349. }
  350. void set(std::string name, std::string value)
  351. {
  352. JMutexAutoLock lock(m_mutex);
  353. m_settings[name] = value;
  354. }
  355. void set(std::string name, const char *value)
  356. {
  357. JMutexAutoLock lock(m_mutex);
  358. m_settings[name] = value;
  359. }
  360. void setDefault(std::string name, std::string value)
  361. {
  362. JMutexAutoLock lock(m_mutex);
  363. m_defaults[name] = value;
  364. }
  365. bool exists(std::string name)
  366. {
  367. JMutexAutoLock lock(m_mutex);
  368. return (m_settings.find(name) != m_settings.end() || m_defaults.find(name) != m_defaults.end());
  369. }
  370. std::string get(std::string name)
  371. {
  372. JMutexAutoLock lock(m_mutex);
  373. std::map<std::string, std::string>::iterator n;
  374. n = m_settings.find(name);
  375. if(n == m_settings.end())
  376. {
  377. n = m_defaults.find(name);
  378. if(n == m_defaults.end())
  379. {
  380. throw SettingNotFoundException(("Setting [" + name + "] not found ").c_str());
  381. }
  382. }
  383. return n->second;
  384. }
  385. //////////// Get setting
  386. bool getBool(std::string name)
  387. {
  388. return is_yes(get(name));
  389. }
  390. bool getFlag(std::string name)
  391. {
  392. try
  393. {
  394. return getBool(name);
  395. }
  396. catch(SettingNotFoundException &e)
  397. {
  398. return false;
  399. }
  400. }
  401. // Asks if empty
  402. bool getBoolAsk(std::string name, std::string question, bool def)
  403. {
  404. // If it is in settings
  405. if(exists(name))
  406. return getBool(name);
  407. std::string s;
  408. char templine[10];
  409. std::cout<<question<<" [y/N]: ";
  410. std::cin.getline(templine, 10);
  411. s = templine;
  412. if(s == "")
  413. return def;
  414. return is_yes(s);
  415. }
  416. float getFloat(std::string name)
  417. {
  418. return stof(get(name));
  419. }
  420. u16 getU16(std::string name)
  421. {
  422. return stoi(get(name), 0, 65535);
  423. }
  424. u16 getU16Ask(std::string name, std::string question, u16 def)
  425. {
  426. // If it is in settings
  427. if(exists(name))
  428. return getU16(name);
  429. std::string s;
  430. char templine[10];
  431. std::cout<<question<<" ["<<def<<"]: ";
  432. std::cin.getline(templine, 10);
  433. s = templine;
  434. if(s == "")
  435. return def;
  436. return stoi(s, 0, 65535);
  437. }
  438. s16 getS16(std::string name)
  439. {
  440. return stoi(get(name), -32768, 32767);
  441. }
  442. s32 getS32(std::string name)
  443. {
  444. return stoi(get(name));
  445. }
  446. v3f getV3F(std::string name)
  447. {
  448. v3f value;
  449. Strfnd f(get(name));
  450. f.next("(");
  451. value.X = stof(f.next(","));
  452. value.Y = stof(f.next(","));
  453. value.Z = stof(f.next(")"));
  454. return value;
  455. }
  456. v2f getV2F(std::string name)
  457. {
  458. v2f value;
  459. Strfnd f(get(name));
  460. f.next("(");
  461. value.X = stof(f.next(","));
  462. value.Y = stof(f.next(")"));
  463. return value;
  464. }
  465. u64 getU64(std::string name)
  466. {
  467. u64 value = 0;
  468. std::string s = get(name);
  469. std::istringstream ss(s);
  470. ss>>value;
  471. return value;
  472. }
  473. u32 getFlagStr(std::string name, FlagDesc *flagdesc, u32 *flagmask)
  474. {
  475. std::string val = get(name);
  476. return (std::isdigit(val[0])) ? stoi(val) :
  477. readFlagString(val, flagdesc, flagmask);
  478. }
  479. // N.B. if getStruct() is used to read a non-POD aggregate type,
  480. // the behavior is undefined.
  481. bool getStruct(std::string name, std::string format, void *out, size_t olen)
  482. {
  483. std::string valstr;
  484. try {
  485. valstr = get(name);
  486. } catch (SettingNotFoundException &e) {
  487. return false;
  488. }
  489. if (!deSerializeStringToStruct(valstr, format, out, olen))
  490. return false;
  491. return true;
  492. }
  493. //////////// Try to get value, no exception thrown
  494. bool getNoEx(std::string name, std::string &val)
  495. {
  496. try {
  497. val = get(name);
  498. return true;
  499. } catch (SettingNotFoundException &e) {
  500. return false;
  501. }
  502. }
  503. // N.B. getFlagStrNoEx() does not set val, but merely modifies it. Thus,
  504. // val must be initialized before using getFlagStrNoEx(). The intention of
  505. // this is to simplify modifying a flags field from a default value.
  506. bool getFlagStrNoEx(std::string name, u32 &val, FlagDesc *flagdesc)
  507. {
  508. try {
  509. u32 flags, flagmask;
  510. flags = getFlagStr(name, flagdesc, &flagmask);
  511. val &= ~flagmask;
  512. val |= flags;
  513. return true;
  514. } catch (SettingNotFoundException &e) {
  515. return false;
  516. }
  517. }
  518. bool getFloatNoEx(std::string name, float &val)
  519. {
  520. try {
  521. val = getFloat(name);
  522. return true;
  523. } catch (SettingNotFoundException &e) {
  524. return false;
  525. }
  526. }
  527. bool getU16NoEx(std::string name, int &val)
  528. {
  529. try {
  530. val = getU16(name);
  531. return true;
  532. } catch (SettingNotFoundException &e) {
  533. return false;
  534. }
  535. }
  536. bool getU16NoEx(std::string name, u16 &val)
  537. {
  538. try {
  539. val = getU16(name);
  540. return true;
  541. } catch (SettingNotFoundException &e) {
  542. return false;
  543. }
  544. }
  545. bool getS16NoEx(std::string name, int &val)
  546. {
  547. try {
  548. val = getU16(name);
  549. return true;
  550. } catch (SettingNotFoundException &e) {
  551. return false;
  552. }
  553. }
  554. bool getS16NoEx(std::string name, s16 &val)
  555. {
  556. try {
  557. val = getS16(name);
  558. return true;
  559. } catch (SettingNotFoundException &e) {
  560. return false;
  561. }
  562. }
  563. bool getS32NoEx(std::string name, s32 &val)
  564. {
  565. try {
  566. val = getS32(name);
  567. return true;
  568. } catch (SettingNotFoundException &e) {
  569. return false;
  570. }
  571. }
  572. bool getV3FNoEx(std::string name, v3f &val)
  573. {
  574. try {
  575. val = getV3F(name);
  576. return true;
  577. } catch (SettingNotFoundException &e) {
  578. return false;
  579. }
  580. }
  581. bool getV2FNoEx(std::string name, v2f &val)
  582. {
  583. try {
  584. val = getV2F(name);
  585. return true;
  586. } catch (SettingNotFoundException &e) {
  587. return false;
  588. }
  589. }
  590. bool getU64NoEx(std::string name, u64 &val)
  591. {
  592. try {
  593. val = getU64(name);
  594. return true;
  595. } catch (SettingNotFoundException &e) {
  596. return false;
  597. }
  598. }
  599. //////////// Set setting
  600. // N.B. if setStruct() is used to write a non-POD aggregate type,
  601. // the behavior is undefined.
  602. bool setStruct(std::string name, std::string format, void *value)
  603. {
  604. std::string structstr;
  605. if (!serializeStructToString(&structstr, format, value))
  606. return false;
  607. set(name, structstr);
  608. return true;
  609. }
  610. void setFlagStr(std::string name, u32 flags,
  611. FlagDesc *flagdesc, u32 flagmask)
  612. {
  613. set(name, writeFlagString(flags, flagdesc, flagmask));
  614. }
  615. void setBool(std::string name, bool value)
  616. {
  617. if(value)
  618. set(name, "true");
  619. else
  620. set(name, "false");
  621. }
  622. void setFloat(std::string name, float value)
  623. {
  624. set(name, ftos(value));
  625. }
  626. void setV3F(std::string name, v3f value)
  627. {
  628. std::ostringstream os;
  629. os<<"("<<value.X<<","<<value.Y<<","<<value.Z<<")";
  630. set(name, os.str());
  631. }
  632. void setV2F(std::string name, v2f value)
  633. {
  634. std::ostringstream os;
  635. os<<"("<<value.X<<","<<value.Y<<")";
  636. set(name, os.str());
  637. }
  638. void setS16(std::string name, s16 value)
  639. {
  640. set(name, itos(value));
  641. }
  642. void setS32(std::string name, s32 value)
  643. {
  644. set(name, itos(value));
  645. }
  646. void setU64(std::string name, u64 value)
  647. {
  648. std::ostringstream os;
  649. os<<value;
  650. set(name, os.str());
  651. }
  652. void clear()
  653. {
  654. JMutexAutoLock lock(m_mutex);
  655. m_settings.clear();
  656. m_defaults.clear();
  657. }
  658. void updateValue(Settings &other, const std::string &name)
  659. {
  660. JMutexAutoLock lock(m_mutex);
  661. if(&other == this)
  662. return;
  663. try{
  664. std::string val = other.get(name);
  665. m_settings[name] = val;
  666. } catch(SettingNotFoundException &e){
  667. }
  668. return;
  669. }
  670. void update(Settings &other)
  671. {
  672. JMutexAutoLock lock(m_mutex);
  673. JMutexAutoLock lock2(other.m_mutex);
  674. if(&other == this)
  675. return;
  676. m_settings.insert(other.m_settings.begin(), other.m_settings.end());
  677. m_defaults.insert(other.m_defaults.begin(), other.m_defaults.end());
  678. return;
  679. }
  680. Settings & operator+=(Settings &other)
  681. {
  682. JMutexAutoLock lock(m_mutex);
  683. JMutexAutoLock lock2(other.m_mutex);
  684. if(&other == this)
  685. return *this;
  686. update(other);
  687. return *this;
  688. }
  689. Settings & operator=(Settings &other)
  690. {
  691. JMutexAutoLock lock(m_mutex);
  692. JMutexAutoLock lock2(other.m_mutex);
  693. if(&other == this)
  694. return *this;
  695. clear();
  696. (*this) += other;
  697. return *this;
  698. }
  699. private:
  700. std::map<std::string, std::string> m_settings;
  701. std::map<std::string, std::string> m_defaults;
  702. // All methods that access m_settings/m_defaults directly should lock this.
  703. JMutex m_mutex;
  704. };
  705. #endif