mtk-rs 0.1.0-beta.4

Muse Toolkit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
use crate::TextStyle;
use crate::colors::Color;
use parley::style::{FontStyle, LineHeight, StyleProperty};
use parley::{
    AlignmentOptions, BreakReason, Cluster, ClusterSide, Cursor, FontContext, LayoutContext,
};
use std::ops::Range;
use std::sync::Arc;
use std::sync::Mutex;
use swash::scale::ScaleContext;

/// Visual styling applied to a specific sub-range of text in a rich text layout.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct SpanStyle {
    pub color: Option<Color>,
    pub font_weight: Option<parley::style::FontWeight>,
    pub font_style: Option<FontStyle>,
    pub font_size: Option<f32>,
    pub underline: bool,
    pub strikethrough: bool,
}

impl SpanStyle {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn color(mut self, color: Color) -> Self {
        self.color = Some(color);
        self
    }

    pub fn bold(mut self) -> Self {
        self.font_weight = Some(parley::style::FontWeight::BOLD);
        self
    }

    pub fn weight(mut self, weight: parley::style::FontWeight) -> Self {
        self.font_weight = Some(weight);
        self
    }

    pub fn italic(mut self) -> Self {
        self.font_style = Some(FontStyle::Italic);
        self
    }

    pub fn font_style(mut self, style: FontStyle) -> Self {
        self.font_style = Some(style);
        self
    }

    pub fn font_size(mut self, size: f32) -> Self {
        self.font_size = Some(size);
        self
    }

    pub fn underline(mut self, underline: bool) -> Self {
        self.underline = underline;
        self
    }

    pub fn strikethrough(mut self, strikethrough: bool) -> Self {
        self.strikethrough = strikethrough;
        self
    }

    /// Overlays another `SpanStyle` onto `self`, preferring non-None and true values from `other`.
    pub fn merge(&self, other: &SpanStyle) -> SpanStyle {
        SpanStyle {
            color: other.color.or(self.color),
            font_weight: other.font_weight.or(self.font_weight),
            font_style: other.font_style.or(self.font_style),
            font_size: other.font_size.or(self.font_size),
            underline: other.underline || self.underline,
            strikethrough: other.strikethrough || self.strikethrough,
        }
    }

    /// Returns `true` if applying this style could alter character advances, line breaks, or text bounds.
    pub fn affects_geometry(&self) -> bool {
        self.font_weight.is_some() || self.font_style.is_some() || self.font_size.is_some()
    }
}

/// A styled range of text with an optional identifier tag for interactivity.
#[derive(Clone, Debug, PartialEq)]
pub struct TextSpan<Id = ()> {
    pub range: Range<usize>,
    pub style: SpanStyle,
    pub hover_style: Option<SpanStyle>,
    pub id: Option<Id>,
}

impl<Id> TextSpan<Id> {
    pub fn new(range: Range<usize>) -> Self {
        Self {
            range,
            style: SpanStyle::default(),
            hover_style: None,
            id: None,
        }
    }

    pub fn id(mut self, id: Id) -> Self {
        self.id = Some(id);
        self
    }

    pub fn color(mut self, color: Color) -> Self {
        self.style.color = Some(color);
        self
    }

    pub fn bold(mut self) -> Self {
        self.style.font_weight = Some(parley::style::FontWeight::BOLD);
        self
    }

    pub fn weight(mut self, weight: parley::style::FontWeight) -> Self {
        self.style.font_weight = Some(weight);
        self
    }

    pub fn italic(mut self) -> Self {
        self.style.font_style = Some(FontStyle::Italic);
        self
    }

    pub fn font_style(mut self, style: FontStyle) -> Self {
        self.style.font_style = Some(style);
        self
    }

    pub fn font_size(mut self, size: f32) -> Self {
        self.style.font_size = Some(size);
        self
    }

    pub fn underline(mut self) -> Self {
        self.style.underline = true;
        self
    }

    pub fn strikethrough(mut self) -> Self {
        self.style.strikethrough = true;
        self
    }

    pub fn style(mut self, style: SpanStyle) -> Self {
        self.style = style;
        self
    }

    /// Configures a full hover style to apply when the mouse cursor hovers over this span.
    pub fn hover_style(mut self, style: SpanStyle) -> Self {
        self.hover_style = Some(style);
        self
    }

