Skip to main content

cranpose_render_wgpu/
lib.rs

1//! WGPU renderer backend for GPU-accelerated 2D rendering.
2//!
3//! This renderer uses WGPU for cross-platform GPU support across
4//! desktop (Windows/Mac/Linux), web (WebGPU), and mobile (Android/iOS).
5
6mod effect_renderer;
7pub(crate) mod gpu_stats;
8mod normalized_scene;
9mod offscreen;
10mod pipeline;
11mod render;
12mod scene;
13mod shader_cache;
14mod shaders;
15mod surface_executor;
16mod surface_plan;
17mod surface_requirements;
18#[cfg(test)]
19mod test_support;
20
21pub use gpu_stats::FrameStatsSnapshot as RenderStatsSnapshot;
22pub use scene::{ClickAction, HitRegion, Scene};
23
24use cranpose_core::{MemoryApplier, NodeId};
25use cranpose_render_common::{
26    graph::{
27        CachePolicy, DrawPrimitiveNode, IsolationReasons, LayerNode, PrimitiveEntry, PrimitiveNode,
28        PrimitivePhase, ProjectiveTransform, RenderGraph, RenderNode, TextPrimitiveNode,
29    },
30    raster_cache::LayerRasterCacheHashes,
31    text_hyphenation::choose_auto_hyphen_break as choose_shared_auto_hyphen_break,
32    RenderScene, Renderer,
33};
34use cranpose_ui::{set_text_measurer, LayoutTree, TextMeasurer};
35use cranpose_ui_graphics::{
36    Brush, Color, CornerRadii, DrawPrimitive, GraphicsLayer, Point, Rect, RenderHash, Size,
37};
38use glyphon::{
39    Attrs, AttrsOwned, Buffer, FamilyOwned, FontSystem, Metrics, Shaping, Style as GlyphonStyle,
40    Weight as GlyphonWeight,
41};
42use lru::LruCache;
43use render::GpuRenderer;
44use rustc_hash::FxHasher;
45use std::cell::RefCell;
46use std::collections::{HashMap, HashSet};
47use std::hash::{Hash, Hasher};
48use std::num::NonZeroUsize;
49use std::rc::Rc;
50use std::sync::atomic::{AtomicU64, Ordering};
51use std::sync::{Arc, Mutex, OnceLock};
52
53/// Convert an axis-aligned rectangle to four corner positions (TL, TR, BL, BR).
54pub(crate) fn rect_to_quad(rect: Rect) -> [[f32; 2]; 4] {
55    [
56        [rect.x, rect.y],
57        [rect.x + rect.width, rect.y],
58        [rect.x, rect.y + rect.height],
59        [rect.x + rect.width, rect.y + rect.height],
60    ]
61}
62
63/// Size-only cache for ultra-fast text measurement lookups.
64/// Key: (text_hash, font_size_fixed_point, style_hash)
65/// Value: (text_content, size) - text stored to handle hash collisions
66type TextSizeCache = Arc<Mutex<LruCache<(u64, i32, u64), (String, Size)>>>;
67type PreparedTextLayoutCache = Rc<
68    RefCell<LruCache<PreparedTextLayoutCacheKey, (String, cranpose_ui::text::PreparedTextLayout)>>,
69>;
70
71#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
72struct PreparedTextLayoutCacheKey {
73    text_hash: u64,
74    size_int: i32,
75    style_hash: u64,
76    options: cranpose_ui::text::TextLayoutOptions,
77    max_width_bits: Option<u32>,
78}
79
80static TEXT_MEASURE_TELEMETRY_ENABLED: OnceLock<bool> = OnceLock::new();
81static TEXT_MEASURE_TELEMETRY: OnceLock<TextMeasureTelemetry> = OnceLock::new();
82
83#[derive(Default)]
84struct TextMeasureTelemetry {
85    measure_calls: AtomicU64,
86    layout_calls: AtomicU64,
87    offset_calls: AtomicU64,
88    measure_with_options_calls: AtomicU64,
89    prepare_with_options_calls: AtomicU64,
90    measure_fast_path_hits: AtomicU64,
91    measure_fast_path_misses: AtomicU64,
92    prepare_fast_path_hits: AtomicU64,
93    prepare_fast_path_misses: AtomicU64,
94    prepared_layout_cache_hits: AtomicU64,
95    prepared_layout_cache_misses: AtomicU64,
96    size_cache_hits: AtomicU64,
97    size_cache_misses: AtomicU64,
98    text_cache_hits: AtomicU64,
99    text_cache_misses: AtomicU64,
100    text_cache_evictions: AtomicU64,
101    text_cache_occupancy: AtomicU64,
102    ensure_reshapes: AtomicU64,
103    ensure_reuses: AtomicU64,
104}
105
106fn text_measure_telemetry_enabled() -> bool {
107    *TEXT_MEASURE_TELEMETRY_ENABLED
108        .get_or_init(|| std::env::var_os("CRANPOSE_TEXT_MEASURE_TELEMETRY").is_some())
109}
110
111fn text_measure_telemetry() -> &'static TextMeasureTelemetry {
112    TEXT_MEASURE_TELEMETRY.get_or_init(TextMeasureTelemetry::default)
113}
114
115fn maybe_report_text_measure_telemetry(sequence: u64) {
116    if !text_measure_telemetry_enabled() || !sequence.is_multiple_of(200) {
117        return;
118    }
119    let telemetry = text_measure_telemetry();
120    let measure_calls = telemetry.measure_calls.load(Ordering::Relaxed);
121    let layout_calls = telemetry.layout_calls.load(Ordering::Relaxed);
122    let offset_calls = telemetry.offset_calls.load(Ordering::Relaxed);
123    let measure_with_options_calls = telemetry.measure_with_options_calls.load(Ordering::Relaxed);
124    let prepare_with_options_calls = telemetry.prepare_with_options_calls.load(Ordering::Relaxed);
125    let measure_fast_path_hits = telemetry.measure_fast_path_hits.load(Ordering::Relaxed);
126    let measure_fast_path_misses = telemetry.measure_fast_path_misses.load(Ordering::Relaxed);
127    let prepare_fast_path_hits = telemetry.prepare_fast_path_hits.load(Ordering::Relaxed);
128    let prepare_fast_path_misses = telemetry.prepare_fast_path_misses.load(Ordering::Relaxed);
129    let prepared_layout_cache_hits = telemetry.prepared_layout_cache_hits.load(Ordering::Relaxed);
130    let prepared_layout_cache_misses = telemetry
131        .prepared_layout_cache_misses
132        .load(Ordering::Relaxed);
133    let size_hits = telemetry.size_cache_hits.load(Ordering::Relaxed);
134    let size_misses = telemetry.size_cache_misses.load(Ordering::Relaxed);
135    let text_hits = telemetry.text_cache_hits.load(Ordering::Relaxed);
136    let text_misses = telemetry.text_cache_misses.load(Ordering::Relaxed);
137    let text_cache_evictions = telemetry.text_cache_evictions.load(Ordering::Relaxed);
138    let text_cache_occupancy = telemetry.text_cache_occupancy.load(Ordering::Relaxed);
139    let reshapes = telemetry.ensure_reshapes.load(Ordering::Relaxed);
140    let reuses = telemetry.ensure_reuses.load(Ordering::Relaxed);
141
142    let size_total = size_hits + size_misses;
143    let text_total = text_hits + text_misses;
144    let ensure_total = reshapes + reuses;
145    let size_hit_rate = if size_total > 0 {
146        (size_hits as f64 / size_total as f64) * 100.0
147    } else {
148        0.0
149    };
150    let text_hit_rate = if text_total > 0 {
151        (text_hits as f64 / text_total as f64) * 100.0
152    } else {
153        0.0
154    };
155    let measure_fast_path_total = measure_fast_path_hits + measure_fast_path_misses;
156    let measure_fast_path_rate = if measure_fast_path_total > 0 {
157        (measure_fast_path_hits as f64 / measure_fast_path_total as f64) * 100.0
158    } else {
159        0.0
160    };
161    let prepare_fast_path_total = prepare_fast_path_hits + prepare_fast_path_misses;
162    let prepare_fast_path_rate = if prepare_fast_path_total > 0 {
163        (prepare_fast_path_hits as f64 / prepare_fast_path_total as f64) * 100.0
164    } else {
165        0.0
166    };
167    let prepared_layout_cache_total = prepared_layout_cache_hits + prepared_layout_cache_misses;
168    let prepared_layout_cache_hit_rate = if prepared_layout_cache_total > 0 {
169        (prepared_layout_cache_hits as f64 / prepared_layout_cache_total as f64) * 100.0
170    } else {
171        0.0
172    };
173    let reshape_rate = if ensure_total > 0 {
174        (reshapes as f64 / ensure_total as f64) * 100.0
175    } else {
176        0.0
177    };
178
179    log::warn!(
180        "[text-measure-telemetry] measure_calls={} layout_calls={} offset_calls={} measure_with_options_calls={} prepare_with_options_calls={} measure_fast_path_rate={:.1}% prepare_fast_path_rate={:.1}% prepared_layout_cache_hit_rate={:.1}% size_hit_rate={:.1}% text_cache_hit_rate={:.1}% text_cache_occupancy={} text_cache_evictions={} reshape_rate={:.1}% reshapes={} reuses={}",
181        measure_calls,
182        layout_calls,
183        offset_calls,
184        measure_with_options_calls,
185        prepare_with_options_calls,
186        measure_fast_path_rate,
187        prepare_fast_path_rate,
188        prepared_layout_cache_hit_rate,
189        size_hit_rate,
190        text_hit_rate,
191        text_cache_occupancy,
192        text_cache_evictions,
193        reshape_rate,
194        reshapes,
195        reuses
196    );
197}
198
199#[derive(Debug)]
200pub enum WgpuRendererError {
201    Layout(String),
202    Wgpu(String),
203}
204
205/// CPU-readable RGBA frame captured from the renderer output.
206#[derive(Debug, Clone)]
207pub struct CapturedFrame {
208    pub width: u32,
209    pub height: u32,
210    pub pixels: Vec<u8>,
211}
212
213#[doc(hidden)]
214#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
215pub struct DebugCpuAllocationStats {
216    pub scene_graph_node_count: usize,
217    pub scene_graph_heap_bytes: usize,
218    pub scene_hits_len: usize,
219    pub scene_hits_cap: usize,
220    pub scene_node_index_len: usize,
221    pub scene_node_index_cap: usize,
222    pub text_renderer_pool_len: usize,
223    pub text_renderer_pool_cap: usize,
224    pub swash_image_cache_len: usize,
225    pub swash_image_cache_cap: usize,
226    pub swash_outline_cache_len: usize,
227    pub swash_outline_cache_cap: usize,
228    pub image_texture_cache_len: usize,
229    pub image_texture_cache_cap: usize,
230    pub scratch_shape_data_cap: usize,
231    pub scratch_gradients_cap: usize,
232    pub scratch_vertices_cap: usize,
233    pub scratch_indices_cap: usize,
234    pub scratch_image_vertices_cap: usize,
235    pub scratch_image_indices_cap: usize,
236    pub scratch_image_cmds_cap: usize,
237    pub scratch_segment_items_cap: usize,
238    pub scratch_effect_ranges_cap: usize,
239    pub scratch_layer_events_cap: usize,
240    pub staged_upload_bytes_cap: usize,
241    pub staged_upload_copies_cap: usize,
242    pub layer_surface_cache_len: usize,
243    pub layer_surface_cache_cap: usize,
244    pub layer_surface_cache_identity_len: usize,
245    pub layer_surface_cache_identity_cap: usize,
246    pub layer_surface_rect_cache_len: usize,
247    pub layer_surface_rect_cache_cap: usize,
248    pub layer_surface_requirements_cache_len: usize,
249    pub layer_surface_requirements_cache_cap: usize,
250    pub layer_cache_seen_this_frame_len: usize,
251    pub layer_cache_seen_this_frame_cap: usize,
252}
253
254/// Unified hash key for text caching - shared between measurement and rendering.
255#[derive(Clone, PartialEq, Eq, Hash)]
256pub(crate) enum TextKey {
257    Content(String),
258    Node(NodeId),
259}
260
261#[derive(Clone, PartialEq, Eq)]
262pub(crate) struct TextCacheKey {
263    key: TextKey,
264    scale_bits: u32, // f32 as bits for hashing
265    style_hash: u64,
266}
267
268impl TextCacheKey {
269    fn new(text: &str, font_size: f32, style_hash: u64) -> Self {
270        Self {
271            key: TextKey::Content(text.to_string()),
272            scale_bits: font_size.to_bits(),
273            style_hash,
274        }
275    }
276
277    fn for_node(node_id: NodeId, font_size: f32, style_hash: u64) -> Self {
278        Self {
279            key: TextKey::Node(node_id),
280            scale_bits: font_size.to_bits(),
281            style_hash,
282        }
283    }
284}
285
286impl Hash for TextCacheKey {
287    fn hash<H: Hasher>(&self, state: &mut H) {
288        self.key.hash(state);
289        self.scale_bits.hash(state);
290        self.style_hash.hash(state);
291    }
292}
293
294/// Cached text buffer shared between measurement and rendering
295pub(crate) struct SharedTextBuffer {
296    pub(crate) buffer: Buffer,
297    text: String,
298    font_size: f32,
299    line_height: f32,
300    style_hash: u64,
301    /// Cached size to avoid recalculating on every access
302    cached_size: Option<Size>,
303}
304
305pub(crate) struct EnsureTextBufferParams<'a> {
306    pub(crate) annotated_text: &'a cranpose_ui::text::AnnotatedString,
307    pub(crate) font_size_px: f32,
308    pub(crate) line_height_px: f32,
309    pub(crate) style_hash: u64,
310    pub(crate) style: &'a cranpose_ui::text::TextStyle,
311    pub(crate) scale: f32,
312}
313
314fn requires_advanced_shaping(text: &str) -> bool {
315    text.chars().any(requires_advanced_shaping_char)
316}
317
318fn requires_advanced_shaping_char(ch: char) -> bool {
319    let code = ch as u32;
320    if ch.is_ascii() || ch.is_whitespace() {
321        return false;
322    }
323
324    matches!(
325        code,
326        0x0300..=0x036F
327            | 0x0590..=0x08FF
328            | 0x0900..=0x109F
329            | 0x135D..=0x135F
330            | 0x1712..=0x1715
331            | 0x1732..=0x1735
332            | 0x1752..=0x1753
333            | 0x1772..=0x1773
334            | 0x17B4..=0x17D3
335            | 0x1885..=0x18A9
336            | 0x1A17..=0x1A1B
337            | 0x1AB0..=0x1AFF
338            | 0x1B00..=0x1CFF
339            | 0x1CD0..=0x1DFF
340            | 0x200C..=0x200F
341            | 0x202A..=0x202E
342            | 0x2066..=0x2069
343            | 0x20D0..=0x20FF
344            | 0x2DE0..=0x2DFF
345            | 0x2E80..=0xA7FF
346            | 0xA980..=0xABFF
347            | 0xD800..=0xF8FF
348            | 0xFB1D..=0xFEFF
349            | 0x1F000..=u32::MAX
350    )
351}
352
353fn select_text_shaping(
354    annotated_text: &cranpose_ui::text::AnnotatedString,
355    style: &cranpose_ui::text::TextStyle,
356) -> Shaping {
357    let requested = style
358        .paragraph_style
359        .platform_style
360        .and_then(|platform| platform.shaping);
361
362    match requested {
363        Some(cranpose_ui::text::TextShaping::Basic)
364            if !requires_advanced_shaping(annotated_text.text.as_str()) =>
365        {
366            Shaping::Basic
367        }
368        _ => Shaping::Advanced,
369    }
370}
371
372fn glyph_foreground_color(
373    span_style: &cranpose_ui::text::SpanStyle,
374) -> Option<cranpose_ui_graphics::Color> {
375    let has_solid_foreground = span_style.color.is_some()
376        || matches!(
377            span_style.brush.as_ref(),
378            Some(cranpose_ui::Brush::Solid(_))
379        );
380    has_solid_foreground
381        .then(|| span_style.resolve_foreground_color(cranpose_ui_graphics::Color::WHITE))
382}
383
384fn hash_optional_glyph_foreground_color<H: Hasher>(
385    span_style: &cranpose_ui::text::SpanStyle,
386    state: &mut H,
387) {
388    match glyph_foreground_color(span_style) {
389        Some(color) => {
390            1u8.hash(state);
391            color.render_hash().hash(state);
392        }
393        None => 0u8.hash(state),
394    }
395}
396
397fn text_span_buffer_hash(text: &cranpose_ui::text::AnnotatedString) -> u64 {
398    let mut hasher = FxHasher::default();
399    text.span_styles.len().hash(&mut hasher);
400    for span in &text.span_styles {
401        span.range.start.hash(&mut hasher);
402        span.range.end.hash(&mut hasher);
403        let span_style = cranpose_ui::text::TextStyle {
404            span_style: span.item.clone(),
405            ..Default::default()
406        };
407        span_style.measurement_hash().hash(&mut hasher);
408        hash_optional_glyph_foreground_color(&span.item, &mut hasher);
409    }
410    hasher.finish()
411}
412
413fn text_buffer_style_hash(
414    style: &cranpose_ui::text::TextStyle,
415    text: &cranpose_ui::text::AnnotatedString,
416) -> u64 {
417    let mut hasher = FxHasher::default();
418    style.measurement_hash().hash(&mut hasher);
419    hash_optional_glyph_foreground_color(&style.span_style, &mut hasher);
420    text_span_buffer_hash(text).hash(&mut hasher);
421    hasher.finish()
422}
423
424impl SharedTextBuffer {
425    /// Ensure the buffer has the correct text and font_size, only reshaping if needed
426    pub(crate) fn ensure(
427        &mut self,
428        font_system: &mut FontSystem,
429        font_family_resolver: &mut WgpuFontFamilyResolver,
430        params: EnsureTextBufferParams<'_>,
431    ) -> bool {
432        let annotated_text = params.annotated_text;
433        let font_size_px = params.font_size_px;
434        let line_height_px = params.line_height_px;
435        let style_hash = params.style_hash;
436        let style = params.style;
437        let scale = params.scale;
438        let text_str = annotated_text.text.as_str();
439        let text_changed = self.text != text_str;
440        let font_changed = (self.font_size - font_size_px).abs() > 0.1;
441        let line_height_changed = (self.line_height - line_height_px).abs() > 0.1;
442        let style_changed = self.style_hash != style_hash;
443
444        // Only reshape if something actually changed
445        if !text_changed && !font_changed && !line_height_changed && !style_changed {
446            return false;
447        }
448
449        // Set metrics and size for unlimited layout
450        let metrics = Metrics::new(font_size_px, line_height_px);
451        self.buffer.set_metrics(font_system, metrics);
452        self.buffer
453            .set_size(font_system, Some(f32::MAX), Some(f32::MAX));
454
455        let unscaled_base_size = if scale > 0.0 {
456            font_size_px / scale
457        } else {
458            14.0
459        };
460        let shaping = select_text_shaping(annotated_text, style);
461
462        // Set text and shape
463        if annotated_text.span_styles.is_empty() {
464            let attrs = attrs_from_text_style(
465                style,
466                unscaled_base_size,
467                scale,
468                font_system,
469                font_family_resolver,
470            );
471            let attrs_ref = attrs.as_attrs();
472            self.buffer
473                .set_text(font_system, text_str, &attrs_ref, shaping, None);
474        } else {
475            let boundaries = annotated_text.span_boundaries();
476            let mut rich_spans: Vec<(usize, usize, AttrsOwned)> =
477                Vec::with_capacity(boundaries.len().saturating_sub(1));
478            let mut chunk_text_style = style.clone();
479            for window in boundaries.windows(2) {
480                let start = window[0];
481                let end = window[1];
482                if start == end {
483                    continue;
484                }
485                let mut merged_style = style.span_style.clone();
486                for span in &annotated_text.span_styles {
487                    if span.range.start <= start && span.range.end >= end {
488                        merged_style = merged_style.merge(&span.item);
489                    }
490                }
491                chunk_text_style.span_style = merged_style;
492                let attrs = attrs_from_text_style(
493                    &chunk_text_style,
494                    unscaled_base_size,
495                    scale,
496                    font_system,
497                    font_family_resolver,
498                );
499                if let Some((_, previous_end, previous_attrs)) = rich_spans.last_mut() {
500                    if *previous_end == start && *previous_attrs == attrs {
501                        *previous_end = end;
502                        continue;
503                    }
504                }
505                rich_spans.push((start, end, attrs));
506            }
507            let default_attrs = attrs_from_text_style(
508                style,
509                unscaled_base_size,
510                scale,
511                font_system,
512                font_family_resolver,
513            );
514            let default_attrs_ref = default_attrs.as_attrs();
515            self.buffer.set_rich_text(
516                font_system,
517                rich_spans.iter().map(|(start, end, attrs)| {
518                    (&annotated_text.text[*start..*end], attrs.as_attrs())
519                }),
520                &default_attrs_ref,
521                shaping,
522                None,
523            );
524        }
525        self.buffer.shape_until_scroll(font_system, false);
526
527        // Update cached values
528        self.text.clear();
529        self.text.push_str(text_str);
530        self.font_size = font_size_px;
531        self.line_height = line_height_px;
532        self.style_hash = style_hash;
533        self.cached_size = None; // Invalidate size cache
534        true
535    }
536
537    /// Get or calculate the size of the shaped text
538    pub(crate) fn size(&mut self) -> Size {
539        if let Some(size) = self.cached_size {
540            return size;
541        }
542
543        // Calculate size from buffer
544        let mut max_width = 0.0f32;
545        let mut total_height = 0.0f32;
546        for run in self.buffer.layout_runs() {
547            let mut run_height = run.line_height;
548            for glyph in run.glyphs {
549                let physical_height = glyph.font_size * 1.4; // 1.4 is our default line_height modifier
550                if physical_height > run_height {
551                    run_height = physical_height;
552                }
553            }
554
555            max_width = max_width.max(run.line_w);
556            total_height = total_height.max(run.line_top + run_height);
557        }
558
559        let size = Size {
560            width: max_width,
561            height: total_height,
562        };
563
564        self.cached_size = Some(size);
565        size
566    }
567}
568
569#[derive(Clone, Debug, PartialEq, Eq, Hash)]
570struct TypefaceRequest {
571    font_family: Option<cranpose_ui::text::FontFamily>,
572    font_weight: cranpose_ui::text::FontWeight,
573    font_style: cranpose_ui::text::FontStyle,
574    font_synthesis: cranpose_ui::text::FontSynthesis,
575}
576
577impl TypefaceRequest {
578    fn from_span_style(span_style: &cranpose_ui::text::SpanStyle) -> Self {
579        Self {
580            font_family: span_style.font_family.clone(),
581            font_weight: span_style.font_weight.unwrap_or_default(),
582            font_style: span_style.font_style.unwrap_or_default(),
583            font_synthesis: span_style.font_synthesis.unwrap_or_default(),
584        }
585    }
586}
587
588#[derive(Default)]
589struct WgpuFontFamilyResolver {
590    request_cache: HashMap<TypefaceRequest, FamilyOwned>,
591    loaded_typeface_paths: HashMap<String, String>,
592    unavailable_typeface_paths: HashSet<String>,
593    available_family_names: HashMap<String, String>,
594    preferred_generic_family: Option<String>,
595    indexed_face_count: usize,
596    generic_fallback_seeded: bool,
597}
598
599impl WgpuFontFamilyResolver {
600    fn prime(&mut self, font_system: &mut FontSystem) {
601        self.ensure_non_empty_font_db(font_system);
602        self.ensure_family_index(font_system);
603        self.ensure_generic_fallbacks(font_system);
604    }
605
606    fn clear_resolution_caches(&mut self) {
607        self.request_cache.clear();
608    }
609
610    fn set_preferred_generic_family(&mut self, family_name: Option<String>) {
611        self.preferred_generic_family = family_name;
612        self.generic_fallback_seeded = false;
613        self.clear_resolution_caches();
614    }
615
616    fn resolve_family_owned(
617        &mut self,
618        font_system: &mut FontSystem,
619        span_style: &cranpose_ui::text::SpanStyle,
620    ) -> FamilyOwned {
621        self.ensure_non_empty_font_db(font_system);
622        self.ensure_family_index(font_system);
623        self.ensure_generic_fallbacks(font_system);
624
625        let request = TypefaceRequest::from_span_style(span_style);
626        if let Some(cached) = self.request_cache.get(&request) {
627            return cached.clone();
628        }
629
630        let resolved = self.resolve_family_owned_uncached(font_system, &request);
631        self.request_cache.insert(request, resolved.clone());
632        resolved
633    }
634
635    fn ensure_non_empty_font_db(&mut self, font_system: &mut FontSystem) {
636        if font_system.db().faces().next().is_none() {
637            log::warn!("Font database is empty; text will not render. Provide fonts via AppLauncher::with_fonts.");
638        }
639    }
640
641    fn resolve_family_owned_uncached(
642        &mut self,
643        font_system: &mut FontSystem,
644        request: &TypefaceRequest,
645    ) -> FamilyOwned {
646        use cranpose_ui::text::FontFamily;
647
648        match request.font_family.as_ref() {
649            None | Some(FontFamily::Default | FontFamily::SansSerif) => FamilyOwned::SansSerif,
650            Some(FontFamily::Serif) => FamilyOwned::Serif,
651            Some(FontFamily::Monospace) => FamilyOwned::Monospace,
652            Some(FontFamily::Cursive) => FamilyOwned::Cursive,
653            Some(FontFamily::Fantasy) => FamilyOwned::Fantasy,
654            Some(FontFamily::Named(name)) => self
655                .canonical_family_name(name)
656                .map(|resolved| FamilyOwned::Name(resolved.into()))
657                .unwrap_or(FamilyOwned::SansSerif),
658            Some(FontFamily::FileBacked(file_backed)) => self
659                .resolve_file_backed_family(font_system, file_backed, request)
660                .unwrap_or(FamilyOwned::SansSerif),
661            Some(FontFamily::LoadedTypeface(typeface_path)) => self
662                .resolve_loaded_typeface_family(font_system, typeface_path.path.as_str())
663                .unwrap_or(FamilyOwned::SansSerif),
664        }
665    }
666
667    fn resolve_file_backed_family(
668        &mut self,
669        font_system: &mut FontSystem,
670        file_backed: &cranpose_ui::text::FileBackedFontFamily,
671        request: &TypefaceRequest,
672    ) -> Option<FamilyOwned> {
673        let mut candidates: Vec<&cranpose_ui::text::FontFile> = file_backed.fonts.iter().collect();
674        candidates.sort_by_key(|candidate| {
675            let style_penalty = if candidate.style == request.font_style {
676                0u32
677            } else {
678                10_000u32
679            };
680            let weight_penalty =
681                (i32::from(candidate.weight.0) - i32::from(request.font_weight.0)).unsigned_abs();
682            style_penalty + weight_penalty
683        });
684
685        for candidate in candidates {
686            let Some(family_name) = self.load_typeface_path(font_system, candidate.path.as_str())
687            else {
688                continue;
689            };
690            if let Some(canonical) = self.canonical_family_name(family_name.as_str()) {
691                return Some(FamilyOwned::Name(canonical.into()));
692            }
693        }
694        None
695    }
696
697    fn resolve_loaded_typeface_family(
698        &mut self,
699        font_system: &mut FontSystem,
700        path: &str,
701    ) -> Option<FamilyOwned> {
702        self.load_typeface_path(font_system, path)
703            .map(|family_name| {
704                self.canonical_family_name(family_name.as_str())
705                    .map(|resolved| FamilyOwned::Name(resolved.into()))
706                    .unwrap_or(FamilyOwned::SansSerif)
707            })
708    }
709
710    fn ensure_family_index(&mut self, font_system: &FontSystem) {
711        let face_count = font_system.db().faces().count();
712        if face_count == self.indexed_face_count {
713            return;
714        }
715
716        self.available_family_names.clear();
717        for face in font_system.db().faces() {
718            for (family_name, _) in &face.families {
719                self.available_family_names
720                    .entry(family_name.to_lowercase())
721                    .or_insert_with(|| family_name.clone());
722            }
723        }
724        self.indexed_face_count = face_count;
725        self.clear_resolution_caches();
726        self.generic_fallback_seeded = false;
727    }
728
729    fn canonical_family_name(&self, family_name: &str) -> Option<String> {
730        self.available_family_names
731            .get(&family_name.to_lowercase())
732            .cloned()
733    }
734
735    fn ensure_generic_fallbacks(&mut self, font_system: &mut FontSystem) {
736        if self.generic_fallback_seeded {
737            return;
738        }
739
740        let primary_family = self
741            .preferred_generic_family
742            .as_deref()
743            .and_then(|name| self.canonical_family_name(name))
744            .or_else(|| {
745                font_system
746                    .db()
747                    .faces()
748                    .find_map(|face| face.families.first().map(|(name, _)| name.clone()))
749            });
750
751        let Some(primary_family) = primary_family else {
752            return;
753        };
754
755        let db = font_system.db_mut();
756        db.set_sans_serif_family(primary_family.clone());
757        db.set_serif_family(primary_family.clone());
758        db.set_monospace_family(primary_family.clone());
759        db.set_cursive_family(primary_family.clone());
760        db.set_fantasy_family(primary_family);
761
762        self.generic_fallback_seeded = true;
763        self.clear_resolution_caches();
764    }
765
766    fn load_typeface_path(&mut self, font_system: &mut FontSystem, path: &str) -> Option<String> {
767        if let Some(family_name) = self.loaded_typeface_paths.get(path) {
768            return Some(family_name.clone());
769        }
770
771        if self.unavailable_typeface_paths.contains(path) {
772            return None;
773        }
774
775        #[cfg(target_arch = "wasm32")]
776        let _ = font_system;
777
778        #[cfg(target_arch = "wasm32")]
779        {
780            log::warn!(
781                "Typeface path '{}' requested on wasm target; filesystem font loading is unavailable",
782                path
783            );
784            self.unavailable_typeface_paths.insert(path.to_string());
785            return None;
786        }
787
788        #[cfg(not(target_arch = "wasm32"))]
789        {
790            let font_bytes = match std::fs::read(path) {
791                Ok(bytes) => bytes,
792                Err(error) => {
793                    log::warn!("Failed to read typeface path '{}': {}", path, error);
794                    self.unavailable_typeface_paths.insert(path.to_string());
795                    return None;
796                }
797            };
798            let preferred_family = primary_family_name_from_bytes(font_bytes.as_slice());
799            let previous_face_count = font_system.db().faces().count();
800            font_system.db_mut().load_font_data(font_bytes);
801
802            self.ensure_family_index(font_system);
803
804            let mut resolved_family =
805                preferred_family.and_then(|name| self.canonical_family_name(name.as_str()));
806            if resolved_family.is_none() && self.indexed_face_count > previous_face_count {
807                resolved_family = font_system
808                    .db()
809                    .faces()
810                    .skip(previous_face_count)
811                    .find_map(|face| face.families.first().map(|(name, _)| name.clone()));
812            }
813
814            let Some(family_name) = resolved_family else {
815                log::warn!(
816                    "Typeface path '{}' loaded but no usable family name was resolved",
817                    path
818                );
819                self.unavailable_typeface_paths.insert(path.to_string());
820                return None;
821            };
822            let family_name = self
823                .canonical_family_name(family_name.as_str())
824                .unwrap_or(family_name);
825
826            self.loaded_typeface_paths
827                .insert(path.to_string(), family_name.clone());
828            self.unavailable_typeface_paths.remove(path);
829            Some(family_name)
830        }
831    }
832}
833
834fn load_fonts(font_system: &mut FontSystem, fonts: &[&[u8]]) -> Vec<String> {
835    let mut loaded_families = Vec::new();
836    for (i, font_data) in fonts.iter().enumerate() {
837        log::info!("Loading font #{}, size: {} bytes", i, font_data.len());
838        if let Some(family_name) = primary_family_name_from_bytes(font_data) {
839            loaded_families.push(family_name);
840        }
841        font_system.db_mut().load_font_data(font_data.to_vec());
842    }
843    log::info!(
844        "Total font faces loaded: {}",
845        font_system.db().faces().count()
846    );
847    loaded_families
848}
849
850fn primary_family_name_from_bytes(bytes: &[u8]) -> Option<String> {
851    let face = ttf_parser::Face::parse(bytes, 0).ok()?;
852    let mut fallback_family = None;
853    for name in face.names() {
854        if name.name_id == ttf_parser::name_id::TYPOGRAPHIC_FAMILY {
855            let resolved = name.to_string().filter(|value| !value.is_empty());
856            if resolved.is_some() {
857                return resolved;
858            }
859        }
860        if fallback_family.is_none() && name.name_id == ttf_parser::name_id::FAMILY {
861            fallback_family = name.to_string().filter(|value| !value.is_empty());
862        }
863    }
864    fallback_family
865}
866
867const SHARED_TEXT_CACHE_CAPACITY: usize = 256;
868
869fn new_shared_text_buffer(
870    font_system: &mut FontSystem,
871    font_size: f32,
872    line_height: f32,
873) -> SharedTextBuffer {
874    let buffer = Buffer::new(font_system, Metrics::new(font_size, line_height));
875    SharedTextBuffer {
876        buffer,
877        text: String::new(),
878        font_size: 0.0,
879        line_height: 0.0,
880        style_hash: 0,
881        cached_size: None,
882    }
883}
884
885fn new_text_cache() -> LruCache<TextCacheKey, SharedTextBuffer> {
886    LruCache::new(NonZeroUsize::new(SHARED_TEXT_CACHE_CAPACITY).unwrap())
887}
888
889pub(crate) fn shared_text_buffer_mut<'a>(
890    cache: &'a mut LruCache<TextCacheKey, SharedTextBuffer>,
891    key: TextCacheKey,
892    font_system: &mut FontSystem,
893    font_size: f32,
894    line_height: f32,
895) -> (bool, bool, usize, &'a mut SharedTextBuffer) {
896    if cache.contains(&key) {
897        let len = cache.len();
898        let buffer = cache.get_mut(&key).expect("text cache hit must exist");
899        return (true, false, len, buffer);
900    }
901
902    let evicted = cache
903        .push(
904            key.clone(),
905            new_shared_text_buffer(font_system, font_size, line_height),
906        )
907        .is_some();
908    let len = cache.len();
909    let buffer = cache
910        .get_mut(&key)
911        .expect("inserted text cache entry must exist");
912    (false, evicted, len, buffer)
913}
914
915pub(crate) struct TextSystemState {
916    pub(crate) font_system: FontSystem,
917    pub(crate) font_family_resolver: WgpuFontFamilyResolver,
918    pub(crate) text_cache: LruCache<TextCacheKey, SharedTextBuffer>,
919}
920
921impl TextSystemState {
922    fn from_fonts(fonts: &[&[u8]]) -> Self {
923        let mut font_system = FontSystem::new();
924
925        // On Android never load system fonts: modern Android ships variable Roboto
926        // which can cause rasterization corruption or font-ID conflicts with glyphon.
927        #[cfg(target_os = "android")]
928        log::info!("Skipping Android system fonts – using application-provided fonts only");
929
930        let loaded_families = load_fonts(&mut font_system, fonts);
931
932        let mut font_family_resolver = WgpuFontFamilyResolver::default();
933        font_family_resolver.set_preferred_generic_family(loaded_families.into_iter().next());
934        font_family_resolver.prime(&mut font_system);
935        Self::from_parts(font_system, font_family_resolver)
936    }
937
938    fn from_parts(font_system: FontSystem, font_family_resolver: WgpuFontFamilyResolver) -> Self {
939        Self {
940            font_system,
941            font_family_resolver,
942            text_cache: new_text_cache(),
943        }
944    }
945
946    pub(crate) fn parts_mut(
947        &mut self,
948    ) -> (
949        &mut FontSystem,
950        &mut WgpuFontFamilyResolver,
951        &mut LruCache<TextCacheKey, SharedTextBuffer>,
952    ) {
953        (
954            &mut self.font_system,
955            &mut self.font_family_resolver,
956            &mut self.text_cache,
957        )
958    }
959}
960
961type SharedTextSystemState = Arc<Mutex<TextSystemState>>;
962
963#[derive(Clone)]
964pub struct WgpuTextSystem {
965    render: SharedTextSystemState,
966    measure: SharedTextSystemState,
967}
968
969impl WgpuTextSystem {
970    pub fn from_fonts(fonts: &[&[u8]]) -> Self {
971        Self {
972            render: Arc::new(Mutex::new(TextSystemState::from_fonts(fonts))),
973            measure: Arc::new(Mutex::new(TextSystemState::from_fonts(fonts))),
974        }
975    }
976
977    fn install_measurer(&self) {
978        set_text_measurer(WgpuTextMeasurer::new(Arc::clone(&self.measure)));
979    }
980
981    fn render_state(&self) -> SharedTextSystemState {
982        Arc::clone(&self.render)
983    }
984}
985
986/// WGPU-based renderer for GPU-accelerated 2D rendering.
987///
988/// This renderer supports:
989/// - GPU-accelerated shape rendering (rectangles, rounded rectangles)
990/// - Gradients (solid, linear, radial)
991/// - GPU text rendering via glyphon
992/// - Cross-platform support (Desktop, Web, Mobile)
993pub struct WgpuRenderer {
994    scene: Scene,
995    gpu_renderer: Option<GpuRenderer>,
996    render_text_state: SharedTextSystemState,
997    /// Root scale factor for text rendering (use for density scaling)
998    root_scale: f32,
999}
1000
1001impl WgpuRenderer {
1002    /// Create a new WGPU renderer.
1003    ///
1004    /// * `fonts` – font bytes to load, ordered by priority (first = highest priority).
1005    ///   Pass `&[]` to load no fonts; text will not render until fonts are provided.
1006    ///
1007    /// Call [`init_gpu`][Self::init_gpu] before rendering.
1008    pub fn new(fonts: &[&[u8]]) -> Self {
1009        Self::with_text_system(WgpuTextSystem::from_fonts(fonts))
1010    }
1011
1012    pub fn with_text_system(text_system: WgpuTextSystem) -> Self {
1013        text_system.install_measurer();
1014
1015        Self {
1016            scene: Scene::new(),
1017            gpu_renderer: None,
1018            render_text_state: text_system.render_state(),
1019            root_scale: 1.0,
1020        }
1021    }
1022
1023    /// Initialize GPU resources with a WGPU device and queue.
1024    pub fn init_gpu(
1025        &mut self,
1026        device: Arc<wgpu::Device>,
1027        queue: Arc<wgpu::Queue>,
1028        surface_format: wgpu::TextureFormat,
1029        adapter_backend: wgpu::Backend,
1030    ) {
1031        self.gpu_renderer = Some(GpuRenderer::new(
1032            device,
1033            queue,
1034            surface_format,
1035            adapter_backend,
1036        ));
1037    }
1038
1039    /// Set root scale factor for text rendering (e.g., density scaling on Android)
1040    pub fn set_root_scale(&mut self, scale: f32) {
1041        self.root_scale = scale;
1042    }
1043
1044    pub fn root_scale(&self) -> f32 {
1045        self.root_scale
1046    }
1047
1048    /// Render the scene to a texture view.
1049    pub fn render(
1050        &mut self,
1051        view: &wgpu::TextureView,
1052        width: u32,
1053        height: u32,
1054    ) -> Result<(), WgpuRendererError> {
1055        if let Some(gpu_renderer) = &mut self.gpu_renderer {
1056            let graph = self
1057                .scene
1058                .graph
1059                .as_ref()
1060                .ok_or_else(|| WgpuRendererError::Wgpu("scene graph is missing".to_string()))?;
1061            let mut text_state = self.render_text_state.lock().unwrap();
1062            let result =
1063                gpu_renderer.render(&mut text_state, view, graph, width, height, self.root_scale);
1064            result.map_err(WgpuRendererError::Wgpu)
1065        } else {
1066            Err(WgpuRendererError::Wgpu(
1067                "GPU renderer not initialized. Call init_gpu() first.".to_string(),
1068            ))
1069        }
1070    }
1071
1072    /// Render the current scene into an RGBA pixel buffer for robot tests.
1073    ///
1074    /// Uses the renderer's configured root scale.
1075    pub fn capture_frame(
1076        &mut self,
1077        width: u32,
1078        height: u32,
1079    ) -> Result<CapturedFrame, WgpuRendererError> {
1080        self.capture_frame_with_scale(width, height, self.root_scale)
1081    }
1082
1083    /// Render the current scene into an RGBA pixel buffer with an explicit scale.
1084    pub fn capture_frame_with_scale(
1085        &mut self,
1086        width: u32,
1087        height: u32,
1088        root_scale: f32,
1089    ) -> Result<CapturedFrame, WgpuRendererError> {
1090        if let Some(gpu_renderer) = &mut self.gpu_renderer {
1091            let graph = self
1092                .scene
1093                .graph
1094                .as_ref()
1095                .ok_or_else(|| WgpuRendererError::Wgpu("scene graph is missing".to_string()))?;
1096            let mut text_state = self.render_text_state.lock().unwrap();
1097            let pixels = gpu_renderer
1098                .render_to_rgba_pixels(&mut text_state, graph, width, height, root_scale)
1099                .map_err(WgpuRendererError::Wgpu)?;
1100            Ok(CapturedFrame {
1101                width,
1102                height,
1103                pixels,
1104            })
1105        } else {
1106            Err(WgpuRendererError::Wgpu(
1107                "GPU renderer not initialized. Call init_gpu() first.".to_string(),
1108            ))
1109        }
1110    }
1111
1112    pub fn last_frame_stats(&self) -> Option<RenderStatsSnapshot> {
1113        self.gpu_renderer
1114            .as_ref()
1115            .and_then(GpuRenderer::last_frame_stats)
1116    }
1117
1118    pub fn debug_cpu_allocation_stats(&self) -> DebugCpuAllocationStats {
1119        let mut stats = self
1120            .gpu_renderer
1121            .as_ref()
1122            .map(GpuRenderer::debug_cpu_allocation_stats)
1123            .unwrap_or_default();
1124        stats.scene_graph_node_count = self
1125            .scene
1126            .graph
1127            .as_ref()
1128            .map(RenderGraph::node_count)
1129            .unwrap_or(0);
1130        stats.scene_graph_heap_bytes = self
1131            .scene
1132            .graph
1133            .as_ref()
1134            .map(RenderGraph::heap_bytes)
1135            .unwrap_or(0);
1136        stats.scene_hits_len = self.scene.hits.len();
1137        stats.scene_hits_cap = self.scene.hits.capacity();
1138        stats.scene_node_index_len = self.scene.node_index.len();
1139        stats.scene_node_index_cap = self.scene.node_index.capacity();
1140        stats
1141    }
1142
1143    /// Get access to the WGPU device (for surface configuration).
1144    pub fn device(&self) -> &wgpu::Device {
1145        self.gpu_renderer
1146            .as_ref()
1147            .map(|r| &*r.device)
1148            .expect("GPU renderer not initialized")
1149    }
1150}
1151
1152impl Default for WgpuRenderer {
1153    fn default() -> Self {
1154        Self::new(&[])
1155    }
1156}
1157
1158impl Renderer for WgpuRenderer {
1159    type Scene = Scene;
1160    type Error = WgpuRendererError;
1161
1162    fn scene(&self) -> &Self::Scene {
1163        &self.scene
1164    }
1165
1166    fn scene_mut(&mut self) -> &mut Self::Scene {
1167        &mut self.scene
1168    }
1169
1170    fn rebuild_scene(
1171        &mut self,
1172        layout_tree: &LayoutTree,
1173        _viewport: Size,
1174    ) -> Result<(), Self::Error> {
1175        self.scene.clear();
1176        // Build scene in logical dp - scaling happens in GPU vertex upload
1177        pipeline::render_layout_tree(layout_tree.root(), &mut self.scene);
1178        Ok(())
1179    }
1180
1181    fn rebuild_scene_from_applier(
1182        &mut self,
1183        applier: &mut MemoryApplier,
1184        root: NodeId,
1185        _viewport: Size,
1186    ) -> Result<(), Self::Error> {
1187        self.scene.clear();
1188        // Build scene in logical dp - scaling happens in GPU vertex upload
1189        // Traverse layout nodes via applier instead of rebuilding LayoutTree
1190        pipeline::render_from_applier(applier, root, &mut self.scene, 1.0);
1191        Ok(())
1192    }
1193
1194    fn draw_dev_overlay(&mut self, text: &str, viewport: Size) {
1195        const DEV_OVERLAY_NODE_ID: NodeId = NodeId::MAX;
1196        let padding = 8.0;
1197        let font_size = 14.0;
1198        let char_width = 7.0;
1199        let text_width = text.len() as f32 * char_width;
1200        let text_height = font_size * 1.4;
1201        let x = (viewport.width - text_width - padding * 2.0).max(padding);
1202        let y = padding;
1203
1204        let mut overlay_layer = LayerNode {
1205            node_id: Some(DEV_OVERLAY_NODE_ID),
1206            local_bounds: Rect {
1207                x: 0.0,
1208                y: 0.0,
1209                width: text_width + padding,
1210                height: text_height + padding / 2.0,
1211            },
1212            transform_to_parent: ProjectiveTransform::translation(x, y),
1213            motion_context_animated: false,
1214            translated_content_context: false,
1215            translated_content_offset: Point::default(),
1216            graphics_layer: GraphicsLayer::default(),
1217            clip_to_bounds: false,
1218            shadow_clip: None,
1219            hit_test: None,
1220            has_hit_targets: false,
1221            isolation: IsolationReasons::default(),
1222            cache_policy: CachePolicy::None,
1223            cache_hashes: LayerRasterCacheHashes::default(),
1224            cache_hashes_valid: false,
1225            children: vec![
1226                RenderNode::Primitive(PrimitiveEntry {
1227                    phase: PrimitivePhase::BeforeChildren,
1228                    node: PrimitiveNode::Draw(DrawPrimitiveNode {
1229                        primitive: DrawPrimitive::RoundRect {
1230                            rect: Rect {
1231                                x: 0.0,
1232                                y: 0.0,
1233                                width: text_width + padding,
1234                                height: text_height + padding / 2.0,
1235                            },
1236                            brush: Brush::Solid(Color(0.0, 0.0, 0.0, 0.7)),
1237                            radii: CornerRadii::uniform(4.0),
1238                        },
1239                        clip: None,
1240                    }),
1241                }),
1242                RenderNode::Primitive(PrimitiveEntry {
1243                    phase: PrimitivePhase::AfterChildren,
1244                    node: PrimitiveNode::Text(Box::new(TextPrimitiveNode {
1245                        node_id: DEV_OVERLAY_NODE_ID,
1246                        rect: Rect {
1247                            x: padding / 2.0,
1248                            y: padding / 4.0,
1249                            width: text_width,
1250                            height: text_height,
1251                        },
1252                        text: cranpose_ui::text::AnnotatedString::from(text),
1253                        text_style: cranpose_ui::TextStyle::default(),
1254                        font_size,
1255                        layout_options: cranpose_ui::TextLayoutOptions::default(),
1256                        clip: None,
1257                    })),
1258                }),
1259            ],
1260        };
1261        overlay_layer.recompute_raster_cache_hashes();
1262
1263        let graph = self.scene.graph.get_or_insert_with(|| {
1264            RenderGraph::new(LayerNode {
1265                node_id: None,
1266                local_bounds: Rect::from_size(viewport),
1267                transform_to_parent: ProjectiveTransform::identity(),
1268                motion_context_animated: false,
1269                translated_content_context: false,
1270                translated_content_offset: Point::default(),
1271                graphics_layer: GraphicsLayer::default(),
1272                clip_to_bounds: false,
1273                shadow_clip: None,
1274                hit_test: None,
1275                has_hit_targets: false,
1276                isolation: IsolationReasons::default(),
1277                cache_policy: CachePolicy::None,
1278                cache_hashes: LayerRasterCacheHashes::default(),
1279                cache_hashes_valid: false,
1280                children: Vec::new(),
1281            })
1282        });
1283
1284        graph.root.children.retain(|child| {
1285            !matches!(
1286                child,
1287                RenderNode::Layer(layer) if layer.node_id == Some(DEV_OVERLAY_NODE_ID)
1288            )
1289        });
1290        graph
1291            .root
1292            .children
1293            .push(RenderNode::Layer(Box::new(overlay_layer)));
1294        graph.root.recompute_raster_cache_hashes();
1295    }
1296}
1297
1298fn resolve_font_size(style: &cranpose_ui::text::TextStyle) -> f32 {
1299    style.resolve_font_size(14.0)
1300}
1301
1302fn resolve_line_height(style: &cranpose_ui::text::TextStyle, font_size: f32) -> f32 {
1303    style.resolve_line_height(14.0, font_size * 1.4)
1304}
1305
1306fn resolve_max_span_font_size(
1307    style: &cranpose_ui::text::TextStyle,
1308    text: &cranpose_ui::text::AnnotatedString,
1309    base_font_size: f32,
1310) -> f32 {
1311    if text.span_styles.is_empty() {
1312        return base_font_size;
1313    }
1314
1315    let mut max_font_size = base_font_size;
1316    for window in text.span_boundaries().windows(2) {
1317        let start = window[0];
1318        let end = window[1];
1319        if start == end {
1320            continue;
1321        }
1322
1323        let mut merged_span = style.span_style.clone();
1324        for span in &text.span_styles {
1325            if span.range.start <= start && span.range.end >= end {
1326                merged_span = merged_span.merge(&span.item);
1327            }
1328        }
1329        let mut chunk_style = style.clone();
1330        chunk_style.span_style = merged_span;
1331        max_font_size = max_font_size.max(chunk_style.resolve_font_size(base_font_size));
1332    }
1333    max_font_size
1334}
1335
1336pub(crate) fn resolve_effective_line_height(
1337    style: &cranpose_ui::text::TextStyle,
1338    text: &cranpose_ui::text::AnnotatedString,
1339    base_font_size: f32,
1340) -> f32 {
1341    let max_font_size = resolve_max_span_font_size(style, text, base_font_size);
1342    resolve_line_height(style, max_font_size)
1343}
1344
1345/// Returns true if the fontdb contains at least one italic (or oblique) face
1346/// whose family matches the given `FamilyOwned`.
1347fn family_has_italic_face(font_system: &FontSystem, family: &FamilyOwned) -> bool {
1348    let family_ref = family.as_family();
1349    let family_name = font_system.db().family_name(&family_ref);
1350    font_system.db().faces().any(|face| {
1351        (face.style == glyphon::fontdb::Style::Italic
1352            || face.style == glyphon::fontdb::Style::Oblique)
1353            && face
1354                .families
1355                .iter()
1356                .any(|(name, _)| name.eq_ignore_ascii_case(family_name))
1357    })
1358}
1359
1360fn attrs_from_text_style(
1361    style: &cranpose_ui::text::TextStyle,
1362    unscaled_base_font_size: f32,
1363    scale: f32,
1364    font_system: &mut FontSystem,
1365    font_family_resolver: &mut WgpuFontFamilyResolver,
1366) -> AttrsOwned {
1367    let mut attrs = Attrs::new();
1368    let span_style = &style.span_style;
1369    let font_weight = span_style.font_weight;
1370    let font_style = span_style.font_style;
1371    let letter_spacing = span_style.letter_spacing;
1372
1373    let unscaled_font_size = style.resolve_font_size(unscaled_base_font_size);
1374    let unscaled_line_height =
1375        style.resolve_line_height(unscaled_base_font_size, unscaled_font_size * 1.4);
1376
1377    let font_size_px = unscaled_font_size * scale;
1378    let line_height_px = unscaled_line_height * scale;
1379    attrs = attrs.metrics(glyphon::Metrics::new(font_size_px, line_height_px));
1380
1381    if let Some(color) = glyph_foreground_color(span_style) {
1382        let r = (color.0 * 255.0).clamp(0.0, 255.0) as u8;
1383        let g = (color.1 * 255.0).clamp(0.0, 255.0) as u8;
1384        let b = (color.2 * 255.0).clamp(0.0, 255.0) as u8;
1385        let a = (color.3 * 255.0).clamp(0.0, 255.0) as u8;
1386        attrs = attrs.color(glyphon::Color::rgba(r, g, b, a));
1387    }
1388
1389    let family_owned = font_family_resolver.resolve_family_owned(font_system, span_style);
1390    attrs = attrs.family(family_owned.as_family());
1391
1392    if let Some(font_weight) = font_weight {
1393        attrs = attrs.weight(GlyphonWeight(font_weight.0));
1394    }
1395
1396    // cosmic-text 0.15 does NOT synthesize italic automatically — it passes
1397    // cache_key_flags through as-is from attrs to glyphs.  We must decide here
1398    // whether to request a native italic face or to ask for synthetic skew.
1399    //
1400    // Strategy:
1401    //   • If the resolved family owns an italic face → set style=Italic so
1402    //     cosmic-text matches the real face.  No FAKE_ITALIC needed.
1403    //   • Otherwise → keep style=Normal (so font matching finds the Regular
1404    //     face) and set FAKE_ITALIC for the swash 14-degree skew.
1405    let mut flags = glyphon::cosmic_text::CacheKeyFlags::DISABLE_HINTING;
1406    if let Some(font_style) = font_style {
1407        match font_style {
1408            cranpose_ui::text::FontStyle::Normal => {}
1409            cranpose_ui::text::FontStyle::Italic => {
1410                if family_has_italic_face(font_system, &family_owned) {
1411                    attrs = attrs.style(GlyphonStyle::Italic);
1412                } else {
1413                    flags |= glyphon::cosmic_text::CacheKeyFlags::FAKE_ITALIC;
1414                }
1415            }
1416        }
1417    }
1418
1419    attrs = match letter_spacing {
1420        cranpose_ui::text::TextUnit::Em(value) => attrs.letter_spacing(value),
1421        cranpose_ui::text::TextUnit::Sp(value) if font_size_px > 0.0 => {
1422            attrs.letter_spacing((value * scale) / font_size_px)
1423        }
1424        _ => attrs,
1425    };
1426    attrs = attrs.cache_key_flags(flags);
1427
1428    AttrsOwned::new(&attrs)
1429}
1430
1431// Text measurer implementation for WGPU
1432
1433#[derive(Clone)]
1434struct WgpuTextMeasurer {
1435    text_state: SharedTextSystemState,
1436    size_cache: TextSizeCache,
1437    prepared_layout_cache: PreparedTextLayoutCache,
1438}
1439
1440impl WgpuTextMeasurer {
1441    fn new(text_state: SharedTextSystemState) -> Self {
1442        Self {
1443            text_state,
1444            // Larger cache size (1024) reduces misses, FxHasher for faster lookups
1445            size_cache: Arc::new(Mutex::new(LruCache::new(NonZeroUsize::new(1024).unwrap()))),
1446            prepared_layout_cache: Rc::new(RefCell::new(LruCache::new(
1447                NonZeroUsize::new(256).unwrap(),
1448            ))),
1449        }
1450    }
1451
1452    fn text_buffer_key(
1453        node_id: Option<NodeId>,
1454        text: &str,
1455        font_size: f32,
1456        style_hash: u64,
1457    ) -> TextCacheKey {
1458        match node_id {
1459            Some(node_id) => TextCacheKey::for_node(node_id, font_size, style_hash),
1460            None => TextCacheKey::new(text, font_size, style_hash),
1461        }
1462    }
1463
1464    fn try_measure_with_options_fast_path(
1465        &self,
1466        node_id: Option<NodeId>,
1467        text: &cranpose_ui::text::AnnotatedString,
1468        style: &cranpose_ui::text::TextStyle,
1469        options: cranpose_ui::text::TextLayoutOptions,
1470        max_width: Option<f32>,
1471    ) -> Option<cranpose_ui::TextMetrics> {
1472        let options = options.normalized();
1473        let max_width = max_width.filter(|w| w.is_finite() && *w > 0.0)?;
1474        if !Self::supports_fast_wrap_options(style, options) {
1475            return None;
1476        }
1477
1478        let text_str = text.text.as_str();
1479        let font_size = resolve_font_size(style);
1480        let line_height = resolve_effective_line_height(style, text, font_size);
1481        let size_style_hash = style.measurement_hash()
1482            ^ text.span_styles_hash()
1483            ^ (max_width.to_bits() as u64).rotate_left(17)
1484            ^ 0x9f4c_3314_2d5b_79e1;
1485        let buffer_style_hash = text_buffer_style_hash(style, text);
1486        let size_int = (font_size * 100.0) as i32;
1487
1488        let mut hasher = FxHasher::default();
1489        text_str.hash(&mut hasher);
1490        let text_hash = hasher.finish();
1491        let cache_key = (text_hash, size_int, size_style_hash);
1492
1493        {
1494            let mut cache = self.size_cache.lock().unwrap();
1495            if let Some((cached_text, size)) = cache.get(&cache_key) {
1496                if cached_text == text_str {
1497                    let width = size.width.min(max_width);
1498                    let min_height = options.min_lines as f32 * line_height;
1499                    let height = size.height.max(min_height);
1500                    let line_count =
1501                        ((height / line_height).ceil() as usize).max(options.min_lines);
1502                    return Some(cranpose_ui::TextMetrics {
1503                        width,
1504                        height,
1505                        line_height,
1506                        line_count,
1507                    });
1508                }
1509            }
1510        }
1511
1512        let text_buffer_key =
1513            Self::text_buffer_key(node_id, text_str, font_size, buffer_style_hash);
1514        let mut text_state = self.text_state.lock().unwrap();
1515        let (font_system, font_family_resolver, text_cache) = text_state.parts_mut();
1516
1517        let (size, wrapped_line_count) = {
1518            let (_, _, _, buffer) = shared_text_buffer_mut(
1519                text_cache,
1520                text_buffer_key,
1521                font_system,
1522                font_size,
1523                line_height,
1524            );
1525
1526            let _ = buffer.ensure(
1527                font_system,
1528                font_family_resolver,
1529                EnsureTextBufferParams {
1530                    annotated_text: text,
1531                    font_size_px: font_size,
1532                    line_height_px: line_height,
1533                    style_hash: buffer_style_hash,
1534                    style,
1535                    scale: 1.0,
1536                },
1537            );
1538
1539            buffer
1540                .buffer
1541                .set_size(font_system, Some(max_width), Some(f32::MAX));
1542            buffer.buffer.shape_until_scroll(font_system, false);
1543            buffer.cached_size = None;
1544            let size = buffer.size();
1545            let line_count = buffer.buffer.layout_runs().count();
1546            (size, line_count)
1547        };
1548        drop(text_state);
1549
1550        let mut size_cache = self.size_cache.lock().unwrap();
1551        size_cache.put(cache_key, (text_str.to_string(), size));
1552
1553        let width = size.width.min(max_width);
1554        let min_height = options.min_lines as f32 * line_height;
1555        let height = size.height.max(min_height);
1556        let line_count = wrapped_line_count.max(options.min_lines).max(1);
1557
1558        Some(cranpose_ui::TextMetrics {
1559            width,
1560            height,
1561            line_height,
1562            line_count,
1563        })
1564    }
1565
1566    fn try_prepare_with_options_fast_path(
1567        &self,
1568        node_id: Option<NodeId>,
1569        text: &cranpose_ui::text::AnnotatedString,
1570        style: &cranpose_ui::text::TextStyle,
1571        options: cranpose_ui::text::TextLayoutOptions,
1572        max_width: Option<f32>,
1573    ) -> Option<cranpose_ui::text::PreparedTextLayout> {
1574        let options = options.normalized();
1575        let max_width = max_width.filter(|w| w.is_finite() && *w > 0.0)?;
1576        if !Self::supports_fast_wrap_options(style, options) {
1577            return None;
1578        }
1579
1580        let text_str = text.text.as_str();
1581        let font_size = resolve_font_size(style);
1582        let line_height = resolve_effective_line_height(style, text, font_size);
1583        let style_hash = text_buffer_style_hash(style, text);
1584
1585        let text_buffer_key = Self::text_buffer_key(node_id, text_str, font_size, style_hash);
1586        let mut text_state = self.text_state.lock().unwrap();
1587        let (font_system, font_family_resolver, text_cache) = text_state.parts_mut();
1588
1589        let (size, wrapped_ranges) = {
1590            let (_, _, _, buffer) = shared_text_buffer_mut(
1591                text_cache,
1592                text_buffer_key,
1593                font_system,
1594                font_size,
1595                line_height,
1596            );
1597
1598            let _ = buffer.ensure(
1599                font_system,
1600                font_family_resolver,
1601                EnsureTextBufferParams {
1602                    annotated_text: text,
1603                    font_size_px: font_size,
1604                    line_height_px: line_height,
1605                    style_hash,
1606                    style,
1607                    scale: 1.0,
1608                },
1609            );
1610
1611            buffer
1612                .buffer
1613                .set_size(font_system, Some(max_width), Some(f32::MAX));
1614            buffer.buffer.shape_until_scroll(font_system, false);
1615            buffer.cached_size = None;
1616            let size = buffer.size();
1617            let wrapped_ranges = collect_wrapped_ranges(text_str, &buffer.buffer)?;
1618            (size, wrapped_ranges)
1619        };
1620
1621        let mut builder = cranpose_ui::text::AnnotatedString::builder();
1622        for (idx, (start, end)) in wrapped_ranges.iter().enumerate() {
1623            builder = builder.append_annotated_subsequence(text, *start..*end);
1624            if idx + 1 < wrapped_ranges.len() {
1625                builder = builder.append("\n");
1626            }
1627        }
1628        let wrapped_annotated = builder.to_annotated_string();
1629
1630        let line_count = wrapped_ranges.len().max(options.min_lines).max(1);
1631        let min_height = options.min_lines as f32 * line_height;
1632        let height = (line_count as f32 * line_height).max(min_height);
1633
1634        Some(cranpose_ui::text::PreparedTextLayout {
1635            text: wrapped_annotated,
1636            metrics: cranpose_ui::TextMetrics {
1637                width: size.width.min(max_width),
1638                height,
1639                line_height,
1640                line_count,
1641            },
1642            did_overflow: false,
1643        })
1644    }
1645
1646    fn supports_fast_wrap_options(
1647        style: &cranpose_ui::text::TextStyle,
1648        options: cranpose_ui::text::TextLayoutOptions,
1649    ) -> bool {
1650        if options.overflow != cranpose_ui::text::TextOverflow::Clip || !options.soft_wrap {
1651            return false;
1652        }
1653        if options.max_lines != usize::MAX {
1654            return false;
1655        }
1656
1657        let line_break = style
1658            .paragraph_style
1659            .line_break
1660            .take_or_else(|| cranpose_ui::text::LineBreak::Simple);
1661        let hyphens = style
1662            .paragraph_style
1663            .hyphens
1664            .take_or_else(|| cranpose_ui::text::Hyphens::None);
1665        line_break == cranpose_ui::text::LineBreak::Simple
1666            && hyphens == cranpose_ui::text::Hyphens::None
1667    }
1668}
1669
1670fn collect_wrapped_ranges(text: &str, buffer: &Buffer) -> Option<Vec<(usize, usize)>> {
1671    if text.is_empty() {
1672        return Some(vec![(0, 0)]);
1673    }
1674
1675    let text_lines: Vec<&str> = text.split('\n').collect();
1676    let line_offsets: Vec<(usize, usize)> = text_lines
1677        .iter()
1678        .scan(0usize, |line_start, line| {
1679            let start = *line_start;
1680            let end = start + line.len();
1681            *line_start = end.saturating_add(1);
1682            Some((start, end))
1683        })
1684        .collect();
1685
1686    let mut wrapped_ranges = Vec::new();
1687    for run in buffer.layout_runs() {
1688        let (line_start, line_end) = line_offsets
1689            .get(run.line_i)
1690            .copied()
1691            .unwrap_or((0usize, text.len()));
1692        let line_len = line_end.saturating_sub(line_start);
1693
1694        if run.glyphs.is_empty() {
1695            wrapped_ranges.push((line_start, line_start));
1696            continue;
1697        }
1698
1699        let mut local_start = line_len;
1700        let mut local_end = 0usize;
1701        for glyph in run.glyphs.iter() {
1702            local_start = local_start.min(glyph.start.min(line_len));
1703            local_end = local_end.max(glyph.end.min(line_len));
1704        }
1705
1706        let range_start = line_start.saturating_add(local_start.min(line_len));
1707        let range_end = line_start.saturating_add(local_end.min(line_len));
1708        if range_start > range_end
1709            || range_end > text.len()
1710            || !text.is_char_boundary(range_start)
1711            || !text.is_char_boundary(range_end)
1712        {
1713            return None;
1714        }
1715        wrapped_ranges.push((range_start, range_end));
1716    }
1717
1718    if wrapped_ranges.is_empty() {
1719        Some(vec![(0, text.len())])
1720    } else {
1721        Some(wrapped_ranges)
1722    }
1723}
1724
1725/// Convenience function for tests to initialize an accurate wgpu text measurer without launching a window.
1726pub fn setup_headless_text_measurer() {
1727    let mut font_system = FontSystem::new();
1728    let mut font_family_resolver_impl = WgpuFontFamilyResolver::default();
1729    font_family_resolver_impl.prime(&mut font_system);
1730    let text_state = Arc::new(Mutex::new(TextSystemState::from_parts(
1731        font_system,
1732        font_family_resolver_impl,
1733    )));
1734    cranpose_ui::text::set_text_measurer(WgpuTextMeasurer::new(text_state));
1735}
1736
1737// Base font size in logical units (dp) - shared between measurement and rendering
1738
1739impl TextMeasurer for WgpuTextMeasurer {
1740    fn measure(
1741        &self,
1742        text: &cranpose_ui::text::AnnotatedString,
1743        style: &cranpose_ui::text::TextStyle,
1744    ) -> cranpose_ui::TextMetrics {
1745        self.measure_for_node(None, text, style)
1746    }
1747
1748    fn measure_for_node(
1749        &self,
1750        node_id: Option<NodeId>,
1751        text: &cranpose_ui::text::AnnotatedString,
1752        style: &cranpose_ui::text::TextStyle,
1753    ) -> cranpose_ui::TextMetrics {
1754        let telemetry = text_measure_telemetry_enabled().then_some(text_measure_telemetry());
1755        let telemetry_sequence = telemetry
1756            .map(|t| t.measure_calls.fetch_add(1, Ordering::Relaxed) + 1)
1757            .unwrap_or(0);
1758        let text_str = text.text.as_str();
1759        let font_size = resolve_font_size(style);
1760        let line_height = resolve_effective_line_height(style, text, font_size);
1761        let size_style_hash = style.measurement_hash() ^ text.span_styles_hash();
1762        let buffer_style_hash = text_buffer_style_hash(style, text);
1763        let size_int = (font_size * 100.0) as i32;
1764
1765        // Calculate hash to avoid allocating String for lookup
1766        // FxHasher is ~3x faster than DefaultHasher for short strings
1767        let mut hasher = FxHasher::default();
1768        text_str.hash(&mut hasher);
1769        let text_hash = hasher.finish();
1770        let cache_key = (text_hash, size_int, size_style_hash);
1771
1772        // Check size cache first (fastest path)
1773        {
1774            let mut cache = self.size_cache.lock().unwrap();
1775            if let Some((cached_text, size)) = cache.get(&cache_key) {
1776                // Verify partial collision
1777                if cached_text == text_str {
1778                    if let Some(t) = telemetry {
1779                        t.size_cache_hits.fetch_add(1, Ordering::Relaxed);
1780                        maybe_report_text_measure_telemetry(telemetry_sequence);
1781                    }
1782                    let line_count = text_str.split('\n').count().max(1);
1783                    return cranpose_ui::TextMetrics {
1784                        width: size.width,
1785                        height: size.height,
1786                        line_height,
1787                        line_count,
1788                    };
1789                }
1790            }
1791        }
1792        if let Some(t) = telemetry {
1793            t.size_cache_misses.fetch_add(1, Ordering::Relaxed);
1794        }
1795
1796        // Get or create text buffer
1797        let text_buffer_key =
1798            Self::text_buffer_key(node_id, text_str, font_size, buffer_style_hash);
1799        let mut text_state = self.text_state.lock().unwrap();
1800        let (font_system, font_family_resolver, text_cache) = text_state.parts_mut();
1801
1802        // Get or create buffer and calculate size
1803        let size = {
1804            let (text_cache_hit, evicted, cache_len, buffer) = shared_text_buffer_mut(
1805                text_cache,
1806                text_buffer_key,
1807                font_system,
1808                font_size,
1809                line_height,
1810            );
1811            if let Some(t) = telemetry {
1812                if text_cache_hit {
1813                    t.text_cache_hits.fetch_add(1, Ordering::Relaxed);
1814                } else {
1815                    t.text_cache_misses.fetch_add(1, Ordering::Relaxed);
1816                }
1817                if evicted {
1818                    t.text_cache_evictions.fetch_add(1, Ordering::Relaxed);
1819                }
1820                t.text_cache_occupancy
1821                    .store(cache_len as u64, Ordering::Relaxed);
1822            }
1823
1824            // Ensure buffer has the correct text
1825            let reshaped = buffer.ensure(
1826                font_system,
1827                font_family_resolver,
1828                EnsureTextBufferParams {
1829                    annotated_text: text,
1830                    font_size_px: font_size,
1831                    line_height_px: line_height,
1832                    style_hash: buffer_style_hash,
1833                    style,
1834                    scale: 1.0,
1835                },
1836            );
1837            if let Some(t) = telemetry {
1838                if reshaped {
1839                    t.ensure_reshapes.fetch_add(1, Ordering::Relaxed);
1840                } else {
1841                    t.ensure_reuses.fetch_add(1, Ordering::Relaxed);
1842                }
1843            }
1844
1845            // Calculate size if not cached
1846            buffer.size()
1847        };
1848
1849        drop(text_state);
1850
1851        // Cache the size result
1852        let mut size_cache = self.size_cache.lock().unwrap();
1853        // Only allocate string on cache miss
1854        size_cache.put(cache_key, (text_str.to_string(), size));
1855
1856        // Calculate line info for multiline support
1857        let line_count = text_str.split('\n').count().max(1);
1858        if telemetry.is_some() {
1859            maybe_report_text_measure_telemetry(telemetry_sequence);
1860        }
1861
1862        cranpose_ui::TextMetrics {
1863            width: size.width,
1864            height: size.height,
1865            line_height,
1866            line_count,
1867        }
1868    }
1869
1870    fn measure_with_options(
1871        &self,
1872        text: &cranpose_ui::text::AnnotatedString,
1873        style: &cranpose_ui::text::TextStyle,
1874        options: cranpose_ui::text::TextLayoutOptions,
1875        max_width: Option<f32>,
1876    ) -> cranpose_ui::TextMetrics {
1877        self.measure_with_options_for_node(None, text, style, options, max_width)
1878    }
1879
1880    fn measure_with_options_for_node(
1881        &self,
1882        node_id: Option<NodeId>,
1883        text: &cranpose_ui::text::AnnotatedString,
1884        style: &cranpose_ui::text::TextStyle,
1885        options: cranpose_ui::text::TextLayoutOptions,
1886        max_width: Option<f32>,
1887    ) -> cranpose_ui::TextMetrics {
1888        let telemetry = text_measure_telemetry_enabled().then_some(text_measure_telemetry());
1889        let telemetry_sequence = telemetry
1890            .map(|t| t.measure_with_options_calls.fetch_add(1, Ordering::Relaxed) + 1)
1891            .unwrap_or(0);
1892        if let Some(metrics) =
1893            self.try_measure_with_options_fast_path(node_id, text, style, options, max_width)
1894        {
1895            if let Some(t) = telemetry {
1896                t.measure_fast_path_hits.fetch_add(1, Ordering::Relaxed);
1897                maybe_report_text_measure_telemetry(telemetry_sequence);
1898            }
1899            return metrics;
1900        }
1901        if let Some(t) = telemetry {
1902            t.measure_fast_path_misses.fetch_add(1, Ordering::Relaxed);
1903            maybe_report_text_measure_telemetry(telemetry_sequence);
1904        }
1905        self.prepare_with_options_for_node(node_id, text, style, options, max_width)
1906            .metrics
1907    }
1908
1909    fn prepare_with_options(
1910        &self,
1911        text: &cranpose_ui::text::AnnotatedString,
1912        style: &cranpose_ui::text::TextStyle,
1913        options: cranpose_ui::text::TextLayoutOptions,
1914        max_width: Option<f32>,
1915    ) -> cranpose_ui::text::PreparedTextLayout {
1916        self.prepare_with_options_for_node(None, text, style, options, max_width)
1917    }
1918
1919    fn prepare_with_options_for_node(
1920        &self,
1921        node_id: Option<NodeId>,
1922        text: &cranpose_ui::text::AnnotatedString,
1923        style: &cranpose_ui::text::TextStyle,
1924        options: cranpose_ui::text::TextLayoutOptions,
1925        max_width: Option<f32>,
1926    ) -> cranpose_ui::text::PreparedTextLayout {
1927        let telemetry = text_measure_telemetry_enabled().then_some(text_measure_telemetry());
1928        let telemetry_sequence = telemetry
1929            .map(|t| t.prepare_with_options_calls.fetch_add(1, Ordering::Relaxed) + 1)
1930            .unwrap_or(0);
1931        let normalized_options = options.normalized();
1932        let normalized_max_width = max_width.filter(|w| w.is_finite() && *w > 0.0);
1933        let text_str = text.text.as_str();
1934        let font_size = resolve_font_size(style);
1935        let style_hash = text_buffer_style_hash(style, text);
1936        let size_int = (font_size * 100.0) as i32;
1937
1938        let mut hasher = FxHasher::default();
1939        text_str.hash(&mut hasher);
1940        let text_hash = hasher.finish();
1941        let cache_key = PreparedTextLayoutCacheKey {
1942            text_hash,
1943            size_int,
1944            style_hash,
1945            options: normalized_options,
1946            max_width_bits: normalized_max_width.map(f32::to_bits),
1947        };
1948
1949        {
1950            let mut cache = self.prepared_layout_cache.borrow_mut();
1951            if let Some((cached_text, prepared)) = cache.get(&cache_key) {
1952                if cached_text == text_str {
1953                    if let Some(t) = telemetry {
1954                        t.prepared_layout_cache_hits.fetch_add(1, Ordering::Relaxed);
1955                        maybe_report_text_measure_telemetry(telemetry_sequence);
1956                    }
1957                    return prepared.clone();
1958                }
1959            }
1960        }
1961        if let Some(t) = telemetry {
1962            t.prepared_layout_cache_misses
1963                .fetch_add(1, Ordering::Relaxed);
1964        }
1965
1966        let prepared = if let Some(prepared) = self.try_prepare_with_options_fast_path(
1967            node_id,
1968            text,
1969            style,
1970            normalized_options,
1971            normalized_max_width,
1972        ) {
1973            if let Some(t) = telemetry {
1974                t.prepare_fast_path_hits.fetch_add(1, Ordering::Relaxed);
1975            }
1976            prepared
1977        } else {
1978            if let Some(t) = telemetry {
1979                t.prepare_fast_path_misses.fetch_add(1, Ordering::Relaxed);
1980            }
1981            cranpose_ui::text::measure::prepare_text_layout_with_measurer_for_node(
1982                self,
1983                node_id,
1984                text,
1985                style,
1986                normalized_options,
1987                normalized_max_width,
1988            )
1989        };
1990
1991        let mut cache = self.prepared_layout_cache.borrow_mut();
1992        cache.put(cache_key, (text_str.to_string(), prepared.clone()));
1993        if telemetry.is_some() {
1994            maybe_report_text_measure_telemetry(telemetry_sequence);
1995        }
1996
1997        prepared
1998    }
1999
2000    fn get_offset_for_position(
2001        &self,
2002        text: &cranpose_ui::text::AnnotatedString,
2003        style: &cranpose_ui::text::TextStyle,
2004        x: f32,
2005        y: f32,
2006    ) -> usize {
2007        let telemetry = text_measure_telemetry_enabled().then_some(text_measure_telemetry());
2008        let telemetry_sequence = telemetry
2009            .map(|t| t.offset_calls.fetch_add(1, Ordering::Relaxed) + 1)
2010            .unwrap_or(0);
2011        let text_str = text.text.as_str();
2012        let font_size = resolve_font_size(style);
2013        let line_height = resolve_effective_line_height(style, text, font_size);
2014        let style_hash = text_buffer_style_hash(style, text);
2015        if text_str.is_empty() {
2016            return 0;
2017        }
2018
2019        let cache_key = TextCacheKey::new(text_str, font_size, style_hash);
2020
2021        let mut text_state = self.text_state.lock().unwrap();
2022        let (font_system, font_family_resolver, text_cache) = text_state.parts_mut();
2023
2024        let (text_cache_hit, evicted, cache_len, buffer) =
2025            shared_text_buffer_mut(text_cache, cache_key, font_system, font_size, line_height);
2026        if let Some(t) = telemetry {
2027            if text_cache_hit {
2028                t.text_cache_hits.fetch_add(1, Ordering::Relaxed);
2029            } else {
2030                t.text_cache_misses.fetch_add(1, Ordering::Relaxed);
2031            }
2032            if evicted {
2033                t.text_cache_evictions.fetch_add(1, Ordering::Relaxed);
2034            }
2035            t.text_cache_occupancy
2036                .store(cache_len as u64, Ordering::Relaxed);
2037        }
2038
2039        let reshaped = buffer.ensure(
2040            font_system,
2041            font_family_resolver,
2042            EnsureTextBufferParams {
2043                annotated_text: text,
2044                font_size_px: font_size,
2045                line_height_px: line_height,
2046                style_hash,
2047                style,
2048                scale: 1.0,
2049            },
2050        );
2051        if let Some(t) = telemetry {
2052            if reshaped {
2053                t.ensure_reshapes.fetch_add(1, Ordering::Relaxed);
2054            } else {
2055                t.ensure_reuses.fetch_add(1, Ordering::Relaxed);
2056            }
2057            maybe_report_text_measure_telemetry(telemetry_sequence);
2058        }
2059
2060        let line_offsets: Vec<(usize, usize)> = text_str
2061            .split('\n')
2062            .scan(0usize, |line_start, line| {
2063                let start = *line_start;
2064                let end = start + line.len();
2065                *line_start = end.saturating_add(1);
2066                Some((start, end))
2067            })
2068            .collect();
2069
2070        let mut target_line = None;
2071        let mut best_vertical_distance = f32::INFINITY;
2072
2073        for run in buffer.buffer.layout_runs() {
2074            let mut run_height = run.line_height;
2075            for glyph in run.glyphs.iter() {
2076                run_height = run_height.max(glyph.font_size * 1.4);
2077            }
2078
2079            let top = run.line_top;
2080            let bottom = top + run_height.max(1.0);
2081            let vertical_distance = if y < top {
2082                top - y
2083            } else if y > bottom {
2084                y - bottom
2085            } else {
2086                0.0
2087            };
2088
2089            if vertical_distance < best_vertical_distance {
2090                best_vertical_distance = vertical_distance;
2091                target_line = Some(run.line_i);
2092                if vertical_distance == 0.0 {
2093                    break;
2094                }
2095            }
2096        }
2097
2098        let fallback_line = (y / line_height).floor().max(0.0) as usize;
2099        let target_line = target_line
2100            .unwrap_or(fallback_line)
2101            .min(line_offsets.len().saturating_sub(1));
2102        let (line_start, line_end) = line_offsets
2103            .get(target_line)
2104            .copied()
2105            .unwrap_or((0, text_str.len()));
2106        let line_len = line_end.saturating_sub(line_start);
2107
2108        let mut best_offset = line_offsets
2109            .get(target_line)
2110            .map(|(_, end)| *end)
2111            .unwrap_or(text_str.len());
2112        let mut best_distance = f32::INFINITY;
2113        let mut found_glyph = false;
2114
2115        for run in buffer.buffer.layout_runs() {
2116            if run.line_i != target_line {
2117                continue;
2118            }
2119            for glyph in run.glyphs.iter() {
2120                found_glyph = true;
2121                let glyph_start = line_start.saturating_add(glyph.start.min(line_len));
2122                let glyph_end = line_start.saturating_add(glyph.end.min(line_len));
2123                let left_dist = (x - glyph.x).abs();
2124                if left_dist < best_distance {
2125                    best_distance = left_dist;
2126                    best_offset = glyph_start;
2127                }
2128
2129                let right_x = glyph.x + glyph.w;
2130                let right_dist = (x - right_x).abs();
2131                if right_dist < best_distance {
2132                    best_distance = right_dist;
2133                    best_offset = glyph_end;
2134                }
2135            }
2136        }
2137
2138        if !found_glyph {
2139            if let Some((start, end)) = line_offsets.get(target_line) {
2140                best_offset = if x <= 0.0 { *start } else { *end };
2141            }
2142        }
2143
2144        best_offset.min(text_str.len())
2145    }
2146
2147    fn get_cursor_x_for_offset(
2148        &self,
2149        text: &cranpose_ui::text::AnnotatedString,
2150        style: &cranpose_ui::text::TextStyle,
2151        offset: usize,
2152    ) -> f32 {
2153        let text = text.text.as_str();
2154        let clamped_offset = offset.min(text.len());
2155        if clamped_offset == 0 {
2156            return 0.0;
2157        }
2158
2159        // Measure text up to offset
2160        let prefix = &text[..clamped_offset];
2161        self.measure(&cranpose_ui::text::AnnotatedString::from(prefix), style)
2162            .width
2163    }
2164
2165    fn choose_auto_hyphen_break(
2166        &self,
2167        line: &str,
2168        style: &cranpose_ui::text::TextStyle,
2169        segment_start_char: usize,
2170        measured_break_char: usize,
2171    ) -> Option<usize> {
2172        choose_shared_auto_hyphen_break(line, style, segment_start_char, measured_break_char)
2173    }
2174
2175    fn layout(
2176        &self,
2177        text: &cranpose_ui::text::AnnotatedString,
2178        style: &cranpose_ui::text::TextStyle,
2179    ) -> cranpose_ui::text_layout_result::TextLayoutResult {
2180        let telemetry = text_measure_telemetry_enabled().then_some(text_measure_telemetry());
2181        let telemetry_sequence = telemetry
2182            .map(|t| t.layout_calls.fetch_add(1, Ordering::Relaxed) + 1)
2183            .unwrap_or(0);
2184        let text_str = text.text.as_str();
2185        use cranpose_ui::text_layout_result::{
2186            GlyphLayout, LineLayout, TextLayoutData, TextLayoutResult,
2187        };
2188
2189        let font_size = resolve_font_size(style);
2190        let line_height = resolve_effective_line_height(style, text, font_size);
2191        let style_hash = text_buffer_style_hash(style, text);
2192
2193        let cache_key = TextCacheKey::new(text_str, font_size, style_hash);
2194        let mut text_state = self.text_state.lock().unwrap();
2195        let (font_system, font_family_resolver, text_cache) = text_state.parts_mut();
2196
2197        let (text_cache_hit, evicted, cache_len, buffer) = shared_text_buffer_mut(
2198            text_cache,
2199            cache_key.clone(),
2200            font_system,
2201            font_size,
2202            line_height,
2203        );
2204        if let Some(t) = telemetry {
2205            if text_cache_hit {
2206                t.text_cache_hits.fetch_add(1, Ordering::Relaxed);
2207            } else {
2208                t.text_cache_misses.fetch_add(1, Ordering::Relaxed);
2209            }
2210            if evicted {
2211                t.text_cache_evictions.fetch_add(1, Ordering::Relaxed);
2212            }
2213            t.text_cache_occupancy
2214                .store(cache_len as u64, Ordering::Relaxed);
2215        }
2216        let reshaped = buffer.ensure(
2217            font_system,
2218            font_family_resolver,
2219            EnsureTextBufferParams {
2220                annotated_text: text,
2221                font_size_px: font_size,
2222                line_height_px: line_height,
2223                style_hash,
2224                style,
2225                scale: 1.0,
2226            },
2227        );
2228        if let Some(t) = telemetry {
2229            if reshaped {
2230                t.ensure_reshapes.fetch_add(1, Ordering::Relaxed);
2231            } else {
2232                t.ensure_reuses.fetch_add(1, Ordering::Relaxed);
2233            }
2234            maybe_report_text_measure_telemetry(telemetry_sequence);
2235        }
2236        let measured_size = buffer.size();
2237
2238        // Extract glyph positions from layout runs
2239        let mut glyph_x_positions = Vec::new();
2240        let mut char_to_byte = Vec::new();
2241        let mut glyph_layouts = Vec::new();
2242        let mut lines = Vec::new();
2243        let text_lines: Vec<&str> = text_str.split('\n').collect();
2244        let line_offsets: Vec<(usize, usize)> = text_lines
2245            .iter()
2246            .scan(0usize, |line_start, line| {
2247                let start = *line_start;
2248                let end = start + line.len();
2249                *line_start = end.saturating_add(1);
2250                Some((start, end))
2251            })
2252            .collect();
2253
2254        for run in buffer.buffer.layout_runs() {
2255            let line_idx = run.line_i;
2256            let run_height = run
2257                .glyphs
2258                .iter()
2259                .fold(run.line_height, |acc, glyph| acc.max(glyph.font_size * 1.4))
2260                .max(1.0);
2261
2262            for glyph in run.glyphs.iter() {
2263                let (line_start, line_end) = line_offsets
2264                    .get(line_idx)
2265                    .copied()
2266                    .unwrap_or((0, text_str.len()));
2267                let line_len = line_end.saturating_sub(line_start);
2268                let glyph_start = line_start.saturating_add(glyph.start.min(line_len));
2269                let glyph_end = line_start.saturating_add(glyph.end.min(line_len));
2270
2271                glyph_x_positions.push(glyph.x);
2272                char_to_byte.push(glyph_start);
2273                if glyph_end > glyph_start {
2274                    glyph_layouts.push(GlyphLayout {
2275                        line_index: line_idx,
2276                        start_offset: glyph_start,
2277                        end_offset: glyph_end,
2278                        x: glyph.x,
2279                        y: run.line_top,
2280                        width: glyph.w.max(0.0),
2281                        height: run_height,
2282                    });
2283                }
2284            }
2285        }
2286
2287        // Add end position
2288        glyph_x_positions.push(measured_size.width);
2289        char_to_byte.push(text_str.len());
2290
2291        // Build lines from text newlines
2292        let mut y = 0.0f32;
2293        let mut line_start = 0usize;
2294        for (i, line_text) in text_lines.iter().enumerate() {
2295            let line_end = if i == text_lines.len() - 1 {
2296                text_str.len()
2297            } else {
2298                line_start + line_text.len()
2299            };
2300
2301            lines.push(LineLayout {
2302                start_offset: line_start,
2303                end_offset: line_end,
2304                y,
2305                height: line_height,
2306            });
2307
2308            line_start = line_end + 1;
2309            y += line_height;
2310        }
2311
2312        if lines.is_empty() {
2313            lines.push(LineLayout {
2314                start_offset: 0,
2315                end_offset: 0,
2316                y: 0.0,
2317                height: line_height,
2318            });
2319        }
2320
2321        let metrics = cranpose_ui::TextMetrics {
2322            width: measured_size.width,
2323            height: measured_size.height,
2324            line_height,
2325            line_count: text_lines.len().max(1),
2326        };
2327        TextLayoutResult::new(
2328            text_str,
2329            TextLayoutData {
2330                width: metrics.width,
2331                height: metrics.height,
2332                line_height,
2333                glyph_x_positions,
2334                char_to_byte,
2335                lines,
2336                glyph_layouts,
2337            },
2338        )
2339    }
2340}
2341
2342#[cfg(test)]
2343mod tests {
2344    use super::*;
2345    use std::sync::mpsc;
2346    use std::time::Duration;
2347
2348    const WORKER_TEST_TIMEOUT_SECS: u64 = 15;
2349
2350    fn seeded_font_system_and_resolver() -> (FontSystem, WgpuFontFamilyResolver) {
2351        let mut db = glyphon::fontdb::Database::new();
2352        db.load_font_data(TEST_FONT.to_vec());
2353        let mut font_system = FontSystem::new_with_locale_and_db("en-US".to_string(), db);
2354        let mut resolver = WgpuFontFamilyResolver::default();
2355        resolver.prime(&mut font_system);
2356        (font_system, resolver)
2357    }
2358
2359    fn seeded_text_state() -> SharedTextSystemState {
2360        let (font_system, resolver) = seeded_font_system_and_resolver();
2361        Arc::new(Mutex::new(TextSystemState::from_parts(
2362            font_system,
2363            resolver,
2364        )))
2365    }
2366
2367    #[test]
2368    fn attrs_resolution_falls_back_for_missing_named_family() {
2369        let (mut font_system, mut resolver) = seeded_font_system_and_resolver();
2370        let style = cranpose_ui::text::TextStyle {
2371            span_style: cranpose_ui::text::SpanStyle {
2372                font_family: Some(cranpose_ui::text::FontFamily::named("Missing Family Name")),
2373                ..Default::default()
2374            },
2375            ..Default::default()
2376        };
2377
2378        let attrs = attrs_from_text_style(&style, 14.0, 1.0, &mut font_system, &mut resolver);
2379        assert_eq!(attrs.family_owned, FamilyOwned::SansSerif);
2380    }
2381
2382    #[test]
2383    fn attrs_resolution_seeds_generic_families_from_loaded_fonts() {
2384        let (font_system, resolver) = seeded_font_system_and_resolver();
2385        assert!(
2386            resolver.generic_fallback_seeded,
2387            "expected generic fallback seeding after resolver prime"
2388        );
2389        let query = glyphon::fontdb::Query {
2390            families: &[glyphon::fontdb::Family::Monospace],
2391            weight: glyphon::fontdb::Weight::NORMAL,
2392            stretch: glyphon::fontdb::Stretch::Normal,
2393            style: glyphon::fontdb::Style::Normal,
2394        };
2395        assert!(
2396            font_system.db().query(&query).is_some(),
2397            "generic monospace query should resolve after fallback seeding"
2398        );
2399    }
2400
2401    #[test]
2402    fn attrs_resolution_named_family_lookup_is_case_insensitive() {
2403        let (mut font_system, mut resolver) = seeded_font_system_and_resolver();
2404        let style = cranpose_ui::text::TextStyle {
2405            span_style: cranpose_ui::text::SpanStyle {
2406                font_family: Some(cranpose_ui::text::FontFamily::named("noto sans")),
2407                ..Default::default()
2408            },
2409            ..Default::default()
2410        };
2411
2412        let attrs = attrs_from_text_style(&style, 14.0, 1.0, &mut font_system, &mut resolver);
2413        assert!(
2414            matches!(attrs.family_owned, FamilyOwned::Name(_)),
2415            "case-insensitive family lookup should resolve to a concrete family name"
2416        );
2417    }
2418
2419    #[test]
2420    fn attrs_resolution_synthesizes_italic_when_no_italic_face_available() {
2421        let (mut font_system, mut resolver) = seeded_font_system_and_resolver();
2422        let style = cranpose_ui::text::TextStyle {
2423            span_style: cranpose_ui::text::SpanStyle {
2424                font_family: Some(cranpose_ui::text::FontFamily::named("Noto Sans")),
2425                font_style: Some(cranpose_ui::text::FontStyle::Italic),
2426                ..Default::default()
2427            },
2428            ..Default::default()
2429        };
2430
2431        let attrs = attrs_from_text_style(&style, 14.0, 1.0, &mut font_system, &mut resolver);
2432        // Noto Sans (test font) has no italic face → style stays Normal,
2433        // FAKE_ITALIC is set so the swash renderer applies 14° skew.
2434        assert_eq!(
2435            attrs.style,
2436            GlyphonStyle::Normal,
2437            "style must stay Normal for font matching when no italic face exists"
2438        );
2439        assert!(
2440            attrs
2441                .cache_key_flags
2442                .contains(glyphon::cosmic_text::CacheKeyFlags::FAKE_ITALIC),
2443            "FAKE_ITALIC must be set when the font family lacks a native italic face"
2444        );
2445    }
2446
2447    #[test]
2448    fn attrs_resolution_preserves_requested_bold_for_synthesis() {
2449        let (mut font_system, mut resolver) = seeded_font_system_and_resolver();
2450        let style = cranpose_ui::text::TextStyle {
2451            span_style: cranpose_ui::text::SpanStyle {
2452                font_family: Some(cranpose_ui::text::FontFamily::named("Noto Sans")),
2453                font_weight: Some(cranpose_ui::text::FontWeight::BOLD),
2454                ..Default::default()
2455            },
2456            ..Default::default()
2457        };
2458
2459        let attrs = attrs_from_text_style(&style, 14.0, 1.0, &mut font_system, &mut resolver);
2460        assert_eq!(
2461            attrs.weight,
2462            GlyphonWeight(cranpose_ui::text::FontWeight::BOLD.0),
2463            "requested bold must be preserved in attrs so glyphon can synthesize it"
2464        );
2465    }
2466
2467    #[test]
2468    fn span_level_italic_propagates_through_rich_text_ensure() {
2469        let (mut font_system, mut resolver) = seeded_font_system_and_resolver();
2470        let mut text = cranpose_ui::text::AnnotatedString::from("normal italic");
2471        text.span_styles.push(cranpose_ui::text::RangeStyle {
2472            item: cranpose_ui::text::SpanStyle {
2473                font_style: Some(cranpose_ui::text::FontStyle::Italic),
2474                ..Default::default()
2475            },
2476            range: 7..13, // "italic"
2477        });
2478        let style = cranpose_ui::text::TextStyle::default();
2479        let style_hash = text_buffer_style_hash(&style, &text);
2480        let mut buffer = new_shared_text_buffer(&mut font_system, 14.0, 14.0 * 1.4);
2481        buffer.ensure(
2482            &mut font_system,
2483            &mut resolver,
2484            EnsureTextBufferParams {
2485                annotated_text: &text,
2486                font_size_px: 14.0,
2487                line_height_px: 14.0 * 1.4,
2488                style_hash,
2489                style: &style,
2490                scale: 1.0,
2491            },
2492        );
2493        // Check that the buffer's layout lines have FAKE_ITALIC flag on the italic span
2494        let has_fake_italic = buffer.buffer.layout_runs().any(|run| {
2495            run.glyphs.iter().any(|glyph| {
2496                glyph.start >= 7
2497                    && glyph
2498                        .cache_key_flags
2499                        .contains(glyphon::cosmic_text::CacheKeyFlags::FAKE_ITALIC)
2500            })
2501        });
2502        assert!(
2503            has_fake_italic,
2504            "span-level italic must produce FAKE_ITALIC glyphs when the font lacks native italic"
2505        );
2506    }
2507
2508    #[test]
2509    fn bold_text_uses_bold_font_face_when_available() {
2510        let mut db = glyphon::fontdb::Database::new();
2511        db.load_font_data(TEST_FONT.to_vec());
2512        db.load_font_data(TEST_BOLD_FONT.to_vec());
2513        let mut font_system = FontSystem::new_with_locale_and_db("en-US".to_string(), db);
2514        let mut resolver = WgpuFontFamilyResolver::default();
2515        resolver.prime(&mut font_system);
2516
2517        let style = cranpose_ui::text::TextStyle {
2518            span_style: cranpose_ui::text::SpanStyle {
2519                font_weight: Some(cranpose_ui::text::FontWeight::BOLD),
2520                ..Default::default()
2521            },
2522            ..Default::default()
2523        };
2524        let text = cranpose_ui::text::AnnotatedString::from("bold text");
2525        let style_hash = text_buffer_style_hash(&style, &text);
2526        let mut buffer = new_shared_text_buffer(&mut font_system, 14.0, 14.0 * 1.4);
2527        buffer.ensure(
2528            &mut font_system,
2529            &mut resolver,
2530            EnsureTextBufferParams {
2531                annotated_text: &text,
2532                font_size_px: 14.0,
2533                line_height_px: 14.0 * 1.4,
2534                style_hash,
2535                style: &style,
2536                scale: 1.0,
2537            },
2538        );
2539        let bold_face_used = buffer.buffer.layout_runs().any(|run| {
2540            run.glyphs.iter().any(|glyph| {
2541                font_system
2542                    .db()
2543                    .face(glyph.font_id)
2544                    .is_some_and(|face| face.weight.0 == 700)
2545            })
2546        });
2547        assert!(
2548            bold_face_used,
2549            "bold text must use the bold font face (weight 700) when available"
2550        );
2551    }
2552
2553    #[test]
2554    fn attrs_from_text_style_applies_alpha_to_foreground_color() {
2555        let (mut font_system, mut resolver) = seeded_font_system_and_resolver();
2556        let style = cranpose_ui::text::TextStyle::from_span_style(cranpose_ui::text::SpanStyle {
2557            color: Some(cranpose_ui::Color(0.2, 0.4, 0.6, 1.0)),
2558            alpha: Some(0.25),
2559            ..Default::default()
2560        });
2561
2562        let attrs = attrs_from_text_style(&style, 14.0, 1.0, &mut font_system, &mut resolver);
2563
2564        assert_eq!(
2565            attrs.color_opt,
2566            Some(glyphon::Color::rgba(51, 102, 153, 63)),
2567            "glyph attrs must track alpha-adjusted foreground color"
2568        );
2569    }
2570
2571    #[test]
2572    fn attrs_from_text_style_disables_native_hinting() {
2573        let (mut font_system, mut resolver) = seeded_font_system_and_resolver();
2574        let attrs = attrs_from_text_style(
2575            &cranpose_ui::text::TextStyle::default(),
2576            14.0,
2577            1.0,
2578            &mut font_system,
2579            &mut resolver,
2580        );
2581
2582        assert!(
2583            attrs
2584                .cache_key_flags
2585                .contains(glyphon::cosmic_text::CacheKeyFlags::DISABLE_HINTING),
2586            "renderer text attrs should disable native hinting to keep glyph rasterization stable across scroll phases"
2587        );
2588    }
2589
2590    #[test]
2591    fn text_buffer_style_hash_changes_when_top_level_color_changes() {
2592        let text = cranpose_ui::text::AnnotatedString::from("theme");
2593        let dark = cranpose_ui::text::TextStyle::from_span_style(cranpose_ui::text::SpanStyle {
2594            color: Some(cranpose_ui::Color::BLACK),
2595            ..Default::default()
2596        });
2597        let light = cranpose_ui::text::TextStyle::from_span_style(cranpose_ui::text::SpanStyle {
2598            color: Some(cranpose_ui::Color::WHITE),
2599            ..Default::default()
2600        });
2601
2602        assert_ne!(
2603            text_buffer_style_hash(&dark, &text),
2604            text_buffer_style_hash(&light, &text),
2605            "color-only theme flips must invalidate glyph buffer caches"
2606        );
2607    }
2608
2609    #[test]
2610    fn text_buffer_style_hash_changes_when_span_alpha_changes() {
2611        let mut opaque = cranpose_ui::text::AnnotatedString::from("theme");
2612        opaque.span_styles.push(cranpose_ui::text::RangeStyle {
2613            item: cranpose_ui::text::SpanStyle {
2614                color: Some(cranpose_ui::Color::BLACK),
2615                alpha: Some(1.0),
2616                ..Default::default()
2617            },
2618            range: 0..5,
2619        });
2620
2621        let mut translucent = cranpose_ui::text::AnnotatedString::from("theme");
2622        translucent.span_styles.push(cranpose_ui::text::RangeStyle {
2623            item: cranpose_ui::text::SpanStyle {
2624                color: Some(cranpose_ui::Color::BLACK),
2625                alpha: Some(0.2),
2626                ..Default::default()
2627            },
2628            range: 0..5,
2629        });
2630
2631        assert_ne!(
2632            text_buffer_style_hash(&cranpose_ui::text::TextStyle::default(), &opaque),
2633            text_buffer_style_hash(&cranpose_ui::text::TextStyle::default(), &translucent),
2634            "span alpha changes must invalidate glyph buffer caches"
2635        );
2636    }
2637
2638    #[test]
2639    fn select_text_shaping_uses_basic_for_simple_text_when_requested() {
2640        let style =
2641            cranpose_ui::text::TextStyle::from_paragraph_style(cranpose_ui::text::ParagraphStyle {
2642                platform_style: Some(cranpose_ui::text::PlatformParagraphStyle {
2643                    include_font_padding: None,
2644                    shaping: Some(cranpose_ui::text::TextShaping::Basic),
2645                }),
2646                ..Default::default()
2647            });
2648        let text = cranpose_ui::text::AnnotatedString::from("• Item 0042: basic markdown text");
2649
2650        assert_eq!(select_text_shaping(&text, &style), Shaping::Basic);
2651    }
2652
2653    #[test]
2654    fn select_text_shaping_falls_back_to_advanced_for_complex_text() {
2655        let style =
2656            cranpose_ui::text::TextStyle::from_paragraph_style(cranpose_ui::text::ParagraphStyle {
2657                platform_style: Some(cranpose_ui::text::PlatformParagraphStyle {
2658                    include_font_padding: None,
2659                    shaping: Some(cranpose_ui::text::TextShaping::Basic),
2660                }),
2661                ..Default::default()
2662            });
2663        let text = cranpose_ui::text::AnnotatedString::from("emoji 😀 requires fallback");
2664
2665        assert_eq!(select_text_shaping(&text, &style), Shaping::Advanced);
2666    }
2667
2668    #[test]
2669    fn layout_matches_measure_without_reentrant_mutex_lock() {
2670        use std::sync::mpsc;
2671        use std::time::Duration;
2672
2673        let (tx, rx) = mpsc::channel();
2674        std::thread::spawn(move || {
2675            let measurer = WgpuTextMeasurer::new(seeded_text_state());
2676            let text = cranpose_ui::text::AnnotatedString::from("hello\nworld");
2677            let style = cranpose_ui::text::TextStyle::default();
2678
2679            let layout = measurer.layout(&text, &style);
2680            let metrics = measurer.measure(&text, &style);
2681            tx.send((
2682                layout.width,
2683                layout.height,
2684                layout.lines.len(),
2685                metrics.width,
2686                metrics.height,
2687                metrics.line_count,
2688            ))
2689            .expect("send layout metrics");
2690        });
2691
2692        let (
2693            layout_width,
2694            layout_height,
2695            layout_lines,
2696            measured_width,
2697            measured_height,
2698            measured_lines,
2699        ) = rx
2700            .recv_timeout(Duration::from_secs(WORKER_TEST_TIMEOUT_SECS))
2701            .expect("layout timed out; possible recursive mutex acquisition");
2702
2703        assert!((layout_width - measured_width).abs() < 0.5);
2704        assert!((layout_height - measured_height).abs() < 0.5);
2705        assert_eq!(layout_lines, measured_lines.max(1));
2706    }
2707
2708    #[test]
2709    fn measure_with_options_fast_path_wraps_to_width() {
2710        use std::sync::mpsc;
2711        use std::time::Duration;
2712
2713        let (tx, rx) = mpsc::channel();
2714        std::thread::spawn(move || {
2715            let measurer = WgpuTextMeasurer::new(seeded_text_state());
2716            let text = cranpose_ui::text::AnnotatedString::from("wrap me ".repeat(120));
2717            let style = cranpose_ui::text::TextStyle::default();
2718            let options = cranpose_ui::text::TextLayoutOptions {
2719                overflow: cranpose_ui::text::TextOverflow::Clip,
2720                soft_wrap: true,
2721                max_lines: usize::MAX,
2722                min_lines: 1,
2723            };
2724            let metrics =
2725                TextMeasurer::measure_with_options(&measurer, &text, &style, options, Some(120.0));
2726            tx.send((metrics.width, metrics.line_count))
2727                .expect("send wrapped metrics");
2728        });
2729
2730        let (width, line_count) = rx
2731            .recv_timeout(Duration::from_secs(WORKER_TEST_TIMEOUT_SECS))
2732            .expect("measure_with_options timed out");
2733        assert!(width <= 120.5, "wrapped width should honor max width");
2734        assert!(line_count > 1, "wrapped text should produce multiple lines");
2735    }
2736
2737    #[test]
2738    fn prepare_with_options_reuses_cached_layout() {
2739        use std::sync::mpsc;
2740        use std::time::Duration;
2741
2742        let (tx, rx) = mpsc::channel();
2743        std::thread::spawn(move || {
2744            let measurer = WgpuTextMeasurer::new(seeded_text_state());
2745            let text = cranpose_ui::text::AnnotatedString::from(
2746                "This paragraph demonstrates wrapping with a cached prepared layout.",
2747            );
2748            let style = cranpose_ui::text::TextStyle::default();
2749            let options = cranpose_ui::text::TextLayoutOptions {
2750                overflow: cranpose_ui::text::TextOverflow::Clip,
2751                soft_wrap: true,
2752                max_lines: usize::MAX,
2753                min_lines: 1,
2754            };
2755
2756            let first =
2757                TextMeasurer::prepare_with_options(&measurer, &text, &style, options, Some(96.0));
2758            let first_cache_len = measurer.prepared_layout_cache.borrow().len();
2759
2760            let second =
2761                TextMeasurer::prepare_with_options(&measurer, &text, &style, options, Some(96.0));
2762            let second_cache_len = measurer.prepared_layout_cache.borrow().len();
2763
2764            tx.send((
2765                first == second,
2766                first.text.text.contains('\n'),
2767                first_cache_len,
2768                second_cache_len,
2769            ))
2770            .expect("send prepared layout cache result");
2771        });
2772
2773        let (same_layout, wrapped_text, first_cache_len, second_cache_len) = rx
2774            .recv_timeout(Duration::from_secs(WORKER_TEST_TIMEOUT_SECS))
2775            .expect("prepare_with_options timed out");
2776        assert!(same_layout, "cached prepared layout should be identical");
2777        assert!(
2778            wrapped_text,
2779            "prepared layout should preserve wrapped text output"
2780        );
2781        assert_eq!(first_cache_len, 1);
2782        assert_eq!(second_cache_len, 1);
2783    }
2784
2785    #[test]
2786    fn measure_for_node_uses_node_cache_identity() {
2787        use std::sync::mpsc;
2788        use std::time::Duration;
2789
2790        let (tx, rx) = mpsc::channel();
2791        std::thread::spawn(move || {
2792            let measurer = WgpuTextMeasurer::new(seeded_text_state());
2793            let text = cranpose_ui::text::AnnotatedString::from("shared node identity");
2794            let style = cranpose_ui::text::TextStyle::default();
2795            let node_id = 4242;
2796
2797            let _ = TextMeasurer::measure_for_node(&measurer, Some(node_id), &text, &style);
2798
2799            let font_size = resolve_font_size(&style);
2800            let style_hash = text_buffer_style_hash(&style, &text);
2801            let expected_key = TextCacheKey::for_node(node_id, font_size, style_hash);
2802            let text_state = measurer.text_state.lock().expect("text state lock");
2803            let cache = &text_state.text_cache;
2804
2805            tx.send((
2806                cache.len(),
2807                cache.contains(&expected_key),
2808                cache
2809                    .iter()
2810                    .any(|(key, _)| matches!(key.key, TextKey::Content(_))),
2811            ))
2812            .expect("send node cache result");
2813        });
2814
2815        let (cache_len, has_node_key, has_content_key) = rx
2816            .recv_timeout(Duration::from_secs(WORKER_TEST_TIMEOUT_SECS))
2817            .expect("measure_for_node timed out");
2818        assert_eq!(cache_len, 1);
2819        assert!(
2820            has_node_key,
2821            "node-aware measurement should populate node cache key"
2822        );
2823        assert!(
2824            !has_content_key,
2825            "node-aware measurement should not populate content cache keys"
2826        );
2827    }
2828
2829    #[test]
2830    fn renderer_measurement_keeps_render_text_cache_empty() {
2831        let (tx, rx) = mpsc::channel();
2832        std::thread::spawn(move || {
2833            let renderer = WgpuRenderer::new(&[TEST_FONT]);
2834            let text = cranpose_ui::text::AnnotatedString::from("phase local text cache");
2835            let style = cranpose_ui::text::TextStyle::default();
2836
2837            let _ = cranpose_ui::text::measure_text(&text, &style);
2838
2839            tx.send(renderer.render_text_state.lock().unwrap().text_cache.len())
2840                .expect("send render text cache size");
2841        });
2842
2843        let render_text_cache_len = rx
2844            .recv_timeout(Duration::from_secs(WORKER_TEST_TIMEOUT_SECS))
2845            .expect("renderer measurement isolation timed out");
2846        assert_eq!(
2847            render_text_cache_len, 0,
2848            "measurement should not populate render-owned text cache"
2849        );
2850    }
2851
2852    #[test]
2853    fn shared_text_cache_uses_bounded_lru_eviction() {
2854        let mut font_system = FontSystem::new();
2855        let mut cache = LruCache::new(NonZeroUsize::new(SHARED_TEXT_CACHE_CAPACITY).unwrap());
2856
2857        for index in 0..=SHARED_TEXT_CACHE_CAPACITY {
2858            let text = format!("cache-entry-{index}");
2859            let key = TextCacheKey::new(text.as_str(), 14.0, 7);
2860            let _ = shared_text_buffer_mut(&mut cache, key, &mut font_system, 14.0, 16.0);
2861        }
2862
2863        let oldest = TextCacheKey::new("cache-entry-0", 14.0, 7);
2864        let newest = TextCacheKey::new(
2865            format!("cache-entry-{}", SHARED_TEXT_CACHE_CAPACITY).as_str(),
2866            14.0,
2867            7,
2868        );
2869
2870        assert_eq!(cache.len(), SHARED_TEXT_CACHE_CAPACITY);
2871        assert!(!cache.contains(&oldest));
2872        assert!(cache.contains(&newest));
2873    }
2874
2875    // Font bytes used by tests — the same file the demo app ships.
2876    static TEST_FONT: &[u8] =
2877        include_bytes!("../../../../apps/desktop-demo/assets/NotoSansMerged.ttf");
2878    static TEST_BOLD_FONT: &[u8] =
2879        include_bytes!("../../../../apps/desktop-demo/assets/NotoSansBold.ttf");
2880    static TEST_EMOJI_FONT: &[u8] =
2881        include_bytes!("../../../../apps/desktop-demo/assets/TwemojiMozilla.ttf");
2882
2883    fn empty_font_system() -> FontSystem {
2884        let db = glyphon::fontdb::Database::new();
2885        FontSystem::new_with_locale_and_db("en-US".to_string(), db)
2886    }
2887
2888    #[test]
2889    fn load_fonts_populates_face_db() {
2890        let mut fs = empty_font_system();
2891        load_fonts(&mut fs, &[TEST_FONT]);
2892        assert!(
2893            fs.db().faces().count() > 0,
2894            "load_fonts must load at least one face"
2895        );
2896    }
2897
2898    #[test]
2899    fn load_fonts_empty_slice_leaves_db_empty() {
2900        let mut fs = empty_font_system();
2901        load_fonts(&mut fs, &[]);
2902        assert_eq!(
2903            fs.db().faces().count(),
2904            0,
2905            "empty slice must not load any faces"
2906        );
2907    }
2908
2909    fn queried_family_name(font_system: &FontSystem, family: glyphon::fontdb::Family) -> String {
2910        let query = glyphon::fontdb::Query {
2911            families: &[family],
2912            weight: glyphon::fontdb::Weight::NORMAL,
2913            stretch: glyphon::fontdb::Stretch::Normal,
2914            style: glyphon::fontdb::Style::Normal,
2915        };
2916        let face_id = font_system
2917            .db()
2918            .query(&query)
2919            .expect("generic family should resolve to a face");
2920        let face = font_system
2921            .db()
2922            .face(face_id)
2923            .expect("queried face id should exist");
2924        face.families
2925            .first()
2926            .map(|(name, _)| name.clone())
2927            .expect("queried face should carry a family name")
2928    }
2929
2930    #[test]
2931    fn generic_fallbacks_prefer_loaded_font_family_over_existing_faces() {
2932        let mut font_system = empty_font_system();
2933        load_fonts(&mut font_system, &[TEST_EMOJI_FONT, TEST_FONT]);
2934        let mut resolver = WgpuFontFamilyResolver::default();
2935        resolver.set_preferred_generic_family(primary_family_name_from_bytes(TEST_FONT));
2936        resolver.prime(&mut font_system);
2937
2938        let generic_serif = queried_family_name(&font_system, glyphon::fontdb::Family::Serif);
2939        let expected = primary_family_name_from_bytes(TEST_FONT)
2940            .expect("test font should resolve to a family name");
2941        assert_eq!(generic_serif, expected);
2942    }
2943
2944    #[test]
2945    fn resolver_logs_warning_if_font_db_is_empty() {
2946        // With no fonts loaded the resolver should not panic; it just warns.
2947        let mut font_system = empty_font_system();
2948        let mut resolver = WgpuFontFamilyResolver::default();
2949        let span_style = cranpose_ui::text::SpanStyle::default();
2950        // Must not panic even with an empty DB.
2951        let _ = resolver.resolve_family_owned(&mut font_system, &span_style);
2952    }
2953
2954    #[test]
2955    #[cfg(not(target_arch = "wasm32"))]
2956    fn attrs_resolution_loads_file_backed_family_from_path() {
2957        let (mut font_system, mut resolver) = seeded_font_system_and_resolver();
2958        let nonce = std::time::SystemTime::now()
2959            .duration_since(std::time::UNIX_EPOCH)
2960            .map(|duration| duration.as_nanos())
2961            .unwrap_or_default();
2962        let unique_path = format!(
2963            "{}/cranpose-font-resolver-{}-{}.ttf",
2964            std::env::temp_dir().display(),
2965            std::process::id(),
2966            nonce
2967        );
2968        std::fs::write(&unique_path, TEST_FONT).expect("write font fixture");
2969
2970        let style = cranpose_ui::text::TextStyle {
2971            span_style: cranpose_ui::text::SpanStyle {
2972                font_family: Some(cranpose_ui::text::FontFamily::file_backed(vec![
2973                    cranpose_ui::text::FontFile::new(unique_path.clone()),
2974                ])),
2975                ..Default::default()
2976            },
2977            ..Default::default()
2978        };
2979
2980        let attrs = attrs_from_text_style(&style, 14.0, 1.0, &mut font_system, &mut resolver);
2981        assert!(
2982            matches!(attrs.family_owned, FamilyOwned::Name(_)),
2983            "file-backed font family should resolve to an installed family name"
2984        );
2985
2986        let _ = std::fs::remove_file(&unique_path);
2987    }
2988}