1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
// Copyright 2020 the Xilem Authors and the Druid Authors
// SPDX-License-Identifier: Apache-2.0
use std::any::TypeId;
use accesskit::{Node, Role};
use tracing::{Span, trace_span};
use crate::core::{
AccessCtx, ArcStr, ChildrenIds, LayoutCtx, MeasureCtx, NoAction, PaintCtx, PropertiesMut,
PropertiesRef, Property, RegisterCtx, Update, UpdateCtx, UsesProperty, Widget, WidgetId,
WidgetMut,
};
use crate::imaging::Painter;
use crate::kurbo::{Axis, Size};
use crate::layout::{LenReq, Length};
use crate::peniko::ImageBrush;
use crate::properties::ObjectFit;
// TODO: Make this a configurable option of the widget.
/// The scale that the image is native to.
///
/// Used to calculate the preferred logical size of the image.
///
/// For example you might have a 256 px icon meant for crisp details on 8K screens.
/// Then the image could have an preferred scale of e.g. 4.0,
/// meaning that its preferred logical size is 64px.
/// That way the image looks good at any scale and doesn't shift the layout around.
const IMAGE_SCALE: f64 = 1.0;
// TODO - Resolve name collision between masonry::Image and peniko::Image
/// A widget that renders a bitmap Image.
///
/// The underlying image uses `Arc` for buffer data, making it cheap to clone.
///
/// This currently uses bilinear interpolation, which falls down when the image is
/// larger than its layout size (e.g. it is in a [sized box](super::SizedBox) smaller
/// than the image size).
///
/// You can change the sizing of the image with the [`ObjectFit`] property.
pub struct Image {
image_data: ImageBrush,
decorative: bool,
alt_text: Option<ArcStr>,
}
// --- MARK: BUILDERS
impl Image {
/// Creates an image drawing widget from an image buffer.
///
/// By default, the image will be scaled to fully fit within the container.
/// ([`ObjectFit::Contain`]).
#[inline]
pub fn new(image_data: impl Into<ImageBrush>) -> Self {
Self {
image_data: image_data.into(),
decorative: false,
alt_text: None,
}
}
/// Specifies whether the image is decorative, meaning it doesn't have meaningful content
/// and is only for visual presentation.
///
/// If `is_decorative` is `true`, the image will be ignored by screen readers.
pub fn decorative(mut self, is_decorative: bool) -> Self {
self.decorative = is_decorative;
self
}
/// Sets the text that will describe the image to screen readers.
///
/// Users are encouraged to set alt text for the image.
/// If possible, the alt-text should succinctly describe what the image represents.
///
/// If the image is decorative users should set alt text to `""`.
/// If it's too hard to describe through text, the alt text should be left unset.
/// This allows accessibility clients to know that there is no accessible description of the image content.
pub fn with_alt_text(mut self, alt_text: impl Into<ArcStr>) -> Self {
self.alt_text = Some(alt_text.into());
self
}
}
// --- MARK: WIDGETMUT
impl Image {
/// Sets new `ImageBrush`.
#[inline]
pub fn set_image_data(this: &mut WidgetMut<'_, Self>, image_data: impl Into<ImageBrush>) {
this.widget.image_data = image_data.into();
this.ctx.request_layout();
}
/// Sets whether the image is decorative, meaning it doesn't have meaningful content
/// and is only for visual presentation.
///
/// See [`Image::decorative`] for details.
pub fn set_decorative(this: &mut WidgetMut<'_, Self>, is_decorative: bool) {
this.widget.decorative = is_decorative;
this.ctx.request_accessibility_update();
}
/// Sets the text that will describe the image to screen readers.
///
/// See [`Image::with_alt_text`] for details.
pub fn set_alt_text(this: &mut WidgetMut<'_, Self>, alt_text: Option<impl Into<ArcStr>>) {
this.widget.alt_text = alt_text.map(Into::into);
this.ctx.request_accessibility_update();
}
}
impl Image {
/// Returns the preferred size of the image.
///
/// The returned size is in logical pixels.
///
/// This takes into account [`IMAGE_SCALE`], so a high-resolution resource can
/// have a stable preferred logical size.
fn preferred_size(&self) -> Size {
Size::new(
self.image_data.image.width as f64 / IMAGE_SCALE,
self.image_data.image.height as f64 / IMAGE_SCALE,
)
}
}
impl UsesProperty<ObjectFit> for Image {}
// --- MARK: IMPL WIDGET
impl Widget for Image {
type Action = NoAction;
fn register_children(&mut self, _ctx: &mut RegisterCtx<'_>) {}
fn property_changed(&mut self, ctx: &mut UpdateCtx<'_>, property_type: TypeId) {
if ObjectFit::matches(property_type) {
ctx.request_layout();
}
}
fn update(
&mut self,
_ctx: &mut UpdateCtx<'_>,
_props: &mut PropertiesMut<'_>,
_event: &Update,
) {
}
fn measure(
&mut self,
ctx: &mut MeasureCtx<'_>,
props: &PropertiesRef<'_>,
axis: Axis,
len_req: LenReq,
cross_length: Option<Length>,
) -> Length {
let cache = ctx.property_cache();
let object_fit = props.get::<ObjectFit>(cache);
let preferred_size = self.preferred_size();
object_fit.measure(axis, len_req, cross_length, preferred_size)
}
fn layout(&mut self, _ctx: &mut LayoutCtx<'_>, _props: &PropertiesRef<'_>, _size: Size) {}
fn paint(
&mut self,
ctx: &mut PaintCtx<'_>,
props: &PropertiesRef<'_>,
painter: &mut Painter<'_>,
) {
let content_box = ctx.content_box();
let cache = ctx.property_cache();
let object_fit = props.get::<ObjectFit>(cache);
// For drawing we want to scale the actual image data lengths, which means
// we need to avoid using Image::preferred_size which does not match the data.
let image_size = Size::new(
self.image_data.image.width as f64,
self.image_data.image.height as f64,
);
let transform = object_fit.affine(content_box, image_size.to_rect());
painter.with_fill_clip(content_box, |painter| {
painter.draw_image(&self.image_data, transform);
});
}
fn accessibility_role(&self) -> Role {
Role::Image
}
fn accessibility(
&mut self,
_ctx: &mut AccessCtx<'_>,
_props: &PropertiesRef<'_>,
node: &mut Node,
) {
if let Some(alt_text) = &self.alt_text {
node.set_description(&**alt_text);
}
if self.decorative {
node.set_hidden();
}
}
fn children_ids(&self) -> ChildrenIds {
ChildrenIds::new()
}
fn make_trace_span(&self, id: WidgetId) -> Span {
trace_span!("Image", id = id.trace())
}
}
// FIXME - remove cfg?
#[cfg(not(target_arch = "wasm32"))]
// --- MARK: TESTS
#[cfg(test)]
mod tests {
use super::*;
use crate::core::NewWidget;
use crate::peniko::{ImageAlphaType, ImageData, ImageFormat};
use crate::testing::{TestHarness, assert_render_snapshot};
use crate::theme::test_property_set;
/// Painting an empty image shouldn't crash.
#[test]
fn empty_paint() {
// TODO - Blob::empty() function?
// TODO: Does Vello promise this is supported?
let image_data = ImageData {
data: Vec::new().into(),
format: ImageFormat::Rgba8,
alpha_type: ImageAlphaType::Alpha,
width: 0,
height: 0,
};
let image_widget = NewWidget::new(Image::new(image_data));
let mut harness = TestHarness::create(test_property_set(), image_widget);
let _ = harness.render();
}
#[test]
fn tall_paint() {
let image_data = ImageData {
// This could have a more concise chain, but previously used versions either
// had unreadable formatting or used `rustfmt::skip`, which broke formatting
// across large parts of the file.
data: [
[255, 255, 255, 255],
[000, 000, 000, 255],
[000, 000, 000, 255],
[255, 255, 255, 255],
]
.into_iter()
.flatten()
.collect::<Vec<_>>()
.into(),
format: ImageFormat::Rgba8,
alpha_type: ImageAlphaType::Alpha,
width: 2,
height: 2,
};
let image_widget = NewWidget::new(Image::new(image_data));
let mut harness =
TestHarness::create_with_size(test_property_set(), image_widget, (40, 60));
assert_render_snapshot!(harness, "image_tall_paint");
}
#[test]
fn edit_image() {
let image_data = ImageData {
data: vec![255; 4 * 8 * 8].into(),
format: ImageFormat::Rgba8,
alpha_type: ImageAlphaType::Alpha,
width: 8,
height: 8,
};
let render_1 = {
let image_widget = NewWidget::new(Image::new(image_data.clone()));
let mut harness =
TestHarness::create_with_size(test_property_set(), image_widget, (40, 60));
harness.render()
};
let render_2 = {
let other_image_data = ImageData {
data: vec![10; 4 * 8 * 8].into(),
format: ImageFormat::Rgba8,
alpha_type: ImageAlphaType::Alpha,
width: 8,
height: 8,
};
let image_widget = NewWidget::new(Image::new(other_image_data));
let mut harness =
TestHarness::create_with_size(test_property_set(), image_widget, (40, 60));
harness.edit_root_widget(|mut image| {
Image::set_image_data(&mut image, image_data);
});
harness.render()
};
// TODO - Use Kompari instead
// We don't use assert_eq because we don't want rich assert
assert!(render_1 == render_2);
}
#[test]
fn layout() {
let image_data = ImageData {
data: vec![255; 4 * 8 * 8].into(),
format: ImageFormat::Rgba8,
alpha_type: ImageAlphaType::Alpha,
width: 8,
height: 8,
};
let image_widget = NewWidget::new(Image::new(image_data.clone()));
let mut harness =
TestHarness::create_with_size(test_property_set(), image_widget, (100, 50));
// Contain.
harness.edit_root_widget(|mut image| {
image.insert_prop(ObjectFit::Contain);
});
assert_render_snapshot!(harness, "image_layout_contain");
// Cover.
harness.edit_root_widget(|mut image| {
image.insert_prop(ObjectFit::Cover);
});
assert_render_snapshot!(harness, "image_layout_cover");
// FitHeight.
harness.edit_root_widget(|mut image| {
image.insert_prop(ObjectFit::FitHeight);
});
assert_render_snapshot!(harness, "image_layout_fitheight");
// FitWidth.
harness.edit_root_widget(|mut image| {
image.insert_prop(ObjectFit::FitWidth);
});
assert_render_snapshot!(harness, "image_layout_fitwidth");
// None.
harness.edit_root_widget(|mut image| {
image.insert_prop(ObjectFit::None);
});
assert_render_snapshot!(harness, "image_layout_none");
// ScaleDown.
harness.edit_root_widget(|mut image| {
image.insert_prop(ObjectFit::ScaleDown);
});
assert_render_snapshot!(harness, "image_layout_scaledown");
// Stretch.
harness.edit_root_widget(|mut image| {
image.insert_prop(ObjectFit::Stretch);
});
assert_render_snapshot!(harness, "image_layout_stretch");
}
}