    /// Convenience builder to override text color on hover.
    pub fn hover_color(mut self, color: Color) -> Self {
        let mut h = self.hover_style.unwrap_or_default();
        h.color = Some(color);
        self.hover_style = Some(h);
        self
    }

    /// Convenience builder to add an underline on hover.
    pub fn hover_underline(mut self) -> Self {
        let mut h = self.hover_style.unwrap_or_default();
        h.underline = true;
        self.hover_style = Some(h);
        self
    }

    /// Convenience builder to make text bold on hover.
    pub fn hover_bold(mut self) -> Self {
        let mut h = self.hover_style.unwrap_or_default();
        h.font_weight = Some(parley::style::FontWeight::BOLD);
        self.hover_style = Some(h);
        self
    }

    /// Convenience builder to set a specific font weight on hover.
    pub fn hover_weight(mut self, weight: parley::style::FontWeight) -> Self {
        let mut h = self.hover_style.unwrap_or_default();
        h.font_weight = Some(weight);
        self.hover_style = Some(h);
        self
    }

    /// Convenience builder to make text italic on hover.
    pub fn hover_italic(mut self) -> Self {
        let mut h = self.hover_style.unwrap_or_default();
        h.font_style = Some(FontStyle::Italic);
        self.hover_style = Some(h);
        self
    }

    /// Convenience builder to set font style on hover.
    pub fn hover_font_style(mut self, style: FontStyle) -> Self {
        let mut h = self.hover_style.unwrap_or_default();
        h.font_style = Some(style);
        self.hover_style = Some(h);
        self
    }

    /// Convenience builder to set font size on hover.
    pub fn hover_font_size(mut self, size: f32) -> Self {
        let mut h = self.hover_style.unwrap_or_default();
        h.font_size = Some(size);
        self.hover_style = Some(h);
        self
    }

    /// Convenience builder to add strikethrough on hover.
    pub fn hover_strikethrough(mut self) -> Self {
        let mut h = self.hover_style.unwrap_or_default();
        h.strikethrough = true;
        self.hover_style = Some(h);
        self
    }

    /// Converts this span to an untyped span for layout and rendering.
    pub fn to_untyped(&self) -> TextSpan<()> {
        TextSpan {
            range: self.range.clone(),
            style: self.style.clone(),
            hover_style: self.hover_style.clone(),
            id: None,
        }
    }
}

pub(crate) fn hash_spans(spans: &[TextSpan<()>]) -> u64 {
    if spans.is_empty() {
        return 0;
    }
    use std::hash::{Hash, Hasher};
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    for span in spans {
        span.range.start.hash(&mut hasher);
        span.range.end.hash(&mut hasher);
        if let Some(c) = span.style.color {
            c.as_u32().hash(&mut hasher);
        }
        if let Some(w) = span.style.font_weight {
            w.value().to_bits().hash(&mut hasher);
        }
        if let Some(s) = span.style.font_style {
            match s {
                FontStyle::Normal => 0u8.hash(&mut hasher),
                FontStyle::Italic => 1u8.hash(&mut hasher),
                FontStyle::Oblique(_) => 2u8.hash(&mut hasher),
            }
        }
        if let Some(sz) = span.style.font_size {
            sz.to_bits().hash(&mut hasher);
        }
        span.style.underline.hash(&mut hasher);
        span.style.strikethrough.hash(&mut hasher);
    }
    hasher.finish()
}

use hashbrown::Equivalent;

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct TextLayoutCacheKey {
    pub text: String,
    pub font_size_bits: u32,
    pub font_family: String,
    pub font_weight_bits: u32,
    pub font_style: u8,
    pub color_u32: u32,
    pub wrap: bool,
    pub strikethrough: bool,
    pub underline: bool,
    pub selection: Option<(usize, usize)>,
    pub preedit_range: Option<(usize, usize)>,
    pub inner_w_bits: u32,
    pub spans_hash: u64,
}

#[derive(Copy, Clone, Debug)]
pub struct TextLayoutLookupKey<'a> {
    pub text: &'a str,
    pub font_size_bits: u32,
    pub font_family: &'a str,
    pub font_weight_bits: u32,
    pub font_style: u8,
    pub color_u32: u32,
    pub wrap: bool,
    pub strikethrough: bool,
    pub underline: bool,
    pub selection: Option<(usize, usize)>,
    pub preedit_range: Option<(usize, usize)>,
    pub inner_w_bits: u32,
    pub spans_hash: u64,
}

