1use alloc::{boxed::Box, rc::Rc};
4use core::hash::{Hash, Hasher};
5
6use blit::{LogicalRect, Paint, PhysicalRect, Rect, Scale2, Size, Ui, Widget, state};
7
8use crate::color::Color;
9
10blit::builder! {
11 #[derive(Clone, Debug, PartialEq)]
13 pub struct Image {
14 new(#[into] image: ImageHandle),
15 #[into]
16 intrinsic: Option<Size<f32>> = None,
17 fit: ImageFit = ImageFit::Fill,
18 sampling: ImageSampling = ImageSampling::Nearest,
19 opacity: f32 = 1.0,
20 colorize: Option<Color> = None,
21 nine_slice: Option<NineSlice> = None,
22 horizontal_tiling: ImageTiling = ImageTiling::None,
23 vertical_tiling: ImageTiling = ImageTiling::None,
24 }
25}
26
27impl<C> Widget<C, state::Insert> for Image
28where
29 C: Paint<Self, Scalar = f32>,
30{
31 type Response = ();
32
33 fn build(self, mut ui: Ui<'_, C, state::Insert>) {
34 let pixels = self.image.size();
35 let intrinsic = self.intrinsic;
36 let contain = self.fit == ImageFit::Contain
37 && self.nine_slice.is_none()
38 && self.horizontal_tiling == ImageTiling::None
39 && self.vertical_tiling == ImageTiling::None;
40 ui.measure(move |_, constraints| {
41 let natural = Size::new(pixels.width as f32, pixels.height as f32);
42 let mut size = intrinsic.unwrap_or(natural);
43 if contain {
44 size.width = size.width.min(constraints.max.width);
45 size.height = size.height.min(constraints.max.height);
46 let scale = (size.width / natural.width).min(size.height / natural.height).max(0.0);
47 size = Size::new(natural.width * scale, natural.height * scale);
48 }
49 constraints.constrain(size)
50 });
51 ui.paint(move |cx, area| cx.context_mut().paint(area, &self));
52 }
53}
54
55impl Image {
56 pub fn for_each_patch(&self, area: LogicalRect, scale_factor: f32, mut emit: impl FnMut(ImagePatch)) {
58 let source_size = self.image.size();
59 let geometry = area.to_physical(Scale2::uniform(scale_factor));
60 let source = Rect {
61 x: 0,
62 y: 0,
63 width: source_size.width,
64 height: source_size.height,
65 };
66 if geometry.width <= 0 || geometry.height <= 0 || source.width == 0 || source.height == 0 || self.opacity <= 0.0
67 {
68 return;
69 }
70
71 let mut emit = |patch: ImagePatch| {
72 if patch.source.width > 0
73 && patch.source.height > 0
74 && patch.display.width > 0
75 && patch.display.height > 0
76 && patch.bounds.width > 0
77 && patch.bounds.height > 0
78 {
79 emit(patch);
80 }
81 };
82
83 if let Some(slice) = self.nine_slice.filter(|slice| {
84 u32::from(slice.left) + u32::from(slice.right) <= source.width
85 && u32::from(slice.top) + u32::from(slice.bottom) <= source.height
86 }) {
87 let fit_borders = |first: i32, second: i32, available: i32| {
88 if first + second <= available {
89 (first, second)
90 } else {
91 let first = libm::roundf(first as f32 * available as f32 / (first + second) as f32) as i32;
92 (first, available - first)
93 }
94 };
95 let (left, right) = fit_borders(
96 libm::roundf(slice.left as f32 * scale_factor) as i32,
97 libm::roundf(slice.right as f32 * scale_factor) as i32,
98 geometry.width,
99 );
100 let (top, bottom) = fit_borders(
101 libm::roundf(slice.top as f32 * scale_factor) as i32,
102 libm::roundf(slice.bottom as f32 * scale_factor) as i32,
103 geometry.height,
104 );
105 let source_x = [
106 0,
107 u32::from(slice.left),
108 source.width - u32::from(slice.right),
109 source.width,
110 ];
111 let source_y = [
112 0,
113 u32::from(slice.top),
114 source.height - u32::from(slice.bottom),
115 source.height,
116 ];
117 let destination_x = [
118 geometry.x,
119 geometry.x + left,
120 geometry.x + geometry.width - right,
121 geometry.x + geometry.width,
122 ];
123 let destination_y = [
124 geometry.y,
125 geometry.y + top,
126 geometry.y + geometry.height - bottom,
127 geometry.y + geometry.height,
128 ];
129 for row in 0..3 {
130 for column in 0..3 {
131 let source = Rect {
132 x: source_x[column],
133 y: source_y[row],
134 width: source_x[column + 1] - source_x[column],
135 height: source_y[row + 1] - source_y[row],
136 };
137 let display = PhysicalRect {
138 x: destination_x[column],
139 y: destination_y[row],
140 width: destination_x[column + 1] - destination_x[column],
141 height: destination_y[row + 1] - destination_y[row],
142 };
143 emit(ImagePatch {
144 source,
145 display,
146 bounds: display,
147 horizontal_tiling: if column == 1 {
148 self.horizontal_tiling
149 } else {
150 ImageTiling::None
151 },
152 vertical_tiling: if row == 1 {
153 self.vertical_tiling
154 } else {
155 ImageTiling::None
156 },
157 });
158 }
159 }
160 return;
161 }
162
163 let tiled = self.horizontal_tiling != ImageTiling::None || self.vertical_tiling != ImageTiling::None;
164 let display = if tiled {
165 geometry
166 } else {
167 match self.fit {
168 ImageFit::Fill => geometry,
169 ImageFit::Contain | ImageFit::Cover => {
170 let horizontal = geometry.width as f32 / source.width as f32;
171 let vertical = geometry.height as f32 / source.height as f32;
172 let scale = if self.fit == ImageFit::Contain {
173 horizontal.min(vertical)
174 } else {
175 horizontal.max(vertical)
176 };
177 let width = libm::roundf(source.width as f32 * scale).max(1.0) as i32;
178 let height = libm::roundf(source.height as f32 * scale).max(1.0) as i32;
179 PhysicalRect {
180 x: geometry.x + (geometry.width - width) / 2,
181 y: geometry.y + (geometry.height - height) / 2,
182 width,
183 height,
184 }
185 }
186 }
187 };
188 let bounds = if self.fit == ImageFit::Cover || tiled {
189 display.intersection(geometry).unwrap_or_default()
190 } else {
191 display
192 };
193 emit(ImagePatch {
194 source,
195 display,
196 bounds,
197 horizontal_tiling: self.horizontal_tiling,
198 vertical_tiling: self.vertical_tiling,
199 });
200 }
201}
202
203impl Hash for Image {
204 fn hash<H: Hasher>(&self, state: &mut H) {
205 self.image.id().hash(state);
206 (if self.opacity == 0.0 { 0 } else { self.opacity.to_bits() }).hash(state);
207 core::mem::discriminant(&self.fit).hash(state);
208 core::mem::discriminant(&self.sampling).hash(state);
209 core::mem::discriminant(&self.horizontal_tiling).hash(state);
210 core::mem::discriminant(&self.vertical_tiling).hash(state);
211 self.colorize.hash(state);
212 self.nine_slice
213 .map(|slice| [slice.top, slice.right, slice.bottom, slice.left])
214 .hash(state);
215 }
216}
217
218#[derive(Clone, Debug)]
219pub struct ImageHandle(Rc<ImageInner>);
220
221impl PartialEq for ImageHandle {
222 fn eq(&self, other: &Self) -> bool {
223 self.id() == other.id()
224 }
225}
226
227impl From<&ImageHandle> for ImageHandle {
228 fn from(image: &ImageHandle) -> Self {
229 image.clone()
230 }
231}
232
233impl ImageHandle {
234 #[doc(hidden)]
235 pub fn new(id: ImageId, size: Size<u32>) -> Self {
236 Self(Rc::new(ImageInner { id, size }))
237 }
238
239 pub fn id(&self) -> ImageId {
240 self.0.id
241 }
242
243 pub fn size(&self) -> Size<u32> {
244 self.0.size
245 }
246
247 pub fn is_uniquely_owned(&self) -> bool {
249 Rc::strong_count(&self.0) == 1
250 }
251}
252
253#[derive(Debug, PartialEq)]
254pub struct ImageData {
255 pub pixels: ImagePixels,
256 pub size: Size<u32>,
257 pub texture_rect: Rect<u32>,
258 pub stride_bytes: usize,
259 pub format: ImageFormat,
260}
261
262impl ImageData {
263 pub fn new(pixels: ImagePixels, format: ImageFormat, width: u32, height: u32) -> Self {
264 let stride_bytes = (width as usize)
265 .checked_mul(format.bytes_per_pixel())
266 .expect("image width is too large");
267 Self {
268 pixels,
269 size: Size { width, height },
270 texture_rect: Rect {
271 x: 0,
272 y: 0,
273 width,
274 height,
275 },
276 stride_bytes,
277 format,
278 }
279 }
280
281 pub fn validate(&self) {
282 assert!(self.size.width > 0 && self.size.height > 0);
283 assert!(self.texture_rect.width > 0 && self.texture_rect.height > 0);
284 assert!(
285 self.texture_rect
286 .x
287 .checked_add(self.texture_rect.width)
288 .is_some_and(|right| right <= self.size.width)
289 );
290 assert!(
291 self.texture_rect
292 .y
293 .checked_add(self.texture_rect.height)
294 .is_some_and(|bottom| bottom <= self.size.height)
295 );
296 let row_bytes = (self.texture_rect.width as usize)
297 .checked_mul(self.format.bytes_per_pixel())
298 .expect("image row is too large");
299 assert!(self.stride_bytes >= row_bytes);
300 let len = (self.texture_rect.height as usize - 1)
301 .checked_mul(self.stride_bytes)
302 .and_then(|offset| offset.checked_add(row_bytes))
303 .expect("image data is too large");
304 assert!(len <= self.pixels.bytes().len());
305 }
306}
307
308#[derive(Debug, PartialEq)]
309pub enum ImagePixels {
310 Static(&'static [u8]),
311 Owned(Box<[u8]>),
312}
313
314impl ImagePixels {
315 pub fn bytes(&self) -> &[u8] {
316 match self {
317 Self::Static(bytes) => bytes,
318 Self::Owned(bytes) => bytes,
319 }
320 }
321}
322
323#[derive(Clone, Copy, Debug, PartialEq, Eq)]
324pub enum ImageFormat {
325 Rgb8,
326 Luma8,
327 Rgba8,
328 Rgba8Premultiplied,
329 Alpha8(Color),
330}
331
332impl ImageFormat {
333 pub fn bytes_per_pixel(self) -> usize {
334 match self {
335 Self::Rgb8 => 3,
336 Self::Rgba8 | Self::Rgba8Premultiplied => 4,
337 Self::Luma8 | Self::Alpha8(_) => 1,
338 }
339 }
340}
341
342#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
343pub struct NineSlice {
344 pub top: u16,
345 pub right: u16,
346 pub bottom: u16,
347 pub left: u16,
348}
349
350impl NineSlice {
351 pub const fn uniform(value: u16) -> Self {
352 Self {
353 top: value,
354 right: value,
355 bottom: value,
356 left: value,
357 }
358 }
359}
360
361#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
362pub enum ImageFit {
363 #[default]
364 Fill,
365 Contain,
366 Cover,
367}
368
369#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
370pub enum ImageSampling {
371 #[default]
372 Nearest,
373 Bilinear,
374}
375
376#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
377pub enum ImageTiling {
378 #[default]
379 None,
380 Repeat,
381 Round,
382}
383
384pub type ImageId = u64;
385
386#[derive(Debug)]
387struct ImageInner {
388 id: ImageId,
389 size: Size<u32>,
390}
391
392#[derive(Clone, Copy, Debug, PartialEq, Eq)]
394pub struct ImagePatch {
395 pub source: Rect<u32>,
396 pub display: PhysicalRect,
397 pub bounds: PhysicalRect,
398 pub horizontal_tiling: ImageTiling,
399 pub vertical_tiling: ImageTiling,
400}