bite-gp-engine-default 1.24.401

gpui_engine_default — part of the bite-gpui rearchitecture of zed's gpui
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
//! Shaping, metric, and wrapping caches for text rendering.
//!
//! `TextSystem` wraps a platform text system with the engine's font-id,
//! metric, raster-bounds, and line-wrapper pools. It has no knowledge of
//! windows; the facade's window-scoped layer drives it.

use anyhow::{Context as _, Result, anyhow};
use collections::{FxHashMap, FxHashSet};
use gpui_engine::{
    Font, FontId, FontMetrics, FontRun, LineLayout, LineLayoutIndex, LineWrapper,
    LineWrapperHandle, MissingGlyph, MissingGlyphReports, MissingGlyphSink, PlatformTextSystem,
    RenderGlyphParams, TextRenderingMode, TextSystem, WrappedLineLayout, font,
};
use gpui_shared_string::SharedString;
use gpui_types::{Bounds, DevicePixels, Hsla, Pixels, Size, px};
use itertools::Itertools;
use parking_lot::{Mutex, RwLock, RwLockUpgradableReadGuard};
use smallvec::{SmallVec, smallvec};
use std::borrow::Cow;
use std::collections::VecDeque;
use std::future::Future;
use std::ops::Range;
use std::pin::Pin;
use std::sync::{
    Arc,
    atomic::{AtomicUsize, Ordering},
};

// Leave enough room below the underline for its stroke while keeping it below the baseline.
const UNDERLINE_DESCENT_OFFSET_FACTOR: f32 = 0.618;

/// Returns the vertical offset used to paint an underline within a line.
pub fn underline_y_offset(line_height: Pixels, ascent: Pixels, descent: Pixels) -> Pixels {
    let padding_top = (line_height - ascent - descent) / 2.;
    padding_top + ascent + descent * UNDERLINE_DESCENT_OFFSET_FACTOR
}

const MAX_REPORTED_MISSING_GLYPHS: usize = 1024;

#[derive(Default)]
struct MissingGlyphState {
    reported: FxHashSet<MissingGlyph>,
    reported_order: VecDeque<MissingGlyph>,
    generation: usize,
}

impl MissingGlyphState {
    fn reset(&mut self, generation: usize) {
        self.reported.clear();
        self.reported_order.clear();
        self.generation = generation;
    }
}

struct QueuedMissingGlyph {
    generation: usize,
    missing_glyph: MissingGlyph,
}

/// Collects missing-glyph reports without invoking application code during layout.
struct MissingGlyphReporter {
    generation: Arc<AtomicUsize>,
    sender: async_channel::Sender<QueuedMissingGlyph>,
}

impl MissingGlyphSink for MissingGlyphReporter {
    fn report(&self, missing_glyphs: Vec<MissingGlyph>) {
        if self.sender.is_closed() {
            return;
        }

        let generation = self.generation.load(Ordering::Acquire);
        // Repetitions within a line must not fill the queue before its other
        // missing glyphs. Cross-report deduplication belongs to the receiver.
        for missing_glyph in missing_glyphs.into_iter().unique() {
            let queued = QueuedMissingGlyph {
                generation,
                missing_glyph,
            };
            if self.sender.try_send(queued).is_err() {
                break;
            }
        }
    }
}

impl MissingGlyphReporter {
    fn reset(&self) {
        self.generation.fetch_add(1, Ordering::AcqRel);
    }
}

/// Receives batches of grapheme clusters that exhausted font fallback.
pub struct MissingGlyphReceiver {
    state: MissingGlyphState,
    generation: Arc<AtomicUsize>,
    receiver: async_channel::Receiver<QueuedMissingGlyph>,
}