impl<'a> std::hash::Hash for TextLayoutLookupKey<'a> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.text.hash(state);
        self.font_size_bits.hash(state);
        self.font_family.hash(state);
        self.font_weight_bits.hash(state);
        self.font_style.hash(state);
        self.color_u32.hash(state);
        self.wrap.hash(state);
        self.strikethrough.hash(state);
        self.underline.hash(state);
        self.selection.hash(state);
        self.preedit_range.hash(state);
        self.inner_w_bits.hash(state);
        self.spans_hash.hash(state);
    }
}

impl<'a> Equivalent<TextLayoutCacheKey> for TextLayoutLookupKey<'a> {
    fn equivalent(&self, key: &TextLayoutCacheKey) -> bool {
        self.text == key.text
            && self.font_size_bits == key.font_size_bits
            && self.font_family == key.font_family
            && self.font_weight_bits == key.font_weight_bits
            && self.font_style == key.font_style
            && self.color_u32 == key.color_u32
            && self.wrap == key.wrap
            && self.strikethrough == key.strikethrough
            && self.underline == key.underline
            && self.selection == key.selection
            && self.preedit_range == key.preedit_range
            && self.inner_w_bits == key.inner_w_bits
            && self.spans_hash == key.spans_hash
    }
}

impl<'a> TextLayoutLookupKey<'a> {
    pub fn to_cache_key(&self) -> TextLayoutCacheKey {
        TextLayoutCacheKey {
            text: self.text.to_string(),
            font_size_bits: self.font_size_bits,
            font_family: self.font_family.to_string(),
            font_weight_bits: self.font_weight_bits,
            font_style: self.font_style,
            color_u32: self.color_u32,
            wrap: self.wrap,
            strikethrough: self.strikethrough,
            underline: self.underline,
            selection: self.selection,
            preedit_range: self.preedit_range,
            inner_w_bits: self.inner_w_bits,
            spans_hash: self.spans_hash,
        }
    }
}

pub struct TextLayoutCacheEntry {
    pub layout: parley::Layout<Color>,
    pub actual_text_width: f32,
    pub actual_text_height: f32,
}

/// Holds the shared text rendering state.
pub struct TextContext {
    pub font_cx: FontContext,
    pub layout_cx: LayoutContext<Color>,
    pub scale_cx: ScaleContext,
    /// Current active generation of cached layouts.
    pub current_cache: hashbrown::HashMap<TextLayoutCacheKey, Arc<TextLayoutCacheEntry>>,
    /// Previous generation of cached layouts. Items queried here are promoted to `current_cache`.
    pub previous_cache: hashbrown::HashMap<TextLayoutCacheKey, Arc<TextLayoutCacheEntry>>,
    /// Maximum capacity per generation before aging out `previous_cache`.
    pub generation_capacity: usize,
}

impl TextContext {
    pub fn new() -> Self {
        Self {
            font_cx: FontContext::new(),
            layout_cx: LayoutContext::new(),
            scale_cx: ScaleContext::new(),
            current_cache: hashbrown::HashMap::new(),
            previous_cache: hashbrown::HashMap::new(),
            generation_capacity: 4096,
        }
    }

    /// Registers raw font bytes (.ttf or .otf) into the Parley font collection.
    pub fn register_fonts(&mut self, font_data: Vec<u8>) {
        self.font_cx
            .collection
            .register_fonts(font_data.into(), None);
        self.clear_cache();
    }

    /// Clears both generations of the layout cache.
    pub fn clear_cache(&mut self) {
        self.current_cache.clear();
        self.previous_cache.clear();
    }

    /// Returns the total number of cached layout entries across both generations.
    pub fn cached_layout_count(&self) -> usize {
        self.current_cache.len() + self.previous_cache.len()
    }

    /// Loads and registers a font file from disk.
    pub fn register_font_file(&mut self, path: impl AsRef<std::path::Path>) -> std::io::Result<()> {
        let data = std::fs::read(path)?;
        self.register_fonts(data);
        Ok(())
    }

