fcft 0.1.0

Bindings to fcft: library for font loading and glyph rasterization
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
//! Bindings for [fcft](https://codeberg.org/dnkl/fcft), a font library font loading,
//! shaping and glyph rasterization using FontConfig, FreeType, Harfbuzz and pixman.
//!
//! # Usage
//!
//! ```no_run
//! use fcft::{Canvas, Color, Font, Subpixel};
//!
//! let font = Font::new(&["Open Sans:pixelsize=28"], None).unwrap();
//! let run = font.shape("Hello world!", Subpixel::None);
//! let width = run.width();
//!
//! let (w, h, stride) = (400usize, font.height() as usize, 400usize * 4);
//! let mut buf = vec![0u8; stride * h];
//! let mut canvas = Canvas::from_xrgb8888(&mut buf, w as u32, h as u32, stride as u32);
//! canvas.draw(&run, 0, font.ascent(), Color::from_argb8888(0xff000000));
//! ```
//!
//! # Locale
//!
//! fcft uses `wcwidth` internally. Its behaviour varies depending on `LC_CTYPE`, which SHOULD be a
//! UTF-8 locale. Applications SHOULD call `setlocale(LC_CTYPE, "")` with a UTF-8 locale.
// XXX: I think this isn't necessary on musl since its default is UTF-8?

#![deny(clippy::pedantic)]
#![allow(clippy::doc_markdown)] // Too many false positives.
#![allow(clippy::missing_errors_doc)] // TODO?

use std::ffi::{CStr, CString, c_char, c_long};
use std::fmt;
use std::marker::PhantomData;
use std::sync::Once;

pub use fcft_sys as ffi;

static INIT: Once = Once::new();

/// Colouring of fcft's own log output.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogColorize {
    Never,
    Always,
    Auto,
}

/// Verbosity of fcft's own log output (on stderr).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogClass {
    None,
    Error,
    Warning,
    Info,
    Debug,
}

/// Initialise fcft with explicit logging options.
///
/// If this function is not called, fcft self-initialises with with warning-level logging.
#[allow(clippy::missing_panics_doc)] // Should never really panic.
pub fn init(colourize: LogColorize, syslog: bool, log_class: LogClass) {
    let colourize = match colourize {
        LogColorize::Never => ffi::fcft_log_colorize_FCFT_LOG_COLORIZE_NEVER,
        LogColorize::Always => ffi::fcft_log_colorize_FCFT_LOG_COLORIZE_ALWAYS,
        LogColorize::Auto => ffi::fcft_log_colorize_FCFT_LOG_COLORIZE_AUTO,
    };
    let log_class = match log_class {
        LogClass::None => ffi::fcft_log_class_FCFT_LOG_CLASS_NONE,
        LogClass::Error => ffi::fcft_log_class_FCFT_LOG_CLASS_ERROR,
        LogClass::Warning => ffi::fcft_log_class_FCFT_LOG_CLASS_WARNING,
        LogClass::Info => ffi::fcft_log_class_FCFT_LOG_CLASS_INFO,
        LogClass::Debug => ffi::fcft_log_class_FCFT_LOG_CLASS_DEBUG,
    };
    INIT.call_once(|| {
        let ok = unsafe { ffi::fcft_init(colourize, syslog, log_class) };
        assert!(ok, "fcft_init failed");
    });
}

fn ensure_init() {
    init(LogColorize::Never, false, LogClass::Warning);
}

/// Optional fcft features; presence depends on how fcft was compiled.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Capabilities {
    bits: ffi::fcft_capabilities,
}

impl Capabilities {
    /// [`fcft_rasterize_grapheme_utf32`](ffi::fcft_rasterize_grapheme_utf32)
    /// is available (fcft built with HarfBuzz).
    #[must_use]
    pub fn grapheme_shaping(self) -> bool {
        self.bits & ffi::fcft_capabilities_FCFT_CAPABILITY_GRAPHEME_SHAPING != 0
    }

