mod equation;
pub use equation::{DeclaredEquationFrameSource, Equation};
use std::collections::HashMap;
use super::document::SectionDef;
use super::footnote::{Endnote, Footnote};
use super::header_footer::{Footer, Header};
use super::image::Picture;
use super::page::ColumnDef;
use super::paragraph::Paragraph;
use super::shape::{CommonObjAttr, ShapeObject};
use super::table::Table;
fn serialize_sorted_string_map<S>(
map: &HashMap<String, String>,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut entries: Vec<(&String, &String)> = map.iter().collect();
entries.sort();
serializer.collect_map(entries)
}
#[derive(Debug, Clone, serde::Serialize)]
pub enum Control {
SectionDef(Box<SectionDef>),
ColumnDef(ColumnDef),
Table(Box<Table>),
Shape(Box<ShapeObject>),
Picture(Box<Picture>),
Header(Box<Header>),
Footer(Box<Footer>),
Footnote(Box<Footnote>),
Endnote(Box<Endnote>),
AutoNumber(AutoNumber),
NewNumber(NewNumber),
PageNumberPos(PageNumberPos),
Bookmark(Bookmark),
IndexMark(IndexMark),
PageNumCtrl(PageNumCtrl),
Hyperlink(Hyperlink),
Ruby(Ruby),
CharOverlap(CharOverlap),
PageHide(PageHide),
HiddenComment(Box<HiddenComment>),
Equation(Box<Equation>),
Field(Field),
Form(Box<FormObject>),
Unknown(UnknownControl),
}
impl Control {
pub fn header_footer_paragraphs(&self) -> Option<&Vec<crate::model::paragraph::Paragraph>> {
match self {
Control::Header(header) => Some(&header.paragraphs),
Control::Footer(footer) => Some(&footer.paragraphs),
_ => None,
}
}
pub fn header_footer_paragraphs_mut(
&mut self,
) -> Option<&mut Vec<crate::model::paragraph::Paragraph>> {
match self {
Control::Header(header) => Some(&mut header.paragraphs),
Control::Footer(footer) => Some(&mut footer.paragraphs),
_ => None,
}
}
pub fn is_treat_as_char_object(&self) -> bool {
match self {
Control::Shape(shape) => shape.common().treat_as_char,
Control::Table(table) => table.common.treat_as_char,
Control::Picture(picture) => picture.common.treat_as_char,
Control::Equation(equation) => equation.common.treat_as_char,
Control::Form(form) => form.common.treat_as_char,
_ => false,
}
}
pub fn is_logical_inline(&self) -> bool {
self.is_treat_as_char_object()
|| matches!(
self,
Control::Footnote(_)
| Control::Endnote(_)
| Control::CharOverlap(_)
| Control::Ruby(_)
)
}
pub fn occupies_ctrl_char_slot(&self) -> bool {
match self {
Control::Hyperlink(_) => false,
Control::Unknown(u) => u.ctrl_id != 0,
_ => true,
}
}
}
pub const CTRL_CHAR_CODE_UNITS: u32 = 8;
pub const EQUATION_LINE_MODE_BIT: u32 = 0x0000_0001;
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct AutoNumber {
pub number_type: AutoNumberType,
pub format: u8,
pub superscript: bool,
pub assigned_number: u16,
pub number: u16,
pub user_symbol: char,
pub prefix_char: char,
pub suffix_char: char,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, serde::Serialize)]
pub enum AutoNumberType {
#[default]
Page,
Footnote,
Endnote,
Picture,
Table,
Equation,
TotalPage,
}
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct NewNumber {
pub number_type: AutoNumberType,
pub number: u16,
}
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct PageNumberPos {
pub format: u8,
pub position: u8,
pub user_symbol: char,
pub prefix_char: char,
pub suffix_char: char,
pub dash_char: char,
}
crate::storage::clone_fields!(PageNumberPos, {format, position, user_symbol, prefix_char, suffix_char, dash_char});
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct Bookmark {
pub name: String,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize)]
pub enum PageStartsOn {
#[default]
Both,
Even,
Odd,
}
impl PageStartsOn {
pub fn from_hwp5(v: u32) -> Self {
match v {
1 => Self::Even,
2 => Self::Odd,
_ => Self::Both,
}
}
pub fn to_hwp5(self) -> u32 {
match self {
Self::Both => 0,
Self::Even => 1,
Self::Odd => 2,
}
}
pub fn as_hwpx(self) -> &'static str {
match self {
Self::Both => "BOTH",
Self::Even => "EVEN",
Self::Odd => "ODD",
}
}
pub fn from_hwpx(v: &str) -> Self {
match v {
"EVEN" => Self::Even,
"ODD" => Self::Odd,
_ => Self::Both,
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize)]
pub struct PageNumCtrl {
pub page_starts_on: PageStartsOn,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]
pub struct IndexMark {
pub first_key: String,
pub second_key: String,
}
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct Hyperlink {
pub url: String,
pub text: String,
}
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct Ruby {
pub main_text: String,
pub ruby_text: String,
pub pos_type: u8,
pub align: u8,
pub sz_ratio: u8,
pub option: u32,
pub style_id_ref: u16,
}
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct CharOverlap {
pub chars: Vec<char>,
pub border_type: u8,
pub inner_char_size: i8,
pub expansion: u8,
pub char_shape_ids: Vec<u32>,
#[serde(skip)]
pub hwp_wire_chars: bool,
}
impl CharOverlap {
pub fn border_glyph(border_type: u8) -> Option<char> {
match border_type {
1 => Some('◯'),
2 => Some('●'),
3 => Some('□'),
4 => Some('■'),
5 => Some('△'),
6 => Some('▲'),
7 => Some('☼'),
8 => Some('◇'),
9 => Some('◆'),
10 => Some('▢'),
11 => Some('♲'),
12 => Some('♺'),
13 => Some('♻'),
_ => None,
}
}
pub fn hwp_prefix(&self) -> Option<char> {
Self::border_glyph(self.border_type).or_else(|| (self.expansion == 0).then_some('\u{3000}'))
}
}
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct PageHide {
pub hide_header: bool,
pub hide_footer: bool,
pub hide_master_page: bool,
pub hide_border: bool,
pub hide_fill: bool,
pub hide_page_num: bool,
}
crate::storage::clone_fields!(PageHide, {hide_header, hide_footer, hide_master_page, hide_border, hide_fill, hide_page_num});
#[derive(Debug, Default, Clone, serde::Serialize)]
pub struct HiddenComment {
pub paragraphs: Vec<Paragraph>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]
pub struct GuideResidue {
pub text: String,
pub char_shape_id: u32,
}
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub enum Parameter {
Boolean {
name: Option<String>,
value: bool,
lexical: Option<String>,
},
Integer {
name: Option<String>,
value: i64,
},
Float {
name: Option<String>,
value: f32,
},
String {
name: Option<String>,
value: String,
preserve_space: bool,
},
List(ParameterList),
}
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize)]
pub struct ParameterList {
pub name: Option<String>,
pub items: Vec<Parameter>,
}
impl ParameterList {
pub fn is_empty(&self) -> bool {
self.items.is_empty()
}
pub fn render_xml(&self, tag: &str) -> String {
let mut out = String::new();
out.push_str("<hp:");
out.push_str(tag);
out.push_str(&format!(" cnt=\"{}\"", self.items.len().max(1)));
out.push_str(" name=\"");
out.push_str(&escape_parameter_xml(self.name.as_deref().unwrap_or("")));
out.push_str("\">");
for item in &self.items {
item.render_xml_into(&mut out);
}
out.push_str("</hp:");
out.push_str(tag);
out.push('>');
out
}
}
impl Parameter {
fn render_xml_into(&self, out: &mut String) {
match self {
Parameter::Boolean {
name,
value,
lexical,
} => {
let text = lexical.as_deref().unwrap_or(if *value { "1" } else { "0" });
render_scalar_param(out, "booleanParam", name, text);
}
Parameter::Integer { name, value } => {
render_scalar_param(out, "integerParam", name, &value.to_string());
}
Parameter::Float { name, value } => {
render_scalar_param(out, "floatParam", name, &value.to_string());
}
Parameter::String {
name,
value,
preserve_space,
} => {
out.push_str("<hp:stringParam name=\"");
out.push_str(&escape_parameter_xml(name.as_deref().unwrap_or("")));
out.push('"');
if *preserve_space {
out.push_str(" xml:space=\"preserve\"");
}
out.push('>');
out.push_str(&escape_parameter_xml(value));
out.push_str("</hp:stringParam>");
}
Parameter::List(list) => out.push_str(&list.render_xml("listParam")),
}
}
}
fn render_scalar_param(out: &mut String, tag: &str, name: &Option<String>, text: &str) {
out.push_str("<hp:");
out.push_str(tag);
out.push_str(" name=\"");
out.push_str(&escape_parameter_xml(name.as_deref().unwrap_or("")));
out.push_str("\">");
out.push_str(text);
out.push_str("</hp:");
out.push_str(tag);
out.push('>');
}
pub(crate) fn boolean_lexical_of(text: &str) -> Option<String> {
let t = text.trim();
matches!(t, "0" | "1" | "true" | "false").then(|| t.to_string())
}
fn escape_parameter_xml(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'"' => out.push_str("""),
'\u{09}' | '\u{0A}' | '\u{0D}' => out.push(c),
'\u{20}'..='\u{D7FF}' | '\u{E000}'..='\u{FFFD}' | '\u{10000}'..='\u{10FFFF}' => {
out.push(c)
}
_ => {}
}
}
out
}
impl ParameterList {
pub fn parse_xml(xml: &str) -> Option<ParameterList> {
let mut pos = 0usize;
let (_, list) = parse_list_tag(xml, &mut pos)?;
Some(list)
}
}
fn parse_list_tag(s: &str, pos: &mut usize) -> Option<(String, ParameterList)> {
expect_lit(s, pos, "<hp:")?;
let tag = read_ident(s, pos)?;
skip_attr(s, pos, "cnt")?;
let name = read_attr(s, pos, "name")?;
expect_lit(s, pos, ">")?;
let close = format!("</hp:{tag}>");
let mut items = Vec::new();
while !s[*pos..].starts_with(&close) {
items.push(parse_one_param(s, pos)?);
}
*pos += close.len();
Some((
tag,
ParameterList {
name: Some(name),
items,
},
))
}
fn parse_one_param(s: &str, pos: &mut usize) -> Option<Parameter> {
if !s[*pos..].starts_with("<hp:") {
return None;
}
let after = &s[*pos + 4..];
if after.starts_with("listParam") {
let (_, list) = parse_list_tag(s, pos)?;
return Some(Parameter::List(list));
}
for tag in ["booleanParam", "integerParam", "floatParam", "stringParam"] {
if !after.starts_with(tag) {
continue;
}
*pos += 4 + tag.len();
let name = read_attr(s, pos, "name")?;
let preserve_space =
tag == "stringParam" && try_consume_lit(s, pos, " xml:space=\"preserve\"");
expect_lit(s, pos, ">")?;
let close = format!("</hp:{tag}>");
let raw_text = read_until(s, pos, &close)?;
expect_lit(s, pos, &close)?;
let text = unescape_parameter_xml(&raw_text);
return Some(match tag {
"booleanParam" => Parameter::Boolean {
name: Some(name),
value: matches!(text.trim(), "1" | "true"),
lexical: boolean_lexical_of(&text),
},
"integerParam" => Parameter::Integer {
name: Some(name),
value: text.trim().parse::<i64>().unwrap_or(0),
},
"floatParam" => Parameter::Float {
name: Some(name),
value: text.trim().parse::<f32>().unwrap_or(0.0),
},
_ => Parameter::String {
name: Some(name),
value: text,
preserve_space,
},
});
}
None
}
fn read_ident(s: &str, pos: &mut usize) -> Option<String> {
let rest = &s[*pos..];
let end = rest.find(|c: char| c == ' ' || c == '>')?;
let ident = rest[..end].to_string();
*pos += end;
Some(ident)
}
fn skip_attr(s: &str, pos: &mut usize, key: &str) -> Option<()> {
let needle = format!(" {key}=\"");
expect_lit(s, pos, &needle)?;
let end = s[*pos..].find('"')?;
*pos += end + 1;
Some(())
}
fn read_attr(s: &str, pos: &mut usize, key: &str) -> Option<String> {
let needle = format!(" {key}=\"");
expect_lit(s, pos, &needle)?;
let end = s[*pos..].find('"')?;
let value = unescape_parameter_xml(&s[*pos..*pos + end]);
*pos += end + 1;
Some(value)
}
fn expect_lit(s: &str, pos: &mut usize, lit: &str) -> Option<()> {
if !s[*pos..].starts_with(lit) {
return None;
}
*pos += lit.len();
Some(())
}
fn try_consume_lit(s: &str, pos: &mut usize, lit: &str) -> bool {
if s[*pos..].starts_with(lit) {
*pos += lit.len();
true
} else {
false
}
}
fn read_until(s: &str, pos: &mut usize, marker: &str) -> Option<String> {
let idx = s[*pos..].find(marker)?;
let text = s[*pos..*pos + idx].to_string();
*pos += idx;
Some(text)
}
fn unescape_parameter_xml(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut i = 0;
while i < s.len() {
if s.as_bytes()[i] == b'&' {
if s[i..].starts_with("&") {
out.push('&');
i += 5;
continue;
} else if s[i..].starts_with("<") {
out.push('<');
i += 4;
continue;
} else if s[i..].starts_with(">") {
out.push('>');
i += 4;
continue;
} else if s[i..].starts_with(""") {
out.push('"');
i += 6;
continue;
}
}
let ch_len = s[i..].chars().next().map(|c| c.len_utf8()).unwrap_or(1);
out.push_str(&s[i..i + ch_len]);
i += ch_len;
}
out
}
#[cfg(test)]
mod parameter_list_codec_tests;
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct Field {
pub field_type: FieldType,
pub command: String,
pub properties: u32,
pub extra_properties: u8,
pub field_id: u32,
pub ctrl_id: u32,
pub raw_type: Option<String>,
pub instance_id: Option<u32>,
pub ctrl_data_name: Option<String>,
pub memo_index: u32,
pub memo_paragraphs: Vec<Paragraph>,
pub memo_text_direction: Option<String>,
pub raw_parameters_xml: Option<String>,
pub parameters: ParameterList,
#[serde(skip_serializing_if = "Option::is_none")]
pub hyperlink_format: Option<Box<super::hyperlink_format::OriginalFormat>>,
pub guide_residue: Option<GuideResidue>,
}
impl Field {
pub fn guide_text(&self) -> Option<&str> {
if self.field_type != FieldType::ClickHere {
return None;
}
self.extract_wstring_value("Direction:")
}
pub fn field_name(&self) -> Option<&str> {
if self.field_type != FieldType::ClickHere {
return None;
}
if let Some(ref name) = self.ctrl_data_name {
if !name.is_empty() {
return Some(name.as_str());
}
}
if let Some(name) = self.extract_wstring_value("Name:") {
return Some(name);
}
self.extract_wstring_value("Direction:")
}
pub fn extract_wstring_value(&self, key: &str) -> Option<&str> {
let key_start = self.command.find(key)?;
let after_key = &self.command[key_start + key.len()..];
let wstring_marker = "wstring:";
let ws_start = after_key.find(wstring_marker)? + wstring_marker.len();
let rest = &after_key[ws_start..];
let colon_pos = rest.find(':')?;
let value_start = key_start + key.len() + ws_start + colon_pos + 1;
let value_part = &self.command[value_start..];
let end = value_part
.find(" HelpState:")
.or_else(|| value_part.find(" Direction:"))
.or_else(|| value_part.find(" Name:"))
.unwrap_or(value_part.len());
let value = value_part[..end].trim();
if value.is_empty() {
None
} else {
Some(value)
}
}
pub fn memo_text(&self) -> Option<&str> {
if self.field_type != FieldType::ClickHere {
return None;
}
self.extract_wstring_value("HelpState:")
}
pub fn is_editable_in_form(&self) -> bool {
self.properties & 1 != 0
}
pub fn is_dirty(&self) -> bool {
self.properties & (1 << 15) != 0
}
pub fn build_clickhere_command(guide: &str, memo: &str) -> String {
let guide_len = guide.encode_utf16().count();
let memo_len = memo.encode_utf16().count();
let inner = format!(
"Direction:wstring:{}:{} HelpState:wstring:{}:{} ",
guide_len, guide, memo_len, memo
);
let set_len = inner.encode_utf16().count() - 1;
format!("Clickhere:set:{}:{}", set_len, inner)
}
pub fn field_type_str(&self) -> &'static str {
match self.field_type {
FieldType::Unknown => "unknown",
FieldType::Date => "date",
FieldType::DocDate => "docdate",
FieldType::Path => "path",
FieldType::Bookmark => "bookmark",
FieldType::MailMerge => "mailmerge",
FieldType::CrossRef => "crossref",
FieldType::Formula => "formula",
FieldType::ClickHere => "clickhere",
FieldType::Summary => "summary",
FieldType::UserInfo => "userinfo",
FieldType::Hyperlink => "hyperlink",
FieldType::Memo => "memo",
FieldType::PrivateInfoSecurity => "privateinfo",
FieldType::TableOfContents => "toc",
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, serde::Serialize)]
pub enum FieldType {
#[default]
Unknown,
Date,
DocDate,
Path,
Bookmark,
MailMerge,
CrossRef,
Formula,
ClickHere,
Summary,
UserInfo,
Hyperlink,
Memo,
PrivateInfoSecurity,
TableOfContents,
}
#[derive(Debug, Clone, Copy, PartialEq, Default, serde::Serialize)]
pub enum FormType {
#[default]
PushButton,
CheckBox,
ComboBox,
RadioButton,
Edit,
}
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct FormObject {
pub common: CommonObjAttr,
pub form_type: FormType,
pub name: String,
pub caption: String,
pub text: String,
pub width: u32,
pub height: u32,
pub fore_color: u32,
pub back_color: u32,
pub value: i32,
pub enabled: bool,
#[serde(serialize_with = "serialize_sorted_string_map")]
pub properties: HashMap<String, String>,
}
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct UnknownControl {
pub ctrl_id: u32,
}
#[cfg(test)]
mod tests;