    pub fn get_or_create_layout(
        &mut self,
        text: &str,
        text_style: &TextStyle,
        avail_w: f32,
        selection: Option<(usize, usize)>,
        preedit_range: Option<(usize, usize)>,
        spans: &[TextSpan<()>],
    ) -> Arc<TextLayoutCacheEntry> {
        let font_style_u8 = match text_style.font_style {
            FontStyle::Normal => 0,
            FontStyle::Italic => 1,
            FontStyle::Oblique(_) => 2,
        };

        let inner_w_bits = if text_style.wrap && avail_w.is_finite() && avail_w > 0.0 {
            avail_w.to_bits()
        } else {
            u32::MAX
        };

        let spans_hash = hash_spans(spans);

        let lookup_key = TextLayoutLookupKey {
            text,
            font_size_bits: text_style.font_size.to_bits(),
            font_family: &text_style.font_family,
            font_weight_bits: text_style.font_weight.value().to_bits(),
            font_style: font_style_u8,
            color_u32: text_style.color.as_u32(),
            wrap: text_style.wrap,
            strikethrough: text_style.strikethrough,
            underline: text_style.underline,
            selection,
            preedit_range,
            inner_w_bits,
            spans_hash,
        };

        // 1. Check current active generation (fast path, zero allocation)
        if let Some(entry) = self.current_cache.get(&lookup_key) {
            return Arc::clone(entry);
        }

        // 2. Check previous generation; if found, promote to current generation (zero allocation)
        if let Some((prev_key, entry)) = self.previous_cache.remove_entry(&lookup_key) {
            let cloned_entry = Arc::clone(&entry);
            if self.current_cache.len() >= self.generation_capacity {
                self.previous_cache = std::mem::take(&mut self.current_cache);
            }
            self.current_cache.insert(prev_key, entry);
            return cloned_entry;
        }

        let display_scale = 1.0;
        let quantize = true;

        let mut builder =
            self.layout_cx
                .ranged_builder(&mut self.font_cx, text, display_scale, quantize);

        builder.push_default(StyleProperty::Brush(text_style.color));
        builder.push_default(StyleProperty::FontSize(text_style.font_size));
        builder.push_default(StyleProperty::LineHeight(LineHeight::FontSizeRelative(
            text_style.line_height.resolve(),
        )));
        builder.push_default(StyleProperty::FontWeight(text_style.font_weight));
        builder.push_default(StyleProperty::FontStyle(text_style.font_style));
        builder.push_default(parley::style::FontFamily::from(
            text_style.font_family.as_ref(),
        ));
        if text_style.wrap {
            builder.push_default(StyleProperty::OverflowWrap(text_style.overflow_wrap));
        }

        if text_style.strikethrough {
            builder.push_default(StyleProperty::Strikethrough(true));
        }

        if text_style.underline {
            builder.push_default(StyleProperty::Underline(true));
        }

        if let Some((start, end)) = preedit_range {
            builder.push(StyleProperty::Underline(true), start..end);
        }

        if let Some((start, end)) = selection {
            builder.push(StyleProperty::Brush(text_style.selection_color), start..end);
        }

        for span in spans {
            let start = span.range.start.min(text.len());
            let end = span.range.end.min(text.len());
            if start >= end {
                continue;
            }

            if let Some(color) = span.style.color {
                builder.push(StyleProperty::Brush(color), start..end);
            }
            if let Some(weight) = span.style.font_weight {
                builder.push(StyleProperty::FontWeight(weight), start..end);
            }
            if let Some(style) = span.style.font_style {
                builder.push(StyleProperty::FontStyle(style), start..end);
            }
            if let Some(size) = span.style.font_size {
                builder.push(StyleProperty::FontSize(size), start..end);
            }
            if span.style.underline {
                builder.push(StyleProperty::Underline(true), start..end);
            }
            if span.style.strikethrough {
                builder.push(StyleProperty::Strikethrough(true), start..end);
            }
        }

        let mut layout = builder.build(text);

        let max_advance = if text_style.wrap && avail_w.is_finite() && avail_w > 0.0 {
            Some(avail_w + 0.5)
        } else {
            None
        };
        layout.break_all_lines(max_advance);
        let actual_text_width = layout.width();
        let actual_text_height = layout.height();

        let entry = Arc::new(TextLayoutCacheEntry {
            layout,
            actual_text_width,
            actual_text_height,
        });

        if self.current_cache.len() >= self.generation_capacity {
            self.previous_cache = std::mem::take(&mut self.current_cache);
        }

        self.current_cache
            .insert(lookup_key.to_cache_key(), Arc::clone(&entry));
        entry
    }
}

pub type SharedTextContext = Arc<Mutex<TextContext>>;