    /// Text-run shaping is available (fcft built with HarfBuzz + utf8proc).
    /// [`Font::shape`] uses it when present, and falls back to per-character
    /// rasterisation otherwise.
    #[must_use]
    pub fn text_run_shaping(self) -> bool {
        self.bits & ffi::fcft_capabilities_FCFT_CAPABILITY_TEXT_RUN_SHAPING != 0
    }

    /// SVG glyphs (e.g: for some colour emoji fonts) can be rasterised.
    #[must_use]
    pub fn svg(self) -> bool {
        self.bits & ffi::fcft_capabilities_FCFT_CAPABILITY_SVG != 0
    }
}

/// Which optional features this fcft build provides.
#[must_use]
pub fn capabilities() -> Capabilities {
    Capabilities {
        bits: unsafe { ffi::fcft_capabilities() },
    }
}

/// Subpixel rendering mode, applied only when the font has antialiasing enabled.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Subpixel {
    /// Use subpixel order configured in FontConfig.
    #[default]
    Default,
    /// Grayscale antialiasing.
    None,
    HorizontalRgb,
    HorizontalBgr,
    VerticalRgb,
    VerticalBgr,
}

impl Subpixel {
    fn to_ffi(self) -> ffi::fcft_subpixel {
        match self {
            Subpixel::Default => ffi::fcft_subpixel_FCFT_SUBPIXEL_DEFAULT,
            Subpixel::None => ffi::fcft_subpixel_FCFT_SUBPIXEL_NONE,
            Subpixel::HorizontalRgb => ffi::fcft_subpixel_FCFT_SUBPIXEL_HORIZONTAL_RGB,
            Subpixel::HorizontalBgr => ffi::fcft_subpixel_FCFT_SUBPIXEL_HORIZONTAL_BGR,
            Subpixel::VerticalRgb => ffi::fcft_subpixel_FCFT_SUBPIXEL_VERTICAL_RGB,
            Subpixel::VerticalBgr => ffi::fcft_subpixel_FCFT_SUBPIXEL_VERTICAL_BGR,
        }
    }
}

/// Font instantiation failed. fcft reports the reason only through its own logging.
/// See [`init`] to raise the log level.
#[derive(Debug)]
pub struct Error(());

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("failed to instantiate font")
    }
}

impl std::error::Error for Error {}

/// Position and thickness of an underline or strikeout, relative to the baseline.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Decoration {
    pub position: i32,
    pub thickness: i32,
}

/// Font instance at a fixed size, with per-codepoint FontConfig fallback and internal glyph caching.
///
/// Changing the font size at runtime is not possible; create a new instance instead.
pub struct Font {
    ptr: *mut ffi::fcft_font,
}

// fcft explicitly supports threaded use: rasterisation takes a global
// FreeType lock plus a per-font mutex, and the glyph caches are rwlocked.
// That would justify Sync too, but nothing here needs it yet, so only Send
// is promised.
unsafe impl Send for Font {}

impl Font {
    /// Create new instance from a FontConfig patterns.
    ///
    /// E.g.: `"Open Sans:pixelsize=24"`. See FontConfig's documentation for details.
    ///
    /// Note that FontConfig matching always finds *some* font: a nonsense
    /// family name yields a fallback, not an error.
    pub fn new(names: &[&str], attributes: Option<&str>) -> Result<Font, Error> {
        ensure_init();
        if names.is_empty() {
            return Err(Error(()));
        }
        let names: Vec<CString> = names
            .iter()
            .map(|n| CString::new(*n).map_err(|_| Error(())))
            .collect::<Result<_, _>>()?;
        let mut ptrs: Vec<*const c_char> = names.iter().map(|n| n.as_ptr()).collect();
        let attributes = match attributes {
            Some(a) => Some(CString::new(a).map_err(|_| Error(()))?),
            None => None,
        };
        let ptr = unsafe {
            ffi::fcft_from_name(
                ptrs.len(),
                ptrs.as_mut_ptr(),
                attributes.as_ref().map_or(std::ptr::null(), |a| a.as_ptr()),
            )
        };
        if ptr.is_null() {
            Err(Error(()))
        } else {
            Ok(Font { ptr })
        }
    }