impl MissingGlyphReceiver {
    /// Waits until at least one new missing glyph has been observed.
    ///
    /// # Errors
    ///
    /// Returns [`async_channel::RecvError`] if the reporting channel is closed.
    pub async fn recv(
        &mut self,
    ) -> std::result::Result<Vec<MissingGlyph>, async_channel::RecvError> {
        loop {
            let queued = self.receiver.recv().await?;
            let mut missing_glyphs = Vec::new();
            for queued in std::iter::once(queued)
                .chain(std::iter::from_fn(|| self.receiver.try_recv().ok()))
                .take(MAX_REPORTED_MISSING_GLYPHS)
            {
                let generation = self.generation.load(Ordering::Acquire);
                if self.state.generation != generation {
                    self.state.reset(generation);
                    missing_glyphs.clear();
                }
                if queued.generation != generation
                    || !self.state.reported.insert(queued.missing_glyph.clone())
                {
                    continue;
                }
                self.state
                    .reported_order
                    .push_back(queued.missing_glyph.clone());
                missing_glyphs.push(queued.missing_glyph);
                if self.state.reported.len() > MAX_REPORTED_MISSING_GLYPHS
                    && let Some(expired) = self.state.reported_order.pop_front()
                {
                    self.state.reported.remove(&expired);
                }
            }
            if !missing_glyphs.is_empty() {
                return Ok(missing_glyphs);
            }
            // A producer can keep refilling the queue with already-reported
            // glyphs. Bound work per poll even when every report is filtered out.
            let mut yielded = false;
            std::future::poll_fn(|cx| {
                if std::mem::replace(&mut yielded, true) {
                    std::task::Poll::Ready(())
                } else {
                    cx.waker().wake_by_ref();
                    std::task::Poll::Pending
                }
            })
            .await;
        }
    }
}

impl Drop for MissingGlyphReceiver {
    fn drop(&mut self) {
        self.receiver.close();
        while self.receiver.try_recv().is_ok() {}
    }
}

impl MissingGlyphReports for MissingGlyphReceiver {
    fn recv(&mut self) -> Pin<Box<dyn Future<Output = Option<Vec<MissingGlyph>>> + Send + '_>> {
        Box::pin(async move { MissingGlyphReceiver::recv(self).await.ok() })
    }
}

use crate::LineLayoutCache;

/// The GPUI text rendering sub system.
pub struct DefaultTextSystem {
    platform_text_system: Arc<dyn PlatformTextSystem>,
    font_ids_by_font: RwLock<FxHashMap<Font, Result<FontId>>>,
    font_metrics: RwLock<FxHashMap<FontId, FontMetrics>>,
    raster_bounds: RwLock<FxHashMap<RenderGlyphParams, Bounds<DevicePixels>>>,
    wrapper_pool: Mutex<FxHashMap<FontIdWithSize, Vec<LineWrapper>>>,
    font_runs_pool: Mutex<Vec<Vec<FontRun>>>,
    fallback_font_stack: SmallVec<[Font; 2]>,
    font_generation: Arc<AtomicUsize>,
    missing_glyph_reporter: Arc<MissingGlyphReporter>,
    missing_glyph_receiver: Mutex<Option<MissingGlyphReceiver>>,
    line_layout_cache: LineLayoutCache,
}

impl DefaultTextSystem {
    /// Create a new DefaultTextSystem with the given platform text system.
    pub fn new(platform_text_system: Arc<dyn PlatformTextSystem>) -> Self {
        let font_generation = Arc::<AtomicUsize>::default();
        let line_layout_cache =
            LineLayoutCache::new(platform_text_system.clone(), font_generation.clone());
        let (sender, receiver) = async_channel::bounded(MAX_REPORTED_MISSING_GLYPHS);
        let missing_glyph_generation = Arc::<AtomicUsize>::default();
        DefaultTextSystem {
            platform_text_system,
            font_metrics: RwLock::default(),
            raster_bounds: RwLock::default(),
            font_ids_by_font: RwLock::default(),
            wrapper_pool: Mutex::default(),
            font_runs_pool: Mutex::default(),
            fallback_font_stack: smallvec![
                // TODO: Remove this when Linux have implemented setting fallbacks.
                font(".ZedMono"),
                font(".ZedSans"),
                font("Helvetica"),
                font("Segoe UI"),     // Windows
                font("Ubuntu"),       // Gnome (Ubuntu)
                font("Adwaita Sans"), // Gnome 47
                font("Cantarell"),    // Gnome
                font("Noto Sans"),    // KDE
                font("DejaVu Sans"),
                font("Arial"), // macOS, Windows
            ],
            font_generation,
            missing_glyph_reporter: Arc::new(MissingGlyphReporter {
                generation: missing_glyph_generation.clone(),
                sender,
            }),
            missing_glyph_receiver: Mutex::new(Some(MissingGlyphReceiver {
                state: MissingGlyphState::default(),
                generation: missing_glyph_generation,
                receiver,
            })),
            line_layout_cache,
        }
    }

