1use std::fmt;
10
11use serde::{Deserialize, Serialize};
12
13use super::error::OrkError;
14use super::left_out::NOTHING_DEPENDS;
15use super::warning::{Imported, Warning, WarningKind};
16
17pub const MAX_KNOWN_MINOR: u32 = 11;
23
24pub const MAX_DEPTH: usize = 64;
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
39pub struct SchemaVersion {
40 pub major: u32,
42 pub minor: u32,
44}
45
46impl SchemaVersion {
47 pub fn parse(text: &str) -> Result<Self, OrkError> {
49 let version = || OrkError::Version {
50 text: text.to_owned(),
51 };
52 let (major, minor) = text.split_once('.').ok_or_else(version)?;
53 let number = |field: &str| {
54 if field.is_empty() || !field.bytes().all(|byte| byte.is_ascii_digit()) {
55 return Err(version());
56 }
57 field.parse::<u32>().map_err(|_| version())
58 };
59 Ok(Self {
60 major: number(major)?,
61 minor: number(minor)?,
62 })
63 }
64
65 pub fn is_known(self) -> bool {
67 self.major == 1 && self.minor <= MAX_KNOWN_MINOR
68 }
69}
70
71impl fmt::Display for SchemaVersion {
72 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73 write!(f, "{}.{}", self.major, self.minor)
74 }
75}
76
77#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
79pub struct Document {
80 pub version: SchemaVersion,
82 pub creator: Option<String>,
85 pub root: Element,
87}
88
89#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
91#[serde(deny_unknown_fields)]
92pub struct Element {
93 pub name: String,
95 pub attributes: Vec<(String, String)>,
97 pub children: Vec<Node>,
99}
100
101#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
103#[serde(rename_all = "snake_case", tag = "kind")]
104#[serde(deny_unknown_fields)]
105pub enum Node {
106 Element(Element),
108 Text {
110 text: String,
112 },
113}
114
115impl Element {
116 pub fn attribute(&self, name: &str) -> Option<&str> {
118 super::reads::note_attribute(self, name);
119 self.attributes
120 .iter()
121 .find(|(key, _)| key == name)
122 .map(|(_, value)| value.as_str())
123 }
124
125 pub fn children_named<'a>(&'a self, name: &str) -> impl Iterator<Item = &'a Element> {
127 let name = name.to_owned();
128 self.elements().filter(move |child| child.name == name)
129 }
130
131 pub fn child<'a>(&'a self, name: &str) -> Option<&'a Element> {
133 self.elements().find(|child| child.name == name)
134 }
135
136 pub fn elements(&self) -> impl Iterator<Item = &Element> {
138 self.children.iter().filter_map(|child| match child {
139 Node::Element(element) => Some(element),
140 Node::Text { .. } => None,
141 })
142 }
143
144 pub fn text(&self) -> String {
149 let mut text = String::new();
150 for child in &self.children {
151 if let Node::Text { text: part } = child {
152 text.push_str(part);
153 }
154 }
155 text
156 }
157
158 fn has_element_child(&self) -> bool {
159 self.elements().next().is_some()
160 }
161
162 fn has_text_child(&self) -> bool {
163 self.children
164 .iter()
165 .any(|child| matches!(child, Node::Text { .. }))
166 }
167}
168
169impl Document {
170 pub fn parse(text: &str) -> Result<Imported<Self>, OrkError> {
180 let deepest = deepest_nesting(text);
181 if deepest > MAX_DEPTH {
182 return Err(OrkError::TooDeep {
183 limit: MAX_DEPTH,
184 depth: deepest,
185 });
186 }
187 let parsed = roxmltree::Document::parse(text).map_err(|error| OrkError::Xml {
188 reason: error.to_string(),
189 })?;
190 let root = parsed.root_element();
191 if root.tag_name().name() != "openrocket" {
192 return Err(OrkError::NotOpenRocket {
193 root: root.tag_name().name().to_owned(),
194 });
195 }
196 let version = SchemaVersion::parse(root.attribute("version").unwrap_or_default())?;
197 let creator = root.attribute("creator").map(str::to_owned);
198
199 let mut warnings = Vec::new();
200 if !version.is_known() {
201 warnings.push(Warning::new(
202 "openrocket",
203 WarningKind::Unusual,
204 if version.major == 1 {
205 format!(
206 "schema version {version} is newer than 1.{MAX_KNOWN_MINOR}, the newest \
207 this reader knows; it was read as far as it is understood"
208 )
209 } else {
210 format!(
211 "schema version {version} is not one this reader knows (1.0 to \
212 1.{MAX_KNOWN_MINOR}); it was read as far as it is understood"
213 )
214 },
215 ));
216 }
217 if creator.is_none() {
218 warnings.push(Warning::new(
219 "openrocket",
220 WarningKind::Unusual,
221 "the root element has no `creator` attribute, so the program that wrote this \
222 design is unknown",
223 ));
224 }
225 if root.tag_name().namespace().is_some()
226 || parsed
227 .descendants()
228 .any(|node| node.namespaces().next().is_some())
229 {
230 warnings.push(Warning::new(
231 "openrocket",
232 WarningKind::Dropped,
233 "this document declares XML namespaces; their prefixes and declarations were left \
234 out, and two attributes that differ only by prefix become one. No `.ork` \
235 OpenRocket writes uses them",
236 ));
237 }
238 let root = read_element(root, "", &mut warnings);
239 Ok(Imported {
240 value: Self {
241 version,
242 creator,
243 root,
244 },
245 warnings,
246 })
247 }
248
249 pub fn to_xml(&self) -> String {
263 let mut root = self.root.clone();
264 set_attribute(&mut root, "version", Some(self.version.to_string()));
265 set_attribute(&mut root, "creator", self.creator.clone());
266 let mut out = String::from("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
267 write_element(&root, 0, &mut out);
268 out.push('\n');
269 out
270 }
271}
272
273fn read_element(
275 node: roxmltree::Node<'_, '_>,
276 parent: &str,
277 warnings: &mut Vec<Warning>,
278) -> Element {
279 let name = node.tag_name().name().to_owned();
280 let at = if parent.is_empty() {
281 name.clone()
282 } else {
283 format!("{parent}/{name}")
284 };
285 let attributes = node
286 .attributes()
287 .map(|attribute| (attribute.name().to_owned(), attribute.value().to_owned()))
288 .collect();
289
290 let keeps_blank_text = !node.children().any(|child| child.is_element());
291 let mut children = Vec::new();
292 for child in node.children() {
293 if child.is_element() {
294 children.push(Node::Element(read_element(child, &at, warnings)));
295 } else if child.is_text() {
296 let text = child.text().unwrap_or_default();
297 if let Some(Node::Text { text: last }) = children.last_mut()
301 && (keeps_blank_text || !text.trim().is_empty())
302 {
303 last.push_str(text);
304 continue;
305 }
306 if keeps_blank_text {
307 children.push(Node::Text {
308 text: text.to_owned(),
309 });
310 } else if !text.trim().is_empty() {
311 children.push(Node::Text {
315 text: text.to_owned(),
316 });
317 }
318 } else if child.is_comment() {
319 warnings.push(Warning::new(
320 at.clone(),
321 WarningKind::Dropped,
322 format!("an XML comment was left out, and {NOTHING_DEPENDS}"),
323 ));
324 } else if child.is_pi() {
325 warnings.push(Warning::new(
326 at.clone(),
327 WarningKind::Dropped,
328 format!("an XML processing instruction was left out, and {NOTHING_DEPENDS}"),
329 ));
330 }
331 }
332 Element {
333 name,
334 attributes,
335 children,
336 }
337}
338
339pub(crate) fn deepest_nesting(text: &str) -> usize {
347 let bytes = text.as_bytes();
348 let mut index = 0;
349 let mut depth = 0usize;
350 let mut deepest = 0usize;
351 while index < bytes.len() {
352 if bytes[index] != b'<' {
353 index += 1;
354 continue;
355 }
356 let rest = &bytes[index..];
357 if let Some(skip) = skipped(rest, b"<!--", b"-->")
358 .or_else(|| skipped(rest, b"<![CDATA[", b"]]>"))
359 .or_else(|| skipped(rest, b"<?", b"?>"))
360 {
361 index += skip;
362 continue;
363 }
364 let closing = rest.starts_with(b"</");
365 let declaration = rest.starts_with(b"<!");
367
368 let mut cursor = index + 1;
369 let mut quote: Option<u8> = None;
370 let mut last = 0u8;
371 while cursor < bytes.len() {
372 let byte = bytes[cursor];
373 match quote {
374 Some(open) if byte == open => quote = None,
375 Some(_) => {}
376 None if byte == b'"' || byte == b'\'' => quote = Some(byte),
377 None if byte == b'>' => break,
378 None => {}
379 }
380 if !byte.is_ascii_whitespace() {
381 last = byte;
382 }
383 cursor += 1;
384 }
385 if !declaration {
386 if closing {
387 depth = depth.saturating_sub(1);
388 } else {
389 depth += 1;
390 deepest = deepest.max(depth);
391 if last == b'/' {
392 depth -= 1;
393 }
394 }
395 }
396 index = cursor + 1;
397 }
398 deepest
399}
400
401fn skipped(rest: &[u8], opening: &[u8], closing: &[u8]) -> Option<usize> {
404 if !rest.starts_with(opening) {
405 return None;
406 }
407 let from = opening.len();
408 let found = rest[from..]
409 .windows(closing.len())
410 .position(|window| window == closing)
411 .map(|at| from + at + closing.len());
412 Some(found.unwrap_or(rest.len()))
413}
414
415fn set_attribute(element: &mut Element, name: &str, value: Option<String>) {
417 let at = element.attributes.iter().position(|(key, _)| key == name);
418 match (at, value) {
419 (Some(at), Some(value)) => element.attributes[at].1 = value,
420 (Some(at), None) => {
421 element.attributes.remove(at);
422 }
423 (None, Some(value)) => element.attributes.push((name.to_owned(), value)),
424 (None, None) => {}
425 }
426}
427
428fn write_element(element: &Element, depth: usize, out: &mut String) {
430 let mixed = element.has_element_child() && element.has_text_child();
431 if mixed {
432 write_compact(element, out);
435 return;
436 }
437 for _ in 0..depth {
438 out.push_str(" ");
439 }
440 write_open_tag(element, out);
441 if element.children.is_empty() {
442 out.truncate(out.len() - 1);
443 out.push_str("/>");
444 return;
445 }
446 if element.has_element_child() {
447 for child in &element.children {
448 if let Node::Element(child) = child {
449 out.push('\n');
450 write_element(child, depth + 1, out);
451 }
452 }
453 out.push('\n');
454 for _ in 0..depth {
455 out.push_str(" ");
456 }
457 } else {
458 out.push_str(&escape_text(&element.text()));
459 }
460 out.push_str("</");
461 out.push_str(&element.name);
462 out.push('>');
463}
464
465fn write_compact(element: &Element, out: &mut String) {
467 write_open_tag(element, out);
468 if element.children.is_empty() {
469 out.truncate(out.len() - 1);
470 out.push_str("/>");
471 return;
472 }
473 for child in &element.children {
474 match child {
475 Node::Element(child) => write_compact(child, out),
476 Node::Text { text } => out.push_str(&escape_text(text)),
477 }
478 }
479 out.push_str("</");
480 out.push_str(&element.name);
481 out.push('>');
482}
483
484fn write_open_tag(element: &Element, out: &mut String) {
485 out.push('<');
486 out.push_str(&element.name);
487 for (name, value) in &element.attributes {
488 out.push(' ');
489 out.push_str(name);
490 out.push_str("=\"");
491 out.push_str(&escape_attribute(value));
492 out.push('"');
493 }
494 out.push('>');
495}
496
497fn escape_text(text: &str) -> String {
500 let mut out = String::with_capacity(text.len());
501 for character in text.chars() {
502 match character {
503 '&' => out.push_str("&"),
504 '<' => out.push_str("<"),
505 '>' => out.push_str(">"),
506 '\r' => out.push_str(" "),
507 other => out.push(other),
508 }
509 }
510 out
511}
512
513fn escape_attribute(value: &str) -> String {
516 let mut out = String::with_capacity(value.len());
517 for character in value.chars() {
518 match character {
519 '&' => out.push_str("&"),
520 '<' => out.push_str("<"),
521 '>' => out.push_str(">"),
522 '"' => out.push_str("""),
523 '\t' => out.push_str("	"),
524 '\n' => out.push_str(" "),
525 '\r' => out.push_str(" "),
526 other => out.push(other),
527 }
528 }
529 out
530}