MayaFlux 1.0.0
Digital-First Multimedia Processing Framework
Loading...
Searching...
No Matches
XmlWriter.cpp
Go to the documentation of this file.
1#include "XmlWriter.hpp"
2
4
5#include <pugixml.hpp>
6
7#include <cctype>
8#include <fstream>
9
10namespace MayaFlux::IO {
11
13 pugi::xml_document document;
14 std::vector<pugi::xml_node> nodes;
15};
16
17namespace {
18
19 std::string extension_of(const std::string& filepath)
20 {
21 auto extension = std::filesystem::path(filepath).extension().string();
22 std::ranges::transform(extension, extension.begin(),
23 [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
24 return extension;
25 }
26
27 bool valid_name(std::string_view name)
28 {
29 if (name.empty())
30 return false;
31
32 const auto first = static_cast<unsigned char>(name.front());
33 const bool valid_first = std::isalpha(first) || first == '_'
34 || first == ':' || first >= 0x80;
35
36 return valid_first && std::ranges::all_of(name, [](unsigned char c) {
37 return std::isalnum(c) || c == '_' || c == ':'
38 || c == '-' || c == '.' || c >= 0x80;
39 });
40 }
41
42 bool valid_xml_value(std::string_view value)
43 {
44 return std::ranges::all_of(value, [](unsigned char c) {
45 return c >= 0x20 || c == '\t' || c == '\n' || c == '\r';
46 });
47 }
48
49 std::optional<pugi::xml_node_type> type_of(std::string_view kind)
50 {
51 if (kind == "element")
52 return pugi::node_element;
53
54 if (kind == "text")
55 return pugi::node_pcdata;
56
57 if (kind == "cdata")
58 return pugi::node_cdata;
59
60 if (kind == "comment")
61 return pugi::node_comment;
62
63 if (kind == "pi")
64 return pugi::node_pi;
65
66 if (kind == "declaration")
67 return pugi::node_declaration;
68
69 if (kind == "doctype")
70 return pugi::node_doctype;
71
72 return std::nullopt;
73 }
74
75}
76
77XmlWriter::XmlWriter() = default;
78
80{
81 if (m_open)
82 close();
83}
84
85bool XmlWriter::can_write(const std::string& filepath) const
86{
87 return extension_of(filepath) == ".xml";
88}
89
91 const std::string& filepath, const Kakshya::CompositeLayout& layout)
92{
93 if (m_open) {
94 m_last_error = "Close the current XML document before opening another";
95 return false;
96 }
97
98 m_last_error.clear();
99 if (!can_write(filepath)) {
100 m_last_error = "Expected an .xml output path";
101 return false;
102 }
103
104 if (!layout.same_structure(xml_composite_layout())) {
105 m_last_error = "XML output requires xml_composite_layout()";
106 return false;
107 }
108
109 m_xml = std::make_unique<Impl>();
110 m_content_started.clear();
111 m_ancestors.clear();
112 m_filepath = resolve_write_path(filepath);
113
114 std::ofstream output(m_filepath, std::ios::binary | std::ios::trunc);
115 if (!output) {
116 m_last_error = "Cannot open XML output";
117 return false;
118 }
119
120 output.close();
121 if (!output) {
122 m_last_error = "Cannot initialize XML output";
123 return false;
124 }
125
126 m_failed = false;
127 m_declaration_seen = false;
128 m_doctype_seen = false;
129 m_root_count = 0;
130 m_open = true;
131
132 return true;
133}
134
136{
137 if (!m_open) {
138 m_last_error = "No writable XML document is open";
139 return false;
140 }
141
142 if (m_failed)
143 return false;
144
146 m_last_error = "Composite slice layout differs from the XML layout";
147 m_failed = true;
148 return false;
149 }
150
151 for (size_t i = 0; i < rows.size(); ++i) {
152 const auto row = rows.at(i);
153 if (!row || !write_row(*row)) {
154 if (m_last_error.empty())
155 m_last_error = "Could not access XML row";
156
157 m_failed = true;
158 return false;
159 }
160 }
161
162 m_last_error.clear();
163 return true;
164}
165
167{
168 const auto kind = row.text("kind");
169 const auto name = row.text("name");
170 const auto value = row.text("value");
171 const auto parent = row.get<uint64_t>("parent");
172 const auto index = static_cast<uint64_t>(m_xml->nodes.size());
173
174 if (!kind) {
175 m_last_error = "XML row is missing its kind";
176 return false;
177 }
178
179 if (*kind == "attribute") {
180 if (!parent || *parent >= index
181 || !name || !valid_name(*name)
182 || !value || !valid_xml_value(*value)
183 || m_ancestors.empty()
184 || m_ancestors.back() != *parent
185 || m_content_started[*parent]) {
186 m_last_error = "XML attribute requires an open parent and must precede its content";
187 return false;
188 }
189
190 auto owner = m_xml->nodes[*parent];
191 if (owner.type() != pugi::node_element
192 && owner.type() != pugi::node_declaration) {
193 m_last_error = "XML attribute parent must be an element or declaration";
194 return false;
195 }
196
197 if (owner.attribute(std::string(*name).c_str())) {
198 m_last_error = "XML attribute names must be unique within an element";
199 return false;
200 }
201
202 auto attribute = owner.append_attribute(std::string(*name).c_str());
203 const std::string output_value =
204 owner.type() == pugi::node_declaration && *name == "encoding"
205 ? "UTF-8"
206 : std::string(*value);
207
208 if (!attribute || !attribute.set_value(output_value.c_str())) {
209 m_last_error = "Could not append XML attribute";
210 return false;
211 }
212
213 m_xml->nodes.emplace_back();
214 m_content_started.push_back(false);
215
216 return true;
217 }
218
219 const auto type = type_of(*kind);
220 if (!type) {
221 m_last_error = "Unsupported XML node kind";
222 return false;
223 }
224
225 pugi::xml_node owner = m_xml->document.root();
226 if (parent) {
227 if (*parent >= index) {
228 m_last_error = "XML parent index must precede its child";
229 return false;
230 }
231
232 while (!m_ancestors.empty() && m_ancestors.back() != *parent)
233 m_ancestors.pop_back();
234
235 if (m_ancestors.empty() || m_xml->nodes[*parent].type() != pugi::node_element) {
236 m_last_error = "XML parent must be an open ancestor element";
237 return false;
238 }
239
240 owner = m_xml->nodes[*parent];
241 m_content_started[*parent] = true;
242
243 if (*type == pugi::node_declaration || *type == pugi::node_doctype) {
244 m_last_error = "XML declaration and doctype must be top-level";
245 return false;
246 }
247 } else {
248 m_ancestors.clear();
249 if (*type == pugi::node_element) {
250 if (m_root_count != 0) {
251 m_last_error = "XML document may contain only one root element";
252 return false;
253 }
254
255 ++m_root_count;
256 } else if (*type == pugi::node_declaration) {
257 if (m_declaration_seen || !m_xml->nodes.empty()) {
258 m_last_error = "XML declaration must be the first document node";
259 return false;
260 }
261
262 m_declaration_seen = true;
263 } else if (*type == pugi::node_doctype) {
264 if (m_doctype_seen || m_root_count != 0) {
265 m_last_error = "XML doctype must occur once before the root";
266 return false;
267 }
268
269 m_doctype_seen = true;
270 } else if (*type != pugi::node_comment && *type != pugi::node_pi) {
271 m_last_error = "XML text and CDATA require a parent element";
272 return false;
273 }
274 }
275
276 const bool needs_name = *type == pugi::node_element
277 || *type == pugi::node_pi || *type == pugi::node_declaration;
278
279 const bool needs_value = *type == pugi::node_pcdata
280 || *type == pugi::node_cdata || *type == pugi::node_comment
281 || *type == pugi::node_pi || *type == pugi::node_doctype;
282
283 if ((needs_name && (!name || !valid_name(*name)))
284 || (*type == pugi::node_declaration && (!name || *name != "xml"))
285 || (*type == pugi::node_pi && name && *name == "xml")
286 || (!needs_name && name)
287 || (needs_value && (!value || !valid_xml_value(*value)))
288 || (!needs_value && value)
289 || (*type == pugi::node_comment
290 && (value->find("--") != std::string_view::npos || value->ends_with('-')))
291 || (*type == pugi::node_cdata && value->find("]]>") != std::string_view::npos)
292 || (*type == pugi::node_pi && value->find("?>") != std::string_view::npos)) {
293 m_last_error = "XML row has invalid name or value fields";
294 return false;
295 }
296
297 auto node = owner.append_child(*type);
298 if (!node || (name && !node.set_name(std::string(*name).c_str()))
299 || (value && !node.set_value(std::string(*value).c_str()))) {
300 m_last_error = "Could not append XML node";
301 return false;
302 }
303
304 m_xml->nodes.push_back(node);
305 m_content_started.push_back(false);
306
307 if (*type == pugi::node_element || *type == pugi::node_declaration)
308 m_ancestors.push_back(index);
309
310 return true;
311}
312
314{
315 if (!m_open) {
316 m_last_error = "No XML document is open";
317 return false;
318 }
319
320 if (m_failed)
321 return false;
322
323 if (m_root_count != 1) {
324 m_last_error = "XML document must contain one root element before saving";
325 return false;
326 }
327
328 const bool saved = m_xml->document.save_file(m_filepath.c_str(), "",
329 pugi::format_raw | pugi::format_no_declaration, pugi::encoding_utf8);
330
331 if (!saved) {
332 m_last_error = "Could not save XML document";
333 } else {
334 m_last_error.clear();
335 }
336 return saved;
337}
338
340{
341 if (!m_open)
342 return true;
343
344 const bool saved = !m_failed && flush();
345 m_xml.reset();
346 m_content_started.clear();
347 m_ancestors.clear();
348 m_filepath.clear();
349 m_open = false;
350
351 return saved;
352}
353
354}
std::vector< bool > m_content_started
Definition XmlWriter.hpp:68
bool close() override
Save and release the document, or return false after failure.
std::unique_ptr< Impl > m_xml
Definition XmlWriter.hpp:67
bool can_write(const std::string &filepath) const override
Accept paths with the .xml extension.
Definition XmlWriter.cpp:85
bool write_rows(const Kakshya::CompositeSlice &rows) override
Append preorder rows whose parent indices are global.
bool open(const std::string &filepath, const Kakshya::CompositeLayout &layout) override
Start a document using xml_composite_layout().
Definition XmlWriter.cpp:90
std::vector< uint64_t > m_ancestors
Definition XmlWriter.hpp:69
bool flush() override
Save the current document, which must contain one root.
bool write_row(const Kakshya::Composite &row)
bool same_structure(const CompositeLayout &other) const noexcept
Compare declared field names, kinds, and nested layouts.
Definition Composite.cpp:71
Shared field description and byte layout for a CompositeArray.
Definition Composite.hpp:60
std::optional< Composite > at(size_t index) const noexcept
Borrow a selected element by slice-relative index.
size_t size() const noexcept
Number of selected elements.
const CompositeLayout & layout() const noexcept
Shared layout of all selected elements.
Borrowed consecutive elements, optionally selected by a Region.
std::optional< std::string_view > text(std::string_view field_name) const noexcept
Read a present std::string field as borrowed UTF-8 bytes.
std::optional< T > get(std::string_view field_name) const noexcept
Read a present arithmetic or GLM field by exact value type.
Read view of one value in a CompositeArray.
std::string resolve_write_path(const std::string &filepath, std::string_view default_directory=Config::OUT_DIR)
Resolve a writable path against the configured output directory.
Kakshya::CompositeLayout xml_composite_layout()
Composite row layout used by the XML reader and writer.
Definition XmlReader.cpp:13
pugi::xml_document document
Definition XmlWriter.cpp:13
std::vector< pugi::xml_node > nodes
Definition XmlWriter.cpp:14