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#[derive(Error, Debug)]
13#[non_exhaustive]
14pub enum WebPError {
15 #[error("WebP encoder setup failed")]
17 EncoderSetupFailed,
18
19 #[error("WebP encode failed")]
21 EncodeFailed,
22
23 #[error("WebP encode failed ({error_code})")]
25 EncodeFailedWithCode {
26 error_code: String,
28 },
29
30 #[error("{name} must be in 1..={max}, got {value}")]
32 InvalidDimension {
33 name: &'static str,
35 value: u32,
37 max: u32,
39 },
40
41 #[error("WebP animation frame dimensions must be in 1..={max}, got {width}x{height}")]
43 InvalidFrameDimensions {
44 width: u32,
46 height: u32,
48 max: u32,
50 },
51
52 #[error("animation must contain at least one frame")]
54 EmptyAnimation,
55
56 #[error(
58 "frame {index} dimensions {frame_width}x{frame_height} exceed canvas {canvas_width}x{canvas_height}"
59 )]
60 FrameExceedsCanvas {
61 index: usize,
63 frame_width: u32,
65 frame_height: u32,
67 canvas_width: u32,
69 canvas_height: u32,
71 },
72
73 #[error("all animation frames must have the same dimensions")]
75 MixedFrameDimensions,
76
77 #[error("WebP encoded data is invalid or unsupported")]
79 InvalidEncodedData,
80
81 #[error("WebP container size exceeds supported limits")]
83 ContainerSizeOverflow,
84}
85
86#[derive(Error, Debug)]
88#[non_exhaustive]
89pub enum Error {
90 #[error("Image resolution error: {0}")]
92 ImageResolveError(#[from] ImageError),
93
94 #[error("IO error: {0}")]
96 IoError(#[from] std::io::Error),
97
98 #[error("Encoding error: {0}")]
100 Encode(#[source] Box<dyn std::error::Error + Send + Sync + 'static>),
101
102 #[error("WebP error: {0}")]
104 WebPError(#[from] WebPError),
105
106 #[error("Invalid viewport dimensions: a canvas holds 1 to 64 megapixels")]
108 InvalidViewport,
109
110 #[error("Page size must be finite and larger than zero")]
112 InvalidPageSize,
113
114 #[error("Invalid RGBA buffer length: expected {expected} bytes, got {actual}")]
116 InvalidRgbaBufferLength {
117 actual: usize,
119 expected: usize,
121 },
122
123 #[error("Invalid alpha buffer length: expected {expected} bytes, got {actual}")]
125 InvalidAlphaBufferLength {
126 actual: usize,
128 expected: usize,
130 },
131
132 #[error("Animation must contain at least one frame")]
134 EmptyAnimationFrames,
135
136 #[error("Frame rate {fps} fps exceeds the maximum {max_fps} fps for this animation format")]
138 AnimationFrameRateTooHigh {
139 fps: u32,
141 max_fps: u32,
143 },
144
145 #[error("Animation frames must share the same dimensions")]
147 MixedAnimationFrameDimensions,
148
149 #[error("GIF frame dimensions must be <= {max}x{max}, got {width}x{height}")]
151 GifFrameDimensionsTooLarge {
152 width: u32,
154 height: u32,
156 max: u16,
158 },
159
160 #[error("Font error: {0}")]
162 FontError(#[from] FontError),
163
164 #[error("Parse error: {0}")]
166 Parse(#[from] crate::style::properties::ParseError),
167
168 #[error("Layout error: {0}")]
170 Layout(String),
171
172 #[error("Invalid layout node id: {0}")]
174 InvalidLayoutNode(u64),
175
176 #[error("The content spans more than {0} pages")]
178 TooManyPages(usize),
179
180 #[error("Page {0} was released before a later page painted from it")]
182 PageReleased(usize),
183
184 #[error("Invalid language tag: {0}")]
186 InvalidLanguageTag(String),
187}
188
189impl Error {
190 pub fn encode(err: impl std::error::Error + Send + Sync + 'static) -> Self {
193 Self::Encode(Box::new(err))
194 }
195}
196
197pub type Result<T> = std::result::Result<T, Error>;
199
200#[derive(Error, Debug, Clone, PartialEq, Eq)]
202pub enum StyleDeclarationBlockParseError {
203 #[error("failed to parse CSS declaration block `{input}` near `{context}`: {reason}")]
205 InvalidDeclarationBlock {
206 input: String,
208 context: String,
210 reason: String,
212 },
213}
214
215#[derive(Debug, Clone, PartialEq, Eq)]
217pub struct StyleSheetParseError {
218 pub context: Option<String>,
220 pub kind: StyleSheetParseErrorKind,
222}
223
224#[derive(Error, Debug, Clone, PartialEq, Eq)]
226pub enum StyleSheetParseErrorKind {
227 #[error("{0}")]
229 InvalidStyleSheet(String),
230
231 #[error("unsupported media feature")]
233 UnsupportedMediaFeature,
234
235 #[error("@property inherits must be true or false")]
237 PropertyInheritsMustBeBoolean,
238
239 #[error("missing `@property` syntax")]
241 MissingPropertySyntax,
242
243 #[error("missing `@property` inherits")]
245 MissingPropertyInherits,
246
247 #[error("`@property` with a typed syntax needs an initial-value")]
249 MissingPropertyInitialValue,
250
251 #[error("`@property` syntax is not a valid syntax string")]
253 InvalidPropertySyntax,
254
255 #[error("`@property` initial-value must match its syntax and be computationally independent")]
258 InvalidPropertyInitialValue,
259
260 #[error("@supports cannot mix `and` and `or` without parentheses")]
262 SupportsMixedAndOrWithoutParentheses,
263
264 #[error("@apply expects plain utilities without variants")]
266 InvalidApplyUtility,
267
268 #[error("@property name must be a custom property")]
270 PropertyNameMustBeCustomProperty,
271
272 #[error("@layer blocks accept at most one name")]
274 LayerBlockMultipleNames,
275
276 #[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 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 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}