rust_widgets 2.7.0

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 180 widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! Pixel-level operations: blend_painted_glyph, glyph_rects, fill_pixels,
//! blend_pixel, set_pixel, pixel_bytes_len, and anti-aliased coverage/geometry helpers.
use crate::core::{Color, Point, Rect, Size};

/// Where one glyph is painted, and into what.
///
/// # Why this is not owned by the glyph
///
/// The cell is the caller's decision (a label draws a cluster in a box as wide as its own advance),
/// not a property of the face — a vector face can rasterise at any cell size. So position and cell
/// travel together in the caller's struct and the face is asked only "paint into this".
///
/// # Why the position is not a field
///
/// It **is** the caller's `x`/`y`, and it used to be copied in here as well: `glyph_rects` read the
/// copies while the caller read the originals, so the two could disagree without anything noticing.
/// [`blend_painted_glyph`] takes the position as arguments instead, which makes that impossible —
/// there is one place a glyph's position is written, so there is nothing to keep in step.
pub(crate) struct GlyphDrawConfig<'a> {
    /// Cell width in pixels.
    pub w: u32,
    /// Cell height in pixels.
    pub h: u32,
    /// Glyph color.
    pub color: Color,
    /// Canvas width.
    pub canvas_width: u32,
    /// Canvas height.
    pub canvas_height: u32,
    /// Canvas pixel buffer (RGBA8).
    pub canvas: &'a mut [u8],
    /// Active render clip, if any.
    pub clip: Option<(i32, i32, u32, u32)>,
}

/// The solid rectangles one glyph's bitmap produces inside its own box.
///
/// # Why this is a function and not a loop body
///
/// The software rasteriser drew glyphs by walking the `font8x8` bitmap and filling one
/// rectangle per set bit, computing each rectangle as
///
/// ```text
/// x0 = x + gx * w / 8,  x1 = x + (gx + 1) * w / 8
/// y0 = y + gy * h / 8,  y1 = y + (gy + 1) * h / 8
/// ```
///
/// while the SVG backend emitted a `<text>` element and let the viewer's font engine pick a
/// font. Those are two different renderers of the same string: different glyph shapes,
/// different advances, different ink boxes. Neither can be reconciled with the other by
/// adjusting a coordinate.
///
/// So the geometry lives here, once, and **both** backends read it: the rasteriser fills the
/// rectangles, the SVG backend emits them as one `<path>`. The two outputs are then the same
/// drawing by construction — not by resemblance, and not by two implementations that have to
/// be kept in step.
///
/// Returns `(x0, y0, x1, y1)` with `x1`/`y1` **exclusive**, matching the rasteriser's
/// half-open fill. A set bit always produces a non-empty rectangle: the `(gx + 1) * w / 8`
/// term can equal `gx * w / 8` when `w < 8`, and a zero-extent rectangle is a drawing command
/// that paints nothing, so it is widened to one pixel (which is also what the rasteriser's
/// own guard did).
///
/// The cell walked here is the one the **active font stack** answers with — 8x8 for Latin,
/// 16x16 for a CJK character when a CJK face is enabled — and the division is by that cell's
/// own dimensions, not by a hardcoded 8. The default build's stack is the 8x8 face, so every
/// coordinate this produced before the stack existed is reproduced bit for bit.
pub(crate) fn glyph_rects(
    ch: char,
    x: i32,
    y: i32,
    w: u32,
    h: u32,
) -> impl Iterator<Item = (i32, i32, i32, i32)> {
    let width = w as i32;
    let height = h as i32;
    let mut rects = crate::compat::Vec::new();
    // A whitespace glyph and a zero-extent box produce no ink; the rasteriser returns early for
    // both, and so does this.
    if !ch.is_whitespace() && w != 0 && h != 0 {
        let (glyph, _) = crate::render::text::resolve(ch);
        let gw = glyph.width as i32;
        let gh = glyph.height as i32;
        // A resolved glyph is always a real cell (8x8 or 16x16); the guard is belt-and-braces so
        // a hypothetical zero-sized face divides nothing.
        if gw > 0 && gh > 0 {
            for gy in 0..gh {
                let y0 = y + (gy * height) / gh;
                let mut y1 = y + ((gy + 1) * height) / gh;
                if y1 <= y0 {
                    y1 = y0 + 1;
                }
                for gx in 0..gw {
                    if !glyph.bit(gx as u32, gy as u32) {
                        continue;
                    }
                    let x0 = x + (gx * width) / gw;
                    let mut x1 = x + ((gx + 1) * width) / gw;
                    if x1 <= x0 {
                        x1 = x0 + 1;
                    }
                    rects.push((x0, y0, x1, y1));
                }
            }
        }
    }
    rects.into_iter()
}