    /// The platform text system this engine wraps.
    pub fn platform_text_system(&self) -> &Arc<dyn PlatformTextSystem> {
        &self.platform_text_system
    }

    /// The generation that advances whenever [`Self::add_fonts`] installs fonts.
    pub fn font_generation(&self) -> &Arc<AtomicUsize> {
        &self.font_generation
    }

    /// Takes a pooled font-run buffer, or an empty one when the pool is dry.
    pub fn take_font_runs(&self) -> Vec<FontRun> {
        self.font_runs_pool.lock().pop().unwrap_or_default()
    }

    /// Returns a font-run buffer to the pool for reuse.
    pub fn recycle_font_runs(&self, font_runs: Vec<FontRun>) {
        self.font_runs_pool.lock().push(font_runs);
    }

    /// Get sorted, unique font family names available to the platform text system.
    ///
    /// Includes fonts registered with [`Self::add_fonts`].
    pub fn all_font_names(&self) -> Vec<String> {
        let mut names = self.platform_text_system.all_font_names();
        names.sort_unstable();
        names.dedup();
        names
    }

    /// Add a font's data to the text system.
    ///
    /// Cached font resolution and line layouts are invalidated after installation.
    /// Layouts already in progress may complete against the previous font set.
    pub fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
        self.platform_text_system.add_fonts(fonts)?;
        self.font_ids_by_font.write().clear();
        self.missing_glyph_reporter.reset();
        self.font_generation.fetch_add(1, Ordering::Release);
        Ok(())
    }

    /// Get the FontId for the configure font family and style.
    fn font_id(&self, font: &Font) -> Result<FontId> {
        fn clone_font_id_result(font_id: &Result<FontId>) -> Result<FontId> {
            match font_id {
                Ok(font_id) => Ok(*font_id),
                Err(err) => Err(anyhow!("{err}")),
            }
        }

        let font_id = self
            .font_ids_by_font
            .read()
            .get(font)
            .map(clone_font_id_result);
        if let Some(font_id) = font_id {
            font_id
        } else {
            let font_id = self.platform_text_system.font_id(font);
            self.font_ids_by_font
                .write()
                .insert(font.clone(), clone_font_id_result(&font_id));
            font_id
        }
    }

    /// Get the Font for the Font Id.
    pub fn get_font_for_id(&self, id: FontId) -> Option<Font> {
        let lock = self.font_ids_by_font.read();
        lock.iter()
            .filter_map(|(font, result)| match result {
                Ok(font_id) if *font_id == id => Some(font.clone()),
                _ => None,
            })
            .next()
    }

    /// Resolves the specified font, falling back to the default font stack if
    /// the font fails to load.
    ///
    /// # Panics
    ///
    /// Panics if the font and none of the fallbacks can be resolved.
    pub fn resolve_font(&self, font: &Font) -> FontId {
        if let Ok(font_id) = self.font_id(font) {
            return font_id;
        }
        for fallback in &self.fallback_font_stack {
            if let Ok(font_id) = self.font_id(fallback) {
                return font_id;
            }
        }

        panic!(
            "failed to resolve font '{}' or any of the fallbacks: {}",
            font.family,
            self.fallback_font_stack
                .iter()
                .map(|fallback| &fallback.family)
                .join(", ")
        );
    }

    /// Prewarm any system font caches needed to shape text.
    ///
    /// This may be expensive, so callers should generally invoke it on a
    /// background executor. Missing entries are still populated on demand by
    /// the normal shaping path.
    pub fn prewarm_fonts(&self, fonts: &[Font]) {
        let mut font_ids = SmallVec::<[FontId; 8]>::new();
        for font in fonts {
            let font_id = self.resolve_font(font);
            if !font_ids.contains(&font_id) {
                font_ids.push(font_id);
            }
        }
        self.platform_text_system.prewarm_fonts(&font_ids);
    }

    /// Get the bounding box for the given font and font size.
    /// A font's bounding box is the smallest rectangle that could enclose all glyphs
    /// in the font. superimposed over one another.
    pub fn bounding_box(&self, font_id: FontId, font_size: Pixels) -> Bounds<Pixels> {
        self.read_metrics(font_id, |metrics| metrics.bounding_box(font_size))
    }

    /// Get the typographic bounds for the given character, in the given font and size.
    pub fn typographic_bounds(
        &self,
        font_id: FontId,
        font_size: Pixels,
        character: char,
    ) -> Result<Bounds<Pixels>> {
        let glyph_id = self
            .platform_text_system
            .glyph_for_char(font_id, character)
            .with_context(|| format!("glyph not found for character '{character}'"))?;
        let bounds = self
            .platform_text_system
            .typographic_bounds(font_id, glyph_id)?;
        Ok(self.read_metrics(font_id, |metrics| {
            (bounds / metrics.units_per_em as f32 * font_size.0).map(px)
        }))
    }

    /// Get the advance width for the given character, in the given font and size.
    pub fn advance(&self, font_id: FontId, font_size: Pixels, ch: char) -> Result<Size<Pixels>> {
        let glyph_id = self
            .platform_text_system
            .glyph_for_char(font_id, ch)
            .with_context(|| format!("glyph not found for character '{ch}'"))?;
        let result = self.platform_text_system.advance(font_id, glyph_id)?
            / self.units_per_em(font_id) as f32;

        Ok(result * font_size)
    }

    // Consider removing this?
    /// Returns the shaped layout width of for the given character, in the given font and size.
    pub fn layout_width(&self, font_id: FontId, font_size: Pixels, ch: char) -> Pixels {
        let mut buffer = [0; 4];
        let buffer = ch.encode_utf8(&mut buffer);
        self.platform_text_system
            .layout_line(
                buffer,
                font_size,
                &[FontRun {
                    len: buffer.len(),
                    font_id,
                }],
            )
            .width
    }

    /// Returns the width of an `em`.
    ///
    /// Uses the width of the `m` character in the given font and size.
    pub fn em_width(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
        Ok(self.typographic_bounds(font_id, font_size, 'm')?.size.width)
    }

    /// Returns the advance width of an `em`.
    ///
    /// Uses the advance width of the `m` character in the given font and size.
    pub fn em_advance(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
        Ok(self.advance(font_id, font_size, 'm')?.width)
    }

    /// Returns the width of an `ch`.
    ///
    /// Uses the width of the `0` character in the given font and size.
    pub fn ch_width(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
        Ok(self.typographic_bounds(font_id, font_size, '0')?.size.width)
    }

    /// Returns the advance width of an `ch`.
    ///
    /// Uses the advance width of the `0` character in the given font and size.
    pub fn ch_advance(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
        Ok(self.advance(font_id, font_size, '0')?.width)
    }

    /// Get the number of font size units per 'em square',
    /// Per MDN: "an abstract square whose height is the intended distance between
    /// lines of type in the same type size"
    pub fn units_per_em(&self, font_id: FontId) -> u32 {
        self.read_metrics(font_id, |metrics| metrics.units_per_em)
    }

    /// Get the height of a capital letter in the given font and size.
    pub fn cap_height(&self, font_id: FontId, font_size: Pixels) -> Pixels {
        self.read_metrics(font_id, |metrics| metrics.cap_height(font_size))
    }

    /// Get the height of the x character in the given font and size.
    pub fn x_height(&self, font_id: FontId, font_size: Pixels) -> Pixels {
        self.read_metrics(font_id, |metrics| metrics.x_height(font_size))
    }

    /// Get the recommended distance from the baseline for the given font
    pub fn ascent(&self, font_id: FontId, font_size: Pixels) -> Pixels {
        self.read_metrics(font_id, |metrics| metrics.ascent(font_size))
    }

    /// Get the recommended distance below the baseline for the given font,
    /// in single spaced text.
    pub fn descent(&self, font_id: FontId, font_size: Pixels) -> Pixels {
        self.read_metrics(font_id, |metrics| metrics.descent(font_size))
    }

    /// Get the recommended baseline offset for the given font and line height.
    pub fn baseline_offset(
        &self,
        font_id: FontId,
        font_size: Pixels,
        line_height: Pixels,
    ) -> Pixels {
        let ascent = self.ascent(font_id, font_size);
        let descent = self.descent(font_id, font_size);
        let padding_top = (line_height - ascent - descent) / 2.;
        padding_top + ascent
    }

    fn read_metrics<T>(&self, font_id: FontId, read: impl FnOnce(&FontMetrics) -> T) -> T {
        let lock = self.font_metrics.upgradable_read();

        if let Some(metrics) = lock.get(&font_id) {
            read(metrics)
        } else {
            let mut lock = RwLockUpgradableReadGuard::upgrade(lock);
            let metrics = lock
                .entry(font_id)
                .or_insert_with(|| self.platform_text_system.font_metrics(font_id));
            read(metrics)
        }
    }

    /// Returns a handle to a line wrapper, for the given font and font size.
    pub fn line_wrapper(self: Arc<Self>, font: Font, font_size: Pixels) -> LineWrapperHandle {
        let font_id = self.resolve_font(&font);
        let wrapper = {
            let mut lock = self.wrapper_pool.lock();
            lock.entry(FontIdWithSize { font_id, font_size })
                .or_default()
                .pop()
                .unwrap_or_else(|| LineWrapper::new(font_id, font_size, self.clone()))
        };
        LineWrapperHandle::new(wrapper, move |wrapper| {
            let mut lock = self.wrapper_pool.lock();
            lock.get_mut(&FontIdWithSize { font_id, font_size })
                .expect("wrapper pool entry exists")
                .push(wrapper);
        })
    }

    /// Get the rasterized size and location of a specific, rendered glyph.
    pub fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
        let raster_bounds = self.raster_bounds.upgradable_read();
        if let Some(bounds) = raster_bounds.get(params) {
            Ok(*bounds)
        } else {
            let mut raster_bounds = RwLockUpgradableReadGuard::upgrade(raster_bounds);
            let bounds = self.platform_text_system.glyph_raster_bounds(params)?;
            raster_bounds.insert(params.clone(), bounds);
            Ok(bounds)
        }
    }

    /// Rasterizes a glyph, returning its size and coverage bitmap.
    pub fn rasterize_glyph(
        &self,
        params: &RenderGlyphParams,
    ) -> Result<(Size<DevicePixels>, Vec<u8>)> {
        let raster_bounds = self.raster_bounds(params)?;
        self.platform_text_system
            .rasterize_glyph(params, raster_bounds)
    }

    /// Returns the dilation level to use for a glyph painted in the given color.
    pub fn glyph_dilation_for_color(&self, color: Hsla) -> u8 {
        self.platform_text_system.glyph_dilation_for_color(color)
    }

    /// Returns the text rendering mode recommended by the platform for the given font and size.
    /// The return value will never be [`TextRenderingMode::PlatformDefault`].
    pub fn recommended_rendering_mode(
        &self,
        font_id: FontId,
        font_size: Pixels,
    ) -> TextRenderingMode {
        self.platform_text_system
            .recommended_rendering_mode(font_id, font_size)
    }
}

