ferroui-base 0.3.0

The base library of FerroUI: the property system, layout, input, styling, media, text, animation, data binding and the compositor
Documentation
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
use crate::media::{BoxShadows, Color, IBrush, IEffect, IExperimentalAcrylicMaterial, IPen, RenderOptions};
use crate::platform::{
    AlphaFormat, IBitmapImpl, IDrawingContextImpl, IDrawingContextImplWithEffects, IDrawingContextLayerImpl,
    IDrawingContextWithAcrylicLikeSupport, IGeometryImpl, IGlyphRunImpl, ILockedFramebuffer,
    IPlatformRenderInterfaceRegion, IReadableBitmapImpl, IRenderTargetBitmapImpl, PixelFormat,
};
use crate::{Matrix, PixelSize, Rect, RoundedRect, Vector};
use std::any::{Any, TypeId};
use std::rc::Rc;

/// The shared record of what was drawn on mock drawing contexts, one line
/// per call, in call order.
#[derive(Clone, Default)]
pub struct DrawingLog(std::sync::Arc<std::sync::Mutex<Vec<String>>>);

impl DrawingLog {
    pub fn new() -> Self {
        Self::default()
    }

    /// Appends an entry.
    pub fn push(&self, entry: impl Into<String>) {
        self.0.lock().unwrap().push(entry.into());
    }

    /// A copy of the entries recorded so far.
    pub fn entries(&self) -> Vec<String> {
        self.0.lock().unwrap().clone()
    }

    /// Removes and returns the entries recorded so far.
    pub fn take(&self) -> Vec<String> {
        std::mem::take(&mut *self.0.lock().unwrap())
    }

    /// The number of entries starting with `prefix`.
    pub fn count(&self, prefix: &str) -> usize {
        self.0.lock().unwrap().iter().filter(|e| e.starts_with(prefix)).count()
    }

    pub fn clear(&self) {
        self.0.lock().unwrap().clear();
    }
}

fn brush_text(brush: Option<&dyn IBrush>) -> String {
    match brush {
        None => "none".to_string(),
        Some(brush) => match brush.as_solid_color_brush() {
            Some(solid) => format!("{}", solid.color()),
            None => "brush".to_string(),
        },
    }
}

fn pen_text(pen: Option<&dyn IPen>) -> String {
    match pen {
        None => "none".to_string(),
        Some(pen) => format!("{}@{}", brush_text(pen.brush().as_deref()), pen.thickness()),
    }
}

/// A platform drawing context that records every call in a [`DrawingLog`].
pub struct MockDrawingContextImpl {
    log: DrawingLog,
    transform: Matrix,
    /// Whether transform changes are recorded (`SetTransform <matrix>`).
    pub log_transforms: bool,
    /// Whether the context reports effect support (`PushEffect <clip>` /
    /// `PopEffect`). Off by default.
    pub supports_effects: bool,
    /// Whether the context reports acrylic support
    /// (`DrawRectangleWithMaterial <tint> <rect>`). Off by default.
    pub supports_acrylic: bool,
    /// Whether pushed render options are recorded with their values
    /// (`PushRenderOptions <text> <interpolation> <edge> <blending>
    /// <full opacity>`) rather than as `PushRenderOptions`. Off by default.
    pub log_render_options: bool,
}

impl MockDrawingContextImpl {
    pub fn new(log: DrawingLog) -> Self {
        Self {
            log,
            transform: Matrix::IDENTITY,
            log_transforms: true,
            supports_effects: false,
            supports_acrylic: false,
            log_render_options: false,
        }
    }

    /// The log this context records to.
    pub fn log(&self) -> &DrawingLog {
        &self.log
    }
}

impl IDrawingContextImpl for MockDrawingContextImpl {
    fn transform(&self) -> Matrix {
        self.transform
    }

    fn set_transform(&mut self, value: Matrix) {
        self.transform = value;
        if self.log_transforms {
            self.log.push(format!("SetTransform {value}"));
        }
    }

    fn clear(&mut self, color: Color) {
        self.log.push(format!("Clear {color}"));
    }

    fn draw_bitmap(&mut self, _source: &dyn IBitmapImpl, opacity: f64, source_rect: Rect, dest_rect: Rect) {
        self.log.push(format!("DrawBitmap {opacity} {source_rect} {dest_rect}"));
    }

    fn draw_bitmap_with_mask(
        &mut self,
        _source: &dyn IBitmapImpl,
        opacity_mask: &dyn IBrush,
        opacity_mask_rect: Rect,
        dest_rect: Rect,
    ) {
        self.log.push(format!(
            "DrawBitmapWithMask {} {opacity_mask_rect} {dest_rect}",
            brush_text(Some(opacity_mask))
        ));
    }