/// Blend one glyph's ink into a canvas, from a face's painted coverage.
///
/// # Why a renderer calls this and not `glyph_rects`
///
/// `glyph_rects` answers "which rectangles does this glyph's 1-bit bitmap produce?" — which is
/// what a *vector* backend wants (one subpath per set source pixel) and what the rasteriser used
/// to want. It is the wrong question for a rasteriser the moment a face can produce partial
/// coverage: antialiased ink is a value per destination pixel, not a set of full-intensity
/// rectangles, and no set of rectangles can express it.
///
/// So the rasteriser asks the face to **paint** and blends what it gets, byte per byte. For a
/// 1-bit face the two are the same picture: [`paint_bitmap`] writes `255` on exactly the pixels
/// `glyph_rects` would have filled, so every existing snapshot is unchanged — and a vector face
/// gets antialiasing through the same blend, with no second code path.
///
/// `coverage` is a caller-owned scratch of at least `cell.area()` bytes, reused across glyphs so
/// no per-glyph allocation happens on a paint path (constraint: a glyph is never resident).
/// Returns whether any ink was blended.
pub(crate) fn blend_painted_glyph(
    ch: char,
    x: i32,
    y: i32,
    /* the cell is taken from `config`, so the two cannot disagree */
    coverage: &mut [u8],
    config: &mut GlyphDrawConfig,
) -> bool {
    if ch.is_whitespace() {
        return false;
    }
    let cell = crate::render::text::Cell::new(config.w, config.h);
    if cell.is_empty() || coverage.len() < cell.area() {
        return false;
    }
    // The face reports *what* it produced, and the two cases blend differently:
    //
    // * coverage (1-bit or a vector ramp) is a per-pixel **alpha** for the caller's text colour,
    //   which is the blend this function has always done;
    // * a colour glyph carries its own colour, so the text colour must **not** be applied — it
    //   replaces the destination instead of tinting it.
    //
    // A colour face needs `cell.area() * 4` bytes, so a caller that reserved one byte per pixel is
    // told `None` rather than having its buffer overrun.
    let Some(painted) = crate::render::text::paint_active(ch, cell, coverage) else {
        return false;
    };
    if painted.is_color() {
        // Colour ink needs a four-byte-per-pixel buffer, which this path does not provide — see
        // `blend_color_glyph`, which is the caller that reserved one. Reporting "nothing drawn" is
        // the honest answer: the alternative is to read four-byte pixels as coverage and paint noise.
        return false;
    }
    let (width, height) = (cell.width as i32, cell.height as i32);
    let mut any = false;
    for py in 0..height {
        let cy = y + py;
        if cy < 0 || cy >= config.canvas_height as i32 {
            continue;
        }
        for px in 0..width {
            let value = coverage[(py * width + px) as usize];
            if value == 0 {
                continue;
            }
            let cx = x + px;
            if cx < 0 || cx >= config.canvas_width as i32 {
                continue;
            }
            if pixel_visible(config.clip, cx, cy) {
                blend_pixel(
                    config.canvas,
                    config.canvas_width,
                    cx as u32,
                    cy as u32,
                    config.color,
                    value as f32 / 255.0,
                );
                any = true;
            }
        }
    }
    any
}