#[derive(Hash, Eq, PartialEq)]
struct FontIdWithSize {
    font_id: FontId,
    font_size: Pixels,
}

/// Affordances of the default text system that the shared [`TextSystem`] SPI does
/// not carry, in the same spirit as `gpui_parley`'s `as_parley`.
pub trait DefaultTextSystemExt {
    /// This text system as a [`DefaultTextSystem`], when it is one.
    fn as_default_text_system(&self) -> Option<&DefaultTextSystem>;
}

impl DefaultTextSystemExt for dyn TextSystem + '_ {
    fn as_default_text_system(&self) -> Option<&DefaultTextSystem> {
        self.as_any().downcast_ref::<DefaultTextSystem>()
    }
}

impl DefaultTextSystem {
    /// Reports missing glyphs as if the platform text system had observed them.
    ///
    /// A test affordance: the production path is
    /// [`Self::enable_missing_glyph_reporting`] plus
    /// [`TextSystem::take_missing_glyph_receiver`]. Test code reaches it by
    /// downcasting, through [`DefaultTextSystemExt::as_default_text_system`].
    #[cfg(any(test, feature = "test-support"))]
    pub fn report_missing_glyphs_in_test(&self, missing_glyphs: Vec<MissingGlyph>) {
        self.missing_glyph_reporter.report(missing_glyphs);
    }
}

