use crate::document_core::helpers::{json_i32, parse_char_shape_mods};
use crate::document_core::DocumentCore;
use crate::error::HwpError;
impl DocumentCore {
pub fn set_numbering_char_shape_native(
&mut self,
numbering_id: u16,
level: usize,
json: Option<&str>,
) -> Result<u32, HwpError> {
let info = &self.document.doc_info;
let index = usize::from(numbering_id)
.checked_sub(1)
.filter(|index| *index < info.numberings.len())
.ok_or_else(|| HwpError::RenderError(format!("번호 정의 {numbering_id}가 없음")))?;
if level >= info.numberings[index].heads.len() {
return Err(HwpError::RenderError(format!(
"번호 수준 {level} 범위 초과"
)));
}
let id = match json {
None => u32::MAX,
Some(json) => {
let base = json_i32(json, "baseCharShapeId")
.and_then(|id| u32::try_from(id).ok())
.filter(|id| (*id as usize) < info.char_shapes.len())
.unwrap_or(0);
let id = self
.document
.find_or_create_char_shape(base, &parse_char_shape_mods(json));
if id == 0 {
let shapes = &mut self.document.doc_info.char_shapes;
match shapes[1..].iter().position(|shape| *shape == shapes[0]) {
Some(index) => index as u32 + 1,
None => {
let mut shape = shapes[0].clone();
shape.raw_data = None;
shapes.push(shape);
(shapes.len() - 1) as u32
}
}
} else {
id
}
}
};
let numbering = &mut self.document.doc_info.numberings[index];
numbering.heads[level].char_shape_id = id;
if let Some(raw) = &numbering.raw_para_heads {
numbering.raw_para_heads = set_para_head_char_shape(raw, level + 1, id);
}
self.document.doc_info.raw_stream_dirty = true;
if self.numbering_in_use(numbering_id) {
self.rebuild_derived_state();
} else {
self.rebuild_resolved_styles();
}
Ok(id)
}
fn numbering_in_use(&self, numbering_id: u16) -> bool {
use crate::model::style::HeadType;
self.document.doc_info.para_shapes.iter().any(|ps| {
matches!(ps.head_type, HeadType::Number | HeadType::Outline)
&& ps.numbering_id == numbering_id
}) || self
.document
.sections
.iter()
.any(|section| section.section_def.outline_numbering_id == numbering_id)
}
}
fn set_para_head_char_shape(raw: &str, level: usize, id: u32) -> Option<String> {
let mut found = false;
let raw = map_para_head_char_refs(raw, |at, old| {
if at == level {
found = true;
Some(id)
} else {
Some(old)
}
})?;
found.then_some(raw)
}
pub(super) fn map_para_head_char_refs(
raw: &str,
mut map: impl FnMut(usize, u32) -> Option<u32>,
) -> Option<String> {
use quick_xml::{events::Event, Reader, XmlVersion};
let mut reader = Reader::from_str(raw);
let mut out = String::with_capacity(raw.len());
let mut copied = 0;
loop {
let open = usize::try_from(reader.buffer_position()).ok()?;
match reader.read_event().ok()? {
Event::Start(tag) | Event::Empty(tag) if tag.local_name().as_ref() == "paraHead" => {
let mut level = 0;
let mut old = None;
for attribute in tag.attributes() {
let attribute = attribute.ok()?;
match attribute.key.as_ref() {
"level" => {
level = attribute
.normalized_value(XmlVersion::Implicit1_0)
.ok()?
.parse()
.ok()?;
}
"charPrIDRef" => {
old = Some(
attribute
.normalized_value(XmlVersion::Implicit1_0)
.ok()?
.parse()
.ok()?,
);
}
_ => {}
}
}
let Some(old) = old else {
continue;
};
let id = map(level, old)?;
let close = usize::try_from(reader.buffer_position()).ok()?;
let value = raw_attribute_value_range(&raw[open..close], "charPrIDRef")?;
out.push_str(&raw[copied..open + value.start]);
out.push_str(&id.to_string());
copied = open + value.end;
}
Event::Eof => break,
_ => {}
}
}
out.push_str(&raw[copied..]);
Some(out)
}
fn raw_attribute_value_range(tag: &str, wanted: &str) -> Option<std::ops::Range<usize>> {
let bytes = tag.as_bytes();
let mut at = tag.find(char::is_whitespace)?;
loop {
while bytes.get(at).is_some_and(u8::is_ascii_whitespace) {
at += 1;
}
let key_start = at;
while bytes
.get(at)
.is_some_and(|b| !b.is_ascii_whitespace() && *b != b'=')
{
at += 1;
}
let key = &tag[key_start..at];
while bytes.get(at).is_some_and(u8::is_ascii_whitespace) {
at += 1;
}
if bytes.get(at) != Some(&b'=') {
return None;
}
at += 1;
while bytes.get(at).is_some_and(u8::is_ascii_whitespace) {
at += 1;
}
let quote = *bytes.get(at)?;
if quote != b'\'' && quote != b'"' {
return None;
}
let value_start = at + 1;
at = value_start + bytes[value_start..].iter().position(|b| *b == quote)?;
if key == wanted {
return Some(value_start..at);
}
at += 1;
}
}