/// Blend one glyph's **colour** ink into a canvas.
///
/// # Why this is a separate function from [`blend_painted_glyph`]
///
/// The two differ in what the face's bytes *mean*, and there is no way to tell from the bytes
/// alone. Coverage ink is one byte per pixel and is an **alpha** for the caller's text colour; a
/// colour glyph is four bytes per pixel and already carries its own colour, so the text colour must
/// not be applied at all. Folding both into one function would mean either a branch on a flag
/// passed alongside the buffer (which the caller can get out of step with what it allocated) or
/// reading the fourth byte of every coverage glyph as alpha (which paints every antialiased glyph
/// as garbage).
///
/// # Why this is gated on `fonts-emoji-color`
///
/// Without that feature no face in the crate can ever return [`InkKind::Color`], so a caller of
/// this function would be drawing nothing on every call. Gating it removes the function — and its
/// call site in the text path — rather than leaving dead code that looks like it works.
///
/// # The buffer is the caller's proof
///
/// `pixels` must hold at least `cell.area() * 4` bytes. `paint_active` reports `None` when the
/// stack's only source for `ch` is a colour face and the buffer is too small, so a caller holding a
/// 1-bit scratch gets `false` rather than a partial colour glyph. That is the same contract
/// [`blend_painted_glyph`] states, expressed once at the point the buffer is chosen.
///
/// Returns whether any ink was blended.
#[cfg(feature = "fonts-emoji-color")]
pub(crate) fn blend_color_glyph(
    ch: char,
    x: i32,
    y: i32,
    /* RGBA scratch of at least `cell.area() * 4` bytes, reused across glyphs */
    pixels: &mut [u8],
    config: &mut GlyphDrawConfig,
) -> bool {
    if ch.is_whitespace() {
        return false;
    }
    let cell = crate::render::text::Cell::new(config.w, config.h);
    if cell.is_empty() || pixels.len() < cell.area() * 4 {
        return false;
    }
    let Some(painted) = crate::render::text::paint_active(ch, cell, pixels) else {
        return false;
    };
    // A face that answered with coverage here means the stack resolved `ch` through a 1-bit or
    // vector source — there is no colour to blend, and reading the buffer as RGBA would be wrong.
    // The caller that wants those uses `blend_painted_glyph`, so refusing is the correct answer.
    if !painted.is_color() {
        return false;
    }
    blend_rgba_over_canvas(pixels, cell, x, y, config)
}

/// Composites a `cell`-sized straight-RGBA buffer into a canvas at `(x, y)`, honouring the clip.
///
/// Split out from [`blend_color_glyph`] so the pixel loop can be tested with a hand-built buffer,
/// without a colour font being present in the build.
#[cfg(feature = "fonts-emoji-color")]
fn blend_rgba_over_canvas(
    pixels: &[u8],
    cell: crate::render::text::Cell,
    x: i32,
    y: i32,
    config: &mut GlyphDrawConfig,
) -> bool {
    let (width, height) = (cell.width as i32, cell.height as i32);
    let mut any = false;
    for py in 0..height {
        let cy = y + py;
        if cy < 0 || cy >= config.canvas_height as i32 {
            continue;
        }
        for px in 0..width {
            let si = ((py * width + px) * 4) as usize;
            let Some(src) = pixels.get(si..si + 4) else {
                continue;
            };
            // A fully transparent source pixel contributes nothing, and skipping it is what keeps a
            // glyph's rectangular bounding box from darkening the canvas around it.
            if src[3] == 0 {
                continue;
            }
            let cx = x + px;
            if cx < 0 || cx >= config.canvas_width as i32 {
                continue;
            }
            if !pixel_visible(config.clip, cx, cy) {
                continue;
            }
            blend_pixel(
                config.canvas,
                config.canvas_width,
                cx as u32,
                cy as u32,
                Color::rgba(src[0], src[1], src[2], src[3]),
                1.0,
            );
            any = true;
        }
    }
    any
}

pub(crate) fn pixel_bytes_len(size: Size) -> usize {
    size.width.saturating_mul(size.height).saturating_mul(4) as usize
}

