Skip to main content

ferric_alpha_render/
options.rs

1use serde::{Deserialize, Serialize};
2
3use crate::{RenderError, RenderResult};
4
5pub const MIN_WIDTH: u32 = 720;
6pub const MAX_WIDTH: u32 = 4096;
7pub const MAX_PHYSICAL_SIDE: u32 = 8_192;
8pub const MAX_LOGICAL_HEIGHT: u32 = 32_768;
9pub const MAX_PANELS: usize = 256;
10pub const MAX_PNG_PIXELS: u64 = 16_000_000;
11pub const MAX_PNG_BYTES: usize = 64 * 1024 * 1024;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
14#[serde(rename_all = "snake_case")]
15pub enum RenderTheme {
16    Light,
17    Dark,
18}
19
20#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
21pub struct RenderOptions {
22    pub width: u32,
23    pub scale: f64,
24    pub theme: RenderTheme,
25}
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub struct PhysicalSize {
29    pub width: u32,
30    pub height: u32,
31}
32
33impl Default for RenderOptions {
34    fn default() -> Self {
35        Self {
36            width: 1200,
37            scale: 1.0,
38            theme: RenderTheme::Light,
39        }
40    }
41}
42
43impl RenderOptions {
44    pub fn validate(&self, logical_height: u32) -> RenderResult<PhysicalSize> {
45        if !(MIN_WIDTH..=MAX_WIDTH).contains(&self.width) {
46            return Err(RenderError::InvalidOption {
47                option: "width",
48                reason: "must be in 720..=4096",
49            });
50        }
51        if !self.scale.is_finite() || !(0.5..=4.0).contains(&self.scale) {
52            return Err(RenderError::InvalidOption {
53                option: "scale",
54                reason: "must be finite and in 0.5..=4.0",
55            });
56        }
57        if logical_height > MAX_LOGICAL_HEIGHT {
58            return Err(RenderError::LayoutOverflow);
59        }
60
61        let physical_width = checked_physical_dimension(self.width, self.scale)?;
62        let physical_height = checked_physical_dimension(logical_height, self.scale)?;
63        if physical_width > MAX_PHYSICAL_SIDE || physical_height > MAX_PHYSICAL_SIDE {
64            return Err(RenderError::LayoutOverflow);
65        }
66
67        let pixels = u64::from(physical_width)
68            .checked_mul(u64::from(physical_height))
69            .ok_or(RenderError::LayoutOverflow)?;
70        if pixels > MAX_PNG_PIXELS {
71            return Err(RenderError::LayoutOverflow);
72        }
73
74        Ok(PhysicalSize {
75            width: physical_width,
76            height: physical_height,
77        })
78    }
79}
80
81fn checked_physical_dimension(logical: u32, scale: f64) -> RenderResult<u32> {
82    let scaled = f64::from(logical) * scale;
83    if !scaled.is_finite() || scaled < 0.0 || scaled > f64::from(u32::MAX) {
84        return Err(RenderError::LayoutOverflow);
85    }
86    Ok(scaled.round() as u32)
87}