    fn raw(&self) -> &ffi::fcft_font {
        unsafe { &*self.ptr }
    }

    /// Name of the primary font, if available.
    #[must_use]
    pub fn name(&self) -> Option<&str> {
        let name = self.raw().name;
        if name.is_null() {
            return None;
        }
        unsafe { CStr::from_ptr(name) }.to_str().ok()
    }

    /// Line height in pixels.
    #[must_use]
    pub fn height(&self) -> i32 {
        self.raw().height
    }

    /// Extent above the baseline.
    ///
    /// Distance from the baseline to the highest point of the tallest character.
    #[must_use]
    pub fn ascent(&self) -> i32 {
        self.raw().ascent
    }

    /// Extent below the baseline.
    #[must_use]
    pub fn descent(&self) -> i32 {
        self.raw().descent
    }

    /// Advance of the font's widest glyph.
    #[must_use]
    pub fn max_advance(&self) -> (i32, i32) {
        let a = self.raw().max_advance;
        (a.x, a.y)
    }

    /// Returns details for rendering an underline.
    #[must_use]
    pub fn underline(&self) -> Decoration {
        let u = self.raw().underline;
        Decoration {
            position: u.position,
            thickness: u.thickness,
        }
    }

    /// Returns details for rendering a strike-through.
    #[must_use]
    pub fn strikeout(&self) -> Decoration {
        let s = self.raw().strikeout;
        Decoration {
            position: s.position,
            thickness: s.thickness,
        }
    }

    #[must_use]
    pub fn antialias(&self) -> bool {
        self.raw().antialias
    }

    /// Subpixel mode used when rasterising with [`Subpixel::Default`].
    #[must_use]
    pub fn subpixel(&self) -> Subpixel {
        match self.raw().subpixel {
            ffi::fcft_subpixel_FCFT_SUBPIXEL_NONE => Subpixel::None,
            ffi::fcft_subpixel_FCFT_SUBPIXEL_HORIZONTAL_RGB => Subpixel::HorizontalRgb,
            ffi::fcft_subpixel_FCFT_SUBPIXEL_HORIZONTAL_BGR => Subpixel::HorizontalBgr,
            ffi::fcft_subpixel_FCFT_SUBPIXEL_VERTICAL_RGB => Subpixel::VerticalRgb,
            ffi::fcft_subpixel_FCFT_SUBPIXEL_VERTICAL_BGR => Subpixel::VerticalBgr,
            _ => Subpixel::Default,
        }
    }