/// BLUE23 §0A.2 — the text-coverage boundary, asserted where it is decided.
///
/// The crate-level docs claim "the default build draws Latin/ASCII only" and explain
/// that anything else becomes the fallback glyph. A claim about what is *not* supported
/// decays silently — the day a font is added the docs go stale and no test notices. This
/// pins the other direction: the tofu path must be what a CJK character takes, on a
/// default build.
///
/// Moved to the end of the file so no production item follows a test module (the crate's
/// own lint posture: tests last).
/// Writes `color` into `pixels` as consecutive RGBA quads.
///
/// `pixels` must be a row-major RGBA buffer. Trailing bytes that do not form a
/// complete quad are filled with the first bytes of `color[r,g,b,a]` — i.e. a
/// non-multiple-of-four length is tolerated rather than rejected.
pub fn fill_pixels(pixels: &mut [u8], color: Color) {
    let chunk_size = 4;
    let color_arr = [color.r, color.g, color.b, color.a];
    for chunk in pixels.chunks_mut(chunk_size) {
        if chunk.len() == chunk_size {
            chunk.copy_from_slice(&color_arr);
        } else {
            chunk.copy_from_slice(&color_arr[..chunk.len()]);
        }
    }
}
pub(crate) fn set_pixel(frame: &mut [u8], width: u32, x: u32, y: u32, color: Color) {
    let idx = ((y * width + x) * 4) as usize;
    if idx + 3 >= frame.len() {
        return;
    }
    frame[idx] = color.r;
    frame[idx + 1] = color.g;
    frame[idx + 2] = color.b;
    frame[idx + 3] = color.a;
}

