use std::path::PathBuf;
use toml_edit::{InlineTable, Item, TableLike, Value};
use crate::{
builder::recipe::Blueprint,
recipe::{
capture::Capture,
codec::{choice, field, invalid, table, Codec},
declaration::{BindingRequirement, BindingValueType},
resolve::Resolver,
},
Result,
};
use crate::recipe::schema::{self as grammar, Schema};
use super::{
fixed::FixedSource, placement::Source, CompositionSource, FixedPanel, ImageRendering,
ObjectFit, ObjectPosition, PanelImage,
};
mod plan;
pub(crate) use plan::{build_plan, schema as plan_schema, BaseBlueprint, StepBlueprint};
pub(crate) const CONTENT_FIELDS: &[&str] = &["plot", "text", "asset", "frozen", "native", "canvas"];
pub(crate) const FIXED_FIELDS: &[&str] = &["width", "height", "fit", "position", "image_rendering"];
pub(crate) fn content_properties(
ctx: &mut Schema,
allow_canvas: bool,
) -> Vec<(&'static str, serde_json::Value)> {
let mut properties = CONTENT_FIELDS
.iter()
.filter(|&&name| allow_canvas || name != "canvas")
.map(|&name| {
let value = match name {
"plot" => crate::builder::recipe::schema(ctx),
"canvas" => crate::canvas::recipe::schema(ctx),
"text" => ctx.reference::<crate::layout::TextPanel>(),
"asset" => grammar::any_of([
ctx.reference::<String>(),
crate::recipe::resolve::DataReference::content_schema(ctx),
]),
"frozen" | "native" => crate::recipe::resolve::DataReference::content_schema(ctx),
_ => unreachable!("current content field"),
};
(name, value)
})
.collect::<Vec<_>>();
properties.push(("use", ctx.reference::<String>()));
properties.push((
"binding_map",
grammar::dictionary(ctx.reference::<String>()),
));
properties
}
pub(crate) fn content_names(allow_canvas: bool) -> Vec<&'static str> {
CONTENT_FIELDS
.iter()
.copied()
.filter(|&name| allow_canvas || name != "canvas")
.chain(std::iter::once("use"))
.collect()
}
pub(crate) fn content_rules(shape: serde_json::Value, allow_canvas: bool) -> serde_json::Value {
let shape = grammar::with(shape, grammar::exclusive(&content_names(allow_canvas)));
grammar::with(
shape,
serde_json::json!({
"dependentRequired":{"binding_map":["use"]},
"not":{"required":["use","binding"]}
}),
)
}
pub(crate) fn definition_schema(ctx: &mut Schema) -> serde_json::Value {
ctx.named("Definition", |ctx| {
content_rules(grammar::object(content_properties(ctx, true), &[]), true)
})
}
pub(crate) fn base_schema(ctx: &mut Schema) -> serde_json::Value {
ctx.named("CompositionBase", |ctx| {
let mut properties = content_properties(ctx, true);
let native = properties
.iter_mut()
.find(|(name, _)| *name == "native")
.expect("native source");
native.1 = grammar::any_of([grammar::literal(true), native.1.clone()]);
content_rules(grammar::object(properties, &[]), true)
})
}
pub(crate) fn fixed_properties(
ctx: &mut Schema,
panel: bool,
) -> Vec<(&'static str, serde_json::Value)> {
FIXED_FIELDS
.iter()
.map(|&name| {
let value = match name {
"width" | "height" => ctx.reference::<Option<f64>>(),
"fit" if panel => ctx.reference::<ObjectFit>(),
"fit" => ctx.reference::<Option<ObjectFit>>(),
"position" if panel => ctx.reference::<ObjectPosition>(),
"position" => ctx.reference::<Option<ObjectPosition>>(),
"image_rendering" if panel => ctx.reference::<ImageRendering>(),
"image_rendering" => ctx.reference::<Option<ImageRendering>>(),
_ => unreachable!("current fixed-frame field"),
};
(name, value)
})
.collect()
}
const PLACEMENT_FIELDS: &[grammar::Field] = &[
grammar::optional::<crate::layout::PlacePoint>("at"),
grammar::optional::<crate::layout::BoxTarget>("box"),
grammar::custom("slot", false, |ctx| {
grammar::any_of([
grammar::pair(ctx.reference::<usize>()),
crate::layout::recipe::slot_reference_schema(ctx),
])
}),
grammar::optional::<Option<crate::layout::Anchor>>("anchor"),
grammar::optional::<Option<crate::layout::BoundaryRef>>("boundary"),
grammar::optional::<String>("binding"),
];
pub(crate) fn placement_schema(ctx: &mut Schema) -> serde_json::Value {
ctx.named("Placement",|ctx|{
let mut properties=content_properties(ctx,true);
properties.extend(fixed_properties(ctx,false));
let positions=grammar::record(ctx,PLACEMENT_FIELDS);
let positions=positions["properties"].as_object().expect("placement fields");
properties.extend(PLACEMENT_FIELDS.iter().map(|field|(field.name,positions[field.name].clone())));
let shape=content_rules(grammar::object(properties,&[]),true);
let shape=grammar::with(shape,grammar::exclusive(&["at","box","slot"]));
grammar::with(shape,serde_json::json!({"allOf":[
{"if":{"required":["at"]},"then":{"properties":{"fit":{"const":false},"position":{"const":false}}}},
{"if":{"anyOf":[{"required":["box"]},{"required":["slot"]}]},"then":{"properties":{"anchor":{"const":false},"width":{"const":false},"height":{"const":false}}}},
{"if":{"required":["image_rendering"],"properties":{"image_rendering":{"not":{"const":false}}}},"then":{"anyOf":[{"required":["asset"]},{"required":["use"]}]}}
]}))
})
}
choice!(ObjectFit {Contain=>"contain",Cover=>"cover",Fill=>"fill",None=>"none",ScaleDown=>"scale-down"});
choice!(ImageRendering {Auto=>"auto",CrispEdges=>"crisp-edges"});
const POSITION_COMPONENT_FIELDS: &[grammar::Field] = &[
grammar::optional::<f64>("fraction"),
grammar::optional::<f64>("offset"),
];
impl Codec for crate::layout::PositionComponent {
fn schema(ctx: &mut Schema) -> serde_json::Value {
grammar::record(ctx, POSITION_COMPONENT_FIELDS)
}
fn encode(&self) -> Value {
let (fraction, offset) = self.components();
let mut fields = InlineTable::new();
fields.insert("fraction", fraction.encode());
fields.insert("offset", offset.encode());
fields.into()
}
fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
let fields = grammar::record_fields(item, POSITION_COMPONENT_FIELDS)?;
Self::new(
field(fields, "fraction", Some(0.0))?,
field(fields, "offset", Some(0.0))?,
)
}
}
const OBJECT_POSITION_FIELDS: &[grammar::Field] = &[
grammar::mandatory::<crate::layout::PositionComponent>("x"),
grammar::mandatory::<crate::layout::PositionComponent>("y"),
];
impl Codec for ObjectPosition {
fn schema(ctx: &mut Schema) -> serde_json::Value {
let component = r"(?:left|right|top|bottom|center|0|[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?(?:%|px))";
let pattern = format!(r"^[\s_\u0085]*{component}(?:[\s_\u0085]+{component})?[\s_\u0085]*$");
grammar::any_of([
serde_json::json!({"type":"string","pattern":pattern}),
grammar::record(ctx, OBJECT_POSITION_FIELDS),
])
}
fn encode(&self) -> Value {
let mut fields = InlineTable::new();
fields.insert("x", self.x.encode());
fields.insert("y", self.y.encode());
fields.into()
}
fn decode(item: &Item, _: Option<Self>) -> Result<Self> {
if let Some(position) = item.as_str() {
return position.parse();
}
let fields = grammar::record_fields(item, OBJECT_POSITION_FIELDS)?;
Ok(Self::new(
field(fields, "x", None)?,
field(fields, "y", None)?,
))
}
}
pub(crate) enum SupplyContent {
Plot(Box<Blueprint>),
Canvas(Box<crate::canvas::recipe::Blueprint>),
Text(crate::layout::TextPanel),
Asset(PathBuf),
Bound(BindingRequirement),
}
impl SupplyContent {
pub(crate) fn permits_native_layout(&self) -> bool {
match self {
Self::Plot(_) | Self::Canvas(_) | Self::Text(_) => true,
Self::Bound(binding) => binding.value_type() == BindingValueType::Native,
Self::Asset(_) => false,
}
}
pub(crate) fn build(self, resolver: &mut Resolver<'_>) -> Result<CompositionSource> {
match self {
Self::Plot(plot) => Ok(CompositionSource(
Source::Plot(Box::new(plot.build_description(resolver)?)),
None,
)),
Self::Canvas(canvas) => Ok(canvas.build(resolver)?.into()),
Self::Text(text) => Ok(text.into()),
Self::Asset(path) => Ok(resolver.asset_path(&path)?.into()),
Self::Bound(binding) => binding.content(resolver),
}
}
pub(crate) fn permits_plot(&self) -> bool {
match self {
Self::Plot(_) => true,
Self::Bound(binding) => binding.value_type() == BindingValueType::Native,
_ => false,
}
}
}
pub(crate) fn read_content(
fields: &dyn TableLike,
path: &str,
fallback: Option<&str>,
requirements: &mut Vec<BindingRequirement>,
allow_canvas: bool,
) -> Result<SupplyContent> {
let mut content = CONTENT_FIELDS
.iter()
.filter_map(|key| fields.get(key).map(|item| (*key, item)));
let (key, item) = content
.next()
.ok_or_else(|| invalid(format!("{path}: missing content")))?;
if content.next().is_some() {
return Err(invalid(format!(
"{path}: content sources are mutually exclusive"
)));
}
let field = format!("{path}.{key}");
match key {
"plot" => {
let plot = Blueprint::read(item, &field, fallback, requirements)?;
Ok(SupplyContent::Plot(Box::new(plot)))
}
"canvas" if allow_canvas => {
let canvas =
crate::canvas::recipe::Blueprint::read(item, &field, fallback, requirements)?;
Ok(SupplyContent::Canvas(Box::new(canvas)))
}
"canvas" => Err(invalid("nested Canvas grid panels are not available")),
"text" => {
let text = crate::layout::TextPanel::decode(item, None)?;
Ok(SupplyContent::Text(text))
}
"asset" if item.is_str() => {
let path = PathBuf::from(item.as_str().expect("local path"));
Ok(SupplyContent::Asset(path))
}
"asset" | "frozen" | "native" => {
let value_type = match key {
"asset" => BindingValueType::Asset,
"frozen" => BindingValueType::Frozen,
_ => BindingValueType::Native,
};
let binding = BindingRequirement::content_role(item, field, value_type, fallback)?;
requirements.push(binding.clone());
Ok(SupplyContent::Bound(binding))
}
_ => unreachable!("closed content declarations"),
}
}
pub(crate) fn capture_content(
source: &CompositionSource,
fields: &mut InlineTable,
context: &mut Capture,
path: &str,
) -> Result<()> {
if let Some(origin) = &source.1 {
let role = match &source.0 {
Source::Fixed(FixedSource::Image(_)) => "asset",
Source::Fixed(FixedSource::Frozen(_)) => "frozen",
_ => "native",
};
fields.insert(
role,
context.content_reference(origin, role, &format!("{path}.{role}"))?,
);
return Ok(());
}
match &source.0 {
Source::Plot(plot) => {
fields.insert(
"plot",
plot.capture_recipe(context, &format!("{path}.plot"))?,
);
}
Source::Canvas(canvas) => {
fields.insert(
"canvas",
canvas.capture_recipe(
context,
&format!("{path}.canvas"),
crate::recipe::CanvasRecipeScope::Full,
)?,
);
}
Source::Text(text) => {
fields.insert("text", text.encode());
}
Source::Fixed(source) => capture_fixed(source, fields, context)?,
}
Ok(())
}
impl CompositionSource {
pub(crate) fn recipe_layout_report(&self) -> Result<crate::layout::LayoutReport> {
use crate::orchestrator::root::RootSource;
match &self.0 {
Source::Plot(plot) => crate::orchestrator::layout_report(RootSource::Plot(plot)),
Source::Canvas(canvas) => canvas.layout_report_inner(),
Source::Text(text) => crate::Canvas::grid(1, 1)?
.default_theme(None)
.panel(0, 0, text.clone())?
.layout_report_inner(),
Source::Fixed(_) => Err(invalid("layout action requires an editable native base")),
}
}
pub(crate) fn validate_recipe_content(&self) -> Result<()> {
let mut context = Capture::new();
let (root, value) = match &self.0 {
Source::Plot(plot) => ("plot", plot.capture_recipe(&mut context, "plot")?),
Source::Canvas(canvas) => (
"canvas",
canvas.capture_recipe(
&mut context,
"canvas",
crate::recipe::CanvasRecipeScope::Full,
)?,
),
_ => return Ok(()),
};
let recipe = crate::recipe::Recipe::from_capture(root, value, context)?;
recipe.check_warnings()
}
}
fn capture_fixed(
source: &FixedSource,
fields: &mut InlineTable,
context: &mut Capture,
) -> Result<()> {
match source {
FixedSource::Image(asset) => {
let value = if let Some(path) = asset.declared_path() {
Value::from(
path.to_str()
.ok_or_else(|| invalid("image paths require valid Unicode"))?,
)
} else {
context.independent("asset")
};
fields.insert("asset", value);
}
FixedSource::Frozen(_) => {
fields.insert("frozen", context.independent("frozen"));
}
}
Ok(())
}
pub(crate) struct FixedOptions {
requested: [Option<f64>; 2],
fit: ObjectFit,
position: ObjectPosition,
rendering: ImageRendering,
}
impl FixedOptions {
pub(crate) fn read(fields: &dyn TableLike) -> Result<Self> {
let requested = [
field(fields, "width", Some(None))?,
field(fields, "height", Some(None))?,
];
if requested
.into_iter()
.flatten()
.any(|n: f64| !n.is_finite() || n <= 0.)
{
return Err(invalid(
"fixed frame dimensions must be positive and finite",
));
}
Ok(Self {
requested,
fit: field(fields, "fit", Some(ObjectFit::Contain))?,
position: field(fields, "position", Some(ObjectPosition::default()))?,
rendering: field(fields, "image_rendering", Some(ImageRendering::Auto))?,
})
}
pub(crate) fn admit(self, source: FixedSource) -> Result<FixedPanel> {
let mut panel = match source {
FixedSource::Image(asset) => PanelImage::from(asset),
FixedSource::Frozen(output) => PanelImage::from(output),
};
if let Some(width) = self.requested[0] {
panel = panel.width(width);
}
if let Some(height) = self.requested[1] {
panel = panel.height(height);
}
panel
.fit(self.fit)
.position(self.position)
.image_rendering(self.rendering)
.admit()
}
}
pub(crate) fn capture_fixed_panel(
panel: &FixedPanel,
fields: &mut InlineTable,
context: &mut Capture,
origin: Option<&crate::data::DataSourceInfo>,
path: &str,
) -> Result<()> {
if let Some(origin) = origin {
let role = if panel.is_frozen() { "frozen" } else { "asset" };
fields.insert(
role,
context.content_reference(origin, role, &format!("{path}.{role}"))?,
);
} else {
capture_fixed(&panel.source, fields, context)?;
}
for (key, value) in ["width", "height"].into_iter().zip(panel.requested) {
if let Some(value) = value {
fields.insert(key, value.encode());
}
}
fields.insert("fit", panel.fit.encode());
fields.insert("position", panel.position.encode());
fields.insert("image_rendering", panel.rendering.encode());
Ok(())
}
use super::{placement::Target, Placement};
use crate::layout::{Anchor, BoundaryRef, BoxTarget, PlacePoint};
pub(crate) struct SupplyPlacement {
source: SupplyContent,
target: Target,
fit: Option<ObjectFit>,
position: Option<ObjectPosition>,
anchor: Option<Anchor>,
requested: [Option<f64>; 2],
rendering: Option<ImageRendering>,
boundary: Option<BoundaryRef>,
}
impl SupplyPlacement {
pub(crate) fn slot_borrow(&self) -> Result<(usize, usize)> {
if self.boundary.is_some() {
return Err(invalid(
"editable Canvas placements cannot use a frozen paint boundary",
));
}
match &self.target {
Target::Box(target) => target.reservation_anchor(),
Target::At(_) => None,
}
.ok_or_else(|| invalid("editable Canvas placements must borrow an actual reservation"))
}
pub(crate) fn build(self, resolver: &mut Resolver<'_>) -> Result<Placement> {
let placement = Placement {
source: self.source.build(resolver)?,
target: self.target,
fit: self.fit,
position: self.position,
anchor: self.anchor,
requested: self.requested,
rendering: self.rendering,
boundary: self.boundary,
};
placement.validate()?;
Ok(placement)
}
}
pub(crate) fn read_placement(
item: &Item,
path: &str,
fallback: Option<&str>,
requirements: &mut Vec<BindingRequirement>,
) -> Result<SupplyPlacement> {
let mut allowed = grammar::names(PLACEMENT_FIELDS);
allowed.extend(CONTENT_FIELDS);
allowed.extend(FIXED_FIELDS);
let fields = table(item, &allowed)?;
let binding = fields
.get("binding")
.map(|binding| String::decode(binding, None))
.transpose()?;
let fallback = binding.as_deref().or(fallback);
let target = match (fields.get("at"), fields.get("box"), fields.get("slot")) {
(Some(at), None, None) => Target::At(PlacePoint::decode(at, None)?),
(None, Some(target), None) => Target::Box(BoxTarget::decode(target, None)?),
(None, None, Some(slot)) => {
let reference = if slot.is_array() {
let [row, column]: [usize; 2] = Vec::<usize>::decode(slot, None)?
.try_into()
.map_err(|_| invalid("slot requires a row and column"))?;
crate::layout::RectRef::slot(row, column)
} else {
crate::layout::RectRef::decode(slot, None)?
};
if reference.reservation_anchor().is_none() {
return Err(invalid("slot placement requires a reserved-grid RectRef"));
}
Target::Box(reference.into())
}
_ => {
return Err(invalid(format!(
"{path}: placement requires exactly one point, box or slot"
)))
}
};
let options = SupplyPlacement {
source: read_content(fields, path, fallback, requirements, true)?,
target,
fit: field(fields, "fit", Some(None))?,
position: field(fields, "position", Some(None))?,
anchor: field(fields, "anchor", Some(None))?,
requested: [
field(fields, "width", Some(None))?,
field(fields, "height", Some(None))?,
],
rendering: field(fields, "image_rendering", Some(None))?,
boundary: field(fields, "boundary", Some(None))?,
};
if options
.requested
.into_iter()
.flatten()
.any(|n| !n.is_finite() || n <= 0.)
{
return Err(invalid("placement dimensions must be positive and finite"));
}
match options.target {
Target::At(_) if options.fit.is_some() || options.position.is_some() => {
return Err(invalid("fit and position require a placement box"))
}
Target::Box(_)
if options.anchor.is_some() || options.requested.iter().any(Option::is_some) =>
{
return Err(invalid("anchor and dimensions require a point placement"))
}
_ => {}
}
if options.rendering.is_some() && !fields.contains_key("asset") {
return Err(invalid("image_rendering requires image content"));
}
Ok(options)
}
impl CompositionSource {
pub(crate) fn check_recipe_science(&self, parent: Option<&crate::Theme>) -> Result<()> {
match &self.0 {
Source::Plot(plot) => {
let mut plot = (**plot).clone();
if let Some(theme) = parent {
plot.inherit_composition_theme(theme);
}
crate::recipe::figure::check_plot(&plot)
}
Source::Canvas(canvas) => {
let mut canvas = (**canvas).clone();
if let Some(theme) = parent.filter(|_| canvas.get_theme().is_none()) {
canvas = canvas.theme(theme.clone());
}
canvas.check_recipe_science()
}
_ => Ok(()),
}
}
}
impl Placement {
pub(crate) fn check_recipe_science(&self, parent: Option<&crate::Theme>) -> Result<()> {
self.source.check_recipe_science(parent)
}
pub(crate) fn capture_recipe(&self, context: &mut Capture, path: &str) -> Result<Value> {
let mut fields = InlineTable::new();
capture_content(&self.source, &mut fields, context, path)?;
match &self.target {
Target::At(at) => {
fields.insert("at", at.encode());
}
Target::Box(target) => {
fields.insert("box", target.encode());
}
}
if let Some(fit) = self.fit {
fields.insert("fit", fit.encode());
}
if let Some(position) = self.position {
fields.insert("position", position.encode());
}
if let Some(anchor) = self.anchor {
fields.insert("anchor", anchor.encode());
}
for (key, value) in ["width", "height"].into_iter().zip(self.requested) {
if let Some(value) = value {
fields.insert(key, value.encode());
}
}
if let Some(rendering) = self.rendering {
fields.insert("image_rendering", rendering.encode());
}
if let Some(boundary) = &self.boundary {
fields.insert("boundary", boundary.encode());
}
Ok(fields.into())
}
}