    /// Rasterise a single codepoint.
    /// The glyph is cached inside the font and borrowed from it.
    /// Returns `None` if the codepoint has no matching glyph.
    #[must_use]
    pub fn glyph(&self, c: char, subpixel: Subpixel) -> Option<Glyph<'_>> {
        let g =
            unsafe { ffi::fcft_rasterize_char_utf32(self.ptr, u32::from(c), subpixel.to_ffi()) };
        if g.is_null() {
            None
        } else {
            Some(Glyph {
                raw: unsafe { &*g },
            })
        }
    }

    /// Kerning between two glyphs, in pixels.
    /// Only relevant for per-character rendering:  shaping already applies kerning.
    #[must_use]
    pub fn kerning(&self, left: char, right: char) -> Option<(i64, i64)> {
        let (mut x, mut y): (c_long, c_long) = (0, 0);
        let ok = unsafe {
            ffi::fcft_kerning(
                self.ptr,
                u32::from(left),
                u32::from(right),
                &raw mut x,
                &raw mut y,
            )
        };
        #[allow(clippy::useless_conversion)] // Necessary on 32-bit targets, where c_long is i32.
        ok.then_some((x.into(), y.into()))
    }

    /// Shape `text` into a run of positioned glyphs.
    ///
    /// Uses [`Font::shape_run`] if available, or falls back to [`Font::shape_chars`].
    #[must_use]
    pub fn shape(&self, text: &str, subpixel: Subpixel) -> TextRun<'_> {
        if capabilities().text_run_shaping()
            && let Some(run) = self.shape_run(text, subpixel)
        {
            return run;
        }
        self.shape_chars(text, subpixel)
    }

    /// Shape `text` into a run of positioned glyphs.
    ///
    /// Uses fcft's text-run shaping (HarfBuzz) when available, returns `None` otherwise.
    #[must_use]
    // XXX: This can never return `TextRun::Chars`.
    pub fn shape_run(&self, text: &str, subpixel: Subpixel) -> Option<TextRun<'_>> {
        let cps: Vec<u32> = text.chars().map(u32::from).collect();
        if cps.is_empty() {
            return None;
        }
        let run = unsafe {
            ffi::fcft_rasterize_text_run_utf32(self.ptr, cps.len(), cps.as_ptr(), subpixel.to_ffi())
        };
        if run.is_null() {
            return None;
        }
        Some(TextRun {
            inner: RunInner::Shaped(run),
            _font: PhantomData,
        })
    }

    /// Shape `text` into a run of positioned glyphs.
    ///
    /// Does not use text shaping, and yields suboptimal results.
    /// Should only be used if [`Font::shape`] is unavailable.
    #[must_use]
    pub fn shape_chars(&self, text: &str, subpixel: Subpixel) -> TextRun<'_> {
        let mut glyphs = Vec::new();
        let mut chars = text.chars().peekable();
        while let Some(c) = chars.next() {
            let Some(glyph) = self.glyph(c, subpixel) else {
                continue;
            };
            let mut advance = glyph.advance();
            // Kerning offsets is a handful of pixels. Cannot overflow i32.
            #[allow(clippy::cast_possible_truncation)]
            if let Some(&next) = chars.peek()
                && let Some((kx, ky)) = self.kerning(c, next)
            {
                advance.0 += kx as i32;
                advance.1 += ky as i32;
            }
            glyphs.push(CharGlyph {
                glyph: glyph.raw,
                advance,
            });
        }
        TextRun {
            inner: RunInner::Chars(glyphs),
            _font: PhantomData,
        }
    }

    /// Shape `text` into a run of positioned glyphs, truncating to fix an ellipsis.
    #[must_use]
    pub fn shape_truncated(&self, text: &str, subpixel: Subpixel, max_width: i32) -> TextRun<'_> {
        let full = self.shape(text, subpixel);
        if full.width() <= max_width {
            return full;
        }

        let chars: Vec<char> = text.chars().collect();
        let fits = |n: usize| {
            let mut s: String = chars[..n].iter().collect();
            s.push('…');
            let run = self.shape(&s, subpixel);
            (run.width() <= max_width).then_some(run)
        };

        // Largest prefix (in chars) that fits with the ellipsis.
        let Some(mut best) = fits(0) else {
            // Not even the ellipsis alone fits, wtf?
            return self.shape_chars("", subpixel);
        };
        // Binary search for correct length.
        // TODO: Maybe there's some smarter algorithm for this?
        let (mut lo, mut hi) = (0, chars.len());
        while hi - lo > 1 {
            let mid = usize::midpoint(lo, hi);
            match fits(mid) {
                Some(run) => {
                    best = run;
                    lo = mid;
                }
                None => hi = mid,
            }
        }
        best
    }
}

impl Drop for Font {
    fn drop(&mut self) {
        // Also frees every cached glyph handed out from this font.
        unsafe { ffi::fcft_destroy(self.ptr) };
    }
}

/// Rasterised glyph, borrowed from the [`Font`] or [`TextRun`] that produced it.
#[derive(Clone, Copy)]
pub struct Glyph<'a> {
    raw: &'a ffi::fcft_glyph,
}

/// Pixel format of a glyph image, determining how to composite it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GlyphFormat {
    /// Monochrome bitmask (font with antialiasing disabled). Use as a mask.
    A1,
    /// Grayscale-antialiasing coverage mask. Use as a mask.
    A8,
    /// Subpixel-LCD mask (component alpha is already set). Use as a mask.
    X8R8G8B8,
    /// Pre-rendered colour image (colour emoji). Use as a source.
    A8R8G8B8,
    Other(u32),
}

