use std::hash::{Hash, Hasher};
use crate::core::settings::named::{self, NamedEntry};
use crate::model::names::Name;
use crate::stdlib::features::numbering::{NumberTemplate, PluralWords, PrefixWords};
use crate::stdlib::features::refs::CAPITAL_VARIANT;
use super::{ANY_HANDLER, RESERVED_KINDS};
pub const INCLUDEGRAPHICS_PACKAGE: &str = "flm.graphics.includegraphics";
pub const INCLUDEGRAPHICS_HANDLER: &str = "includegraphics";
pub const CELLS_PACKAGE: &str = "flm.cells.environment";
pub const CELLS_HANDLER: &str = "cells";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Deserialize, serde::Serialize)]
#[derive(schemars::JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum FloatNumbering {
Numbered,
Unnumbered,
#[default]
AutoNumbered,
}
impl FloatNumbering {
pub fn as_str(self) -> &'static str {
match self {
FloatNumbering::Numbered => "numbered",
FloatNumbering::Unnumbered => "unnumbered",
FloatNumbering::AutoNumbered => "auto-numbered",
}
}
pub fn numbers(self, labeled: bool, nonumber: bool) -> bool {
match self {
FloatNumbering::Numbered => !nonumber,
FloatNumbering::Unnumbered => false,
FloatNumbering::AutoNumbered => labeled && !nonumber,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
#[derive(schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
#[schemars(transform = float_type_schema)]
pub struct FloatType {
#[schemars(skip)]
pub name: Name,
pub caption_name: String,
pub numbering: FloatNumbering,
pub number_format: NumberTemplate,
pub words: PrefixWords,
pub handlers: Vec<String>,
pub scoped_packages: Vec<Name>,
pub label_types: Vec<String>,
}
fn float_type_schema(schema: &mut schemars::Schema) {
crate::core::settings::named::require_only(schema, &["handlers"]);
}
impl FloatType {
pub fn new(
name: impl Into<Name>,
handlers: impl IntoIterator<Item = impl Into<String>>,
) -> FloatType {
let name = name.into();
let caption_name = capitalized(name.as_str());
let one = format!("{caption_name}~");
let other = format!("{caption_name}s~");
let words = PrefixWords::new(one.clone(), other.clone())
.with_variant(CAPITAL_VARIANT, PluralWords::new(one, other));
FloatType {
label_types: vec![name.to_string()],
name,
caption_name,
numbering: FloatNumbering::default(),
number_format: NumberTemplate::formats("#{arabic}"),
words,
handlers: handlers.into_iter().map(Into::into).collect(),
scoped_packages: Vec::new(),
}
}
pub fn figure() -> FloatType {
FloatType::new("figure", [INCLUDEGRAPHICS_HANDLER])
.words(
PrefixWords::new("Fig.~", "Figs.~")
.with_variant(CAPITAL_VARIANT, PluralWords::new("Figure~", "Figures~")),
)
.scoped_packages([INCLUDEGRAPHICS_PACKAGE])
}
pub fn table() -> FloatType {
FloatType::new("table", [CELLS_HANDLER, INCLUDEGRAPHICS_HANDLER])
.words(
PrefixWords::new("Tab.~", "Tabs.~")
.with_variant(CAPITAL_VARIANT, PluralWords::new("Table~", "Tables~")),
)
.scoped_packages([CELLS_PACKAGE, INCLUDEGRAPHICS_PACKAGE])
}
pub fn caption_name(mut self, caption_name: impl Into<String>) -> FloatType {
self.caption_name = caption_name.into();
self
}
pub fn numbering(mut self, numbering: FloatNumbering) -> FloatType {
self.numbering = numbering;
self
}
pub fn number_format(mut self, number_format: NumberTemplate) -> FloatType {
self.number_format = number_format;
self
}
pub fn words(mut self, words: PrefixWords) -> FloatType {
self.words = words;
self
}
pub fn handlers(mut self, handlers: impl IntoIterator<Item = impl Into<String>>) -> FloatType {
self.handlers = handlers.into_iter().map(Into::into).collect();
self
}
pub fn scoped_packages(
mut self,
scoped_packages: impl IntoIterator<Item = impl Into<Name>>,
) -> FloatType {
self.scoped_packages = scoped_packages.into_iter().map(Into::into).collect();
self
}
pub fn label_types(mut self, label_types: impl IntoIterator<Item = impl Into<String>>) -> FloatType {
self.label_types = label_types.into_iter().map(Into::into).collect();
self
}
pub fn validate(&self) -> Result<(), String> {
let name = self.name.as_str();
if name.is_empty() || !name.chars().all(|ch| ch.is_ascii_alphabetic()) {
return Err(format!("the float type name `{name}` must consist of ASCII letters only"));
}
if RESERVED_KINDS.contains(&name) {
let reserved: Vec<String> = RESERVED_KINDS.iter().map(|kind| format!("`{kind}`")).collect();
return Err(format!(
"a float type may not be named `{name}`: the names {} are reserved",
reserved.join(" and ")
));
}
if self.handlers.is_empty() {
return Err(format!(
"the float type `{name}` must list at least one content handler (`{ANY_HANDLER}` \
accepts any content)"
));
}
Ok(())
}
fn push_digest(&self, out: &mut Vec<u8>) {
let FloatType {
name,
caption_name,
numbering,
number_format,
words,
handlers,
scoped_packages,
label_types,
} = self;
push_text(out, name.as_str());
push_text(out, caption_name);
push_text(out, numbering.as_str());
match number_format {
NumberTemplate::Formats(text) => {
out.push(0);
push_text(out, text);
}
NumberTemplate::Initial(text) => {
out.push(1);
push_text(out, text);
}
}
push_plural(out, &words.base);
push_len(out, words.variants.len());
for (variant, plural) in &words.variants {
push_text(out, variant);
push_plural(out, plural);
}
push_len(out, handlers.len());
for handler in handlers {
push_text(out, handler);
}
push_len(out, scoped_packages.len());
for package in scoped_packages {
push_text(out, package.as_str());
}
push_len(out, label_types.len());
for label_type in label_types {
push_text(out, label_type);
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
#[derive(schemars::JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct FloatsConfig {
#[serde(deserialize_with = "crate::core::settings::named::deserialize")]
#[schemars(
transform = crate::core::settings::named::map_schema,
with = "std::collections::BTreeMap<String, FloatType>"
)]
pub types: Vec<FloatType>,
}
impl Default for FloatsConfig {
fn default() -> FloatsConfig {
FloatsConfig::new()
}
}
impl FloatsConfig {
pub fn new() -> FloatsConfig {
FloatsConfig { types: vec![FloatType::figure(), FloatType::table()] }
}
pub fn empty() -> FloatsConfig {
FloatsConfig { types: Vec::new() }
}
pub fn float_type(mut self, float_type: FloatType) -> FloatsConfig {
match self.types.iter_mut().find(|known| known.name == float_type.name) {
Some(known) => *known = float_type,
None => self.types.push(float_type),
}
self
}
pub fn without_type(mut self, name: &str) -> FloatsConfig {
self.types.retain(|known| known.name.as_str() != name);
self
}
pub fn get(&self, name: &str) -> Option<&FloatType> {
self.types.iter().find(|known| known.name.as_str() == name)
}
pub fn validate(&self) -> Result<(), String> {
for (at, float_type) in self.types.iter().enumerate() {
float_type.validate()?;
if self.types[..at].iter().any(|earlier| earlier.name == float_type.name) {
return Err(format!(
"the float type `{}` may not be declared twice",
float_type.name
));
}
}
Ok(())
}
pub fn digest_bytes(&self) -> Vec<u8> {
let FloatsConfig { types } = self;
let mut out = Vec::new();
push_len(&mut out, types.len());
for float_type in types {
float_type.push_digest(&mut out);
}
out
}
}
impl Hash for FloatsConfig {
fn hash<H: Hasher>(&self, state: &mut H) {
state.write(&self.digest_bytes());
}
}
fn capitalized(text: &str) -> String {
let mut chars = text.chars();
match chars.next() {
Some(first) => first.to_uppercase().chain(chars).collect(),
None => String::new(),
}
}
fn push_len(out: &mut Vec<u8>, len: usize) {
out.extend_from_slice(&(len as u64).to_le_bytes());
}
fn push_text(out: &mut Vec<u8>, text: &str) {
push_len(out, text.len());
out.extend_from_slice(text.as_bytes());
}
fn push_plural(out: &mut Vec<u8>, plural: &PluralWords) {
push_text(out, &plural.one);
push_text(out, &plural.other);
}
impl NamedEntry for FloatType {
fn read_entry(name: &str, data: serde_json::Value) -> Result<FloatType, String> {
let handlers: Vec<String> = named::required(name, &data, "handlers")?;
named::read_over(&FloatType::new(name, handlers), "name", name, data)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_type_takes_its_defaults_from_its_name() {
let diagram = FloatType::new("diagram", ["any"]);
assert_eq!(diagram.caption_name, "Diagram");
assert_eq!(diagram.words.base, PluralWords::new("Diagram~", "Diagrams~"));
assert_eq!(diagram.words.variants[CAPITAL_VARIANT], PluralWords::new("Diagram~", "Diagrams~"));
assert_eq!(diagram.numbering, FloatNumbering::AutoNumbered);
assert_eq!(FloatType::figure().numbering, FloatNumbering::AutoNumbered);
assert_eq!(FloatType::table().numbering, FloatNumbering::AutoNumbered);
assert_eq!(diagram.number_format, NumberTemplate::formats("#{arabic}"));
assert_eq!(diagram.label_types, ["diagram"]);
assert!(diagram.scoped_packages.is_empty());
}
#[test]
fn the_shipped_types_carry_the_words_handlers_and_package() {
let figure = FloatType::figure();
assert_eq!(figure.caption_name, "Figure");
assert_eq!(figure.words.base, PluralWords::new("Fig.~", "Figs.~"));
assert_eq!(figure.words.variants[CAPITAL_VARIANT], PluralWords::new("Figure~", "Figures~"));
assert_eq!(figure.handlers, ["includegraphics"]);
assert_eq!(figure.scoped_packages, [Name::from(INCLUDEGRAPHICS_PACKAGE)]);
assert_eq!(
FloatType::table().scoped_packages,
[Name::from(CELLS_PACKAGE), Name::from(INCLUDEGRAPHICS_PACKAGE)]
);
let table = FloatType::table();
assert_eq!(table.caption_name, "Table");
assert_eq!(table.words.base, PluralWords::new("Tab.~", "Tabs.~"));
assert_eq!(table.handlers, ["cells", "includegraphics"]);
assert_eq!(FloatsConfig::new().validate(), Ok(()));
}
#[test]
fn the_policy_decides_the_number_from_the_fields() {
use FloatNumbering::*;
assert!(Numbered.numbers(false, false) && !Numbered.numbers(true, true));
assert!(!Unnumbered.numbers(true, false));
assert!(AutoNumbered.numbers(true, false));
assert!(!AutoNumbered.numbers(false, false) && !AutoNumbered.numbers(true, true));
}
#[test]
fn a_name_an_empty_handler_list_and_a_repeated_type_are_refused() {
let refused = |config: FloatsConfig| config.validate().is_err();
assert!(refused(FloatsConfig::empty().float_type(FloatType::new("my-float", ["any"]))));
assert!(refused(FloatsConfig::empty().float_type(FloatType::new("", ["any"]))));
assert!(refused(FloatsConfig::empty().float_type(FloatType::new("numbered", ["any"]))));
assert!(refused(FloatsConfig::empty().float_type(FloatType::new("unnumbered", ["any"]))));
assert!(refused(FloatsConfig::empty().float_type(FloatType::new("x", Vec::<String>::new()))));
let twice = FloatsConfig { types: vec![FloatType::figure(), FloatType::figure()] };
assert!(refused(twice));
}
#[test]
fn declaring_a_type_of_a_known_name_replaces_it_in_place() {
let config = FloatsConfig::new().float_type(FloatType::figure().caption_name("Fig"));
assert_eq!(config.types.len(), 2);
assert_eq!(config.types[0].caption_name, "Fig");
assert_eq!(FloatsConfig::new().without_type("figure").types.len(), 1);
}
#[test]
fn the_digest_bytes_change_with_every_field() {
let base = FloatsConfig::new();
let figure = FloatType::figure;
let changed = [
base.clone().without_type("table"),
base.clone().float_type(FloatType::new("diagram", ["any"])),
base.clone().float_type(figure().caption_name("Fig")),
base.clone().float_type(figure().numbering(FloatNumbering::Numbered)),
base.clone().float_type(figure().numbering(FloatNumbering::Unnumbered)),
base.clone().float_type(figure().number_format(NumberTemplate::formats("#{roman}"))),
base.clone().float_type(figure().number_format(NumberTemplate::initial("#{arabic}"))),
base.clone().float_type(figure().words(PrefixWords::new("Fig.~", "Figs.~"))),
base.clone().float_type(figure().handlers(["any"])),
base.clone().float_type(figure().scoped_packages(Vec::<Name>::new())),
base.clone().float_type(figure().label_types(["figure", "fig"])),
];
for other in &changed {
assert_ne!(other.digest_bytes(), base.digest_bytes(), "{other:?}");
}
assert_eq!(FloatsConfig::new().digest_bytes(), base.digest_bytes());
}
}