sugarloaf 0.2.24

Sugarloaf is Rio rendering engine, designed to be multiplatform. It is based on WebGPU, Rust library for Desktops and WebAssembly for Web (JavaScript). This project is created and maintained for Rio terminal purposes but feel free to use it.
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
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
// Copyright (c) 2023-present, Raphael Amorim.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
//

#![allow(clippy::uninlined_format_args)]
// Positioning tests for cached vs non-cached text rendering

use crate::components::rich_text::text_run_manager::{CacheResult, TextRunManager};
use crate::font::text_run_cache::ShapedGlyph;
use crate::sugarloaf::primitives::{DrawableChar, SugarCursor};

/// Captured positioning data for comparison
#[derive(Debug, Clone, PartialEq)]
pub struct PositioningData {
    pub baseline: f32,
    pub topline: f32,
    pub py: f32,
    pub padding_y: f32,
    pub line_height: f32,
    pub glyph_positions: Vec<(f32, f32)>, // (x, y) for each glyph
    pub cursor: Option<SugarCursor>,
    pub drawable_char: Option<DrawableChar>,
    pub advance: f32,
}

/// Test helper to simulate text rendering and capture positioning data
pub struct PositioningTestHelper {
    text_run_manager: TextRunManager,
}

impl PositioningTestHelper {
    pub fn new() -> Self {
        Self {
            text_run_manager: TextRunManager::new(),
        }
    }

    /// Simulate the positioning calculations from the rich text renderer
    #[allow(clippy::too_many_arguments)]
    pub fn calculate_positioning(
        &mut self,
        text: &str,
        font_id: usize,
        font_size: f32,
        ascent: f32,
        descent: f32,
        line_height: f32,
        cursor: Option<SugarCursor>,
        drawable_char: Option<DrawableChar>,
        use_cache: bool,
    ) -> PositioningData {
        let char_width = 1.0f32;

        // Simulate the line positioning calculations from mod.rs
        let line_y = 0.0f32; // Starting position
        let padding_top = (line_height - ascent - descent) / 2.0;
        let baseline = line_y + padding_top + ascent;
        let py = line_y; // py is now just the line_y, not modified

        // Calculate padding (from line height modifier logic)
        let line_height_without_mod = ascent + descent;
        let line_height_mod = line_height / line_height_without_mod;
        let padding_y = if line_height_mod > 1.0 {
            (line_height - line_height_without_mod) / 2.0
        } else {
            0.0
        };

        let mut glyph_positions = Vec::new();
        let mut px = 0.0f32;
        let advance;

        if use_cache {
            // Try to get cached data
            let cached_result = self.text_run_manager.get_cached_data(
                text,
                font_id,
                font_size,
                Some([1.0, 1.0, 1.0, 1.0]), // white color
            );

            match cached_result {
                CacheResult::ShapingOnly {
                    glyphs: cached_glyphs,
                    ..
                }
                | CacheResult::GlyphsOnly {
                    glyphs: cached_glyphs,
                    ..
                } => {
                    // Use cached glyph data
                    for shaped_glyph in cached_glyphs.iter() {
                        let x = px;
                        let y = py + padding_y;
                        glyph_positions.push((x, y));
                        px += shaped_glyph.x_advance * char_width;
                    }
                    advance = cached_glyphs.iter().map(|g| g.x_advance).sum();
                }
                CacheResult::FullRender { .. } => {
                    // For full render, we'd use cached vertices, but for testing
                    // we'll simulate the same glyph positioning
                    advance = text.len() as f32 * 10.0; // Mock advance
                }
                CacheResult::Miss => {
                    // Cache miss - simulate fresh shaping
                    advance = self.simulate_fresh_shaping(
                        text,
                        &mut px,
                        py,
                        padding_y,
                        char_width,
                        &mut glyph_positions,
                    );
                }
            }
        } else {
            // Simulate non-cached path
            advance = self.simulate_fresh_shaping(
                text,
                &mut px,
                py,
                padding_y,
                char_width,
                &mut glyph_positions,
            );
        }

        PositioningData {
            baseline,    // Use the calculated baseline position
            topline: py, // Use py (line top) for cursor positioning
            py,
            padding_y,
            line_height,
            glyph_positions,
            cursor,
            drawable_char,
            advance,
        }
    }

