Skip to main content

graphics/
logo.rs

1//! Xila Monogram symbol drawn with LVGL.
2//!
3//! Geometry source: `xila-project/brand` `source/symbol.svg` at commit
4//! `00d6686` (identity 2.0.0, designed by Martin Legand). The symbol is four
5//! rounded diagonal arms around a separate rounded center square.
6//!
7//! A single LVGL object draws the symbol directly into the current layer.
8//! Whole-pixel inner edges, notches and center-square edges preserve the gaps
9//! between the pieces at every factor.
10
11use core::{mem::ManuallyDrop, ptr};
12use synchronization::once_lock::OnceLock;
13
14use crate::{Color, Error, Point, Result, lvgl, theme};
15
16/// Width of the supplied artwork, in source units.
17const EXTENT: f32 = 617.45;
18/// Center of the supplied artwork, in source units.
19const CENTER: f32 = EXTENT / 2.0;
20/// Distance from the center to the inner edges of an arm.
21const ARM_INNER: f32 = CENTER - 280.12;
22/// Distance from the center to the outer edges of the notch around the square.
23const NOTCH: f32 = 403.63 - CENTER;
24/// Half the side of the center square.
25const SQUARE_HALF: f32 = 118.02 / 2.0;
26/// Corner radius of the center square.
27const SQUARE_RADIUS: f32 = 4.4;
28
29/// Pixel metrics of a symbol, with the axis-aligned edges snapped to pixels.
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31struct Metrics {
32    /// Symbol side.
33    size: u16,
34    /// Distance from the center to the inner edges of an arm.
35    arm_inner: u16,
36    /// Distance from the center to the outer edges of the notch.
37    notch: u16,
38    /// Half the side of the center square.
39    square_half: u16,
40    /// Corner radius of the center square.
41    square_radius: u16,
42}
43
44impl Metrics {
45    fn new(size: u16) -> Self {
46        // Keep an even size so the center falls on a pixel boundary.
47        let size = size & !1;
48        let scale = size as f32 / EXTENT;
49        let half = size / 2;
50        let snap = |value: f32| (value * scale + 0.5) as u16;
51
52        let arm_inner = snap(ARM_INNER).max(1).min(half);
53        let square_half = snap(SQUARE_HALF).max(1).min(half);
54        // Keep at least one transparent pixel between the square and the arms.
55        let notch = snap(NOTCH).max(square_half + 1).max(arm_inner + 1);
56
57        Self {
58            size,
59            arm_inner,
60            notch,
61            square_half,
62            square_radius: snap(SQUARE_RADIUS),
63        }
64    }
65
66    /// Side of one arm bounding square.
67    const fn arm_size(&self) -> u16 {
68        self.size / 2 - self.arm_inner
69    }
70
71    /// Map a distance from the symbol center in source units to pixels,
72    /// keeping the snapped inner, notch and outer edges in place.
73    fn map_distance(&self, distance: f32) -> f32 {
74        let scale = self.size as f32 / EXTENT;
75        let knots = [
76            (0.0, 0.0),
77            (ARM_INNER, self.arm_inner as f32),
78            (NOTCH, self.notch as f32),
79            (CENTER, (self.size / 2) as f32),
80        ];
81
82        for window in knots.windows(2) {
83            let ((from_source, from_pixel), (to_source, to_pixel)) = (window[0], window[1]);
84
85            if distance <= to_source {
86                return from_pixel
87                    + (distance - from_source) * (to_pixel - from_pixel)
88                        / (to_source - from_source);
89            }
90        }
91
92        (self.size / 2) as f32 + (distance - CENTER) * scale
93    }
94
95    /// Map a top-right arm point in source units to its local coordinates.
96    fn map_arm_point(&self, (x, y): (f32, f32)) -> (f32, f32) {
97        let arm_size = self.arm_size() as f32;
98        let x = self.map_distance(x - CENTER) - self.arm_inner as f32;
99        let y = (self.size / 2) as f32 - self.map_distance(CENTER - y);
100
101        (x.clamp(0.0, arm_size), y.clamp(0.0, arm_size))
102    }
103}
104
105/// The top-right arm's two edges, ordered from its outer horizontal edge
106/// down to its inner horizontal edge. The obtuse corners and recessed notch
107/// use two chords through each source Bézier's midpoint. The outside right
108/// angle uses an LVGL rounded rectangle.
109const LEFT_EDGE: [(f32, f32); 10] = [
110    (485.12, 0.02),
111    (475.51, 1.93),
112    (467.36, 7.38),
113    (344.69, 130.05),
114    (339.24, 138.20),
115    (337.33, 147.81),
116    (337.33, 213.82),
117    (374.18, 213.82),
118    (394.98, 222.47),
119    (403.63, 243.27),
120];
121const RIGHT_EDGE: [(f32, f32); 7] = [
122    (617.45, 25.14),
123    (617.45, 132.31),
124    (615.54, 141.92),
125    (610.09, 150.07),
126    (487.40, 272.76),
127    (479.25, 278.21),
128    (469.64, 280.12),
129];
130
131/// Coordinates on pixel boundaries in the canonical (top-right) arm.
132#[derive(Clone, Copy)]
133struct Vertex {
134    x: i32,
135    y: i32,
136}
137
138struct Arm {
139    x: i32,
140    y: i32,
141    mirror_x: bool,
142    mirror_y: bool,
143    side: i32,
144}
145
146impl Arm {
147    fn vertex(&self, point: Vertex) -> lvgl::lv_point_precise_t {
148        lvgl::lv_point_precise_t {
149            x: self.x
150                + if self.mirror_x {
151                    self.side - point.x
152                } else {
153                    point.x
154                },
155            y: self.y
156                + if self.mirror_y {
157                    self.side - point.y
158                } else {
159                    point.y
160                },
161        }
162    }
163
164    /// Convert a half-open rectangle on pixel boundaries to LVGL's inclusive area.
165    fn area(&self, x1: i32, y1: i32, x2: i32, y2: i32) -> lvgl::lv_area_t {
166        let a = self.vertex(Vertex { x: x1, y: y1 });
167        let b = self.vertex(Vertex { x: x2, y: y2 });
168        lvgl::lv_area_t {
169            x1: a.x.min(b.x),
170            x2: a.x.max(b.x) - 1,
171            y1: a.y.min(b.y),
172            y2: a.y.max(b.y) - 1,
173        }
174    }
175}
176
177struct Painter {
178    layer: *mut lvgl::lv_layer_t,
179    fill: lvgl::lv_draw_fill_dsc_t,
180    triangle: lvgl::lv_draw_triangle_dsc_t,
181    line: lvgl::lv_draw_line_dsc_t,
182}
183
184impl Painter {
185    unsafe fn draw_fill(&self, area: &lvgl::lv_area_t) {
186        unsafe {
187            if lvgl::lv_area_is_on(area, &(*self.layer)._clip_area) {
188                lvgl::lv_draw_fill(self.layer, &self.fill, area);
189            }
190        }
191    }
192
193    /// Paint one edge up to the arm's interior split column. The solid
194    /// rectangle and the sloping triangle own disjoint columns, so their
195    /// shared vertical edge never receives two antialiased fills.
196    unsafe fn fill_edge(&mut self, arm: &Arm, edge: &[Vertex], left: bool, radius: i32) {
197        let side = arm.side;
198        let middle = side / 2;
199        // The midline moves left between the upper and lower halves so
200        // it stays inside the diagonal band at the top and bottom.
201        for (top, bottom, split) in [(0, middle, side * 2 / 3), (middle, side, side / 3)] {
202            let (near, far) = if left { (0, split) } else { (split, side) };
203            let original = unsafe { (*self.layer)._clip_area };
204            if !left && top == 0 && radius > 0 {
205                let area = arm.area(split, 0, side - radius, radius);
206                unsafe { self.draw_fill(&area) };
207            }
208            for pair in edge.windows(2) {
209                let [a, b] = [pair[0], pair[1]];
210                let y1 = a.y.max(top);
211                let y2 = b.y.min(bottom);
212                if y1 >= y2 {
213                    continue;
214                }
215                let (tip, base) = if (a.x < b.x) == left { (b, a) } else { (a, b) };
216                let (rect_left, rect_right) = if left { (tip.x, far) } else { (near, tip.x) };
217                if rect_left < rect_right {
218                    let area = arm.area(rect_left, y1, rect_right, y2);
219                    unsafe { self.draw_fill(&area) };
220                }
221
222                let x1 = near.max(a.x.min(b.x));
223                let x2 = far.min(a.x.max(b.x));
224                if x1 < x2 {
225                    let area = arm.area(x1, y1, x2, y2);
226                    let mut clip = lvgl::lv_area_t::default();
227                    if unsafe { lvgl::lv_area_intersect(&mut clip, &original, &area) } {
228                        self.triangle.p = [
229                            arm.vertex(tip),
230                            arm.vertex(base),
231                            arm.vertex(Vertex {
232                                x: tip.x,
233                                y: base.y,
234                            }),
235                        ];
236                        unsafe {
237                            (*self.layer)._clip_area = clip;
238                            lvgl::lv_draw_triangle(self.layer, &self.triangle);
239                            (*self.layer)._clip_area = original;
240                        }
241                    }
242                }
243            }
244        }
245    }
246
247    /// Draw only the quadrant in the outside corner. The other arms mirror
248    /// its pixel bounds in the same way as the straight edges.
249    unsafe fn rounded_corner(&self, arm: &Arm, radius: i32, outline: bool) {
250        let area = arm.area(arm.side - 2 * radius, 0, arm.side, 2 * radius);
251        let quadrant = arm.area(arm.side - radius, 0, arm.side, radius);
252        unsafe {
253            let original = (*self.layer)._clip_area;
254            let mut clip = lvgl::lv_area_t::default();
255            if lvgl::lv_area_intersect(&mut clip, &original, &quadrant) {
256                (*self.layer)._clip_area = clip;
257                draw_rounded_rect(
258                    self.layer,
259                    &area,
260                    self.fill.color,
261                    radius,
262                    outline,
263                    self.fill.opa,
264                );
265                (*self.layer)._clip_area = original;
266            }
267        }
268    }
269
270    /// Stroke the inside of an edge. The row clip makes adjacent chords meet
271    /// without accumulating opacity at their joins.
272    unsafe fn stroke_edge(&mut self, arm: &Arm, edge: &[Vertex], left: bool) {
273        let original = unsafe { (*self.layer)._clip_area };
274        for pair in edge.windows(2) {
275            let [a, b] = [pair[0], pair[1]];
276            if a.y == b.y {
277                if a.x != b.x {
278                    // The notch and flattened corner chords can be horizontal.
279                    let interior_below = (b.x < a.x) == left;
280                    let y = (a.y - i32::from(!interior_below)).clamp(0, arm.side - 1);
281                    let area = arm.area(a.x.min(b.x), y, a.x.max(b.x), y + 1);
282                    unsafe { self.draw_fill(&area) };
283                }
284                continue;
285            }
286            let mut p = arm.vertex(a);
287            let mut q = arm.vertex(b);
288            if p.y > q.y {
289                core::mem::swap(&mut p, &mut q);
290            }
291            let interior_right = left != arm.mirror_x;
292            let dx = q.x - p.x;
293            // LVGL places a one-pixel steep stroke to the right of its
294            // geometric line. For a shallow stroke the bias is along y.
295            if dx.abs() <= q.y - p.y {
296                let inset = i32::from(!interior_right);
297                p.x -= inset;
298                q.x -= inset;
299            } else if interior_right == (dx > 0) {
300                p.y -= 1;
301                q.y -= 1;
302            }
303            let area = arm.area(0, a.y, arm.side, b.y);
304            let mut clip = lvgl::lv_area_t::default();
305            if unsafe { lvgl::lv_area_intersect(&mut clip, &original, &area) } {
306                self.line.p1 = p;
307                self.line.p2 = q;
308                unsafe {
309                    (*self.layer)._clip_area = clip;
310                    lvgl::lv_draw_line(self.layer, &self.line);
311                    (*self.layer)._clip_area = original;
312                }
313            }
314        }
315    }
316}
317
318unsafe fn draw_logo(object: *mut lvgl::lv_obj_t, layer: *mut lvgl::lv_layer_t) {
319    unsafe {
320        let instance = object.cast::<LogoObject>();
321        let outline = (*instance).style == LogoStyle::Outline;
322        let pose = (*instance).pose;
323        let mut bounds = lvgl::lv_area_t::default();
324        lvgl::lv_obj_get_coords(object, &mut bounds);
325        let width = bounds.x2 - bounds.x1 + 1;
326        let height = bounds.y2 - bounds.y1 + 1;
327        let size = width.min(height).min(i32::from(u8::MAX) * 32) & !1;
328        if size < 32 {
329            return;
330        }
331        let x = bounds.x1 + (width - size) / 2;
332        let y = bounds.y1 + (height - size) / 2;
333        let metrics = Metrics::new(size as u16);
334        let side = i32::from(metrics.arm_size());
335        let map = |point| {
336            let (x, y) = metrics.map_arm_point(point);
337            Vertex {
338                x: (x + 0.5) as i32,
339                y: (y + 0.5) as i32,
340            }
341        };
342        let left = LEFT_EDGE.map(map);
343        let right = RIGHT_EDGE.map(map);
344        let radius = right[0].y;
345        let bottom_left = Vertex {
346            x: i32::from(metrics.notch - metrics.arm_inner),
347            y: side,
348        };
349
350        // The logo takes its color directly from text_color and deliberately
351        // ignores color_filter and layer recolor.
352        let color = lvgl::lv_obj_get_style_text_color(object, lvgl::LV_PART_MAIN);
353        let clip = (*layer)._clip_area;
354        let layer_opa = (*layer).opa;
355        // Match LVGL's descriptor initialization, including LV_OPA_MIX2
356        // when the layer is translucent.
357        let mix_opacity = |opacity| {
358            if layer_opa < lvgl::LV_OPA_MAX as u8 {
359                ((u16::from(opacity) * u16::from(layer_opa)) >> 8) as u8
360            } else {
361                opacity
362            }
363        };
364        let mut painter = Painter {
365            layer,
366            fill: lvgl::lv_draw_fill_dsc_t::default(),
367            triangle: lvgl::lv_draw_triangle_dsc_t::default(),
368            line: lvgl::lv_draw_line_dsc_t::default(),
369        };
370        lvgl::lv_draw_fill_dsc_init(&mut painter.fill);
371        lvgl::lv_draw_triangle_dsc_init(&mut painter.triangle);
372        lvgl::lv_draw_line_dsc_init(&mut painter.line);
373        painter.fill.color = color;
374        painter.triangle.color = color;
375        painter.line.color = color;
376        painter.line.width = 1;
377        painter.line.set_raw_end(1);
378
379        let mut left_edge = [bottom_left; LEFT_EDGE.len() + 1];
380        left_edge[..left.len()].copy_from_slice(&left);
381        let mirrors = [(true, false), (true, true), (false, true), (false, false)];
382        for ((mirror_x, mirror_y), arm_pose) in mirrors.into_iter().zip(pose.arms) {
383            let opacity = mix_opacity(arm_pose.opacity);
384            if opacity == 0 {
385                continue;
386            }
387            let offset = i32::from(arm_pose.offset);
388            let arm = Arm {
389                x: if mirror_x {
390                    x - offset
391                } else {
392                    x + size - side + offset
393                },
394                y: if mirror_y {
395                    y + size - side + offset
396                } else {
397                    y - offset
398                },
399                mirror_x,
400                mirror_y,
401                side,
402            };
403            if !lvgl::lv_area_is_on(&arm.area(0, 0, side, side), &clip) {
404                continue;
405            }
406            painter.fill.opa = opacity;
407            painter.line.opa = opacity;
408            painter.triangle.opa = opacity;
409            painter.rounded_corner(&arm, radius, outline);
410            if outline {
411                let top_right = Vertex {
412                    x: side - radius,
413                    y: 0,
414                };
415                painter.stroke_edge(&arm, &left_edge, true);
416                painter.stroke_edge(&arm, &right, false);
417                painter.stroke_edge(&arm, &[left[0], top_right], false);
418                painter.stroke_edge(&arm, &[bottom_left, right[right.len() - 1]], false);
419            } else {
420                painter.fill_edge(&arm, &left_edge, true, 0);
421                painter.fill_edge(&arm, &right, false, radius);
422            }
423        }
424
425        let half = i32::from(metrics.square_half);
426        let center_x = x + size / 2;
427        let center_y = y + size / 2;
428        draw_rounded_rect(
429            layer,
430            &lvgl::lv_area_t {
431                x1: center_x - half,
432                y1: center_y - half,
433                x2: center_x + half - 1,
434                y2: center_y + half - 1,
435            },
436            color,
437            i32::from(metrics.square_radius),
438            outline,
439            mix_opacity(pose.center_opacity),
440        );
441    }
442}
443
444unsafe fn draw_rounded_rect(
445    layer: *mut lvgl::lv_layer_t,
446    area: &lvgl::lv_area_t,
447    color: lvgl::lv_color_t,
448    radius: i32,
449    outline: bool,
450    opacity: lvgl::lv_opa_t,
451) {
452    unsafe {
453        if opacity == 0 || !lvgl::lv_area_is_on(area, &(*layer)._clip_area) {
454            return;
455        }
456        let mut rect = lvgl::lv_draw_rect_dsc_t::default();
457        lvgl::lv_draw_rect_dsc_init(&mut rect);
458        rect.radius = radius;
459        if outline {
460            rect.bg_opa = 0;
461            rect.border_width = 1;
462            rect.border_color = color;
463            rect.border_opa = opacity;
464        } else {
465            rect.bg_color = color;
466            rect.bg_opa = opacity;
467        }
468        lvgl::lv_draw_rect(layer, &rect, area);
469    }
470}
471
472/// How the arms and the center square are painted.
473#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
474pub enum LogoStyle {
475    /// Solid symbol, as supplied by the brand.
476    #[default]
477    Filled,
478    /// One-pixel contour of the symbol, for subdued backgrounds.
479    Outline,
480}
481
482/// Visual state of one arm in an animated logo.
483#[derive(Clone, Copy, Debug, PartialEq, Eq)]
484pub struct LogoArmPose {
485    /// Outward displacement in pixels on each axis.
486    pub offset: u16,
487    /// Opacity from 0 (transparent) to 255 (opaque).
488    pub opacity: u8,
489}
490
491/// Per-piece animation state, stored inline in the logo object.
492#[derive(Clone, Copy, Debug, PartialEq, Eq)]
493pub struct LogoPose {
494    /// Top-left, bottom-left, bottom-right, top-right.
495    pub arms: [LogoArmPose; Logo::ARM_COUNT],
496    /// Opacity from 0 (transparent) to 255 (opaque).
497    pub center_opacity: u8,
498}
499
500impl LogoPose {
501    /// Centered, fully opaque logo.
502    pub const REST: Self = Self {
503        arms: [LogoArmPose {
504            offset: 0,
505            opacity: 255,
506        }; Logo::ARM_COUNT],
507        center_opacity: 255,
508    };
509
510    fn outset(&self) -> i32 {
511        i32::from(self.arms.iter().map(|arm| arm.offset).max().unwrap_or(0))
512    }
513}
514
515#[repr(C)]
516struct LogoObject {
517    base: lvgl::lv_obj_t,
518    pose: LogoPose,
519    style: LogoStyle,
520}
521
522struct LogoClass(lvgl::lv_obj_class_t);
523
524// The descriptor is immutable after initialization and points to static data.
525unsafe impl Send for LogoClass {}
526unsafe impl Sync for LogoClass {}
527
528static LOGO_CLASS: OnceLock<LogoClass> = OnceLock::new();
529
530fn logo_class() -> &'static lvgl::lv_obj_class_t {
531    &LOGO_CLASS
532        .get_or_init(|| {
533            let mut class = lvgl::lv_obj_class_t {
534                base_class: &raw const lvgl::lv_obj_class,
535                constructor_cb: Some(construct_logo),
536                event_cb: Some(logo_event),
537                name: c"logo".as_ptr(),
538                ..Default::default()
539            };
540            class.set_instance_size(size_of::<LogoObject>() as _);
541            LogoClass(class)
542        })
543        .0
544}
545
546unsafe extern "C" fn construct_logo(_: *const lvgl::lv_obj_class_t, object: *mut lvgl::lv_obj_t) {
547    unsafe {
548        let instance = object.cast::<LogoObject>();
549        ptr::addr_of_mut!((*instance).pose).write(LogoPose::REST);
550        ptr::addr_of_mut!((*instance).style).write(LogoStyle::Filled);
551    }
552}
553
554unsafe extern "C" fn logo_event(class: *const lvgl::lv_obj_class_t, event: *mut lvgl::lv_event_t) {
555    unsafe {
556        if lvgl::lv_obj_event_base(class, event) != lvgl::lv_result_t_LV_RESULT_OK {
557            return;
558        }
559        let object = lvgl::lv_event_get_current_target(event).cast::<lvgl::lv_obj_t>();
560        match lvgl::lv_event_get_code(event) {
561            lvgl::lv_event_code_t_LV_EVENT_DRAW_MAIN => {
562                draw_logo(object, lvgl::lv_event_get_layer(event));
563            }
564            lvgl::lv_event_code_t_LV_EVENT_REFR_EXT_DRAW_SIZE => {
565                let pose = (*object.cast::<LogoObject>()).pose;
566                lvgl::lv_event_set_ext_draw_size(event, pose.outset());
567            }
568            _ => {}
569        }
570    }
571}
572
573/// A logo that deletes its LVGL object on drop.
574#[non_exhaustive]
575pub struct Logo {
576    pub object: *mut lvgl::lv_obj_t,
577}
578
579unsafe extern "C" fn palette_color_changed(event: *mut lvgl::lv_event_t) {
580    unsafe {
581        let object = lvgl::lv_event_get_current_target(event) as *mut lvgl::lv_obj_t;
582        let role = lvgl::lv_event_get_user_data(event) as usize;
583
584        if let Some(color) = theme::get_palette_color(object, theme::PaletteColor::from_index(role))
585        {
586            Logo::apply_color(object, color);
587        }
588    }
589}
590
591impl Logo {
592    pub const BASE_SIZE: Point = Point::new(32, 32);
593    pub const ARM_COUNT: usize = 4;
594
595    pub fn get_factor(size: Point) -> u8 {
596        let factor_x = size.get_x() / Self::BASE_SIZE.get_x();
597        let factor_y = size.get_y() / Self::BASE_SIZE.get_y();
598
599        factor_x.min(factor_y) as u8
600    }
601
602    /// Create a filled logo of `32 * factor` pixels.
603    ///
604    /// # Safety
605    /// `parent` must be a live LVGL object and the caller must hold the LVGL lock.
606    /// Keep the logo's object alive until the wrapper is dropped or converted
607    /// with [`Self::into_inner_object`]. Drop the wrapper under the LVGL lock.
608    pub unsafe fn new(parent: *mut lvgl::lv_obj_t, factor: u8, color: Color) -> Result<Self> {
609        unsafe { Self::new_with_style(parent, factor, color, LogoStyle::Filled) }
610    }
611
612    /// Create a logo of `32 * factor` pixels with the given style.
613    ///
614    /// # Safety
615    /// `parent` must be a live LVGL object and the caller must hold the LVGL lock.
616    /// Keep the logo's object alive until the wrapper is dropped or converted
617    /// with [`Self::into_inner_object`]. Drop the wrapper under the LVGL lock.
618    pub unsafe fn new_with_style(
619        parent: *mut lvgl::lv_obj_t,
620        factor: u8,
621        color: Color,
622        style: LogoStyle,
623    ) -> Result<Self> {
624        if factor == 0 {
625            return Err(Error::InvalidParameter);
626        }
627        let size = i32::from(Self::BASE_SIZE.get_x()) * i32::from(factor);
628
629        unsafe {
630            let object = lvgl::lv_obj_class_create_obj(logo_class(), parent);
631
632            if object.is_null() {
633                return Err(Error::FailedToCreateObject);
634            }
635
636            lvgl::lv_obj_class_init_obj(object);
637            (*object.cast::<LogoObject>()).style = style;
638
639            // Decorative and theme independent: no surface, padding or input.
640            lvgl::lv_obj_remove_style_all(object);
641            lvgl::lv_obj_set_size(object, size, size);
642            lvgl::lv_obj_remove_flag(object, lvgl::lv_obj_flag_t_LV_OBJ_FLAG_CLICKABLE);
643            lvgl::lv_obj_remove_flag(object, lvgl::lv_obj_flag_t_LV_OBJ_FLAG_SCROLLABLE);
644            lvgl::lv_obj_set_style_text_color(object, color.into_lvgl_color(), 0);
645            Ok(Self { object })
646        }
647    }
648
649    /// Replace the animation pose of a logo, invalidating its old and new bounds.
650    ///
651    /// # Safety
652    /// `object` must be a live object created by [`Self::new`] or
653    /// [`Self::new_with_style`]. The caller must hold the LVGL lock.
654    pub unsafe fn set_pose(object: *mut lvgl::lv_obj_t, pose: LogoPose) {
655        unsafe {
656            debug_assert!(lvgl::lv_obj_has_class(object, logo_class()));
657            let instance = object.cast::<LogoObject>();
658            let previous = (*instance).pose;
659            if pose == previous {
660                return;
661            }
662            lvgl::lv_obj_invalidate(object);
663            (*instance).pose = pose;
664            if pose.outset() != previous.outset() {
665                lvgl::lv_obj_refresh_ext_draw_size(object);
666            }
667            lvgl::lv_obj_invalidate(object);
668        }
669    }
670
671    unsafe fn apply_color(object: *mut lvgl::lv_obj_t, color: Color) {
672        let color = color.into_lvgl_color();
673        unsafe {
674            // Setting a style sends STYLE_CHANGED to the logo itself.
675            if !lvgl::lv_color_eq(lvgl::lv_obj_get_style_text_color(object, 0), color) {
676                lvgl::lv_obj_set_style_text_color(object, color, 0);
677            }
678        }
679    }
680
681    /// Repaint the logo with a fixed color and stop following the palette.
682    ///
683    /// # Safety
684    /// The caller must hold the LVGL lock.
685    pub unsafe fn set_color(&self, color: Color) {
686        unsafe {
687            lvgl::lv_obj_remove_event_cb(self.object, Some(palette_color_changed));
688            Self::apply_color(self.object, color);
689        }
690    }
691
692    /// Paint the logo with a theme palette color and follow later palette or
693    /// dark/light changes.
694    ///
695    /// # Safety
696    /// The caller must hold the LVGL lock.
697    pub unsafe fn follow_palette_color(&self, color: theme::PaletteColor) {
698        unsafe {
699            lvgl::lv_obj_remove_event_cb(self.object, Some(palette_color_changed));
700            if let Some(value) = theme::get_palette_color(self.object, color) {
701                Self::apply_color(self.object, value);
702            }
703            lvgl::lv_obj_add_event_cb(
704                self.object,
705                Some(palette_color_changed),
706                lvgl::lv_event_code_t_LV_EVENT_STYLE_CHANGED,
707                color as usize as *mut core::ffi::c_void,
708            );
709        }
710    }
711
712    pub fn get_inner_object(&self) -> *mut lvgl::lv_obj_t {
713        self.object
714    }
715
716    /// Leave the logo owned by the LVGL object tree.
717    /// The returned pointer is valid until LVGL deletes the logo.
718    pub fn into_inner_object(self) -> *mut lvgl::lv_obj_t {
719        ManuallyDrop::new(self).object
720    }
721}
722
723impl Drop for Logo {
724    fn drop(&mut self) {
725        unsafe { lvgl::lv_obj_delete(self.object) };
726    }
727}
728
729#[cfg(test)]
730mod tests {
731    use super::*;
732
733    #[test]
734    fn metrics_keep_edges_snapped_and_separations_open() {
735        for size in (1..=u16::from(u8::MAX)).map(|factor| factor * 32) {
736            let metrics = Metrics::new(size);
737            assert!(metrics.arm_inner >= 1, "{size}: arms must not touch");
738            assert!(metrics.notch > metrics.square_half, "{size}: square gap");
739            assert!(metrics.notch > metrics.arm_inner, "{size}: notch depth");
740            assert!(metrics.square_half < size / 2);
741        }
742        // Integer factors used by the bootsplash and the desktop.
743        assert_eq!(
744            Metrics::new(160),
745            Metrics {
746                size: 160,
747                arm_inner: 7,
748                notch: 25,
749                square_half: 15,
750                square_radius: 1,
751            }
752        );
753    }
754}