pub fn measure_text(
    text: &str,
    text_style: &TextStyle,
    avail_w: f32,
    _avail_h: f32,
    shared_ctx: &SharedTextContext,
    spans: &[TextSpan<()>],
) -> TextComputedOutput {
    let mut ctx_guard = shared_ctx.lock().unwrap();
    let entry = ctx_guard.get_or_create_layout(text, text_style, avail_w, None, None, spans);

    TextComputedOutput {
        computed_width: entry.actual_text_width.ceil(),
        computed_height: entry.actual_text_height.ceil(),
        baseline_offset: entry
            .layout
            .lines()
            .next()
            .map(|l| l.metrics().ascent)
            .unwrap_or(text_style.font_size),
    }
}

pub fn hit_test_text(
    text: &str,
    text_style: &TextStyle,
    avail_w: f32,
    avail_h: f32,
    x: f32,
    y: f32,
    shared_ctx: &SharedTextContext,
    spans: &[TextSpan<()>],
) -> usize {
    let mut ctx_guard = shared_ctx.lock().unwrap();
    let entry = ctx_guard.get_or_create_layout(text, text_style, avail_w, None, None, spans);
    let layout = &entry.layout;
    let actual_text_width = entry.actual_text_width;
    let actual_text_height = entry.actual_text_height;

    let horizontal_offset = match text_style.alignment {
        parley::layout::Alignment::Center => {
            if avail_w.is_finite() && avail_w > 0.0 {
                ((avail_w - actual_text_width) / 2.0).max(0.0)
            } else {
                0.0
            }
        }
        parley::layout::Alignment::End | parley::layout::Alignment::Right => {
            if avail_w.is_finite() && avail_w > 0.0 {
                (avail_w - actual_text_width).max(0.0)
            } else {
                0.0
            }
        }
        _ => 0.0,
    };

    let vertical_offset = match text_style.vertical_alignment {
        crate::style::VerticalAlignment::Top => 0.0,
        crate::style::VerticalAlignment::Center => {
            if avail_h.is_finite() && avail_h > 0.0 {
                ((avail_h - actual_text_height) / 2.0).max(0.0)
            } else {
                0.0
            }
        }
        crate::style::VerticalAlignment::Bottom => {
            if avail_h.is_finite() && avail_h > 0.0 {
                (avail_h - actual_text_height).max(0.0)
            } else {
                0.0
            }
        }
    };

    let rel_x = x - horizontal_offset;
    let rel_y = y - vertical_offset;

    if let Some((cluster, side)) = Cluster::from_point(layout, rel_x, rel_y) {
        let is_leading = side == ClusterSide::Left;
        if cluster.is_rtl() {
            if is_leading {
                cluster.text_range().end
            } else {
                cluster.text_range().start
            }
        } else {
            if is_leading || cluster.is_line_break() == Some(BreakReason::Explicit) {
                cluster.text_range().start
            } else {
                cluster.text_range().end
            }
        }
    } else {
        let cursor = Cursor::from_point(layout, rel_x, rel_y);
        cursor.index()
    }
}

/// Returns the bounding rectangles (in local text coordinates `[x, y, w, h]`) of a byte range in the text.
pub fn get_range_geometry(
    text: &str,
    text_style: &TextStyle,
    avail_w: f32,
    avail_h: f32,
    range: std::ops::Range<usize>,
    shared_ctx: &SharedTextContext,
    spans: &[TextSpan<()>],
) -> Vec<[f32; 4]> {
    let mut ctx_guard = shared_ctx.lock().unwrap();
    let entry = ctx_guard.get_or_create_layout(text, text_style, avail_w, None, None, spans);
    let layout = &entry.layout;
    let actual_text_width = entry.actual_text_width;
    let actual_text_height = entry.actual_text_height;

    let horizontal_offset = match text_style.alignment {
        parley::layout::Alignment::Center => {
            if avail_w.is_finite() && avail_w > 0.0 {
                ((avail_w - actual_text_width) / 2.0).max(0.0)
            } else {
                0.0
            }
        }
        parley::layout::Alignment::End | parley::layout::Alignment::Right => {
            if avail_w.is_finite() && avail_w > 0.0 {
                (avail_w - actual_text_width).max(0.0)
            } else {
                0.0
            }
        }
        _ => 0.0,
    };

    let vertical_offset = match text_style.vertical_alignment {
        crate::style::VerticalAlignment::Top => 0.0,
        crate::style::VerticalAlignment::Center => {
            if avail_h.is_finite() && avail_h > 0.0 {
                ((avail_h - actual_text_height) / 2.0).max(0.0)
            } else {
                0.0
            }
        }
        crate::style::VerticalAlignment::Bottom => {
            if avail_h.is_finite() && avail_h > 0.0 {
                (avail_h - actual_text_height).max(0.0)
            } else {
                0.0
            }
        }
    };

    let start = range.start.min(text.len());
    let end = range.end.min(text.len());
    if start >= end {
        return Vec::new();
    }

    use parley::Selection;
    let start_cursor = Cursor::from_byte_index(layout, start, parley::layout::Affinity::Downstream);
    let end_cursor = Cursor::from_byte_index(layout, end, parley::layout::Affinity::Upstream);
    let selection_obj = Selection::new(start_cursor, end_cursor);

    let mut rects = Vec::new();
    for (bbox, _line_idx) in selection_obj.geometry(layout) {
        rects.push([
            horizontal_offset + bbox.x0 as f32,
            vertical_offset + bbox.y0 as f32,
            (bbox.x1 - bbox.x0) as f32,
            (bbox.y1 - bbox.y0) as f32,
        ]);
    }
    rects
}

