use std::sync::Arc;
use techy::core::node::{BuildId, NodeRef};
use techy::serialize::{DeserializeContext, DeserializeError, SerialValue};
use crate::dump::session::PayloadReaders;
use crate::lang::rewrites::blocks::{
argument_holds_blocks, run_holds_blocks, BlockCutter, BlockTransparent, CutItem, CutPart,
Cutting, StructureCx, StructureError,
};
use crate::lang::{Flm, PresPayload};
use crate::model::aspects::{BlockRole, BlockRoleAspect, InlineSpacing};
use crate::stdlib::backends::pres::payload::{bad, entries, field, map};
use crate::stdlib::backends::pres::read::payload_of;
use super::{AnnotationElement, ANNOTATION, TEXT_ARG};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct AnnotationPiece {
pub cut: usize,
pub index: usize,
pub count: usize,
}
impl AnnotationPiece {
pub fn is_first(&self) -> bool {
self.index == 0
}
pub fn is_last(&self) -> bool {
self.index + 1 == self.count
}
pub fn from_projection(value: &SerialValue) -> Result<AnnotationPiece, DeserializeError> {
let e = entries(ANNOTATION, value)?;
let number = |key: &str| match field(e, key) {
Some(SerialValue::Int(n)) if *n >= 0 => Ok(*n as usize),
Some(other) => Err(bad(ANNOTATION, format!("`{key}` must be a count, found {other:?}"))),
None => Err(bad(ANNOTATION, format!("`{key}` is missing"))),
};
Ok(AnnotationPiece { cut: number("cut")?, index: number("index")?, count: number("count")? })
}
}
impl PresPayload for AnnotationPiece {
fn project(&self) -> SerialValue {
let count = |n: usize| SerialValue::Int(n as i64);
map(vec![("cut", count(self.cut)), ("index", count(self.index)), ("count", count(self.count))])
}
}
pub fn payload_readers() -> PayloadReaders {
let mut readers = PayloadReaders::new();
readers.register(ANNOTATION, |value: &SerialValue, _cx: &mut DeserializeContext<'_, Flm>| {
AnnotationPiece::from_projection(value).map(|record| Arc::new(record) as Arc<dyn PresPayload>)
});
readers
}
const TEXT_INDEX: usize = 0;
impl BlockRoleAspect for AnnotationElement {
fn block_role(&self, node: &NodeRef<'_, Flm>) -> BlockRole {
if argument_holds_blocks(node, TEXT_INDEX) {
BlockRole::Block
} else {
BlockRole::Inline(InlineSpacing::CONTENT)
}
}
}
enum Plan {
Piece(Vec<BuildId>, bool),
Through(CutItem),
}
impl BlockTransparent for AnnotationElement {
fn cut(
&self,
node: NodeRef<'_, Flm>,
cx: &mut StructureCx<'_>,
cutter: &mut dyn BlockCutter,
) -> Result<Cutting, StructureError> {
if payload_of::<AnnotationPiece>(&node).is_some() {
return Ok(Cutting::Default);
}
let run: Vec<NodeRef<'_, Flm>> =
node.argument_content_nodes(TEXT_INDEX).map(|content| content.iter().collect()).unwrap_or_default();
if !run_holds_blocks(&run) {
return Ok(Cutting::Default);
}
let cut = cutter.new_cut_number();
let mut plans = Vec::new();
let mut stretch = Vec::new();
for item in cutter.restage_and_classify(cx, &run)? {
match item {
CutItem::Inline(_) | CutItem::Blank(_) => stretch.push(item),
CutItem::Marker(_) => {
flush(&mut stretch, &mut plans);
plans.push(Plan::Through(item));
}
CutItem::Block(id) => {
flush(&mut stretch, &mut plans);
plans.push(Plan::Piece(vec![id], true));
}
}
}
flush(&mut stretch, &mut plans);
let count = plans.iter().filter(|plan| matches!(plan, Plan::Piece(..))).count();
let mut items = Vec::with_capacity(plans.len());
let mut index = 0;
for plan in plans {
match plan {
Plan::Through(item) => items.push(item),
Plan::Piece(content, block) => {
let record = Arc::new(AnnotationPiece { cut, index, count });
let part = vec![(CutPart::ArgumentNamed(TEXT_ARG.to_string()), content)];
let id = cutter.rebuild(cx, &node, part, Some(record))?;
items.push(if block { CutItem::Block(id) } else { CutItem::Inline(id) });
index += 1;
}
}
}
Ok(Cutting::Emit(items))
}
}
fn flush(stretch: &mut Vec<CutItem>, plans: &mut Vec<Plan>) {
if stretch.iter().any(|item| matches!(item, CutItem::Inline(_))) {
plans.push(Plan::Piece(stretch.drain(..).map(CutItem::id).collect(), false));
} else {
plans.extend(stretch.drain(..).map(Plan::Through));
}
}