profile.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. // SuperTux
  2. // Copyright (C) 2023 Vankata453
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. #include "supertux/profile.hpp"
  17. #include <physfs.h>
  18. #include <sstream>
  19. #include "physfs/util.hpp"
  20. #include "util/log.hpp"
  21. #include "util/reader.hpp"
  22. #include "util/reader_document.hpp"
  23. #include "util/reader_mapping.hpp"
  24. #include "util/writer.hpp"
  25. Profile::Profile(int id) :
  26. m_id(id),
  27. m_name(),
  28. m_last_world()
  29. {
  30. const std::string info_file = get_basedir() + "/info";
  31. try
  32. {
  33. auto doc = ReaderDocument::from_file(info_file);
  34. auto root = doc.get_root();
  35. if (root.get_name() != "supertux-profile")
  36. {
  37. throw std::runtime_error("File is not a 'supertux-profile' file.");
  38. }
  39. auto reader = root.get_mapping();
  40. reader.get("name", m_name);
  41. reader.get("last-world", m_last_world);
  42. }
  43. catch (const std::exception& err)
  44. {
  45. log_info << "Failed to load profile info from '" << info_file << "': " << err.what() << std::endl;
  46. save();
  47. }
  48. }
  49. void
  50. Profile::save()
  51. {
  52. create_basedir();
  53. Writer writer(get_basedir() + "/info");
  54. writer.start_list("supertux-profile");
  55. writer.write("name", m_name);
  56. writer.write("last-world", m_last_world);
  57. writer.end_list("supertux-profile");
  58. }
  59. void
  60. Profile::reset()
  61. {
  62. m_last_world.clear();
  63. save();
  64. }
  65. void
  66. Profile::create_basedir()
  67. {
  68. const std::string basedir = get_basedir();
  69. if (!PHYSFS_exists(basedir.c_str()) && !PHYSFS_mkdir(basedir.c_str()))
  70. {
  71. std::ostringstream msg;
  72. msg << "Couldn't create directory '" << basedir << "' for profile " << m_id << ":"
  73. << physfsutil::get_last_error();
  74. throw std::runtime_error(msg.str());
  75. }
  76. }
  77. std::string
  78. Profile::get_basedir() const
  79. {
  80. return "profile" + std::to_string(m_id);
  81. }
  82. /* EOF */