mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-17 18:04:48 +00:00
SmartArt: an item's opacity is read, written and drawn (#1906)
This commit is contained in:
@@ -129,7 +129,14 @@ fn placeholder(out: &mut Vec<GraphicItem>, space: &El, theme: &[Rgb], w: f32, h:
|
||||
}
|
||||
let Some(ty) = plot.els().find(|e| e.name.ends_with("Chart")) else { return };
|
||||
backdrop(out, space, theme, w, h);
|
||||
out.push(GraphicItem::Shape { rect: [0.0, 0.0, w, h], kind: ShapeKind::Rectangle, fill: None, stroke: Some(AXIS), stroke_width: 0.75 });
|
||||
out.push(GraphicItem::Shape {
|
||||
rect: [0.0, 0.0, w, h],
|
||||
kind: ShapeKind::Rectangle,
|
||||
fill: None,
|
||||
stroke: Some(AXIS),
|
||||
stroke_width: 0.75,
|
||||
alpha: 1.0,
|
||||
});
|
||||
let mut area = Rect { x: PAD, y: PAD, w: (w - 2.0 * PAD).max(1.0), h: (h - 2.0 * PAD).max(1.0) };
|
||||
if let Some(t) = title_of(chart, &read_series(ty, false, theme)) {
|
||||
area = title_block(out, &t, area);
|
||||
@@ -150,7 +157,14 @@ pub(crate) fn chartex_items(space: Option<&El>, w: f32, h: f32) -> Vec<GraphicIt
|
||||
if !(w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0) {
|
||||
return out;
|
||||
}
|
||||
out.push(GraphicItem::Shape { rect: [0.0, 0.0, w, h], kind: ShapeKind::Rectangle, fill: None, stroke: Some(AXIS), stroke_width: 0.75 });
|
||||
out.push(GraphicItem::Shape {
|
||||
rect: [0.0, 0.0, w, h],
|
||||
kind: ShapeKind::Rectangle,
|
||||
fill: None,
|
||||
stroke: Some(AXIS),
|
||||
stroke_width: 0.75,
|
||||
alpha: 1.0,
|
||||
});
|
||||
let mut area = Rect { x: PAD, y: PAD, w: (w - 2.0 * PAD).max(1.0), h: (h - 2.0 * PAD).max(1.0) };
|
||||
let chart = space.and_then(|s| s.child("cx:chart"));
|
||||
let title = chart.and_then(|c| c.child("cx:title")).and_then(|t| {
|
||||
|
||||
@@ -69,7 +69,14 @@ pub(super) fn stroke(out: &mut Vec<GraphicItem>, segs: Vec<PathSeg>, color: Rgb,
|
||||
}
|
||||
|
||||
fn swatch(out: &mut Vec<GraphicItem>, x: f32, y: f32, color: Rgb) {
|
||||
out.push(GraphicItem::Shape { rect: [x, y, SWATCH, SWATCH], kind: ShapeKind::Rectangle, fill: Some(color), stroke: None, stroke_width: 0.0 });
|
||||
out.push(GraphicItem::Shape {
|
||||
rect: [x, y, SWATCH, SWATCH],
|
||||
kind: ShapeKind::Rectangle,
|
||||
fill: Some(color),
|
||||
stroke: None,
|
||||
stroke_width: 0.0,
|
||||
alpha: 1.0,
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn seg(x0: f32, y0: f32, x1: f32, y1: f32) -> Vec<PathSeg> {
|
||||
|
||||
@@ -24,7 +24,7 @@ pub(super) fn backdrop(out: &mut Vec<GraphicItem>, space: &El, theme: &[Rgb], w:
|
||||
let stroke = ln.and_then(|l| fill_colour(l, theme));
|
||||
let stroke_width = ln.and_then(|l| l.attr("w")).and_then(|v| measure(v, 12_700.0)).unwrap_or(0.75).clamp(0.0, 20.0);
|
||||
if fill.is_some() || stroke.is_some() {
|
||||
out.push(GraphicItem::Shape { rect: [0.0, 0.0, w, h], kind: ShapeKind::Rectangle, fill, stroke, stroke_width });
|
||||
out.push(GraphicItem::Shape { rect: [0.0, 0.0, w, h], kind: ShapeKind::Rectangle, fill, stroke, stroke_width, alpha: 1.0 });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -544,7 +544,7 @@ fn markers(out: &mut Vec<GraphicItem>, pts: impl Iterator<Item = (f32, f32)>, co
|
||||
let size = s.marker_size.filter(|v| v.is_finite()).unwrap_or(MARKER).clamp(2.0, 72.0);
|
||||
let h = size / 2.0;
|
||||
let shape = |out: &mut Vec<GraphicItem>, rect: [f32; 4], kind: ShapeKind| {
|
||||
out.push(GraphicItem::Shape { rect, kind, fill: Some(colour), stroke: None, stroke_width: 0.0 });
|
||||
out.push(GraphicItem::Shape { rect, kind, fill: Some(colour), stroke: None, stroke_width: 0.0, alpha: 1.0 });
|
||||
};
|
||||
let mut strokes = Vec::new();
|
||||
for (x, y) in pts {
|
||||
|
||||
@@ -96,7 +96,7 @@ pub(super) fn radar(out: &mut Vec<GraphicItem>, c: &Chart, area: Rect) {
|
||||
for (i, p) in ring.iter().enumerate() {
|
||||
if c.radar_marks && s.values.get(i).copied().flatten().is_some() {
|
||||
let rect = [p.0 as f32 - MARKER / 2.0, p.1 as f32 - MARKER / 2.0, MARKER, MARKER];
|
||||
out.push(GraphicItem::Shape { rect, kind: ShapeKind::Ellipse, fill: Some(col), stroke: None, stroke_width: 0.0 });
|
||||
out.push(GraphicItem::Shape { rect, kind: ShapeKind::Ellipse, fill: Some(col), stroke: None, stroke_width: 0.0, alpha: 1.0 });
|
||||
}
|
||||
if let Some(text) = label_of(s, i) {
|
||||
labels.push(DataLabel { x: p.0 as f32, y: p.1 as f32, text, inside: false, pos: LabelPos::Above, off: 0.0 });
|
||||
|
||||
@@ -7,7 +7,7 @@ use craft_wordmodel::props::Rgb;
|
||||
|
||||
use super::Reader;
|
||||
use super::chart::text_w;
|
||||
use super::drawing_color::{color, paint};
|
||||
use super::drawing_color::{color, color_alpha, paint};
|
||||
use crate::package::{Rel, Rels, rel_is, rt};
|
||||
use crate::units::{MAX_LEN_PT, int};
|
||||
use crate::xml::El;
|
||||
@@ -164,7 +164,7 @@ fn shape(sp: &El, xf: Xf, b: [f64; 4], theme: &[Rgb], fit: f32, image: &mut dyn
|
||||
},
|
||||
};
|
||||
match geo {
|
||||
Geo::Kind(kind) => out.push(GraphicItem::Shape { rect, kind, fill, stroke, stroke_width }),
|
||||
Geo::Kind(kind) => out.push(GraphicItem::Shape { rect, kind, fill, stroke, stroke_width, alpha: fill_opacity(sppr, theme) }),
|
||||
Geo::Poly(pts, closed) if !pts.is_empty() => {
|
||||
// Flip in the box, then turn about its centre (clockwise, y down).
|
||||
let (s, c) = rot.to_radians().sin_cos();
|
||||
@@ -215,6 +215,12 @@ fn fill_of(sp: &El, sppr: Option<&El>, theme: &[Rgb]) -> Option<Rgb> {
|
||||
}
|
||||
}
|
||||
|
||||
/// How opaque a shape's own solid fill is, 0 to 1.
|
||||
fn fill_opacity(sppr: Option<&El>, theme: &[Rgb]) -> f32 {
|
||||
let solid = sppr.and_then(|p| p.child("a:solidFill"));
|
||||
solid.and_then(|f| color_alpha(f, theme, None)).map_or(1.0, |(_, t)| 1.0 - t / 100.0)
|
||||
}
|
||||
|
||||
/// A shape's outline colour and width in points (`a:ln`, else the style's line at 0.75 pt).
|
||||
fn line_of(sp: &El, sppr: Option<&El>, theme: &[Rgb]) -> (Option<Rgb>, f32) {
|
||||
let ln = sppr.and_then(|p| p.child("a:ln"));
|
||||
|
||||
@@ -156,6 +156,7 @@ impl Sh {
|
||||
/// keep the theme's background colour so adjacent nodes remain separated.
|
||||
fn recolor(&mut self, spec: &SmartArtSpec, i: usize) {
|
||||
let Some(c) = spec.items.get(i).and_then(|it| it.color) else { return };
|
||||
self.alpha = Some(u32::from(spec.items.get(i).and_then(|it| it.opacity).unwrap_or(100).min(100)) * 1000);
|
||||
for p in [&mut self.fill, &mut self.line] {
|
||||
if let Paint::Accent(_, tint) = *p {
|
||||
*p = Paint::Rgb(c, tint);
|
||||
@@ -788,7 +789,14 @@ pub fn data_xml(spec: &SmartArtSpec, drawing_rel: &str) -> String {
|
||||
Some(c) => {
|
||||
w.open("dgm:spPr", &[]);
|
||||
w.open("a:solidFill", &[]);
|
||||
w.empty("a:srgbClr", &[("val", &c.hex())]);
|
||||
match it.opacity {
|
||||
Some(o) => {
|
||||
w.open("a:srgbClr", &[("val", &c.hex())]);
|
||||
w.empty("a:alpha", &[("val", &(u32::from(o.min(100)) * 1000).to_string())]);
|
||||
w.close("a:srgbClr");
|
||||
}
|
||||
None => w.empty("a:srgbClr", &[("val", &c.hex())]),
|
||||
}
|
||||
w.close("a:solidFill");
|
||||
w.close("dgm:spPr");
|
||||
}
|
||||
@@ -1114,7 +1122,11 @@ pub(crate) fn spec_of(data: &El) -> Option<SmartArtSpec> {
|
||||
let text: String = p.child("dgm:t")?.child("a:p")?.children("a:r").filter_map(|r| r.child("a:t")).map(|t| t.text()).collect();
|
||||
let color =
|
||||
p.child("dgm:spPr").and_then(|s| s.child("a:solidFill")).and_then(|f| f.child("a:srgbClr")).and_then(|c| Rgb::parse(c.attr("val")?));
|
||||
Some(SmartArtItem { text, level: (*l)?, color })
|
||||
let opacity = color.and_then(|_| {
|
||||
let a = p.child("dgm:spPr")?.child("a:solidFill")?.child("a:srgbClr")?.child("a:alpha")?;
|
||||
u8::try_from((a.attr("val")?.parse::<u32>().ok()? / 1000).min(100)).ok()
|
||||
});
|
||||
Some(SmartArtItem { text, level: (*l)?, color, opacity })
|
||||
})
|
||||
.collect::<Option<Vec<_>>>()?;
|
||||
let spec = SmartArtSpec { layout, items, colors }.sanitized();
|
||||
@@ -1256,3 +1268,50 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod opacity_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn an_items_opacity_is_drawn_and_read_back() {
|
||||
let mut spec = SmartArtSpec::sample(SmartArtLayout::Venn);
|
||||
spec.items[0].color = Some(Rgb(0x12, 0x34, 0x56));
|
||||
spec.items[0].opacity = Some(12);
|
||||
let drawing = drawing_xml(&spec, 400.0, 250.0);
|
||||
assert!(drawing.contains("<a:alpha val=\"12000\""), "{drawing}");
|
||||
let items = smart_art_items(&spec, &[], 400.0, 250.0);
|
||||
let GraphicItem::Shape { alpha, .. } = &items[0] else { panic!("shape first") };
|
||||
assert!((alpha - 0.12).abs() < 0.01, "{alpha}");
|
||||
}
|
||||
#[test]
|
||||
fn an_omitted_opacity_on_a_coloured_item_is_solid_and_hostile_values_write_clamped() {
|
||||
let mut spec = SmartArtSpec::sample(SmartArtLayout::Venn);
|
||||
spec.items[0].color = Some(Rgb(0x12, 0x34, 0x56));
|
||||
let items = smart_art_items(&spec, &[], 400.0, 250.0);
|
||||
let GraphicItem::Shape { alpha, .. } = &items[0] else { panic!("shape first") };
|
||||
assert!((alpha - 1.0).abs() < 0.01, "{alpha}");
|
||||
spec.items[0].opacity = Some(250);
|
||||
let drawing = drawing_xml(&spec, 400.0, 250.0);
|
||||
assert!(!drawing.contains("val=\"250000\""), "{drawing}");
|
||||
assert!(drawing.contains("val=\"100000\""), "{drawing}");
|
||||
}
|
||||
#[test]
|
||||
fn opacity_of_0_50_and_100_survives_and_hostile_values_are_clamped() {
|
||||
for pct in [0u8, 50, 100] {
|
||||
let mut spec = SmartArtSpec::sample(SmartArtLayout::Venn);
|
||||
spec.items[0].color = Some(Rgb(1, 2, 3));
|
||||
spec.items[0].opacity = Some(pct);
|
||||
let items = smart_art_items(&spec, &[], 400.0, 250.0);
|
||||
let GraphicItem::Shape { alpha, .. } = &items[0] else { panic!("shape first") };
|
||||
assert!((alpha - f32::from(pct) / 100.0).abs() < 0.01, "{pct}: {alpha}");
|
||||
}
|
||||
let mut spec = SmartArtSpec::sample(SmartArtLayout::Venn);
|
||||
spec.items[0].color = Some(Rgb(1, 2, 3));
|
||||
spec.items[0].opacity = Some(250);
|
||||
spec.items[1].opacity = Some(40);
|
||||
spec.sanitize();
|
||||
assert_eq!(spec.items[0].opacity, Some(100), "above 100 is clamped");
|
||||
assert_eq!(spec.items[1].opacity, None, "no colour, no opacity");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -760,9 +760,14 @@ fn graphic_group(
|
||||
.iter()
|
||||
.take(10_000)
|
||||
.filter_map(|item| match item {
|
||||
GraphicItem::Shape { rect, kind, fill, stroke, stroke_width } if finite(rect) => {
|
||||
GraphicItem::Shape { rect, kind, fill, stroke, stroke_width, alpha } if finite(rect) => {
|
||||
let look = BoxLook {
|
||||
fill: fill.map(craft_wordmodel::fill::Fill::solid).filter(|_| *kind != ShapeKind::Line),
|
||||
fill: fill
|
||||
.map(|color| craft_wordmodel::fill::Fill::Solid {
|
||||
color,
|
||||
transparency: (1.0 - if alpha.is_finite() { alpha.clamp(0.0, 1.0) } else { 1.0 }) * 100.0,
|
||||
})
|
||||
.filter(|_| *kind != ShapeKind::Line),
|
||||
line: stroke.filter(|_| stroke_width.is_finite() && *stroke_width > 0.0).map(|c| (c, stroke_width.min(12.0))),
|
||||
..plain.clone()
|
||||
};
|
||||
|
||||
@@ -233,7 +233,7 @@ impl Graphic {
|
||||
/// no fill; a gradient, hatch or bitmap stands as its colour.
|
||||
fn fill_with(&self, default: Option<&str>, defs: &Defs) -> Option<Fill> {
|
||||
let color = self.fill_color.or(self.background.flatten());
|
||||
let solid = |c: Option<Rgb>| c.map(Fill::solid);
|
||||
let solid = |c: Option<Rgb>| c.map(|color| Fill::Solid { color, transparency: (100.0 - self.opacity.unwrap_or(100.0)).clamp(0.0, 100.0) });
|
||||
match self.fill.as_deref().or(default) {
|
||||
Some("none") => None,
|
||||
Some("solid") => solid(color),
|
||||
|
||||
@@ -121,7 +121,14 @@ fn a_diagram_is_saved_as_a_group_of_its_drawing() {
|
||||
let graphic = Graphic {
|
||||
kind: GraphicKind::Diagram,
|
||||
items: vec![
|
||||
GraphicItem::Shape { rect: [0.0, 0.0, 72.0, 36.0], kind: ShapeKind::RoundedRectangle, fill: Some(blue), stroke: None, stroke_width: 0.0 },
|
||||
GraphicItem::Shape {
|
||||
rect: [0.0, 0.0, 72.0, 36.0],
|
||||
kind: ShapeKind::RoundedRectangle,
|
||||
fill: Some(blue),
|
||||
stroke: None,
|
||||
stroke_width: 0.0,
|
||||
alpha: 1.0,
|
||||
},
|
||||
GraphicItem::Text {
|
||||
rect: [0.0, 0.0, 72.0, 36.0],
|
||||
text: "Plan".into(),
|
||||
@@ -132,7 +139,14 @@ fn a_diagram_is_saved_as_a_group_of_its_drawing() {
|
||||
font: None,
|
||||
angle: 0.0,
|
||||
},
|
||||
GraphicItem::Shape { rect: [90.0, 9.0, 18.0, 18.0], kind: ShapeKind::Arrow, fill: Some(blue), stroke: None, stroke_width: 0.0 },
|
||||
GraphicItem::Shape {
|
||||
rect: [90.0, 9.0, 18.0, 18.0],
|
||||
kind: ShapeKind::Arrow,
|
||||
fill: Some(blue),
|
||||
stroke: None,
|
||||
stroke_width: 0.0,
|
||||
alpha: 1.0,
|
||||
},
|
||||
],
|
||||
w: 108.0,
|
||||
h: 36.0,
|
||||
|
||||
@@ -39,7 +39,7 @@ fn open() -> Document {
|
||||
);
|
||||
let content = format!(
|
||||
r##"<office:document-content {NS_T} {NS_D}><office:automatic-styles>
|
||||
<style:style style:name="gr1" style:family="graphic"><style:graphic-properties svg:stroke-width="0.5pt" svg:stroke-color="#0000ff" draw:fill="solid" draw:fill-color="#ffcc00"/></style:style>
|
||||
<style:style style:name="gr1" style:family="graphic"><style:graphic-properties svg:stroke-width="0.5pt" svg:stroke-color="#0000ff" draw:fill="solid" draw:fill-color="#ffcc00" draw:opacity="50%"/></style:style>
|
||||
<style:style style:name="gr2" style:family="graphic"><style:graphic-properties draw:fill="solid" draw:fill-color="#00aa00"/></style:style>
|
||||
<style:style style:name="gr3" style:family="graphic"><style:graphic-properties svg:stroke-color="#000080" draw:fill-color="#99ccff" style:wrap="parallel" style:horizontal-pos="from-left" style:horizontal-rel="paragraph" style:vertical-pos="from-top" style:vertical-rel="paragraph"/></style:style>
|
||||
<style:style style:name="gr4" style:family="graphic"><style:graphic-properties svg:stroke-width="2pt" svg:stroke-color="#000000" style:wrap="run-through" style:run-through="background"/></style:style>
|
||||
@@ -88,6 +88,12 @@ fn shapes_open_with_their_kind_size_look_and_text() {
|
||||
let Some(InlineObject::Shape { float, .. }) = d.body[2].as_para().unwrap().objects.first() else { panic!() };
|
||||
assert_eq!((float.x, float.y), (72.0, 0.0));
|
||||
assert_eq!(float.wrap, Wrap::BehindText);
|
||||
let Some(InlineObject::Shape { fill: Some(craft_wordmodel::fill::Fill::Solid { transparency, .. }), .. }) =
|
||||
d.body[0].as_para().unwrap().objects.first()
|
||||
else {
|
||||
panic!("the first shape has a solid fill");
|
||||
};
|
||||
assert_eq!(*transparency, 50.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -100,6 +106,13 @@ fn shapes_round_trip() {
|
||||
}
|
||||
let back = import(&bytes).unwrap();
|
||||
assert_eq!(shapes(&back), shapes(&d));
|
||||
assert!(c.contains("draw:opacity=\"50%\""));
|
||||
let Some(InlineObject::Shape { fill: Some(craft_wordmodel::fill::Fill::Solid { transparency, .. }), .. }) =
|
||||
back.body[0].as_para().unwrap().objects.first()
|
||||
else {
|
||||
panic!("the first shape has a solid fill");
|
||||
};
|
||||
assert_eq!(*transparency, 50.0);
|
||||
assert_eq!(back.body[1].as_para().unwrap().text, d.body[1].as_para().unwrap().text);
|
||||
}
|
||||
|
||||
|
||||
@@ -53,7 +53,13 @@ pub(in crate::text) fn fill_attrs(
|
||||
}
|
||||
Some(f) => {
|
||||
let c = hex(f.main_color());
|
||||
format!("{} draw:fill=\"solid\" draw:fill-color=\"{c}\"", background(&c))
|
||||
let opacity = match f {
|
||||
Fill::Solid { transparency, .. } if *transparency > 0.0 => {
|
||||
format!(" draw:opacity=\"{:.0}%\"", (100.0 - transparency).clamp(0.0, 100.0))
|
||||
}
|
||||
_ => String::new(),
|
||||
};
|
||||
format!("{} draw:fill=\"solid\" draw:fill-color=\"{c}\"{opacity}", background(&c))
|
||||
}
|
||||
None => format!("{} draw:fill=\"none\"", background("transparent")),
|
||||
}
|
||||
|
||||
@@ -106,6 +106,9 @@ pub enum GraphicItem {
|
||||
stroke: Option<Rgb>,
|
||||
#[serde(default)]
|
||||
stroke_width: f32,
|
||||
/// Opacity of `fill`, 0 to 1.
|
||||
#[serde(default = "opaque")]
|
||||
alpha: f32,
|
||||
},
|
||||
/// A path: polygons, pie slices, line series.
|
||||
Path {
|
||||
@@ -153,3 +156,7 @@ pub enum PathSeg {
|
||||
Cubic(f32, f32, f32, f32, f32, f32),
|
||||
Close,
|
||||
}
|
||||
|
||||
fn opaque() -> f32 {
|
||||
1.0
|
||||
}
|
||||
|
||||
@@ -203,11 +203,14 @@ pub struct SmartArtItem {
|
||||
/// Fill of the item's shape in place of the style's colour.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub color: Option<Rgb>,
|
||||
/// Percent of `color` that shows (100 or none: solid). Needs `color`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub opacity: Option<u8>,
|
||||
}
|
||||
|
||||
impl SmartArtItem {
|
||||
pub fn new(text: impl Into<String>, level: u8) -> SmartArtItem {
|
||||
SmartArtItem { text: text.into(), level, color: None }
|
||||
SmartArtItem { text: text.into(), level, color: None, opacity: None }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -256,6 +259,7 @@ impl SmartArtSpec {
|
||||
let mut prev: Option<u8> = None;
|
||||
for it in &mut self.items {
|
||||
it.text = clean_text(&it.text);
|
||||
it.opacity = it.opacity.filter(|_| it.color.is_some()).map(|o| o.min(100));
|
||||
let most = prev.map_or(0, |p| p.saturating_add(1)).min(MAX_LEVEL);
|
||||
it.level = it.level.min(most);
|
||||
prev = Some(it.level);
|
||||
@@ -271,6 +275,7 @@ impl SmartArtSpec {
|
||||
pub fn clear_custom_colors(&mut self) {
|
||||
for it in &mut self.items {
|
||||
it.color = None;
|
||||
it.opacity = None;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user