pub fn get_cursor_geometry(
    text: &str,
    text_style: &TextStyle,
    avail_w: f32,
    cursor_index: usize,
    shared_ctx: &SharedTextContext,
) -> (f32, f32, f32) {
    let mut text_context = shared_ctx.lock().unwrap();
    let TextContext {
        font_cx, layout_cx, ..
    } = &mut *text_context;

    let mut builder = layout_cx.ranged_builder(font_cx, text, 1.0, true);

    builder.push_default(StyleProperty::FontSize(text_style.font_size));
    builder.push_default(parley::style::FontFamily::from(
        text_style.font_family.as_ref(),
    ));
    builder.push_default(StyleProperty::FontWeight(text_style.font_weight));
    builder.push_default(StyleProperty::FontStyle(text_style.font_style));

    if text_style.wrap {
        builder.push_default(StyleProperty::OverflowWrap(text_style.overflow_wrap));
    }

    if text_style.strikethrough {
        builder.push_default(StyleProperty::Strikethrough(true));
    }

    if text_style.underline {
        builder.push_default(StyleProperty::Underline(true));
    }

    let mut layout = builder.build(text);
    let max_advance = if text_style.wrap && avail_w.is_finite() && avail_w > 0.0 {
        Some(avail_w)
    } else {
        None
    };

    layout.break_all_lines(max_advance);
    layout.align(text_style.alignment, AlignmentOptions::default());

    let actual_text_width = layout.width();
    let horizontal_offset = match text_style.alignment {
        parley::layout::Alignment::Center => {
            if avail_w.is_finite() && avail_w > 0.0 {
                ((avail_w - actual_text_width) / 2.0).max(0.0)
            } else {
                0.0
            }
        }
        parley::layout::Alignment::End | parley::layout::Alignment::Right => {
            if avail_w.is_finite() && avail_w > 0.0 {
                (avail_w - actual_text_width).max(0.0)
            } else {
                0.0
            }
        }
        _ => 0.0,
    };

    let cursor_layout =
        Cursor::from_byte_index(&layout, cursor_index, parley::layout::Affinity::Downstream);
    let geom = cursor_layout.geometry(&layout, 1.0);
    let h = (geom.y1 - geom.y0) as f32;
    (geom.x0 as f32 + horizontal_offset, geom.y0 as f32, h)
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TextComputedOutput {
    pub computed_width: f32,
    pub computed_height: f32,
    pub baseline_offset: f32,
}

impl Default for TextComputedOutput {
    fn default() -> Self {
        Self {
            computed_width: 0.0,
            computed_height: 0.0,
            baseline_offset: 0.0,
        }
    }
}
impl From<crate::layout::TextMetrics> for TextComputedOutput {
    fn from(m: crate::layout::TextMetrics) -> Self {
        Self {
            computed_width: m.width,
            computed_height: m.height,
            baseline_offset: m.baseline_offset,
        }
    }
}

impl From<TextComputedOutput> for crate::layout::TextMetrics {
    fn from(o: TextComputedOutput) -> Self {
        Self {
            width: o.computed_width,
            height: o.computed_height,
            baseline_offset: o.baseline_offset,
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct TextRenderInfo {
    pub style: TextStyle,
    pub cursor: Option<usize>,
    pub selection: Option<(usize, usize)>,
    pub preedit_range: Option<(usize, usize)>,
    pub spans: Vec<TextSpan<()>>,
}

impl Default for TextRenderInfo {
    fn default() -> Self {
        Self {
            style: TextStyle::default(),
            cursor: None,
            selection: None,
            preedit_range: None,
            spans: Vec::new(),
        }
    }
}

impl TextRenderInfo {
    pub fn new(style: TextStyle) -> Self {
        Self {
            style,
            cursor: None,
            selection: None,
            preedit_range: None,
            spans: Vec::new(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::clr;
    use parley::layout::PositionedLayoutItem;

    #[test]
    fn test_layout_span_underline_and_brush() {
        let mut text_cx = TextContext::new();
        let text_style = TextStyle::default();
        let spans = vec![
            TextSpan::new(0..2).color(clr!(blue)).underline(),
            TextSpan::new(3..12).color(clr!(red)),
        ];

        let entry = text_cx.get_or_create_layout(
            "fn calculate",
            &text_style,
            f32::INFINITY,
            None,
            None,
            &spans,
        );

        let line = entry
            .layout
            .lines()
            .next()
            .expect("Expected at least one line");
        let items: Vec<_> = line.items().collect();
        assert!(!items.is_empty());

        let mut found_underlined_blue = false;
        let mut found_non_underlined_red = false;

        for item in items {
            if let PositionedLayoutItem::GlyphRun(glyph_run) = item {
                if glyph_run.style().underline.is_some() {
                    assert_eq!(glyph_run.style().brush, clr!(blue));
                    found_underlined_blue = true;
                } else if glyph_run.style().brush == clr!(red) {
                    assert!(glyph_run.style().underline.is_none());
                    found_non_underlined_red = true;
                }
            }
        }

        assert!(
            found_underlined_blue,
            "Must find an underlined run with blue brush"
        );
        assert!(
            found_non_underlined_red,
            "Must find a non-underlined run with red brush"
        );
    }

    #[test]
    fn test_text_layout_cache_generational_promotion() {
        let mut text_cx = TextContext::new();
        text_cx.generation_capacity = 3; // Small generation capacity for deterministic testing
        let style = TextStyle::default();

        // 1. Insert 3 items to fill generation 0
        let entry1 = text_cx.get_or_create_layout("Item 1", &style, 100.0, None, None, &[]);
        let _entry2 = text_cx.get_or_create_layout("Item 2", &style, 100.0, None, None, &[]);
        let _entry3 = text_cx.get_or_create_layout("Item 3", &style, 100.0, None, None, &[]);

        assert_eq!(text_cx.current_cache.len(), 3);
        assert_eq!(text_cx.previous_cache.len(), 0);

        // 2. Insert 4th item -> causes generation rollover!
        // current_cache moves to previous_cache; 4th item goes into new current_cache
        let _entry4 = text_cx.get_or_create_layout("Item 4", &style, 100.0, None, None, &[]);
        assert_eq!(text_cx.current_cache.len(), 1);
        assert_eq!(text_cx.previous_cache.len(), 3);

        // 3. Query "Item 1" which lives in previous_cache -> should be promoted to current_cache!
        let entry1_hit = text_cx.get_or_create_layout("Item 1", &style, 100.0, None, None, &[]);
        assert!(Arc::ptr_eq(&entry1, &entry1_hit));
        assert_eq!(text_cx.current_cache.len(), 2);
        assert_eq!(text_cx.previous_cache.len(), 2); // "Item 1" was moved out of previous_cache

        // 4. Fill up current_cache until rollover again
        let _entry5 = text_cx.get_or_create_layout("Item 5", &style, 100.0, None, None, &[]);
        let _entry6 = text_cx.get_or_create_layout("Item 6", &style, 100.0, None, None, &[]);
        // Now current has 1, 4, 5, 6 -> rollover!
        // "Item 2" and "Item 3" (which were never queried) get naturally evicted!
        assert!(
            !text_cx
                .current_cache
                .keys()
                .any(|k| k.text == "Item 2" || k.text == "Item 3")
        );
        assert!(
            !text_cx
                .previous_cache
                .keys()
                .any(|k| k.text == "Item 2" || k.text == "Item 3")
        );
        // But "Item 1" survived into previous_cache because it was promoted!
        assert!(text_cx.previous_cache.keys().any(|k| k.text == "Item 1"));
    }
}