Skip to main content

takumi_core/
error.rs

1use cssparser::{BasicParseErrorKind, ParseError, ParseErrorKind};
2use selectors::parser::SelectorParseErrorKind;
3use thiserror::Error;
4
5use crate::{
6  keyframes::KeyframePreludeParseError,
7  resources::{font::FontError, image::ImageError},
8  style::ValueError,
9};
10
11/// Structured errors raised by the WebP encoding and container assembly paths.
12#[derive(Error, Debug)]
13#[non_exhaustive]
14pub enum WebPError {
15  /// Encoder setup failed before actual frame encoding.
16  #[error("WebP encoder setup failed")]
17  EncoderSetupFailed,
18
19  /// Encoding failed.
20  #[error("WebP encode failed")]
21  EncodeFailed,
22
23  /// Encoding failed with a libwebp error code.
24  #[error("WebP encode failed ({error_code})")]
25  EncodeFailedWithCode {
26    /// The libwebp error code rendered as text.
27    error_code: String,
28  },
29
30  /// A named dimension exceeded the supported WebP 24-bit range.
31  #[error("{name} must be in 1..={max}, got {value}")]
32  InvalidDimension {
33    /// The dimension name used in the error message.
34    name: &'static str,
35    /// The invalid dimension value that was supplied.
36    value: u32,
37    /// The maximum accepted dimension value.
38    max: u32,
39  },
40
41  /// The animation frame size exceeded the supported WebP 24-bit range.
42  #[error("WebP animation frame dimensions must be in 1..={max}, got {width}x{height}")]
43  InvalidFrameDimensions {
44    /// The invalid frame width.
45    width: u32,
46    /// The invalid frame height.
47    height: u32,
48    /// The maximum accepted dimension value.
49    max: u32,
50  },
51
52  /// An animated encode was requested without any frames.
53  #[error("animation must contain at least one frame")]
54  EmptyAnimation,
55
56  /// A frame exceeded the dimensions of the animation canvas.
57  #[error(
58    "frame {index} dimensions {frame_width}x{frame_height} exceed canvas {canvas_width}x{canvas_height}"
59  )]
60  FrameExceedsCanvas {
61    /// The zero-based frame index.
62    index: usize,
63    /// The frame width.
64    frame_width: u32,
65    /// The frame height.
66    frame_height: u32,
67    /// The canvas width.
68    canvas_width: u32,
69    /// The canvas height.
70    canvas_height: u32,
71  },
72
73  /// Animated frames did not all share the same dimensions.
74  #[error("all animation frames must have the same dimensions")]
75  MixedFrameDimensions,
76
77  /// Encoded data cannot be parsed as the expected WebP structure.
78  #[error("WebP encoded data is invalid or unsupported")]
79  InvalidEncodedData,
80
81  /// Internal WebP container size calculations exceeded supported limits.
82  #[error("WebP container size exceeds supported limits")]
83  ContainerSizeOverflow,
84}
85
86/// The main error type for the Takumi crate.
87#[derive(Error, Debug)]
88#[non_exhaustive]
89pub enum Error {
90  /// Error resolving an image resource.
91  #[error("Image resolution error: {0}")]
92  ImageResolveError(#[from] ImageError),
93
94  /// Standard IO error.
95  #[error("IO error: {0}")]
96  IoError(#[from] std::io::Error),
97
98  /// Encoding an image or animation failed.
99  #[error("Encoding error: {0}")]
100  Encode(#[source] Box<dyn std::error::Error + Send + Sync + 'static>),
101
102  /// Structured errors from WebP encoding and RIFF container assembly.
103  #[error("WebP error: {0}")]
104  WebPError(#[from] WebPError),
105
106  /// Zero-sized viewport, or one over the 64 megapixel canvas budget.
107  #[error("Invalid viewport dimensions: a canvas holds 1 to 64 megapixels")]
108  InvalidViewport,
109
110  /// A page size that is not finite or not larger than zero, or a page `f32` cannot end below its top.
111  #[error("Page size must be finite and larger than zero")]
112  InvalidPageSize,
113
114  /// RGBA buffer length does not match `width * height * 4`.
115  #[error("Invalid RGBA buffer length: expected {expected} bytes, got {actual}")]
116  InvalidRgbaBufferLength {
117    /// Actual RGBA byte length in the buffer.
118    actual: usize,
119    /// Expected RGBA byte length from dimensions.
120    expected: usize,
121  },
122
123  /// Alpha buffer length does not match `width * height`.
124  #[error("Invalid alpha buffer length: expected {expected} bytes, got {actual}")]
125  InvalidAlphaBufferLength {
126    /// Actual alpha byte length in the buffer.
127    actual: usize,
128    /// Expected alpha byte length from dimensions.
129    expected: usize,
130  },
131
132  /// Animated encode was requested without any frames.
133  #[error("Animation must contain at least one frame")]
134  EmptyAnimationFrames,
135
136  /// The frame rate is past what the format plays back without browsers clamping frames.
137  #[error("Frame rate {fps} fps exceeds the maximum {max_fps} fps for this animation format")]
138  AnimationFrameRateTooHigh {
139    /// The requested frame rate.
140    fps: u32,
141    /// The highest frame rate the format encodes without decoder clamping.
142    max_fps: u32,
143  },
144
145  /// Animated frames for a given format did not all share the same dimensions.
146  #[error("Animation frames must share the same dimensions")]
147  MixedAnimationFrameDimensions,
148
149  /// GIF frame dimensions exceeded the format limits.
150  #[error("GIF frame dimensions must be <= {max}x{max}, got {width}x{height}")]
151  GifFrameDimensionsTooLarge {
152    /// The invalid frame width.
153    width: u32,
154    /// The invalid frame height.
155    height: u32,
156    /// The maximum accepted dimension value.
157    max: u16,
158  },
159
160  /// Error related to font processing.
161  #[error("Font error: {0}")]
162  FontError(#[from] FontError),
163
164  /// Parsing a CSS value or property failed.
165  #[error("Parse error: {0}")]
166  Parse(#[from] crate::style::properties::ParseError),
167
168  /// Computing layout failed.
169  #[error("Layout error: {0}")]
170  Layout(String),
171
172  /// The layout engine was asked for a node id it does not know.
173  #[error("Invalid layout node id: {0}")]
174  InvalidLayoutNode(u64),
175
176  /// Paged layout needed more pages than the caller allows.
177  #[error("The content spans more than {0} pages")]
178  TooManyPages(usize),
179
180  /// A page was painted from a page of the layout that was already released.
181  #[error("Page {0} was released before a later page painted from it")]
182  PageReleased(usize),
183
184  /// An invalid BCP-47 language tag was supplied to a node's `lang` attribute.
185  #[error("Invalid language tag: {0}")]
186  InvalidLanguageTag(String),
187}
188
189impl Error {
190  /// Wraps an encoder-crate error opaquely so takumi's public API stays
191  /// independent of the encoder crates' versions.
192  pub fn encode(err: impl std::error::Error + Send + Sync + 'static) -> Self {
193    Self::Encode(Box::new(err))
194  }
195}
196
197/// A specialized Result type for Takumi operations.
198pub type Result<T> = std::result::Result<T, Error>;
199
200/// Errors raised while parsing a CSS declaration block string.
201#[derive(Error, Debug, Clone, PartialEq, Eq)]
202pub enum StyleDeclarationBlockParseError {
203  /// The declaration block could not be parsed as CSS declarations.
204  #[error("failed to parse CSS declaration block `{input}` near `{context}`: {reason}")]
205  InvalidDeclarationBlock {
206    /// The original declaration block input.
207    input: String,
208    /// The declaration slice being parsed when the error was raised.
209    context: String,
210    /// The parser failure rendered as text.
211    reason: String,
212  },
213}
214
215/// Errors raised while parsing a CSS stylesheet string.
216#[derive(Debug, Clone, PartialEq, Eq)]
217pub struct StyleSheetParseError {
218  /// The stylesheet slice being parsed when the error was raised.
219  pub context: Option<String>,
220  /// The specific stylesheet parse failure.
221  pub kind: StyleSheetParseErrorKind,
222}
223
224/// The specific stylesheet parse failure.
225#[derive(Error, Debug, Clone, PartialEq, Eq)]
226pub enum StyleSheetParseErrorKind {
227  /// The stylesheet could not be parsed as valid CSS.
228  #[error("{0}")]
229  InvalidStyleSheet(String),
230
231  /// The stylesheet uses an unsupported media feature.
232  #[error("unsupported media feature")]
233  UnsupportedMediaFeature,
234
235  /// `@property` requires `inherits` to be `true` or `false`.
236  #[error("@property inherits must be true or false")]
237  PropertyInheritsMustBeBoolean,
238
239  /// `@property` is missing its `syntax` descriptor.
240  #[error("missing `@property` syntax")]
241  MissingPropertySyntax,
242
243  /// `@property` is missing its `inherits` descriptor.
244  #[error("missing `@property` inherits")]
245  MissingPropertyInherits,
246
247  /// `@property` gives a typed `syntax` without the `initial-value` it needs.
248  #[error("`@property` with a typed syntax needs an initial-value")]
249  MissingPropertyInitialValue,
250
251  /// `@property` gives a `syntax` that is not a valid syntax string.
252  #[error("`@property` syntax is not a valid syntax string")]
253  InvalidPropertySyntax,
254
255  /// `@property` gives an `initial-value` its syntax does not take, or one that needs the
256  /// element to compute.
257  #[error("`@property` initial-value must match its syntax and be computationally independent")]
258  InvalidPropertyInitialValue,
259
260  /// `@supports` mixed `and` and `or` without parentheses.
261  #[error("@supports cannot mix `and` and `or` without parentheses")]
262  SupportsMixedAndOrWithoutParentheses,
263
264  /// `@apply` only takes plain utilities, without variants.
265  #[error("@apply expects plain utilities without variants")]
266  InvalidApplyUtility,
267
268  /// `@property` names must be custom properties.
269  #[error("@property name must be a custom property")]
270  PropertyNameMustBeCustomProperty,
271
272  /// `@layer` blocks accept at most one name.
273  #[error("@layer blocks accept at most one name")]
274  LayerBlockMultipleNames,
275
276  /// Nested `@keyframes` and `@property` rules are not supported.
277  #[error("unsupported nested at-rule")]
278  UnsupportedNestedAtRule,
279}
280
281impl std::fmt::Display for StyleSheetParseError {
282  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
283    if let Some(context) = &self.context {
284      write!(
285        f,
286        "failed to parse stylesheet near `{context}`: {}",
287        self.kind
288      )
289    } else {
290      write!(f, "failed to parse stylesheet: {}", self.kind)
291    }
292  }
293}
294
295impl std::error::Error for StyleSheetParseError {}
296
297impl From<StyleSheetParseErrorKind> for StyleSheetParseError {
298  fn from(kind: StyleSheetParseErrorKind) -> Self {
299    Self {
300      context: None,
301      kind,
302    }
303  }
304}
305
306impl From<SelectorParseErrorKind> for StyleSheetParseError {
307  fn from(err: SelectorParseErrorKind) -> Self {
308    Self::invalid_reason(format!("{err:?}"))
309  }
310}
311
312impl<'i> From<ValueError<'i>> for StyleSheetParseError {
313  fn from(err: ValueError<'i>) -> Self {
314    Self::invalid_reason(err.to_string())
315  }
316}
317
318impl<'i> From<KeyframePreludeParseError<'i>> for StyleSheetParseError {
319  fn from(_err: KeyframePreludeParseError<'i>) -> Self {
320    Self::invalid_reason(format!("{:?}", BasicParseErrorKind::QualifiedRuleInvalid))
321  }
322}
323
324impl StyleSheetParseError {
325  /// Builds an invalid-stylesheet error from a reason string.
326  pub(crate) fn invalid_reason(reason: impl Into<String>) -> Self {
327    StyleSheetParseErrorKind::InvalidStyleSheet(reason.into()).into()
328  }
329
330  fn with_context(self, context: &str) -> Self {
331    Self {
332      context: Some(context.to_owned()),
333      kind: self.kind,
334    }
335  }
336
337  /// Converts a `cssparser` parse error into a stylesheet error with context.
338  pub(crate) fn from_parse_error(context: &str, error: ParseError<StyleSheetParseError>) -> Self {
339    match error.kind {
340      ParseErrorKind::Basic(error) => Self::invalid_reason(format!("{error:?}")),
341      ParseErrorKind::Custom(error) => error,
342    }
343    .with_context(context)
344  }
345}