Skip to main content

embedded_gui/
render.rs

1use core::marker::PhantomData;
2
3use embedded_graphics_core::{
4    Pixel,
5    draw_target::DrawTarget,
6    geometry::Point,
7    pixelcolor::{Rgb565, RgbColor},
8};
9
10#[cfg(not(feature = "std"))]
11use crate::math::F32Ext as _;
12use crate::{
13    font::{FontId, glyph_rows},
14    geometry::Rect,
15    image::{ImageFit, ImageRef},
16    style::{Border, GradientDirection, LinearGradient},
17    text,
18};
19
20pub const CHAR_WIDTH: u32 = 4;
21pub const CHAR_HEIGHT: u32 = 6;
22
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum TextAlign {
25    Left,
26    Center,
27    Right,
28}
29
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31pub enum VerticalAlign {
32    Top,
33    Middle,
34    Bottom,
35}
36
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38pub enum TextWrap {
39    None,
40    Character,
41    Word,
42}
43
44#[derive(Clone, Copy, Debug, PartialEq, Eq)]
45pub enum TextOverflow {
46    Clip,
47    Ellipsis,
48}
49
50#[derive(Clone, Copy, Debug, PartialEq, Eq)]
51pub enum EllipsisMode {
52    ThreeDots,
53    SingleGlyph,
54}
55
56#[derive(Clone, Copy, Debug, PartialEq, Eq)]
57pub enum TextOverflowPolicy {
58    Global(TextOverflow),
59    WrapThenEllipsis { max_lines: u8 },
60}
61
62#[derive(Clone, Copy, Debug, PartialEq, Eq)]
63pub struct TextStyle {
64    pub color: Rgb565,
65    pub font: FontId,
66    pub opacity: u8,
67    pub align: TextAlign,
68    pub vertical_align: VerticalAlign,
69    pub wrap: TextWrap,
70    pub overflow: TextOverflow,
71    pub overflow_policy: TextOverflowPolicy,
72    pub kerning: bool,
73    pub max_lines: Option<u8>,
74    pub ellipsis: EllipsisMode,
75    pub line_spacing: u8,
76}
77
78impl TextStyle {
79    pub const fn new(color: Rgb565) -> Self {
80        Self {
81            color,
82            font: FontId::Tiny3x5,
83            opacity: 255,
84            align: TextAlign::Left,
85            vertical_align: VerticalAlign::Top,
86            wrap: TextWrap::None,
87            overflow: TextOverflow::Clip,
88            overflow_policy: TextOverflowPolicy::Global(TextOverflow::Clip),
89            kerning: false,
90            max_lines: None,
91            ellipsis: EllipsisMode::ThreeDots,
92            line_spacing: 1,
93        }
94    }
95
96    pub const fn centered(mut self) -> Self {
97        self.align = TextAlign::Center;
98        self.vertical_align = VerticalAlign::Middle;
99        self
100    }
101
102    pub const fn with_align(mut self, align: TextAlign) -> Self {
103        self.align = align;
104        self
105    }
106
107    pub const fn with_vertical_align(mut self, align: VerticalAlign) -> Self {
108        self.vertical_align = align;
109        self
110    }
111
112    pub const fn with_wrap(mut self, wrap: TextWrap) -> Self {
113        self.wrap = wrap;
114        self
115    }
116
117    pub const fn with_line_spacing(mut self, spacing: u8) -> Self {
118        self.line_spacing = spacing;
119        self
120    }
121
122    pub const fn with_overflow(mut self, overflow: TextOverflow) -> Self {
123        self.overflow = overflow;
124        self.overflow_policy = TextOverflowPolicy::Global(overflow);
125        self
126    }
127
128    pub const fn with_kerning(mut self, kerning: bool) -> Self {
129        self.kerning = kerning;
130        self
131    }
132
133    pub const fn with_max_lines(mut self, max_lines: Option<u8>) -> Self {
134        self.max_lines = max_lines;
135        self
136    }
137
138    pub const fn with_ellipsis_mode(mut self, ellipsis: EllipsisMode) -> Self {
139        self.ellipsis = ellipsis;
140        self
141    }
142
143    pub const fn with_overflow_policy(mut self, policy: TextOverflowPolicy) -> Self {
144        self.overflow_policy = policy;
145        self
146    }
147
148    pub const fn with_opacity(mut self, opacity: u8) -> Self {
149        self.opacity = opacity;
150        self
151    }
152
153    pub const fn with_font(mut self, font: FontId) -> Self {
154        self.font = font;
155        self
156    }
157}
158
159#[derive(Clone, Copy, Debug, PartialEq, Eq)]
160pub struct TextMetrics {
161    pub width: u32,
162    pub height: u32,
163}
164
165#[derive(Clone, Copy, Debug, PartialEq, Eq)]
166pub enum RenderQuality {
167    Low,
168    Medium,
169    High,
170}
171
172#[derive(Clone, Copy, Debug, PartialEq, Eq)]
173pub enum AntiAliasMode {
174    None,
175    Coverage,
176    Subpixel,
177}
178
179#[derive(Clone, Copy, Debug, PartialEq, Eq)]
180pub struct StrokeStyle {
181    pub color: Rgb565,
182    pub width: u8,
183    pub antialias: bool,
184    pub antialias_mode: AntiAliasMode,
185    pub cap: StrokeCap,
186    pub join: StrokeJoin,
187}
188
189#[derive(Clone, Copy, Debug, PartialEq, Eq)]
190pub enum StrokeCap {
191    Butt,
192    Round,
193}
194
195#[derive(Clone, Copy, Debug, PartialEq, Eq)]
196pub enum StrokeJoin {
197    Miter,
198    Round,
199}
200
201#[derive(Clone, Copy, Debug, PartialEq)]
202pub struct Transform2D {
203    pub m11: f32,
204    pub m12: f32,
205    pub m21: f32,
206    pub m22: f32,
207    pub tx: f32,
208    pub ty: f32,
209}
210
211impl Transform2D {
212    pub const IDENTITY: Self = Self {
213        m11: 1.0,
214        m12: 0.0,
215        m21: 0.0,
216        m22: 1.0,
217        tx: 0.0,
218        ty: 0.0,
219    };
220
221    pub const fn translation(x: f32, y: f32) -> Self {
222        Self {
223            tx: x,
224            ty: y,
225            ..Self::IDENTITY
226        }
227    }
228
229    pub const fn scale(x: f32, y: f32) -> Self {
230        Self {
231            m11: x,
232            m22: y,
233            ..Self::IDENTITY
234        }
235    }
236
237    pub fn rotation(deg: f32) -> Self {
238        let r = deg.to_radians();
239        Self {
240            m11: r.cos(),
241            m12: -r.sin(),
242            m21: r.sin(),
243            m22: r.cos(),
244            ..Self::IDENTITY
245        }
246    }
247
248    pub fn skew(x_deg: f32, y_deg: f32) -> Self {
249        Self {
250            m12: x_deg.to_radians().tan(),
251            m21: y_deg.to_radians().tan(),
252            ..Self::IDENTITY
253        }
254    }
255
256    pub fn then(self, rhs: Self) -> Self {
257        Self {
258            m11: self.m11 * rhs.m11 + self.m12 * rhs.m21,
259            m12: self.m11 * rhs.m12 + self.m12 * rhs.m22,
260            m21: self.m21 * rhs.m11 + self.m22 * rhs.m21,
261            m22: self.m21 * rhs.m12 + self.m22 * rhs.m22,
262            tx: self.m11 * rhs.tx + self.m12 * rhs.ty + self.tx,
263            ty: self.m21 * rhs.tx + self.m22 * rhs.ty + self.ty,
264        }
265    }
266
267    pub fn apply(self, x: i32, y: i32) -> (i32, i32) {
268        let xf = x as f32;
269        let yf = y as f32;
270        (
271            (self.m11 * xf + self.m12 * yf + self.tx).round() as i32,
272            (self.m21 * xf + self.m22 * yf + self.ty).round() as i32,
273        )
274    }
275}
276
277#[derive(Clone, Copy, Debug, PartialEq, Eq)]
278pub enum BlendMode {
279    Normal,
280    Add,
281    Multiply,
282    Screen,
283}
284
285/// Capability trait for draw targets that can read back a pixel they've
286/// already written. Optional: the default opacity/blend APIs on
287/// [`RenderCtx`] only require [`DrawTarget`] and approximate translucency
288/// with ordered dithering, so they keep working on write-only displays.
289/// Implementing `PixelRead` additionally unlocks the `*_true_alpha` methods,
290/// which composite against the destination's actual current contents
291/// instead of dithering.
292pub trait PixelRead: DrawTarget {
293    fn get_pixel(&self, point: Point) -> Self::Color;
294}
295
296/// Pixel-plotting policy for a [`RenderCtx`]. Selected by the ctx's `C` type
297/// parameter so the *same* drawing calls composite differently depending on
298/// the target's capabilities — with no runtime branch and no specialization.
299///
300/// - [`Dither`] (the default) approximates translucency with ordered dithering
301///   and works on any write-only [`DrawTarget`].
302/// - [`Blend`] performs true per-pixel alpha compositing and requires a
303///   readback-capable target ([`PixelRead`]), e.g. a
304///   [`Framebuffer`](crate::Framebuffer).
305///
306/// `plot` receives screen-space coords already transformed and clipped, the
307/// layer-combined `opacity`, and the active layer blend mode + backdrop.
308pub trait Compositor<D: DrawTarget<Color = Rgb565>> {
309    fn plot(
310        target: &mut D,
311        x: i32,
312        y: i32,
313        color: Rgb565,
314        opacity: u8,
315        blend: BlendMode,
316        backdrop: Rgb565,
317    ) -> Result<(), D::Error>;
318}
319
320/// Ordered-dither compositor (default). No readback required.
321#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
322pub struct Dither;
323
324/// True alpha-blending compositor. Requires a [`PixelRead`] target.
325#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
326pub struct Blend;
327
328impl<D: DrawTarget<Color = Rgb565>> Compositor<D> for Dither {
329    fn plot(
330        target: &mut D,
331        x: i32,
332        y: i32,
333        color: Rgb565,
334        opacity: u8,
335        blend: BlendMode,
336        backdrop: Rgb565,
337    ) -> Result<(), D::Error> {
338        if !should_draw_at_opacity(x, y, opacity) {
339            return Ok(());
340        }
341        let color = apply_blend_mode(color, blend, backdrop);
342        target.draw_iter([Pixel(Point::new(x, y), color)])
343    }
344}
345
346impl<D: DrawTarget<Color = Rgb565> + PixelRead> Compositor<D> for Blend {
347    fn plot(
348        target: &mut D,
349        x: i32,
350        y: i32,
351        color: Rgb565,
352        opacity: u8,
353        blend: BlendMode,
354        backdrop: Rgb565,
355    ) -> Result<(), D::Error> {
356        if opacity == 0 {
357            return Ok(());
358        }
359        let bg = target.get_pixel(Point::new(x, y));
360        let blended = lerp_rgb565(bg, color, opacity);
361        let blended = apply_blend_mode(blended, blend, backdrop);
362        target.draw_iter([Pixel(Point::new(x, y), blended)])
363    }
364}
365
366#[derive(Clone, Copy, Debug, PartialEq, Eq)]
367pub enum ColorFormat {
368    Rgb565,
369    Rgb888,
370    Argb8888,
371}
372
373#[derive(Clone, Copy, Debug, PartialEq, Eq)]
374pub struct RenderBackendCaps {
375    pub color_format: ColorFormat,
376    pub supports_layers: bool,
377    pub supports_subpixel: bool,
378}
379
380impl RenderBackendCaps {
381    pub const fn software_rgb565() -> Self {
382        Self {
383            color_format: ColorFormat::Rgb565,
384            supports_layers: true,
385            supports_subpixel: false,
386        }
387    }
388}
389
390#[derive(Clone, Copy, Debug, PartialEq, Eq)]
391pub struct LayerState {
392    pub opacity: u8,
393    pub blend: BlendMode,
394    pub backdrop: Rgb565,
395}
396
397impl LayerState {
398    pub const fn normal() -> Self {
399        Self {
400            opacity: 255,
401            blend: BlendMode::Normal,
402            backdrop: Rgb565::BLACK,
403        }
404    }
405}
406
407impl StrokeStyle {
408    pub const fn new(color: Rgb565) -> Self {
409        Self {
410            color,
411            width: 1,
412            antialias: false,
413            antialias_mode: AntiAliasMode::None,
414            cap: StrokeCap::Butt,
415            join: StrokeJoin::Miter,
416        }
417    }
418
419    pub const fn with_width(mut self, width: u8) -> Self {
420        self.width = if width == 0 { 1 } else { width };
421        self
422    }
423
424    pub const fn with_antialias(mut self, antialias: bool) -> Self {
425        self.antialias = antialias;
426        if antialias {
427            if let AntiAliasMode::None = self.antialias_mode {
428                self.antialias_mode = AntiAliasMode::Coverage;
429            }
430        }
431        if !antialias {
432            self.antialias_mode = AntiAliasMode::None;
433        }
434        self
435    }
436
437    pub const fn with_antialias_mode(mut self, mode: AntiAliasMode) -> Self {
438        self.antialias_mode = mode;
439        self.antialias = !matches!(mode, AntiAliasMode::None);
440        self
441    }
442
443    pub const fn with_cap(mut self, cap: StrokeCap) -> Self {
444        self.cap = cap;
445        self
446    }
447
448    pub const fn with_join(mut self, join: StrokeJoin) -> Self {
449        self.join = join;
450        self
451    }
452}
453
454pub struct RenderCtx<'a, D, C = Dither>
455where
456    D: DrawTarget<Color = Rgb565>,
457{
458    target: &'a mut D,
459    clip: Rect,
460    dirty: Option<Rect>,
461    quality: RenderQuality,
462    backend_caps: RenderBackendCaps,
463    transform_stack: [Transform2D; 8],
464    transform_len: usize,
465    layer_stack: [LayerState; 8],
466    layer_len: usize,
467    _compositor: PhantomData<C>,
468}
469
470impl<'a, D> RenderCtx<'a, D, Dither>
471where
472    D: DrawTarget<Color = Rgb565>,
473{
474    pub fn new(target: &'a mut D, viewport: Rect) -> Self {
475        Self {
476            target,
477            clip: viewport,
478            dirty: None,
479            quality: RenderQuality::High,
480            backend_caps: RenderBackendCaps::software_rgb565(),
481            transform_stack: [Transform2D::IDENTITY; 8],
482            transform_len: 1,
483            layer_stack: [LayerState::normal(); 8],
484            layer_len: 1,
485            _compositor: PhantomData,
486        }
487    }
488
489    pub fn with_dirty(target: &'a mut D, viewport: Rect, dirty: Rect) -> Self {
490        Self {
491            target,
492            clip: viewport,
493            dirty: Some(dirty),
494            quality: RenderQuality::High,
495            backend_caps: RenderBackendCaps::software_rgb565(),
496            transform_stack: [Transform2D::IDENTITY; 8],
497            transform_len: 1,
498            layer_stack: [LayerState::normal(); 8],
499            layer_len: 1,
500            _compositor: PhantomData,
501        }
502    }
503}
504
505impl<'a, D> RenderCtx<'a, D, Blend>
506where
507    D: DrawTarget<Color = Rgb565> + PixelRead,
508{
509    /// Like [`RenderCtx::new`], but every drawing call alpha-composites against
510    /// the target's current contents (true blending) instead of dithering.
511    /// Requires a readback-capable target ([`PixelRead`]), e.g. a
512    /// [`Framebuffer`](crate::Framebuffer).
513    pub fn compositing(target: &'a mut D, viewport: Rect) -> Self {
514        Self {
515            target,
516            clip: viewport,
517            dirty: None,
518            quality: RenderQuality::High,
519            backend_caps: RenderBackendCaps::software_rgb565(),
520            transform_stack: [Transform2D::IDENTITY; 8],
521            transform_len: 1,
522            layer_stack: [LayerState::normal(); 8],
523            layer_len: 1,
524            _compositor: PhantomData,
525        }
526    }
527}
528
529impl<'a, D, C> RenderCtx<'a, D, C>
530where
531    D: DrawTarget<Color = Rgb565>,
532    C: Compositor<D>,
533{
534    pub const fn clip(&self) -> Rect {
535        self.clip
536    }
537
538    pub fn set_clip(&mut self, clip: Rect) {
539        self.clip = clip;
540    }
541
542    pub const fn quality(&self) -> RenderQuality {
543        self.quality
544    }
545
546    pub fn set_quality(&mut self, quality: RenderQuality) {
547        self.quality = quality;
548    }
549
550    pub const fn backend_caps(&self) -> RenderBackendCaps {
551        self.backend_caps
552    }
553
554    pub fn set_backend_caps(&mut self, caps: RenderBackendCaps) {
555        self.backend_caps = caps;
556    }
557
558    pub fn push_transform(&mut self, transform: Transform2D) {
559        if self.transform_len >= self.transform_stack.len() {
560            return;
561        }
562        let current = self.current_transform();
563        self.transform_stack[self.transform_len] = current.then(transform);
564        self.transform_len += 1;
565    }
566
567    pub fn pop_transform(&mut self) {
568        if self.transform_len > 1 {
569            self.transform_len -= 1;
570        }
571    }
572
573    pub fn translate(&mut self, x: f32, y: f32) {
574        self.push_transform(Transform2D::translation(x, y));
575    }
576
577    pub fn scale(&mut self, x: f32, y: f32) {
578        self.push_transform(Transform2D::scale(x, y));
579    }
580
581    pub fn rotate(&mut self, deg: f32) {
582        self.push_transform(Transform2D::rotation(deg));
583    }
584
585    pub fn skew(&mut self, x_deg: f32, y_deg: f32) {
586        self.push_transform(Transform2D::skew(x_deg, y_deg));
587    }
588
589    pub fn push_layer(&mut self, layer: LayerState) {
590        if self.layer_len >= self.layer_stack.len() {
591            return;
592        }
593        let current = self.current_layer();
594        self.layer_stack[self.layer_len] = LayerState {
595            opacity: ((current.opacity as u16 * layer.opacity as u16) / 255) as u8,
596            blend: layer.blend,
597            backdrop: layer.backdrop,
598        };
599        self.layer_len += 1;
600    }
601
602    pub fn pop_layer(&mut self) {
603        if self.layer_len > 1 {
604            self.layer_len -= 1;
605        }
606    }
607
608    pub const fn shadow_spread_for(&self, spread: u8) -> u8 {
609        match self.quality {
610            RenderQuality::Low => 0,
611            RenderQuality::Medium => {
612                if spread > 1 {
613                    1
614                } else {
615                    spread
616                }
617            }
618            RenderQuality::High => spread,
619        }
620    }
621
622    pub fn fill_rect(&mut self, rect: Rect, color: Rgb565) -> Result<(), D::Error> {
623        self.fill_rect_alpha(rect, color, 255)
624    }
625
626    pub fn fill_rect_alpha(
627        &mut self,
628        rect: Rect,
629        color: Rgb565,
630        opacity: u8,
631    ) -> Result<(), D::Error> {
632        self.fill_rounded_rect_alpha(rect, 0, color, opacity)
633    }
634
635    pub fn fill_rounded_rect(
636        &mut self,
637        rect: Rect,
638        radius: u8,
639        color: Rgb565,
640    ) -> Result<(), D::Error> {
641        self.fill_rounded_rect_alpha(rect, radius, color, 255)
642    }
643
644    pub fn fill_rounded_rect_alpha(
645        &mut self,
646        rect: Rect,
647        radius: u8,
648        color: Rgb565,
649        opacity: u8,
650    ) -> Result<(), D::Error> {
651        let draw = self.visible_rect(rect);
652        if draw.is_empty() || opacity == 0 {
653            return Ok(());
654        }
655        let radius = radius.min((rect.w.min(rect.h) / 2) as u8);
656
657        for y in draw.y..draw.bottom() {
658            for x in draw.x..draw.right() {
659                if !in_rounded_rect(x, y, rect, radius) {
660                    continue;
661                }
662                self.pixel(x, y, color, opacity)?;
663            }
664        }
665        Ok(())
666    }
667
668    pub fn fill_rounded_rect_gradient_alpha(
669        &mut self,
670        rect: Rect,
671        radius: u8,
672        gradient: LinearGradient,
673        opacity: u8,
674    ) -> Result<(), D::Error> {
675        let draw = self.visible_rect(rect);
676        if draw.is_empty() || opacity == 0 {
677            return Ok(());
678        }
679        let radius = radius.min((rect.w.min(rect.h) / 2) as u8);
680        let denom = match gradient.direction {
681            GradientDirection::Horizontal => rect.w.saturating_sub(1).max(1),
682            GradientDirection::Vertical => rect.h.saturating_sub(1).max(1),
683        };
684
685        for y in draw.y..draw.bottom() {
686            for x in draw.x..draw.right() {
687                if !in_rounded_rect(x, y, rect, radius) {
688                    continue;
689                }
690                let numer = match gradient.direction {
691                    GradientDirection::Horizontal => (x - rect.x).max(0) as u32,
692                    GradientDirection::Vertical => (y - rect.y).max(0) as u32,
693                }
694                .min(denom);
695                let mut t = ((numer * 255) / denom) as u8;
696                t = match self.quality {
697                    RenderQuality::Low => 128,
698                    RenderQuality::Medium => (t / 64) * 64,
699                    RenderQuality::High => t,
700                };
701                let color = lerp_rgb565(gradient.start, gradient.end, t);
702                self.pixel(x, y, color, opacity)?;
703            }
704        }
705        Ok(())
706    }
707
708    pub fn stroke_rect(&mut self, rect: Rect, border: Border) -> Result<(), D::Error> {
709        self.stroke_rect_alpha(rect, border, 255)
710    }
711
712    pub fn stroke_rect_alpha(
713        &mut self,
714        rect: Rect,
715        border: Border,
716        opacity: u8,
717    ) -> Result<(), D::Error> {
718        if border.width == 0 || rect.is_empty() {
719            return Ok(());
720        }
721
722        for i in 0..border.width as i32 {
723            let w = rect.w.saturating_sub((i as u32).saturating_mul(2));
724            let h = rect.h.saturating_sub((i as u32).saturating_mul(2));
725            if w == 0 || h == 0 {
726                break;
727            }
728            let r = Rect::new(rect.x + i, rect.y + i, w, h);
729            self.fill_rect_alpha(Rect::new(r.x, r.y, r.w, 1), border.color, opacity)?;
730            if r.h > 1 {
731                self.fill_rect_alpha(
732                    Rect::new(r.x, r.bottom() - 1, r.w, 1),
733                    border.color,
734                    opacity,
735                )?;
736            }
737            if r.h > 2 {
738                self.fill_rect_alpha(Rect::new(r.x, r.y + 1, 1, r.h - 2), border.color, opacity)?;
739                if r.w > 1 {
740                    self.fill_rect_alpha(
741                        Rect::new(r.right() - 1, r.y + 1, 1, r.h - 2),
742                        border.color,
743                        opacity,
744                    )?;
745                }
746            }
747        }
748        Ok(())
749    }
750
751    pub fn stroke_rounded_rect(
752        &mut self,
753        rect: Rect,
754        radius: u8,
755        border: Border,
756    ) -> Result<(), D::Error> {
757        self.stroke_rounded_rect_alpha(rect, radius, border, 255)
758    }
759
760    pub fn stroke_rounded_rect_alpha(
761        &mut self,
762        rect: Rect,
763        radius: u8,
764        border: Border,
765        opacity: u8,
766    ) -> Result<(), D::Error> {
767        if border.width == 0 || rect.is_empty() || opacity == 0 {
768            return Ok(());
769        }
770        let draw = self.visible_rect(rect);
771        if draw.is_empty() {
772            return Ok(());
773        }
774
775        let radius = radius.min((rect.w.min(rect.h) / 2) as u8);
776        for y in draw.y..draw.bottom() {
777            for x in draw.x..draw.right() {
778                if !in_rounded_rect(x, y, rect, radius) {
779                    continue;
780                }
781
782                let mut inner_hit = false;
783                let mut i = 1u8;
784                while i < border.width {
785                    let inset = i as i32;
786                    let inner = Rect::new(
787                        rect.x + inset,
788                        rect.y + inset,
789                        rect.w.saturating_sub((i as u32) * 2),
790                        rect.h.saturating_sub((i as u32) * 2),
791                    );
792                    let inner_radius = radius.saturating_sub(i);
793                    if !inner.is_empty() && in_rounded_rect(x, y, inner, inner_radius) {
794                        inner_hit = true;
795                        break;
796                    }
797                    i += 1;
798                }
799
800                if !inner_hit {
801                    self.pixel(x, y, border.color, opacity)?;
802                }
803            }
804        }
805        Ok(())
806    }
807
808    pub fn draw_text(&mut self, x: i32, y: i32, text: &str, color: Rgb565) -> Result<(), D::Error> {
809        self.draw_text_with_font(x, y, text, color, FontId::Tiny3x5)
810    }
811
812    pub fn draw_text_with_font(
813        &mut self,
814        x: i32,
815        y: i32,
816        text: &str,
817        color: Rgb565,
818        font: FontId,
819    ) -> Result<(), D::Error> {
820        let advance = font.advance() as i32;
821        let line_h = font.line_height() as i32;
822        let mut cursor_x = x;
823        let mut cursor_y = y;
824        for ch in text.chars() {
825            if ch == '\n' {
826                cursor_x = x;
827                cursor_y += line_h;
828                continue;
829            }
830            self.draw_char_with_font(cursor_x, cursor_y, ch, color, 255, font)?;
831            cursor_x += advance;
832        }
833        Ok(())
834    }
835
836    pub fn draw_text_in(
837        &mut self,
838        rect: Rect,
839        text: &str,
840        style: TextStyle,
841    ) -> Result<(), D::Error> {
842        self.draw_text_in_with_font(rect, text, style, style.font)
843    }
844
845    pub fn draw_text_shaped_in<S, const N: usize>(
846        &mut self,
847        rect: Rect,
848        text: &str,
849        style: TextStyle,
850        shaper: &S,
851        config: crate::text::ShapingConfig,
852    ) -> Result<(), D::Error>
853    where
854        S: crate::text::TextShaper,
855    {
856        if rect.is_empty() {
857            return Ok(());
858        }
859        let mut shaped = heapless::Vec::<crate::text::ShapedGlyph, N>::new();
860        shaper.shape(text, config, &mut shaped);
861        if shaped.is_empty() {
862            return Ok(());
863        }
864        let mut x = rect.x;
865        let y = rect.y + rect.h.saturating_sub(style.font.line_height()) as i32 / 2;
866        for glyph in shaped {
867            self.draw_char_with_font(x, y, glyph.ch, style.color, style.opacity, style.font)?;
868            x += (glyph.x_advance as i32).max(1) * style.font.advance() as i32;
869            if x >= rect.right() {
870                break;
871            }
872        }
873        Ok(())
874    }
875
876    pub fn draw_text_in_with_font(
877        &mut self,
878        rect: Rect,
879        text: &str,
880        style: TextStyle,
881        font: FontId,
882    ) -> Result<(), D::Error> {
883        if rect.is_empty() {
884            return Ok(());
885        }
886
887        let advance = font.advance();
888        let line_h = font.line_height();
889        let max_chars = (rect.w / advance).max(1) as usize;
890        let char_count = text.chars().count();
891        let line_count = count_lines(text, max_chars, style.wrap).max(1);
892        let line_step = line_h + style.line_spacing as u32;
893        let total_h = line_count as u32 * line_h
894            + line_count.saturating_sub(1) as u32 * style.line_spacing as u32;
895        let mut y = match style.vertical_align {
896            VerticalAlign::Top => rect.y,
897            VerticalAlign::Middle => rect.y + rect.h.saturating_sub(total_h) as i32 / 2,
898            VerticalAlign::Bottom => rect.y + rect.h.saturating_sub(total_h) as i32,
899        };
900
901        let mut start = 0;
902        let mut rendered_lines = 0u8;
903        let max_lines = match style.overflow_policy {
904            TextOverflowPolicy::WrapThenEllipsis { max_lines } => max_lines.max(1),
905            TextOverflowPolicy::Global(_) => style.max_lines.unwrap_or(u8::MAX),
906        };
907        while start < char_count {
908            if rendered_lines >= max_lines {
909                break;
910            }
911            let (len, consumed_newline) = line_len_at(text, start, max_chars, style.wrap);
912            let mut draw_len = len;
913            let is_last_allowed_line = rendered_lines.saturating_add(1) >= max_lines;
914            let use_ellipsis = match style.overflow_policy {
915                TextOverflowPolicy::WrapThenEllipsis { .. } => is_last_allowed_line,
916                TextOverflowPolicy::Global(mode) => mode == TextOverflow::Ellipsis,
917            };
918            if use_ellipsis
919                && ((!consumed_newline && start + len < char_count) || is_last_allowed_line)
920            {
921                let ellipsis_width = match style.ellipsis {
922                    EllipsisMode::ThreeDots => 3usize,
923                    EllipsisMode::SingleGlyph => 1usize,
924                };
925                if len > ellipsis_width {
926                    draw_len = len - ellipsis_width;
927                }
928            }
929            let line_w = self.substring_width(text, start, draw_len, font, style.kerning);
930            let x = match style.align {
931                TextAlign::Left => rect.x,
932                TextAlign::Center => rect.x + rect.w.saturating_sub(line_w) as i32 / 2,
933                TextAlign::Right => rect.x + rect.w.saturating_sub(line_w) as i32,
934            };
935            self.draw_chars_with_font(
936                x,
937                y,
938                text,
939                start,
940                draw_len,
941                style.color,
942                style.opacity,
943                font,
944                style.kerning,
945            )?;
946            if draw_len < len && use_ellipsis {
947                let token = match style.ellipsis {
948                    EllipsisMode::ThreeDots => "...",
949                    EllipsisMode::SingleGlyph => ".",
950                };
951                self.draw_text_with_font(x + line_w as i32, y, token, style.color, font)?;
952            }
953            y += line_step as i32;
954            rendered_lines = rendered_lines.saturating_add(1);
955            start += len + usize::from(consumed_newline);
956            if style.wrap == TextWrap::Word && start < char_count {
957                while text.chars().nth(start).is_some_and(|ch| ch == ' ') {
958                    start += 1;
959                }
960            }
961            if len == 0 && !consumed_newline {
962                break;
963            }
964        }
965
966        Ok(())
967    }
968
969    pub fn draw_line_in(&mut self, rect: Rect, line: text::Line<'_>) -> Result<(), D::Error> {
970        if rect.is_empty() {
971            return Ok(());
972        }
973
974        self.draw_line_segment_in(rect, line, 0, line.width_chars())
975    }
976
977    pub fn draw_line(
978        &mut self,
979        x0: i32,
980        y0: i32,
981        x1: i32,
982        y1: i32,
983        color: Rgb565,
984    ) -> Result<(), D::Error> {
985        self.draw_line_styled(x0, y0, x1, y1, StrokeStyle::new(color))
986    }
987
988    pub fn draw_line_styled(
989        &mut self,
990        x0: i32,
991        y0: i32,
992        x1: i32,
993        y1: i32,
994        style: StrokeStyle,
995    ) -> Result<(), D::Error> {
996        let mut x = x0;
997        let mut y = y0;
998        let dx = (x1 - x0).abs();
999        let sx = if x0 < x1 { 1 } else { -1 };
1000        let dy = -(y1 - y0).abs();
1001        let sy = if y0 < y1 { 1 } else { -1 };
1002        let mut err = dx + dy;
1003        let half = (style.width as i32 / 2).max(0);
1004        let opacity = self.stroke_opacity(style);
1005
1006        loop {
1007            for oy in -half..=half {
1008                for ox in -half..=half {
1009                    self.pixel(x + ox, y + oy, style.color, opacity)?;
1010                }
1011            }
1012            if style.cap == StrokeCap::Round {
1013                self.fill_circle(x0, y0, half.max(1) as u32, style.color)?;
1014                self.fill_circle(x1, y1, half.max(1) as u32, style.color)?;
1015            }
1016            if x == x1 && y == y1 {
1017                break;
1018            }
1019            let e2 = 2 * err;
1020            if e2 >= dy {
1021                err += dy;
1022                x += sx;
1023            }
1024            if e2 <= dx {
1025                err += dx;
1026                y += sy;
1027            }
1028        }
1029        Ok(())
1030    }
1031
1032    pub fn fill_circle(
1033        &mut self,
1034        center_x: i32,
1035        center_y: i32,
1036        radius: u32,
1037        color: Rgb565,
1038    ) -> Result<(), D::Error> {
1039        let radius = radius as i32;
1040        if radius <= 0 {
1041            return Ok(());
1042        }
1043        for y in -radius..=radius {
1044            for x in -radius..=radius {
1045                if x * x + y * y <= radius * radius {
1046                    self.pixel(center_x + x, center_y + y, color, 255)?;
1047                }
1048            }
1049        }
1050        Ok(())
1051    }
1052
1053    pub fn stroke_circle(
1054        &mut self,
1055        center_x: i32,
1056        center_y: i32,
1057        radius: u32,
1058        color: Rgb565,
1059    ) -> Result<(), D::Error> {
1060        let radius = radius as i32;
1061        if radius <= 0 {
1062            return Ok(());
1063        }
1064        let mut x = radius;
1065        let mut y = 0;
1066        let mut err = 1 - x;
1067        while x >= y {
1068            self.pixel(center_x + x, center_y + y, color, 255)?;
1069            self.pixel(center_x + y, center_y + x, color, 255)?;
1070            self.pixel(center_x - y, center_y + x, color, 255)?;
1071            self.pixel(center_x - x, center_y + y, color, 255)?;
1072            self.pixel(center_x - x, center_y - y, color, 255)?;
1073            self.pixel(center_x - y, center_y - x, color, 255)?;
1074            self.pixel(center_x + y, center_y - x, color, 255)?;
1075            self.pixel(center_x + x, center_y - y, color, 255)?;
1076            y += 1;
1077            if err < 0 {
1078                err += 2 * y + 1;
1079            } else {
1080                x -= 1;
1081                err += 2 * (y - x) + 1;
1082            }
1083        }
1084        Ok(())
1085    }
1086
1087    pub fn stroke_arc(
1088        &mut self,
1089        center_x: i32,
1090        center_y: i32,
1091        radius: u32,
1092        start_deg: i32,
1093        end_deg: i32,
1094        color: Rgb565,
1095    ) -> Result<(), D::Error> {
1096        self.stroke_arc_styled(
1097            center_x,
1098            center_y,
1099            radius,
1100            start_deg,
1101            end_deg,
1102            StrokeStyle::new(color),
1103        )
1104    }
1105
1106    pub fn stroke_arc_styled(
1107        &mut self,
1108        center_x: i32,
1109        center_y: i32,
1110        radius: u32,
1111        start_deg: i32,
1112        end_deg: i32,
1113        style: StrokeStyle,
1114    ) -> Result<(), D::Error> {
1115        let mut start = start_deg;
1116        let mut end = end_deg;
1117        if end < start {
1118            core::mem::swap(&mut start, &mut end);
1119        }
1120        let mut deg = start;
1121        let step = match self.quality {
1122            RenderQuality::Low => 8,
1123            RenderQuality::Medium => 4,
1124            RenderQuality::High => 2,
1125        };
1126        while deg <= end {
1127            let rad = (deg as f32).to_radians();
1128            let x = center_x + (radius as f32 * rad.cos()) as i32;
1129            let y = center_y + (radius as f32 * rad.sin()) as i32;
1130            let half = (style.width as i32 / 2).max(0);
1131            let opacity = self.stroke_opacity(style);
1132            for oy in -half..=half {
1133                for ox in -half..=half {
1134                    self.pixel(x + ox, y + oy, style.color, opacity)?;
1135                }
1136            }
1137            if style.join == StrokeJoin::Round {
1138                self.fill_circle(x, y, half.max(1) as u32, style.color)?;
1139            }
1140            deg += step;
1141        }
1142        Ok(())
1143    }
1144
1145    /// Fill a sector ("pie slice") using a start angle and sweep angle in degrees.
1146    ///
1147    /// Positive sweep draws counterclockwise, negative sweep clockwise.
1148    pub fn fill_sector_sweep(
1149        &mut self,
1150        center_x: i32,
1151        center_y: i32,
1152        radius: u32,
1153        start_deg: f32,
1154        sweep_deg: f32,
1155        color: Rgb565,
1156    ) -> Result<(), D::Error> {
1157        if radius == 0 {
1158            return Ok(());
1159        }
1160
1161        let draw = self.visible_rect(Rect::new(
1162            center_x - radius as i32,
1163            center_y - radius as i32,
1164            radius.saturating_mul(2).saturating_add(1),
1165            radius.saturating_mul(2).saturating_add(1),
1166        ));
1167        if draw.is_empty() {
1168            return Ok(());
1169        }
1170
1171        let max_sweep = sweep_deg.abs().min(360.0);
1172        if max_sweep <= 0.0 {
1173            return Ok(());
1174        }
1175
1176        let rr = (radius as i32) * (radius as i32);
1177        let start = normalize_angle_deg(start_deg);
1178        let ccw = sweep_deg >= 0.0;
1179
1180        for y in draw.y..draw.bottom() {
1181            for x in draw.x..draw.right() {
1182                let dx = x - center_x;
1183                let dy = y - center_y;
1184                let d2 = dx * dx + dy * dy;
1185                if d2 > rr {
1186                    continue;
1187                }
1188
1189                let mut angle = (dy as f32).atan2(dx as f32).to_degrees();
1190                if angle < 0.0 {
1191                    angle += 360.0;
1192                }
1193                let in_sweep = if ccw {
1194                    ccw_distance_deg(start, angle) <= max_sweep
1195                } else {
1196                    ccw_distance_deg(angle, start) <= max_sweep
1197                };
1198                if in_sweep {
1199                    self.pixel(x, y, color, 255)?;
1200                }
1201            }
1202        }
1203        Ok(())
1204    }
1205
1206    pub fn fill_polygon(&mut self, points: &[Point], color: Rgb565) -> Result<(), D::Error> {
1207        if points.len() < 3 {
1208            return Ok(());
1209        }
1210        let min_y = points.iter().map(|p| p.y).min().unwrap_or(0);
1211        let max_y = points.iter().map(|p| p.y).max().unwrap_or(-1);
1212        for y in min_y..=max_y {
1213            let mut intersections = [i32::MIN; 16];
1214            let mut count = 0usize;
1215            for i in 0..points.len() {
1216                let p1 = points[i];
1217                let p2 = points[(i + 1) % points.len()];
1218                let (y1, y2) = if p1.y <= p2.y {
1219                    (p1.y, p2.y)
1220                } else {
1221                    (p2.y, p1.y)
1222                };
1223                if y < y1 || y >= y2 || y1 == y2 {
1224                    continue;
1225                }
1226                if count >= intersections.len() {
1227                    break;
1228                }
1229                let x = p1.x + ((y - p1.y) * (p2.x - p1.x)) / (p2.y - p1.y);
1230                intersections[count] = x;
1231                count += 1;
1232            }
1233            intersections[..count].sort_unstable();
1234            let mut i = 0;
1235            while i + 1 < count {
1236                let x0 = intersections[i];
1237                let x1 = intersections[i + 1];
1238                for x in x0..=x1 {
1239                    self.pixel(x, y, color, 255)?;
1240                }
1241                i += 2;
1242            }
1243        }
1244        Ok(())
1245    }
1246
1247    pub fn draw_image(
1248        &mut self,
1249        rect: Rect,
1250        image: ImageRef<'_>,
1251        fit: ImageFit,
1252    ) -> Result<(), D::Error> {
1253        self.draw_image_region(rect, image, fit, Rect::new(0, 0, image.width, image.height))
1254    }
1255
1256    pub fn draw_image_region(
1257        &mut self,
1258        rect: Rect,
1259        image: ImageRef<'_>,
1260        fit: ImageFit,
1261        src_rect: Rect,
1262    ) -> Result<(), D::Error> {
1263        let bounds = image.bounds_at(rect, fit);
1264        if bounds.is_empty() || image.width == 0 || image.height == 0 {
1265            return Ok(());
1266        }
1267        let src_w = image.width as usize;
1268        for y in 0..bounds.h {
1269            let src_y = match fit {
1270                ImageFit::Stretch => {
1271                    src_rect.y.max(0) as usize
1272                        + ((y as u64 * src_rect.h as u64) / bounds.h as u64) as usize
1273                }
1274                ImageFit::Center => src_rect.y.max(0) as usize + y as usize,
1275            };
1276            for x in 0..bounds.w {
1277                let src_x = match fit {
1278                    ImageFit::Stretch => {
1279                        src_rect.x.max(0) as usize
1280                            + ((x as u64 * src_rect.w as u64) / bounds.w as u64) as usize
1281                    }
1282                    ImageFit::Center => src_rect.x.max(0) as usize + x as usize,
1283                };
1284                let idx = src_y.saturating_mul(src_w).saturating_add(src_x);
1285                if let Some(raw) = image.pixels.get(idx) {
1286                    let color = Rgb565::new(
1287                        ((raw >> 11) & 0x1F) as u8,
1288                        ((raw >> 5) & 0x3F) as u8,
1289                        (raw & 0x1F) as u8,
1290                    );
1291                    self.pixel(bounds.x + x as i32, bounds.y + y as i32, color, 255)?;
1292                }
1293            }
1294        }
1295        Ok(())
1296    }
1297
1298    pub fn draw_image_transformed(
1299        &mut self,
1300        rect: Rect,
1301        image: ImageRef<'_>,
1302        scale: f32,
1303        rotation_deg: f32,
1304    ) -> Result<(), D::Error> {
1305        if rect.is_empty() || image.width == 0 || image.height == 0 || scale <= 0.0 {
1306            return Ok(());
1307        }
1308        let cx = rect.x + rect.w as i32 / 2;
1309        let cy = rect.y + rect.h as i32 / 2;
1310        let rad = rotation_deg.to_radians();
1311        let cos_r = rad.cos();
1312        let sin_r = rad.sin();
1313        let src_w = image.width as usize;
1314        let src_cx = image.width as f32 / 2.0;
1315        let src_cy = image.height as f32 / 2.0;
1316        for y in rect.y..rect.bottom() {
1317            for x in rect.x..rect.right() {
1318                let dx = (x - cx) as f32 / scale;
1319                let dy = (y - cy) as f32 / scale;
1320                let sx = cos_r * dx + sin_r * dy + src_cx;
1321                let sy = -sin_r * dx + cos_r * dy + src_cy;
1322                if sx < 0.0 || sy < 0.0 || sx >= image.width as f32 || sy >= image.height as f32 {
1323                    continue;
1324                }
1325                let idx = (sy as usize)
1326                    .saturating_mul(src_w)
1327                    .saturating_add(sx as usize);
1328                if let Some(raw) = image.pixels.get(idx) {
1329                    let color = Rgb565::new(
1330                        ((raw >> 11) & 0x1F) as u8,
1331                        ((raw >> 5) & 0x3F) as u8,
1332                        (raw & 0x1F) as u8,
1333                    );
1334                    self.pixel(x, y, color, 255)?;
1335                }
1336            }
1337        }
1338        Ok(())
1339    }
1340
1341    pub fn fill_rect_masked(
1342        &mut self,
1343        rect: Rect,
1344        color: Rgb565,
1345        mask: fn(i32, i32) -> bool,
1346    ) -> Result<(), D::Error> {
1347        let draw = self.visible_rect(rect);
1348        if draw.is_empty() {
1349            return Ok(());
1350        }
1351        for y in draw.y..draw.bottom() {
1352            for x in draw.x..draw.right() {
1353                if mask(x, y) {
1354                    self.pixel(x, y, color, 255)?;
1355                }
1356            }
1357        }
1358        Ok(())
1359    }
1360
1361    pub fn draw_text_model_in(&mut self, rect: Rect, text: text::Text<'_>) -> Result<(), D::Error> {
1362        if rect.is_empty() || text.lines.is_empty() {
1363            return Ok(());
1364        }
1365
1366        let metrics = text.metrics(rect.w);
1367        let max_line_height = text
1368            .lines
1369            .iter()
1370            .map(|line| line.max_line_height())
1371            .max()
1372            .unwrap_or(CHAR_HEIGHT);
1373        let line_step = max_line_height + text.line_spacing as u32;
1374        let mut y = match text.vertical_align {
1375            VerticalAlign::Top => rect.y,
1376            VerticalAlign::Middle => rect.y + rect.h.saturating_sub(metrics.height) as i32 / 2,
1377            VerticalAlign::Bottom => rect.y + rect.h.saturating_sub(metrics.height) as i32,
1378        };
1379        for line in text.lines {
1380            let align = if line.align == TextAlign::Left {
1381                text.align
1382            } else {
1383                line.align
1384            };
1385            let line = text::Line { align, ..*line };
1386
1387            let mut start = 0;
1388            let char_count = line.char_count();
1389            if char_count == 0 {
1390                y += line_step as i32;
1391                continue;
1392            }
1393            while start < char_count {
1394                if y >= rect.bottom() {
1395                    return Ok(());
1396                }
1397                let (len, consumed_newline) = line.segment_len_at(start, rect.w, text.wrap);
1398                self.draw_line_segment_in(
1399                    Rect::new(rect.x, y, rect.w, max_line_height),
1400                    line,
1401                    start,
1402                    len,
1403                )?;
1404                y += line_step as i32;
1405                start += len + usize::from(consumed_newline);
1406                if len == 0 && !consumed_newline {
1407                    break;
1408                }
1409            }
1410        }
1411
1412        Ok(())
1413    }
1414
1415    pub fn text_metrics(text: &str) -> TextMetrics {
1416        Self::text_metrics_with_font(text, FontId::Tiny3x5)
1417    }
1418
1419    pub fn text_metrics_with_font(text: &str, font: FontId) -> TextMetrics {
1420        TextMetrics {
1421            width: text.chars().count() as u32 * font.advance(),
1422            height: font.line_height(),
1423        }
1424    }
1425
1426    pub fn text_metrics_wrapped(text: &str, max_width: u32, wrap: TextWrap) -> TextMetrics {
1427        Self::text_metrics_wrapped_with_font(text, max_width, wrap, FontId::Tiny3x5)
1428    }
1429
1430    pub fn text_metrics_wrapped_with_font(
1431        text: &str,
1432        max_width: u32,
1433        wrap: TextWrap,
1434        font: FontId,
1435    ) -> TextMetrics {
1436        let max_chars = (max_width / font.advance()).max(1) as usize;
1437        let lines = count_lines(text, max_chars, wrap).max(1);
1438        let widest = widest_line(text, max_chars, wrap) as u32 * font.advance();
1439        TextMetrics {
1440            width: widest.min(max_width),
1441            height: lines as u32 * font.line_height() + lines.saturating_sub(1) as u32,
1442        }
1443    }
1444
1445    #[allow(clippy::too_many_arguments)]
1446    fn draw_chars_with_font(
1447        &mut self,
1448        x: i32,
1449        y: i32,
1450        text: &str,
1451        start: usize,
1452        len: usize,
1453        color: Rgb565,
1454        opacity: u8,
1455        font: FontId,
1456        kerning: bool,
1457    ) -> Result<(), D::Error> {
1458        let advance = font.advance() as i32;
1459        let mut cursor_x = x;
1460        let mut prev: Option<char> = None;
1461        for ch in text.chars().skip(start).take(len) {
1462            self.draw_char_with_font(cursor_x, y, ch, color, opacity, font)?;
1463            cursor_x += advance + kerning_adjust(prev, ch, kerning);
1464            prev = Some(ch);
1465        }
1466        Ok(())
1467    }
1468
1469    fn substring_width(
1470        &self,
1471        text: &str,
1472        start: usize,
1473        len: usize,
1474        font: FontId,
1475        kerning: bool,
1476    ) -> u32 {
1477        let mut width = 0u32;
1478        let mut prev = None;
1479        for ch in text.chars().skip(start).take(len) {
1480            width = width.saturating_add(font.advance());
1481            let adjust = kerning_adjust(prev, ch, kerning);
1482            if adjust < 0 {
1483                width = width.saturating_sub((-adjust) as u32);
1484            } else {
1485                width = width.saturating_add(adjust as u32);
1486            }
1487            prev = Some(ch);
1488        }
1489        width
1490    }
1491
1492    fn draw_line_segment_in(
1493        &mut self,
1494        rect: Rect,
1495        line: text::Line<'_>,
1496        start: usize,
1497        len: usize,
1498    ) -> Result<(), D::Error> {
1499        if rect.is_empty() || len == 0 {
1500            return Ok(());
1501        }
1502
1503        let line_w = self.line_segment_width(line, start, len);
1504        let x = match line.align {
1505            TextAlign::Left => rect.x,
1506            TextAlign::Center => rect.x + rect.w.saturating_sub(line_w) as i32 / 2,
1507            TextAlign::Right => rect.x + rect.w.saturating_sub(line_w) as i32,
1508        };
1509
1510        let old_clip = self.clip;
1511        self.clip = self.clip.intersection(rect);
1512        let result = self.draw_span_chars(x, rect.y, line, start, len);
1513        self.clip = old_clip;
1514        result
1515    }
1516
1517    fn draw_span_chars(
1518        &mut self,
1519        x: i32,
1520        y: i32,
1521        line: text::Line<'_>,
1522        start: usize,
1523        len: usize,
1524    ) -> Result<(), D::Error> {
1525        let mut cursor_x = x;
1526        for (idx, (ch, style)) in line
1527            .spans
1528            .iter()
1529            .flat_map(|span| span.content.chars().map(move |ch| (ch, span.style)))
1530            .enumerate()
1531        {
1532            if idx < start {
1533                continue;
1534            }
1535            if idx >= start + len {
1536                break;
1537            }
1538            if ch != '\n' {
1539                self.draw_char_with_font(cursor_x, y, ch, style.color, 255, style.font)?;
1540                cursor_x += style.font.advance() as i32;
1541            }
1542        }
1543        Ok(())
1544    }
1545
1546    fn line_segment_width(&self, line: text::Line<'_>, start: usize, len: usize) -> u32 {
1547        line.spans
1548            .iter()
1549            .flat_map(|span| span.content.chars().map(move |ch| (ch, span.style.font)))
1550            .enumerate()
1551            .filter_map(|(idx, (ch, font))| {
1552                if idx < start || idx >= start + len || ch == '\n' {
1553                    None
1554                } else {
1555                    Some(font.advance())
1556                }
1557            })
1558            .sum()
1559    }
1560
1561    fn draw_char_with_font(
1562        &mut self,
1563        x: i32,
1564        y: i32,
1565        ch: char,
1566        color: Rgb565,
1567        opacity: u8,
1568        font: FontId,
1569    ) -> Result<(), D::Error> {
1570        let glyph = glyph_rows(font, ch);
1571        match font {
1572            FontId::Tiny3x5 => {
1573                for (row, bits) in glyph.iter().enumerate() {
1574                    for col in 0..3 {
1575                        if bits & (1 << (2 - col)) != 0 {
1576                            self.pixel(x + col, y + row as i32, color, opacity)?;
1577                        }
1578                    }
1579                }
1580            }
1581            FontId::Medium4x7 => {
1582                for (row, bits) in glyph.iter().enumerate() {
1583                    for col in 0..3 {
1584                        if bits & (1 << (2 - col)) != 0 {
1585                            self.pixel(x + col, y + row as i32, color, opacity)?;
1586                        }
1587                    }
1588                }
1589            }
1590            FontId::Scaled6x10 => {
1591                for (row, bits) in glyph.iter().enumerate() {
1592                    for col in 0..3 {
1593                        if bits & (1 << (2 - col)) != 0 {
1594                            let px = x + (col * 2);
1595                            let py = y + (row as i32 * 2);
1596                            self.pixel(px, py, color, opacity)?;
1597                            self.pixel(px + 1, py, color, opacity)?;
1598                            self.pixel(px, py + 1, color, opacity)?;
1599                            self.pixel(px + 1, py + 1, color, opacity)?;
1600                        }
1601                    }
1602                }
1603            }
1604        }
1605        Ok(())
1606    }
1607
1608    fn pixel(&mut self, x: i32, y: i32, color: Rgb565, opacity: u8) -> Result<(), D::Error> {
1609        let (x, y) = self.current_transform().apply(x, y);
1610        if !self.clip.contains(x, y) {
1611            return Ok(());
1612        }
1613        if let Some(dirty) = self.dirty {
1614            if !dirty.contains(x, y) {
1615                return Ok(());
1616            }
1617        }
1618        let layer = self.current_layer();
1619        let combined_opacity = ((opacity as u16 * layer.opacity as u16) / 255) as u8;
1620        // The compositor policy (`Dither` vs `Blend`) decides how the pixel
1621        // lands: ordered dither for write-only targets, true alpha blend for
1622        // readback-capable ones. Zero-cost — resolved by `C` at monomorphization.
1623        C::plot(
1624            self.target,
1625            x,
1626            y,
1627            color,
1628            combined_opacity,
1629            layer.blend,
1630            layer.backdrop,
1631        )
1632    }
1633
1634    fn visible_rect(&self, rect: Rect) -> Rect {
1635        let mut draw = rect.intersection(self.clip);
1636        if let Some(dirty) = self.dirty {
1637            draw = draw.intersection(dirty);
1638        }
1639        draw
1640    }
1641
1642    fn current_transform(&self) -> Transform2D {
1643        self.transform_stack[self.transform_len - 1]
1644    }
1645
1646    fn current_layer(&self) -> LayerState {
1647        self.layer_stack[self.layer_len - 1]
1648    }
1649
1650    fn stroke_opacity(&self, style: StrokeStyle) -> u8 {
1651        if !style.antialias || matches!(style.antialias_mode, AntiAliasMode::None) {
1652            return 255;
1653        }
1654        match style.antialias_mode {
1655            AntiAliasMode::None => 255,
1656            AntiAliasMode::Coverage => match self.quality {
1657                RenderQuality::Low => 96,
1658                RenderQuality::Medium => 160,
1659                RenderQuality::High => 220,
1660            },
1661            AntiAliasMode::Subpixel => {
1662                if self.backend_caps.supports_subpixel {
1663                    match self.quality {
1664                        RenderQuality::Low => 128,
1665                        RenderQuality::Medium => 192,
1666                        RenderQuality::High => 240,
1667                    }
1668                } else {
1669                    match self.quality {
1670                        RenderQuality::Low => 96,
1671                        RenderQuality::Medium => 160,
1672                        RenderQuality::High => 220,
1673                    }
1674                }
1675            }
1676        }
1677    }
1678}
1679
1680impl<'a, D, C> RenderCtx<'a, D, C>
1681where
1682    D: DrawTarget<Color = Rgb565> + PixelRead,
1683    C: Compositor<D>,
1684{
1685    /// Alpha-composite `color` over whatever is already at `(x, y)` in the
1686    /// destination, using true per-pixel blending (`lerp_rgb565`) rather
1687    /// than the dithered approximation `pixel()` uses.
1688    fn pixel_blended(&mut self, x: i32, y: i32, color: Rgb565, alpha: u8) -> Result<(), D::Error> {
1689        let (x, y) = self.current_transform().apply(x, y);
1690        if !self.clip.contains(x, y) {
1691            return Ok(());
1692        }
1693        if let Some(dirty) = self.dirty {
1694            if !dirty.contains(x, y) {
1695                return Ok(());
1696            }
1697        }
1698        let layer = self.current_layer();
1699        let combined_alpha = ((alpha as u16 * layer.opacity as u16) / 255) as u8;
1700        if combined_alpha == 0 {
1701            return Ok(());
1702        }
1703        let backdrop = self.target.get_pixel(Point::new(x, y));
1704        let blended = lerp_rgb565(backdrop, color, combined_alpha);
1705        let blended = apply_blend_mode(blended, layer.blend, layer.backdrop);
1706        self.target.draw_iter([Pixel(Point::new(x, y), blended)])
1707    }
1708
1709    /// Like [`RenderCtx::fill_rect_alpha`], but alpha-composites against the
1710    /// destination's real current pixels instead of dithering.
1711    pub fn fill_rect_true_alpha(
1712        &mut self,
1713        rect: Rect,
1714        color: Rgb565,
1715        alpha: u8,
1716    ) -> Result<(), D::Error> {
1717        self.fill_rounded_rect_true_alpha(rect, 0, color, alpha)
1718    }
1719
1720    /// Like [`RenderCtx::fill_rounded_rect_alpha`], but alpha-composites
1721    /// against the destination's real current pixels instead of dithering.
1722    pub fn fill_rounded_rect_true_alpha(
1723        &mut self,
1724        rect: Rect,
1725        radius: u8,
1726        color: Rgb565,
1727        alpha: u8,
1728    ) -> Result<(), D::Error> {
1729        let draw = self.visible_rect(rect);
1730        if draw.is_empty() || alpha == 0 {
1731            return Ok(());
1732        }
1733        let radius = radius.min((rect.w.min(rect.h) / 2) as u8);
1734
1735        for y in draw.y..draw.bottom() {
1736            for x in draw.x..draw.right() {
1737                if !in_rounded_rect(x, y, rect, radius) {
1738                    continue;
1739                }
1740                self.pixel_blended(x, y, color, alpha)?;
1741            }
1742        }
1743        Ok(())
1744    }
1745}
1746
1747fn should_draw_at_opacity(x: i32, y: i32, opacity: u8) -> bool {
1748    if opacity == 255 {
1749        return true;
1750    }
1751    if opacity == 0 {
1752        return false;
1753    }
1754    let bayer4 = [
1755        [0u8, 8, 2, 10],
1756        [12, 4, 14, 6],
1757        [3, 11, 1, 9],
1758        [15, 7, 13, 5],
1759    ];
1760    let threshold = ((opacity as u16 * 16) / 255) as u8;
1761    let sample = bayer4[(y as usize) & 3][(x as usize) & 3];
1762    sample < threshold.max(1)
1763}
1764
1765fn lerp_rgb565(a: Rgb565, b: Rgb565, t: u8) -> Rgb565 {
1766    let t = t as u16;
1767    let inv = 255u16.saturating_sub(t);
1768    let r = ((a.r() as u16 * inv) + (b.r() as u16 * t)) / 255;
1769    let g = ((a.g() as u16 * inv) + (b.g() as u16 * t)) / 255;
1770    let bb = ((a.b() as u16 * inv) + (b.b() as u16 * t)) / 255;
1771    Rgb565::new(r as u8, g as u8, bb as u8)
1772}
1773
1774#[inline]
1775fn normalize_angle_deg(mut deg: f32) -> f32 {
1776    while deg < 0.0 {
1777        deg += 360.0;
1778    }
1779    while deg >= 360.0 {
1780        deg -= 360.0;
1781    }
1782    deg
1783}
1784
1785#[inline]
1786fn ccw_distance_deg(from: f32, to: f32) -> f32 {
1787    let mut d = normalize_angle_deg(to) - normalize_angle_deg(from);
1788    if d < 0.0 {
1789        d += 360.0;
1790    }
1791    d
1792}
1793
1794fn apply_blend_mode(src: Rgb565, mode: BlendMode, backdrop: Rgb565) -> Rgb565 {
1795    match mode {
1796        BlendMode::Normal => src,
1797        BlendMode::Add => Rgb565::new(
1798            src.r().saturating_add(backdrop.r()),
1799            src.g().saturating_add(backdrop.g()),
1800            src.b().saturating_add(backdrop.b()),
1801        ),
1802        BlendMode::Multiply => Rgb565::new(
1803            ((src.r() as u16 * backdrop.r() as u16) / 31) as u8,
1804            ((src.g() as u16 * backdrop.g() as u16) / 63) as u8,
1805            ((src.b() as u16 * backdrop.b() as u16) / 31) as u8,
1806        ),
1807        BlendMode::Screen => Rgb565::new(
1808            (31 - ((31 - src.r() as u16) * (31 - backdrop.r() as u16) / 31)) as u8,
1809            (63 - ((63 - src.g() as u16) * (63 - backdrop.g() as u16) / 63)) as u8,
1810            (31 - ((31 - src.b() as u16) * (31 - backdrop.b() as u16) / 31)) as u8,
1811        ),
1812    }
1813}
1814
1815fn in_rounded_rect(x: i32, y: i32, rect: Rect, radius: u8) -> bool {
1816    if rect.is_empty() {
1817        return false;
1818    }
1819    let radius = radius as i32;
1820    if radius <= 0 {
1821        return rect.contains(x, y);
1822    }
1823
1824    let left = rect.x;
1825    let top = rect.y;
1826    let right = rect.right() - 1;
1827    let bottom = rect.bottom() - 1;
1828    let inner_left = left + radius;
1829    let inner_right = right - radius;
1830    let inner_top = top + radius;
1831    let inner_bottom = bottom - radius;
1832
1833    if (x >= inner_left && x <= inner_right) || (y >= inner_top && y <= inner_bottom) {
1834        return rect.contains(x, y);
1835    }
1836
1837    let (cx, cy) = if x < inner_left && y < inner_top {
1838        (inner_left, inner_top)
1839    } else if x > inner_right && y < inner_top {
1840        (inner_right, inner_top)
1841    } else if x < inner_left && y > inner_bottom {
1842        (inner_left, inner_bottom)
1843    } else if x > inner_right && y > inner_bottom {
1844        (inner_right, inner_bottom)
1845    } else {
1846        return rect.contains(x, y);
1847    };
1848
1849    let dx = x - cx;
1850    let dy = y - cy;
1851    dx * dx + dy * dy <= radius * radius
1852}
1853
1854fn line_len_at(text: &str, start: usize, max_chars: usize, wrap: TextWrap) -> (usize, bool) {
1855    let mut len = 0;
1856    let limit = match wrap {
1857        TextWrap::None => usize::MAX,
1858        TextWrap::Character => max_chars.max(1),
1859        TextWrap::Word => max_chars.max(1),
1860    };
1861    let mut last_ws_break = None;
1862
1863    for ch in text.chars().skip(start) {
1864        if ch == '\n' {
1865            return (len, true);
1866        }
1867        if matches!(wrap, TextWrap::Word) && ch.is_whitespace() {
1868            last_ws_break = Some(len + 1);
1869        }
1870        if len >= limit {
1871            if matches!(wrap, TextWrap::Word) {
1872                if let Some(idx) = last_ws_break {
1873                    return (idx, false);
1874                }
1875            }
1876            return (len, false);
1877        }
1878        len += 1;
1879    }
1880
1881    (len, false)
1882}
1883
1884fn count_lines(text: &str, max_chars: usize, wrap: TextWrap) -> usize {
1885    if text.is_empty() {
1886        return 1;
1887    }
1888    let char_count = text.chars().count();
1889    let mut lines = 0;
1890    let mut start = 0;
1891    while start < char_count {
1892        let (len, consumed_newline) = line_len_at(text, start, max_chars, wrap);
1893        lines += 1;
1894        start += len + usize::from(consumed_newline);
1895        if len == 0 && !consumed_newline {
1896            break;
1897        }
1898    }
1899    lines
1900}
1901
1902fn widest_line(text: &str, max_chars: usize, wrap: TextWrap) -> usize {
1903    let char_count = text.chars().count();
1904    let mut widest = 0;
1905    let mut start = 0;
1906    while start < char_count {
1907        let (len, consumed_newline) = line_len_at(text, start, max_chars, wrap);
1908        widest = widest.max(len);
1909        start += len + usize::from(consumed_newline);
1910        if len == 0 && !consumed_newline {
1911            break;
1912        }
1913    }
1914    widest
1915}
1916
1917fn kerning_adjust(prev: Option<char>, next: char, enabled: bool) -> i32 {
1918    if !enabled {
1919        return 0;
1920    }
1921    match (prev, next) {
1922        (Some('A'), 'V') | (Some('A'), 'W') | (Some('T'), 'o') | (Some('L'), 'T') => -1,
1923        _ => 0,
1924    }
1925}