    fn simulate_fresh_shaping(
        &mut self,
        text: &str,
        px: &mut f32,
        py: f32,
        padding_y: f32,
        char_width: f32,
        glyph_positions: &mut Vec<(f32, f32)>,
    ) -> f32 {
        let mut shaped_glyphs = Vec::new();
        let run_start_x = *px;

        // Simulate shaping each character
        for (i, _ch) in text.chars().enumerate() {
            let x = *px;
            let y = py + padding_y;
            let advance = 10.0f32; // Mock advance per character

            glyph_positions.push((x, y));
            *px += advance * char_width;

            // Create shaped glyph for caching
            shaped_glyphs.push(ShapedGlyph {
                glyph_id: (65 + i) as u32, // Mock glyph IDs (A, B, C, ...)
                x_advance: advance,
                y_advance: 0.0,
                x_offset: 0.0,
                y_offset: 0.0,
                cluster: i as u32,
                atlas_coords: None,
                atlas_layer: None,
            });
        }

        // Cache the shaped data for future use
        self.text_run_manager.cache_shaping_data(
            text,
            0,    // font_id
            12.0, // font_size
            shaped_glyphs,
            false, // has_emoji
            None,  // shaping_features
        );

        *px - run_start_x
    }

    /// Clear the cache to test non-cached behavior
    pub fn clear_cache(&mut self) {
        self.text_run_manager.clear_all();
    }
}

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

    #[test]
    fn test_positioning_consistency_without_cursor() {
        let mut helper = PositioningTestHelper::new();

        // Test basic text positioning
        let text = "Hello";
        let font_id = 0;
        let font_size = 12.0;
        let ascent = 10.0;
        let descent = 3.0;
        let line_height = 15.0;

        // First run - no cache (fresh shaping)
        let non_cached = helper.calculate_positioning(
            text,
            font_id,
            font_size,
            ascent,
            descent,
            line_height,
            None,
            None,
            false,
        );

        // Second run - should use cache
        let cached = helper.calculate_positioning(
            text,
            font_id,
            font_size,
            ascent,
            descent,
            line_height,
            None,
            None,
            true,
        );

        // Compare positioning data
        assert_eq!(
            non_cached.baseline, cached.baseline,
            "Baseline should be identical"
        );
        assert_eq!(
            non_cached.topline, cached.topline,
            "Topline should be identical"
        );
        assert_eq!(non_cached.py, cached.py, "py should be identical");
        assert_eq!(
            non_cached.padding_y, cached.padding_y,
            "padding_y should be identical"
        );
        assert_eq!(
            non_cached.glyph_positions.len(),
            cached.glyph_positions.len(),
            "Should have same number of glyphs"
        );

        // Check each glyph position
        for (i, (non_cached_pos, cached_pos)) in non_cached
            .glyph_positions
            .iter()
            .zip(cached.glyph_positions.iter())
            .enumerate()
        {
            assert_eq!(
                non_cached_pos.0, cached_pos.0,
                "Glyph {} x position should match",
                i
            );
            assert_eq!(
                non_cached_pos.1, cached_pos.1,
                "Glyph {} y position should match",
                i
            );
        }

        // println!("Non-cached positioning: {:?}", non_cached);
        // println!("Cached positioning: {:?}", cached);
    }

    #[test]
    fn test_cursor_positioning_consistency() {
        let mut helper = PositioningTestHelper::new();

        let text = "Test";
        let font_id = 0;
        let font_size = 12.0;
        let ascent = 10.0;
        let descent = 3.0;
        let line_height = 15.0;
        let _cursor = Some(SugarCursor::Block([1.0, 0.0, 0.0, 1.0]));

        // Test with different cursor types
        let cursor_types = vec![
            SugarCursor::Block([1.0, 0.0, 0.0, 1.0]),
            SugarCursor::Underline([0.0, 1.0, 0.0, 1.0]),
            SugarCursor::Caret([0.0, 0.0, 1.0, 1.0]),
        ];

        for cursor_type in cursor_types {
            helper.clear_cache();

            // Non-cached run
            let non_cached = helper.calculate_positioning(
                text,
                font_id,
                font_size,
                ascent,
                descent,
                line_height,
                Some(cursor_type),
                None,
                false,
            );

            // Cached run
            let cached = helper.calculate_positioning(
                text,
                font_id,
                font_size,
                ascent,
                descent,
                line_height,
                Some(cursor_type),
                None,
                true,
            );

            // Cursor positioning should be identical
            assert_eq!(
                non_cached.baseline, cached.baseline,
                "Cursor baseline should match for {:?}",
                cursor_type
            );
            assert_eq!(
                non_cached.topline, cached.topline,
                "Cursor topline should match for {:?}",
                cursor_type
            );

            // println!(
            //     "Cursor {:?} - Non-cached: baseline={}, topline={}",
            //     cursor_type, non_cached.baseline, non_cached.topline
            // );
            // println!(
            //     "Cursor {:?} - Cached: baseline={}, topline={}",
            //     cursor_type, cached.baseline, cached.topline
            // );
        }
    }

    #[test]
    fn test_drawable_character_cached_vs_non_cached() {
        let mut helper = PositioningTestHelper::new();

        let text = "X";
        let font_id = 0;
        let font_size = 12.0;
        let ascent = 10.0;
        let descent = 3.0;
        let line_height = 15.0;
        let drawable_char = Some(DrawableChar::Cross);

        helper.clear_cache();

        // Non-cached run
        let non_cached = helper.calculate_positioning(
            text,
            font_id,
            font_size,
            ascent,
            descent,
            line_height,
            None,
            drawable_char,
            false,
        );

        // Cached run
        let cached = helper.calculate_positioning(
            text,
            font_id,
            font_size,
            ascent,
            descent,
            line_height,
            None,
            drawable_char,
            true,
        );

        // Drawable character positioning should be identical
        assert_eq!(
            non_cached.baseline, cached.baseline,
            "Drawable char baseline should match"
        );
        assert_eq!(
            non_cached.topline, cached.topline,
            "Drawable char topline should match"
        );
        assert_eq!(non_cached.py, cached.py, "Drawable char py should match");
    }

    #[test]
    fn test_padding_y_effects() {
        let mut helper = PositioningTestHelper::new();

        let text = "Test";
        let font_id = 0;
        let font_size = 12.0;
        let ascent = 10.0;
        let descent = 3.0;

        // Test with different line heights to trigger different padding_y values
        let line_heights = vec![13.0, 15.0, 20.0]; // Normal, slightly increased, significantly increased

        for line_height in line_heights {
            helper.clear_cache();

            let non_cached = helper.calculate_positioning(
                text,
                font_id,
                font_size,
                ascent,
                descent,
                line_height,
                None,
                None,
                false,
            );

            let cached = helper.calculate_positioning(
                text,
                font_id,
                font_size,
                ascent,
                descent,
                line_height,
                None,
                None,
                true,
            );

            // println!(
            //     "Line height {}: padding_y={}, baseline={}, topline={}, py={}",
            //     line_height,
            //     non_cached.padding_y,
            //     non_cached.baseline,
            //     non_cached.topline,
            //     non_cached.py
            // );

            assert_eq!(
                non_cached.padding_y, cached.padding_y,
                "padding_y should match for line_height {}",
                line_height
            );
            assert_eq!(
                non_cached.baseline, cached.baseline,
                "baseline should match for line_height {}",
                line_height
            );
            assert_eq!(
                non_cached.topline, cached.topline,
                "topline should match for line_height {}",
                line_height
            );
        }
    }

    #[test]
    fn test_glyph_vs_cursor_positioning_relationship() {
        let mut helper = PositioningTestHelper::new();

        let text = "A";
        let font_id = 0;
        let font_size = 12.0;
        let ascent = 10.0;
        let descent = 3.0;
        let line_height = 15.0;

        helper.clear_cache();

        // Test text with cursor
        let with_cursor = helper.calculate_positioning(
            text,
            font_id,
            font_size,
            ascent,
            descent,
            line_height,
            Some(SugarCursor::Block([1.0, 0.0, 0.0, 1.0])),
            None,
            true,
        );

        // The relationship between glyph y position and cursor positioning elements:
        // - Glyph y = py + padding_y
        // - Cursor block uses topline = baseline - ascent
        // - Cursor underline uses baseline + 1.0

        if let Some((_glyph_x, glyph_y)) = with_cursor.glyph_positions.first() {
            // println!("Glyph position: ({}, {})", glyph_x, glyph_y);
            // println!(
            //     "Expected glyph y: py + padding_y = {} + {} = {}",
            //     with_cursor.py,
            //     with_cursor.padding_y,
            //     with_cursor.py + with_cursor.padding_y
            // );
            // println!("Cursor topline (block): {}", with_cursor.topline);
            // println!("Cursor baseline (underline): {}", with_cursor.baseline);

            // Verify the glyph y calculation
            assert_eq!(
                *glyph_y,
                with_cursor.py + with_cursor.padding_y,
                "Glyph y should equal py + padding_y"
            );

            // The cursor should be positioned relative to the same baseline as the text
            // Now that baseline = py - descent, the relationships are:
            // - glyph_y = py + padding_y (glyphs positioned relative to py)
            // - cursor baseline = py - descent (actual text baseline)
            let expected_glyph_baseline = glyph_y - with_cursor.padding_y; // This should be py
            let cursor_baseline_in_line_coords = with_cursor.baseline; // This should be py - descent

            // println!(
            //     "Expected glyph baseline (line coords): {}",
            //     expected_glyph_baseline
            // );
            // println!(
            //     "Cursor baseline (line coords): {}",
            //     cursor_baseline_in_line_coords
            // );

            // With the new coordinate system: cursor_baseline = glyph_baseline + padding_top + ascent
            let padding_top = (line_height - ascent - descent) / 2.0;
            assert!((cursor_baseline_in_line_coords - (expected_glyph_baseline + padding_top + ascent)).abs() < 0.1,
                   "Cursor baseline should equal glyph baseline + padding_top + ascent. Cursor: {}, Glyph: {}, Padding: {}, Ascent: {}", 
                   cursor_baseline_in_line_coords, expected_glyph_baseline, padding_top, ascent);
        }
    }

    #[test]
    fn test_drawable_character_positioning() {
        let mut helper = PositioningTestHelper::new();
        let font_id = 0;
        let font_size = 16.0;
        let ascent = 12.0;
        let descent = 3.0;
        let line_height = 20.0;
        let drawable_char = Some(crate::DrawableChar::Horizontal);

        let result = helper.calculate_positioning(
            "─",
            font_id,
            font_size,
            ascent,
            descent,
            line_height,
            None,
            drawable_char,
            false,
        );

        // Verify baseline relationships are correct with new coordinate system
        let padding_top = (line_height - ascent - descent) / 2.0;
        let expected_baseline = result.py + padding_top + ascent;
        assert_eq!(
            result.baseline, expected_baseline,
            "baseline should equal py + padding_top + ascent"
        );
        assert_eq!(
            result.topline, result.py,
            "topline should be py (line top) for cursor positioning"
        );

        // The drawable character should be positioned at topline
        // This means center_y = topline + (line_height / 2.0)
        let expected_center_y = result.topline + (line_height / 2.0);

        // For horizontal lines, center should be reasonably close to text baseline
        let text_baseline = result.baseline; // Use the actual baseline
        let diff = (expected_center_y - text_baseline).abs();

        // Should be within reasonable range (half the line height)
        assert!(diff < line_height / 2.0,
               "Drawable character center ({}) should be reasonably close to text baseline ({}). Diff: {}", 
               expected_center_y, text_baseline, diff);
    }

    #[test]
    fn test_cursor_positioning_relationships() {
        let mut helper = PositioningTestHelper::new();
        let font_id = 0;
        let font_size = 16.0;
        let ascent = 12.0;
        let descent = 3.0;
        let line_height = 20.0;

        for cursor_type in [
            Some(crate::SugarCursor::Block([1.0, 1.0, 1.0, 1.0])),
            Some(crate::SugarCursor::Caret([1.0, 1.0, 1.0, 1.0])),
            Some(crate::SugarCursor::Underline([1.0, 1.0, 1.0, 1.0])),
        ] {
            let result = helper.calculate_positioning(
                "A",
                font_id,
                font_size,
                ascent,
                descent,
                line_height,
                cursor_type,
                None,
                false,
            );

            // Core relationships that must always hold with new coordinate system
            let padding_top = (line_height - ascent - descent) / 2.0;
            assert_eq!(
                result.baseline,
                result.py + padding_top + ascent,
                "baseline should equal py + padding_top + ascent for cursor {:?}",
                cursor_type
            );
            assert_eq!(
                result.topline, result.py,
                "topline should be py (line top) for cursor {:?}",
                cursor_type
            );

            // Block and Caret cursors use topline
            // Underline cursor uses baseline + 1.0
            match cursor_type {
                Some(crate::SugarCursor::Block(_))
                | Some(crate::SugarCursor::Caret(_)) => {
                    // These should span from topline to topline + line_height
                    let cursor_top = result.topline;
                    let cursor_bottom = result.topline + line_height;

                    // Verify cursor encompasses the text area
                    let text_top = result.baseline - ascent;
                    let text_bottom = result.baseline + descent;
                    assert!(
                        cursor_top <= text_top,
                        "Block/Caret cursor top should be at or above text top"
                    );
                    assert!(
                        cursor_bottom >= text_bottom,
                        "Block/Caret cursor bottom should be at or below text bottom"
                    );
                }
                Some(crate::SugarCursor::Underline(_)) => {
                    // Underline should be positioned at baseline + 1.0
                    let underline_y = result.baseline + 1.0;

                    // Should be close to the text baseline
                    let text_baseline = result.baseline; // In new system, baseline is the actual text baseline
                    assert!(
                        (underline_y - text_baseline).abs() < descent + 2.0,
                        "Underline cursor should be close to text baseline"
                    );
                }
                _ => {}
            }
        }
    }

    #[test]
    fn test_glyph_and_cursor_baseline_consistency() {
        let mut helper = PositioningTestHelper::new();
        let font_id = 0;
        let font_size = 16.0;
        let ascent = 12.0;
        let descent = 3.0;
        let cursor = Some(crate::SugarCursor::Block([1.0, 1.0, 1.0, 1.0]));

        // Test with different line heights to ensure consistency
        for test_line_height in [16.0, 20.0, 24.0, 30.0] {
            let result = helper.calculate_positioning(
                "Ag",
                font_id,
                font_size,
                ascent,
                descent,
                test_line_height,
                cursor,
                None,
                false,
            );

            // Get glyph positioning
            let glyph_y = result.py + result.padding_y;
            let glyph_baseline_in_line_coords = glyph_y - result.padding_y; // Should be py

            // With the new coordinate system:
            // - glyph_baseline_in_line_coords is py (top of line)
            // - cursor baseline is py + padding_top + ascent
            // So the relationship is: cursor_baseline = glyph_baseline + padding_top + ascent
            let padding_top = (test_line_height - ascent - descent) / 2.0;
            assert_eq!(result.baseline, glyph_baseline_in_line_coords + padding_top + ascent,
                      "Cursor baseline ({}) should equal glyph baseline ({}) + padding_top ({}) + ascent ({}) for line_height {}",
                      result.baseline, glyph_baseline_in_line_coords, padding_top, ascent, test_line_height);

            // Verify padding_y calculation is correct
            // The actual calculation is: if line_height_mod > 1.0 then (line_height - line_height_without_mod) / 2.0 else 0.0
            // where line_height = line_height_without_mod * line_height_mod
            // and line_height_without_mod = ascent + descent + leading (leading is usually 0)
            let line_height_without_mod = ascent + descent; // assuming leading = 0
            let line_height_mod = test_line_height / line_height_without_mod;
            let expected_padding_y = if line_height_mod > 1.0 {
                (test_line_height - line_height_without_mod) / 2.0
            } else {
                0.0
            };
            assert!((result.padding_y - expected_padding_y).abs() < 0.1,
                   "padding_y should be calculated correctly for line_height {}. Expected: {}, Got: {}, line_height_mod: {}",
                   test_line_height, expected_padding_y, result.padding_y, line_height_mod);
        }
    }

    #[test]
    fn test_cached_vs_non_cached_positioning_consistency() {
        let mut helper = PositioningTestHelper::new();
        let font_id = 0;
        let font_size = 16.0;
        let ascent = 12.0;
        let descent = 3.0;
        let line_height = 20.0;

        let test_cases = [
            ("Hello", None, None),
            (
                "World",
                Some(crate::SugarCursor::Block([1.0, 1.0, 1.0, 1.0])),
                None,
            ),
            ("─", None, Some(crate::DrawableChar::Horizontal)),
            (
                "│",
                Some(crate::SugarCursor::Underline([1.0, 1.0, 1.0, 1.0])),
                Some(crate::DrawableChar::Vertical),
            ),
        ];

        for (text, cursor, drawable_char) in test_cases {
            let non_cached = helper.calculate_positioning(
                text,
                font_id,
                font_size,
                ascent,
                descent,
                line_height,
                cursor,
                drawable_char,
                false,
            );

            let cached = helper.calculate_positioning(
                text,
                font_id,
                font_size,
                ascent,
                descent,
                line_height,
                cursor,
                drawable_char,
                true,
            );

            // All positioning values must be identical between cached and non-cached
            assert_eq!(
                non_cached.baseline, cached.baseline,
                "Baseline mismatch for '{}': non-cached={}, cached={}",
                text, non_cached.baseline, cached.baseline
            );
            assert_eq!(
                non_cached.topline, cached.topline,
                "Topline mismatch for '{}': non-cached={}, cached={}",
                text, non_cached.topline, cached.topline
            );
            assert_eq!(
                non_cached.py, cached.py,
                "py mismatch for '{}': non-cached={}, cached={}",
                text, non_cached.py, cached.py
            );
            assert_eq!(
                non_cached.padding_y, cached.padding_y,
                "padding_y mismatch for '{}': non-cached={}, cached={}",
                text, non_cached.padding_y, cached.padding_y
            );
        }
    }

    #[test]
    fn test_positioning_invariants() {
        let mut helper = PositioningTestHelper::new();
        let font_id = 0;
        let font_size = 16.0;
        let ascent = 12.0;
        let descent = 3.0;

        // Test various line heights
        for line_height in [16.0, 18.0, 20.0, 24.0, 32.0] {
            let result = helper.calculate_positioning(
                "Test",
                font_id,
                font_size,
                ascent,
                descent,
                line_height,
                None,
                None,
                false,
            );

            // Core invariants that must always hold with new coordinate system
            let padding_top = (line_height - ascent - descent) / 2.0;
            assert_eq!(
                result.baseline,
                result.py + padding_top + ascent,
                "INVARIANT: baseline must equal py + padding_top + ascent (line_height={})",
                line_height
            );

            assert_eq!(
                result.topline, result.py,
                "INVARIANT: topline must equal py (line top) (line_height={})",
                line_height
            );

            // Padding calculation invariant
            let line_height_without_mod = ascent + descent; // assuming leading = 0
            let line_height_mod = line_height / line_height_without_mod;
            let expected_padding = if line_height_mod > 1.0 {
                (line_height - line_height_without_mod) / 2.0
            } else {
                0.0
            };
            assert!(
                (result.padding_y - expected_padding).abs() < 0.1,
                "INVARIANT: padding_y calculation (line_height={}, mod={})",
                line_height,
                line_height_mod
            );

            // Glyph positioning invariant
            let glyph_y = result.py + result.padding_y;
            assert!(
                glyph_y >= result.py,
                "INVARIANT: glyph_y must be >= py (line_height={})",
                line_height
            );

            // Text should fit within the line
            let text_top = result.py - ascent;
            let text_bottom = result.py + descent;
            let line_span = text_bottom - text_top;
            assert!(
                line_span <= line_height + 1.0, // +1 for rounding tolerance
                "INVARIANT: text should fit within line_height (line_height={})",
                line_height
            );
        }
    }

    #[test]
    fn test_strikethrough_positioning() {
        use crate::components::rich_text::compositor::Compositor;
        use crate::components::rich_text::text::TextRunStyle;
        use crate::components::rich_text::Rect;
        use crate::layout::FragmentStyleDecoration;

        let compositor = Compositor::new();
        let font_size = 16.0;
        let line_height = 20.0;
        let x_height = 8.0; // Typical x-height is about half the font size
        let strikeout_offset = 4.0; // Font-provided strikeout offset
        let ascent = 12.0;
        let descent = 4.0;

        // Test with font-provided strikeout offset
        let style_with_offset = TextRunStyle {
            font_coords: &[],
            font_size,
            color: [1.0, 1.0, 1.0, 1.0],
            background_color: None,
            baseline: 16.0,
            topline: 0.0,
            line_height,
            padding_y: 0.0,
            line_height_without_mod: line_height,
            advance: 100.0,
            decoration: Some(FragmentStyleDecoration::Strikethrough),
            decoration_color: None,
            cursor: None,
            drawable_char: None,
            underline_offset: 2.0,
            strikeout_offset,
            underline_thickness: 1.0,
            x_height,
            ascent,
            descent,
        };

        let rect = Rect::new(0.0, 0.0, 100.0, line_height);
        let underline =
            compositor.create_underline_from_decoration(&style_with_offset, &rect);

        if let Some(underline) = underline {
            // Should use font's strikeout offset (negated)
            assert_eq!(underline.offset, -strikeout_offset);
        } else {
            panic!("Expected strikethrough underline");
        }

        // Test with x-height fallback (no font strikeout offset)
        let style_with_x_height = TextRunStyle {
            strikeout_offset: 0.0, // No font-provided offset
            x_height,
            ..style_with_offset
        };

        let underline =
            compositor.create_underline_from_decoration(&style_with_x_height, &rect);

        if let Some(underline) = underline {
            // Should use half of x-height above baseline
            assert_eq!(underline.offset, -(x_height / 2.0));
        } else {
            panic!("Expected strikethrough underline");
        }

        // Test with final fallback (no font offset or x-height)
        let style_fallback = TextRunStyle {
            strikeout_offset: 0.0,
            x_height: 0.0,
            ..style_with_offset
        };

        let underline =
            compositor.create_underline_from_decoration(&style_fallback, &rect);

        if let Some(underline) = underline {
            // Should use approximate position
            assert_eq!(underline.offset, -(rect.height * 0.3));
        } else {
            panic!("Expected strikethrough underline");
        }
    }

    #[test]
    fn test_cursor_font_based_sizing() {
        // Test that cursor size is based on font metrics, not line height
        let _font_size = 16.0;
        let ascent = 12.0;
        let descent = 4.0;
        let font_height = ascent + descent; // 16.0

        // Test with different line heights to ensure cursor size is independent
        let line_heights = [16.0, 20.0, 24.0, 32.0];

        for line_height in line_heights {
            let baseline = 16.0;
            let cursor_top = baseline - ascent; // 16 - 12 = 4.0

            // Verify cursor dimensions are based on font metrics
            assert_eq!(
                font_height,
                ascent + descent,
                "Font height should equal ascent + descent"
            );
            assert_eq!(
                cursor_top,
                baseline - ascent,
                "Cursor top should be baseline - ascent"
            );

            // Cursor should be smaller than line height for increased line spacing
            if line_height > font_height {
                assert!(font_height < line_height, "Cursor should be smaller than line height when line spacing is increased");
            }
        }
    }

    #[test]
    fn test_cursor_positioning_with_different_font_metrics() {
        let _font_size = 16.0;
        let _line_height = 24.0; // Larger than font size
        let baseline = 20.0;

        // Test different font metric combinations
        let font_metrics = [
            ("Normal font", 12.0, 4.0),     // ascent=12, descent=4, total=16
            ("Tall font", 14.0, 6.0),       // ascent=14, descent=6, total=20
            ("Short font", 10.0, 2.0),      // ascent=10, descent=2, total=12
            ("Deep descenders", 11.0, 8.0), // ascent=11, descent=8, total=19
        ];

        for (font_name, ascent, descent) in font_metrics {
            let font_height = ascent + descent;
            let cursor_top = baseline - ascent;

            // Verify cursor positioning
            assert_eq!(
                font_height,
                ascent + descent,
                "{}: Font height should equal ascent + descent",
                font_name
            );
            assert_eq!(
                cursor_top,
                baseline - ascent,
                "{}: Cursor top should be baseline - ascent",
                font_name
            );

            // Cursor should start above baseline for fonts with ascent
            if ascent > 0.0 {
                assert!(
                    cursor_top < baseline,
                    "{}: Cursor should start above baseline",
                    font_name
                );
            }

            // Cursor should end below baseline for fonts with descent
            if descent > 0.0 {
                assert!(
                    cursor_top + font_height > baseline,
                    "{}: Cursor should extend below baseline",
                    font_name
                );
            }
        }
    }

    #[test]
    fn test_underline_cursor_positioning() {
        let _font_size = 16.0;
        let _line_height = 24.0;
        let baseline = 20.0;
        let _ascent = 12.0;
        let _descent = 4.0;

        // Underline cursor should be positioned at baseline + 1.0 with height 2.0
        let expected_underline_y = baseline + 1.0;
        let expected_underline_height = 2.0;

        // Underline cursor positioning should be independent of font metrics
        // It should always be just below the baseline
        assert_eq!(
            expected_underline_y,
            baseline + 1.0,
            "Underline cursor should be 1px below baseline"
        );
        assert_eq!(
            expected_underline_height, 2.0,
            "Underline cursor should be 2px tall"
        );
    }
}