utopia_image/options.rs
1//! The values the operations take: gravities, focal points, output formats
2//! and resource limits.
3
4use std::str::FromStr;
5
6use crate::error::{Error, Result};
7
8/// Which part of the image a crop keeps.
9///
10/// PHP: the `Image::GRAVITY_*` string constants.
11///
12/// ```
13/// use utopia_image::Gravity;
14///
15/// assert_eq!(Gravity::from_name("top-left"), Some(Gravity::TopLeft));
16/// assert_eq!(Gravity::TopLeft.name(), "top-left");
17/// assert_eq!(Gravity::ALL.len(), 9);
18/// ```
19///
20/// ```php
21/// use Utopia\Image\Image;
22///
23/// echo Image::GRAVITY_TOP_LEFT, "\n"; // top-left
24/// echo count(Image::getGravityTypes()), "\n"; // 9
25/// ```
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
27pub enum Gravity {
28 /// `center`: a centred thumbnail crop.
29 #[default]
30 Center,
31 /// `top-left`
32 TopLeft,
33 /// `top`
34 Top,
35 /// `top-right`
36 TopRight,
37 /// `left`
38 Left,
39 /// `right`
40 Right,
41 /// `bottom-left`
42 BottomLeft,
43 /// `bottom`
44 Bottom,
45 /// `bottom-right`
46 BottomRight,
47}
48
49impl Gravity {
50 /// Every gravity, in the order of `Image::getGravityTypes()`.
51 ///
52 /// PHP: `Image::getGravityTypes()` returns their names.
53 pub const ALL: [Gravity; 9] = [
54 Gravity::Center,
55 Gravity::TopLeft,
56 Gravity::Top,
57 Gravity::TopRight,
58 Gravity::Left,
59 Gravity::Right,
60 Gravity::BottomLeft,
61 Gravity::Bottom,
62 Gravity::BottomRight,
63 ];
64
65 /// The PHP constant's value (`top-left`).
66 pub const fn name(self) -> &'static str {
67 match self {
68 Gravity::Center => "center",
69 Gravity::TopLeft => "top-left",
70 Gravity::Top => "top",
71 Gravity::TopRight => "top-right",
72 Gravity::Left => "left",
73 Gravity::Right => "right",
74 Gravity::BottomLeft => "bottom-left",
75 Gravity::Bottom => "bottom",
76 Gravity::BottomRight => "bottom-right",
77 }
78 }
79
80 /// The gravity named `name`, if there is one.
81 pub fn from_name(name: &str) -> Option<Gravity> {
82 Gravity::ALL.into_iter().find(|g| g.name() == name)
83 }
84}
85
86/// A focal point: the spot a crop keeps in view, as fractions of the width
87/// and height (`0.0..=1.0`).
88///
89/// PHP: the `$x` and `$y` arguments of `crop()`.
90///
91/// ```
92/// use utopia_image::FocalPoint;
93///
94/// let point = FocalPoint::new(0.75, 0.5)?;
95/// assert_eq!((point.x(), point.y()), (0.75, 0.5));
96/// assert!(FocalPoint::new(1.1, 0.5).is_err());
97/// assert!(FocalPoint::from_parts(Some(0.5), None).is_err());
98/// assert_eq!(FocalPoint::from_parts(None, None)?, None);
99/// # Ok::<(), utopia_image::Error>(())
100/// ```
101///
102/// ```php
103/// use Utopia\Image\Image;
104///
105/// $source = new \Imagick();
106/// $source->newImage(6, 2, 'red', 'png');
107/// $image = new Image($source->getImageBlob());
108/// $image->crop(2, 2, x: 0.75, y: 0.5);
109/// try {
110/// $image->crop(2, 2, x: 1.1, y: 0.5);
111/// } catch (\InvalidArgumentException $e) {
112/// echo $e->getMessage(), "\n";
113/// }
114/// ```
115#[derive(Debug, Clone, Copy, PartialEq)]
116pub struct FocalPoint {
117 x: f64,
118 y: f64,
119}
120
121impl FocalPoint {
122 /// A focal point, refused unless both coordinates are finite and within
123 /// `0.0..=1.0`.
124 pub fn new(x: f64, y: f64) -> Result<Self> {
125 if !x.is_finite() || !y.is_finite() || !(0.0..=1.0).contains(&x) || !(0.0..=1.0).contains(&y) {
126 return Err(Error::InvalidArgument("Focal point coordinates must be finite and between 0 and 1".into()));
127 }
128 Ok(FocalPoint { x, y })
129 }
130
131 /// A focal point from two optional coordinates, as a request carries them:
132 /// none for neither, an error for only one.
133 pub fn from_parts(x: Option<f64>, y: Option<f64>) -> Result<Option<Self>> {
134 match (x, y) {
135 (None, None) => Ok(None),
136 (Some(x), Some(y)) => FocalPoint::new(x, y).map(Some),
137 _ => Err(Error::InvalidArgument("Both focal point coordinates are required".into())),
138 }
139 }
140
141 /// The horizontal coordinate.
142 pub const fn x(self) -> f64 {
143 self.x
144 }
145
146 /// The vertical coordinate.
147 pub const fn y(self) -> f64 {
148 self.y
149 }
150}
151
152/// An output format.
153///
154/// PHP: the `$type` string of `output()` and `save()`; `jpg` and `jpeg` are
155/// the same format.
156///
157/// ```
158/// use utopia_image::OutputFormat;
159///
160/// assert_eq!("jpeg".parse::<OutputFormat>()?, OutputFormat::Jpeg);
161/// assert_eq!("bmp".parse::<OutputFormat>().unwrap_err().to_string(), "Unsupported output format: bmp");
162/// # Ok::<(), utopia_image::Error>(())
163/// ```
164///
165/// ```php
166/// use Utopia\Image\Image;
167///
168/// $source = new \Imagick();
169/// $source->newImage(2, 2, 'red', 'png');
170/// try {
171/// (new Image($source->getImageBlob()))->output('bmp');
172/// } catch (\Exception $e) {
173/// echo $e->getMessage(), "\n"; // Invalid output type given
174/// }
175/// ```
176#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
177pub enum OutputFormat {
178 /// `jpg` or `jpeg`
179 Jpeg,
180 /// `gif`, every frame
181 Gif,
182 /// `png`, the first frame
183 Png,
184 /// `webp`, every frame
185 Webp,
186 /// `avif`, the first frame
187 Avif,
188 /// `heic`: refused, as no HEVC encoder is available (see the crate docs)
189 Heic,
190}
191
192impl FromStr for OutputFormat {
193 type Err = Error;
194
195 fn from_str(s: &str) -> Result<Self> {
196 Ok(match s {
197 "jpg" | "jpeg" => OutputFormat::Jpeg,
198 "gif" => OutputFormat::Gif,
199 "png" => OutputFormat::Png,
200 "webp" => OutputFormat::Webp,
201 "avif" => OutputFormat::Avif,
202 "heic" => OutputFormat::Heic,
203 _ => return Err(Error::UnsupportedFormat(format!("Unsupported output format: {s}"))),
204 })
205 }
206}
207
208/// What one image may cost: its largest width and height in pixels, and how
209/// many bytes of decoded pixels it may hold at once.
210///
211/// The defaults are conservative (16,000 pixels a side, 512 MiB of pixels); a
212/// caller that wants more says so. There is no "unlimited".
213///
214/// PHP: `Utopia\Image\Limits`.
215///
216/// ```
217/// use utopia_image::Limits;
218///
219/// let limits = Limits { width: 4_000, ..Limits::default() };
220/// assert_eq!(limits.height, 16_000);
221/// ```
222#[derive(Debug, Clone, Copy, PartialEq, Eq)]
223pub struct Limits {
224 /// The largest width of any image held, decoded or produced.
225 pub width: u64,
226 /// The largest height of any image held, decoded or produced.
227 pub height: u64,
228 /// Bytes of decoded pixels held at once (four a pixel, every frame).
229 pub memory: u64,
230}
231
232impl Default for Limits {
233 fn default() -> Self {
234 Limits { width: 16_000, height: 16_000, memory: 512 * 1024 * 1024 }
235 }
236}
237
238thread_local! {
239 /// The limits of the canvas being worked on. Every operation runs to
240 /// completion on the calling thread, so the decoders and transforms read
241 /// them from here rather than each taking them as an argument.
242 static ACTIVE: std::cell::Cell<Limits> = std::cell::Cell::new(Limits::default());
243}
244
245impl Limits {
246 /// Runs `work` under these limits, restoring the previous ones after, also when `work`
247 /// panics: the extension turns a panic into a PHP error and the worker carries on.
248 pub(crate) fn scope<T>(self, work: impl FnOnce() -> T) -> T {
249 struct Restore(Limits);
250 impl Drop for Restore {
251 fn drop(&mut self) {
252 ACTIVE.set(self.0);
253 }
254 }
255 let _restore = Restore(ACTIVE.replace(self));
256 work()
257 }
258
259 fn active() -> Limits {
260 ACTIVE.get()
261 }
262}
263
264/// Bytes of RGBA pixels held for one canvas of `width` x `height`.
265pub(crate) fn canvas_bytes(width: u64, height: u64) -> u64 {
266 width.saturating_mul(height).saturating_mul(4)
267}
268
269/// How many bytes of pixels the image being worked on may hold.
270pub(crate) fn pixel_budget() -> u64 {
271 Limits::active().memory
272}
273
274/// Fails when holding `bytes` more of pixels would pass [`pixel_budget`].
275/// Called with the size a decoder announces, before its buffers are allocated.
276pub(crate) fn check_pixels(bytes: u64) -> Result<()> {
277 if bytes > pixel_budget() {
278 return Err(Error::LimitExceeded);
279 }
280 Ok(())
281}
282
283/// Fails when a dimension passes its limit, or when one canvas of this size
284/// would pass the pixel budget.
285pub(crate) fn check_dimensions(width: u64, height: u64) -> Result<()> {
286 let limits = Limits::active();
287 if width > limits.width || height > limits.height {
288 return Err(Error::LimitExceeded);
289 }
290 check_pixels(canvas_bytes(width, height))
291}
292
293#[cfg(test)]
294mod tests {
295 use super::*;
296
297 #[test]
298 fn a_panic_inside_a_scope_restores_the_limits() {
299 let narrow = Limits { width: 1, height: 1, memory: 4 };
300 let panicked = std::panic::catch_unwind(|| narrow.scope(|| panic!("a codec panicked")));
301 assert!(panicked.is_err());
302 assert_eq!(Limits::active(), Limits::default());
303 assert!(check_dimensions(100, 100).is_ok());
304 }
305}