    fn draw_line(&mut self, pen: Option<&dyn IPen>, p1: crate::Point, p2: crate::Point) {
        self.log.push(format!("DrawLine {} {p1} {p2}", pen_text(pen)));
    }

    fn draw_geometry(&mut self, brush: Option<&dyn IBrush>, pen: Option<&dyn IPen>, geometry: &dyn IGeometryImpl) {
        self.log.push(format!("DrawGeometry {} {} {}", brush_text(brush), pen_text(pen), geometry.bounds()));
    }

    fn draw_rectangle(
        &mut self,
        brush: Option<&dyn IBrush>,
        pen: Option<&dyn IPen>,
        rect: RoundedRect,
        box_shadows: &BoxShadows,
    ) {
        self.log.push(format!(
            "DrawRectangle {} {} {} shadows={}",
            brush_text(brush),
            pen_text(pen),
            rect.rect,
            box_shadows.count()
        ));
    }

    fn draw_region(
        &mut self,
        brush: Option<&dyn IBrush>,
        pen: Option<&dyn IPen>,
        _region: &dyn IPlatformRenderInterfaceRegion,
    ) {
        self.log.push(format!("DrawRegion {} {}", brush_text(brush), pen_text(pen)));
    }

    fn draw_ellipse(&mut self, brush: Option<&dyn IBrush>, pen: Option<&dyn IPen>, rect: Rect) {
        self.log.push(format!("DrawEllipse {} {} {rect}", brush_text(brush), pen_text(pen)));
    }

    fn draw_glyph_run(&mut self, foreground: Option<&dyn IBrush>, glyph_run: &dyn IGlyphRunImpl) {
        self.log.push(format!("DrawGlyphRun {} {}", brush_text(foreground), glyph_run.bounds()));
    }

    fn create_layer(&mut self, size: PixelSize) -> Rc<dyn IDrawingContextLayerImpl> {
        self.log.push(format!("CreateLayer {size}"));
        Rc::new(MockDrawingContextLayerImpl::new(self.log.clone(), size))
    }

    fn push_clip(&mut self, clip: Rect) {
        self.log.push(format!("PushClip {clip}"));
    }

    fn push_clip_rounded(&mut self, clip: RoundedRect) {
        self.log.push(format!("PushRoundedClip {}", clip.rect));
    }

    fn push_clip_region(&mut self, _region: &dyn IPlatformRenderInterfaceRegion) {
        self.log.push("PushClipRegion");
    }

    fn pop_clip(&mut self) {
        self.log.push("PopClip");
    }

    fn push_layer(&mut self, bounds: Rect) {
        self.log.push(format!("PushLayer {bounds}"));
    }

    fn pop_layer(&mut self) {
        self.log.push("PopLayer");
    }

    fn push_opacity(&mut self, opacity: f64, _bounds: Option<Rect>) {
        self.log.push(format!("PushOpacity {opacity}"));
    }

    fn pop_opacity(&mut self) {
        self.log.push("PopOpacity");
    }

    fn push_opacity_mask(&mut self, mask: &dyn IBrush, bounds: Rect) {
        self.log.push(format!("PushOpacityMask {} {bounds}", brush_text(Some(mask))));
    }

    fn pop_opacity_mask(&mut self) {
        self.log.push("PopOpacityMask");
    }

    fn push_geometry_clip(&mut self, clip: &dyn IGeometryImpl) {
        self.log.push(format!("PushGeometryClip {}", clip.bounds()));
    }

    fn pop_geometry_clip(&mut self) {
        self.log.push("PopGeometryClip");
    }

    fn push_render_options(&mut self, render_options: RenderOptions) {
        if self.log_render_options {
            self.log.push(format!(
                "PushRenderOptions {:?} {:?} {:?} {:?} {:?}",
                render_options.text_rendering_mode,
                render_options.bitmap_interpolation_mode,
                render_options.edge_mode,
                render_options.bitmap_blending_mode,
                render_options.requires_full_opacity_handling
            ));
        } else {
            self.log.push("PushRenderOptions");
        }
    }

    fn pop_render_options(&mut self) {
        self.log.push("PopRenderOptions");
    }

    fn push_text_options(&mut self, text_options: crate::media::TextOptions) {
        self.log.push(format!(
            "PushTextOptions {:?} {:?} {:?}",
            text_options.text_rendering_mode, text_options.text_hinting_mode, text_options.baseline_pixel_alignment
        ));
    }

    fn pop_text_options(&mut self) {
        self.log.push("PopTextOptions");
    }

    fn get_feature(&mut self, _feature_type: TypeId) -> Option<Rc<dyn Any>> {
        None
    }

