use indicatrix::{geometry::meet_solver::SolvedTier, optics::materials::GemMaterial};
use indicatrix_cut_core::{ConstraintTier, Design};
use indicatrix_formats::asc::{
AscLineEnding, AscParseError, AscSchedule, parse_asc, parse_asc_with_gear_line, to_asc_string,
};
use std::fmt;
mod diff;
mod pairing;
mod plan;
#[cfg(test)]
mod tests;
pub use diff::{DiffKind, DiffRow, TextDiff, diff_lines};
pub use plan::{ApplyPlan, ApplyReport, apply_plan, plan_apply};
const MAX_LISTED_NAMES: usize = 4;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TextProblem {
pub line: Option<usize>,
pub message: String,
}
impl TextProblem {
fn at(line: Option<usize>, message: impl Into<String>) -> Self {
Self {
line,
message: message.into(),
}
}
fn general(message: impl Into<String>) -> Self {
Self::at(None, message)
}
}
impl fmt::Display for TextProblem {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.line {
Some(line) => write!(f, "Line {line}: {}", self.message),
None => f.write_str(&self.message),
}
}
}
impl std::error::Error for TextProblem {}
const fn error_line(error: &AscParseError) -> Option<usize> {
match error {
AscParseError::GearLineMissingFields { line, .. }
| AscParseError::GearTeethNotNumeric { line, .. }
| AscParseError::GearReferenceAngleNotNumeric { line, .. }
| AscParseError::SymmetryLineMissingFields { line, .. }
| AscParseError::SymmetryOrderNotNumeric { line, .. }
| AscParseError::RefractiveIndexMissing { line }
| AscParseError::RefractiveIndexNotNumeric { line, .. }
| AscParseError::NotWholeNumber { line, .. }
| AscParseError::GearTeethZero { line }
| AscParseError::GearTeethTooLarge { line, .. }
| AscParseError::MirrorFlagInvalid { line, .. }
| AscParseError::TierRecordTooShort { line, .. }
| AscParseError::AngleNotNumeric { line, .. }
| AscParseError::MastNotNumeric { line, .. }
| AscParseError::NonFiniteValue { line, .. }
| AscParseError::SymmetryOrderZero { line }
| AscParseError::RefractiveIndexOutOfRange { line, .. } => Some(*line),
_ => None,
}
}
fn capitalise(text: &str) -> String {
let mut chars = text.chars();
chars.next().map_or_else(String::new, |first| {
first.to_uppercase().chain(chars).collect()
})
}
fn problem_from(error: &AscParseError) -> TextProblem {
let line = error_line(error);
let message = match error {
AscParseError::EmptyInput => "The text is empty.".to_owned(),
AscParseError::MissingGearLine => {
"There is no gear line. Add one such as: g 96 0.0".to_owned()
}
AscParseError::MissingSymmetryLine => {
"There is no symmetry line. Add one such as: y 8 y".to_owned()
}
AscParseError::MissingRefractiveIndexLine => {
"There is no refractive index line. Add one such as: I 1.54".to_owned()
}
AscParseError::NoTierRecords => {
"There are no facet tiers. Every tier is a line that starts with a.".to_owned()
}
other => {
let full = other.to_string();
let prefix = line.map(|number| format!("line {number}: "));
let stripped = prefix
.as_deref()
.and_then(|prefix| full.strip_prefix(prefix))
.unwrap_or(&full);
capitalise(stripped)
}
};
TextProblem::at(line, message)
}
#[derive(Debug, Clone, PartialEq)]
pub struct ParsedText {
pub schedule: AscSchedule,
pub tier_lines: Vec<usize>,
pub gear_line: Option<usize>,
}
impl ParsedText {
#[must_use]
pub fn tier_line(&self, index: usize) -> Option<usize> {
self.tier_lines.get(index).copied()
}
}
fn tier_line_numbers(text: &str) -> Vec<usize> {
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
text.lines()
.enumerate()
.filter(|(_, raw)| {
let line = raw.trim();
!(line.is_empty() || line.starts_with(';') || line.starts_with('#'))
&& line.split_whitespace().next() == Some("a")
})
.map(|(index, _)| index + 1)
.collect()
}
pub fn parse_text(text: &str) -> Result<ParsedText, TextProblem> {
let (schedule, gear_line) =
parse_asc_with_gear_line(text).map_err(|error| problem_from(&error))?;
Ok(ParsedText {
schedule,
tier_lines: tier_line_numbers(text),
gear_line,
})
}
pub fn normalize_text(text: &str) -> Result<String, TextProblem> {
let mut schedule = parse_asc(text).map_err(|error| problem_from(&error))?;
schedule.line_ending = AscLineEnding::Lf;
schedule.warnings.clear();
to_asc_string(&schedule).map_err(|error| TextProblem::general(error.to_string()))
}
pub fn generate_text(
design: &Design,
solved: &[SolvedTier],
custom: &[GemMaterial],
) -> Result<String, String> {
let mut schedule = design
.try_to_asc_schedule_from_solved_with(solved, custom)
.map_err(|error| error.to_string())?;
design.append_concave_footnotes(&mut schedule);
schedule.line_ending = AscLineEnding::Lf;
to_asc_string(&schedule).map_err(|error| error.to_string())
}
fn counted(count: usize, noun: &str) -> String {
if count == 1 {
format!("1 {noun}")
} else {
format!("{count} {noun}s")
}
}
#[must_use]
pub fn omitted_items(design: &Design) -> Vec<String> {
let mut items = Vec::new();
let notes = design
.tier_notes
.values()
.filter(|note| !note.trim().is_empty())
.count();
if notes > 0 {
items.push(counted(notes, "tier note"));
}
let offsets = design
.cheater_offsets_deg
.values()
.filter(|offset| **offset != 0.0)
.count();
if offsets > 0 {
items.push(counted(offsets, "cheater offset"));
}
if !design.tier_targets.is_empty() {
items.push(format!(
"{} (only the cut depths they give are written)",
counted(design.tier_targets.len(), "depth or width target")
));
}
if !design.tier_relations.is_empty() {
items.push(format!(
"{} (only the angles they give are written)",
counted(design.tier_relations.len(), "tier relation")
));
}
if !design.concave_tiers.is_empty() {
items.push(format!(
"{} (written as footnotes only)",
counted(design.concave_tiers.len(), "concave tier")
));
}
items.push("the preform, the material and the girdle size".to_owned());
items
}
#[must_use]
pub fn omitted_line(design: &Design) -> String {
format!(
"Not in this text: {}. Tiers you keep by name keep these.",
omitted_items(design).join(", ")
)
}
const fn same(a: f64, b: f64) -> bool {
a.to_bits() == b.to_bits()
}
fn same_all(a: &[f64], b: &[f64]) -> bool {
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| same(*x, *y))
}
fn list(names: &[String]) -> String {
let shown = names
.iter()
.take(MAX_LISTED_NAMES)
.map(String::as_str)
.collect::<Vec<_>>()
.join(", ");
match names.len().saturating_sub(MAX_LISTED_NAMES) {
0 => shown,
rest => format!("{shown} and {rest} more"),
}
}
fn sentence(prefix: &str, names: &[String]) -> Option<String> {
(!names.is_empty()).then(|| format!("{prefix} {}.", list(names)))
}
fn tier_label(tier: &ConstraintTier, position: usize) -> String {
if tier.name.is_empty() {
format!("tier {}", position + 1)
} else {
tier.name.clone()
}
}