impl Glyph<'_> {
    /// Codepoint from which this glyph was rasterised.
    #[must_use]
    pub fn codepoint(&self) -> u32 {
        self.raw.cp
    }

    // FIXME: unclear docs.
    /// Horizontal bearing: with the pen at `(pen_x, baseline_y)`, the
    /// glyph's left edge lands at `pen_x + x()`.
    #[must_use]
    pub fn x(&self) -> i32 {
        self.raw.x
    }

    // FIXME: unclear docs.
    /// Vertical bearing: with the pen at `(pen_x, baseline_y)`, the glyph's
    /// top edge lands at `baseline_y - y()`.
    #[must_use]
    pub fn y(&self) -> i32 {
        self.raw.y
    }

    /// Width of the glyph image in pixels.
    #[must_use]
    pub fn width(&self) -> i32 {
        self.raw.width
    }

    /// Height of the glyph image in pixels.
    #[must_use]
    pub fn height(&self) -> i32 {
        self.raw.height
    }

    /// Pen advance after this glyph.
    #[must_use]
    pub fn advance(&self) -> (i32, i32) {
        (self.raw.advance.x, self.raw.advance.y)
    }

    /// Whether the image is a pre-rendered colour image.
    ///
    /// Indicates whether to composite as a source rather than a mask to fill with a colour.
    #[must_use]
    pub fn is_color_glyph(&self) -> bool {
        self.raw.is_color_glyph
    }

    /// Pixel format of the glyph image.
    #[must_use]
    pub fn format(&self) -> GlyphFormat {
        match unsafe { ffi::pixman_image_get_format(self.raw.pix) } {
            ffi::pixman_format_code_t_PIXMAN_a1 => GlyphFormat::A1,
            ffi::pixman_format_code_t_PIXMAN_a8 => GlyphFormat::A8,
            ffi::pixman_format_code_t_PIXMAN_x8r8g8b8 => GlyphFormat::X8R8G8B8,
            ffi::pixman_format_code_t_PIXMAN_a8r8g8b8 => GlyphFormat::A8R8G8B8,
            other => GlyphFormat::Other(other),
        }
    }

    /// Raw pixman image.
    ///
    /// Owned by fcft; do not free it!
    #[must_use]
    pub fn pixman_image(&mut self) -> *mut ffi::pixman_image_t {
        self.raw.pix
    }

    /// Raw glyph, for use with `fcft-sys`.
    #[must_use]
    pub fn as_raw(&self) -> &ffi::fcft_glyph {
        self.raw
    }
}

/// Glyph within a [`TextRun`], paired with its effective pen advance.
pub struct ShapedGlyph<'a> {
    pub glyph: Glyph<'a>,
    /// Pen advance after this glyph.
    pub advance: (i32, i32),
}

enum RunInner {
    /// A run shaped by fcft; owned, freed on drop.
    Shaped(*mut ffi::fcft_text_run),
    /// Per-character fallback.
    Chars(Vec<CharGlyph>),
}

struct CharGlyph {
    glyph: *const ffi::fcft_glyph,
    advance: (i32, i32),
}

/// A shaped, rasterised line of text.
///
/// Produced by [`Font::shape`]; iterate glyphs with [`TextRun::glyphs`],
/// measure with [`TextRun::width`], or composite with [`Canvas::draw`].
pub struct TextRun<'f> {
    inner: RunInner,
    // fcft-shaped runs may technically outlive their font, but the
    // per-character fallback borrows glyphs from the font's cache.
    // Tie both to the font to keep both paths interchangeable.
    _font: PhantomData<&'f Font>,
}