/// Returns whether a logical pixel lies inside the active render clip.
pub(crate) fn pixel_visible(clip: Option<(i32, i32, u32, u32)>, x: i32, y: i32) -> bool {
    let Some((clip_x, clip_y, clip_width, clip_height)) = clip else {
        return true;
    };
    x >= clip_x
        && y >= clip_y
        && x < clip_x.saturating_add(clip_width as i32)
        && y < clip_y.saturating_add(clip_height as i32)
}
/// Alpha-blends `color` over the pixel at `(x, y)` of a row-major RGBA frame
/// buffer, using `coverage` as an extra multiplier on the source alpha.
///
/// `frame` must be laid out with `width` pixels per row in RGBA order. The call
/// is a no-op when `coverage` is non-positive or when `(x, y)` falls outside
/// `frame`. `coverage` is clamped to `[0, 1]`.
pub fn blend_pixel(frame: &mut [u8], width: u32, x: u32, y: u32, color: Color, coverage: f32) {
    if coverage <= 0.0 {
        return;
    }
    let idx = ((y * width + x) * 4) as usize;
    if idx + 3 >= frame.len() {
        return;
    }
    let src_a = (color.a as f32 / 255.0) * coverage.clamp(0.0, 1.0);
    if src_a <= 0.0 {
        frame[idx] = 0;
        frame[idx + 1] = 0;
        frame[idx + 2] = 0;
        frame[idx + 3] = 0;
        return;
    }
    let dst = &mut frame[idx..idx + 4];
    let src = [color.r, color.g, color.b, color.a];
    let src_f: [f32; 4] = [
        src[0] as f32 / 255.0,
        src[1] as f32 / 255.0,
        src[2] as f32 / 255.0,
        src[3] as f32 / 255.0,
    ];
    let dst_f: [f32; 4] = [
        dst[0] as f32 / 255.0,
        dst[1] as f32 / 255.0,
        dst[2] as f32 / 255.0,
        dst[3] as f32 / 255.0,
    ];
    let out_a = src_a + dst_f[3] * (1.0 - src_a);
    if out_a <= f32::EPSILON {
        dst.copy_from_slice(&[0, 0, 0, 0]);
        return;
    }
    let out_r = (src_f[0] * src_a + dst_f[0] * dst_f[3] * (1.0 - src_a)) / out_a;
    let out_g = (src_f[1] * src_a + dst_f[1] * dst_f[3] * (1.0 - src_a)) / out_a;
    let out_b = (src_f[2] * src_a + dst_f[2] * dst_f[3] * (1.0 - src_a)) / out_a;
    dst[0] = (out_r * 255.0).round().clamp(0.0, 255.0) as u8;
    dst[1] = (out_g * 255.0).round().clamp(0.0, 255.0) as u8;
    dst[2] = (out_b * 255.0).round().clamp(0.0, 255.0) as u8;
    dst[3] = (out_a * 255.0).round().clamp(0.0, 255.0) as u8;
}
pub(crate) fn circle_fill_coverage(distance: f32, radius: f32) -> f32 {
    if radius <= 0.0 {
        return 0.0;
    }
    (radius + 1.0 - distance).clamp(0.0, 1.0)
}
pub(crate) fn circle_fill_coverage_grid(
    px: i32,
    py: i32,
    center: Point,
    radius: f32,
    grid: u8,
) -> f32 {
    let sample_count = grid.clamp(1, 8) as u32;
    let total = sample_count * sample_count;
    let mut coverage_sum = 0.0f32;
    for sy in 0..sample_count {
        for sx in 0..sample_count {
            let sample_x = px as f32 + (sx as f32 + 0.5) / sample_count as f32;
            let sample_y = py as f32 + (sy as f32 + 0.5) / sample_count as f32;
            let dx = sample_x - center.x as f32;
            let dy = sample_y - center.y as f32;
            let distance = (dx * dx + dy * dy).sqrt();
            coverage_sum += circle_fill_coverage(distance, radius);
        }
    }
    (coverage_sum / total as f32).clamp(0.0, 1.0)
}
pub(crate) fn circle_stroke_coverage_grid(
    px: i32,
    py: i32,
    center: Point,
    radius: f32,
    stroke_width: f32,
    grid: u8,
) -> f32 {
    let sample_count = grid.clamp(1, 8) as u32;
    let total = sample_count * sample_count;
    let mut coverage_sum = 0.0f32;
    // radius is the outer radius, stroke_width is the width of the ring
    let outer_radius = radius;
    let inner_radius = (radius - stroke_width).max(0.0);
    for sy in 0..sample_count {
        for sx in 0..sample_count {
            let sample_x = px as f32 + (sx as f32 + 0.5) / sample_count as f32;
            let sample_y = py as f32 + (sy as f32 + 0.5) / sample_count as f32;
            let dx = sample_x - center.x as f32;
            let dy = sample_y - center.y as f32;
            let distance = (dx * dx + dy * dy).sqrt();
            // Ring coverage: outside inner radius and inside outer radius
            let inner_coverage = circle_fill_coverage(distance, inner_radius);
            let outer_coverage = circle_fill_coverage(distance, outer_radius);
            // Ring is outer circle minus inner circle
            coverage_sum += (outer_coverage - inner_coverage).max(0.0);
        }
    }
    (coverage_sum / total as f32).clamp(0.0, 1.0)
}
pub(crate) fn point_to_segment_distance(
    px: f32,
    py: f32,
    ax: f32,
    ay: f32,
    bx: f32,
    by: f32,
) -> f32 {
    let abx = bx - ax;
    let aby = by - ay;
    let apx = px - ax;
    let apy = py - ay;
    let ab_len2 = abx * abx + aby * aby;
    if ab_len2 <= f32::EPSILON {
        let dx = px - ax;
        let dy = py - ay;
        return (dx * dx + dy * dy).sqrt();
    }
    let t = ((apx * abx + apy * aby) / ab_len2).clamp(0.0, 1.0);
    let cx = ax + t * abx;
    let cy = ay + t * aby;
    let dx = px - cx;
    let dy = py - cy;
    (dx * dx + dy * dy).sqrt()
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn line_stroke_coverage_grid(
    px: i32,
    py: i32,
    ax: f32,
    ay: f32,
    bx: f32,
    by: f32,
    half_width: f32,
    grid: u8,
) -> f32 {
    let sample_count = grid.clamp(1, 8) as u32;
    let total = sample_count * sample_count;
    let mut coverage_sum = 0.0f32;
    for sy in 0..sample_count {
        for sx in 0..sample_count {
            let sample_x = px as f32 + (sx as f32 + 0.5) / sample_count as f32;
            let sample_y = py as f32 + (sy as f32 + 0.5) / sample_count as f32;
            let distance = point_to_segment_distance(sample_x, sample_y, ax, ay, bx, by);
            coverage_sum += (half_width + 0.5 - distance).clamp(0.0, 1.0);
        }
    }
    (coverage_sum / total as f32).clamp(0.0, 1.0)
}
pub(crate) fn rounded_rect_effective_radius(rect: Rect, radius: u32) -> u32 {
    radius.min(rect.width / 2).min(rect.height / 2)
}
pub(crate) fn inset_rect(rect: Rect, inset: i32) -> Rect {
    let x = rect.x + inset;
    let y = rect.y + inset;
    let width = (rect.width as i32 - inset * 2).max(0) as u32;
    let height = (rect.height as i32 - inset * 2).max(0) as u32;
    Rect { x, y, width, height }
}
pub(crate) fn point_in_rounded_rect_f32(px: f32, py: f32, rect: Rect, radius: u32) -> bool {
    if rect.width == 0 || rect.height == 0 {
        return false;
    }
    let left = rect.x as f32;
    let top = rect.y as f32;
    let right = rect.x as f32 + rect.width as f32;
    let bottom = rect.y as f32 + rect.height as f32;
    if px < left || px >= right || py < top || py >= bottom {
        return false;
    }
    let r = rounded_rect_effective_radius(rect, radius) as f32;
    if r <= 0.0 {
        return true;
    }
    if (px >= left + r && px < right - r) || (py >= top + r && py < bottom - r) {
        return true;
    }
    let cx = if px < left + r {
        left + r
    } else if px >= right - r {
        right - r
    } else {
        px
    };
    let cy = if py < top + r {
        top + r
    } else if py >= bottom - r {
        bottom - r
    } else {
        py
    };
    let dx = px - cx;
    let dy = py - cy;
    dx * dx + dy * dy <= r * r
}
pub(crate) fn rounded_rect_coverage(px: i32, py: i32, rect: Rect, radius: u32) -> f32 {
    rounded_rect_coverage_grid(px, py, rect, radius, 2)
}
pub(crate) fn rounded_rect_coverage_grid(
    px: i32,
    py: i32,
    rect: Rect,
    radius: u32,
    grid: u8,
) -> f32 {
    let sample_count = grid.clamp(1, 8) as u32;
    let mut covered = 0u32;
    let total = sample_count * sample_count;
    for sy in 0..sample_count {
        for sx in 0..sample_count {
            let sample_x = (sx as f32 + 0.5) / sample_count as f32;
            let sample_y = (sy as f32 + 0.5) / sample_count as f32;
            if point_in_rounded_rect_f32(px as f32 + sample_x, py as f32 + sample_y, rect, radius) {
                covered += 1;
            }
        }
    }
    covered as f32 / total as f32
}

/// BLUE23 §0A.2 — the text-coverage boundary, asserted where it is decided.
///
/// The crate-level docs claim "the default build draws Latin/ASCII only" and explain that
/// anything else becomes the fallback glyph. A claim about what is *not* supported decays
/// silently — the day a font is added the docs go stale and no test notices. So the boundary
/// is pinned from both sides: the tofu path is what a non-Latin character takes on a default
/// build, and enabling a data feature moves that boundary by exactly the face it adds.
#[cfg(test)]
mod text_coverage_tests {
    use crate::render::text;

    #[test]
    fn ascii_resolves_to_a_real_glyph() {
        assert_eq!(text::source_for('A'), Some("font8x8"), "'A' is inside the base face");
        assert_eq!(text::source_for('5'), Some("font8x8"));
    }

    /// The scripts the crate docs name as unsupported: CJK, Cyrillic, Arabic, emoji. With no
    /// font data enabled, every one of them must take the fallback glyph.
    #[cfg(not(feature = "fonts-cjk-bitmap"))]
    #[test]
    fn non_latin_resolves_to_the_fallback_glyph_by_default() {
        for ch in ['\u{4e2d}', '\u{0416}', '\u{0627}', '\u{1f600}'] {
            assert_eq!(
                text::source_for(ch),
                None,
                "U+{:04X} is outside the base face and must take the fallback glyph",
                ch as u32
            );
        }
    }

    /// With the CJK data enabled, the boundary moves to exactly where the feature says: Han is
    /// covered by the added face, and the scripts the feature does *not* carry still fall back.
    /// This is the half of the claim that would otherwise rot unnoticed.
    #[cfg(feature = "fonts-cjk-bitmap")]
    #[test]
    fn enabling_the_cjk_data_moves_the_boundary_by_exactly_one_face() {
        assert_eq!(text::source_for('\u{4e2d}'), Some("cjk-bitmap"));
        assert_eq!(text::source_for('\u{0416}'), None, "Cyrillic is not in the CJK subset");
        assert_eq!(text::source_for('\u{0627}'), None, "Arabic is not in the CJK subset");
        assert_eq!(text::source_for('\u{1f600}'), None, "emoji is not in the CJK subset");
    }
}