    fn as_drawing_context_impl_with_effects(&mut self) -> Option<&mut dyn IDrawingContextImplWithEffects> {
        if self.supports_effects {
            Some(self)
        } else {
            None
        }
    }

    fn as_drawing_context_with_acrylic_like_support(
        &mut self,
    ) -> Option<&mut dyn IDrawingContextWithAcrylicLikeSupport> {
        if self.supports_acrylic {
            Some(self)
        } else {
            None
        }
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    fn dispose(&mut self) {
        self.log.push("Dispose");
    }
}

impl IDrawingContextImplWithEffects for MockDrawingContextImpl {
    fn push_effect(&mut self, clip_rect: Option<Rect>, _effect: &dyn IEffect) {
        match clip_rect {
            Some(clip_rect) => self.log.push(format!("PushEffect {clip_rect}")),
            None => self.log.push("PushEffect none"),
        }
    }

    fn pop_effect(&mut self) {
        self.log.push("PopEffect");
    }
}

impl IDrawingContextWithAcrylicLikeSupport for MockDrawingContextImpl {
    fn draw_rectangle_with_material(&mut self, material: &dyn IExperimentalAcrylicMaterial, rect: RoundedRect) {
        self.log.push(format!("DrawRectangleWithMaterial {} {}", material.tint_color(), rect.rect));
    }
}

/// An offscreen layer whose drawing contexts record to a [`DrawingLog`].
pub struct MockDrawingContextLayerImpl {
    log: DrawingLog,
    size: PixelSize,
}

impl MockDrawingContextLayerImpl {
    pub fn new(log: DrawingLog, size: PixelSize) -> Self {
        Self { log, size }
    }
}

impl IBitmapImpl for MockDrawingContextLayerImpl {
    fn dpi(&self) -> Vector {
        Vector::new(96.0, 96.0)
    }

    fn pixel_size(&self) -> PixelSize {
        self.size
    }

    fn version(&self) -> i32 {
        0
    }

    fn save(
        &self,
        _stream: &mut dyn std::io::Write,
        _options: &crate::media::imaging::BitmapEncoderOptions,
    ) -> std::io::Result<()> {
        Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "the mock layer has no pixels to save"))
    }

    fn dispose(&self) {}

    fn as_any(&self) -> &dyn Any {
        self
    }
}

impl IDrawingContextLayerImpl for MockDrawingContextLayerImpl {
    fn blit(&self, _context: &mut dyn IDrawingContextImpl) {
        self.log.push("Blit");
    }

    fn can_blit(&self) -> bool {
        true
    }

    fn is_corrupted(&self) -> bool {
        false
    }

    fn create_drawing_context(&self) -> Box<dyn IDrawingContextImpl> {
        Box::new(MockDrawingContextImpl::new(self.log.clone()))
    }

    fn create_shared_snapshot(&self) -> std::sync::Arc<crate::platform::SharedBitmapImpl> {
        std::sync::Arc::new(MockRenderTargetBitmapImpl::new(self.log.clone(), self.size, Vector::new(96.0, 96.0)))
    }
}

/// A render target bitmap whose drawing contexts record to a
/// [`DrawingLog`]. It has no pixels: locking it panics.
pub struct MockRenderTargetBitmapImpl {
    log: DrawingLog,
    size: PixelSize,
    dpi: Vector,
}

impl MockRenderTargetBitmapImpl {
    pub fn new(log: DrawingLog, size: PixelSize, dpi: Vector) -> Self {
        Self { log, size, dpi }
    }
}

impl IBitmapImpl for MockRenderTargetBitmapImpl {
    fn dpi(&self) -> Vector {
        self.dpi
    }

    fn pixel_size(&self) -> PixelSize {
        self.size
    }

    fn version(&self) -> i32 {
        0
    }

    fn save(
        &self,
        _stream: &mut dyn std::io::Write,
        _options: &crate::media::imaging::BitmapEncoderOptions,
    ) -> std::io::Result<()> {
        Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "the mock bitmap has no pixels to save"))
    }

    fn dispose(&self) {}

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_readable_bitmap(&self) -> Option<&dyn IReadableBitmapImpl> {
        Some(self)
    }
}

impl IReadableBitmapImpl for MockRenderTargetBitmapImpl {
    fn format(&self) -> Option<PixelFormat> {
        None
    }

    fn alpha_format(&self) -> Option<AlphaFormat> {
        None
    }

    fn lock(&self) -> Rc<dyn ILockedFramebuffer> {
        panic!("the mock render target bitmap has no pixels")
    }
}

impl IRenderTargetBitmapImpl for MockRenderTargetBitmapImpl {
    fn create_drawing_context(&self) -> Box<dyn IDrawingContextImpl> {
        Box::new(MockDrawingContextImpl::new(self.log.clone()))
    }
}