impl TextRun<'_> {
    /// Number of glyphs in the run.
    #[must_use]
    pub fn len(&self) -> usize {
        match &self.inner {
            RunInner::Shaped(run) => unsafe { &**run }.count,
            RunInner::Chars(glyphs) => glyphs.len(),
        }
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    pub fn glyphs(&self) -> impl Iterator<Item = ShapedGlyph<'_>> {
        let (run, chars) = match &self.inner {
            RunInner::Shaped(run) => (Some(unsafe { &**run }), [].iter()),
            RunInner::Chars(glyphs) => (None, glyphs.iter()),
        };
        let shaped = run.into_iter().flat_map(|run| {
            unsafe { std::slice::from_raw_parts(run.glyphs, run.count) }
                .iter()
                .map(|&g| {
                    let glyph = Glyph {
                        raw: unsafe { &*g },
                    };
                    ShapedGlyph {
                        advance: glyph.advance(),
                        glyph,
                    }
                })
        });
        let chars = chars.map(|cg| ShapedGlyph {
            glyph: Glyph {
                raw: unsafe { &*cg.glyph },
            },
            advance: cg.advance,
        });
        shaped.chain(chars)
    }

    /// Total horizontal pen advance.
    #[must_use]
    pub fn width(&self) -> i32 {
        self.glyphs().map(|g| g.advance.0).sum()
    }
}

impl Drop for TextRun<'_> {
    fn drop(&mut self) {
        if let RunInner::Shaped(run) = self.inner {
            unsafe { ffi::fcft_text_run_destroy(run) };
        }
    }
}

/// Colour without premultiplied 16-bit channels.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Color {
    pub r: u16,
    pub g: u16,
    pub b: u16,
    pub a: u16,
}

impl Color {
    /// From packed 8-bit ARGB, e.g. `0xff000000` for opaque black.
    #[must_use]
    pub const fn from_argb8888(argb: u32) -> Color {
        // 0x101 replicates the 8-bit value into both bytes (0xff → 0xffff).
        Color {
            a: ((argb >> 24) & 0xff) as u16 * 0x101,
            r: ((argb >> 16) & 0xff) as u16 * 0x101,
            g: ((argb >> 8) & 0xff) as u16 * 0x101,
            b: (argb & 0xff) as u16 * 0x101,
        }
    }

    fn to_pixman(self) -> ffi::pixman_color {
        // pixman solid-fill sources are premultiplied.
        // c * a / 0xffff never exceeds 0xffff, so the cast cannot truncate.
        #[allow(clippy::cast_possible_truncation)]
        let premul = |c: u16| ((u32::from(c) * u32::from(self.a)) / 0xffff) as u16;
        ffi::pixman_color {
            red: premul(self.r),
            green: premul(self.g),
            blue: premul(self.b),
            alpha: self.a,
        }
    }
}

/// XRGB8888 pixel buffer wrapped as a pixman image, for compositing text.
pub struct Canvas<'buf> {
    image: *mut ffi::pixman_image_t,
    _buf: PhantomData<&'buf mut [u8]>,
}

