TU-Programmieren_2/exercise6/task3.ImageUP.hpp
2025-04-09 10:22:44 +02:00

54 lines
1.6 KiB
C++

#pragma once
#include "task2.Element.hpp" // task2::Element
#include <filesystem> // std::filesystem::path
#include <fstream> // std::ofstream
#include <memory> // std::unique_ptr
#include <ostream> // std::endl
#include <utility> // std::move
#include <vector> // 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 the root element
Image(std::unique_ptr<Element> root) : root(std::move(root)), elements() {}
/// @brief Adds a SVG element inside the root element
/// @param elem Pointer to the element
void add(std::unique_ptr<Element> elem) { elements.emplace_back(std::move(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;
}
private:
std::unique_ptr<Element> root; ///< root element containing all other elements
std::vector<std::unique_ptr<Element>> elements; ///< sequence of elements
};
} // namespace task2