use f_office_drawingml::color::{ColorNames, DrawColor};
use f_office_drawingml::gradient::LinearGradient;
use f_office_units::Length;
use f_office_units::scale::DRAWING_WHOLE;
use f_office_xml::NodeId;
use f_office_xml::enumeration::{Case, Values, another, own};
use super::border::{BORDER_LINE, LineStyle};
use super::color::{HIGHLIGHT, parse_color, read_text_color};
use super::{Color, SetIn, overlay, read_shading};
use crate::ns::{W, W14};
use crate::on_off::{self, off_also_for_none};
use crate::reader::PartReader;
use crate::warnings::Feature;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FontRef {
Name(String),
MinorLatin,
MajorLatin,
MinorBidi,
MajorBidi,
MinorEastAsia,
MajorEastAsia,
}
impl FontRef {
pub(crate) fn of_typeface(face: &str) -> Self {
match face {
"+mn-lt" => Self::MinorLatin,
"+mj-lt" => Self::MajorLatin,
name => Self::Name(name.to_owned()),
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct RunProps {
pub font_ascii: Option<FontRef>,
pub font_hansi: Option<FontRef>,
pub bold: Option<bool>,
pub italic: Option<bool>,
pub size: Option<i64>,
pub color: Option<Color>,
pub underline: Option<Underline>,
pub strike: Option<Strike>,
pub changed: Option<bool>,
pub shading: Option<Color>,
pub highlight: Option<Color>,
pub caps: Option<bool>,
pub small_caps: Option<bool>,
pub vertical: Option<VerticalAlign>,
pub math_script: Option<MathScript>,
pub math: Option<bool>,
pub position: Option<Length>,
pub hidden: Option<bool>,
pub phantom: Option<bool>,
pub kern: Option<i64>,
pub spacing: Option<Length>,
pub scale: Option<i64>,
pub outline: Option<TextOutline>,
pub text_fill: Option<TextFill>,
pub shadow: Option<TextShadow>,
pub glow: Option<TextGlow>,
pub reflection: Option<Box<TextReflection>>,
pub legacy_shadow: Option<bool>,
pub legacy_outline: Option<bool>,
pub emboss: Option<bool>,
pub imprint: Option<bool>,
pub effect: Option<bool>,
pub ligatures: Option<bool>,
pub font_cs: Option<Box<FontRef>>,
pub size_cs: Option<i64>,
pub bold_cs: Option<bool>,
pub italic_cs: Option<bool>,
pub complex: Option<bool>,
pub rtl: Option<bool>,
pub field_rtl: Option<bool>,
pub form_text: Option<bool>,
pub font_east_asia: Option<Box<FontRef>>,
pub east_asian_hint: Option<bool>,
pub east_asian_language: Option<EastAsianLanguage>,
pub lang: Option<Box<str>>,
pub bidi_script: Option<BidiScript>,
pub bidi_class: Option<BidiLanguageClass>,
pub snap_to_grid: Option<bool>,
pub(crate) bordered: Option<bool>,
pub unsupported: UnsupportedProperties,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum BidiLanguageClass {
#[default]
Arabic,
OtherRightToLeft,
Unicode,
}
impl BidiLanguageClass {
#[must_use]
pub fn of(lang: &str) -> Self {
let lang = lang.to_ascii_lowercase();
match lang.split('-').next().unwrap_or_default() {
"ar" if lang == "ar-ma" => Self::OtherRightToLeft,
"ar" => Self::Arabic,
"fa" | "prs" | "ur" | "ps" | "ug" | "sd" | "ku" | "syr" | "dv" => {
Self::OtherRightToLeft
}
_ => Self::Unicode,
}
}
#[must_use]
pub fn starts_with_arabic_number(self) -> bool {
self == Self::Arabic
}
#[must_use]
pub fn has_neutral_slash(self) -> bool {
self != Self::Unicode
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BidiScript {
Hebrew,
Other,
}
impl BidiScript {
#[must_use]
pub fn of(lang: &str) -> Self {
let primary = lang.split('-').next().unwrap_or_default();
if primary.eq_ignore_ascii_case("he") {
Self::Hebrew
} else {
Self::Other
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum EastAsianScript {
Japanese,
Simplified,
Traditional,
Korean,
}
impl EastAsianScript {
#[must_use]
pub fn of(lang: &str) -> Option<Self> {
let lang = lang.to_ascii_lowercase();
if lang.starts_with("ja") {
Some(Self::Japanese)
} else if lang.starts_with("ko") {
Some(Self::Korean)
} else if matches!(lang.as_str(), "zh-tw" | "zh-hk" | "zh-mo") {
Some(Self::Traditional)
} else if lang.starts_with("zh") {
Some(Self::Simplified)
} else {
None
}
}
#[must_use]
pub fn theme_name(self) -> &'static str {
match self {
Self::Japanese => "Jpan",
Self::Simplified => "Hans",
Self::Traditional => "Hant",
Self::Korean => "Hang",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum EastAsianLanguage {
Script(EastAsianScript),
NonEastAsian,
}
impl EastAsianLanguage {
#[must_use]
pub fn of(lang: &str) -> Self {
EastAsianScript::of(lang).map_or(Self::NonEastAsian, Self::Script)
}
#[must_use]
pub const fn script(self) -> Option<EastAsianScript> {
match self {
Self::Script(script) => Some(script),
Self::NonEastAsian => None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TextOutline {
None,
Solid {
width: Length,
color: OutlineColor,
},
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TextFill {
None,
Solid(DrawColor),
Gradient(Box<LinearGradient>),
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct TextShadow {
pub blur: Length,
pub distance: Length,
pub direction: i64,
pub color: Option<[u8; 3]>,
pub transparency: i64,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct TextGlow {
pub radius: Length,
pub color: Option<[u8; 3]>,
pub transparency: i64,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct TextReflection {
pub blur: Length,
pub distance: Length,
pub start_alpha: i64,
pub start_pos: i64,
pub end_alpha: i64,
pub end_pos: i64,
pub downward: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OutlineColor {
Rgb([u8; 3]),
Scheme,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MathStep {
Superscript,
SuperscriptBesideSubscript,
Subscript,
Numerator,
Denominator,
Degree,
UpperLimit(Limit),
LowerLimit(Limit),
Limit {
lower: bool,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Limit {
pub operator: char,
pub beside: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum MathStyle {
Display,
Text,
Script,
ScriptScript,
}
impl MathStyle {
#[must_use]
pub fn script_level(self) -> Option<f_office_fonts::ScriptLevel> {
match self {
Self::Display | Self::Text => None,
Self::Script => Some(f_office_fonts::ScriptLevel::Script),
Self::ScriptScript => Some(f_office_fonts::ScriptLevel::ScriptOfScript),
}
}
#[must_use]
pub fn inside(self, step: MathStep) -> Self {
match (step, self) {
(MathStep::Degree, _) | (_, Self::Script | Self::ScriptScript) => Self::ScriptScript,
(
MathStep::Superscript
| MathStep::SuperscriptBesideSubscript
| MathStep::Subscript
| MathStep::UpperLimit(_)
| MathStep::LowerLimit(_)
| MathStep::Limit { .. },
_,
)
| (MathStep::Numerator | MathStep::Denominator, Self::Text) => Self::Script,
(MathStep::Numerator | MathStep::Denominator, Self::Display) => Self::Text,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum SmallFractions {
#[default]
Off,
On,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum EquationMode {
#[default]
Inline,
Display,
DisplayText,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct MathScript {
steps: [Option<MathStep>; crate::params::MATH_SCRIPT_DEPTH],
control_sizes: [Option<i64>; crate::params::MATH_SCRIPT_DEPTH],
mode: EquationMode,
small_frac: SmallFractions,
large: bool,
on_axis: Option<char>,
cramped: bool,
outermost: OutermostStructure,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum OutermostStructure {
#[default]
Outside,
Inside { control_size: Option<i64> },
}
impl MathScript {
#[must_use]
pub fn display() -> Self {
Self {
mode: EquationMode::Display,
..Self::default()
}
}
#[must_use]
pub fn large(self) -> Self {
Self {
large: true,
..self
}
}
#[must_use]
pub fn is_large(self) -> bool {
self.large
}
#[must_use]
pub fn on_axis(self, ch: char) -> Self {
Self {
on_axis: Some(ch),
..self
}
}
#[must_use]
pub fn axis_character(self) -> Option<char> {
self.on_axis
}
#[must_use]
pub fn cramped(self) -> Self {
Self {
cramped: true,
..self
}
}
#[must_use]
pub fn is_cramped(self) -> bool {
self.cramped
}
#[must_use]
pub fn in_structure(self, control_size: Option<i64>) -> Self {
if self.outermost != OutermostStructure::Outside {
return self;
}
Self {
outermost: OutermostStructure::Inside { control_size },
..self
}
}
#[must_use]
pub fn without_outermost(self) -> Self {
Self {
outermost: OutermostStructure::Outside,
..self
}
}
#[must_use]
pub fn in_no_structure(self) -> bool {
self.outermost == OutermostStructure::Outside
}
#[must_use]
pub fn outermost_size(self) -> Option<i64> {
match self.outermost {
OutermostStructure::Outside => None,
OutermostStructure::Inside { control_size } => control_size,
}
}
#[must_use]
pub fn in_limit(self) -> bool {
self.steps()
.any(|step| matches!(step, MathStep::UpperLimit(_) | MathStep::LowerLimit(_)))
}
#[must_use]
pub fn in_script(self) -> bool {
self.steps().any(|step| {
matches!(
step,
MathStep::Superscript | MathStep::SuperscriptBesideSubscript | MathStep::Subscript
)
})
}
#[must_use]
pub fn inside(self, step: MathStep, control_size: Option<i64>) -> Self {
let size = match self.outermost {
OutermostStructure::Outside => control_size,
OutermostStructure::Inside {
control_size: outermost,
} => outermost,
};
let mut inner = self;
let free = inner
.steps
.iter_mut()
.zip(inner.control_sizes.iter_mut())
.find(|(s, _)| s.is_none());
if let Some((free_step, free_size)) = free {
*free_step = Some(step);
*free_size = size;
}
inner
}
#[must_use]
pub fn shifted_at(self, half_points: i64) -> bool {
self.control_sizes
.iter()
.flatten()
.all(|size| *size == half_points)
}
#[must_use]
pub fn at_paragraph_size(self, half_points: i64) -> Self {
let mut sized = self;
for (step, size) in sized.steps.iter().zip(sized.control_sizes.iter_mut()) {
if step.is_some() && size.is_none() {
*size = Some(half_points);
}
}
sized
}
#[must_use]
pub fn depth(self) -> usize {
self.steps.iter().flatten().count()
}
#[must_use]
pub fn is_display(self) -> bool {
!matches!(self.mode, EquationMode::Inline)
}
#[must_use]
pub(crate) const fn in_text_style(mut self) -> Self {
if matches!(self.mode, EquationMode::Display) {
self.mode = EquationMode::DisplayText;
}
self
}
#[must_use]
pub(crate) fn outermost_style(self) -> MathStyle {
if matches!(self.mode, EquationMode::Display) {
MathStyle::Display
} else {
MathStyle::Text
}
}
#[must_use]
pub(crate) const fn with_small_frac(mut self, small_frac: SmallFractions) -> Self {
self.small_frac = small_frac;
self
}
#[must_use]
pub(crate) fn step_style(self, style: MathStyle, step: MathStep) -> MathStyle {
if self.is_display()
&& self.small_frac == SmallFractions::Off
&& matches!(step, MathStep::Numerator | MathStep::Denominator)
{
match style {
MathStyle::Display => MathStyle::Text,
other => other,
}
} else {
style.inside(step)
}
}
#[must_use]
pub fn style(self) -> MathStyle {
self.steps().fold(self.outermost_style(), |style, step| {
self.step_style(style, step)
})
}
pub fn steps(self) -> impl Iterator<Item = MathStep> {
self.steps.into_iter().flatten()
}
pub fn steps_with_control_sizes(self) -> impl Iterator<Item = (MathStep, Option<i64>)> {
self.steps
.into_iter()
.zip(self.control_sizes)
.filter_map(|(step, size)| step.map(|step| (step, size)))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VerticalAlign {
Baseline,
Superscript,
Subscript,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CodeFormat {
font_ascii: Option<FontRef>,
font_hansi: Option<FontRef>,
font_cs: Option<Box<FontRef>>,
size: Option<i64>,
size_cs: Option<i64>,
bold: Option<bool>,
bold_cs: Option<bool>,
italic: Option<bool>,
italic_cs: Option<bool>,
color: CodeColor,
style: CodeStyle,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum CodeColor {
#[default]
Own,
Code(Option<Color>),
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
enum CodeStyle {
#[default]
Own,
Code(Option<String>),
}
impl CodeFormat {
#[must_use]
pub fn of(props: &RunProps) -> Self {
Self {
font_ascii: props.font_ascii.clone(),
font_hansi: props.font_hansi.clone(),
font_cs: props.font_cs.clone(),
size: props.size,
size_cs: props.size_cs,
bold: props.bold,
bold_cs: props.bold_cs,
italic: props.italic,
italic_cs: props.italic_cs,
color: CodeColor::Code(props.color),
style: CodeStyle::Own,
}
}
#[must_use]
pub(crate) fn with_style(self, style: Option<String>) -> Self {
Self {
style: CodeStyle::Code(style),
..self
}
}
#[must_use]
pub(crate) fn style_over<'a>(&'a self, own: Option<&'a str>) -> Option<&'a str> {
match &self.style {
CodeStyle::Own => own,
CodeStyle::Code(style) => style.as_deref(),
}
}
#[must_use]
pub fn with_own_color(self) -> Self {
Self {
color: CodeColor::Own,
..self
}
}
#[must_use]
pub fn over(&self, props: &RunProps) -> RunProps {
RunProps {
font_ascii: self.font_ascii.clone(),
font_hansi: self.font_hansi.clone(),
font_cs: self.font_cs.clone(),
size: self.size,
size_cs: self.size_cs,
bold: self.bold,
bold_cs: self.bold_cs,
italic: self.italic,
italic_cs: self.italic_cs,
color: match self.color {
CodeColor::Own => props.color,
CodeColor::Code(color) => color,
},
..props.clone()
}
}
}
impl RunProps {
#[must_use]
pub fn drawn_half_points(&self) -> i64 {
self.size
.filter(|size| *size > 0)
.unwrap_or(crate::params::DEFAULT_FONT_SIZE)
}
#[must_use]
pub fn uses_complex_formatting(&self) -> bool {
self.complex.unwrap_or(false) || self.rtl.unwrap_or(false)
}
pub fn apply(&mut self, other: &Self) {
macro_rules! apply_all {
($($field:ident),+ $(,)?) => {{
let Self { $($field,)+ unsupported } = other;
$(overlay(&mut self.$field, $field.as_ref());)+
self.unsupported.apply(unsupported);
}};
}
apply_all!(
font_ascii,
font_hansi,
bold,
italic,
size,
color,
underline,
strike,
changed,
shading,
highlight,
caps,
small_caps,
vertical,
math_script,
math,
position,
hidden,
phantom,
kern,
spacing,
scale,
outline,
text_fill,
shadow,
glow,
reflection,
legacy_shadow,
legacy_outline,
emboss,
imprint,
effect,
ligatures,
font_cs,
size_cs,
bold_cs,
italic_cs,
complex,
rtl,
field_rtl,
form_text,
font_east_asia,
east_asian_hint,
east_asian_language,
lang,
bidi_script,
bidi_class,
snap_to_grid,
bordered,
);
}
#[must_use]
pub fn east_asian_script(&self) -> Option<EastAsianScript> {
self.east_asian_language.and_then(EastAsianLanguage::script)
}
pub(crate) fn apply_style_layer(&mut self, other: &Self, defaults: &Self) {
let prev = (
self.bold,
self.bold_cs,
self.italic,
self.italic_cs,
self.caps,
self.small_caps,
self.hidden,
self.legacy_shadow,
self.legacy_outline,
self.emboss,
self.imprint,
);
self.apply(other);
self.bold = combine_toggle(prev.0, other.bold, defaults.bold);
self.bold_cs = combine_toggle(prev.1, other.bold_cs, defaults.bold_cs);
self.italic = combine_toggle(prev.2, other.italic, defaults.italic);
self.italic_cs = combine_toggle(prev.3, other.italic_cs, defaults.italic_cs);
self.caps = combine_toggle(prev.4, other.caps, defaults.caps);
self.small_caps = combine_toggle(prev.5, other.small_caps, defaults.small_caps);
self.hidden = combine_toggle(prev.6, other.hidden, defaults.hidden);
self.legacy_shadow = combine_toggle(prev.7, other.legacy_shadow, defaults.legacy_shadow);
self.legacy_outline = combine_toggle(prev.8, other.legacy_outline, defaults.legacy_outline);
self.emboss = combine_toggle(prev.9, other.emboss, defaults.emboss);
self.imprint = combine_toggle(prev.10, other.imprint, defaults.imprint);
}
}
fn combine_toggle(prev: Option<bool>, layer: Option<bool>, default: Option<bool>) -> Option<bool> {
if default == Some(true) {
layer.or(prev)
} else if layer == Some(true) {
Some(!prev.unwrap_or(false))
} else {
prev
}
}
impl RunProps {
#[must_use]
pub fn east_asian(&self) -> Self {
let font = self
.font_east_asia
.as_deref()
.cloned()
.or_else(|| self.font_hansi.clone())
.or_else(|| self.font_ascii.clone());
Self {
font_ascii: font.clone(),
font_hansi: font,
..self.clone()
}
}
fn complex_size(&self) -> Option<i64> {
if self.uses_complex_formatting() {
self.size_cs
} else {
self.size_cs.or(self.size)
}
}
#[must_use]
pub fn complex_script(&self) -> Self {
let font = self
.font_cs
.as_deref()
.cloned()
.or_else(|| self.font_ascii.clone());
Self {
font_ascii: font.clone(),
font_hansi: font,
size: self.complex_size(),
bold: self.bold_cs,
italic: self.italic_cs,
..self.clone()
}
}
#[must_use]
pub fn joins(&self, other: &Self) -> bool {
let italic = |props: &Self| props.italic == Some(true) || props.italic_cs == Some(true);
let math =
if self.math.is_some() == other.math.is_some() && !(italic(self) || italic(other)) {
self.math
} else {
other.math
};
let hint = |props: &Self| props.east_asian_hint.unwrap_or(false);
let east_asian_hint = if hint(self) == hint(other) {
self.east_asian_hint
} else {
other.east_asian_hint
};
let snap = |props: &Self| props.snap_to_grid.unwrap_or(true);
let snap_to_grid = if snap(self) == snap(other) {
self.snap_to_grid
} else {
other.snap_to_grid
};
if self.bidi_class == other.bidi_class
&& self.unsupported == other.unsupported
&& other.math == math
&& other.east_asian_hint == east_asian_hint
&& other.snap_to_grid == snap_to_grid
{
return self == other;
}
let measured_alike = Self {
bidi_class: self.bidi_class,
unsupported: self.unsupported.clone(),
math,
east_asian_hint,
snap_to_grid,
..other.clone()
};
*self == measured_alike
}
#[must_use]
pub fn hebrew_language(&self) -> bool {
self.bidi_script == Some(BidiScript::Hebrew)
}
#[must_use]
pub fn has_digit_face(&self) -> bool {
self.rtl.unwrap_or(false) && self.bidi_script != Some(BidiScript::Hebrew)
}
#[must_use]
pub fn complex_digits(&self) -> Self {
Self {
size: self.complex_size(),
bold: self.bold_cs,
italic: self.italic_cs,
..self.clone()
}
}
pub(crate) fn read(reader: &mut PartReader, rpr: NodeId) -> Self {
let mut props = Self::default();
props.read_into(reader, rpr);
props
}
pub(crate) fn read_into(&mut self, reader: &mut PartReader, rpr: NodeId) {
for child in reader.doc.child_elements(rpr) {
self.read_child(reader, child);
}
}
fn read_child(&mut self, reader: &mut PartReader, child: NodeId) {
let doc = reader.doc;
let Some(element) = doc.element(child) else {
return;
};
let local = element.name.local;
if doc.is(child, W, local)
&& let Some((property, shows)) = unsupported_property(reader, child, local)
{
self.unsupported.set(property, SetIn::read(shows, reader));
}
match local {
"rFonts" => self.read_fonts(reader, child),
"b" => self.bold = Some(off_also_for_none(doc, child)),
"i" => self.italic = Some(off_also_for_none(doc, child)),
"bCs" => self.bold_cs = Some(off_also_for_none(doc, child)),
"iCs" => self.italic_cs = Some(off_also_for_none(doc, child)),
"szCs" => self.size_cs = reader.font_size(child, "val"),
"rtl" => self.rtl = Some(off_also_for_none(doc, child)),
"cs" => self.complex = Some(off_also_for_none(doc, child)),
"bdr" => {
let visible = doc
.attribute(child, Some(W), "val")
.and_then(|name| BORDER_LINE.find(name))
.is_some_and(|(style, ..)| *style != LineStyle::None);
let frame = doc
.attribute(child, Some(W), "frame")
.and_then(on_off::read)
== Some(true);
self.bordered = Some(visible || frame);
}
"lang" => {
if let Some(lang) = doc.attribute(child, Some(W), "eastAsia") {
self.east_asian_language = Some(EastAsianLanguage::of(lang));
}
if let Some(lang) = doc.attribute(child, Some(W), "val") {
self.lang = Some(lang.into());
}
if let Some(lang) = doc.attribute(child, Some(W), "bidi") {
self.bidi_script = Some(BidiScript::of(lang));
self.bidi_class = Some(BidiLanguageClass::of(lang));
}
}
"caps" => self.caps = Some(off_also_for_none(doc, child)),
"smallCaps" => self.small_caps = Some(off_also_for_none(doc, child)),
"sz" => self.size = reader.font_size(child, "val"),
"color" => self.color = read_text_color(reader, child),
"u" => self.underline = reader.enumeration(child, "val", UNDERLINE),
"strike" => {
self.strike = Some(Strike::of(Strike::Single, off_also_for_none(doc, child)));
}
"dstrike" => {
self.strike = Strike::with_double(self.strike, off_also_for_none(doc, child));
}
"rPrChange" | "ins" | "moveTo" => self.changed = Some(true),
"shd" => self.shading = read_shading(reader, child),
"highlight" => {
self.highlight = reader
.enumeration(child, "val", HIGHLIGHT)
.map(|rgb| rgb.map_or(Color::Auto, Color::Rgb));
}
"vertAlign" => self.vertical = reader.enumeration(child, "val", RUN_V_ALIGN),
"position" => {
self.position = reader
.half_points(child, "val")
.and_then(Length::from_half_points);
}
"vanish" => self.hidden = Some(off_also_for_none(doc, child)),
"snapToGrid" => self.snap_to_grid = Some(off_also_for_none(doc, child)),
"kern" => self.kern = reader.half_points(child, "val"),
"spacing" => self.spacing = reader.twips(child, "val"),
"w" => self.scale = reader.text_scale(child, "val"),
local if doc.is(child, W14, local) => self.read_word_2010(reader, child, local),
local if doc.is(child, W, local) => self.read_legacy_effect(reader, child, local),
_ => {}
}
}
fn read_legacy_effect(&mut self, reader: &PartReader, child: NodeId, local: &str) {
let on = || Some(off_also_for_none(reader.doc, child));
match local {
"shadow" => self.legacy_shadow = on(),
"outline" => self.legacy_outline = on(),
"emboss" => self.emboss = on(),
"imprint" => self.imprint = on(),
_ => {}
}
}
fn read_word_2010(&mut self, reader: &mut PartReader, node: NodeId, local: &str) {
if let Some(effect) = TextEffect::named(local) {
if effect.draws_paths() {
self.effect = Some(true);
}
let shows = effect.shows(reader, node);
if effect == TextEffect::Shadow {
self.shadow = shows.then(|| text_shadow(reader, node));
} else if effect == TextEffect::Glow {
self.glow = shows.then(|| text_glow(reader, node));
} else if effect == TextEffect::Reflection {
self.reflection = shows.then(|| Box::new(text_reflection(reader, node)));
}
self.unsupported.set(
UnsupportedProperty::Effect(effect),
SetIn::read(shows, reader),
);
return;
}
match local {
"textOutline" => {
let shows = outline_fill_replaced(reader, node);
self.unsupported.set(
UnsupportedProperty::TextOutlineFill,
SetIn::read(shows, reader),
);
self.outline = text_outline(reader, node).or(self.outline);
}
"textFill" => {
let (fill, unsupported) = text_fill(reader, node);
self.unsupported.set(
UnsupportedProperty::TextFill,
SetIn::read(unsupported, reader),
);
self.text_fill = fill.or(self.text_fill.take());
}
"ligatures" => {
self.ligatures = reader
.doc
.attribute(node, Some(W14), "val")
.map(|v| v.starts_with("standard") || v == "all");
}
_ => {}
}
}
fn read_fonts(&mut self, reader: &mut PartReader, node: NodeId) {
if let Some(font) = font_ref(reader, node, "ascii") {
self.font_ascii = Some(font);
}
if let Some(font) = font_ref(reader, node, "hAnsi") {
self.font_hansi = Some(font);
}
if let Some(font) = font_ref(reader, node, "cs") {
self.font_cs = Some(Box::new(font));
}
if let Some(font) = font_ref(reader, node, "eastAsia") {
self.font_east_asia = Some(Box::new(font));
}
if let Some(hint) = reader.enumeration(node, "hint", HINT) {
self.east_asian_hint = Some(hint);
}
}
}
pub(super) static THEME_FONT: Values<FontRef> = Values::new(&THEME_FONTS);
static THEME_FONTS: [Case<FontRef>; 8] = [
own("majorAscii", FontRef::MajorLatin),
own("majorHAnsi", FontRef::MajorLatin),
own("minorAscii", FontRef::MinorLatin),
own("minorHAnsi", FontRef::MinorLatin),
own("majorBidi", FontRef::MajorBidi),
own("minorBidi", FontRef::MinorBidi),
own("majorEastAsia", FontRef::MajorEastAsia),
own("minorEastAsia", FontRef::MinorEastAsia),
];
pub(super) const HINT: &Values<bool> = &Values::new(&[
own("default", false),
own("eastAsia", true),
another("cs", false),
]);
fn font_ref(reader: &mut PartReader, node: NodeId, slot: &str) -> Option<FontRef> {
let theme_attribute = if slot == "cs" {
"cstheme".to_owned()
} else {
format!("{slot}Theme")
};
reader
.enumeration(node, &theme_attribute, &THEME_FONT)
.or_else(|| {
reader
.doc
.attribute(node, Some(W), slot)
.map(|name| FontRef::Name(name.to_owned()))
})
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Underline {
#[default]
None,
Single,
Words,
Double,
Thick,
Dotted,
DottedHeavy,
Dash,
DashedHeavy,
DashLong,
DashLongHeavy,
DotDash,
DashDotHeavy,
DotDotDash,
DashDotDotHeavy,
Wave,
WavyHeavy,
WavyDouble,
}
pub(crate) const UNDERLINE: &Values<Underline> = &Values::new(&[
own("single", Underline::Single),
own("none", Underline::None),
another("words", Underline::Words),
another("double", Underline::Double),
another("thick", Underline::Thick),
another("dotted", Underline::Dotted),
another("dottedHeavy", Underline::DottedHeavy),
another("dash", Underline::Dash),
another("dashedHeavy", Underline::DashedHeavy),
another("dashLong", Underline::DashLong),
another("dashLongHeavy", Underline::DashLongHeavy),
another("dotDash", Underline::DotDash),
another("dashDotHeavy", Underline::DashDotHeavy),
another("dotDotDash", Underline::DotDotDash),
another("dashDotDotHeavy", Underline::DashDotDotHeavy),
another("wave", Underline::Wave),
another("wavyHeavy", Underline::WavyHeavy),
another("wavyDouble", Underline::WavyDouble),
]);
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Strike {
#[default]
None,
Single,
Double,
}
impl Strike {
const fn of(kind: Self, on: bool) -> Self {
if on { kind } else { Self::None }
}
fn with_double(read: Option<Self>, on: bool) -> Option<Self> {
match read {
_ if on => Some(Self::Double),
Some(Self::Double) => Some(Self::None),
other => other,
}
}
#[must_use]
pub const fn is_on(self) -> bool {
!matches!(self, Self::None)
}
}
pub(super) const RUN_V_ALIGN: &Values<VerticalAlign> = &Values::new(&[
own("baseline", VerticalAlign::Baseline),
own("superscript", VerticalAlign::Superscript),
own("subscript", VerticalAlign::Subscript),
]);
const EMPHASIS_MARKS: [&str; 4] = ["dot", "comma", "circle", "underDot"];
fn unsupported_property(
reader: &mut PartReader,
node: NodeId,
local: &str,
) -> Option<(UnsupportedProperty, bool)> {
let doc = reader.doc;
let on = || off_also_for_none(doc, node);
let value = || doc.attribute(node, Some(W), "val");
let unsupported = match local {
"outline" => (UnsupportedProperty::Outline, on()),
"shadow" => (UnsupportedProperty::Shadow, on()),
"emboss" => (UnsupportedProperty::Emboss, on()),
"imprint" => (UnsupportedProperty::Imprint, on()),
"dstrike" => (UnsupportedProperty::DoubleStrike, on()),
"bdr" => (
UnsupportedProperty::Border,
value()
.and_then(|name| BORDER_LINE.find(name))
.is_some_and(|(style, ..)| *style != LineStyle::None),
),
"fitText" => (
UnsupportedProperty::FitText,
reader
.twips(node, "val")
.is_some_and(|width| width > Length::ZERO),
),
"em" => (
UnsupportedProperty::Emphasis,
value().is_some_and(|mark| EMPHASIS_MARKS.contains(&mark)),
),
"eastAsianLayout" => (
UnsupportedProperty::EastAsianLayout,
["combine", "vert"].into_iter().any(|name| {
doc.attribute(node, Some(W), name).and_then(on_off::read) == Some(true)
}),
),
_ => return None,
};
Some(unsupported)
}
fn emu_length_attr(reader: &mut PartReader, node: NodeId, name: &str) -> Length {
Length::from_emus(size(reader, node, name)).unwrap_or(Length::ZERO)
}
fn text_shadow(reader: &mut PartReader, node: NodeId) -> TextShadow {
let direction = reader
.or_missing_in(node, (Some(W14), "dir"), |value| {
f_office_drawingml::integer(value)
.filter(|angle| (0..f_office_units::scale::FULL_TURN).contains(angle))
})
.unwrap_or(0);
let doc = reader.doc;
let untransformed = percent(reader, node, "sx") == DRAWING_WHOLE
&& percent(reader, node, "sy") == DRAWING_WHOLE
&& percent(reader, node, "kx") == 0
&& percent(reader, node, "ky") == 0;
let transparency = transparency(reader, node)
.unwrap_or(0)
.clamp(0, DRAWING_WHOLE);
let color = untransformed
.then(|| {
f_office_drawingml::color::DrawColor::read_in(
doc,
node,
f_office_drawingml::color::ColorNames::Word2010,
reader.drawing_warnings(),
)
.and_then(|color| color.resolve(reader.scheme()))
.map(|(rgb, _)| [rgb.r, rgb.g, rgb.b])
})
.flatten();
TextShadow {
blur: emu_length_attr(reader, node, "blurRad"),
distance: emu_length_attr(reader, node, "dist"),
direction,
color,
transparency,
}
}
fn text_glow(reader: &mut PartReader, node: NodeId) -> TextGlow {
let radius = Length::from_emus(size(reader, node, "rad")).unwrap_or(Length::ZERO);
let transparency = transparency(reader, node)
.unwrap_or(0)
.clamp(0, DRAWING_WHOLE);
let color = f_office_drawingml::color::DrawColor::read_in(
reader.doc,
node,
f_office_drawingml::color::ColorNames::Word2010,
reader.drawing_warnings(),
)
.and_then(|color| color.resolve(reader.scheme()))
.map(|(rgb, _)| [rgb.r, rgb.g, rgb.b]);
TextGlow {
radius,
color,
transparency,
}
}
fn text_reflection(reader: &mut PartReader, node: NodeId) -> TextReflection {
let direction = reader
.or_missing_in(node, (Some(W14), "dir"), |value| {
f_office_drawingml::integer(value)
.filter(|angle| (0..f_office_units::scale::FULL_TURN).contains(angle))
})
.unwrap_or(f_office_units::scale::QUARTER_TURN);
let downward = direction == f_office_units::scale::QUARTER_TURN
&& percent(reader, node, "sx") == DRAWING_WHOLE
&& percent(reader, node, "sy") == -DRAWING_WHOLE
&& percent(reader, node, "kx") == 0
&& percent(reader, node, "ky") == 0;
TextReflection {
blur: emu_length_attr(reader, node, "blurRad"),
distance: emu_length_attr(reader, node, "dist"),
start_alpha: percent(reader, node, "stA").clamp(0, DRAWING_WHOLE),
start_pos: percent(reader, node, "stPos").clamp(0, DRAWING_WHOLE),
end_alpha: percent(reader, node, "endA").clamp(0, DRAWING_WHOLE),
end_pos: percent(reader, node, "endPos").clamp(0, DRAWING_WHOLE),
downward,
}
}
fn text_outline(reader: &mut PartReader, node: NodeId) -> Option<TextOutline> {
let doc = reader.doc;
if doc.child(node, W14, "noFill").is_some() {
return Some(TextOutline::None);
}
if doc.child(node, W14, "gradFill").is_some() {
return None;
}
let fill = doc.child(node, W14, "solidFill")?;
let color = if let Some(rgb) = doc.child(fill, W14, "srgbClr") {
match doc.attribute(rgb, Some(W14), "val").map(parse_color)? {
Color::Rgb(rgb) => OutlineColor::Rgb(rgb),
Color::Auto => return None,
}
} else {
doc.child(fill, W14, "schemeClr")?;
OutlineColor::Scheme
};
let width = reader
.or_missing_in(node, (Some(W14), "w"), f_office_drawingml::emu_length)
.unwrap_or(Length::ZERO);
Some(TextOutline::Solid { width, color })
}
fn outline_fill_replaced(reader: &mut PartReader, node: NodeId) -> bool {
let doc = reader.doc;
if doc.child(node, W14, "noFill").is_some() {
return false;
}
if doc.child(node, W14, "gradFill").is_some() {
return true;
}
doc.child(node, W14, "solidFill")
.is_some_and(|fill| translucent(reader, fill))
}
fn text_fill(reader: &mut PartReader, node: NodeId) -> (Option<TextFill>, bool) {
let doc = reader.doc;
if doc.child(node, W14, "noFill").is_some() {
return (Some(TextFill::None), false);
}
if let Some(grad) = doc.child(node, W14, "gradFill") {
return match LinearGradient::read_word2010(doc, grad, reader.drawing_warnings()) {
Some(gradient) => (Some(TextFill::Gradient(Box::new(gradient))), false),
None => (None, true),
};
}
if let Some(solid) = doc.child(node, W14, "solidFill") {
return match DrawColor::read_in(doc, solid, ColorNames::Word2010, reader.drawing_warnings())
{
Some(color) => (Some(TextFill::Solid(color)), false),
None => (None, translucent(reader, solid)),
};
}
(None, false)
}
fn translucent(reader: &mut PartReader, fill: NodeId) -> bool {
transparency(reader, fill).is_some_and(|transparency| transparency > 0)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum UnsupportedProperty {
Outline,
Shadow,
Emboss,
Imprint,
DoubleStrike,
Border,
FitText,
Emphasis,
EastAsianLayout,
Effect(TextEffect),
TextFill,
TextOutlineFill,
}
impl UnsupportedProperty {
#[cfg(test)]
pub const ALL: [Self; 16] = [
Self::Outline,
Self::Shadow,
Self::Emboss,
Self::Imprint,
Self::DoubleStrike,
Self::Border,
Self::FitText,
Self::Emphasis,
Self::EastAsianLayout,
Self::Effect(TextEffect::Glow),
Self::Effect(TextEffect::Shadow),
Self::Effect(TextEffect::Reflection),
Self::Effect(TextEffect::Scene),
Self::Effect(TextEffect::Depth),
Self::TextFill,
Self::TextOutlineFill,
];
#[must_use]
pub const fn feature(self) -> Feature {
match self {
Self::Outline | Self::Shadow | Self::Emboss | Self::Imprint | Self::Effect(_) => {
Feature::TextEffect
}
Self::DoubleStrike => Feature::DoubleStrike,
Self::Border => Feature::TextBorder,
Self::FitText => Feature::FitText,
Self::Emphasis | Self::EastAsianLayout => Feature::EastAsianLayout,
Self::TextFill => Feature::TextFill,
Self::TextOutlineFill => Feature::TextOutlineFill,
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct UnsupportedProperties(Vec<(UnsupportedProperty, SetIn<bool>)>);
impl UnsupportedProperties {
pub(crate) fn set(&mut self, property: UnsupportedProperty, shows: SetIn<bool>) {
match self.0.binary_search_by_key(&property, |(set, _)| *set) {
Ok(at) => {
if let Some((_, value)) = self.0.get_mut(at) {
*value = shows;
}
}
Err(at) => self.0.insert(at, (property, shows)),
}
}
pub(crate) fn shadow_drawn(&mut self) {
let shadow = UnsupportedProperty::Effect(TextEffect::Shadow);
self.0.retain(|(set, _)| *set != shadow);
}
pub(crate) fn glow_drawn(&mut self) {
let glow = UnsupportedProperty::Effect(TextEffect::Glow);
self.0.retain(|(set, _)| *set != glow);
}
pub(crate) fn reflection_drawn(&mut self) {
let reflection = UnsupportedProperty::Effect(TextEffect::Reflection);
self.0.retain(|(set, _)| *set != reflection);
}
pub(crate) fn legacy_effects_drawn(&mut self) {
self.0.retain(|(set, _)| {
!matches!(
set,
UnsupportedProperty::Outline
| UnsupportedProperty::Shadow
| UnsupportedProperty::Emboss
| UnsupportedProperty::Imprint
)
});
}
fn apply(&mut self, other: &Self) {
for (property, shows) in &other.0 {
self.set(*property, shows.clone());
}
}
pub fn shown(&self) -> impl Iterator<Item = (Feature, &std::rc::Rc<f_office_warnings::Name>)> {
self.0
.iter()
.filter(|(_, shows)| shows.value)
.map(|(property, shows)| (property.feature(), &shows.part))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum TextEffect {
Glow,
Shadow,
Reflection,
Scene,
Depth,
}
impl TextEffect {
fn named(local: &str) -> Option<Self> {
Some(match local {
"glow" => Self::Glow,
"shadow" => Self::Shadow,
"reflection" => Self::Reflection,
"scene3d" => Self::Scene,
"props3d" => Self::Depth,
_ => return None,
})
}
fn draws_paths(self) -> bool {
matches!(self, Self::Reflection | Self::Depth)
}
fn shows(self, reader: &mut PartReader, node: NodeId) -> bool {
let doc = reader.doc;
let seen = |reader: &mut PartReader| {
transparency(reader, node).is_none_or(|transparency| transparency < DRAWING_WHOLE)
};
match self {
Self::Glow => size(reader, node, "rad") > 0 && seen(reader),
Self::Shadow => scaled(reader, node) && seen(reader),
Self::Reflection => {
scaled(reader, node)
&& (percent(reader, node, "stA") > 0 || percent(reader, node, "endA") > 0)
}
Self::Scene => doc.child(node, W14, "camera").is_some_and(|camera| {
doc.attribute(camera, Some(W14), "prst") != Some("orthographicFront")
}),
Self::Depth => {
let bevel = ["bevelT", "bevelB"]
.into_iter()
.filter_map(|name| doc.child(node, W14, name))
.any(|bevel| size(reader, bevel, "w") > 0 && size(reader, bevel, "h") > 0);
bevel || size(reader, node, "extrusionH") > 0 || size(reader, node, "contourW") > 0
}
}
}
}
fn size(reader: &mut PartReader, node: NodeId, name: &str) -> i64 {
reader
.or_missing_in(node, (Some(W14), name), f_office_drawingml::emus)
.unwrap_or(0)
}
fn percent(reader: &mut PartReader, node: NodeId, name: &str) -> i64 {
reader
.or_missing_in(
node,
(Some(W14), name),
f_office_drawingml::color::percentage,
)
.unwrap_or(0)
}
fn scaled(reader: &mut PartReader, node: NodeId) -> bool {
percent(reader, node, "sx") != 0 && percent(reader, node, "sy") != 0
}
fn transparency(reader: &mut PartReader, node: NodeId) -> Option<i64> {
let doc = reader.doc;
let alpha = doc
.child_elements(node)
.find_map(|color| doc.child(color, W14, "alpha"))?;
reader.or_missing_in(
alpha,
(Some(W14), "val"),
f_office_drawingml::color::percentage,
)
}