fret-core 0.1.0

Core contracts, IDs, geometry, events, and shared data types for the Fret framework.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
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
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
use crate::{
    TextBlobId,
    geometry::{Point, Px, Rect},
    ids::FontId,
};
use serde::{Deserialize, Serialize};
use smol_str::SmolStr;
use std::sync::Arc;

use crate::scene::Color;

/// Overrides for the default font family selection used by the text system.
///
/// This is intended to be persisted in settings/config files and applied by the host/runner.
/// It configures the three generic families used by `TextStyle.font` (`Ui`/`Serif`/`Monospace`).
///
/// Notes:
/// - Entries are treated as ordered "try this first" candidates; backends will pick the first
///   installed family name and ignore unknown ones.
/// - This does not attempt to model per-script fallback chains yet (ADR 0029); for now, we expose
///   a single `common_fallback` list for cross-script "no tofu" baseline behavior.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct TextFontFamilyConfig {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub ui_sans: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub ui_serif: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub ui_mono: Vec<String>,
    /// Controls how `common_fallback` is injected into the effective font stack.
    ///
    /// - `platform_default`: prefer deterministic injection on wasm/bundled-only environments; on
    ///   native system-font builds, keep named families on the system-fallback lane but inject the
    ///   framework no-tofu baseline into generic UI families.
    /// - `none`: never inject `common_fallback` into the explicit stack (system fallback only).
    /// - `common_fallback`: inject `common_fallback` into both generic and named family stacks to
    ///   enforce a "no tofu" baseline (may override system fallback selection on desktop).
    #[serde(
        default,
        skip_serializing_if = "TextCommonFallbackInjection::is_platform_default"
    )]
    pub common_fallback_injection: TextCommonFallbackInjection,
    /// Additional family candidates appended to the framework fallback stack.
    ///
    /// This list is intended to cover "missing glyph" cases for mixed-script UIs (CJK + emoji +
    /// RTL) without requiring per-span font selection.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub common_fallback: Vec<String>,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TextCommonFallbackInjection {
    #[default]
    PlatformDefault,
    None,
    CommonFallback,
}

