use std::{collections::TryReserveError, error::Error, fmt};
use sim_engine::{FontError, LogicalScreenPosition, ShapedLineError};
use crate::screen::ScreenVisualError;
#[derive(Debug)]
#[non_exhaustive]
pub enum TextError {
InvalidAtlasLimits,
ForeignFont,
Font(FontError),
Prepared(ShapedLineError),
FontLimitExceeded {
limit: usize,
},
FontByteLimitExceeded {
limit: usize,
retained: usize,
incoming: usize,
},
RunBudgetExceeded {
glyphs: usize,
max_glyphs: usize,
required_bytes: usize,
max_retained_bytes: usize,
},
Screen(ScreenVisualError),
InvalidBounds {
position: LogicalScreenPosition,
},
AllocationFailed {
source: TryReserveError,
},
}
impl fmt::Display for TextError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidAtlasLimits => formatter.write_str("invalid text atlas/run limits"),
Self::ForeignFont => formatter.write_str("font is not registered by this application"),
Self::Font(error) => write!(formatter, "text font: {error}"),
Self::Prepared(error) => write!(formatter, "text preparation: {error}"),
Self::FontLimitExceeded { limit } => {
write!(
formatter,
"text font registry reached its {limit}-font limit"
)
}
Self::FontByteLimitExceeded {
limit,
retained,
incoming,
} => write!(
formatter,
"font source capacity {retained} plus {incoming} bytes exceeds limit {limit}"
),
Self::RunBudgetExceeded {
glyphs,
max_glyphs,
required_bytes,
max_retained_bytes,
} => write!(
formatter,
"text run needs {glyphs} glyphs and {required_bytes} retained bytes; limits are {max_glyphs} and {max_retained_bytes}"
),
Self::Screen(error) => write!(formatter, "screen text: {error}"),
Self::InvalidBounds { position } => write!(
formatter,
"text baseline and typographic bounds are not representable at {position:?}"
),
Self::AllocationFailed { source } => {
write!(formatter, "text allocation failed: {source}")
}
}
}
}
impl Error for TextError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Font(error) => Some(error),
Self::Prepared(error) => Some(error),
Self::Screen(error) => Some(error),
Self::AllocationFailed { source } => Some(source),
_ => None,
}
}
}
impl From<FontError> for TextError {
fn from(error: FontError) -> Self {
Self::Font(error)
}
}
impl From<ShapedLineError> for TextError {
fn from(error: ShapedLineError) -> Self {
Self::Prepared(error)
}
}
impl From<ScreenVisualError> for TextError {
fn from(error: ScreenVisualError) -> Self {
Self::Screen(error)
}
}