use std::{collections::HashSet, sync::Arc};
use toml_edit::{InlineTable, Item, TableLike, Value};
use crate::{
builder::recipe::style::PlotStyle,
composition::style::{FixedAppearance, PlacementStyle},
operation::{self, OperationOptions},
recipe::{
codec::{array_items, field, invalid, table, Codec},
style::{capture_text, is_style, style_theme, text_field},
StyleSource,
},
text::{TextAlignment, TextLayout},
Result, Text, Theme,
};
use crate::recipe::schema::{self as grammar, Schema};
use super::{
placement::Payload, Canvas, CanvasHeader, CanvasLegendPolicy, LegendComposition, PanelPath,
TextPanel,
};
const TEXT_PANEL_STYLE: &[grammar::Field] = &[
grammar::custom("title", false, crate::recipe::style::text_schema),
grammar::custom("body", false, crate::recipe::style::text_schema),
];
const PANEL_STYLE_FIELDS: &[grammar::Field] = &[
grammar::optional::<Option<String>>("name"),
grammar::optional::<usize>("row"),
grammar::optional::<usize>("column"),
grammar::custom("plot", false, |ctx| {
crate::builder::recipe::style::schema(ctx, false)
}),
grammar::custom("text", false, text_panel_schema),
grammar::custom("asset", false, crate::composition::style::fixed_schema),
grammar::custom("frozen", false, crate::composition::style::fixed_schema),
];
const STYLE_HEADER: &[grammar::Field] = &[
grammar::mandatory::<usize>("start"),
grammar::optional::<usize>("span"),
grammar::custom("text", false, crate::recipe::style::text_schema),
];
pub(crate) fn text_panel_schema(ctx: &mut Schema) -> serde_json::Value {
grammar::record(ctx, TEXT_PANEL_STYLE)
}
fn panel_style_schema(ctx: &mut Schema) -> serde_json::Value {
let shape = grammar::with(
grammar::record(ctx, PANEL_STYLE_FIELDS),
grammar::exclusive(&["plot", "text", "asset", "frozen"]),
);
let names = ["name", "row", "column"];
grammar::with(
shape,
grammar::one_of(
[
&["name"][..],
&["name", "row", "column"],
&["row", "column"],
]
.into_iter()
.map(|fields| grammar::exact_values(&names, fields)),
),
)
}
pub(crate) fn schema(ctx: &mut Schema, root: bool) -> serde_json::Value {
ctx.named(
if root {
"CanvasStyleRoot"
} else {
"CanvasStyleChild"
},
|ctx| {
let shape = grammar::record(ctx, FIELDS);
if root {
grammar::with(shape, grammar::required(&["theme"]))
} else {
shape
}
},
)
}
pub(crate) struct TextPanelStyle {
title: Text,
body: Text,
}
impl TextPanelStyle {
pub(crate) fn read(item: &Item) -> Result<Self> {
let fields = grammar::record_fields(item, TEXT_PANEL_STYLE)?;
Ok(Self {
title: text_field(fields, "title")?,
body: text_field(fields, "body")?,
})
}
pub(crate) fn capture(panel: &TextPanel) -> Value {
let mut fields = InlineTable::new();
fields.insert("title", capture_text(&panel.title));
fields.insert("body", capture_text(&panel.body));
fields.into()
}
pub(crate) fn apply(self, target: &mut TextPanel) {
target.title.apply_appearance(self.title);
target.body.apply_appearance(self.body);
}
}
enum PanelAppearance {
Plot(Box<PlotStyle>),
Text(TextPanelStyle),
Fixed(FixedAppearance),
}
struct PanelStyle {
address: PanelPath,
content: PanelAppearance,
}
impl PanelStyle {
fn read(item: &Item, path: &str) -> Result<Self> {
let fields = grammar::record_fields(item, PANEL_STYLE_FIELDS)?;
let name: Option<String> = field(fields, "name", Some(None))?;
let address = if let Some(name) = name {
if name.is_empty() || fields.contains_key("row") != fields.contains_key("column") {
return Err(invalid(
"a named style owner may include its complete original anchor",
));
}
if fields.contains_key("row") {
field::<usize>(fields, "row", None)?;
field::<usize>(fields, "column", None)?;
}
PanelPath::from(name.as_str())
} else {
PanelPath::from((
field::<usize>(fields, "row", None)?,
field::<usize>(fields, "column", None)?,
))
};
let mut content = ["plot", "text", "asset", "frozen"]
.into_iter()
.filter_map(|name| fields.get(name).map(|item| (name, item)));
let (kind, item) = content
.next()
.ok_or_else(|| invalid("panel style is missing its content role"))?;
if content.next().is_some() {
return Err(invalid("panel style content roles are mutually exclusive"));
}
let content = match kind {
"plot" => PanelAppearance::Plot(Box::new(PlotStyle::read(
item,
&format!("{path}.plot"),
false,
)?)),
"text" => PanelAppearance::Text(TextPanelStyle::read(item)?),
"asset" | "frozen" => {
PanelAppearance::Fixed(FixedAppearance::read(item, kind == "frozen")?)
}
_ => unreachable!("current grid style roles"),
};
Ok(Self { address, content })
}
}
struct HeaderStyle {
start: usize,
span: usize,
text: Text,
}
fn capture_headers(headers: &[CanvasHeader]) -> Value {
let values: toml_edit::Array = headers
.iter()
.map(|header| {
let mut fields = InlineTable::new();
fields.insert("start", header.start.encode());
fields.insert("span", header.span.encode());
fields.insert("text", capture_text(&header.text));
Value::from(fields)
})
.collect();
values.into()
}
fn read_headers(fields: &dyn TableLike, name: &str) -> Result<Vec<HeaderStyle>> {
let Some(item) = fields.get(name) else {
return Ok(Vec::new());
};
let mut seen = HashSet::new();
array_items(item)?
.map(|item| {
let fields = grammar::record_fields(item, STYLE_HEADER)?;
let start: usize = field(fields, "start", None)?;
let span: usize = field(fields, "span", Some(1))?;
if span == 0
|| (name == "row_titles" && span != 1)
|| start.checked_add(span).is_none()
|| !seen.insert((start, span))
{
return Err(invalid(format!(
"{name}: invalid or duplicate header style role"
)));
}
Ok(HeaderStyle {
start,
span,
text: text_field(fields, "text")?,
})
})
.collect()
}
fn apply_headers(styles: Vec<HeaderStyle>, targets: &mut [CanvasHeader], name: &str) -> Result<()> {
for style in styles {
let target = targets
.iter_mut()
.find(|target| target.start == style.start && target.span == style.span)
.ok_or_else(|| {
invalid(format!(
"{name}: missing target header at {} spanning {}",
style.start, style.span
))
})?;
target.text.apply_appearance(style.text);
}
Ok(())
}
type CanvasStyleEdit = Box<dyn FnOnce(&mut Canvas) -> Result<()>>;
pub(crate) struct CanvasStyle {
theme: Option<Arc<Theme>>,
configure: CanvasStyleEdit,
panels: Vec<PanelStyle>,
placements: Vec<PlacementStyle>,
}
fn read_config(fields: &dyn TableLike) -> Result<CanvasStyleEdit> {
let title = text_field(fields, "title")?;
let subtitle = text_field(fields, "subtitle")?;
let caption = text_field(fields, "caption")?;
let legend = field(fields, "legend_policy", Some(CanvasLegendPolicy::PerPlot))?;
let composition = field(
fields,
"legend_composition",
Some(LegendComposition::Combined),
)?;
let panel_title = field::<Option<TextAlignment>>(fields, "panel_title_alignment", Some(None))?;
let panel_subtitle =
field::<Option<TextAlignment>>(fields, "panel_subtitle_alignment", Some(None))?;
let mut guides: [Option<TextLayout>; 3] = [None, None, None];
if let Some(item) = fields.get("guide_text_layouts") {
let fields = table(item, &["title", "entry", "number"])?;
for (slot, name) in guides.iter_mut().zip(["title", "entry", "number"]) {
*slot = field(fields, name, Some(None))?;
}
}
let rows = read_headers(fields, "row_headers")?;
let columns = read_headers(fields, "column_headers")?;
let titles = read_headers(fields, "row_titles")?;
Ok(Box::new(move |canvas| {
canvas.title.apply_appearance(title);
canvas.subtitle.apply_appearance(subtitle);
canvas.caption.apply_appearance(caption);
canvas.legend_policy = legend;
canvas.legend_composition = composition;
canvas.panel_title_alignment = panel_title;
canvas.panel_subtitle_alignment = panel_subtitle;
canvas.guide_text_layouts = guides;
apply_headers(rows, &mut canvas.row_headers, "row_headers")?;
apply_headers(columns, &mut canvas.column_headers, "column_headers")?;
apply_headers(titles, &mut canvas.row_titles, "row_titles")
}))
}
const FIELDS: &[grammar::Field] = &[
grammar::custom("scope", true, |_| grammar::literal("style")),
grammar::optional::<Theme>("theme"),
grammar::custom("title", false, crate::recipe::style::text_schema),
grammar::custom("subtitle", false, crate::recipe::style::text_schema),
grammar::custom("caption", false, crate::recipe::style::text_schema),
grammar::optional::<CanvasLegendPolicy>("legend_policy"),
grammar::optional::<LegendComposition>("legend_composition"),
grammar::optional::<Option<TextAlignment>>("panel_title_alignment"),
grammar::optional::<Option<TextAlignment>>("panel_subtitle_alignment"),
grammar::custom(
"guide_text_layouts",
false,
super::recipe::guide_layouts_schema,
),
grammar::custom("row_headers", false, |ctx| {
grammar::array(grammar::record(ctx, STYLE_HEADER))
}),
grammar::custom("column_headers", false, |ctx| {
grammar::array(grammar::record(ctx, STYLE_HEADER))
}),
grammar::custom("row_titles", false, |ctx| {
grammar::array(grammar::record(ctx, STYLE_HEADER))
}),
grammar::custom("panels", false, |ctx| {
grammar::array(panel_style_schema(ctx))
}),
grammar::custom("slot_placements", false, |ctx| {
grammar::array(crate::composition::style::schema(ctx))
}),
];
impl CanvasStyle {
pub(crate) fn read(item: &Item, path: &str, root: bool) -> Result<Self> {
let fields = grammar::record_fields(item, FIELDS)?;
if !is_style(item) {
return Err(invalid(format!("{path}: expected Canvas style scope")));
}
let theme = style_theme(fields, root)?;
let configure = read_config(fields)?;
let mut panels = Vec::new();
let mut seen = HashSet::new();
let mut anchors = HashSet::new();
if let Some(item) = fields.get("panels") {
for (index, item) in array_items(item)?.enumerate() {
let panel = PanelStyle::read(item, &format!("{path}.panels[{index}]"))?;
if !seen.insert(panel.address.clone()) {
return Err(invalid("duplicate Canvas style panel address"));
}
if let Some(fields) = item
.as_table_like()
.filter(|fields| fields.contains_key("row"))
{
let anchor = (
field::<usize>(fields, "row", None)?,
field::<usize>(fields, "column", None)?,
);
if !anchors.insert(anchor) {
return Err(invalid("duplicate original Canvas style anchor"));
}
}
panels.push(panel);
}
}
let mut placements = Vec::new();
if let Some(item) = fields.get("slot_placements") {
for (index, item) in array_items(item)?.enumerate() {
placements.push(PlacementStyle::read(
item,
&format!("{path}.slot_placements[{index}]"),
)?);
}
}
Ok(Self {
theme,
configure,
panels,
placements,
})
}
pub(crate) fn apply(self, canvas: &mut Canvas) -> Result<()> {
let Self {
theme,
configure,
panels,
placements,
} = self;
canvas.theme = theme;
configure(canvas)?;
Self::apply_content(panels, placements, canvas)
}
fn apply_content(
panels: Vec<PanelStyle>,
floating: Vec<PlacementStyle>,
canvas: &mut Canvas,
) -> Result<()> {
let placements = Arc::make_mut(&mut canvas.placements);
if placements
.slots()
.filter(super::placement::PanelSlot::is_filled)
.count()
!= panels.len()
{
return Err(invalid(
"complete Canvas style requires matching populated panel roles",
));
}
let mut seen = HashSet::new();
for panel in panels {
operation::check()?;
let [step] = panel.address.steps() else {
return Err(invalid("Canvas styles require a direct panel address"));
};
let index = placements.resolve_step(step)?;
if !seen.insert(index) {
return Err(invalid(
"multiple style declarations address the same target panel",
));
}
let target = placements
.payload_mut(index)
.ok_or_else(|| invalid("missing Canvas style target"))?;
match (panel.content, target) {
(PanelAppearance::Plot(style), Payload::Plot(plot)) => {
style.apply(plot)?;
placements.set_content_origin(index, None);
}
(PanelAppearance::Text(style), Payload::Text(text)) => {
style.apply(text);
placements.set_content_origin(index, None);
}
(PanelAppearance::Fixed(style), Payload::Fixed(fixed)) => style.apply(fixed)?,
_ => {
return Err(invalid(format!(
"incompatible Canvas style owner {:?}",
panel.address
)))
}
}
}
let slots = Arc::make_mut(&mut canvas.slot_placements);
if floating.len() != slots.len() {
return Err(invalid(
"Canvas style requires the corresponding ordered reservation placements",
));
}
for (index, (style, placement)) in floating.into_iter().zip(slots).enumerate() {
style
.apply(placement)
.map_err(|error| error.with_prefix(&format!("slot_placements[{index}]")))?;
}
Ok(())
}
}
impl Canvas {
pub(crate) fn capture_style(&self, root: bool) -> Result<Value> {
let mut fields = InlineTable::new();
fields.insert("scope", "style".into());
let fallback = Theme::publication();
let theme = if root {
Some(
self.get_theme()
.or(self.get_default_theme())
.unwrap_or(&fallback),
)
} else {
self.get_theme()
};
if let Some(theme) = theme {
fields.insert("theme", theme.encode());
}
self.capture_style_config(&mut fields);
let mut panels = toml_edit::Array::new();
for slot in self
.placements
.slots()
.filter(super::placement::PanelSlot::is_filled)
{
operation::check()?;
let mut fields = InlineTable::new();
fields.insert("row", slot.row().encode());
fields.insert("column", slot.column().encode());
if let Some(name) = slot.name() {
fields.insert("name", name.into());
}
let index = slot.row() * self.columns + slot.column();
let (kind, appearance) = match self
.placements
.payload(index)
.expect("actual populated owner")
{
Payload::Plot(plot) => ("plot", plot.capture_style(false)?),
Payload::Text(text) => ("text", TextPanelStyle::capture(text)),
Payload::Fixed(fixed) => (
if fixed.is_frozen() { "frozen" } else { "asset" },
FixedAppearance::capture(fixed),
),
Payload::Vacant | Payload::Reserved(_) => unreachable!("populated content"),
};
fields.insert(kind, appearance);
panels.push(Value::from(fields));
}
fields.insert("panels", panels.into());
if !self.slot_placements.is_empty() {
let placements = self
.slot_placements
.iter()
.map(PlacementStyle::capture)
.collect::<Result<toml_edit::Array>>()?;
fields.insert("slot_placements", placements.into());
}
Ok(fields.into())
}
fn capture_style_config(&self, fields: &mut InlineTable) {
for (name, text) in [
("title", &self.title),
("subtitle", &self.subtitle),
("caption", &self.caption),
] {
let appearance = text.appearance_only();
if appearance != Text::UNSET {
fields.insert(name, appearance.encode());
}
}
fields.insert("legend_policy", self.legend_policy.encode());
fields.insert("legend_composition", self.legend_composition.encode());
if let Some(alignment) = self.panel_title_alignment {
fields.insert("panel_title_alignment", alignment.encode());
}
if let Some(alignment) = self.panel_subtitle_alignment {
fields.insert("panel_subtitle_alignment", alignment.encode());
}
let mut guides = InlineTable::new();
for (name, layout) in ["title", "entry", "number"]
.into_iter()
.zip(&self.guide_text_layouts)
{
if let Some(layout) = layout {
guides.insert(name, layout.encode());
}
}
if !guides.is_empty() {
fields.insert("guide_text_layouts", guides.into());
}
for (name, headers) in [
("row_headers", &self.row_headers),
("column_headers", &self.column_headers),
("row_titles", &self.row_titles),
] {
if !headers.is_empty() {
fields.insert(name, capture_headers(headers));
}
}
}
pub fn apply_style<'a>(self, source: impl Into<StyleSource<'a>>) -> Result<Self> {
self.apply_style_with_operation(source, &OperationOptions::default())
}
pub fn apply_style_with_operation<'a>(
mut self,
source: impl Into<StyleSource<'a>>,
options: &OperationOptions,
) -> Result<Self> {
operation::run(options, || {
source.into().with_recipe(|recipe| {
CanvasStyle::read(recipe.style_root("canvas")?, "canvas", true)?.apply(&mut self)
})?;
self.check_recipe_science()?;
operation::checkpoint()?;
Ok(self)
})
}
}
pub(crate) fn project(item: &Item, parent: Option<&Theme>, root: bool) -> Result<Value> {
use crate::recipe::style::{
copy_fields, effective_theme, project_existing_style, project_text,
};
if is_style(item) {
return Ok(project_existing_style(item, parent, root)?.into());
}
let source = item
.as_table_like()
.ok_or_else(|| invalid("expected a Canvas declaration"))?;
if source.get("scope").and_then(Item::as_str) == Some("layout") {
return Err(invalid("a layout recipe retains no previous content style"));
}
let mut style = InlineTable::new();
style.insert("scope", "style".into());
if root {
style.insert("theme", effective_theme(source, parent)?.encode());
} else if let Some(theme) = field::<Option<Theme>>(source, "theme", Some(None))? {
style.insert("theme", theme.encode());
}
project_text(source, &mut style, &["title", "subtitle", "caption"])?;
copy_fields(
source,
&mut style,
&[
"legend_policy",
"legend_composition",
"panel_title_alignment",
"panel_subtitle_alignment",
"guide_text_layouts",
],
)?;
for name in ["row_headers", "column_headers", "row_titles"] {
if let Some(item) = source.get(name) {
let headers = Vec::<CanvasHeader>::decode(item, None)?;
style.insert(name, capture_headers(&headers));
}
}
project_contents(source, &mut style)?;
Ok(style.into())
}
fn project_contents(source: &dyn TableLike, style: &mut InlineTable) -> Result<()> {
use crate::recipe::style::copy_fields;
let mut panels = toml_edit::Array::new();
let mut placements = toml_edit::Array::new();
if let Some(items) = source.get("panels") {
for (index, item) in array_items(items)?.enumerate() {
operation::check()?;
let source = item
.as_table_like()
.ok_or_else(|| invalid("expected a panel declaration"))?;
if ["slot", "box", "at"]
.iter()
.any(|name| source.contains_key(name))
{
placements.push(crate::composition::style::project_placement(item)?);
continue;
}
if source.contains_key("reserve")
|| source.get("vacant").and_then(Item::as_bool) == Some(true)
{
continue;
}
let mut style = InlineTable::new();
copy_fields(source, &mut style, &["name", "row", "column"])?;
if let Some(plot) = source.get("plot") {
style.insert(
"plot",
crate::builder::recipe::style::project(plot, None, false)?,
);
} else if let Some(text) = source.get("text") {
style.insert(
"text",
TextPanelStyle::capture(&TextPanel::decode(text, None)?),
);
} else if let Some(kind) = ["asset", "frozen"]
.into_iter()
.find(|name| source.contains_key(name))
{
let mut fixed = InlineTable::new();
copy_fields(source, &mut fixed, &["fit", "position", "image_rendering"])?;
style.insert(kind, fixed.into());
} else {
return Err(invalid(format!("canvas.panels[{index}]: bound native content requires its actual configuration to extract style")));
}
panels.push(Value::from(style));
}
}
style.insert("panels", panels.into());
if !placements.is_empty() {
style.insert("slot_placements", placements.into());
}
Ok(())
}