Skip to main content

pillow_rs/
lib.rs

1//! Pure Rust image processing with a Pillow-compatible core API.
2//!
3//! `pillow-rs` is the runtime-independent image crate used by the Python and
4//! WebAssembly bindings in this workspace. It takes Rust primitives, image
5//! buffers, mode strings, and font bytes as input; binding crates are
6//! responsible for translating Python objects, JavaScript objects, file paths,
7//! and host I/O before calling into this crate.
8//!
9//! # Design Boundary
10//!
11//! Core modules do not depend on Python or JavaScript runtime types. Public
12//! functions model Pillow behavior where practical, but their contracts are
13//! expressed in Rust terms: [`Image`] values, [`crate::raster::DynamicImage`]
14//! buffers, [`FreeTypeFont`] values, and [`PilError`] failures.
15//!
16//! # Allocation Safety
17//!
18//! Image allocation paths validate dimensions before allocating. This prevents
19//! zero-sized images, integer overflow, and accidental attacker-controlled large
20//! allocations before a pixel buffer is created.
21//!
22//! # Modes And Layout
23//!
24//! Public image APIs use Pillow mode strings such as `"L"`, `"RGB"`, `"RGBA"`,
25//! `"CMYK"`, `"P"`, and `"1"`. Core operations normalize those modes into Rust
26//! image buffers before dispatching to CPU, SIMD, or GPU backends. Raw byte APIs
27//! return tightly packed pixels in the image's current mode unless a method says
28//! otherwise.
29//!
30//! # Feature Flags
31//!
32//! - `gpu` enables the wgpu/WebGPU backend where an operation has a shader.
33//! - `parallel` opt-in enables Rayon-backed Parallel CPU row and pixel paths;
34//!   SIMD adapters and GPU execution stay thread-scheduler independent.
35//! - `image-codecs-all` enables all codec features exposed through
36//!   `image-slash-star`; individual codec features can be selected instead.
37//!
38//! CPU execution remains the fallback path. Feature flags should not change the
39//! public Pillow-style contract of an operation.
40//!
41//! # Public API Boundary
42//!
43//! `pillow-rs/src/lib.rs` is the single public API definition for this crate.
44//! Implementation modules are private crate internals; downstream callers,
45//! including the Python and WebAssembly bindings, must use the exact root
46//! symbols re-exported below such as [`Image`], [`FreeTypeFont`], [`Draw`],
47//! [`imageops_grayscale`], and [`imagefont_getbbox`].
48//!
49//! # Quick Start
50//!
51//! ```
52//! use pillow_rs::Image;
53//!
54//! let image = Image::new(4, 4, "RGB", (0, 128, 255, 255)).unwrap();
55//! assert_eq!(image.size().unwrap(), (4, 4));
56//! assert_eq!(image.mode().unwrap(), "RGB");
57//! ```
58//!
59//! # Converting Modes
60//!
61//! ```
62//! use pillow_rs::Image;
63//!
64//! let rgb = Image::new(2, 2, "RGB", (255, 0, 0, 255)).unwrap();
65//! let gray = rgb.convert("L", None, None, None, None).unwrap();
66//! assert_eq!(gray.mode().unwrap(), "L");
67//! assert_eq!(gray.tobytes().unwrap().len(), 4);
68//! ```
69//!
70// AS PER DESIGN — DO NOT REMOVE:
71//   These allows are explicitly deferred. pillow-rs must eventually:
72//   1. Replace unwrap() with expect() explaining invariants
73//   2. Prefer Result propagation for recoverable failures
74//   3. Replace .map().unwrap_or() with .map_or()
75//   4. Remove redundant clones
76//   5. Replace manual loop indexing with iter()/enumerate()
77//   Tracked at docs/ARCHITECTURE.md (existing Clippy allowances). Remove each when addressed.
78#![allow(clippy::unwrap_used)]
79#![allow(clippy::expect_used)]
80#![allow(clippy::unwrap_in_result)]
81#![allow(clippy::map_unwrap_or)]
82#![allow(clippy::redundant_clone)]
83#![allow(clippy::needless_range_loop)]
84// PIL API compatibility — many functions have 8+ parameters matching PIL signatures
85#![allow(clippy::too_many_arguments)]
86
87#[cfg(feature = "parallel")]
88use rayon as _;
89#[cfg(feature = "test-api")]
90use std::collections::BTreeMap;
91
92// ============================================================================
93// AS PER DESIGN — DO NOT REMOVE THESE MODULES:
94//   Each module below is a foundational piece of the systemic fix architecture
95//   (see docs/ARCHITECTURE.md). Removing any of them breaks the guarantees enforced
96//   by CI and creates entire classes of bugs.
97//
98//   - checked_dims:  Only way to allocate image buffers (no overflow, no DoS)
99//   - par:           Approved Rayon row helpers (opt-in through `parallel`)
100//   - image_utils:   Canonical buffer conversion (no duplicate copies)
101// ============================================================================
102
103/// Validated image dimensions and allocation-size helpers.
104mod checked_dims;
105/// Pillow-compatible color parsing and color-space conversion.
106mod color;
107/// CPU/GPU/SIMD operation registration and dispatch infrastructure.
108mod compute;
109/// Pillow-compatible drawing primitives and text rendering.
110mod draw;
111/// Error types shared by core image, drawing, color, and format operations.
112mod error;
113/// Pillow-compatible font loading and `_imagingft` adapter behavior.
114mod font;
115/// Lightweight image format identifiers.
116mod format;
117/// High-level image object and Pillow-style image methods.
118mod image;
119/// Rust-owned state for Pillow's host-neutral image-sequence iterator.
120mod image_sequence;
121/// Shared helpers for converting between image buffers and modes.
122mod image_utils;
123/// Exact Pillow-compatible RGB-to-LAB byte conversion.
124mod lab;
125/// Reusable image operation implementations.
126mod ops;
127#[cfg(feature = "parallel")]
128/// Approved parallel iteration helpers for pixel and row operations.
129mod par;
130/// Declarative operation pipeline types used by compute backends.
131///
132/// See [`pipeline::PipelineOp`] for the operation descriptor carried through
133/// lazy image pipelines.
134mod pipeline;
135/// Pillow-owned materialized pixel storage and raster primitives.
136mod raster;
137pub use crate::color::ColorValue;
138pub use crate::color::PaletteColorInput;
139pub use crate::color::color_has_explicit_alpha;
140pub use crate::color::getcolor;
141pub use crate::color::palette_getcolor;
142pub use crate::color::palette_getcolor_append;
143pub use crate::color::palette_getcolor_validate;
144pub use crate::color::palette_getcolor_validate_input;
145pub use crate::color::palette_to_text;
146pub use crate::color::parse_color_str;
147pub use crate::color::parse_color_str_unclamped;
148pub use crate::color::resolve_new_color;
149pub use crate::compute::Backend;
150#[cfg(feature = "gpu")]
151pub use crate::compute::BatchError;
152#[cfg(feature = "gpu")]
153pub use crate::compute::BatchErrorKind;
154#[cfg(feature = "gpu")]
155pub use crate::compute::BatchKey;
156#[cfg(feature = "gpu")]
157pub use crate::compute::BatchOutput;
158#[cfg(feature = "gpu")]
159pub use crate::compute::BatchResult;
160#[cfg(feature = "gpu")]
161pub use crate::compute::GpuBatchConfig;
162#[cfg(feature = "gpu")]
163pub use crate::compute::GpuBatchExecutor;
164#[cfg(feature = "gpu")]
165pub use crate::compute::GpuBatchStats;
166#[cfg(feature = "gpu")]
167pub use crate::compute::GpuImage;
168pub use crate::compute::PipelineOperationTelemetry;
169pub use crate::compute::PipelineResourceTelemetry;
170pub use crate::compute::active_backends;
171pub use crate::compute::available_backends;
172pub use crate::compute::backend_enabled;
173pub use crate::compute::disable_backend;
174pub use crate::compute::enable_backend;
175pub use crate::draw::Draw;
176pub use crate::draw::DrawBoxInput;
177pub use crate::draw::DrawCircleCenterInput;
178pub use crate::draw::DrawColorInput;
179pub use crate::draw::DrawPointsInput;
180pub use crate::draw::RegularPolygonCircle;
181pub use crate::draw::RegularPolygonSides;
182pub use crate::draw::normalize_draw_box;
183pub use crate::draw::normalize_draw_circle_center;
184pub use crate::draw::normalize_draw_width;
185pub use crate::draw::normalize_rounded_rectangle_box;
186pub use crate::draw::outline_curve_points;
187pub use crate::error::PilError;
188pub use crate::font::FreeTypeFont;
189pub use crate::font::ImageFontBBoxValue;
190pub use crate::font::ImageFontFaceInfo;
191pub use crate::font::ImageFontLoadOptions;
192pub use crate::font::ImageFontSourceInput;
193pub use crate::font::ImageFontTextInput;
194pub use crate::font::ImageFontTextOptions;
195pub use crate::font::ImageFontVariantOptions;
196pub use crate::font::ImageFontVariationAxesInput;
197pub use crate::font::ImageFontVariationAxis;
198pub use crate::font::ImageFontVariationNameInput;
199pub use crate::font::mask_image as imagefont_mask_image;
200pub use crate::font::normalize_font_bbox;
201pub use crate::font::normalize_layout_engine;
202pub use crate::font::pilfont::PilFont;
203pub use crate::font::pilfont::PilFontGlyphImage;
204pub use crate::font::pilfont::PilFontMask;
205pub use crate::font::pilfont::PilFontMode;
206pub use crate::font::pilfont::PilFontTextInput;
207pub use crate::font::transposed_bbox;
208pub use crate::font::validate_transposed_length;
209pub use crate::image::ChannelSelector;
210pub use crate::image::ExifCompatFields;
211pub use crate::image::FormattedExtrema;
212pub use crate::image::FormattedImageData;
213pub use crate::image::FormattedPixelValue;
214pub use crate::image::Image;
215pub use crate::image::ImageInfoValue;
216pub use crate::image::ImagingCoreBytesInput;
217pub use crate::image::PaletteTransparency;
218pub use crate::image::PutAlphaInput;
219pub use crate::image::PutDataInput;
220pub use crate::image::PutDataValue;
221pub use crate::image::PutDataValueKind;
222pub use crate::image::PutPixelValue;
223pub use crate::image::PythonNewColorInput;
224pub use crate::image::PythonOpenFormatsInput;
225pub use crate::image::PythonOpenModeInput;
226pub use crate::image::StatResult;
227pub use crate::image::StatValue;
228pub use crate::image::imaging_core_to_bytes;
229pub use crate::image::prepare_exif_compat;
230pub use crate::image::stat_from_histogram;
231pub use crate::image::stat_from_list;
232pub use crate::image::validate_python_open_inputs;
233pub use crate::image::validate_python_open_source_bytes;
234pub use crate::image_sequence::ImageSequenceIterator;
235pub use crate::ops::analysis::ImageAnalysisMask;
236pub use crate::ops::analysis::validate_transparency_mask;
237pub use crate::ops::array::ArrayLayout;
238pub use crate::ops::array::from_resolved_array_interface;
239pub use crate::ops::array::resolve_array_layout;
240pub use crate::ops::chops::add as chops_add;
241pub use crate::ops::chops::add_modulo as chops_add_modulo;
242pub use crate::ops::chops::constant as chops_constant;
243pub use crate::ops::chops::darker as chops_darker;
244pub use crate::ops::chops::difference as chops_difference;
245pub use crate::ops::chops::duplicate as chops_duplicate;
246pub use crate::ops::chops::hard_light as chops_hard_light;
247pub use crate::ops::chops::invert as chops_invert;
248pub use crate::ops::chops::lighter as chops_lighter;
249pub use crate::ops::chops::logical_and as chops_logical_and;
250pub use crate::ops::chops::logical_or as chops_logical_or;
251pub use crate::ops::chops::logical_xor as chops_logical_xor;
252pub use crate::ops::chops::multiply as chops_multiply;
253pub use crate::ops::chops::offset as chops_offset;
254pub use crate::ops::chops::offset_with_default as chops_offset_with_default;
255pub use crate::ops::chops::overlay as chops_overlay;
256pub use crate::ops::chops::screen as chops_screen;
257pub use crate::ops::chops::soft_light as chops_soft_light;
258pub use crate::ops::chops::subtract as chops_subtract;
259pub use crate::ops::chops::subtract_modulo as chops_subtract_modulo;
260pub use crate::ops::convert::PythonConvertModeInput;
261pub use crate::ops::convert::PythonConvertPaletteInput;
262pub use crate::ops::convert::PythonDitherInput;
263pub use crate::ops::convert::normalize_python_convert_dither;
264pub use crate::ops::convert::validate_python_convert_dither;
265pub use crate::ops::filter::prepare_kernel;
266pub use crate::ops::filter::validate_kernel_coefficients;
267pub use crate::ops::imageops::CenteringInput;
268pub use crate::ops::imageops::ImageOpsColor;
269pub use crate::ops::imageops::ImageOpsMask;
270pub use crate::ops::imageops::SolarizeInput;
271pub use crate::ops::imageops::autocontrast as imageops_autocontrast;
272pub use crate::ops::imageops::autocontrast_with_mask as imageops_autocontrast_with_mask;
273pub use crate::ops::imageops::colorize as imageops_colorize;
274pub use crate::ops::imageops::contain as imageops_contain;
275pub use crate::ops::imageops::contain_with_input as imageops_contain_with_input;
276pub use crate::ops::imageops::cover as imageops_cover;
277pub use crate::ops::imageops::cover_with_input as imageops_cover_with_input;
278pub use crate::ops::imageops::crop as imageops_crop;
279pub use crate::ops::imageops::equalize as imageops_equalize;
280pub use crate::ops::imageops::equalize_with_mask as imageops_equalize_with_mask;
281pub use crate::ops::imageops::exif_get_orientation;
282pub use crate::ops::imageops::exif_remove_orientation;
283pub use crate::ops::imageops::exif_transpose as imageops_exif_transpose;
284pub use crate::ops::imageops::expand as imageops_expand;
285pub use crate::ops::imageops::expand_with_input as imageops_expand_with_input;
286pub use crate::ops::imageops::fit as imageops_fit;
287pub use crate::ops::imageops::fit_with_input as imageops_fit_with_input;
288pub use crate::ops::imageops::flip as imageops_flip;
289pub use crate::ops::imageops::grayscale as imageops_grayscale;
290pub use crate::ops::imageops::invert_ops as imageops_invert;
291pub use crate::ops::imageops::mirror as imageops_mirror;
292pub use crate::ops::imageops::pad as imageops_pad;
293pub use crate::ops::imageops::pad_with_input as imageops_pad_with_input;
294pub use crate::ops::imageops::posterize as imageops_posterize;
295pub use crate::ops::imageops::scale_with_input as imageops_scale_with_input;
296pub use crate::ops::imageops::solarize as imageops_solarize;
297pub use crate::ops::imageops::solarize_with_input as imageops_solarize_with_input;
298pub use crate::ops::imageops::validate_colorize_mode as imageops_validate_colorize_mode;
299pub use crate::ops::imageops::validate_deform_resample as imageops_validate_deform_resample;
300pub use crate::ops::module_fns::EvalInputKind;
301pub use crate::ops::module_fns::MergeInput;
302pub use crate::ops::module_fns::alpha_composite as image_alpha_composite;
303pub use crate::ops::module_fns::blend as image_blend;
304pub use crate::ops::module_fns::composite as image_composite;
305pub use crate::ops::module_fns::effect_mandelbrot as image_effect_mandelbrot;
306pub use crate::ops::module_fns::effect_mandelbrot_with_extent as image_effect_mandelbrot_with_extent;
307pub use crate::ops::module_fns::effect_noise as image_effect_noise;
308pub use crate::ops::module_fns::effect_noise_from_size as image_effect_noise_from_size;
309pub use crate::ops::module_fns::effect_spread as image_effect_spread;
310pub use crate::ops::module_fns::eval as image_eval;
311pub use crate::ops::module_fns::eval_callable as image_eval_callable;
312pub use crate::ops::module_fns::eval_float as image_eval_float;
313pub use crate::ops::module_fns::eval_point_transform as image_eval_point_transform;
314pub use crate::ops::module_fns::eval_replicated_for_image as image_eval_replicated_for_image;
315pub use crate::ops::module_fns::eval_validated as image_eval_validated;
316pub use crate::ops::module_fns::frombytes as image_frombytes;
317pub use crate::ops::module_fns::frombytes_owned as image_frombytes_owned;
318pub use crate::ops::module_fns::linear_gradient as image_linear_gradient;
319pub use crate::ops::module_fns::make_lut;
320pub use crate::ops::module_fns::merge as image_merge;
321pub use crate::ops::module_fns::merge_inputs as image_merge_inputs;
322pub use crate::ops::module_fns::radial_gradient as image_radial_gradient;
323pub use crate::ops::module_fns::validate_eval_input;
324pub use crate::ops::param_filters::Color3DLutTable;
325pub use crate::ops::param_filters::PreparedColor3DLut;
326pub use crate::ops::param_filters::color3dlut_check_size;
327pub use crate::ops::param_filters::color3dlut_generate_table;
328pub use crate::ops::param_filters::color3dlut_prepare_table;
329pub use crate::ops::param_filters::color3dlut_repr;
330pub use crate::ops::param_filters::color3dlut_transform_table;
331pub use crate::ops::param_filters::prepare_color3dlut;
332pub use crate::ops::paste::AlphaCompositeBox;
333pub use crate::ops::paste::PasteSource;
334pub use crate::ops::paste::PythonPasteBox;
335pub use crate::ops::paste::PythonPasteMask;
336pub use crate::ops::paste::PythonPasteSource;
337pub use crate::ops::quantize::QuantizePalette;
338pub use crate::ops::resize::ResampleInput;
339pub use crate::ops::resize::parse_resample;
340pub use crate::ops::resize::parse_resample_input;
341pub use crate::ops::rotate::RotateExpandInput;
342pub use crate::ops::rotate::RotatePointInput;
343pub use crate::ops::rotate::RotateResampleInput;
344pub use crate::ops::rotate::normalize_python_rotate;
345pub use crate::ops::transform::ReduceBox;
346pub use crate::ops::transform::ReduceFactor;
347pub use crate::ops::transform::TransformData;
348pub use crate::ops::transform::TransformFill;
349pub use crate::ops::transpose::TransposeInput;
350pub use crate::ops::transpose::normalize_transpose_input;
351pub use crate::ops::transpose::normalize_transposed_font_input;
352pub use crate::ops::transpose::transpose_name_from_int;
353pub use crate::ops::utils::align_row_to_32;
354pub use crate::pipeline::ColorMode;
355pub use crate::pipeline::DitherMethod;
356pub use crate::pipeline::PipelineOp;
357pub use crate::pipeline::PixelMode;
358pub use crate::pipeline::ResampleFilter;
359pub use crate::pipeline::TransformMethod;
360pub use crate::pipeline::TransposeMethod;
361pub use crate::raster::ConvertBuffer;
362pub use crate::raster::DynamicImage;
363pub use crate::raster::EncodableLayout;
364pub use crate::raster::Enlargeable;
365pub use crate::raster::EnumeratePixels;
366pub use crate::raster::EnumeratePixelsMut;
367pub use crate::raster::EnumerateRows;
368pub use crate::raster::EnumerateRowsMut;
369pub use crate::raster::ExtendedColorType;
370pub use crate::raster::FromColor;
371pub use crate::raster::FromPrimitive;
372pub use crate::raster::GenericImage;
373pub use crate::raster::GenericImageView;
374pub use crate::raster::GrayAlphaImage;
375pub use crate::raster::GrayImage;
376pub use crate::raster::ImageBuffer;
377pub use crate::raster::Luma;
378pub use crate::raster::LumaA;
379pub use crate::raster::Pixel;
380pub use crate::raster::Pixels;
381pub use crate::raster::PixelsMut;
382pub use crate::raster::Primitive;
383pub use crate::raster::Rect;
384pub use crate::raster::Rgb;
385pub use crate::raster::Rgb32FImage;
386pub use crate::raster::RgbImage;
387pub use crate::raster::Rgba;
388pub use crate::raster::Rgba32FImage;
389pub use crate::raster::RgbaImage;
390pub use crate::raster::Rows;
391pub use crate::raster::RowsMut;
392
393/// Load a TrueType/OpenType face from bytes at the requested Pillow point size.
394pub fn imagefont_from_bytes(data: Vec<u8>, size: f32) -> Result<FreeTypeFont, PilError> {
395    FreeTypeFont::from_bytes(data, size)
396}
397
398/// Load a TrueType/OpenType face from bytes with Pillow constructor options.
399pub fn imagefont_from_bytes_with_options(
400    data: Vec<u8>,
401    size: f32,
402    options: &ImageFontLoadOptions,
403) -> Result<FreeTypeFont, PilError> {
404    FreeTypeFont::from_bytes_with_options(data, size, options)
405}
406
407/// Load a TrueType/OpenType face from a host-marshaled source.
408pub fn imagefont_from_source(
409    source: ImageFontSourceInput,
410    size: f32,
411    options: &ImageFontLoadOptions,
412) -> Result<FreeTypeFont, PilError> {
413    FreeTypeFont::from_source(source, size, options)
414}
415
416/// Loads the same embedded default font subset as Pillow.
417pub fn imagefont_load_default(size: f32) -> Result<FreeTypeFont, PilError> {
418    FreeTypeFont::load_default(size)
419}
420
421/// Return the requested Pillow point size for this FreeType font.
422pub fn imagefont_size(font: &FreeTypeFont) -> f32 {
423    font.font_size()
424}
425
426/// Return the non-negative text mask extent for Pillow-style text layout.
427pub fn imagefont_text_bbox(font: &FreeTypeFont, text: &str) -> Result<(u32, u32), PilError> {
428    font.text_bbox(text)
429}
430
431/// Return the non-negative text mask extent for Pillow byte text.
432pub fn imagefont_text_bbox_bytes(font: &FreeTypeFont, text: &[u8]) -> Result<(u32, u32), PilError> {
433    font.text_bbox_bytes(text)
434}
435
436/// Return Pillow's public `(family, style)` font name tuple.
437pub fn imagefont_getname(font: &FreeTypeFont) -> (Option<&str>, Option<&str>) {
438    font.getname()
439}
440
441/// Return Pillow's raw public name tuple, preserving missing face names.
442pub fn imagefont_getname_optional(font: &FreeTypeFont) -> (Option<&str>, Option<&str>) {
443    font.getname_optional()
444}
445
446/// Return Pillow's public ascent/descent metrics.
447pub fn imagefont_getmetrics(font: &FreeTypeFont) -> (u32, u32) {
448    font.getmetrics()
449}
450
451/// Return Pillow's public text length in pixels.
452pub fn imagefont_getlength(font: &FreeTypeFont, text: &str) -> Result<f32, PilError> {
453    font.getlength(text)
454}
455
456/// Return Pillow native `_imagingft.Font.getlength()` 26.6 advance.
457pub fn imagefont_native_getlength_26dot6(font: &FreeTypeFont, text: &str) -> Result<i32, PilError> {
458    font.native_getlength_26dot6(text)
459}
460
461/// Return Pillow native `_imagingft.Font.getsize()` size and offset tuple.
462pub fn imagefont_native_getsize(
463    font: &FreeTypeFont,
464    text: &str,
465) -> Result<((i32, i32), (i32, i32)), PilError> {
466    font.native_getsize(text)
467}
468
469/// Return Pillow native `_imagingft.Font.render()` mask and offset.
470pub fn imagefont_native_render(
471    font: &FreeTypeFont,
472    text: &str,
473    options: &ImageFontTextOptions,
474) -> Result<(u32, u32, Vec<u8>, (i32, i32)), PilError> {
475    font.native_render(text, options)
476}
477
478/// Return Pillow native render output for host-classified text input.
479pub fn imagefont_native_render_input(
480    font: &FreeTypeFont,
481    text: ImageFontTextInput,
482    options: &ImageFontTextOptions,
483) -> Result<(u32, u32, Vec<u8>, (i32, i32)), PilError> {
484    font.native_render_input(text, options)
485}
486
487/// Return Pillow native `_imagingft.Font` public face attributes.
488pub fn imagefont_native_face_attrs(
489    font: &FreeTypeFont,
490) -> (Option<&str>, Option<&str>, u32, u32, u32, u32, u32, i64) {
491    font.native_face_attrs()
492}
493
494/// Return the active font face capabilities reported by fontdone.
495pub fn imagefont_native_face_info(font: &FreeTypeFont) -> ImageFontFaceInfo<'_> {
496    font.native_face_info()
497}
498
499/// Return the active font-driver format reported by fontdone.
500pub fn imagefont_font_format(font: &FreeTypeFont) -> &'static str {
501    font.font_format()
502}
503
504/// Return whether the active font face has scalable outlines.
505pub fn imagefont_is_scalable(font: &FreeTypeFont) -> bool {
506    font.is_scalable()
507}
508
509/// Return Pillow's public text length for byte text.
510pub fn imagefont_getlength_bytes(font: &FreeTypeFont, text: &[u8]) -> Result<f32, PilError> {
511    font.getlength_bytes(text)
512}
513
514/// Return Pillow's public text length with optional layout arguments.
515pub fn imagefont_getlength_with_options(
516    font: &FreeTypeFont,
517    text: &str,
518    options: &ImageFontTextOptions,
519) -> Result<f32, PilError> {
520    font.getlength_with_options(text, options)
521}
522
523/// Return Pillow's public text length for byte text with optional layout arguments.
524pub fn imagefont_getlength_bytes_with_options(
525    font: &FreeTypeFont,
526    text: &[u8],
527    options: &ImageFontTextOptions,
528) -> Result<f32, PilError> {
529    font.getlength_bytes_with_options(text, options)
530}
531
532/// Return whether the font exposes variation axes.
533pub fn imagefont_has_variations(font: &FreeTypeFont) -> bool {
534    font.has_variations()
535}
536
537/// Create a Pillow-compatible variant font.
538pub fn imagefont_variant(font: &FreeTypeFont, size: Option<f32>) -> Result<FreeTypeFont, PilError> {
539    font.font_variant(size)
540}
541
542/// Create a Pillow-compatible variant font with public override arguments.
543pub fn imagefont_variant_with_options(
544    font: &FreeTypeFont,
545    options: &ImageFontVariantOptions,
546) -> Result<FreeTypeFont, PilError> {
547    font.font_variant_with_options(options)
548}
549
550/// Return Pillow's public variation-axis records.
551pub fn imagefont_get_variation_axes(
552    font: &FreeTypeFont,
553) -> Result<Vec<ImageFontVariationAxis>, PilError> {
554    font.get_variation_axes()
555}
556
557/// Return Pillow's public named-variation style names.
558pub fn imagefont_get_variation_names(font: &FreeTypeFont) -> Result<Vec<Vec<u8>>, PilError> {
559    font.get_variation_names()
560}
561
562/// Set a named variation instance by Pillow-style name bytes.
563pub fn imagefont_set_variation_by_name(
564    font: &mut FreeTypeFont,
565    name: &[u8],
566) -> Result<(), PilError> {
567    font.set_variation_by_name(name)
568}
569
570/// Set a named variation instance after applying Pillow's host input rules.
571pub fn imagefont_set_variation_by_name_input(
572    font: &mut FreeTypeFont,
573    name: ImageFontVariationNameInput,
574) -> Result<(), PilError> {
575    font.set_variation_by_name_input(name)
576}
577
578/// Set variation design coordinates from Pillow-style user coordinates.
579pub fn imagefont_set_variation_by_axes(
580    font: &mut FreeTypeFont,
581    axes: &[f32],
582) -> Result<(), PilError> {
583    font.set_variation_by_axes(axes)
584}
585
586/// Validate and set variation axes using Pillow's list-only public contract.
587pub fn imagefont_set_variation_by_axes_input(
588    font: &mut FreeTypeFont,
589    input: ImageFontVariationAxesInput,
590) -> Result<(), PilError> {
591    match input {
592        ImageFontVariationAxesInput::Values(axes) => imagefont_set_variation_by_axes(font, &axes),
593        ImageFontVariationAxesInput::Invalid => {
594            Err(PilError::TypeError("argument must be a list".into()))
595        }
596    }
597}
598
599/// Return Pillow native `_imagingft.Font.getvaraxes()` records.
600pub fn imagefont_native_getvaraxes(
601    font: &FreeTypeFont,
602) -> Result<Vec<ImageFontVariationAxis>, PilError> {
603    font.native_getvaraxes()
604}
605
606/// Return Pillow native `_imagingft.Font.getvarnames()` records.
607pub fn imagefont_native_getvarnames(font: &FreeTypeFont) -> Result<Vec<Vec<u8>>, PilError> {
608    font.native_getvarnames()
609}
610
611/// Set Pillow native `_imagingft.Font` named instance index.
612pub fn imagefont_native_setvarname(
613    font: &mut FreeTypeFont,
614    instance_index: i64,
615) -> Result<(), PilError> {
616    font.native_setvarname(instance_index)
617}
618
619/// Set Pillow native `_imagingft.Font` variation coordinates.
620pub fn imagefont_native_setvaraxes(font: &mut FreeTypeFont, axes: &[f32]) -> Result<(), PilError> {
621    font.native_setvaraxes(axes)
622}
623
624/// Return Pillow's public text bounding box.
625pub fn imagefont_getbbox(
626    font: &FreeTypeFont,
627    text: &str,
628) -> Result<(i32, i32, i32, i32), PilError> {
629    font.getbbox(text)
630}
631
632/// Return Pillow's public text bounding box for byte text.
633pub fn imagefont_getbbox_bytes(
634    font: &FreeTypeFont,
635    text: &[u8],
636) -> Result<(i32, i32, i32, i32), PilError> {
637    font.getbbox_bytes(text)
638}
639
640/// Return Pillow's public binary-mode text bounding box.
641#[cfg(feature = "test-api")]
642pub fn imagefont_getbbox_binary(
643    font: &FreeTypeFont,
644    text: &str,
645) -> Result<(i32, i32, i32, i32), PilError> {
646    font.getbbox_binary(text)
647}
648
649/// Return Pillow's public binary-mode text bounding box for byte text.
650#[cfg(feature = "test-api")]
651pub fn imagefont_getbbox_binary_bytes(
652    font: &FreeTypeFont,
653    text: &[u8],
654) -> Result<(i32, i32, i32, i32), PilError> {
655    font.getbbox_binary_bytes(text)
656}
657
658/// Return Pillow's public text bounding box with optional layout arguments.
659pub fn imagefont_getbbox_with_options(
660    font: &FreeTypeFont,
661    text: &str,
662    options: &ImageFontTextOptions,
663) -> Result<(f32, f32, f32, f32), PilError> {
664    font.getbbox_with_options(text, options)
665}
666
667/// Return a text bounding box using Pillow's optional draw-font rules.
668pub fn imagefont_getbbox_with_optional_font(
669    font: Option<&FreeTypeFont>,
670    size: Option<f32>,
671    text: &str,
672    options: &ImageFontTextOptions,
673) -> Result<(f32, f32, f32, f32), PilError> {
674    crate::font::with_text_font(font, size, |font| font.getbbox_with_options(text, options))
675}
676
677/// Return an offset text bounding box using Pillow's optional draw-font rules.
678pub fn imagefont_textbbox_at_with_optional_font(
679    font: Option<&FreeTypeFont>,
680    size: Option<f32>,
681    xy: (i32, i32),
682    text: &str,
683    options: &ImageFontTextOptions,
684) -> Result<(i32, i32, i32, i32), PilError> {
685    let bbox = imagefont_getbbox_with_optional_font(font, size, text, options)?;
686    Ok((
687        xy.0 + bbox.0 as i32,
688        xy.1 + bbox.1 as i32,
689        xy.0 + bbox.2 as i32,
690        xy.1 + bbox.3 as i32,
691    ))
692}
693
694/// Return an offset text bounding box using host-classified text input.
695pub fn imagefont_textbbox_at_with_optional_font_input(
696    font: Option<&FreeTypeFont>,
697    size: Option<f32>,
698    xy: (i32, i32),
699    text: ImageFontTextInput,
700    options: &ImageFontTextOptions,
701) -> Result<(i32, i32, i32, i32), PilError> {
702    let bbox = crate::font::with_text_font(font, size, |font| {
703        font.getbbox_input_with_options(text, options)
704    })?;
705    Ok((
706        xy.0 + bbox.0 as i32,
707        xy.1 + bbox.1 as i32,
708        xy.0 + bbox.2 as i32,
709        xy.1 + bbox.3 as i32,
710    ))
711}
712
713/// Return text length using Pillow's optional draw-font rules.
714pub fn imagefont_getlength_with_optional_font(
715    font: Option<&FreeTypeFont>,
716    size: Option<f32>,
717    text: &str,
718    options: &ImageFontTextOptions,
719) -> Result<f32, PilError> {
720    crate::font::with_text_font(font, size, |font| {
721        font.getlength_with_options(text, options)
722    })
723}
724
725/// Return text length using optional-font rules and host-classified text input.
726pub fn imagefont_getlength_with_optional_font_input(
727    font: Option<&FreeTypeFont>,
728    size: Option<f32>,
729    text: ImageFontTextInput,
730    options: &ImageFontTextOptions,
731) -> Result<f32, PilError> {
732    crate::font::with_text_font(font, size, |font| {
733        font.getlength_input_with_options(text, options)
734    })
735}
736
737/// Return Pillow's public multiline text bounding box.
738pub fn imagefont_multiline_textbbox(
739    font: &FreeTypeFont,
740    xy: (i32, i32),
741    text: &str,
742    spacing: i32,
743    align: &str,
744    options: &ImageFontTextOptions,
745) -> Result<(i32, i32, i32, i32), PilError> {
746    font.multiline_textbbox(xy, text, spacing, align, options)
747}
748
749/// Return a multiline text bounding box using Pillow's optional draw-font rules.
750pub fn imagefont_multiline_textbbox_with_optional_font(
751    font: Option<&FreeTypeFont>,
752    size: Option<f32>,
753    xy: (i32, i32),
754    text: &str,
755    spacing: i32,
756    align: &str,
757    options: &ImageFontTextOptions,
758) -> Result<(i32, i32, i32, i32), PilError> {
759    crate::font::with_text_font(font, size, |font| {
760        font.multiline_textbbox(xy, text, spacing, align, options)
761    })
762}
763
764/// Return a multiline text bounding box using host-classified text input.
765pub fn imagefont_multiline_textbbox_with_optional_font_input(
766    font: Option<&FreeTypeFont>,
767    size: Option<f32>,
768    xy: (i32, i32),
769    text: ImageFontTextInput,
770    spacing: i32,
771    align: &str,
772    options: &ImageFontTextOptions,
773) -> Result<(i32, i32, i32, i32), PilError> {
774    crate::font::with_text_font(font, size, |font| {
775        font.multiline_textbbox_input(xy, text, spacing, align, options)
776    })
777}
778
779/// Return Pillow's public text bounding box for byte text with optional layout arguments.
780pub fn imagefont_getbbox_bytes_with_options(
781    font: &FreeTypeFont,
782    text: &[u8],
783    options: &ImageFontTextOptions,
784) -> Result<(f32, f32, f32, f32), PilError> {
785    font.getbbox_bytes_with_options(text, options)
786}
787
788/// Return Pillow's public text bounding box for host-classified text input.
789pub fn imagefont_getbbox_input_with_options(
790    font: &FreeTypeFont,
791    text: ImageFontTextInput,
792    options: &ImageFontTextOptions,
793) -> Result<(f32, f32, f32, f32), PilError> {
794    font.getbbox_input_with_options(text, options)
795}
796
797/// Return the Pillow-compatible grayscale text mask.
798pub fn imagefont_getmask(font: &FreeTypeFont, text: &str) -> Result<(u32, u32, Vec<u8>), PilError> {
799    font.getmask(text)
800}
801
802/// Return the Pillow-compatible grayscale text mask for byte text.
803pub fn imagefont_getmask_bytes(
804    font: &FreeTypeFont,
805    text: &[u8],
806) -> Result<(u32, u32, Vec<u8>), PilError> {
807    font.getmask_bytes(text)
808}
809
810/// Render a Pillow-compatible mask with offset.
811pub fn imagefont_getmask2(
812    font: &FreeTypeFont,
813    text: &str,
814) -> Result<(u32, u32, Vec<u8>, (i32, i32)), PilError> {
815    font.getmask2(text)
816}
817
818/// Render a Pillow-compatible mask with offset for byte text.
819pub fn imagefont_getmask2_bytes(
820    font: &FreeTypeFont,
821    text: &[u8],
822) -> Result<(u32, u32, Vec<u8>, (i32, i32)), PilError> {
823    font.getmask2_bytes(text)
824}
825
826/// Return the Pillow-compatible grayscale text mask with optional render arguments.
827pub fn imagefont_getmask_with_options(
828    font: &FreeTypeFont,
829    text: &str,
830    options: &ImageFontTextOptions,
831) -> Result<(u32, u32, Vec<u8>), PilError> {
832    font.getmask_with_options(text, options)
833}
834
835/// Return the Pillow-compatible grayscale text mask for byte text with optional render arguments.
836pub fn imagefont_getmask_bytes_with_options(
837    font: &FreeTypeFont,
838    text: &[u8],
839    options: &ImageFontTextOptions,
840) -> Result<(u32, u32, Vec<u8>), PilError> {
841    font.getmask_bytes_with_options(text, options)
842}
843
844/// Return the Pillow-compatible grayscale text mask for host-classified text.
845pub fn imagefont_getmask_input_with_options(
846    font: &FreeTypeFont,
847    text: ImageFontTextInput,
848    options: &ImageFontTextOptions,
849) -> Result<(u32, u32, Vec<u8>), PilError> {
850    font.getmask_input_with_options(text, options)
851}
852
853/// Render a Pillow-compatible mask with a fractional raster start.
854pub fn imagefont_getmask2_with_start(
855    font: &FreeTypeFont,
856    text: &str,
857    start: (f64, f64),
858) -> Result<(u32, u32, Vec<u8>, (i32, i32)), PilError> {
859    font.getmask2_with_start(text, start)
860}
861
862/// Render a Pillow-compatible byte-text mask with a fractional raster start.
863pub fn imagefont_getmask2_bytes_with_start(
864    font: &FreeTypeFont,
865    text: &[u8],
866    start: (f64, f64),
867) -> Result<(u32, u32, Vec<u8>, (i32, i32)), PilError> {
868    font.getmask2_bytes_with_start(text, start)
869}
870
871/// Render a Pillow-compatible mask with optional render arguments.
872pub fn imagefont_getmask2_with_options(
873    font: &FreeTypeFont,
874    text: &str,
875    options: &ImageFontTextOptions,
876) -> Result<(u32, u32, Vec<u8>, (i32, i32)), PilError> {
877    font.getmask2_with_options(text, options)
878}
879
880/// Render a Pillow-compatible byte-text mask with optional render arguments.
881pub fn imagefont_getmask2_bytes_with_options(
882    font: &FreeTypeFont,
883    text: &[u8],
884    options: &ImageFontTextOptions,
885) -> Result<(u32, u32, Vec<u8>, (i32, i32)), PilError> {
886    font.getmask2_bytes_with_options(text, options)
887}
888
889/// Render a Pillow-compatible mask with offset for host-classified text.
890pub fn imagefont_getmask2_input_with_options(
891    font: &FreeTypeFont,
892    text: ImageFontTextInput,
893    options: &ImageFontTextOptions,
894) -> Result<(u32, u32, Vec<u8>, (i32, i32)), PilError> {
895    font.getmask2_input_with_options(text, options)
896}
897
898/// Return text length for host-classified text input with optional layout.
899pub fn imagefont_getlength_input_with_options(
900    font: &FreeTypeFont,
901    text: ImageFontTextInput,
902    options: &ImageFontTextOptions,
903) -> Result<f32, PilError> {
904    font.getlength_input_with_options(text, options)
905}
906
907/// Render a font mask and apply Pillow's optional transpose operation.
908pub fn imagefont_get_transposed_mask(
909    font: &FreeTypeFont,
910    text: &str,
911    orientation: Option<&str>,
912) -> Result<(u32, u32, Vec<u8>), PilError> {
913    font.get_transposed_mask(text, orientation)
914}
915
916/// Return a transposed mask for host-classified text input.
917pub fn imagefont_get_transposed_mask_input(
918    font: &FreeTypeFont,
919    text: ImageFontTextInput,
920    orientation: Option<&str>,
921) -> Result<(u32, u32, Vec<u8>), PilError> {
922    font.get_transposed_mask_input(text, orientation)
923}
924
925/// Return Pillow-compatible binary-mode RGBA text rendering.
926#[cfg(feature = "test-api")]
927pub fn imagefont_render_text_binary(
928    font: &FreeTypeFont,
929    text: &str,
930    fill: (u8, u8, u8, u8),
931    spacing: f32,
932) -> Result<(u32, u32, Vec<u8>), PilError> {
933    font.render_text_binary(text, fill, spacing)
934}
935
936/// Public backend capability summary for one registered operation.
937#[cfg(feature = "test-api")]
938#[derive(Clone, Debug, PartialEq, Eq)]
939pub struct BackendSupportEntry {
940    /// CPU implementation marker.
941    pub cpu_fn: Option<()>,
942    /// SIMD-pool implementation marker.
943    pub simd_fn: Option<()>,
944    /// GPU shader name when the operation has a shader.
945    pub gpu_shader: Option<&'static str>,
946    /// GPU shader source marker.
947    pub gpu_source: Option<()>,
948}
949
950/// Returns the backend capability registry as explicit public summary data.
951#[cfg(feature = "test-api")]
952pub fn backend_support_registry() -> Result<BTreeMap<&'static str, BackendSupportEntry>, PilError> {
953    Ok(crate::compute::registry::registry()?
954        .iter()
955        .map(|(name, entry)| {
956            (
957                *name,
958                BackendSupportEntry {
959                    cpu_fn: entry.cpu_fn.map(|_| ()),
960                    simd_fn: entry.simd_fn.map(|_| ()),
961                    gpu_shader: {
962                        #[cfg(feature = "gpu")]
963                        {
964                            entry.gpu_shader
965                        }
966                        #[cfg(not(feature = "gpu"))]
967                        {
968                            None
969                        }
970                    },
971                    gpu_source: {
972                        #[cfg(feature = "gpu")]
973                        {
974                            entry.gpu_source.map(|_| ())
975                        }
976                        #[cfg(not(feature = "gpu"))]
977                        {
978                            None
979                        }
980                    },
981                },
982            )
983        })
984        .collect())
985}
986
987/// Returns whether CPU declares support for a pipeline operation.
988#[cfg(feature = "test-api")]
989pub fn backend_cpu_supports(op: &PipelineOp) -> Result<bool, PilError> {
990    crate::compute::registry::cpu_supports(op)
991}
992
993/// Returns whether SIMD declares support for a pipeline operation.
994#[cfg(feature = "test-api")]
995pub fn backend_simd_supports(op: &PipelineOp) -> Result<bool, PilError> {
996    crate::compute::registry::simd_supports(op)
997}
998
999/// Returns whether GPU declares support for a pipeline operation.
1000#[cfg(feature = "test-api")]
1001pub fn backend_gpu_supports(op: &PipelineOp) -> Result<bool, PilError> {
1002    #[cfg(feature = "gpu")]
1003    {
1004        crate::compute::registry::gpu_supports(op)
1005    }
1006    #[cfg(not(feature = "gpu"))]
1007    {
1008        let _ = op;
1009        Ok(false)
1010    }
1011}
1012
1013/// Returns the backend support matrix as deterministic pretty JSON.
1014#[cfg(feature = "test-api")]
1015pub fn backend_support_matrix_json() -> Result<String, PilError> {
1016    let registry = backend_support_registry()?;
1017    let operations = registry
1018        .iter()
1019        .map(|(name, entry)| {
1020            format!(
1021                "{{\"operation\":\"{name}\",\"cpu\":{},\"simd_pool\":{},\"gpu_shader\":{}}}",
1022                entry.cpu_fn.is_some(),
1023                entry.simd_fn.is_some(),
1024                entry.gpu_shader.is_some()
1025            )
1026        })
1027        .collect::<Vec<_>>();
1028    let cpu = registry
1029        .values()
1030        .filter(|entry| entry.cpu_fn.is_some())
1031        .count();
1032    let simd_pool = registry
1033        .values()
1034        .filter(|entry| entry.simd_fn.is_some())
1035        .count();
1036    let gpu_shader = registry
1037        .values()
1038        .filter(|entry| entry.gpu_shader.is_some())
1039        .count();
1040    let cpu_without_simd = registry
1041        .iter()
1042        .filter_map(|(name, entry)| {
1043            (entry.cpu_fn.is_some() && entry.simd_fn.is_none()).then_some(*name)
1044        })
1045        .collect::<Vec<_>>();
1046
1047    let cpu_without_simd_json = cpu_without_simd
1048        .iter()
1049        .map(|name| format!("\"{name}\""))
1050        .collect::<Vec<_>>()
1051        .join(", ");
1052    let operations_json = operations
1053        .iter()
1054        .map(|entry| entry.to_string())
1055        .collect::<Vec<_>>()
1056        .join(",\n    ");
1057
1058    Ok(format!(
1059        concat!(
1060            "{{\n",
1061            "  \"totals\": {{\n",
1062            "    \"operations\": {operations},\n",
1063            "    \"cpu\": {cpu},\n",
1064            "    \"simd_pool\": {simd_pool},\n",
1065            "    \"gpu_shader\": {gpu_shader},\n",
1066            "    \"cpu_without_simd\": {cpu_without_simd_len}\n",
1067            "  }},\n",
1068            "  \"cpu_without_simd\": [{cpu_without_simd_json}],\n",
1069            "  \"operations\": [\n",
1070            "    {operations_json}\n",
1071            "  ]\n",
1072            "}}"
1073        ),
1074        operations = registry.len(),
1075        cpu = cpu,
1076        simd_pool = simd_pool,
1077        gpu_shader = gpu_shader,
1078        cpu_without_simd_len = cpu_without_simd.len(),
1079        cpu_without_simd_json = cpu_without_simd_json,
1080        operations_json = operations_json
1081    ))
1082}