impl<'buf> Canvas<'buf> {
    /// Wrap `buf` as a an XRGB8888 image.
    ///
    /// # Panics
    ///
    /// - If the buffer is too small for `stride * height`.
    /// - If `stride` cannot hold a row.
    /// - If the buffer is not 4-byte aligned (as pixman requires).
    /// - If `width`, `height` or `stride` exceed `i32::MAX`.
    // XXX: error instead?
    pub fn from_xrgb8888(
        buf: &'buf mut [u8],
        width: u32,
        height: u32,
        stride: u32,
    ) -> Canvas<'buf> {
        assert!(stride.is_multiple_of(4), "stride must be a multiple of 4");
        assert!(stride >= width * 4, "stride too small for width");
        assert!(
            buf.len() >= stride as usize * height as usize,
            "buffer too small"
        );
        assert!(
            buf.as_ptr().addr().is_multiple_of(4),
            "buffer must be 4-byte aligned"
        );
        let image = unsafe {
            ffi::pixman_image_create_bits_no_clear(
                ffi::pixman_format_code_t_PIXMAN_x8r8g8b8,
                i32::try_from(width).expect("width should fit in i32"),
                i32::try_from(height).expect("height should fit in i32"),
                buf.as_mut_ptr().cast(),
                i32::try_from(stride).expect("stride should fit in i32"),
            )
        };
        assert!(!image.is_null(), "pixman_image_create_bits_no_clear failed");
        Canvas {
            image,
            _buf: PhantomData,
        }
    }

    /// Composite a run with the pen starting at `(pen_x, baseline_y)`.
    ///
    /// For a box starting at `top`, the baseline is `top + font.ascent()`.
    ///
    /// Mask glyphs are filled with `colour`; colour glyphs are blended as-is.
    ///
    /// Anything outside the canvas is clipped. Returns the final pen position.
    ///
    /// # Panics
    ///
    /// If creating the pixman solid fill fails.
    pub fn draw(
        &mut self,
        run: &TextRun,
        pen_x: i32,
        baseline_y: i32,
        colour: Color,
    ) -> (i32, i32) {
        let solid = unsafe { ffi::pixman_image_create_solid_fill(&colour.to_pixman()) };
        assert!(!solid.is_null(), "pixman_image_create_solid_fill failed");
        let (mut x, mut y) = (pen_x, baseline_y);
        for ShapedGlyph { glyph, advance } in run.glyphs() {
            self.composite(&glyph, solid, x, y);
            x += advance.0;
            y += advance.1;
        }
        unsafe { ffi::pixman_image_unref(solid) };
        (x, y)
    }

    /// Composite a single glyph with the pen at `(pen_x, baseline_y)`.
    ///
    /// # Panics
    ///
    /// If creating the pixman solid fill fails.
    // XXX: unnecessary after all?
    pub fn draw_glyph(&mut self, glyph: &Glyph, pen_x: i32, baseline_y: i32, colour: Color) {
        let solid = unsafe { ffi::pixman_image_create_solid_fill(&colour.to_pixman()) };
        assert!(!solid.is_null(), "pixman_image_create_solid_fill failed");
        self.composite(glyph, solid, pen_x, baseline_y);
        unsafe { ffi::pixman_image_unref(solid) };
    }

    fn composite(
        &mut self,
        glyph: &Glyph,
        solid: *mut ffi::pixman_image_t,
        pen_x: i32,
        baseline_y: i32,
    ) {
        let g = glyph.as_raw();
        unsafe {
            if g.is_color_glyph {
                // Pre-rendered colour image: source OVER dest.
                ffi::pixman_image_composite32(
                    ffi::pixman_op_t_PIXMAN_OP_OVER,
                    g.pix,
                    std::ptr::null_mut(),
                    self.image,
                    0,
                    0,
                    0,
                    0,
                    pen_x + g.x,
                    baseline_y - g.y,
                    g.width,
                    g.height,
                );
            } else {
                // Mask: solid colour through the glyph's coverage mask.
                ffi::pixman_image_composite32(
                    ffi::pixman_op_t_PIXMAN_OP_OVER,
                    solid,
                    g.pix,
                    self.image,
                    0,
                    0,
                    0,
                    0,
                    pen_x + g.x,
                    baseline_y - g.y,
                    g.width,
                    g.height,
                );
            }
        }
    }

    /// The underlying pixman image.
    pub fn pixman_image(&mut self) -> *mut ffi::pixman_image_t {
        self.image
    }
}

impl Drop for Canvas<'_> {
    fn drop(&mut self) {
        unsafe { ffi::pixman_image_unref(self.image) };
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn char_fallback_matches_shaped_glyph_count() {
        let font = Font::new(&["Open Sans:pixelsize=24"], None).unwrap();
        let run = font.shape_chars("Hello 123", Subpixel::None);
        assert_eq!(run.len(), 9);
        assert!(run.width() > 0);
        for g in run.glyphs() {
            assert!(g.advance.0 > 0);
        }

        // Kerning-adjusted advances still sum close to the shaped result.
        let shaped = font.shape("Hello 123", Subpixel::None);
        let diff = (run.width() - shaped.width()).abs();
        assert!(
            diff <= i32::try_from(run.len()).unwrap(),
            "fallback width {} vs shaped {}",
            run.width(),
            shaped.width()
        );
    }

    #[test]
    fn empty_text_yields_empty_run() {
        let font = Font::new(&["Open Sans:pixelsize=24"], None).unwrap();
        let run = font.shape("", Subpixel::None);
        assert!(run.is_empty());
        assert_eq!(run.width(), 0);
    }
}