use crate::layout::kernel::{FeedbackRound, SpatialRounding};
use crate::{Error, Result};
use super::spacing::ExactLength;
use super::{LocalMetric, RelativeSpacing, StrokeTheme};
pub(crate) fn stroke_style(stroke: &StrokeTheme) -> Result<crate::render::backend::LineStyle> {
stroke.validate()?;
let width = crate::layout::kernel::LayoutScalar::from_css_pixels(
f64::from(stroke.get_width()),
SpatialRounding::NearestEven,
)?;
if width.quanta() == 0 {
return Err(Error::Render("axis stroke collapses in CSS quanta".into()));
}
Ok(stroke.backend_style())
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FrameSides {
bits: u8,
}
macro_rules! side_field {
($field:ident, $get:ident, $bit:literal) => {
#[doc = concat!("Inspect whether the physical `", stringify!($field), "` side is present.")]
pub fn $get(&self) -> bool {
self.bits & $bit != 0
}
#[doc = concat!("Replace only the `", stringify!($field), "` side; at least one side must remain.")]
pub fn $field(mut self, value: bool) -> Result<Self> {
self.bits = if value {
self.bits | $bit
} else {
self.bits & !$bit
};
self.validate()?;
Ok(self)
}
};
}
impl FrameSides {
#[expect(
clippy::fn_params_excessive_bools,
reason = "the complete constructor explicitly names the four independent frame sides"
)]
pub fn new(top: bool, right: bool, bottom: bool, left: bool) -> Result<Self> {
let value = Self {
bits: u8::from(top)
| (u8::from(right) << 1)
| (u8::from(bottom) << 2)
| (u8::from(left) << 3),
};
value.validate()?;
Ok(value)
}
fn validate(&self) -> Result<()> {
if self.bits != 0 && self.bits & !15 == 0 {
Ok(())
} else {
Err(Error::Data(
"a present frame requires at least one side".into(),
))
}
}
side_field!(top, get_top, 1);
side_field!(right, get_right, 2);
side_field!(bottom, get_bottom, 4);
side_field!(left, get_left, 8);
pub(crate) fn drawing_order(&self) -> [bool; 4] {
[
self.get_bottom(),
self.get_right(),
self.get_top(),
self.get_left(),
]
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct FrameTheme {
pub(crate) sides: FrameSides,
pub(crate) stroke: StrokeTheme,
}
impl FrameTheme {
pub fn new(sides: FrameSides, stroke: StrokeTheme) -> Result<Self> {
let value = Self { sides, stroke };
value.validate()?;
Ok(value)
}
fn validate(&self) -> Result<()> {
self.sides.validate()?;
self.stroke.validate()
}
pub fn get_sides(&self) -> &FrameSides {
&self.sides
}
pub fn get_stroke(&self) -> &StrokeTheme {
&self.stroke
}
pub fn sides(self, sides: FrameSides) -> Result<Self> {
Self::new(sides, self.stroke)
}
pub fn stroke(self, stroke: StrokeTheme) -> Result<Self> {
Self::new(self.sides, stroke)
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct TickTheme {
pub(crate) stroke: StrokeTheme,
pub(crate) length: u32,
}
impl TickTheme {
pub fn new(stroke: StrokeTheme, length: u32) -> Result<Self> {
let value = Self { stroke, length };
value.validate()?;
Ok(value)
}
fn validate(&self) -> Result<()> {
self.stroke.validate()?;
if self.length == 0 {
return Err(Error::Data(
"tick length must be positive CSS pixels".into(),
));
}
Ok(())
}
pub fn get_stroke(&self) -> &StrokeTheme {
&self.stroke
}
pub fn get_length(&self) -> u32 {
self.length
}
pub fn stroke(self, stroke: StrokeTheme) -> Result<Self> {
Self::new(stroke, self.length)
}
pub fn length(self, length: u32) -> Result<Self> {
Self::new(self.stroke, length)
}
}
macro_rules! axis_spacing {
($($field:ident => $get:ident : $metric:literal),+ $(,)?) => {
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AxisSpacing { $(pub(crate) $field: RelativeSpacing),+ }
impl AxisSpacing {
pub fn new($($field: RelativeSpacing),+) -> Result<Self> { Ok(Self { $($field),+ }) }
$(
#[doc = concat!("Borrow the exact `", stringify!($field), "` relationship.")]
pub fn $get(&self) -> &RelativeSpacing { &self.$field }
#[doc = concat!("Replace only the `", stringify!($field), "` relationship.")]
pub fn $field(mut self, value: RelativeSpacing) -> Result<Self> {
self.$field = value;
self.revalidated()
}
)+
fn revalidated(self) -> Result<Self> { Self::new($(self.$field),+) }
pub(crate) fn relationships(&self) -> [&RelativeSpacing; 6] { [$(&self.$field),+] }
pub(crate) fn lengths(&self, tick: f64, title: f64) -> Result<AxisLengths> {
let metrics = [LocalMetric::css_pixels(tick)?, LocalMetric::css_pixels(title)?];
Ok(AxisLengths { $($field: self.$get().product(metrics[$metric])),+ })
}
}
#[derive(Debug)]
pub(crate) struct AxisLengths { $(pub(crate) $field: ExactLength),+ }
};
}
axis_spacing! {
x_tick_label_gap => get_x_tick_label_gap: 0,
y_tick_label_gap => get_y_tick_label_gap: 0,
x_title_tick_label_gap => get_x_title_tick_label_gap: 1,
x_title_without_tick_labels_gap => get_x_title_without_tick_labels_gap: 1,
y_title_tick_label_gap => get_y_title_tick_label_gap: 1,
y_title_edge_padding => get_y_title_edge_padding: 1,
}
#[derive(Clone, Debug, PartialEq)]
pub struct AxisTheme {
pub(crate) frame: Option<FrameTheme>,
pub(crate) cell_frame: Option<FrameTheme>,
pub(crate) ticks: Option<TickTheme>,
pub(crate) grid: Option<StrokeTheme>,
pub(crate) spacing: AxisSpacing,
}
pub(crate) struct AxisChrome<'a> {
pub(crate) frame: Option<&'a FrameTheme>,
pub(crate) grid: Option<&'a StrokeTheme>,
ticks: Option<&'a TickTheme>,
}
impl AxisChrome<'_> {
pub(crate) fn outward(
&self,
side: crate::layout::AxisSide,
present_ticks: bool,
) -> Result<ExactLength> {
let frame = self.frame.filter(|frame| match side {
crate::layout::AxisSide::Bottom => frame.get_sides().get_bottom(),
crate::layout::AxisSide::Left => frame.get_sides().get_left(),
});
let mut length = ExactLength::pixels(
frame.map_or(0.0, |frame| f64::from(frame.get_stroke().get_width()) / 2.0),
)?;
if let Some(ticks) = self.ticks.filter(|_| present_ticks) {
length = length
.add_pixels(f64::from(ticks.get_length()))?
.add_pixels(f64::from(ticks.get_stroke().get_width()) / 2.0)?;
}
Ok(length)
}
}
impl AxisTheme {
pub fn new(
frame: Option<FrameTheme>,
cell_frame: Option<FrameTheme>,
ticks: Option<TickTheme>,
grid: Option<StrokeTheme>,
spacing: AxisSpacing,
) -> Result<Self> {
let value = Self {
frame,
cell_frame,
ticks,
grid,
spacing,
};
value.validate()?;
Ok(value)
}
pub(crate) fn validate(&self) -> Result<()> {
if let Some(value) = self.get_frame() {
value.validate()?;
}
if let Some(value) = self.get_cell_frame() {
value.validate()?;
}
if let Some(value) = self.get_ticks() {
value.validate()?;
}
if let Some(value) = self.get_grid() {
value.validate()?;
}
Ok(())
}
pub fn get_frame(&self) -> Option<&FrameTheme> {
self.frame.as_ref()
}
pub fn get_cell_frame(&self) -> Option<&FrameTheme> {
self.cell_frame.as_ref()
}
pub fn get_ticks(&self) -> Option<&TickTheme> {
self.ticks.as_ref()
}
pub fn get_grid(&self) -> Option<&StrokeTheme> {
self.grid.as_ref()
}
pub fn get_spacing(&self) -> &AxisSpacing {
&self.spacing
}
pub(crate) fn coordinate_chrome(&self) -> AxisChrome<'_> {
AxisChrome {
frame: self.get_frame(),
grid: self.get_grid(),
ticks: self.get_ticks(),
}
}
pub(crate) fn cell_axis_chrome(&self) -> AxisChrome<'_> {
AxisChrome {
frame: None,
grid: None,
ticks: self.get_ticks(),
}
}
pub fn frame(self, frame: Option<FrameTheme>) -> Result<Self> {
Self::new(frame, self.cell_frame, self.ticks, self.grid, self.spacing)
}
pub fn cell_frame(self, cell_frame: Option<FrameTheme>) -> Result<Self> {
Self::new(self.frame, cell_frame, self.ticks, self.grid, self.spacing)
}
pub fn ticks(self, ticks: Option<TickTheme>) -> Result<Self> {
Self::new(self.frame, self.cell_frame, ticks, self.grid, self.spacing)
}
pub fn grid(self, grid: Option<StrokeTheme>) -> Result<Self> {
Self::new(self.frame, self.cell_frame, self.ticks, grid, self.spacing)
}
pub fn spacing(self, spacing: AxisSpacing) -> Result<Self> {
Self::new(self.frame, self.cell_frame, self.ticks, self.grid, spacing)
}
pub(crate) fn same_validated(&self, other: &Self) -> Result<bool> {
self.validate()?;
other.validate()?;
if self.frame != other.frame
|| self.cell_frame != other.cell_frame
|| self.ticks != other.ticks
|| self.grid != other.grid
{
return Ok(false);
}
for (left, right) in self
.get_spacing()
.relationships()
.into_iter()
.zip(other.get_spacing().relationships())
{
if !left.same(right) {
return Ok(false);
}
}
Ok(true)
}
pub(crate) fn observe_feedback(&self, round: &mut FeedbackRound) -> Result<()> {
for stroke in [
self.get_frame().map(FrameTheme::get_stroke),
self.get_cell_frame().map(FrameTheme::get_stroke),
self.get_ticks().map(TickTheme::get_stroke),
self.get_grid(),
] {
round.observe_count(usize::from(stroke.is_some()))?;
if let Some(stroke) = stroke {
round.observe_number(f64::from(stroke.get_width()))?;
round.observe_count(stroke.get_pattern() as usize)?;
for channel in [
stroke.get_color().red(),
stroke.get_color().green(),
stroke.get_color().blue(),
] {
round.observe_count(usize::from(channel))?;
}
round.observe_number(stroke.get_color().get_alpha())?;
}
}
for frame in [self.get_frame(), self.get_cell_frame()]
.into_iter()
.flatten()
{
for side in frame.get_sides().drawing_order() {
round.observe_count(usize::from(side))?;
}
}
if let Some(ticks) = self.get_ticks() {
round.observe_count(ticks.get_length() as usize)?;
}
for spacing in self.get_spacing().relationships() {
spacing.observe_feedback(round)?;
}
Ok(())
}
}
impl AxisLengths {
pub(crate) fn before(value: &ExactLength, anchor: f64) -> Result<f64> {
Self::pixels(value.before(anchor)?)
}
pub(crate) fn hard(value: &ExactLength) -> Result<f64> {
Self::pixels(value.round(SpatialRounding::Ceil)?)
}
#[expect(
clippy::cast_precision_loss,
reason = "the checked quanta bound guarantees exact integer conversion"
)]
fn pixels(value: crate::layout::kernel::LayoutScalar) -> Result<f64> {
if value.quanta().unsigned_abs() > (1_u64 << 53) {
return Err(Error::Render(
"axis length cannot retain exact CSS quanta".into(),
));
}
Ok(value.quanta() as f64 / 1024.0)
}
}