Skip to main content

lichtung_plot/canvas/
style.rs

1//! Canvas appearance is matched to real content owners, independently of the grid size.
2
3use std::{collections::HashSet, sync::Arc};
4
5use toml_edit::{InlineTable, Item, TableLike, Value};
6
7use crate::{
8    builder::recipe::style::PlotStyle,
9    composition::style::{FixedAppearance, PlacementStyle},
10    operation::{self, OperationOptions},
11    recipe::{
12        codec::{array_items, field, invalid, table, Codec},
13        style::{capture_text, is_style, style_theme, text_field},
14        StyleSource,
15    },
16    text::{TextAlignment, TextLayout},
17    Result, Text, Theme,
18};
19
20use crate::recipe::schema::{self as grammar, Schema};
21
22use super::{
23    placement::Payload, Canvas, CanvasHeader, CanvasLegendPolicy, LegendComposition, PanelPath,
24    TextPanel,
25};
26
27const TEXT_PANEL_STYLE: &[grammar::Field] = &[
28    grammar::custom("title", false, crate::recipe::style::text_schema),
29    grammar::custom("body", false, crate::recipe::style::text_schema),
30];
31
32const PANEL_STYLE_FIELDS: &[grammar::Field] = &[
33    grammar::optional::<Option<String>>("name"),
34    grammar::optional::<usize>("row"),
35    grammar::optional::<usize>("column"),
36    grammar::custom("plot", false, |ctx| {
37        crate::builder::recipe::style::schema(ctx, false)
38    }),
39    grammar::custom("text", false, text_panel_schema),
40    grammar::custom("asset", false, crate::composition::style::fixed_schema),
41    grammar::custom("frozen", false, crate::composition::style::fixed_schema),
42];
43
44const STYLE_HEADER: &[grammar::Field] = &[
45    grammar::mandatory::<usize>("start"),
46    grammar::optional::<usize>("span"),
47    grammar::custom("text", false, crate::recipe::style::text_schema),
48];
49
50pub(crate) fn text_panel_schema(ctx: &mut Schema) -> serde_json::Value {
51    grammar::record(ctx, TEXT_PANEL_STYLE)
52}
53fn panel_style_schema(ctx: &mut Schema) -> serde_json::Value {
54    let shape = grammar::with(
55        grammar::record(ctx, PANEL_STYLE_FIELDS),
56        grammar::exclusive(&["plot", "text", "asset", "frozen"]),
57    );
58    let names = ["name", "row", "column"];
59    grammar::with(
60        shape,
61        grammar::one_of(
62            [
63                &["name"][..],
64                &["name", "row", "column"],
65                &["row", "column"],
66            ]
67            .into_iter()
68            .map(|fields| grammar::exact_values(&names, fields)),
69        ),
70    )
71}
72
73pub(crate) fn schema(ctx: &mut Schema, root: bool) -> serde_json::Value {
74    ctx.named(
75        if root {
76            "CanvasStyleRoot"
77        } else {
78            "CanvasStyleChild"
79        },
80        |ctx| {
81            let shape = grammar::record(ctx, FIELDS);
82            if root {
83                grammar::with(shape, grammar::required(&["theme"]))
84            } else {
85                shape
86            }
87        },
88    )
89}
90
91pub(crate) struct TextPanelStyle {
92    title: Text,
93    body: Text,
94}
95impl TextPanelStyle {
96    pub(crate) fn read(item: &Item) -> Result<Self> {
97        let fields = grammar::record_fields(item, TEXT_PANEL_STYLE)?;
98        Ok(Self {
99            title: text_field(fields, "title")?,
100            body: text_field(fields, "body")?,
101        })
102    }
103
104    pub(crate) fn capture(panel: &TextPanel) -> Value {
105        let mut fields = InlineTable::new();
106        fields.insert("title", capture_text(&panel.title));
107        fields.insert("body", capture_text(&panel.body));
108        fields.into()
109    }
110
111    pub(crate) fn apply(self, target: &mut TextPanel) {
112        target.title.apply_appearance(self.title);
113        target.body.apply_appearance(self.body);
114    }
115}
116
117enum PanelAppearance {
118    Plot(Box<PlotStyle>),
119    Text(TextPanelStyle),
120    Fixed(FixedAppearance),
121}
122
123struct PanelStyle {
124    address: PanelPath,
125    content: PanelAppearance,
126}
127
128impl PanelStyle {
129    fn read(item: &Item, path: &str) -> Result<Self> {
130        let fields = grammar::record_fields(item, PANEL_STYLE_FIELDS)?;
131        let name: Option<String> = field(fields, "name", Some(None))?;
132        let address = if let Some(name) = name {
133            if name.is_empty() || fields.contains_key("row") != fields.contains_key("column") {
134                return Err(invalid(
135                    "a named style owner may include its complete original anchor",
136                ));
137            }
138            if fields.contains_key("row") {
139                field::<usize>(fields, "row", None)?;
140                field::<usize>(fields, "column", None)?;
141            }
142            PanelPath::from(name.as_str())
143        } else {
144            PanelPath::from((
145                field::<usize>(fields, "row", None)?,
146                field::<usize>(fields, "column", None)?,
147            ))
148        };
149        let mut content = ["plot", "text", "asset", "frozen"]
150            .into_iter()
151            .filter_map(|name| fields.get(name).map(|item| (name, item)));
152        let (kind, item) = content
153            .next()
154            .ok_or_else(|| invalid("panel style is missing its content role"))?;
155        if content.next().is_some() {
156            return Err(invalid("panel style content roles are mutually exclusive"));
157        }
158        let content = match kind {
159            "plot" => PanelAppearance::Plot(Box::new(PlotStyle::read(
160                item,
161                &format!("{path}.plot"),
162                false,
163            )?)),
164            "text" => PanelAppearance::Text(TextPanelStyle::read(item)?),
165            "asset" | "frozen" => {
166                PanelAppearance::Fixed(FixedAppearance::read(item, kind == "frozen")?)
167            }
168            _ => unreachable!("current grid style roles"),
169        };
170        Ok(Self { address, content })
171    }
172}
173
174struct HeaderStyle {
175    start: usize,
176    span: usize,
177    text: Text,
178}
179
180fn capture_headers(headers: &[CanvasHeader]) -> Value {
181    let values: toml_edit::Array = headers
182        .iter()
183        .map(|header| {
184            let mut fields = InlineTable::new();
185            fields.insert("start", header.start.encode());
186            fields.insert("span", header.span.encode());
187            fields.insert("text", capture_text(&header.text));
188            Value::from(fields)
189        })
190        .collect();
191    values.into()
192}
193
194fn read_headers(fields: &dyn TableLike, name: &str) -> Result<Vec<HeaderStyle>> {
195    let Some(item) = fields.get(name) else {
196        return Ok(Vec::new());
197    };
198    let mut seen = HashSet::new();
199    array_items(item)?
200        .map(|item| {
201            let fields = grammar::record_fields(item, STYLE_HEADER)?;
202            let start: usize = field(fields, "start", None)?;
203            let span: usize = field(fields, "span", Some(1))?;
204            if span == 0
205                || (name == "row_titles" && span != 1)
206                || start.checked_add(span).is_none()
207                || !seen.insert((start, span))
208            {
209                return Err(invalid(format!(
210                    "{name}: invalid or duplicate header style role"
211                )));
212            }
213            Ok(HeaderStyle {
214                start,
215                span,
216                text: text_field(fields, "text")?,
217            })
218        })
219        .collect()
220}
221
222fn apply_headers(styles: Vec<HeaderStyle>, targets: &mut [CanvasHeader], name: &str) -> Result<()> {
223    for style in styles {
224        let target = targets
225            .iter_mut()
226            .find(|target| target.start == style.start && target.span == style.span)
227            .ok_or_else(|| {
228                invalid(format!(
229                    "{name}: missing target header at {} spanning {}",
230                    style.start, style.span
231                ))
232            })?;
233        target.text.apply_appearance(style.text);
234    }
235    Ok(())
236}
237
238type CanvasStyleEdit = Box<dyn FnOnce(&mut Canvas) -> Result<()>>;
239
240pub(crate) struct CanvasStyle {
241    theme: Option<Arc<Theme>>,
242    configure: CanvasStyleEdit,
243    panels: Vec<PanelStyle>,
244    placements: Vec<PlacementStyle>,
245}
246
247fn read_config(fields: &dyn TableLike) -> Result<CanvasStyleEdit> {
248    let title = text_field(fields, "title")?;
249    let subtitle = text_field(fields, "subtitle")?;
250    let caption = text_field(fields, "caption")?;
251    let legend = field(fields, "legend_policy", Some(CanvasLegendPolicy::PerPlot))?;
252    let composition = field(
253        fields,
254        "legend_composition",
255        Some(LegendComposition::Combined),
256    )?;
257    let panel_title = field::<Option<TextAlignment>>(fields, "panel_title_alignment", Some(None))?;
258    let panel_subtitle =
259        field::<Option<TextAlignment>>(fields, "panel_subtitle_alignment", Some(None))?;
260    let mut guides: [Option<TextLayout>; 3] = [None, None, None];
261    if let Some(item) = fields.get("guide_text_layouts") {
262        let fields = table(item, &["title", "entry", "number"])?;
263        for (slot, name) in guides.iter_mut().zip(["title", "entry", "number"]) {
264            *slot = field(fields, name, Some(None))?;
265        }
266    }
267    let rows = read_headers(fields, "row_headers")?;
268    let columns = read_headers(fields, "column_headers")?;
269    let titles = read_headers(fields, "row_titles")?;
270    Ok(Box::new(move |canvas| {
271        canvas.title.apply_appearance(title);
272        canvas.subtitle.apply_appearance(subtitle);
273        canvas.caption.apply_appearance(caption);
274        canvas.legend_policy = legend;
275        canvas.legend_composition = composition;
276        canvas.panel_title_alignment = panel_title;
277        canvas.panel_subtitle_alignment = panel_subtitle;
278        canvas.guide_text_layouts = guides;
279        apply_headers(rows, &mut canvas.row_headers, "row_headers")?;
280        apply_headers(columns, &mut canvas.column_headers, "column_headers")?;
281        apply_headers(titles, &mut canvas.row_titles, "row_titles")
282    }))
283}
284
285const FIELDS: &[grammar::Field] = &[
286    grammar::custom("scope", true, |_| grammar::literal("style")),
287    grammar::optional::<Theme>("theme"),
288    grammar::custom("title", false, crate::recipe::style::text_schema),
289    grammar::custom("subtitle", false, crate::recipe::style::text_schema),
290    grammar::custom("caption", false, crate::recipe::style::text_schema),
291    grammar::optional::<CanvasLegendPolicy>("legend_policy"),
292    grammar::optional::<LegendComposition>("legend_composition"),
293    grammar::optional::<Option<TextAlignment>>("panel_title_alignment"),
294    grammar::optional::<Option<TextAlignment>>("panel_subtitle_alignment"),
295    grammar::custom(
296        "guide_text_layouts",
297        false,
298        super::recipe::guide_layouts_schema,
299    ),
300    grammar::custom("row_headers", false, |ctx| {
301        grammar::array(grammar::record(ctx, STYLE_HEADER))
302    }),
303    grammar::custom("column_headers", false, |ctx| {
304        grammar::array(grammar::record(ctx, STYLE_HEADER))
305    }),
306    grammar::custom("row_titles", false, |ctx| {
307        grammar::array(grammar::record(ctx, STYLE_HEADER))
308    }),
309    grammar::custom("panels", false, |ctx| {
310        grammar::array(panel_style_schema(ctx))
311    }),
312    grammar::custom("slot_placements", false, |ctx| {
313        grammar::array(crate::composition::style::schema(ctx))
314    }),
315];
316
317impl CanvasStyle {
318    pub(crate) fn read(item: &Item, path: &str, root: bool) -> Result<Self> {
319        let fields = grammar::record_fields(item, FIELDS)?;
320        if !is_style(item) {
321            return Err(invalid(format!("{path}: expected Canvas style scope")));
322        }
323        let theme = style_theme(fields, root)?;
324        let configure = read_config(fields)?;
325        let mut panels = Vec::new();
326        let mut seen = HashSet::new();
327        let mut anchors = HashSet::new();
328        if let Some(item) = fields.get("panels") {
329            for (index, item) in array_items(item)?.enumerate() {
330                let panel = PanelStyle::read(item, &format!("{path}.panels[{index}]"))?;
331                if !seen.insert(panel.address.clone()) {
332                    return Err(invalid("duplicate Canvas style panel address"));
333                }
334                if let Some(fields) = item
335                    .as_table_like()
336                    .filter(|fields| fields.contains_key("row"))
337                {
338                    let anchor = (
339                        field::<usize>(fields, "row", None)?,
340                        field::<usize>(fields, "column", None)?,
341                    );
342                    if !anchors.insert(anchor) {
343                        return Err(invalid("duplicate original Canvas style anchor"));
344                    }
345                }
346                panels.push(panel);
347            }
348        }
349        let mut placements = Vec::new();
350        if let Some(item) = fields.get("slot_placements") {
351            for (index, item) in array_items(item)?.enumerate() {
352                placements.push(PlacementStyle::read(
353                    item,
354                    &format!("{path}.slot_placements[{index}]"),
355                )?);
356            }
357        }
358        Ok(Self {
359            theme,
360            configure,
361            panels,
362            placements,
363        })
364    }
365
366    pub(crate) fn apply(self, canvas: &mut Canvas) -> Result<()> {
367        let Self {
368            theme,
369            configure,
370            panels,
371            placements,
372        } = self;
373        canvas.theme = theme;
374        configure(canvas)?;
375        Self::apply_content(panels, placements, canvas)
376    }
377
378    fn apply_content(
379        panels: Vec<PanelStyle>,
380        floating: Vec<PlacementStyle>,
381        canvas: &mut Canvas,
382    ) -> Result<()> {
383        let placements = Arc::make_mut(&mut canvas.placements);
384        if placements
385            .slots()
386            .filter(super::placement::PanelSlot::is_filled)
387            .count()
388            != panels.len()
389        {
390            return Err(invalid(
391                "complete Canvas style requires matching populated panel roles",
392            ));
393        }
394        let mut seen = HashSet::new();
395        for panel in panels {
396            operation::check()?;
397            let [step] = panel.address.steps() else {
398                return Err(invalid("Canvas styles require a direct panel address"));
399            };
400            let index = placements.resolve_step(step)?;
401            if !seen.insert(index) {
402                return Err(invalid(
403                    "multiple style declarations address the same target panel",
404                ));
405            }
406            let target = placements
407                .payload_mut(index)
408                .ok_or_else(|| invalid("missing Canvas style target"))?;
409            match (panel.content, target) {
410                (PanelAppearance::Plot(style), Payload::Plot(plot)) => {
411                    style.apply(plot)?;
412                    placements.set_content_origin(index, None);
413                }
414                (PanelAppearance::Text(style), Payload::Text(text)) => {
415                    style.apply(text);
416                    placements.set_content_origin(index, None);
417                }
418                (PanelAppearance::Fixed(style), Payload::Fixed(fixed)) => style.apply(fixed)?,
419                _ => {
420                    return Err(invalid(format!(
421                        "incompatible Canvas style owner {:?}",
422                        panel.address
423                    )))
424                }
425            }
426        }
427        let slots = Arc::make_mut(&mut canvas.slot_placements);
428        if floating.len() != slots.len() {
429            return Err(invalid(
430                "Canvas style requires the corresponding ordered reservation placements",
431            ));
432        }
433        for (index, (style, placement)) in floating.into_iter().zip(slots).enumerate() {
434            style
435                .apply(placement)
436                .map_err(|error| error.with_prefix(&format!("slot_placements[{index}]")))?;
437        }
438        Ok(())
439    }
440}
441
442impl Canvas {
443    pub(crate) fn capture_style(&self, root: bool) -> Result<Value> {
444        let mut fields = InlineTable::new();
445        fields.insert("scope", "style".into());
446        let fallback = Theme::publication();
447        let theme = if root {
448            Some(
449                self.get_theme()
450                    .or(self.get_default_theme())
451                    .unwrap_or(&fallback),
452            )
453        } else {
454            self.get_theme()
455        };
456        if let Some(theme) = theme {
457            fields.insert("theme", theme.encode());
458        }
459        self.capture_style_config(&mut fields);
460        let mut panels = toml_edit::Array::new();
461        for slot in self
462            .placements
463            .slots()
464            .filter(super::placement::PanelSlot::is_filled)
465        {
466            operation::check()?;
467            let mut fields = InlineTable::new();
468            fields.insert("row", slot.row().encode());
469            fields.insert("column", slot.column().encode());
470            if let Some(name) = slot.name() {
471                fields.insert("name", name.into());
472            }
473            let index = slot.row() * self.columns + slot.column();
474            let (kind, appearance) = match self
475                .placements
476                .payload(index)
477                .expect("actual populated owner")
478            {
479                Payload::Plot(plot) => ("plot", plot.capture_style(false)?),
480                Payload::Text(text) => ("text", TextPanelStyle::capture(text)),
481                Payload::Fixed(fixed) => (
482                    if fixed.is_frozen() { "frozen" } else { "asset" },
483                    FixedAppearance::capture(fixed),
484                ),
485                Payload::Vacant | Payload::Reserved(_) => unreachable!("populated content"),
486            };
487            fields.insert(kind, appearance);
488            panels.push(Value::from(fields));
489        }
490        fields.insert("panels", panels.into());
491        if !self.slot_placements.is_empty() {
492            let placements = self
493                .slot_placements
494                .iter()
495                .map(PlacementStyle::capture)
496                .collect::<Result<toml_edit::Array>>()?;
497            fields.insert("slot_placements", placements.into());
498        }
499        Ok(fields.into())
500    }
501
502    fn capture_style_config(&self, fields: &mut InlineTable) {
503        for (name, text) in [
504            ("title", &self.title),
505            ("subtitle", &self.subtitle),
506            ("caption", &self.caption),
507        ] {
508            let appearance = text.appearance_only();
509            if appearance != Text::UNSET {
510                fields.insert(name, appearance.encode());
511            }
512        }
513        fields.insert("legend_policy", self.legend_policy.encode());
514        fields.insert("legend_composition", self.legend_composition.encode());
515        if let Some(alignment) = self.panel_title_alignment {
516            fields.insert("panel_title_alignment", alignment.encode());
517        }
518        if let Some(alignment) = self.panel_subtitle_alignment {
519            fields.insert("panel_subtitle_alignment", alignment.encode());
520        }
521        let mut guides = InlineTable::new();
522        for (name, layout) in ["title", "entry", "number"]
523            .into_iter()
524            .zip(&self.guide_text_layouts)
525        {
526            if let Some(layout) = layout {
527                guides.insert(name, layout.encode());
528            }
529        }
530        if !guides.is_empty() {
531            fields.insert("guide_text_layouts", guides.into());
532        }
533        for (name, headers) in [
534            ("row_headers", &self.row_headers),
535            ("column_headers", &self.column_headers),
536            ("row_titles", &self.row_titles),
537        ] {
538            if !headers.is_empty() {
539                fields.insert(name, capture_headers(headers));
540            }
541        }
542    }
543
544    /// Apply compatible visual requests to this Canvas and its actual child owners.
545    pub fn apply_style<'a>(self, source: impl Into<StyleSource<'a>>) -> Result<Self> {
546        self.apply_style_with_operation(source, &OperationOptions::default())
547    }
548
549    /// Apply a complete Canvas style under the caller's cancellation options.
550    pub fn apply_style_with_operation<'a>(
551        mut self,
552        source: impl Into<StyleSource<'a>>,
553        options: &OperationOptions,
554    ) -> Result<Self> {
555        operation::run(options, || {
556            source.into().with_recipe(|recipe| {
557                CanvasStyle::read(recipe.style_root("canvas")?, "canvas", true)?.apply(&mut self)
558            })?;
559            self.check_recipe_science()?;
560            operation::checkpoint()?;
561            Ok(self)
562        })
563    }
564}
565
566pub(crate) fn project(item: &Item, parent: Option<&Theme>, root: bool) -> Result<Value> {
567    use crate::recipe::style::{
568        copy_fields, effective_theme, project_existing_style, project_text,
569    };
570    if is_style(item) {
571        return Ok(project_existing_style(item, parent, root)?.into());
572    }
573    let source = item
574        .as_table_like()
575        .ok_or_else(|| invalid("expected a Canvas declaration"))?;
576    if source.get("scope").and_then(Item::as_str) == Some("layout") {
577        return Err(invalid("a layout recipe retains no previous content style"));
578    }
579    let mut style = InlineTable::new();
580    style.insert("scope", "style".into());
581    if root {
582        style.insert("theme", effective_theme(source, parent)?.encode());
583    } else if let Some(theme) = field::<Option<Theme>>(source, "theme", Some(None))? {
584        style.insert("theme", theme.encode());
585    }
586    project_text(source, &mut style, &["title", "subtitle", "caption"])?;
587    copy_fields(
588        source,
589        &mut style,
590        &[
591            "legend_policy",
592            "legend_composition",
593            "panel_title_alignment",
594            "panel_subtitle_alignment",
595            "guide_text_layouts",
596        ],
597    )?;
598    for name in ["row_headers", "column_headers", "row_titles"] {
599        if let Some(item) = source.get(name) {
600            let headers = Vec::<CanvasHeader>::decode(item, None)?;
601            style.insert(name, capture_headers(&headers));
602        }
603    }
604    project_contents(source, &mut style)?;
605    Ok(style.into())
606}
607
608fn project_contents(source: &dyn TableLike, style: &mut InlineTable) -> Result<()> {
609    use crate::recipe::style::copy_fields;
610    let mut panels = toml_edit::Array::new();
611    let mut placements = toml_edit::Array::new();
612    if let Some(items) = source.get("panels") {
613        for (index, item) in array_items(items)?.enumerate() {
614            operation::check()?;
615            let source = item
616                .as_table_like()
617                .ok_or_else(|| invalid("expected a panel declaration"))?;
618            if ["slot", "box", "at"]
619                .iter()
620                .any(|name| source.contains_key(name))
621            {
622                placements.push(crate::composition::style::project_placement(item)?);
623                continue;
624            }
625            if source.contains_key("reserve")
626                || source.get("vacant").and_then(Item::as_bool) == Some(true)
627            {
628                continue;
629            }
630            let mut style = InlineTable::new();
631            copy_fields(source, &mut style, &["name", "row", "column"])?;
632            if let Some(plot) = source.get("plot") {
633                style.insert(
634                    "plot",
635                    crate::builder::recipe::style::project(plot, None, false)?,
636                );
637            } else if let Some(text) = source.get("text") {
638                style.insert(
639                    "text",
640                    TextPanelStyle::capture(&TextPanel::decode(text, None)?),
641                );
642            } else if let Some(kind) = ["asset", "frozen"]
643                .into_iter()
644                .find(|name| source.contains_key(name))
645            {
646                let mut fixed = InlineTable::new();
647                copy_fields(source, &mut fixed, &["fit", "position", "image_rendering"])?;
648                style.insert(kind, fixed.into());
649            } else {
650                return Err(invalid(format!("canvas.panels[{index}]: bound native content requires its actual configuration to extract style")));
651            }
652            panels.push(Value::from(style));
653        }
654    }
655    style.insert("panels", panels.into());
656    if !placements.is_empty() {
657        style.insert("slot_placements", placements.into());
658    }
659    Ok(())
660}