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, 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            graphics_layer: GraphicsLayer::default(),
1216            clip_to_bounds: false,
1217            shadow_clip: None,
1218            hit_test: None,
1219            has_hit_targets: false,
1220            isolation: IsolationReasons::default(),
1221            cache_policy: CachePolicy::None,
1222            cache_hashes: LayerRasterCacheHashes::default(),
1223            cache_hashes_valid: false,
1224            children: vec![
1225                RenderNode::Primitive(PrimitiveEntry {
1226                    phase: PrimitivePhase::BeforeChildren,
1227                    node: PrimitiveNode::Draw(DrawPrimitiveNode {
1228                        primitive: DrawPrimitive::RoundRect {
1229                            rect: Rect {
1230                                x: 0.0,
1231                                y: 0.0,
1232                                width: text_width + padding,
1233                                height: text_height + padding / 2.0,
1234                            },
1235                            brush: Brush::Solid(Color(0.0, 0.0, 0.0, 0.7)),
1236                            radii: CornerRadii::uniform(4.0),
1237                        },
1238                        clip: None,
1239                    }),
1240                }),
1241                RenderNode::Primitive(PrimitiveEntry {
1242                    phase: PrimitivePhase::AfterChildren,
1243                    node: PrimitiveNode::Text(Box::new(TextPrimitiveNode {
1244                        node_id: DEV_OVERLAY_NODE_ID,
1245                        rect: Rect {
1246                            x: padding / 2.0,
1247                            y: padding / 4.0,
1248                            width: text_width,
1249                            height: text_height,
1250                        },
1251                        text: cranpose_ui::text::AnnotatedString::from(text),
1252                        text_style: cranpose_ui::TextStyle::default(),
1253                        font_size,
1254                        layout_options: cranpose_ui::TextLayoutOptions::default(),
1255                        clip: None,
1256                    })),
1257                }),
1258            ],
1259        };
1260        overlay_layer.recompute_raster_cache_hashes();
1261
1262        let graph = self.scene.graph.get_or_insert_with(|| {
1263            RenderGraph::new(LayerNode {
1264                node_id: None,
1265                local_bounds: Rect::from_size(viewport),
1266                transform_to_parent: ProjectiveTransform::identity(),
1267                motion_context_animated: false,
1268                translated_content_context: false,
1269                graphics_layer: GraphicsLayer::default(),
1270                clip_to_bounds: false,
1271                shadow_clip: None,
1272                hit_test: None,
1273                has_hit_targets: false,
1274                isolation: IsolationReasons::default(),
1275                cache_policy: CachePolicy::None,
1276                cache_hashes: LayerRasterCacheHashes::default(),
1277                cache_hashes_valid: false,
1278                children: Vec::new(),
1279            })
1280        });
1281
1282        graph.root.children.retain(|child| {
1283            !matches!(
1284                child,
1285                RenderNode::Layer(layer) if layer.node_id == Some(DEV_OVERLAY_NODE_ID)
1286            )
1287        });
1288        graph
1289            .root
1290            .children
1291            .push(RenderNode::Layer(Box::new(overlay_layer)));
1292        graph.root.recompute_raster_cache_hashes();
1293    }
1294}
1295
1296fn resolve_font_size(style: &cranpose_ui::text::TextStyle) -> f32 {
1297    style.resolve_font_size(14.0)
1298}
1299
1300fn resolve_line_height(style: &cranpose_ui::text::TextStyle, font_size: f32) -> f32 {
1301    style.resolve_line_height(14.0, font_size * 1.4)
1302}
1303
1304fn resolve_max_span_font_size(
1305    style: &cranpose_ui::text::TextStyle,
1306    text: &cranpose_ui::text::AnnotatedString,
1307    base_font_size: f32,
1308) -> f32 {
1309    if text.span_styles.is_empty() {
1310        return base_font_size;
1311    }
1312
1313    let mut max_font_size = base_font_size;
1314    for window in text.span_boundaries().windows(2) {
1315        let start = window[0];
1316        let end = window[1];
1317        if start == end {
1318            continue;
1319        }
1320
1321        let mut merged_span = style.span_style.clone();
1322        for span in &text.span_styles {
1323            if span.range.start <= start && span.range.end >= end {
1324                merged_span = merged_span.merge(&span.item);
1325            }
1326        }
1327        let mut chunk_style = style.clone();
1328        chunk_style.span_style = merged_span;
1329        max_font_size = max_font_size.max(chunk_style.resolve_font_size(base_font_size));
1330    }
1331    max_font_size
1332}
1333
1334pub(crate) fn resolve_effective_line_height(
1335    style: &cranpose_ui::text::TextStyle,
1336    text: &cranpose_ui::text::AnnotatedString,
1337    base_font_size: f32,
1338) -> f32 {
1339    let max_font_size = resolve_max_span_font_size(style, text, base_font_size);
1340    resolve_line_height(style, max_font_size)
1341}
1342
1343/// Returns true if the fontdb contains at least one italic (or oblique) face
1344/// whose family matches the given `FamilyOwned`.
1345fn family_has_italic_face(font_system: &FontSystem, family: &FamilyOwned) -> bool {
1346    let family_ref = family.as_family();
1347    let family_name = font_system.db().family_name(&family_ref);
1348    font_system.db().faces().any(|face| {
1349        (face.style == glyphon::fontdb::Style::Italic
1350            || face.style == glyphon::fontdb::Style::Oblique)
1351            && face
1352                .families
1353                .iter()
1354                .any(|(name, _)| name.eq_ignore_ascii_case(family_name))
1355    })
1356}
1357
1358fn attrs_from_text_style(
1359    style: &cranpose_ui::text::TextStyle,
1360    unscaled_base_font_size: f32,
1361    scale: f32,
1362    font_system: &mut FontSystem,
1363    font_family_resolver: &mut WgpuFontFamilyResolver,
1364) -> AttrsOwned {
1365    let mut attrs = Attrs::new();
1366    let span_style = &style.span_style;
1367    let font_weight = span_style.font_weight;
1368    let font_style = span_style.font_style;
1369    let letter_spacing = span_style.letter_spacing;
1370
1371    let unscaled_font_size = style.resolve_font_size(unscaled_base_font_size);
1372    let unscaled_line_height =
1373        style.resolve_line_height(unscaled_base_font_size, unscaled_font_size * 1.4);
1374
1375    let font_size_px = unscaled_font_size * scale;
1376    let line_height_px = unscaled_line_height * scale;
1377    attrs = attrs.metrics(glyphon::Metrics::new(font_size_px, line_height_px));
1378
1379    if let Some(color) = glyph_foreground_color(span_style) {
1380        let r = (color.0 * 255.0).clamp(0.0, 255.0) as u8;
1381        let g = (color.1 * 255.0).clamp(0.0, 255.0) as u8;
1382        let b = (color.2 * 255.0).clamp(0.0, 255.0) as u8;
1383        let a = (color.3 * 255.0).clamp(0.0, 255.0) as u8;
1384        attrs = attrs.color(glyphon::Color::rgba(r, g, b, a));
1385    }
1386
1387    let family_owned = font_family_resolver.resolve_family_owned(font_system, span_style);
1388    attrs = attrs.family(family_owned.as_family());
1389
1390    if let Some(font_weight) = font_weight {
1391        attrs = attrs.weight(GlyphonWeight(font_weight.0));
1392    }
1393
1394    // cosmic-text 0.15 does NOT synthesize italic automatically — it passes
1395    // cache_key_flags through as-is from attrs to glyphs.  We must decide here
1396    // whether to request a native italic face or to ask for synthetic skew.
1397    //
1398    // Strategy:
1399    //   • If the resolved family owns an italic face → set style=Italic so
1400    //     cosmic-text matches the real face.  No FAKE_ITALIC needed.
1401    //   • Otherwise → keep style=Normal (so font matching finds the Regular
1402    //     face) and set FAKE_ITALIC for the swash 14-degree skew.
1403    let mut flags = glyphon::cosmic_text::CacheKeyFlags::DISABLE_HINTING;
1404    if let Some(font_style) = font_style {
1405        match font_style {
1406            cranpose_ui::text::FontStyle::Normal => {}
1407            cranpose_ui::text::FontStyle::Italic => {
1408                if family_has_italic_face(font_system, &family_owned) {
1409                    attrs = attrs.style(GlyphonStyle::Italic);
1410                } else {
1411                    flags |= glyphon::cosmic_text::CacheKeyFlags::FAKE_ITALIC;
1412                }
1413            }
1414        }
1415    }
1416
1417    attrs = match letter_spacing {
1418        cranpose_ui::text::TextUnit::Em(value) => attrs.letter_spacing(value),
1419        cranpose_ui::text::TextUnit::Sp(value) if font_size_px > 0.0 => {
1420            attrs.letter_spacing((value * scale) / font_size_px)
1421        }
1422        _ => attrs,
1423    };
1424    attrs = attrs.cache_key_flags(flags);
1425
1426    AttrsOwned::new(&attrs)
1427}
1428
1429// Text measurer implementation for WGPU
1430
1431#[derive(Clone)]
1432struct WgpuTextMeasurer {
1433    text_state: SharedTextSystemState,
1434    size_cache: TextSizeCache,
1435    prepared_layout_cache: PreparedTextLayoutCache,
1436}
1437
1438impl WgpuTextMeasurer {
1439    fn new(text_state: SharedTextSystemState) -> Self {
1440        Self {
1441            text_state,
1442            // Larger cache size (1024) reduces misses, FxHasher for faster lookups
1443            size_cache: Arc::new(Mutex::new(LruCache::new(NonZeroUsize::new(1024).unwrap()))),
1444            prepared_layout_cache: Rc::new(RefCell::new(LruCache::new(
1445                NonZeroUsize::new(256).unwrap(),
1446            ))),
1447        }
1448    }
1449
1450    fn text_buffer_key(
1451        node_id: Option<NodeId>,
1452        text: &str,
1453        font_size: f32,
1454        style_hash: u64,
1455    ) -> TextCacheKey {
1456        match node_id {
1457            Some(node_id) => TextCacheKey::for_node(node_id, font_size, style_hash),
1458            None => TextCacheKey::new(text, font_size, style_hash),
1459        }
1460    }
1461
1462    fn try_measure_with_options_fast_path(
1463        &self,
1464        node_id: Option<NodeId>,
1465        text: &cranpose_ui::text::AnnotatedString,
1466        style: &cranpose_ui::text::TextStyle,
1467        options: cranpose_ui::text::TextLayoutOptions,
1468        max_width: Option<f32>,
1469    ) -> Option<cranpose_ui::TextMetrics> {
1470        let options = options.normalized();
1471        let max_width = max_width.filter(|w| w.is_finite() && *w > 0.0)?;
1472        if !Self::supports_fast_wrap_options(style, options) {
1473            return None;
1474        }
1475
1476        let text_str = text.text.as_str();
1477        let font_size = resolve_font_size(style);
1478        let line_height = resolve_effective_line_height(style, text, font_size);
1479        let size_style_hash = style.measurement_hash()
1480            ^ text.span_styles_hash()
1481            ^ (max_width.to_bits() as u64).rotate_left(17)
1482            ^ 0x9f4c_3314_2d5b_79e1;
1483        let buffer_style_hash = text_buffer_style_hash(style, text);
1484        let size_int = (font_size * 100.0) as i32;
1485
1486        let mut hasher = FxHasher::default();
1487        text_str.hash(&mut hasher);
1488        let text_hash = hasher.finish();
1489        let cache_key = (text_hash, size_int, size_style_hash);
1490
1491        {
1492            let mut cache = self.size_cache.lock().unwrap();
1493            if let Some((cached_text, size)) = cache.get(&cache_key) {
1494                if cached_text == text_str {
1495                    let width = size.width.min(max_width);
1496                    let min_height = options.min_lines as f32 * line_height;
1497                    let height = size.height.max(min_height);
1498                    let line_count =
1499                        ((height / line_height).ceil() as usize).max(options.min_lines);
1500                    return Some(cranpose_ui::TextMetrics {
1501                        width,
1502                        height,
1503                        line_height,
1504                        line_count,
1505                    });
1506                }
1507            }
1508        }
1509
1510        let text_buffer_key =
1511            Self::text_buffer_key(node_id, text_str, font_size, buffer_style_hash);
1512        let mut text_state = self.text_state.lock().unwrap();
1513        let (font_system, font_family_resolver, text_cache) = text_state.parts_mut();
1514
1515        let (size, wrapped_line_count) = {
1516            let (_, _, _, buffer) = shared_text_buffer_mut(
1517                text_cache,
1518                text_buffer_key,
1519                font_system,
1520                font_size,
1521                line_height,
1522            );
1523
1524            let _ = buffer.ensure(
1525                font_system,
1526                font_family_resolver,
1527                EnsureTextBufferParams {
1528                    annotated_text: text,
1529                    font_size_px: font_size,
1530                    line_height_px: line_height,
1531                    style_hash: buffer_style_hash,
1532                    style,
1533                    scale: 1.0,
1534                },
1535            );
1536
1537            buffer
1538                .buffer
1539                .set_size(font_system, Some(max_width), Some(f32::MAX));
1540            buffer.buffer.shape_until_scroll(font_system, false);
1541            buffer.cached_size = None;
1542            let size = buffer.size();
1543            let line_count = buffer.buffer.layout_runs().count();
1544            (size, line_count)
1545        };
1546        drop(text_state);
1547
1548        let mut size_cache = self.size_cache.lock().unwrap();
1549        size_cache.put(cache_key, (text_str.to_string(), size));
1550
1551        let width = size.width.min(max_width);
1552        let min_height = options.min_lines as f32 * line_height;
1553        let height = size.height.max(min_height);
1554        let line_count = wrapped_line_count.max(options.min_lines).max(1);
1555
1556        Some(cranpose_ui::TextMetrics {
1557            width,
1558            height,
1559            line_height,
1560            line_count,
1561        })
1562    }
1563
1564    fn try_prepare_with_options_fast_path(
1565        &self,
1566        node_id: Option<NodeId>,
1567        text: &cranpose_ui::text::AnnotatedString,
1568        style: &cranpose_ui::text::TextStyle,
1569        options: cranpose_ui::text::TextLayoutOptions,
1570        max_width: Option<f32>,
1571    ) -> Option<cranpose_ui::text::PreparedTextLayout> {
1572        let options = options.normalized();
1573        let max_width = max_width.filter(|w| w.is_finite() && *w > 0.0)?;
1574        if !Self::supports_fast_wrap_options(style, options) {
1575            return None;
1576        }
1577
1578        let text_str = text.text.as_str();
1579        let font_size = resolve_font_size(style);
1580        let line_height = resolve_effective_line_height(style, text, font_size);
1581        let style_hash = text_buffer_style_hash(style, text);
1582
1583        let text_buffer_key = Self::text_buffer_key(node_id, text_str, font_size, style_hash);
1584        let mut text_state = self.text_state.lock().unwrap();
1585        let (font_system, font_family_resolver, text_cache) = text_state.parts_mut();
1586
1587        let (size, wrapped_ranges) = {
1588            let (_, _, _, buffer) = shared_text_buffer_mut(
1589                text_cache,
1590                text_buffer_key,
1591                font_system,
1592                font_size,
1593                line_height,
1594            );
1595
1596            let _ = buffer.ensure(
1597                font_system,
1598                font_family_resolver,
1599                EnsureTextBufferParams {
1600                    annotated_text: text,
1601                    font_size_px: font_size,
1602                    line_height_px: line_height,
1603                    style_hash,
1604                    style,
1605                    scale: 1.0,
1606                },
1607            );
1608
1609            buffer
1610                .buffer
1611                .set_size(font_system, Some(max_width), Some(f32::MAX));
1612            buffer.buffer.shape_until_scroll(font_system, false);
1613            buffer.cached_size = None;
1614            let size = buffer.size();
1615            let wrapped_ranges = collect_wrapped_ranges(text_str, &buffer.buffer)?;
1616            (size, wrapped_ranges)
1617        };
1618
1619        let mut builder = cranpose_ui::text::AnnotatedString::builder();
1620        for (idx, (start, end)) in wrapped_ranges.iter().enumerate() {
1621            builder = builder.append_annotated_subsequence(text, *start..*end);
1622            if idx + 1 < wrapped_ranges.len() {
1623                builder = builder.append("\n");
1624            }
1625        }
1626        let wrapped_annotated = builder.to_annotated_string();
1627
1628        let line_count = wrapped_ranges.len().max(options.min_lines).max(1);
1629        let min_height = options.min_lines as f32 * line_height;
1630        let height = (line_count as f32 * line_height).max(min_height);
1631
1632        Some(cranpose_ui::text::PreparedTextLayout {
1633            text: wrapped_annotated,
1634            metrics: cranpose_ui::TextMetrics {
1635                width: size.width.min(max_width),
1636                height,
1637                line_height,
1638                line_count,
1639            },
1640            did_overflow: false,
1641        })
1642    }
1643
1644    fn supports_fast_wrap_options(
1645        style: &cranpose_ui::text::TextStyle,
1646        options: cranpose_ui::text::TextLayoutOptions,
1647    ) -> bool {
1648        if options.overflow != cranpose_ui::text::TextOverflow::Clip || !options.soft_wrap {
1649            return false;
1650        }
1651        if options.max_lines != usize::MAX {
1652            return false;
1653        }
1654
1655        let line_break = style
1656            .paragraph_style
1657            .line_break
1658            .take_or_else(|| cranpose_ui::text::LineBreak::Simple);
1659        let hyphens = style
1660            .paragraph_style
1661            .hyphens
1662            .take_or_else(|| cranpose_ui::text::Hyphens::None);
1663        line_break == cranpose_ui::text::LineBreak::Simple
1664            && hyphens == cranpose_ui::text::Hyphens::None
1665    }
1666}
1667
1668fn collect_wrapped_ranges(text: &str, buffer: &Buffer) -> Option<Vec<(usize, usize)>> {
1669    if text.is_empty() {
1670        return Some(vec![(0, 0)]);
1671    }
1672
1673    let text_lines: Vec<&str> = text.split('\n').collect();
1674    let line_offsets: Vec<(usize, usize)> = text_lines
1675        .iter()
1676        .scan(0usize, |line_start, line| {
1677            let start = *line_start;
1678            let end = start + line.len();
1679            *line_start = end.saturating_add(1);
1680            Some((start, end))
1681        })
1682        .collect();
1683
1684    let mut wrapped_ranges = Vec::new();
1685    for run in buffer.layout_runs() {
1686        let (line_start, line_end) = line_offsets
1687            .get(run.line_i)
1688            .copied()
1689            .unwrap_or((0usize, text.len()));
1690        let line_len = line_end.saturating_sub(line_start);
1691
1692        if run.glyphs.is_empty() {
1693            wrapped_ranges.push((line_start, line_start));
1694            continue;
1695        }
1696
1697        let mut local_start = line_len;
1698        let mut local_end = 0usize;
1699        for glyph in run.glyphs.iter() {
1700            local_start = local_start.min(glyph.start.min(line_len));
1701            local_end = local_end.max(glyph.end.min(line_len));
1702        }
1703
1704        let range_start = line_start.saturating_add(local_start.min(line_len));
1705        let range_end = line_start.saturating_add(local_end.min(line_len));
1706        if range_start > range_end
1707            || range_end > text.len()
1708            || !text.is_char_boundary(range_start)
1709            || !text.is_char_boundary(range_end)
1710        {
1711            return None;
1712        }
1713        wrapped_ranges.push((range_start, range_end));
1714    }
1715
1716    if wrapped_ranges.is_empty() {
1717        Some(vec![(0, text.len())])
1718    } else {
1719        Some(wrapped_ranges)
1720    }
1721}
1722
1723/// Convenience function for tests to initialize an accurate wgpu text measurer without launching a window.
1724pub fn setup_headless_text_measurer() {
1725    let mut font_system = FontSystem::new();
1726    let mut font_family_resolver_impl = WgpuFontFamilyResolver::default();
1727    font_family_resolver_impl.prime(&mut font_system);
1728    let text_state = Arc::new(Mutex::new(TextSystemState::from_parts(
1729        font_system,
1730        font_family_resolver_impl,
1731    )));
1732    cranpose_ui::text::set_text_measurer(WgpuTextMeasurer::new(text_state));
1733}
1734
1735// Base font size in logical units (dp) - shared between measurement and rendering
1736
1737impl TextMeasurer for WgpuTextMeasurer {
1738    fn measure(
1739        &self,
1740        text: &cranpose_ui::text::AnnotatedString,
1741        style: &cranpose_ui::text::TextStyle,
1742    ) -> cranpose_ui::TextMetrics {
1743        self.measure_for_node(None, text, style)
1744    }
1745
1746    fn measure_for_node(
1747        &self,
1748        node_id: Option<NodeId>,
1749        text: &cranpose_ui::text::AnnotatedString,
1750        style: &cranpose_ui::text::TextStyle,
1751    ) -> cranpose_ui::TextMetrics {
1752        let telemetry = text_measure_telemetry_enabled().then_some(text_measure_telemetry());
1753        let telemetry_sequence = telemetry
1754            .map(|t| t.measure_calls.fetch_add(1, Ordering::Relaxed) + 1)
1755            .unwrap_or(0);
1756        let text_str = text.text.as_str();
1757        let font_size = resolve_font_size(style);
1758        let line_height = resolve_effective_line_height(style, text, font_size);
1759        let size_style_hash = style.measurement_hash() ^ text.span_styles_hash();
1760        let buffer_style_hash = text_buffer_style_hash(style, text);
1761        let size_int = (font_size * 100.0) as i32;
1762
1763        // Calculate hash to avoid allocating String for lookup
1764        // FxHasher is ~3x faster than DefaultHasher for short strings
1765        let mut hasher = FxHasher::default();
1766        text_str.hash(&mut hasher);
1767        let text_hash = hasher.finish();
1768        let cache_key = (text_hash, size_int, size_style_hash);
1769
1770        // Check size cache first (fastest path)
1771        {
1772            let mut cache = self.size_cache.lock().unwrap();
1773            if let Some((cached_text, size)) = cache.get(&cache_key) {
1774                // Verify partial collision
1775                if cached_text == text_str {
1776                    if let Some(t) = telemetry {
1777                        t.size_cache_hits.fetch_add(1, Ordering::Relaxed);
1778                        maybe_report_text_measure_telemetry(telemetry_sequence);
1779                    }
1780                    let line_count = text_str.split('\n').count().max(1);
1781                    return cranpose_ui::TextMetrics {
1782                        width: size.width,
1783                        height: size.height,
1784                        line_height,
1785                        line_count,
1786                    };
1787                }
1788            }
1789        }
1790        if let Some(t) = telemetry {
1791            t.size_cache_misses.fetch_add(1, Ordering::Relaxed);
1792        }
1793
1794        // Get or create text buffer
1795        let text_buffer_key =
1796            Self::text_buffer_key(node_id, text_str, font_size, buffer_style_hash);
1797        let mut text_state = self.text_state.lock().unwrap();
1798        let (font_system, font_family_resolver, text_cache) = text_state.parts_mut();
1799
1800        // Get or create buffer and calculate size
1801        let size = {
1802            let (text_cache_hit, evicted, cache_len, buffer) = shared_text_buffer_mut(
1803                text_cache,
1804                text_buffer_key,
1805                font_system,
1806                font_size,
1807                line_height,
1808            );
1809            if let Some(t) = telemetry {
1810                if text_cache_hit {
1811                    t.text_cache_hits.fetch_add(1, Ordering::Relaxed);
1812                } else {
1813                    t.text_cache_misses.fetch_add(1, Ordering::Relaxed);
1814                }
1815                if evicted {
1816                    t.text_cache_evictions.fetch_add(1, Ordering::Relaxed);
1817                }
1818                t.text_cache_occupancy
1819                    .store(cache_len as u64, Ordering::Relaxed);
1820            }
1821
1822            // Ensure buffer has the correct text
1823            let reshaped = buffer.ensure(
1824                font_system,
1825                font_family_resolver,
1826                EnsureTextBufferParams {
1827                    annotated_text: text,
1828                    font_size_px: font_size,
1829                    line_height_px: line_height,
1830                    style_hash: buffer_style_hash,
1831                    style,
1832                    scale: 1.0,
1833                },
1834            );
1835            if let Some(t) = telemetry {
1836                if reshaped {
1837                    t.ensure_reshapes.fetch_add(1, Ordering::Relaxed);
1838                } else {
1839                    t.ensure_reuses.fetch_add(1, Ordering::Relaxed);
1840                }
1841            }
1842
1843            // Calculate size if not cached
1844            buffer.size()
1845        };
1846
1847        drop(text_state);
1848
1849        // Cache the size result
1850        let mut size_cache = self.size_cache.lock().unwrap();
1851        // Only allocate string on cache miss
1852        size_cache.put(cache_key, (text_str.to_string(), size));
1853
1854        // Calculate line info for multiline support
1855        let line_count = text_str.split('\n').count().max(1);
1856        if telemetry.is_some() {
1857            maybe_report_text_measure_telemetry(telemetry_sequence);
1858        }
1859
1860        cranpose_ui::TextMetrics {
1861            width: size.width,
1862            height: size.height,
1863            line_height,
1864            line_count,
1865        }
1866    }
1867
1868    fn measure_with_options(
1869        &self,
1870        text: &cranpose_ui::text::AnnotatedString,
1871        style: &cranpose_ui::text::TextStyle,
1872        options: cranpose_ui::text::TextLayoutOptions,
1873        max_width: Option<f32>,
1874    ) -> cranpose_ui::TextMetrics {
1875        self.measure_with_options_for_node(None, text, style, options, max_width)
1876    }
1877
1878    fn measure_with_options_for_node(
1879        &self,
1880        node_id: Option<NodeId>,
1881        text: &cranpose_ui::text::AnnotatedString,
1882        style: &cranpose_ui::text::TextStyle,
1883        options: cranpose_ui::text::TextLayoutOptions,
1884        max_width: Option<f32>,
1885    ) -> cranpose_ui::TextMetrics {
1886        let telemetry = text_measure_telemetry_enabled().then_some(text_measure_telemetry());
1887        let telemetry_sequence = telemetry
1888            .map(|t| t.measure_with_options_calls.fetch_add(1, Ordering::Relaxed) + 1)
1889            .unwrap_or(0);
1890        if let Some(metrics) =
1891            self.try_measure_with_options_fast_path(node_id, text, style, options, max_width)
1892        {
1893            if let Some(t) = telemetry {
1894                t.measure_fast_path_hits.fetch_add(1, Ordering::Relaxed);
1895                maybe_report_text_measure_telemetry(telemetry_sequence);
1896            }
1897            return metrics;
1898        }
1899        if let Some(t) = telemetry {
1900            t.measure_fast_path_misses.fetch_add(1, Ordering::Relaxed);
1901            maybe_report_text_measure_telemetry(telemetry_sequence);
1902        }
1903        self.prepare_with_options_for_node(node_id, text, style, options, max_width)
1904            .metrics
1905    }
1906
1907    fn prepare_with_options(
1908        &self,
1909        text: &cranpose_ui::text::AnnotatedString,
1910        style: &cranpose_ui::text::TextStyle,
1911        options: cranpose_ui::text::TextLayoutOptions,
1912        max_width: Option<f32>,
1913    ) -> cranpose_ui::text::PreparedTextLayout {
1914        self.prepare_with_options_for_node(None, text, style, options, max_width)
1915    }
1916
1917    fn prepare_with_options_for_node(
1918        &self,
1919        node_id: Option<NodeId>,
1920        text: &cranpose_ui::text::AnnotatedString,
1921        style: &cranpose_ui::text::TextStyle,
1922        options: cranpose_ui::text::TextLayoutOptions,
1923        max_width: Option<f32>,
1924    ) -> cranpose_ui::text::PreparedTextLayout {
1925        let telemetry = text_measure_telemetry_enabled().then_some(text_measure_telemetry());
1926        let telemetry_sequence = telemetry
1927            .map(|t| t.prepare_with_options_calls.fetch_add(1, Ordering::Relaxed) + 1)
1928            .unwrap_or(0);
1929        let normalized_options = options.normalized();
1930        let normalized_max_width = max_width.filter(|w| w.is_finite() && *w > 0.0);
1931        let text_str = text.text.as_str();
1932        let font_size = resolve_font_size(style);
1933        let style_hash = text_buffer_style_hash(style, text);
1934        let size_int = (font_size * 100.0) as i32;
1935
1936        let mut hasher = FxHasher::default();
1937        text_str.hash(&mut hasher);
1938        let text_hash = hasher.finish();
1939        let cache_key = PreparedTextLayoutCacheKey {
1940            text_hash,
1941            size_int,
1942            style_hash,
1943            options: normalized_options,
1944            max_width_bits: normalized_max_width.map(f32::to_bits),
1945        };
1946
1947        {
1948            let mut cache = self.prepared_layout_cache.borrow_mut();
1949            if let Some((cached_text, prepared)) = cache.get(&cache_key) {
1950                if cached_text == text_str {
1951                    if let Some(t) = telemetry {
1952                        t.prepared_layout_cache_hits.fetch_add(1, Ordering::Relaxed);
1953                        maybe_report_text_measure_telemetry(telemetry_sequence);
1954                    }
1955                    return prepared.clone();
1956                }
1957            }
1958        }
1959        if let Some(t) = telemetry {
1960            t.prepared_layout_cache_misses
1961                .fetch_add(1, Ordering::Relaxed);
1962        }
1963
1964        let prepared = if let Some(prepared) = self.try_prepare_with_options_fast_path(
1965            node_id,
1966            text,
1967            style,
1968            normalized_options,
1969            normalized_max_width,
1970        ) {
1971            if let Some(t) = telemetry {
1972                t.prepare_fast_path_hits.fetch_add(1, Ordering::Relaxed);
1973            }
1974            prepared
1975        } else {
1976            if let Some(t) = telemetry {
1977                t.prepare_fast_path_misses.fetch_add(1, Ordering::Relaxed);
1978            }
1979            cranpose_ui::text::measure::prepare_text_layout_with_measurer_for_node(
1980                self,
1981                node_id,
1982                text,
1983                style,
1984                normalized_options,
1985                normalized_max_width,
1986            )
1987        };
1988
1989        let mut cache = self.prepared_layout_cache.borrow_mut();
1990        cache.put(cache_key, (text_str.to_string(), prepared.clone()));
1991        if telemetry.is_some() {
1992            maybe_report_text_measure_telemetry(telemetry_sequence);
1993        }
1994
1995        prepared
1996    }
1997
1998    fn get_offset_for_position(
1999        &self,
2000        text: &cranpose_ui::text::AnnotatedString,
2001        style: &cranpose_ui::text::TextStyle,
2002        x: f32,
2003        y: f32,
2004    ) -> usize {
2005        let telemetry = text_measure_telemetry_enabled().then_some(text_measure_telemetry());
2006        let telemetry_sequence = telemetry
2007            .map(|t| t.offset_calls.fetch_add(1, Ordering::Relaxed) + 1)
2008            .unwrap_or(0);
2009        let text_str = text.text.as_str();
2010        let font_size = resolve_font_size(style);
2011        let line_height = resolve_effective_line_height(style, text, font_size);
2012        let style_hash = text_buffer_style_hash(style, text);
2013        if text_str.is_empty() {
2014            return 0;
2015        }
2016
2017        let cache_key = TextCacheKey::new(text_str, font_size, style_hash);
2018
2019        let mut text_state = self.text_state.lock().unwrap();
2020        let (font_system, font_family_resolver, text_cache) = text_state.parts_mut();
2021
2022        let (text_cache_hit, evicted, cache_len, buffer) =
2023            shared_text_buffer_mut(text_cache, cache_key, font_system, font_size, line_height);
2024        if let Some(t) = telemetry {
2025            if text_cache_hit {
2026                t.text_cache_hits.fetch_add(1, Ordering::Relaxed);
2027            } else {
2028                t.text_cache_misses.fetch_add(1, Ordering::Relaxed);
2029            }
2030            if evicted {
2031                t.text_cache_evictions.fetch_add(1, Ordering::Relaxed);
2032            }
2033            t.text_cache_occupancy
2034                .store(cache_len as u64, Ordering::Relaxed);
2035        }
2036
2037        let reshaped = buffer.ensure(
2038            font_system,
2039            font_family_resolver,
2040            EnsureTextBufferParams {
2041                annotated_text: text,
2042                font_size_px: font_size,
2043                line_height_px: line_height,
2044                style_hash,
2045                style,
2046                scale: 1.0,
2047            },
2048        );
2049        if let Some(t) = telemetry {
2050            if reshaped {
2051                t.ensure_reshapes.fetch_add(1, Ordering::Relaxed);
2052            } else {
2053                t.ensure_reuses.fetch_add(1, Ordering::Relaxed);
2054            }
2055            maybe_report_text_measure_telemetry(telemetry_sequence);
2056        }
2057
2058        let line_offsets: Vec<(usize, usize)> = text_str
2059            .split('\n')
2060            .scan(0usize, |line_start, line| {
2061                let start = *line_start;
2062                let end = start + line.len();
2063                *line_start = end.saturating_add(1);
2064                Some((start, end))
2065            })
2066            .collect();
2067
2068        let mut target_line = None;
2069        let mut best_vertical_distance = f32::INFINITY;
2070
2071        for run in buffer.buffer.layout_runs() {
2072            let mut run_height = run.line_height;
2073            for glyph in run.glyphs.iter() {
2074                run_height = run_height.max(glyph.font_size * 1.4);
2075            }
2076
2077            let top = run.line_top;
2078            let bottom = top + run_height.max(1.0);
2079            let vertical_distance = if y < top {
2080                top - y
2081            } else if y > bottom {
2082                y - bottom
2083            } else {
2084                0.0
2085            };
2086
2087            if vertical_distance < best_vertical_distance {
2088                best_vertical_distance = vertical_distance;
2089                target_line = Some(run.line_i);
2090                if vertical_distance == 0.0 {
2091                    break;
2092                }
2093            }
2094        }
2095
2096        let fallback_line = (y / line_height).floor().max(0.0) as usize;
2097        let target_line = target_line
2098            .unwrap_or(fallback_line)
2099            .min(line_offsets.len().saturating_sub(1));
2100        let (line_start, line_end) = line_offsets
2101            .get(target_line)
2102            .copied()
2103            .unwrap_or((0, text_str.len()));
2104        let line_len = line_end.saturating_sub(line_start);
2105
2106        let mut best_offset = line_offsets
2107            .get(target_line)
2108            .map(|(_, end)| *end)
2109            .unwrap_or(text_str.len());
2110        let mut best_distance = f32::INFINITY;
2111        let mut found_glyph = false;
2112
2113        for run in buffer.buffer.layout_runs() {
2114            if run.line_i != target_line {
2115                continue;
2116            }
2117            for glyph in run.glyphs.iter() {
2118                found_glyph = true;
2119                let glyph_start = line_start.saturating_add(glyph.start.min(line_len));
2120                let glyph_end = line_start.saturating_add(glyph.end.min(line_len));
2121                let left_dist = (x - glyph.x).abs();
2122                if left_dist < best_distance {
2123                    best_distance = left_dist;
2124                    best_offset = glyph_start;
2125                }
2126
2127                let right_x = glyph.x + glyph.w;
2128                let right_dist = (x - right_x).abs();
2129                if right_dist < best_distance {
2130                    best_distance = right_dist;
2131                    best_offset = glyph_end;
2132                }
2133            }
2134        }
2135
2136        if !found_glyph {
2137            if let Some((start, end)) = line_offsets.get(target_line) {
2138                best_offset = if x <= 0.0 { *start } else { *end };
2139            }
2140        }
2141
2142        best_offset.min(text_str.len())
2143    }
2144
2145    fn get_cursor_x_for_offset(
2146        &self,
2147        text: &cranpose_ui::text::AnnotatedString,
2148        style: &cranpose_ui::text::TextStyle,
2149        offset: usize,
2150    ) -> f32 {
2151        let text = text.text.as_str();
2152        let clamped_offset = offset.min(text.len());
2153        if clamped_offset == 0 {
2154            return 0.0;
2155        }
2156
2157        // Measure text up to offset
2158        let prefix = &text[..clamped_offset];
2159        self.measure(&cranpose_ui::text::AnnotatedString::from(prefix), style)
2160            .width
2161    }
2162
2163    fn choose_auto_hyphen_break(
2164        &self,
2165        line: &str,
2166        style: &cranpose_ui::text::TextStyle,
2167        segment_start_char: usize,
2168        measured_break_char: usize,
2169    ) -> Option<usize> {
2170        choose_shared_auto_hyphen_break(line, style, segment_start_char, measured_break_char)
2171    }
2172
2173    fn layout(
2174        &self,
2175        text: &cranpose_ui::text::AnnotatedString,
2176        style: &cranpose_ui::text::TextStyle,
2177    ) -> cranpose_ui::text_layout_result::TextLayoutResult {
2178        let telemetry = text_measure_telemetry_enabled().then_some(text_measure_telemetry());
2179        let telemetry_sequence = telemetry
2180            .map(|t| t.layout_calls.fetch_add(1, Ordering::Relaxed) + 1)
2181            .unwrap_or(0);
2182        let text_str = text.text.as_str();
2183        use cranpose_ui::text_layout_result::{
2184            GlyphLayout, LineLayout, TextLayoutData, TextLayoutResult,
2185        };
2186
2187        let font_size = resolve_font_size(style);
2188        let line_height = resolve_effective_line_height(style, text, font_size);
2189        let style_hash = text_buffer_style_hash(style, text);
2190
2191        let cache_key = TextCacheKey::new(text_str, font_size, style_hash);
2192        let mut text_state = self.text_state.lock().unwrap();
2193        let (font_system, font_family_resolver, text_cache) = text_state.parts_mut();
2194
2195        let (text_cache_hit, evicted, cache_len, buffer) = shared_text_buffer_mut(
2196            text_cache,
2197            cache_key.clone(),
2198            font_system,
2199            font_size,
2200            line_height,
2201        );
2202        if let Some(t) = telemetry {
2203            if text_cache_hit {
2204                t.text_cache_hits.fetch_add(1, Ordering::Relaxed);
2205            } else {
2206                t.text_cache_misses.fetch_add(1, Ordering::Relaxed);
2207            }
2208            if evicted {
2209                t.text_cache_evictions.fetch_add(1, Ordering::Relaxed);
2210            }
2211            t.text_cache_occupancy
2212                .store(cache_len as u64, Ordering::Relaxed);
2213        }
2214        let reshaped = buffer.ensure(
2215            font_system,
2216            font_family_resolver,
2217            EnsureTextBufferParams {
2218                annotated_text: text,
2219                font_size_px: font_size,
2220                line_height_px: line_height,
2221                style_hash,
2222                style,
2223                scale: 1.0,
2224            },
2225        );
2226        if let Some(t) = telemetry {
2227            if reshaped {
2228                t.ensure_reshapes.fetch_add(1, Ordering::Relaxed);
2229            } else {
2230                t.ensure_reuses.fetch_add(1, Ordering::Relaxed);
2231            }
2232            maybe_report_text_measure_telemetry(telemetry_sequence);
2233        }
2234        let measured_size = buffer.size();
2235
2236        // Extract glyph positions from layout runs
2237        let mut glyph_x_positions = Vec::new();
2238        let mut char_to_byte = Vec::new();
2239        let mut glyph_layouts = Vec::new();
2240        let mut lines = Vec::new();
2241        let text_lines: Vec<&str> = text_str.split('\n').collect();
2242        let line_offsets: Vec<(usize, usize)> = text_lines
2243            .iter()
2244            .scan(0usize, |line_start, line| {
2245                let start = *line_start;
2246                let end = start + line.len();
2247                *line_start = end.saturating_add(1);
2248                Some((start, end))
2249            })
2250            .collect();
2251
2252        for run in buffer.buffer.layout_runs() {
2253            let line_idx = run.line_i;
2254            let run_height = run
2255                .glyphs
2256                .iter()
2257                .fold(run.line_height, |acc, glyph| acc.max(glyph.font_size * 1.4))
2258                .max(1.0);
2259
2260            for glyph in run.glyphs.iter() {
2261                let (line_start, line_end) = line_offsets
2262                    .get(line_idx)
2263                    .copied()
2264                    .unwrap_or((0, text_str.len()));
2265                let line_len = line_end.saturating_sub(line_start);
2266                let glyph_start = line_start.saturating_add(glyph.start.min(line_len));
2267                let glyph_end = line_start.saturating_add(glyph.end.min(line_len));
2268
2269                glyph_x_positions.push(glyph.x);
2270                char_to_byte.push(glyph_start);
2271                if glyph_end > glyph_start {
2272                    glyph_layouts.push(GlyphLayout {
2273                        line_index: line_idx,
2274                        start_offset: glyph_start,
2275                        end_offset: glyph_end,
2276                        x: glyph.x,
2277                        y: run.line_top,
2278                        width: glyph.w.max(0.0),
2279                        height: run_height,
2280                    });
2281                }
2282            }
2283        }
2284
2285        // Add end position
2286        glyph_x_positions.push(measured_size.width);
2287        char_to_byte.push(text_str.len());
2288
2289        // Build lines from text newlines
2290        let mut y = 0.0f32;
2291        let mut line_start = 0usize;
2292        for (i, line_text) in text_lines.iter().enumerate() {
2293            let line_end = if i == text_lines.len() - 1 {
2294                text_str.len()
2295            } else {
2296                line_start + line_text.len()
2297            };
2298
2299            lines.push(LineLayout {
2300                start_offset: line_start,
2301                end_offset: line_end,
2302                y,
2303                height: line_height,
2304            });
2305
2306            line_start = line_end + 1;
2307            y += line_height;
2308        }
2309
2310        if lines.is_empty() {
2311            lines.push(LineLayout {
2312                start_offset: 0,
2313                end_offset: 0,
2314                y: 0.0,
2315                height: line_height,
2316            });
2317        }
2318
2319        let metrics = cranpose_ui::TextMetrics {
2320            width: measured_size.width,
2321            height: measured_size.height,
2322            line_height,
2323            line_count: text_lines.len().max(1),
2324        };
2325        TextLayoutResult::new(
2326            text_str,
2327            TextLayoutData {
2328                width: metrics.width,
2329                height: metrics.height,
2330                line_height,
2331                glyph_x_positions,
2332                char_to_byte,
2333                lines,
2334                glyph_layouts,
2335            },
2336        )
2337    }
2338}
2339
2340#[cfg(test)]
2341mod tests {
2342    use super::*;
2343    use std::sync::mpsc;
2344    use std::time::Duration;
2345
2346    const WORKER_TEST_TIMEOUT_SECS: u64 = 15;
2347
2348    fn seeded_font_system_and_resolver() -> (FontSystem, WgpuFontFamilyResolver) {
2349        let mut db = glyphon::fontdb::Database::new();
2350        db.load_font_data(TEST_FONT.to_vec());
2351        let mut font_system = FontSystem::new_with_locale_and_db("en-US".to_string(), db);
2352        let mut resolver = WgpuFontFamilyResolver::default();
2353        resolver.prime(&mut font_system);
2354        (font_system, resolver)
2355    }
2356
2357    fn seeded_text_state() -> SharedTextSystemState {
2358        let (font_system, resolver) = seeded_font_system_and_resolver();
2359        Arc::new(Mutex::new(TextSystemState::from_parts(
2360            font_system,
2361            resolver,
2362        )))
2363    }
2364
2365    #[test]
2366    fn attrs_resolution_falls_back_for_missing_named_family() {
2367        let (mut font_system, mut resolver) = seeded_font_system_and_resolver();
2368        let style = cranpose_ui::text::TextStyle {
2369            span_style: cranpose_ui::text::SpanStyle {
2370                font_family: Some(cranpose_ui::text::FontFamily::named("Missing Family Name")),
2371                ..Default::default()
2372            },
2373            ..Default::default()
2374        };
2375
2376        let attrs = attrs_from_text_style(&style, 14.0, 1.0, &mut font_system, &mut resolver);
2377        assert_eq!(attrs.family_owned, FamilyOwned::SansSerif);
2378    }
2379
2380    #[test]
2381    fn attrs_resolution_seeds_generic_families_from_loaded_fonts() {
2382        let (font_system, resolver) = seeded_font_system_and_resolver();
2383        assert!(
2384            resolver.generic_fallback_seeded,
2385            "expected generic fallback seeding after resolver prime"
2386        );
2387        let query = glyphon::fontdb::Query {
2388            families: &[glyphon::fontdb::Family::Monospace],
2389            weight: glyphon::fontdb::Weight::NORMAL,
2390            stretch: glyphon::fontdb::Stretch::Normal,
2391            style: glyphon::fontdb::Style::Normal,
2392        };
2393        assert!(
2394            font_system.db().query(&query).is_some(),
2395            "generic monospace query should resolve after fallback seeding"
2396        );
2397    }
2398
2399    #[test]
2400    fn attrs_resolution_named_family_lookup_is_case_insensitive() {
2401        let (mut font_system, mut resolver) = seeded_font_system_and_resolver();
2402        let style = cranpose_ui::text::TextStyle {
2403            span_style: cranpose_ui::text::SpanStyle {
2404                font_family: Some(cranpose_ui::text::FontFamily::named("noto sans")),
2405                ..Default::default()
2406            },
2407            ..Default::default()
2408        };
2409
2410        let attrs = attrs_from_text_style(&style, 14.0, 1.0, &mut font_system, &mut resolver);
2411        assert!(
2412            matches!(attrs.family_owned, FamilyOwned::Name(_)),
2413            "case-insensitive family lookup should resolve to a concrete family name"
2414        );
2415    }
2416
2417    #[test]
2418    fn attrs_resolution_synthesizes_italic_when_no_italic_face_available() {
2419        let (mut font_system, mut resolver) = seeded_font_system_and_resolver();
2420        let style = cranpose_ui::text::TextStyle {
2421            span_style: cranpose_ui::text::SpanStyle {
2422                font_family: Some(cranpose_ui::text::FontFamily::named("Noto Sans")),
2423                font_style: Some(cranpose_ui::text::FontStyle::Italic),
2424                ..Default::default()
2425            },
2426            ..Default::default()
2427        };
2428
2429        let attrs = attrs_from_text_style(&style, 14.0, 1.0, &mut font_system, &mut resolver);
2430        // Noto Sans (test font) has no italic face → style stays Normal,
2431        // FAKE_ITALIC is set so the swash renderer applies 14° skew.
2432        assert_eq!(
2433            attrs.style,
2434            GlyphonStyle::Normal,
2435            "style must stay Normal for font matching when no italic face exists"
2436        );
2437        assert!(
2438            attrs
2439                .cache_key_flags
2440                .contains(glyphon::cosmic_text::CacheKeyFlags::FAKE_ITALIC),
2441            "FAKE_ITALIC must be set when the font family lacks a native italic face"
2442        );
2443    }
2444
2445    #[test]
2446    fn attrs_resolution_preserves_requested_bold_for_synthesis() {
2447        let (mut font_system, mut resolver) = seeded_font_system_and_resolver();
2448        let style = cranpose_ui::text::TextStyle {
2449            span_style: cranpose_ui::text::SpanStyle {
2450                font_family: Some(cranpose_ui::text::FontFamily::named("Noto Sans")),
2451                font_weight: Some(cranpose_ui::text::FontWeight::BOLD),
2452                ..Default::default()
2453            },
2454            ..Default::default()
2455        };
2456
2457        let attrs = attrs_from_text_style(&style, 14.0, 1.0, &mut font_system, &mut resolver);
2458        assert_eq!(
2459            attrs.weight,
2460            GlyphonWeight(cranpose_ui::text::FontWeight::BOLD.0),
2461            "requested bold must be preserved in attrs so glyphon can synthesize it"
2462        );
2463    }
2464
2465    #[test]
2466    fn span_level_italic_propagates_through_rich_text_ensure() {
2467        let (mut font_system, mut resolver) = seeded_font_system_and_resolver();
2468        let mut text = cranpose_ui::text::AnnotatedString::from("normal italic");
2469        text.span_styles.push(cranpose_ui::text::RangeStyle {
2470            item: cranpose_ui::text::SpanStyle {
2471                font_style: Some(cranpose_ui::text::FontStyle::Italic),
2472                ..Default::default()
2473            },
2474            range: 7..13, // "italic"
2475        });
2476        let style = cranpose_ui::text::TextStyle::default();
2477        let style_hash = text_buffer_style_hash(&style, &text);
2478        let mut buffer = new_shared_text_buffer(&mut font_system, 14.0, 14.0 * 1.4);
2479        buffer.ensure(
2480            &mut font_system,
2481            &mut resolver,
2482            EnsureTextBufferParams {
2483                annotated_text: &text,
2484                font_size_px: 14.0,
2485                line_height_px: 14.0 * 1.4,
2486                style_hash,
2487                style: &style,
2488                scale: 1.0,
2489            },
2490        );
2491        // Check that the buffer's layout lines have FAKE_ITALIC flag on the italic span
2492        let has_fake_italic = buffer.buffer.layout_runs().any(|run| {
2493            run.glyphs.iter().any(|glyph| {
2494                glyph.start >= 7
2495                    && glyph
2496                        .cache_key_flags
2497                        .contains(glyphon::cosmic_text::CacheKeyFlags::FAKE_ITALIC)
2498            })
2499        });
2500        assert!(
2501            has_fake_italic,
2502            "span-level italic must produce FAKE_ITALIC glyphs when the font lacks native italic"
2503        );
2504    }
2505
2506    #[test]
2507    fn bold_text_uses_bold_font_face_when_available() {
2508        let mut db = glyphon::fontdb::Database::new();
2509        db.load_font_data(TEST_FONT.to_vec());
2510        db.load_font_data(TEST_BOLD_FONT.to_vec());
2511        let mut font_system = FontSystem::new_with_locale_and_db("en-US".to_string(), db);
2512        let mut resolver = WgpuFontFamilyResolver::default();
2513        resolver.prime(&mut font_system);
2514
2515        let style = cranpose_ui::text::TextStyle {
2516            span_style: cranpose_ui::text::SpanStyle {
2517                font_weight: Some(cranpose_ui::text::FontWeight::BOLD),
2518                ..Default::default()
2519            },
2520            ..Default::default()
2521        };
2522        let text = cranpose_ui::text::AnnotatedString::from("bold text");
2523        let style_hash = text_buffer_style_hash(&style, &text);
2524        let mut buffer = new_shared_text_buffer(&mut font_system, 14.0, 14.0 * 1.4);
2525        buffer.ensure(
2526            &mut font_system,
2527            &mut resolver,
2528            EnsureTextBufferParams {
2529                annotated_text: &text,
2530                font_size_px: 14.0,
2531                line_height_px: 14.0 * 1.4,
2532                style_hash,
2533                style: &style,
2534                scale: 1.0,
2535            },
2536        );
2537        let bold_face_used = buffer.buffer.layout_runs().any(|run| {
2538            run.glyphs.iter().any(|glyph| {
2539                font_system
2540                    .db()
2541                    .face(glyph.font_id)
2542                    .is_some_and(|face| face.weight.0 == 700)
2543            })
2544        });
2545        assert!(
2546            bold_face_used,
2547            "bold text must use the bold font face (weight 700) when available"
2548        );
2549    }
2550
2551    #[test]
2552    fn attrs_from_text_style_applies_alpha_to_foreground_color() {
2553        let (mut font_system, mut resolver) = seeded_font_system_and_resolver();
2554        let style = cranpose_ui::text::TextStyle::from_span_style(cranpose_ui::text::SpanStyle {
2555            color: Some(cranpose_ui::Color(0.2, 0.4, 0.6, 1.0)),
2556            alpha: Some(0.25),
2557            ..Default::default()
2558        });
2559
2560        let attrs = attrs_from_text_style(&style, 14.0, 1.0, &mut font_system, &mut resolver);
2561
2562        assert_eq!(
2563            attrs.color_opt,
2564            Some(glyphon::Color::rgba(51, 102, 153, 63)),
2565            "glyph attrs must track alpha-adjusted foreground color"
2566        );
2567    }
2568
2569    #[test]
2570    fn attrs_from_text_style_disables_native_hinting() {
2571        let (mut font_system, mut resolver) = seeded_font_system_and_resolver();
2572        let attrs = attrs_from_text_style(
2573            &cranpose_ui::text::TextStyle::default(),
2574            14.0,
2575            1.0,
2576            &mut font_system,
2577            &mut resolver,
2578        );
2579
2580        assert!(
2581            attrs
2582                .cache_key_flags
2583                .contains(glyphon::cosmic_text::CacheKeyFlags::DISABLE_HINTING),
2584            "renderer text attrs should disable native hinting to keep glyph rasterization stable across scroll phases"
2585        );
2586    }
2587
2588    #[test]
2589    fn text_buffer_style_hash_changes_when_top_level_color_changes() {
2590        let text = cranpose_ui::text::AnnotatedString::from("theme");
2591        let dark = cranpose_ui::text::TextStyle::from_span_style(cranpose_ui::text::SpanStyle {
2592            color: Some(cranpose_ui::Color::BLACK),
2593            ..Default::default()
2594        });
2595        let light = cranpose_ui::text::TextStyle::from_span_style(cranpose_ui::text::SpanStyle {
2596            color: Some(cranpose_ui::Color::WHITE),
2597            ..Default::default()
2598        });
2599
2600        assert_ne!(
2601            text_buffer_style_hash(&dark, &text),
2602            text_buffer_style_hash(&light, &text),
2603            "color-only theme flips must invalidate glyph buffer caches"
2604        );
2605    }
2606
2607    #[test]
2608    fn text_buffer_style_hash_changes_when_span_alpha_changes() {
2609        let mut opaque = cranpose_ui::text::AnnotatedString::from("theme");
2610        opaque.span_styles.push(cranpose_ui::text::RangeStyle {
2611            item: cranpose_ui::text::SpanStyle {
2612                color: Some(cranpose_ui::Color::BLACK),
2613                alpha: Some(1.0),
2614                ..Default::default()
2615            },
2616            range: 0..5,
2617        });
2618
2619        let mut translucent = cranpose_ui::text::AnnotatedString::from("theme");
2620        translucent.span_styles.push(cranpose_ui::text::RangeStyle {
2621            item: cranpose_ui::text::SpanStyle {
2622                color: Some(cranpose_ui::Color::BLACK),
2623                alpha: Some(0.2),
2624                ..Default::default()
2625            },
2626            range: 0..5,
2627        });
2628
2629        assert_ne!(
2630            text_buffer_style_hash(&cranpose_ui::text::TextStyle::default(), &opaque),
2631            text_buffer_style_hash(&cranpose_ui::text::TextStyle::default(), &translucent),
2632            "span alpha changes must invalidate glyph buffer caches"
2633        );
2634    }
2635
2636    #[test]
2637    fn select_text_shaping_uses_basic_for_simple_text_when_requested() {
2638        let style =
2639            cranpose_ui::text::TextStyle::from_paragraph_style(cranpose_ui::text::ParagraphStyle {
2640                platform_style: Some(cranpose_ui::text::PlatformParagraphStyle {
2641                    include_font_padding: None,
2642                    shaping: Some(cranpose_ui::text::TextShaping::Basic),
2643                }),
2644                ..Default::default()
2645            });
2646        let text = cranpose_ui::text::AnnotatedString::from("• Item 0042: basic markdown text");
2647
2648        assert_eq!(select_text_shaping(&text, &style), Shaping::Basic);
2649    }
2650
2651    #[test]
2652    fn select_text_shaping_falls_back_to_advanced_for_complex_text() {
2653        let style =
2654            cranpose_ui::text::TextStyle::from_paragraph_style(cranpose_ui::text::ParagraphStyle {
2655                platform_style: Some(cranpose_ui::text::PlatformParagraphStyle {
2656                    include_font_padding: None,
2657                    shaping: Some(cranpose_ui::text::TextShaping::Basic),
2658                }),
2659                ..Default::default()
2660            });
2661        let text = cranpose_ui::text::AnnotatedString::from("emoji 😀 requires fallback");
2662
2663        assert_eq!(select_text_shaping(&text, &style), Shaping::Advanced);
2664    }
2665
2666    #[test]
2667    fn layout_matches_measure_without_reentrant_mutex_lock() {
2668        use std::sync::mpsc;
2669        use std::time::Duration;
2670
2671        let (tx, rx) = mpsc::channel();
2672        std::thread::spawn(move || {
2673            let measurer = WgpuTextMeasurer::new(seeded_text_state());
2674            let text = cranpose_ui::text::AnnotatedString::from("hello\nworld");
2675            let style = cranpose_ui::text::TextStyle::default();
2676
2677            let layout = measurer.layout(&text, &style);
2678            let metrics = measurer.measure(&text, &style);
2679            tx.send((
2680                layout.width,
2681                layout.height,
2682                layout.lines.len(),
2683                metrics.width,
2684                metrics.height,
2685                metrics.line_count,
2686            ))
2687            .expect("send layout metrics");
2688        });
2689
2690        let (
2691            layout_width,
2692            layout_height,
2693            layout_lines,
2694            measured_width,
2695            measured_height,
2696            measured_lines,
2697        ) = rx
2698            .recv_timeout(Duration::from_secs(WORKER_TEST_TIMEOUT_SECS))
2699            .expect("layout timed out; possible recursive mutex acquisition");
2700
2701        assert!((layout_width - measured_width).abs() < 0.5);
2702        assert!((layout_height - measured_height).abs() < 0.5);
2703        assert_eq!(layout_lines, measured_lines.max(1));
2704    }
2705
2706    #[test]
2707    fn measure_with_options_fast_path_wraps_to_width() {
2708        use std::sync::mpsc;
2709        use std::time::Duration;
2710
2711        let (tx, rx) = mpsc::channel();
2712        std::thread::spawn(move || {
2713            let measurer = WgpuTextMeasurer::new(seeded_text_state());
2714            let text = cranpose_ui::text::AnnotatedString::from("wrap me ".repeat(120));
2715            let style = cranpose_ui::text::TextStyle::default();
2716            let options = cranpose_ui::text::TextLayoutOptions {
2717                overflow: cranpose_ui::text::TextOverflow::Clip,
2718                soft_wrap: true,
2719                max_lines: usize::MAX,
2720                min_lines: 1,
2721            };
2722            let metrics =
2723                TextMeasurer::measure_with_options(&measurer, &text, &style, options, Some(120.0));
2724            tx.send((metrics.width, metrics.line_count))
2725                .expect("send wrapped metrics");
2726        });
2727
2728        let (width, line_count) = rx
2729            .recv_timeout(Duration::from_secs(WORKER_TEST_TIMEOUT_SECS))
2730            .expect("measure_with_options timed out");
2731        assert!(width <= 120.5, "wrapped width should honor max width");
2732        assert!(line_count > 1, "wrapped text should produce multiple lines");
2733    }
2734
2735    #[test]
2736    fn prepare_with_options_reuses_cached_layout() {
2737        use std::sync::mpsc;
2738        use std::time::Duration;
2739
2740        let (tx, rx) = mpsc::channel();
2741        std::thread::spawn(move || {
2742            let measurer = WgpuTextMeasurer::new(seeded_text_state());
2743            let text = cranpose_ui::text::AnnotatedString::from(
2744                "This paragraph demonstrates wrapping with a cached prepared layout.",
2745            );
2746            let style = cranpose_ui::text::TextStyle::default();
2747            let options = cranpose_ui::text::TextLayoutOptions {
2748                overflow: cranpose_ui::text::TextOverflow::Clip,
2749                soft_wrap: true,
2750                max_lines: usize::MAX,
2751                min_lines: 1,
2752            };
2753
2754            let first =
2755                TextMeasurer::prepare_with_options(&measurer, &text, &style, options, Some(96.0));
2756            let first_cache_len = measurer.prepared_layout_cache.borrow().len();
2757
2758            let second =
2759                TextMeasurer::prepare_with_options(&measurer, &text, &style, options, Some(96.0));
2760            let second_cache_len = measurer.prepared_layout_cache.borrow().len();
2761
2762            tx.send((
2763                first == second,
2764                first.text.text.contains('\n'),
2765                first_cache_len,
2766                second_cache_len,
2767            ))
2768            .expect("send prepared layout cache result");
2769        });
2770
2771        let (same_layout, wrapped_text, first_cache_len, second_cache_len) = rx
2772            .recv_timeout(Duration::from_secs(WORKER_TEST_TIMEOUT_SECS))
2773            .expect("prepare_with_options timed out");
2774        assert!(same_layout, "cached prepared layout should be identical");
2775        assert!(
2776            wrapped_text,
2777            "prepared layout should preserve wrapped text output"
2778        );
2779        assert_eq!(first_cache_len, 1);
2780        assert_eq!(second_cache_len, 1);
2781    }
2782
2783    #[test]
2784    fn measure_for_node_uses_node_cache_identity() {
2785        use std::sync::mpsc;
2786        use std::time::Duration;
2787
2788        let (tx, rx) = mpsc::channel();
2789        std::thread::spawn(move || {
2790            let measurer = WgpuTextMeasurer::new(seeded_text_state());
2791            let text = cranpose_ui::text::AnnotatedString::from("shared node identity");
2792            let style = cranpose_ui::text::TextStyle::default();
2793            let node_id = 4242;
2794
2795            let _ = TextMeasurer::measure_for_node(&measurer, Some(node_id), &text, &style);
2796
2797            let font_size = resolve_font_size(&style);
2798            let style_hash = text_buffer_style_hash(&style, &text);
2799            let expected_key = TextCacheKey::for_node(node_id, font_size, style_hash);
2800            let text_state = measurer.text_state.lock().expect("text state lock");
2801            let cache = &text_state.text_cache;
2802
2803            tx.send((
2804                cache.len(),
2805                cache.contains(&expected_key),
2806                cache
2807                    .iter()
2808                    .any(|(key, _)| matches!(key.key, TextKey::Content(_))),
2809            ))
2810            .expect("send node cache result");
2811        });
2812
2813        let (cache_len, has_node_key, has_content_key) = rx
2814            .recv_timeout(Duration::from_secs(WORKER_TEST_TIMEOUT_SECS))
2815            .expect("measure_for_node timed out");
2816        assert_eq!(cache_len, 1);
2817        assert!(
2818            has_node_key,
2819            "node-aware measurement should populate node cache key"
2820        );
2821        assert!(
2822            !has_content_key,
2823            "node-aware measurement should not populate content cache keys"
2824        );
2825    }
2826
2827    #[test]
2828    fn renderer_measurement_keeps_render_text_cache_empty() {
2829        let (tx, rx) = mpsc::channel();
2830        std::thread::spawn(move || {
2831            let renderer = WgpuRenderer::new(&[TEST_FONT]);
2832            let text = cranpose_ui::text::AnnotatedString::from("phase local text cache");
2833            let style = cranpose_ui::text::TextStyle::default();
2834
2835            let _ = cranpose_ui::text::measure_text(&text, &style);
2836
2837            tx.send(renderer.render_text_state.lock().unwrap().text_cache.len())
2838                .expect("send render text cache size");
2839        });
2840
2841        let render_text_cache_len = rx
2842            .recv_timeout(Duration::from_secs(WORKER_TEST_TIMEOUT_SECS))
2843            .expect("renderer measurement isolation timed out");
2844        assert_eq!(
2845            render_text_cache_len, 0,
2846            "measurement should not populate render-owned text cache"
2847        );
2848    }
2849
2850    #[test]
2851    fn shared_text_cache_uses_bounded_lru_eviction() {
2852        let mut font_system = FontSystem::new();
2853        let mut cache = LruCache::new(NonZeroUsize::new(SHARED_TEXT_CACHE_CAPACITY).unwrap());
2854
2855        for index in 0..=SHARED_TEXT_CACHE_CAPACITY {
2856            let text = format!("cache-entry-{index}");
2857            let key = TextCacheKey::new(text.as_str(), 14.0, 7);
2858            let _ = shared_text_buffer_mut(&mut cache, key, &mut font_system, 14.0, 16.0);
2859        }
2860
2861        let oldest = TextCacheKey::new("cache-entry-0", 14.0, 7);
2862        let newest = TextCacheKey::new(
2863            format!("cache-entry-{}", SHARED_TEXT_CACHE_CAPACITY).as_str(),
2864            14.0,
2865            7,
2866        );
2867
2868        assert_eq!(cache.len(), SHARED_TEXT_CACHE_CAPACITY);
2869        assert!(!cache.contains(&oldest));
2870        assert!(cache.contains(&newest));
2871    }
2872
2873    // Font bytes used by tests — the same file the demo app ships.
2874    static TEST_FONT: &[u8] =
2875        include_bytes!("../../../../apps/desktop-demo/assets/NotoSansMerged.ttf");
2876    static TEST_BOLD_FONT: &[u8] =
2877        include_bytes!("../../../../apps/desktop-demo/assets/NotoSansBold.ttf");
2878    static TEST_EMOJI_FONT: &[u8] =
2879        include_bytes!("../../../../apps/desktop-demo/assets/TwemojiMozilla.ttf");
2880
2881    fn empty_font_system() -> FontSystem {
2882        let db = glyphon::fontdb::Database::new();
2883        FontSystem::new_with_locale_and_db("en-US".to_string(), db)
2884    }
2885
2886    #[test]
2887    fn load_fonts_populates_face_db() {
2888        let mut fs = empty_font_system();
2889        load_fonts(&mut fs, &[TEST_FONT]);
2890        assert!(
2891            fs.db().faces().count() > 0,
2892            "load_fonts must load at least one face"
2893        );
2894    }
2895
2896    #[test]
2897    fn load_fonts_empty_slice_leaves_db_empty() {
2898        let mut fs = empty_font_system();
2899        load_fonts(&mut fs, &[]);
2900        assert_eq!(
2901            fs.db().faces().count(),
2902            0,
2903            "empty slice must not load any faces"
2904        );
2905    }
2906
2907    fn queried_family_name(font_system: &FontSystem, family: glyphon::fontdb::Family) -> String {
2908        let query = glyphon::fontdb::Query {
2909            families: &[family],
2910            weight: glyphon::fontdb::Weight::NORMAL,
2911            stretch: glyphon::fontdb::Stretch::Normal,
2912            style: glyphon::fontdb::Style::Normal,
2913        };
2914        let face_id = font_system
2915            .db()
2916            .query(&query)
2917            .expect("generic family should resolve to a face");
2918        let face = font_system
2919            .db()
2920            .face(face_id)
2921            .expect("queried face id should exist");
2922        face.families
2923            .first()
2924            .map(|(name, _)| name.clone())
2925            .expect("queried face should carry a family name")
2926    }
2927
2928    #[test]
2929    fn generic_fallbacks_prefer_loaded_font_family_over_existing_faces() {
2930        let mut font_system = empty_font_system();
2931        load_fonts(&mut font_system, &[TEST_EMOJI_FONT, TEST_FONT]);
2932        let mut resolver = WgpuFontFamilyResolver::default();
2933        resolver.set_preferred_generic_family(primary_family_name_from_bytes(TEST_FONT));
2934        resolver.prime(&mut font_system);
2935
2936        let generic_serif = queried_family_name(&font_system, glyphon::fontdb::Family::Serif);
2937        let expected = primary_family_name_from_bytes(TEST_FONT)
2938            .expect("test font should resolve to a family name");
2939        assert_eq!(generic_serif, expected);
2940    }
2941
2942    #[test]
2943    fn resolver_logs_warning_if_font_db_is_empty() {
2944        // With no fonts loaded the resolver should not panic; it just warns.
2945        let mut font_system = empty_font_system();
2946        let mut resolver = WgpuFontFamilyResolver::default();
2947        let span_style = cranpose_ui::text::SpanStyle::default();
2948        // Must not panic even with an empty DB.
2949        let _ = resolver.resolve_family_owned(&mut font_system, &span_style);
2950    }
2951
2952    #[test]
2953    #[cfg(not(target_arch = "wasm32"))]
2954    fn attrs_resolution_loads_file_backed_family_from_path() {
2955        let (mut font_system, mut resolver) = seeded_font_system_and_resolver();
2956        let nonce = std::time::SystemTime::now()
2957            .duration_since(std::time::UNIX_EPOCH)
2958            .map(|duration| duration.as_nanos())
2959            .unwrap_or_default();
2960        let unique_path = format!(
2961            "{}/cranpose-font-resolver-{}-{}.ttf",
2962            std::env::temp_dir().display(),
2963            std::process::id(),
2964            nonce
2965        );
2966        std::fs::write(&unique_path, TEST_FONT).expect("write font fixture");
2967
2968        let style = cranpose_ui::text::TextStyle {
2969            span_style: cranpose_ui::text::SpanStyle {
2970                font_family: Some(cranpose_ui::text::FontFamily::file_backed(vec![
2971                    cranpose_ui::text::FontFile::new(unique_path.clone()),
2972                ])),
2973                ..Default::default()
2974            },
2975            ..Default::default()
2976        };
2977
2978        let attrs = attrs_from_text_style(&style, 14.0, 1.0, &mut font_system, &mut resolver);
2979        assert!(
2980            matches!(attrs.family_owned, FamilyOwned::Name(_)),
2981            "file-backed font family should resolve to an installed family name"
2982        );
2983
2984        let _ = std::fs::remove_file(&unique_path);
2985    }
2986}