impl TextCommonFallbackInjection {
    fn is_platform_default(v: &TextCommonFallbackInjection) -> bool {
        *v == TextCommonFallbackInjection::PlatformDefault
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct FontWeight(pub u16);

impl FontWeight {
    pub const THIN: Self = Self(100);
    pub const EXTRA_LIGHT: Self = Self(200);
    pub const LIGHT: Self = Self(300);
    pub const NORMAL: Self = Self(400);
    pub const MEDIUM: Self = Self(500);
    pub const SEMIBOLD: Self = Self(600);
    pub const BOLD: Self = Self(700);
    pub const EXTRA_BOLD: Self = Self(800);
    pub const BLACK: Self = Self(900);
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TextWrap {
    None,
    Word,
    /// Attempt to balance line breaks for wrapped text.
    ///
    /// This is intended to approximate CSS `text-wrap: balance` / Tailwind `text-balance`:
    /// keep the same overall wrapping behavior as `Word`, but avoid a very short last line when
    /// possible.
    ///
    /// Note: this is an outcome-driven policy; implementations may use heuristics.
    Balance,
    /// Wrap at word boundaries, but allow breaking long tokens when necessary.
    ///
    /// This is similar to CSS `overflow-wrap: break-word` (with `word-break: normal`): prefer
    /// wrapping at whitespace/line-break opportunities, but fall back to mid-token breaks when a
    /// single "word" exceeds the available width.
    WordBreak,
    /// Break between grapheme clusters when needed.
    ///
    /// This is intended for editor surfaces (CJK, file paths/URLs, code identifiers) where long
    /// "tokens" must still wrap without relying on whitespace or word boundaries.
    Grapheme,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum TextOverflow {
    #[default]
    Clip,
    Ellipsis,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum TextAlign {
    #[default]
    Start,
    Center,
    End,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TextVerticalPlacement {
    /// Center the prepared text box (`TextMetrics.size.height`) within the allocated bounds.
    ///
    /// This is the historical Fret behavior and remains the default in v1.
    #[default]
    CenterMetricsBox,
    /// Treat the allocated bounds height as the effective line box height for single-line text
    /// and compute baseline placement via a CSS/GPUI-like "half-leading" model:
    ///
    /// - `padding_top = (bounds_h - ascent - descent) / 2`
    /// - `baseline_y = padding_top + ascent`
    ///
    /// Notes:
    /// - This mode is intended for fixed-height controls (tabs, pills, buttons) where authors
    ///   want a stable baseline placement without per-component y-offset hacks.
    /// - Implementations should fall back to `CenterMetricsBox` when line metrics are unavailable
    ///   or the prepared text contains multiple lines.
    BoundsAsLineBox,
}

impl TextVerticalPlacement {
    fn is_center_metrics_box(v: &TextVerticalPlacement) -> bool {
        *v == TextVerticalPlacement::CenterMetricsBox
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TextLineHeightPolicy {
    /// Expand the line box to fit font extents (never reduce below ascent+descent).
    ///
    /// This avoids clipping but can cause line height to vary when fallback fonts or emoji
    /// participate in shaping.
    #[default]
    ExpandToFit,
    /// Keep a fixed line box derived from style (px or ratio) and compute baseline placement via
    /// a CSS/GPUI-like "half-leading" model.
    ///
    /// This favors stable layout for UI surfaces (forms, lists, buttons). Glyphs whose ink
    /// extends beyond the line box may be clipped by the caller's bounds.
    FixedFromStyle,
}

impl TextLineHeightPolicy {
    fn is_expand_to_fit(v: &TextLineHeightPolicy) -> bool {
        *v == TextLineHeightPolicy::ExpandToFit
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TextLeadingDistribution {
    /// Distribute extra leading evenly above and below the text box ("half-leading").
    #[default]
    Even,
    /// Distribute extra leading proportionally by ascent/descent.
    Proportional,
}

impl TextLeadingDistribution {
    fn is_even(v: &TextLeadingDistribution) -> bool {
        *v == TextLeadingDistribution::Even
    }
}

/// Paragraph-level strut style used to stabilize line box metrics across fallback runs.
///
/// This is a mechanism-only surface. Ecosystem presets (e.g. `fret-ui-kit::typography`) decide
/// when to enable it (see ADR 0287 and related workstreams).
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct TextStrutStyle {
    /// Optional font override used for strut metrics (defaults to `TextStyle.font`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub font: Option<FontId>,
    /// Optional font size override used for strut metrics (defaults to `TextStyle.size`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub size: Option<Px>,
    /// Optional line height override, in logical px.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub line_height: Option<Px>,
    /// Optional line height override, expressed as a multiple of the effective size.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub line_height_em: Option<f32>,
    /// Optional leading distribution override (defaults to `TextStyle.leading_distribution`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub leading_distribution: Option<TextLeadingDistribution>,
    /// If true, force the strut line box even when the style's policy is `ExpandToFit`.
    ///
    /// This mirrors the intent of Flutter's `forceStrutHeight`: stabilize layout for UI-like
    /// multiline surfaces, at the cost of potential glyph ink clipping.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub force: bool,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TextConstraints {
    pub max_width: Option<Px>,
    pub wrap: TextWrap,
    pub overflow: TextOverflow,
    pub align: TextAlign,
    /// Window/device scale factor used for rasterization and caching.
    ///
    /// UI/layout coordinates remain in logical pixels. Implementations should rasterize at
    /// `style.size * scale_factor` (and any other scale-dependent parameters), then return metrics
    /// back in logical units.
    pub scale_factor: f32,
}

impl Default for TextConstraints {
    fn default() -> Self {
        Self {
            max_width: None,
            wrap: TextWrap::Word,
            overflow: TextOverflow::Clip,
            align: TextAlign::Start,
            scale_factor: 1.0,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TextStyle {
    pub font: FontId,
    pub size: Px,
    pub weight: FontWeight,
    pub slant: TextSlant,
    /// Optional line height override, in logical px.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub line_height: Option<Px>,
    /// Optional line height override, expressed as a multiple of `size` (CSS-like).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub line_height_em: Option<f32>,
    /// Controls whether the line box can expand beyond the style-provided line height.
    #[serde(
        default,
        skip_serializing_if = "TextLineHeightPolicy::is_expand_to_fit"
    )]
    pub line_height_policy: TextLineHeightPolicy,
    /// Optional tracking (letter spacing) override, in EM.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub letter_spacing_em: Option<f32>,
    /// Optional OpenType feature overrides applied to the whole text run.
    ///
    /// This is intended for UI authoring ergonomics (e.g. `tabular-nums`) and editor-grade
    /// surfaces that want a stable default without requiring attributed spans.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub features: Vec<TextFontFeatureSetting>,
    /// Optional variable font axis overrides applied to the whole text run.
    ///
    /// Note: `wght` overlaps with `weight`. Shaping backends should interpret `wght` as an
    /// override (mapping it to `FontWeight`) and exclude it from variation lists.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub axes: Vec<TextFontAxisSetting>,
    /// Controls how the prepared text is vertically placed inside an allocated bounds height.
    ///
    /// This is a mechanism-level knob intended for fixed-height controls. See
    /// `TextVerticalPlacement` for details.
    #[serde(
        default,
        skip_serializing_if = "TextVerticalPlacement::is_center_metrics_box"
    )]
    pub vertical_placement: TextVerticalPlacement,
    /// Controls how extra leading is distributed above/below the text box when a line height is
    /// larger than font extents.
    #[serde(default, skip_serializing_if = "TextLeadingDistribution::is_even")]
    pub leading_distribution: TextLeadingDistribution,
    /// Optional paragraph-level strut style used to stabilize line box metrics across fallback
    /// runs (especially useful for multiline UI-like surfaces).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub strut_style: Option<TextStrutStyle>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TextSlant {
    #[default]
    Normal,
    Italic,
    Oblique,
}

impl Default for TextStyle {
    fn default() -> Self {
        Self {
            font: FontId::default(),
            size: Px(13.0),
            weight: FontWeight::NORMAL,
            slant: TextSlant::Normal,
            line_height: None,
            line_height_em: None,
            line_height_policy: TextLineHeightPolicy::ExpandToFit,
            letter_spacing_em: None,
            features: Vec::new(),
            axes: Vec::new(),
            vertical_placement: TextVerticalPlacement::CenterMetricsBox,
            leading_distribution: TextLeadingDistribution::Even,
            strut_style: None,
        }
    }
}

/// Partial, mergeable subtree text-style refinement used for inherited typography defaults.
///
/// This is intentionally narrower than [`TextStyle`]: v1 only carries the portable fields needed
/// for passive-text cascade (`Text`, `StyledText`, `SelectableText`).
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct TextStyleRefinement {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub font: Option<FontId>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub size: Option<Px>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub weight: Option<FontWeight>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub slant: Option<TextSlant>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub line_height: Option<Px>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub line_height_em: Option<f32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub line_height_policy: Option<TextLineHeightPolicy>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub letter_spacing_em: Option<f32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub vertical_placement: Option<TextVerticalPlacement>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub leading_distribution: Option<TextLeadingDistribution>,
}

impl TextStyleRefinement {
    pub fn is_empty(&self) -> bool {
        self.font.is_none()
            && self.size.is_none()
            && self.weight.is_none()
            && self.slant.is_none()
            && self.line_height.is_none()
            && self.line_height_em.is_none()
            && self.line_height_policy.is_none()
            && self.letter_spacing_em.is_none()
            && self.vertical_placement.is_none()
            && self.leading_distribution.is_none()
    }

    pub fn merge(&mut self, other: &Self) {
        if let Some(font) = other.font.clone() {
            self.font = Some(font);
        }
        if let Some(size) = other.size {
            self.size = Some(size);
        }
        if let Some(weight) = other.weight {
            self.weight = Some(weight);
        }
        if let Some(slant) = other.slant {
            self.slant = Some(slant);
        }
        if let Some(line_height) = other.line_height {
            self.line_height = Some(line_height);
            self.line_height_em = None;
        } else if let Some(line_height_em) = other.line_height_em {
            self.line_height_em = Some(line_height_em);
            self.line_height = None;
        }
        if let Some(line_height_policy) = other.line_height_policy {
            self.line_height_policy = Some(line_height_policy);
        }
        if let Some(letter_spacing_em) = other.letter_spacing_em {
            self.letter_spacing_em = Some(letter_spacing_em);
        }
        if let Some(vertical_placement) = other.vertical_placement {
            self.vertical_placement = Some(vertical_placement);
        }
        if let Some(leading_distribution) = other.leading_distribution {
            self.leading_distribution = Some(leading_distribution);
        }
    }

    pub fn merged(&self, other: &Self) -> Self {
        let mut merged = self.clone();
        merged.merge(other);
        merged
    }
}

impl TextStyle {
    pub fn refine(&mut self, refinement: &TextStyleRefinement) {
        if let Some(font) = refinement.font.clone() {
            self.font = font;
        }
        if let Some(size) = refinement.size {
            self.size = size;
        }
        if let Some(weight) = refinement.weight {
            self.weight = weight;
        }
        if let Some(slant) = refinement.slant {
            self.slant = slant;
        }
        if let Some(line_height) = refinement.line_height {
            self.line_height = Some(line_height);
            self.line_height_em = None;
        } else if let Some(line_height_em) = refinement.line_height_em {
            self.line_height_em = Some(line_height_em);
            self.line_height = None;
        }
        if let Some(line_height_policy) = refinement.line_height_policy {
            self.line_height_policy = line_height_policy;
        }
        if let Some(letter_spacing_em) = refinement.letter_spacing_em {
            self.letter_spacing_em = Some(letter_spacing_em);
        }
        if let Some(vertical_placement) = refinement.vertical_placement {
            self.vertical_placement = vertical_placement;
        }
        if let Some(leading_distribution) = refinement.leading_distribution {
            self.leading_distribution = leading_distribution;
        }
    }

    pub fn refined(mut self, refinement: &TextStyleRefinement) -> Self {
        self.refine(refinement);
        self
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TextMetrics {
    pub size: crate::Size,
    pub baseline: Px,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TextLineMetrics {
    pub ascent: Px,
    pub descent: Px,
    pub line_height: Px,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TextInkMetrics {
    pub ascent: Px,
    pub descent: Px,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CaretAffinity {
    Upstream,
    Downstream,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct HitTestResult {
    pub index: usize,
    pub affinity: CaretAffinity,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DecorationLineStyle {
    #[default]
    Solid,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct UnderlineStyle {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub color: Option<Color>,
    #[serde(default)]
    pub style: DecorationLineStyle,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StrikethroughStyle {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub color: Option<Color>,
    #[serde(default)]
    pub style: DecorationLineStyle,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct TextShapingStyle {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub font: Option<FontId>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub weight: Option<FontWeight>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub slant: Option<TextSlant>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub letter_spacing_em: Option<f32>,
    /// Explicit OpenType feature overrides (best-effort).
    ///
    /// This is intended for editor-grade text surfaces (e.g. ligature policy in code) and
    /// diagnostics. Callers should treat this as best-effort: if the resolved face does not
    /// support a requested tag, it will be ignored by shaping backends.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub features: Vec<TextFontFeatureSetting>,
    /// Explicit variable font axis overrides.
    ///
    /// This is an advanced surface intended for code editors and diagnostics. Callers should treat
    /// this as best-effort: if the requested axis is not supported by the resolved font face, it
    /// will be ignored by the shaping backend.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub axes: Vec<TextFontAxisSetting>,
}

/// A single OpenType font feature setting, identified by a 4-byte OpenType feature tag.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TextFontFeatureSetting {
    /// 4-byte OpenType feature tag (e.g. "liga", "calt", "ss01").
    pub tag: SmolStr,
    /// OpenType feature value (best-effort). Conventionally 0=off, 1=on.
    pub value: u32,
}

/// A single variable font axis setting, identified by a 4-byte OpenType axis tag.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TextFontAxisSetting {
    pub tag: SmolStr,
    pub value: f32,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct TextPaintStyle {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fg: Option<Color>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bg: Option<Color>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub underline: Option<UnderlineStyle>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub strikethrough: Option<StrikethroughStyle>,
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct TextSpan {
    /// Span length in UTF-8 bytes.
    pub len: usize,
    #[serde(default)]
    pub shaping: TextShapingStyle,
    #[serde(default)]
    pub paint: TextPaintStyle,
}

impl TextSpan {
    pub fn new(len: usize) -> Self {
        Self {
            len,
            shaping: TextShapingStyle::default(),
            paint: TextPaintStyle::default(),
        }
    }
}

impl TextShapingStyle {
    pub fn with_font(mut self, font: FontId) -> Self {
        self.font = Some(font);
        self
    }

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

    pub fn with_slant(mut self, slant: TextSlant) -> Self {
        self.slant = Some(slant);
        self
    }

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

    pub fn with_axis(mut self, tag: impl Into<String>, value: f32) -> Self {
        self.axes.push(TextFontAxisSetting {
            tag: tag.into().into(),
            value,
        });
        self
    }

    pub fn with_feature(mut self, tag: impl Into<String>, value: u32) -> Self {
        self.features.push(TextFontFeatureSetting {
            tag: tag.into().into(),
            value,
        });
        self
    }
}

impl TextPaintStyle {
    pub fn with_fg(mut self, fg: Color) -> Self {
        self.fg = Some(fg);
        self
    }

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

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

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

#[derive(Debug, Clone, PartialEq)]
pub struct AttributedText {
    pub text: Arc<str>,
    pub spans: Arc<[TextSpan]>,
}

fn spans_are_valid(text: &str, spans: &[TextSpan]) -> bool {
    let mut offset = 0usize;
    for span in spans {
        let end = offset.saturating_add(span.len);
        if end > text.len() {
            return false;
        }
        if !text.is_char_boundary(offset) || !text.is_char_boundary(end) {
            return false;
        }
        offset = end;
    }
    offset == text.len()
}

impl AttributedText {
    pub fn new(text: impl Into<Arc<str>>, spans: impl Into<Arc<[TextSpan]>>) -> Self {
        let text: Arc<str> = text.into();
        let spans: Arc<[TextSpan]> = spans.into();
        debug_assert!(spans_are_valid(text.as_ref(), spans.as_ref()));
        Self { text, spans }
    }

    /// Returns true if `self` and `other` have identical shaping-relevant content.
    ///
    /// This intentionally ignores paint-only fields (e.g. colors, underlines). It is useful for
    /// caching/layout decisions where theme-driven paint changes should not force reshaping.
    pub fn shaping_eq(&self, other: &Self) -> bool {
        if self.text != other.text {
            return false;
        }
        if self.spans.len() != other.spans.len() {
            return false;
        }
        self.spans
            .iter()
            .zip(other.spans.iter())
            .all(|(a, b)| a.len == b.len && a.shaping == b.shaping)
    }

    pub fn is_valid(&self) -> bool {
        spans_are_valid(self.text.as_ref(), self.spans.as_ref())
    }
}

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

    #[test]
    fn attributed_text_shaping_eq_ignores_paint() {
        let text: Arc<str> = Arc::<str>::from("hello");
        let base = TextSpan {
            len: text.len(),
            shaping: Default::default(),
            paint: Default::default(),
        };

        let mut spans_a = vec![base.clone()];
        spans_a[0].paint.fg = Some(Color {
            r: 1.0,
            g: 0.0,
            b: 0.0,
            a: 1.0,
        });
        let mut spans_b = vec![base];
        spans_b[0].paint.fg = Some(Color {
            r: 0.0,
            g: 1.0,
            b: 0.0,
            a: 1.0,
        });

        let a = AttributedText::new(Arc::clone(&text), Arc::<[TextSpan]>::from(spans_a));
        let b = AttributedText::new(Arc::clone(&text), Arc::<[TextSpan]>::from(spans_b));
        assert_ne!(a, b, "full equality should include paint");
        assert!(
            a.shaping_eq(&b),
            "shaping_eq should ignore paint-only changes"
        );
    }

    #[test]
    fn attributed_text_shaping_eq_detects_shaping_changes() {
        let text: Arc<str> = Arc::<str>::from("hello");
        let spans_a = vec![TextSpan {
            len: text.len(),
            shaping: Default::default(),
            paint: Default::default(),
        }];
        let mut spans_b = spans_a.clone();
        spans_b[0].shaping.weight = Some(FontWeight(700));

        let a = AttributedText::new(Arc::clone(&text), Arc::<[TextSpan]>::from(spans_a));
        let b = AttributedText::new(Arc::clone(&text), Arc::<[TextSpan]>::from(spans_b));
        assert!(
            !a.shaping_eq(&b),
            "shaping_eq must treat shaping changes as unequal"
        );
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TextInputRef<'a> {
    Plain {
        text: &'a str,
        style: &'a TextStyle,
    },
    Attributed {
        text: &'a str,
        base: &'a TextStyle,
        spans: &'a [TextSpan],
    },
}

impl<'a> TextInputRef<'a> {
    pub fn plain(text: &'a str, style: &'a TextStyle) -> Self {
        Self::Plain { text, style }
    }

    pub fn attributed(text: &'a str, base: &'a TextStyle, spans: &'a [TextSpan]) -> Self {
        debug_assert!(spans_are_valid(text, spans));
        Self::Attributed { text, base, spans }
    }
}

#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum TextInput {
    Plain {
        text: Arc<str>,
        style: TextStyle,
    },
    Attributed {
        text: Arc<str>,
        base: TextStyle,
        spans: Arc<[TextSpan]>,
    },
}

impl TextInput {
    pub fn plain(text: impl Into<Arc<str>>, style: TextStyle) -> Self {
        Self::Plain {
            text: text.into(),
            style,
        }
    }

    pub fn attributed(
        text: impl Into<Arc<str>>,
        base: TextStyle,
        spans: impl Into<Arc<[TextSpan]>>,
    ) -> Self {
        Self::Attributed {
            text: text.into(),
            base,
            spans: spans.into(),
        }
    }

    pub fn text(&self) -> &str {
        match self {
            Self::Plain { text, .. } => text.as_ref(),
            Self::Attributed { text, .. } => text.as_ref(),
        }
    }
}

pub trait TextService {
    fn prepare(
        &mut self,
        input: &TextInput,
        constraints: TextConstraints,
    ) -> (TextBlobId, TextMetrics);

    fn prepare_str(
        &mut self,
        text: &str,
        style: &TextStyle,
        constraints: TextConstraints,
    ) -> (TextBlobId, TextMetrics) {
        let input = TextInput::plain(Arc::<str>::from(text), style.clone());
        self.prepare(&input, constraints)
    }

    fn prepare_rich(
        &mut self,
        rich: &AttributedText,
        base_style: &TextStyle,
        constraints: TextConstraints,
    ) -> (TextBlobId, TextMetrics) {
        let input =
            TextInput::attributed(rich.text.clone(), base_style.clone(), rich.spans.clone());
        self.prepare(&input, constraints)
    }

    fn measure(&mut self, input: &TextInput, constraints: TextConstraints) -> TextMetrics {
        let (blob, metrics) = self.prepare(input, constraints);
        self.release(blob);
        metrics
    }

    fn measure_str(
        &mut self,
        text: &str,
        style: &TextStyle,
        constraints: TextConstraints,
    ) -> TextMetrics {
        let input = TextInput::plain(Arc::<str>::from(text), style.clone());
        self.measure(&input, constraints)
    }

    fn measure_rich(
        &mut self,
        rich: &AttributedText,
        base_style: &TextStyle,
        constraints: TextConstraints,
    ) -> TextMetrics {
        let (blob, metrics) = self.prepare_rich(rich, base_style, constraints);
        self.release(blob);
        metrics
    }

    /// Returns the X offset (in logical px) of the caret at `index` within the prepared text blob.
    ///
    /// Coordinate space: relative to the text origin (x=0 at the beginning of the line).
    ///
    /// Notes:
    /// - `index` is a byte offset into the UTF-8 text, clamped to valid char boundaries (ADR 0044).
    /// - Implementations may clamp to the nearest representable caret position.
    fn caret_x(&mut self, _blob: TextBlobId, _index: usize) -> Px {
        Px(0.0)
    }

    /// Performs hit-testing for a single-line text blob and returns the nearest caret byte index.
    ///
    /// Coordinate space: `x` is relative to the text origin (x=0 at the beginning of the line).
    fn hit_test_x(&mut self, _blob: TextBlobId, _x: Px) -> usize {
        0
    }

    /// Computes selection rectangles for a single-line selection range.
    ///
    /// Coordinate space: rects are relative to the text origin (x=0, y=0 at top of text box).
    ///
    /// Geometry contract:
    /// - For a non-empty range (`start != end`), conforming implementations should emit rectangles
    ///   with positive height (and should avoid emitting zero-width rectangles).
    fn selection_rects(&mut self, _blob: TextBlobId, _range: (usize, usize), _out: &mut Vec<Rect>) {
    }

    /// Best-effort first-line font extents for a prepared text blob.
    ///
    /// This is primarily intended for mechanism-level vertical placement policies in fixed-height
    /// controls. Implementations should return `None` if the data is unavailable or expensive to
    /// compute.
    fn first_line_metrics(&mut self, _blob: TextBlobId) -> Option<TextLineMetrics> {
        None
    }

    /// Best-effort first-line ink extents (ascent/descent) for a prepared text blob.
    ///
    /// This differs from `first_line_metrics` when the line box is fixed (e.g.
    /// `TextLineHeightPolicy::FixedFromStyle`) but the shaped content includes taller fallback
    /// glyphs (emoji/CJK/etc). Callers may use this to detect potential clipping and apply
    /// padding or a different line-height preset.
    fn first_line_ink_metrics(&mut self, _blob: TextBlobId) -> Option<TextInkMetrics> {
        None
    }

    /// Best-effort last-line font extents for a prepared multi-line text blob.
    ///
    /// This is primarily intended for mechanism-level vertical placement and overflow handling
    /// policies. Implementations should return `None` if the data is unavailable or expensive to
    /// compute.
    fn last_line_metrics(&mut self, _blob: TextBlobId) -> Option<TextLineMetrics> {
        None
    }

    /// Best-effort last-line ink extents (ascent/descent) for a prepared multi-line text blob.
    ///
    /// This is intended for avoiding bottom-edge clipping in fixed line-box layouts when the last
    /// line contains tall fallback glyphs (emoji/CJK/etc).
    fn last_line_ink_metrics(&mut self, _blob: TextBlobId) -> Option<TextInkMetrics> {
        None
    }

    /// Computes selection rectangles and clips them to `clip` in the same coordinate space.
    ///
    /// This is intended for large multi-line selections where generating rectangles for off-screen
    /// lines is wasteful. Implementations may override this to cull work earlier.
    ///
    /// Coordinate space: rects and `clip` are relative to the text origin (x=0, y=0 at top of text box).
    fn selection_rects_clipped(
        &mut self,
        blob: TextBlobId,
        range: (usize, usize),
        clip: Rect,
        out: &mut Vec<Rect>,
    ) {
        self.selection_rects(blob, range, out);
        clip_rects_in_place(clip, out);
    }

    /// Extracts the precomputed caret stop table (byte index -> x offset) for a single-line blob.
    ///
    /// This is primarily intended for UI hit-testing in event handlers, which do not have access
    /// to the text service.
    fn caret_stops(&mut self, _blob: TextBlobId, _out: &mut Vec<(usize, Px)>) {}

    /// Returns the caret rectangle (in logical px) for the given `index`.
    ///
    /// Coordinate space: rect is relative to the text origin (x=0, y=0 at the top of the text box).
    ///
    /// Notes:
    /// - Single-line implementations may ignore affinity.
    /// - Multi-line implementations should use affinity to disambiguate positions at line breaks.
    /// - Conforming implementations should return a rectangle with positive height.
    fn caret_rect(&mut self, _blob: TextBlobId, _index: usize, _affinity: CaretAffinity) -> Rect {
        Rect::default()
    }

    /// Hit-test a point in the text's local coordinate space and return a caret index and affinity.
    ///
    /// Coordinate space: `point` is relative to the text origin (x=0, y=0 at the top of the text box).
    fn hit_test_point(&mut self, _blob: TextBlobId, _point: Point) -> HitTestResult {
        HitTestResult {
            index: 0,
            affinity: CaretAffinity::Downstream,
        }
    }

    fn release(&mut self, blob: TextBlobId);
}

fn clip_rects_in_place(clip: Rect, out: &mut Vec<Rect>) {
    let clip_x0 = clip.origin.x.0;
    let clip_y0 = clip.origin.y.0;
    let clip_x1 = clip_x0 + clip.size.width.0;
    let clip_y1 = clip_y0 + clip.size.height.0;

    if clip_x1 <= clip_x0 || clip_y1 <= clip_y0 {
        out.clear();
        return;
    }

    out.retain_mut(|r| {
        let x0 = r.origin.x.0;
        let y0 = r.origin.y.0;
        let x1 = x0 + r.size.width.0;
        let y1 = y0 + r.size.height.0;

        let ix0 = x0.max(clip_x0);
        let iy0 = y0.max(clip_y0);
        let ix1 = x1.min(clip_x1);
        let iy1 = y1.min(clip_y1);

        if ix1 <= ix0 || iy1 <= iy0 {
            return false;
        }

        r.origin.x = Px(ix0);
        r.origin.y = Px(iy0);
        r.size.width = Px(ix1 - ix0);
        r.size.height = Px(iy1 - iy0);
        true
    });
}