/// @file /// @brief Task3: Simple SVG-Writer #pragma once #include "task2.Element.hpp" // task2::Element #include // std::filesystem::path #include // std::ofstream #include // std::endl #include // std::vector namespace task2 { /// @brief Simple SVG-Writer using the task2::Element interface class Image { public: /// @brief Constructs an Image from a root SVG element /// @param root Pointer to a dynamically allocated element /// - ownership of the dynamic resource (pointer) is transfered to the class instance Image(Element* root) : root(root), elements() {} /// @brief Adds a SVG element inside the root element /// @param elem Pointer to a dynamically allocated element /// - ownership of the dynamic resource (pointer) is transfered to the class instance void add(Element* elem) { elements.push_back(elem); } /// @brief Writes the Image to a file /// @param filepath Filename of the image to be written void save(std::filesystem::path filepath) const { std::ofstream fs; fs.exceptions(std::ifstream::badbit); fs.open(filepath); fs << root->open() << std::endl; if (!root->text().empty()) fs << root->text() << std::endl; for (const auto& e : elements) { fs << " " << e->open() << std::endl; if (!e->text().empty()) fs << " " << e->text() << std::endl; if (!e->close().empty()) fs << " " << e->close() << std::endl; } if (!root->close().empty()) fs << root->close() << std::endl; } /// @brief Destructor /// @note Deallocates all dynamic resources owned by this instance ~Image() { for (auto& e : elements) delete e; delete root; } private: Element* root; ///< root element containing all other elements std::vector elements; ///< sequence of elements }; } // namespace task2