lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! The single immutable guide: typed sections, resolved keys and
//! actual source occurrences, prepared before fonts or panel assignment.

mod composition;
mod projection;
pub(crate) mod scoped;

use std::sync::Arc;

use super::identity::PrimaryTitleIdentity;
use super::source::{LiteralDomain, Projection, SourceMapping};
use super::{GuideEntryIdentity, ResolvedGuideKey};
use crate::data::category::RawField;
use crate::layout::{AddressRole, ComponentAddress, PreparedTextRequirement, PreparedTextRole};
use crate::{guides::LegendComposition, Error, Result};

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum GuideSectionIdentity {
    Combined(PrimaryTitleIdentity),
    GroupStyle(RawField),
    Joint(RawField),
    HueColor(RawField),
    Literal(LiteralDomain),
    SupplementalSeries,
    ContinuousColor(RawField),
    Alpha(super::alpha::AlphaSectionIdentity),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct GuideKeySource {
    producer: crate::plots::PlotKind,
    contributor_address: ComponentAddress,
    source_ordinal: u32,
    layer_slot: crate::elements::LayerSlot,
    mapping: SourceMapping,
    projection: Projection,
    group_neutral_rgb: Option<crate::theme::OpaqueColor>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PreparedGuideEntry {
    pub(crate) identity: GuideEntryIdentity,
    pub(crate) display_label: Arc<crate::Text>,
    pub(crate) key: ResolvedGuideKey,
    pub(super) sources: Arc<[GuideKeySource]>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PreparedGuideSection {
    pub(crate) identity: GuideSectionIdentity,
    pub(crate) display_title: Arc<crate::Text>,
    pub(crate) body: GuideSectionBody,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum GuideSectionBody {
    Symbols(Arc<[PreparedGuideEntry]>),
    ContinuousColor(Arc<super::descriptor::ContinuousDescriptor>),
    Alpha(Arc<super::alpha::PreparedAlphaSection>),
}

impl PreparedGuideSection {
    pub(crate) fn entries(&self) -> &[PreparedGuideEntry] {
        match &self.body {
            GuideSectionBody::Symbols(entries) => entries,
            GuideSectionBody::Alpha(alpha) => &alpha.entries,
            GuideSectionBody::ContinuousColor(_) => &[],
        }
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct GuideCounts {
    pub(crate) sections: u32,
    pub(crate) entries: u32,
    pub(crate) points: u32,
    pub(crate) lines: u32,
    pub(crate) fills: u32,
    pub(crate) primary_source_keys: u32,
    pub(crate) observed_pair_source_keys: u32,
    pub(crate) labeled_layer_source_keys: u32,
    pub(crate) source_occurrences: u32,
}

#[derive(Debug, PartialEq, Eq)]
pub(crate) struct PreparedGuide {
    pub(crate) composition: LegendComposition,
    pub(crate) counts: GuideCounts,
    pub(crate) sections: Arc<[PreparedGuideSection]>,
}

/// A consumed guide retains its semantic owner even when routed to a facet
/// cell. Placement never reparents its section/title/entry addresses.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct GuideSlot {
    pub(crate) descriptor: Arc<PreparedGuide>,
    pub(crate) owner: ComponentAddress,
}

impl GuideSlot {
    pub(crate) fn new(
        descriptor: Arc<PreparedGuide>,
        parent: &ComponentAddress,
        position: crate::guides::LegendPosition,
    ) -> Result<Self> {
        Ok(Self {
            descriptor,
            owner: parent.child(super::address_role(position), 0)?,
        })
    }
}

fn count(value: usize) -> Result<u32> {
    u32::try_from(value).map_err(|_| Error::Render("discrete guide count overflow".into()))
}

pub(super) fn shared_slice<T>(values: Vec<T>) -> Result<Arc<[T]>> {
    let storage = std::alloc::Layout::array::<T>(values.len())
        .map_err(|_| Error::Render("discrete guide storage overflow".into()))?;
    std::alloc::Layout::new::<[std::sync::atomic::AtomicUsize; 2]>()
        .extend(storage)
        .map_err(|_| Error::Render("discrete guide Arc layout overflow".into()))?;
    Ok(values.into())
}

impl PreparedGuide {
    #[cfg(test)]
    pub(crate) fn prepare_for_test(
        plot: &crate::Plot,
        theme: &crate::text::TextRequestContext<'_, '_>,
        composition: LegendComposition,
    ) -> Result<Option<Arc<Self>>> {
        let operation = crate::font::canonical::OperationContext::new();
        let (mut inputs, _) =
            crate::plots::shared_x::prepare_plot(plot.description(), &operation, theme)?;
        for registered in &mut inputs.panels {
            registered.policy.guide_composition = composition;
        }
        crate::layout::interior::guide::prepare_discrete_guides(
            plot.description(),
            &mut inputs.panels,
            &operation,
            false,
        )
    }

    pub(crate) fn append_requirements(
        &self,
        requirements: &mut Vec<PreparedTextRequirement>,
        theme: &crate::text::TextRequestContext<'_, '_>,
        owner: &ComponentAddress,
        mut stage: Option<&mut crate::layout::kernel::PreparedStage<'_>>,
    ) -> Result<()> {
        for (ordinal, section) in self.sections.iter().enumerate() {
            let section_owner = owner.child(AddressRole::LegendSection, count(ordinal)?)?;
            PreparedTextRequirement::push_authored(
                requirements,
                section_owner.child(AddressRole::LegendTitle, 0)?,
                PreparedTextRole::LegendTitle,
                Some(&section.display_title),
                theme.guide_text_appearance(crate::guides::GuideTextRole::Title),
                false,
                stage.as_deref_mut(),
            )?;
            let eligible =
                crate::data::source::collect_source((0..section.entries().len()).map(Ok))?;
            for (index, entry) in section.entries().iter().enumerate() {
                if !entry
                    .display_label
                    .appearance(theme.guide_text_appearance(crate::guides::GuideTextRole::Entry))
                    .includes(index, &eligible)
                {
                    continue;
                }
                PreparedTextRequirement::push_authored(
                    requirements,
                    section_owner
                        .child(AddressRole::LegendEntry, count(index)?)?
                        .child(AddressRole::LegendLabel, 0)?,
                    PreparedTextRole::LegendLabel,
                    Some(&entry.display_label),
                    theme.guide_text_appearance(crate::guides::GuideTextRole::Entry),
                    false,
                    stage.as_deref_mut(),
                )?;
            }
            if let GuideSectionBody::ContinuousColor(color) = &section.body {
                let eligible =
                    crate::data::source::collect_source((0..color.numeric.labels.len()).map(Ok))?;
                for (index, label) in color.numeric.labels.iter().enumerate() {
                    if !theme
                        .guide_text_appearance(crate::guides::GuideTextRole::Number)
                        .includes(index, &eligible)
                    {
                        continue;
                    }
                    PreparedTextRequirement::push_into(
                        requirements,
                        section_owner.child(AddressRole::GuideLabel, count(index)?)?,
                        PreparedTextRole::LegendLabel,
                        count(index)?,
                        label,
                        &[],
                        theme.guide_text_appearance(crate::guides::GuideTextRole::Number),
                        stage.as_deref_mut(),
                    )?;
                }
                PreparedTextRequirement::push_authored(
                    requirements,
                    section_owner
                        .child(AddressRole::GuideLabel, count(color.numeric.labels.len())?)?,
                    PreparedTextRole::LegendLabel,
                    color.numeric.explanation.as_ref(),
                    theme.guide_text_appearance(crate::guides::GuideTextRole::Number),
                    false,
                    stage.as_deref_mut(),
                )?;
                if let Some(missing) = &color.missing {
                    PreparedTextRequirement::push_into(
                        requirements,
                        section_owner.child(AddressRole::GuideMissingBlock, 0)?,
                        PreparedTextRole::LegendLabel,
                        0,
                        &missing.label,
                        &[],
                        theme.guide_text_appearance(crate::guides::GuideTextRole::Entry),
                        stage.as_deref_mut(),
                    )?;
                }
            }
        }
        Ok(())
    }
}

fn add(target: &mut u32, value: u32) -> Result<()> {
    *target = u32::try_from(u128::from(*target) + u128::from(value))
        .map_err(|_| Error::Render("discrete guide count overflow".into()))?;
    Ok(())
}

fn incompatible(context: &str) -> Error {
    use crate::errors::{Diagnostic, DiagnosticKind, ErrorContext, OperationPhase};
    let constraint = "compatible semantic titles, labels, and styles; glyphs must match exactly";
    Error::Render(
        Diagnostic::new(
            DiagnosticKind::InvalidValue {
                value: None,
                constraint: constraint.into(),
            },
            format!("{context} requires {constraint}"),
        )
        .with_context(
            ErrorContext::new().with_operation(
                crate::operation::current_phase().unwrap_or(OperationPhase::Prepare),
            ),
        ),
    )
}

fn incompatible_entry(context: &str, entry: &PreparedGuideEntry, reason: &str) -> Error {
    use crate::data::RawKey;
    use crate::errors::{Diagnostic, DiagnosticKind, ErrorContext, OperationPhase};
    let (binding, value) = match &entry.identity {
        GuideEntryIdentity::Category { field, value } => {
            (Some(field.key().clone()), Some(value.key().clone()))
        }
        GuideEntryIdentity::Pair {
            group_field,
            group_value,
            hue_field,
            hue_value,
        } => (
            Some(RawKey::Tuple(vec![
                group_field.key().clone(),
                hue_field.key().clone(),
            ])),
            Some(RawKey::Tuple(vec![
                group_value.key().clone(),
                hue_value.key().clone(),
            ])),
        ),
        _ => (None, None),
    };
    let message = if let Some(value) = &value {
        format!("{context} requires compatible semantic titles, labels, and styles: raw identity {value:?} has {reason}")
    } else {
        format!("{context} requires compatible semantic titles, labels, and styles: {reason}")
    };
    let mut error_context = ErrorContext::new()
        .with_operation(crate::operation::current_phase().unwrap_or(OperationPhase::Prepare));
    if let Some(binding) = binding {
        error_context = error_context.with_binding(binding);
    }
    Error::Render(
        Diagnostic::new(
            DiagnosticKind::InvalidValue {
                value,
                constraint: "one raw guide identity must have a consistent display label and glyph"
                    .into(),
            },
            message,
        )
        .with_context(error_context),
    )
}

fn merge_entry(
    entries: &mut Vec<PreparedGuideEntry>,
    entry: PreparedGuideEntry,
    context: &str,
) -> Result<()> {
    for existing in entries.iter_mut() {
        if existing.identity == entry.identity {
            if existing.display_label != entry.display_label {
                return Err(incompatible_entry(context, &entry, "conflicting labels"));
            }
            if existing.key != entry.key {
                return Err(incompatible_entry(
                    context,
                    &entry,
                    &format!(
                        "incompatible {}; glyphs must match exactly",
                        existing.key.mismatched_component(&entry.key),
                    ),
                ));
            }
            let length = existing
                .sources
                .len()
                .checked_add(entry.sources.len())
                .ok_or_else(|| Error::Render("guide source occurrence count overflow".into()))?;
            let mut sources = Vec::new();
            crate::data::source::reserve_source(&mut sources, length)?;
            sources.extend(existing.sources.iter().chain(entry.sources.iter()).cloned());
            existing.sources = shared_slice(sources)?;
            return Ok(());
        }
    }
    crate::data::source::reserve_source(entries, 1)?;
    entries.push(entry);
    Ok(())
}

impl PreparedGuide {
    pub(crate) fn continuous(&self) -> Option<&Arc<super::descriptor::ContinuousDescriptor>> {
        self.sections
            .iter()
            .find_map(|section| match &section.body {
                GuideSectionBody::ContinuousColor(color) => Some(color),
                GuideSectionBody::Symbols(_) | GuideSectionBody::Alpha(_) => None,
            })
    }

    pub(crate) fn has_symbols(&self) -> bool {
        self.sections
            .iter()
            .any(|section| !section.entries().is_empty())
    }
}

#[test]
fn supplemental_entry_retains_the_actual_added_layer_slot() {
    use crate::elements::{LayerSlot, PointLayer};
    let values = || {
        (
            crate::NumericValues::new("x", [1., 2.]),
            crate::NumericValues::new("y", [3., 4.]),
        )
    };
    let (x, y) = values();
    let (unlabeled_x, unlabeled_y) = values();
    let (labeled_x, labeled_y) = values();
    let plot = crate::Plot::line(x, y)
        .point_layer(PointLayer::new(unlabeled_x, unlabeled_y))
        .point_layer(PointLayer::new(labeled_x, labeled_y).legend_label("Measured"))
        .erase();
    let appearance = crate::Theme::publication().resolve().unwrap();
    let service = crate::text::TextService::default();
    let theme = crate::text::TextRequestContext::new(&appearance, &service);
    let descriptor = PreparedGuide::prepare_for_test(&plot, &theme, LegendComposition::Combined)
        .unwrap()
        .unwrap();
    let entries = descriptor.sections[0].entries();
    assert_eq!(entries.len(), 1);
    assert_eq!(entries[0].display_label.as_str(), "Measured");
    assert_eq!(entries[0].sources.len(), 1);
    assert_eq!(entries[0].sources[0].layer_slot, LayerSlot::Added(1));
}