impl TextSystem for DefaultTextSystem {
    fn take_missing_glyph_receiver(&self) -> Option<Box<dyn MissingGlyphReports>> {
        self.missing_glyph_receiver
            .try_lock()
            .and_then(|mut receiver| receiver.take())
            .map(|receiver| Box::new(receiver) as Box<dyn MissingGlyphReports>)
    }

    fn enable_missing_glyph_reporting(&self) {
        self.platform_text_system
            .set_missing_glyph_sink(Some(self.missing_glyph_reporter.clone()));
    }

    fn disable_missing_glyph_reporting(&self) {
        self.platform_text_system.set_missing_glyph_sink(None);
        self.missing_glyph_reporter.reset();
    }

    fn platform_text_system(&self) -> &Arc<dyn PlatformTextSystem> {
        &self.platform_text_system
    }

    fn all_font_names(&self) -> Vec<String> {
        self.all_font_names()
    }

    fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
        self.add_fonts(fonts)
    }

    fn get_font_for_id(&self, id: FontId) -> Option<Font> {
        self.get_font_for_id(id)
    }

    fn resolve_font(&self, font: &Font) -> FontId {
        self.resolve_font(font)
    }

    fn prewarm_fonts(&self, fonts: &[Font]) {
        self.prewarm_fonts(fonts)
    }

    fn bounding_box(&self, font_id: FontId, font_size: Pixels) -> Bounds<Pixels> {
        self.bounding_box(font_id, font_size)
    }

    fn typographic_bounds(
        &self,
        font_id: FontId,
        font_size: Pixels,
        character: char,
    ) -> Result<Bounds<Pixels>> {
        self.typographic_bounds(font_id, font_size, character)
    }

    fn advance(&self, font_id: FontId, font_size: Pixels, ch: char) -> Result<Size<Pixels>> {
        self.advance(font_id, font_size, ch)
    }

    fn layout_width(&self, font_id: FontId, font_size: Pixels, ch: char) -> Pixels {
        self.layout_width(font_id, font_size, ch)
    }

    fn em_width(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
        self.em_width(font_id, font_size)
    }

    fn em_advance(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
        self.em_advance(font_id, font_size)
    }

    fn ch_width(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
        self.ch_width(font_id, font_size)
    }

    fn ch_advance(&self, font_id: FontId, font_size: Pixels) -> Result<Pixels> {
        self.ch_advance(font_id, font_size)
    }

    fn units_per_em(&self, font_id: FontId) -> u32 {
        self.units_per_em(font_id)
    }

    fn cap_height(&self, font_id: FontId, font_size: Pixels) -> Pixels {
        self.cap_height(font_id, font_size)
    }

    fn x_height(&self, font_id: FontId, font_size: Pixels) -> Pixels {
        self.x_height(font_id, font_size)
    }

    fn ascent(&self, font_id: FontId, font_size: Pixels) -> Pixels {
        self.ascent(font_id, font_size)
    }

    fn descent(&self, font_id: FontId, font_size: Pixels) -> Pixels {
        self.descent(font_id, font_size)
    }

    fn baseline_offset(&self, font_id: FontId, font_size: Pixels, line_height: Pixels) -> Pixels {
        self.baseline_offset(font_id, font_size, line_height)
    }

    fn take_font_runs(&self) -> Vec<FontRun> {
        self.take_font_runs()
    }

    fn recycle_font_runs(&self, font_runs: Vec<FontRun>) {
        self.recycle_font_runs(font_runs)
    }

    fn line_wrapper(self: Arc<Self>, font: Font, font_size: Pixels) -> LineWrapperHandle {
        DefaultTextSystem::line_wrapper(self, font, font_size)
    }

    fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
        self.raster_bounds(params)
    }

    fn rasterize_glyph(&self, params: &RenderGlyphParams) -> Result<(Size<DevicePixels>, Vec<u8>)> {
        self.rasterize_glyph(params)
    }

    fn glyph_dilation_for_color(&self, color: Hsla) -> u8 {
        self.glyph_dilation_for_color(color)
    }

    fn recommended_rendering_mode(&self, font_id: FontId, font_size: Pixels) -> TextRenderingMode {
        self.recommended_rendering_mode(font_id, font_size)
    }

    fn layout_index(&self) -> LineLayoutIndex {
        self.line_layout_cache.layout_index()
    }

    fn reuse_layouts(&self, range: Range<LineLayoutIndex>) {
        self.line_layout_cache.reuse_layouts(range)
    }

    fn truncate_layouts(&self, index: LineLayoutIndex) {
        self.line_layout_cache.truncate_layouts(index)
    }

    fn finish_frame(&self) {
        self.line_layout_cache.finish_frame()
    }

    fn layout_wrapped_line(
        &self,
        text: &str,
        font_size: Pixels,
        runs: &[FontRun],
        wrap_width: Option<Pixels>,
        max_lines: Option<usize>,
    ) -> Arc<WrappedLineLayout> {
        self.line_layout_cache
            .layout_wrapped_line(text, font_size, runs, wrap_width, max_lines)
    }

    fn layout_line(
        &self,
        text: &str,
        font_size: Pixels,
        runs: &[FontRun],
        force_width: Option<Pixels>,
    ) -> Arc<LineLayout> {
        self.line_layout_cache
            .layout_line(text, font_size, runs, force_width)
    }

    fn try_layout_line_by_hash(
        &self,
        text_hash: u64,
        text_len: usize,
        font_size: Pixels,
        runs: &[FontRun],
        force_width: Option<Pixels>,
    ) -> Option<Arc<LineLayout>> {
        self.line_layout_cache.try_layout_line_by_hash(
            text_hash,
            text_len,
            font_size,
            runs,
            force_width,
        )
    }

    fn layout_line_by_hash(
        &self,
        text_hash: u64,
        text_len: usize,
        font_size: Pixels,
        runs: &[FontRun],
        force_width: Option<Pixels>,
        materialize_text: Box<dyn FnOnce() -> SharedString>,
    ) -> Arc<LineLayout> {
        self.line_layout_cache.layout_line_by_hash(
            text_hash,
            text_len,
            font_size,
            runs,
            force_width,
            materialize_text,
        )
    }
}

#[cfg(test)]
mod missing_glyph_tests {
    use super::*;
    use futures::FutureExt as _;
    use gpui_engine::FallbackFontClass;

    #[test]
    fn bounds_retained_missing_glyphs() {
        let (reporter, mut receiver) = missing_glyph_channel();
        reporter.report(
            (0..MAX_REPORTED_MISSING_GLYPHS)
                .map(|index| {
                    MissingGlyph::new(index.to_string().into(), FallbackFontClass::Proportional)
                })
                .collect(),
        );
        assert!(receiver.recv().now_or_never().unwrap().is_ok());

        let newest = MissingGlyph::new("newest".into(), FallbackFontClass::Monospace);
        reporter.report(vec![newest.clone()]);
        assert!(receiver.recv().now_or_never().unwrap().is_ok());

        let state = &receiver.state;
        assert_eq!(state.reported.len(), MAX_REPORTED_MISSING_GLYPHS);
        assert_eq!(state.reported_order.len(), MAX_REPORTED_MISSING_GLYPHS);
        assert!(state.reported.contains(&newest));
    }

    #[test]
    fn dropping_receiver_closes_and_clears_reports() {
        let (reporter, receiver) = missing_glyph_channel();
        reporter.report(vec![missing_glyph("missing")]);

        drop(receiver);

        assert!(reporter.sender.is_closed());
        assert!(reporter.sender.is_empty());
    }

    fn missing_glyph_channel() -> (MissingGlyphReporter, MissingGlyphReceiver) {
        let (sender, receiver) = async_channel::bounded(MAX_REPORTED_MISSING_GLYPHS);
        let generation = Arc::<AtomicUsize>::default();
        let reporter = MissingGlyphReporter {
            generation: generation.clone(),
            sender,
        };
        let receiver = MissingGlyphReceiver {
            state: MissingGlyphState::default(),
            generation,
            receiver,
        };
        (reporter, receiver)
    }

    fn missing_glyph(grapheme: &'static str) -> MissingGlyph {
        MissingGlyph::new(grapheme.into(), FallbackFontClass::Proportional)
    }
}