protextinator 0.5.2

Text management, made simple
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
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
//! Text state management and editing functionality.
//!
//! This module provides the core `TextState` type and related functionality for managing
//! text content, cursor position, selection, scrolling, and text editing operations.

use crate::action::{Action, ActionResult};
use crate::buffer_utils::{
    adjust_vertical_scroll_to_make_caret_visible, char_under_position,
    cursor_position_with_trailing_space_fallback, update_buffer, vertical_offset,
};
use crate::byte_cursor::ByteCursor;
use crate::math::Size;
use crate::style::{FontFamily, TextStyle, VerticalTextAlignment};
use crate::text_manager::TextContext;
use crate::text_params::TextParams;
use crate::utils::{linear_to_srgb_u8, srgb_to_linear_u8};
use crate::{Point, Rect};
#[cfg(test)]
use cosmic_text::LayoutGlyph;
use cosmic_text::{Buffer, Cursor, Edit, Editor, FontSystem, Motion};
use smol_str::SmolStr;
use std::time::{Duration, Instant};

/// Size comparison epsilon for floating-point calculations.
pub const SIZE_EPSILON: f32 = 0.0001;

/// CPU-side RGBA8 texture holding the rasterized contents of a text buffer.
#[derive(Debug, Clone)]
pub struct RasterizedTexture {
    pub pixels: Vec<u8>,
    pub width: u32,
    pub height: u32,
}

/// Represents a single line of text selection with visual boundaries.
///
/// Selection lines define the visual appearance of selected text, with start and end
/// coordinates for rendering selection highlights.
#[derive(Clone, Default, Debug, Copy)]
pub struct SelectionLine {
    /// X coordinate where the selection starts on this line.
    pub start_x_pt: Option<f32>,
    /// Y coordinate where the selection starts on this line.
    pub start_y_pt: Option<f32>,
    /// X coordinate where the selection ends on this line.
    pub end_x_pt: Option<f32>,
    /// Y coordinate where the selection ends on this line.
    pub end_y_pt: Option<f32>,
}

/// Represents the current text selection state.
///
/// A selection is defined by an origin point (where selection started) and an end point
/// (where selection currently ends). The selection can span multiple lines, with each
/// line's visual boundaries stored in the `lines` vector.
#[derive(Clone, Default, Debug)]
pub struct Selection {
    origin_character_byte_cursor: Option<ByteCursor>,
    ends_before_character_byte_cursor: Option<ByteCursor>,
    lines: Vec<SelectionLine>,
}

impl Selection {
    /// Returns `true` if there is no active selection.
    ///
    /// A selection is considered empty if either the origin or end cursor is not set.
    ///
    /// # Examples
    /// ```
    /// use protextinator::Selection;
    ///
    /// let selection = Selection::default();
    /// assert!(selection.is_empty());
    /// ```
    #[inline(always)]
    pub const fn is_empty(&self) -> bool {
        self.origin_character_byte_cursor.is_none()
            || self.ends_before_character_byte_cursor.is_none()
    }

    /// Returns the visual selection lines for rendering.
    ///
    /// Each line represents a portion of the selection with its visual boundaries.
    ///
    /// # Returns
    /// A slice of `SelectionLine` objects representing the visual selection
    #[inline(always)]
    pub fn lines(&self) -> &[SelectionLine] {
        &self.lines
    }
}

/// The main text state container that manages text content, cursor, selection, and styling.
///
/// `TextState` is the core type for text editing functionality. It maintains the text buffer,
/// cursor position, selection state, scroll position, and handles text editing operations.
///
/// # Type Parameters
/// * `T` - Custom metadata type that can be attached to the text state
///
/// # Features
/// - Text editing (insert, delete, copy, paste, cut)
/// - Cursor movement and positioning
/// - Text selection with visual feedback
/// - Automatic scrolling to keep cursor visible
/// - Rich text styling
/// - Configurable editing behavior
#[derive(Debug)]
pub struct TextState<T> {
    params: TextParams,
    cursor: ByteCursor,
    // Caret position relative to the buffer viewport with scroll applied
    relative_caret_position: Option<Point>,
    caret_width: f32,
    selection: Selection,
    resolved_font_family: FontFamily,

    last_scroll_timestamp: Instant,

    inner_dimensions: Size,
    buffer: Buffer,

    // CPU-side cached rasterized texture of the current buffer (RGBA8, device pixels)
    rasterized_texture: RasterizedTexture,
    // Whether raster content needs to be regenerated
    raster_dirty: bool,

    // Settings
    /// Can text be selected?
    pub is_selectable: bool,
    /// Can text be edited?
    pub is_editable: bool,
    /// Various actions, such as copy, paste, cut, etc., are going to be performed
    pub is_editing: bool,
    /// Are actions enabled? If false, no actions will be performed.
    pub are_actions_enabled: bool,
    /// Interval between scroll updates when dragging the selection
    pub scroll_interval: Duration,

    /// Doesn't affect anything - just some metadata that you can later use during rendering
    pub metadata: T,
}

impl<T> TextState<T> {
    /// Creates a new text state with the specified text content and metadata.
    ///
    /// The text state is created with default settings:
    /// - Editing and selection disabled
    /// - Actions disabled
    /// - Default caret width of 3.0 pixels
    /// - 50ms scroll interval
    ///
    /// # Arguments
    /// * `text` - The initial text content
    /// * `font_system` - Mutable reference to the font system for text layout
    /// * `metadata` - Custom metadata to associate with this text state
    ///
    /// # Returns
    /// A new `TextState` instance
    ///
    /// # Examples
    /// ```
    /// use protextinator::{TextState, TextContext};
    /// use cosmic_text::FontSystem;
    ///
    /// let mut font_system = FontSystem::new();
    /// let state = TextState::new_with_text("Hello, world!", &mut font_system, ());
    /// ```
    pub fn new_with_text(
        text: impl Into<String>,
        font_system: &mut FontSystem,
        metadata: T,
    ) -> Self {
        let text = text.into();
        let params = TextParams::new(Size::ZERO, TextStyle::default(), text, 0);
        let metrics = params.metrics();

        Self {
            params,

            is_editing: false,
            are_actions_enabled: false,

            cursor: ByteCursor::default(),
            relative_caret_position: None,

            resolved_font_family: FontFamily::SansSerif,

            selection: Selection::default(),
            last_scroll_timestamp: Instant::now(),
            scroll_interval: Duration::from_millis(50),
            caret_width: 3.0,
            is_selectable: false,
            is_editable: false,

            inner_dimensions: Size::ZERO,
            buffer: Buffer::new(font_system, metrics),

            rasterized_texture: RasterizedTexture {
                pixels: Vec::new(),
                width: 0,
                height: 0,
            },
            raster_dirty: true,

            metadata,
        }
    }

    /// Sets the caret width, which is the width of the cursor when editing text.
    ///
    /// # Arguments
    /// * `width` - The caret width in pixels
    ///
    /// # Examples
    /// ```
    /// # use protextinator::TextState;
    /// # use cosmic_text::FontSystem;
    /// # let mut font_system = FontSystem::new();
    /// # let mut state = TextState::new_with_text("", &mut font_system, ());
    /// state.set_caret_width(2.0);
    /// assert_eq!(state.caret_width(), 2.0);
    /// ```
    pub fn set_caret_width(&mut self, width: f32) {
        self.caret_width = width;
    }

    /// Returns the caret width, which is the width of the cursor when editing text.
    ///
    /// # Returns
    /// The caret width in pixels
    ///
    /// # Examples
    /// ```
    /// # use protextinator::TextState;
    /// # use cosmic_text::FontSystem;
    /// # let mut font_system = FontSystem::new();
    /// # let state = TextState::new_with_text("", &mut font_system, ());
    /// let width = state.caret_width();
    /// ```
    pub const fn caret_width(&self) -> f32 {
        self.caret_width
    }

    /// Caret position relative to the buffer viewport with scroll applied. Returns `None` if
    /// the caret is not visible or the buffer is not shaped yet.
    ///
    /// # Returns
    /// The caret position relative to the viewport, or `None` if not visible
    ///
    /// # Examples
    /// ```
    /// # use protextinator::TextState;
    /// # use cosmic_text::FontSystem;
    /// # let mut font_system = FontSystem::new();
    /// # let state = TextState::new_with_text("Hello", &mut font_system, ());
    /// if let Some(position) = state.caret_position_relative() {
    ///     println!("Caret at: ({}, {})", position.x, position.y);
    /// }
    /// ```
    pub fn caret_position_relative(&self) -> Option<Point> {
        self.relative_caret_position
    }

    /// Returns the position of the selection lines in the buffer viewport.
    ///
    /// # Returns
    /// A reference to the current selection state
    ///
    /// # Examples
    /// ```
    /// # use protextinator::TextState;
    /// # use cosmic_text::FontSystem;
    /// # let mut font_system = FontSystem::new();
    /// # let state = TextState::new_with_text("Hello", &mut font_system, ());
    /// let selection = state.selection();
    /// if !selection.is_empty() {
    ///     println!("Text is selected");
    /// }
    /// ```
    pub fn selection(&self) -> &Selection {
        &self.selection
    }

    /// Sets the text in the buffer and updates the cursor position if necessary.
    ///
    /// This method only updates the text content without reshaping. You'll need to call
    /// `recalculate` or `reshape_if_params_changed` separately to update the layout.
    ///
    /// # Arguments
    /// * `text` - The new text content
    ///
    /// # Examples
    /// ```
    /// # use protextinator::TextState;
    /// # use cosmic_text::FontSystem;
    /// # let mut font_system = FontSystem::new();
    /// # let mut state = TextState::new_with_text("", &mut font_system, ());
    /// state.set_text("Updated text");
    /// assert_eq!(state.text(), "Updated text");
    /// ```
    pub fn set_text(&mut self, text: &str) {
        self.params.set_text(text);

        // TODO: should we just reset cursor on whole text update?
        if self.cursor.byte_character_start > self.params.text_for_internal_use().len() {
            if text.is_empty() {
                self.cursor = ByteCursor::default()
            } else {
                self.update_cursor_before_glyph_with_bytes_offset(
                    self.params.text_for_internal_use().len(),
                );
            }
        }
    }

    /// Returns the text in the buffer
    ///
    /// # Returns
    /// The current text content as a string slice
    ///
    /// # Examples
    /// ```
    /// # use protextinator::TextState;
    /// # use cosmic_text::FontSystem;
    /// # let mut font_system = FontSystem::new();
    /// # let state = TextState::new_with_text("Hello, world!", &mut font_system, ());
    /// assert_eq!(state.text(), "Hello, world!");
    /// ```
    pub fn text(&self) -> &str {
        self.params.original_text()
    }

    /// Sets the text style
    ///
    /// # Arguments
    /// * `style` - The new text style to apply
    ///
    /// # Examples
    /// ```
    /// # use protextinator::{TextState, style::TextStyle};
    /// # use cosmic_text::{FontSystem, Color};
    /// # let mut font_system = FontSystem::new();
    /// # let mut state = TextState::new_with_text("", &mut font_system, ());
    /// let style = TextStyle::new(16.0, Color::rgb(255, 0, 0));
    /// state.set_style(&style);
    /// ```
    pub fn set_style(&mut self, style: &TextStyle) {
        self.params.set_style(style);
    }

    /// Returns the text style
    ///
    /// # Returns
    /// A reference to the current text style
    ///
    /// # Examples
    /// ```
    /// # use protextinator::TextState;
    /// # use cosmic_text::FontSystem;
    /// # let mut font_system = FontSystem::new();
    /// # let state = TextState::new_with_text("", &mut font_system, ());
    /// let style = state.style();
    /// println!("Font size: {}", style.font_size.value());
    /// ```
    pub fn style(&self) -> &TextStyle {
        self.params.style()
    }

    /// Returns the resolved font family after font matching has been performed.
    ///
    /// This may differ from the font family in the style if font substitution occurred.
    ///
    /// # Returns
    /// A reference to the resolved font family
    ///
    /// # Examples
    /// ```
    /// # use protextinator::TextState;
    /// # use cosmic_text::FontSystem;
    /// # let mut font_system = FontSystem::new();
    /// # let state = TextState::new_with_text("", &mut font_system, ());
    /// let resolved = state.resolved_font_family();
    /// ```
    pub fn resolved_font_family(&self) -> &FontFamily {
        &self.resolved_font_family
    }

    /// Sets the visible area of the text buffer. This is going to be used to determine the buffer's
    /// viewport size and how much text is visible.
    ///
    /// # Arguments
    /// * `size` - The new visible area size
    ///
    /// # Examples
    /// ```
    /// # use protextinator::{TextState, math::Size};
    /// # use cosmic_text::FontSystem;
    /// # let mut font_system = FontSystem::new();
    /// # let mut state = TextState::new_with_text("", &mut font_system, ());
    /// state.set_outer_size(&Size::new(400.0, 200.0));
    /// ```
    pub fn set_outer_size(&mut self, size: &Size) {
        self.params.set_size(size)
    }

    /// Metadata set to a cosmic_text's buffer
    ///
    /// # Returns
    /// The current buffer metadata value
    ///
    /// # Examples
    /// ```
    /// # use protextinator::TextState;
    /// # use cosmic_text::FontSystem;
    /// # let mut font_system = FontSystem::new();
    /// # let state = TextState::new_with_text("", &mut font_system, ());
    /// let metadata = state.buffer_metadata();
    /// ```
    pub fn buffer_metadata(&self) -> usize {
        self.params.metadata()
    }

    /// Sets the metadata for the text cosmic_text's buffer. Note that this is different from
    /// the `metadata` field in `TextState`, which is a custom type.
    ///
    /// # Arguments
    /// * `metadata` - The metadata value to set
    ///
    /// # Examples
    /// ```
    /// # use protextinator::TextState;
    /// # use cosmic_text::FontSystem;
    /// # let mut font_system = FontSystem::new();
    /// # let mut state = TextState::new_with_text("", &mut font_system, ());
    /// state.set_buffer_metadata(42);
    /// assert_eq!(state.buffer_metadata(), 42);
    /// ```
    #[inline(always)]
    pub fn set_buffer_metadata(&mut self, metadata: usize) {
        self.params.set_metadata(metadata)
    }

    /// Returns the visible area size of the text buffer. Note that this is set directly by the
    /// `set_outer_size` method, and it does not represent the actual text dimensions. To get the
    /// inner dimensions of the text buffer, use `inner_size`.
    ///
    /// # Returns
    /// The outer size (visible area) of the text buffer
    ///
    /// # Examples
    /// ```
    /// # use protextinator::{TextState, math::Size};
    /// # use cosmic_text::FontSystem;
    /// # let mut font_system = FontSystem::new();
    /// # let mut state = TextState::new_with_text("", &mut font_system, ());
    /// state.set_outer_size(&Size::new(400.0, 200.0));
    /// assert_eq!(state.outer_size(), Size::new(400.0, 200.0));
    /// ```
    pub fn outer_size(&self) -> Size {
        self.params.size()
    }

    /// Returns the inner dimensions of the text buffer. This represents the actual size of the text
    /// content, which may differ from the outer size if the text is larger than the visible area.
    ///
    /// # Returns
    /// The inner dimensions representing the actual text content size
    ///
    /// # Examples
    /// ```
    /// # use protextinator::TextState;
    /// # use cosmic_text::FontSystem;
    /// # let mut font_system = FontSystem::new();
    /// # let state = TextState::new_with_text("Some text", &mut font_system, ());
    /// let inner_size = state.inner_size();
    /// println!("Text content size: {}x{}", inner_size.x, inner_size.y);
    /// ```
    pub const fn inner_size(&self) -> Size {
        self.inner_dimensions
    }

    /// Returns the text buffer that can be used for rendering
    ///
    /// # Returns
    /// A reference to the underlying cosmic-text Buffer
    ///
    /// # Examples
    /// ```
    /// # use protextinator::TextState;
    /// # use cosmic_text::FontSystem;
    /// # let mut font_system = FontSystem::new();
    /// # let state = TextState::new_with_text("Hello", &mut font_system, ());
    /// let buffer = state.buffer();
    /// // Use buffer for rendering operations
    /// ```
    pub fn buffer(&self) -> &Buffer {
        &self.buffer
    }

    /// Returns the last rasterized CPU texture.
    pub fn rasterized_texture(&self) -> &RasterizedTexture {
        &self.rasterized_texture
    }

    /// Returns the length of the text in characters. Note that this is different from the
    /// string .len(), which returns the length in bytes.
    ///
    /// # Returns
    /// The number of Unicode characters in the text
    ///
    /// # Examples
    /// ```
    /// # use protextinator::TextState;
    /// # use cosmic_text::FontSystem;
    /// # let mut font_system = FontSystem::new();
    /// # let state = TextState::new_with_text("Hello 🦀", &mut font_system, ());
    /// assert_eq!(state.text_char_len(), 7); // 5 ASCII chars + 1 space + 1 emoji
    /// ```
    pub fn text_char_len(&self) -> usize {
        self.params.original_text().chars().count()
    }

    /// Returns the char index of the cursor in the text buffer. Note that this returns the
    /// char index, not the char byte index.
    ///
    /// # Returns
    /// The character index of the cursor, or `None` if the cursor position is invalid
    ///
    /// # Examples
    /// ```
    /// # use protextinator::TextState;
    /// # use cosmic_text::FontSystem;
    /// # let mut font_system = FontSystem::new();
    /// # let state = TextState::new_with_text("Hello", &mut font_system, ());
    /// if let Some(index) = state.cursor_char_index() {
    ///     println!("Cursor is at character index: {}", index);
    /// }
    /// ```
    pub fn cursor_char_index(&self) -> Option<usize> {
        self.cursor.char_index(self.params.text_for_internal_use())
    }

    fn insert_char_at_cursor(&mut self, character: char, ctx: &mut TextContext) -> ActionResult {
        let text = self.params.text_for_internal_use();
        let at_end = self.cursor.byte_character_start >= text.len();
        let ends_with_newline = text.ends_with('\n');

        // cosmic_text quirk: when inserting a newline at the end of text that doesn't
        // already end with a newline, we need to insert two newlines so the caret can
        // be placed on the new line
        if character == '\n' && at_end && !ends_with_newline {
            self.params
                .insert_char(self.cursor.byte_character_start, '\n');
            self.params
                .insert_char(self.cursor.byte_character_start + 1, '\n');
        } else {
            self.params
                .insert_char(self.cursor.byte_character_start, character);
        }

        self.reshape_if_params_changed(ctx);
        self.move_cursor(ctx, Motion::Next);

        ActionResult::TextChanged
    }

    // fn insert_text_at_cursor(&mut self, text: &str) {
    //     self.params
    //         .insert_str(self.cursor.byte_character_start, text);
    //     self.update_cursor_before_glyph_with_bytes_offset(
    //         self.cursor.byte_character_start + text.len(),
    //     );
    // }

    fn remove_char_at_cursor(&mut self) {
        if !self.params.text_for_internal_use().is_empty() {
            if let Some(prev_char) = self
                .cursor
                .prev_char_byte_offset(self.params.text_for_internal_use())
            {
                self.remove_character(prev_char);
                if !self
                    .cursor
                    .update_byte_offset(prev_char, self.params.text_for_internal_use())
                {
                    // TODO: print a warning
                }
            }
        }
    }

    fn remove_characters(&mut self, byte_offset_start: usize, byte_offset_end: usize) {
        self.params.remove_range(byte_offset_start, byte_offset_end);
    }

    fn set_cursor_before_glyph(&mut self, cursor: ByteCursor) {
        self.cursor = cursor;
    }

    fn update_cursor_before_glyph_with_cursor(&mut self, cursor: Cursor) {
        self.cursor
            .update_cursor(cursor, self.params.text_for_internal_use());
    }

    fn update_cursor_before_glyph_with_bytes_offset(&mut self, byte_offset: usize) {
        self.cursor
            .update_byte_offset(byte_offset, self.params.text_for_internal_use());
    }

    fn remove_character(&mut self, byte_offset: usize) -> Option<char> {
        self.params.remove_char(byte_offset)
    }

    fn remove_selected_text(&mut self) -> Option<()> {
        if let (Some(origin), Some(end)) = (
            self.selection.origin_character_byte_cursor,
            self.selection.ends_before_character_byte_cursor,
        ) {
            let origin_offset = origin.byte_character_start;
            let end_offset = end.byte_character_start;

            if origin > end {
                self.remove_characters(end_offset, origin_offset);
                self.cursor = end;
            } else {
                self.remove_characters(origin_offset, end_offset);
                self.cursor = origin;
            }
            self.reset_selection();
            Some(())
        } else {
            None
        }
    }

    fn move_cursor_to_selection_left(&mut self) {
        if let (Some(origin), Some(end)) = (
            self.selection.origin_character_byte_cursor,
            self.selection.ends_before_character_byte_cursor,
        ) {
            if origin > end {
                self.set_cursor_before_glyph(end);
            } else {
                self.set_cursor_before_glyph(origin);
            }
        }
    }

    fn move_cursor_to_selection_right(&mut self) {
        if let (Some(origin), Some(end)) = (
            self.selection.origin_character_byte_cursor,
            self.selection.ends_before_character_byte_cursor,
        ) {
            if origin < end {
                self.set_cursor_before_glyph(end);
            } else {
                self.set_cursor_before_glyph(origin);
            }
        }
    }

    /// Checks if there is a text selection that is not empty.
    ///
    /// # Returns
    /// `true` if text is currently selected, `false` otherwise
    ///
    /// # Examples
    /// ```
    /// # use protextinator::TextState;
    /// # use cosmic_text::FontSystem;
    /// # let mut font_system = FontSystem::new();
    /// # let state = TextState::new_with_text("Hello", &mut font_system, ());
    /// if state.is_text_selected() {
    ///     println!("Some text is selected");
    /// }
    /// ```
    pub fn is_text_selected(&self) -> bool {
        if let Some(origin) = self.selection.origin_character_byte_cursor {
            if let Some(end) = self.selection.ends_before_character_byte_cursor {
                origin != end
            } else {
                false
            }
        } else {
            false
        }
    }

    fn reset_selection_end(&mut self) {
        self.selection.ends_before_character_byte_cursor = None;
        self.selection.lines.clear();
    }

    /// Clears the current text selection.
    ///
    /// This removes any active text selection, returning the text state to having
    /// only a cursor position without any selected text.
    ///
    /// # Examples
    /// ```
    /// # use protextinator::TextState;
    /// # use cosmic_text::FontSystem;
    /// # let mut font_system = FontSystem::new();
    /// # let mut state = TextState::new_with_text("Hello", &mut font_system, ());
    /// state.reset_selection();
    /// assert!(!state.is_text_selected());
    /// ```
    pub fn reset_selection(&mut self) {
        self.selection.origin_character_byte_cursor = None;
        self.selection.ends_before_character_byte_cursor = None;
        self.selection.lines.clear();
    }

    fn select_all(&mut self) {
        self.selection.origin_character_byte_cursor = Some(ByteCursor::string_start());
        if !self.params.original_text().is_empty() {
            self.selection.ends_before_character_byte_cursor = Some(
                ByteCursor::after_last_character(self.params.original_text()),
            )
        } else {
            self.selection.ends_before_character_byte_cursor = None;
        }
    }

    fn substring_byte_offset(&self, start: usize, end: usize) -> &str {
        // TODO: add bounds checking
        &self.params.original_text()[start..end]
    }

    /// Returns the selected text as a substring based on the selection start and end byte offsets.
    /// You also can get the selected text by using [`TextState::apply_action`] with
    /// [`Action::CopySelectedText`].
    ///
    /// # Returns
    /// The currently selected text, or `None` if no text is selected
    ///
    /// # Examples
    /// ```
    /// # use protextinator::TextState;
    /// # use cosmic_text::FontSystem;
    /// # let mut font_system = FontSystem::new();
    /// # let state = TextState::new_with_text("Hello, world!", &mut font_system, ());
    /// if let Some(selected) = state.selected_text() {
    ///     println!("Selected text: {}", selected);
    /// }
    /// ```
    pub fn selected_text(&self) -> Option<&str> {
        if let (Some(mut origin), Some(mut end)) = (
            self.selection.origin_character_byte_cursor,
            self.selection.ends_before_character_byte_cursor,
        ) {
            if origin > end {
                std::mem::swap(&mut origin, &mut end);
            }
            Some(self.substring_byte_offset(origin.byte_character_start, end.byte_character_start))
        } else {
            None
        }
    }

    //
    /// Gets the current absolute scroll position of the text buffer. Note that
    /// the buffer must be shaped and updated before calling this function, i.e. if anything
    /// changed in the text, you should call [`TextState::recalculate`].
    ///
    /// The scroll position represents how much the text content has been scrolled
    /// from its original position. This accounts for both horizontal and vertical scrolling.
    ///
    /// # Returns
    /// A `Point` representing the absolute scroll offset
    ///
    /// # Note
    /// The buffer must be shaped and updated before calling this function for accurate results.
    ///
    /// # Examples
    /// ```
    /// # use protextinator::TextState;
    /// # use cosmic_text::FontSystem;
    /// # let mut font_system = FontSystem::new();
    /// # let state = TextState::new_with_text("Hello", &mut font_system, ());
    /// let scroll = state.absolute_scroll();
    /// println!("Scrolled by: ({}, {})", scroll.x, scroll.y);
    /// ```
    pub fn absolute_scroll(&self) -> Point {
        let scale = self.params.scale_factor().max(0.01);
        let scroll = self.buffer.scroll();
        let scroll_line = scroll.line;
        let scroll_vertical = scroll.vertical;
        let scroll_horizontal = scroll.horizontal;
        let mut line_vertical_start = 0.0;
        let line_height = self.style().line_height_pt();
        for (line_i, line) in self.buffer.lines.iter().enumerate() {
            if line_i == scroll_line {
                // Found line
                break;
            }
            if let Some(layout_lines) = line.layout_opt() {
                for layout_line in layout_lines {
                    line_vertical_start +=
                        layout_line.line_height_opt.unwrap_or(line_height * scale);
                }
            }
        }
        // Convert to LOGICAL pixels
        Point {
            x: scroll_horizontal / scale,
            y: (scroll_vertical + line_vertical_start) / scale,
        }
    }

    /// Sets the absolute scroll position of the text buffer. Note that text that has fixed
    /// alignment (e.g. `VerticalTextAlignment::Top`) will not be affected by this method,
    /// and the scroll position will be calculated based on the current text layout and line
    /// heights. For the scroll to take effect, alignment must be set to
    /// `VerticalTextAlignment::None`.
    ///
    /// This allows you to programmatically scroll the text content to a specific position.
    /// The scroll position is calculated based on line heights and text layout.
    ///
    /// # Arguments
    /// * `scroll` - The absolute scroll position to set
    ///
    /// # Examples
    /// ```
    /// # use protextinator::{TextState, math::Point};
    /// # use cosmic_text::FontSystem;
    /// # let mut font_system = FontSystem::new();
    /// # let mut state = TextState::new_with_text("Hello\nWorld\nMore\nText", &mut font_system, ());
    /// state.set_absolute_scroll(Point::new(0.0, 50.0));
    /// ```
    pub fn set_absolute_scroll(&mut self, scroll: Point) {
        let mut new_scroll = self.buffer.scroll();
        let scale = self.params.scale_factor().max(0.01);

        let can_scroll_vertically =
            matches!(self.style().vertical_alignment, VerticalTextAlignment::None);

        // Horizontal scroll is stored in DEVICE pixels
        new_scroll.horizontal = scroll.x * scale;

        if can_scroll_vertically {
            let line_height = self.style().line_height_pt();
            let mut line_index = 0;
            let mut accumulated_height_device = 0.0;
            let target_y_device = scroll.y * scale;

            for (i, line) in self.buffer.lines.iter().enumerate() {
                let mut line_height_total_device = 0.0;

                if let Some(layout_lines) = line.layout_opt() {
                    for layout_line in layout_lines {
                        line_height_total_device +=
                            layout_line.line_height_opt.unwrap_or(line_height * scale);
                    }
                }

                if accumulated_height_device + line_height_total_device > target_y_device {
                    line_index = i;
                    break;
                }

                accumulated_height_device += line_height_total_device;
                line_index = i + 1; // In case we don't break, this will be the last line
            }

            // Set the line and calculate the remaining vertical offset (device px)
            new_scroll.line = line_index;
            new_scroll.vertical = target_y_device - accumulated_height_device;
        }

        // Apply only if changed
        let old = self.buffer.scroll();
        if (old.horizontal - new_scroll.horizontal).abs() > SIZE_EPSILON
            || (old.vertical - new_scroll.vertical).abs() > SIZE_EPSILON
            || old.line != new_scroll.line
        {
            self.buffer.set_scroll(new_scroll);
            // Any scroll change requires re-rasterization
            self.raster_dirty = true;
        }
    }

    /// Calculates physical selection area based on the selection start and end glyph indices
    fn recalculate_selection_area(&mut self) -> Option<()> {
        if !self.is_selectable {
            return None;
        }

        let mut selection_starts_at_index = self.selection.origin_character_byte_cursor?;
        let mut selection_ends_before_char_index =
            self.selection.ends_before_character_byte_cursor?;
        if selection_starts_at_index > selection_ends_before_char_index {
            // Swap the values
            std::mem::swap(
                &mut selection_ends_before_char_index,
                &mut selection_starts_at_index,
            );
        }

        let start_cursor = selection_starts_at_index;
        let end_cursor = selection_ends_before_char_index;

        self.selection.lines.clear();
        for run in self.buffer.layout_runs() {
            if let Some((start_x, width)) = run.highlight(start_cursor.cursor, end_cursor.cursor) {
                let scale = self.params.scale_factor().max(0.01);
                self.selection.lines.push(SelectionLine {
                    // Convert to LOGICAL pixels
                    start_x_pt: Some((start_x - self.buffer.scroll().horizontal) / scale),
                    end_x_pt: Some((start_x + width - self.buffer.scroll().horizontal) / scale),
                    start_y_pt: Some(run.line_top / scale),
                    end_y_pt: Some((run.line_top + run.line_height) / scale),
                });
            }
        }
        None
    }

    pub fn recalculate_with_update_reason(
        &mut self,
        ctx: &mut TextContext,
        update_reason: UpdateReason,
    ) {
        self.reshape_if_params_changed(ctx);
        self.adjust_scroll_if_cursor_moved(update_reason, &mut ctx.font_system);
        // TODO: do only if scroll/selection changed
        self.recalculate_selection_area();

        // TODO: do that if the buffer was reshaped
        self.relative_caret_position = self.calculate_caret_position();
        self.align_vertically();
    }

    /// Recalculates and reshapes the text buffer, scroll, caret position, and selection area.
    /// The results are cached, so don't be afraid to call this function multiple times.
    ///
    /// This is the main method to call after making changes to text content, style, or size
    /// to ensure the visual representation is updated correctly.
    ///
    /// # Arguments
    /// * `ctx` - Mutable reference to the text context for processing
    ///
    /// # Examples
    /// ```
    /// # use protextinator::{TextState, TextContext};
    /// # use cosmic_text::FontSystem;
    /// # let mut font_system = FontSystem::new();
    /// # let mut state = TextState::new_with_text("Hello", &mut font_system, ());
    /// # let mut ctx = TextContext::default();
    /// state.recalculate(&mut ctx);
    /// ```
    pub fn recalculate(&mut self, ctx: &mut TextContext) {
        self.recalculate_with_update_reason(ctx, UpdateReason::Unknown);
    }

    fn calculate_caret_position(&mut self) -> Option<Point> {
        // Return caret position in LOGICAL pixels relative to viewport
        let horizontal_scroll_device = self.buffer.scroll().horizontal;
        let scale = self.params.scale_factor().max(0.01);
        cursor_position_with_trailing_space_fallback(&mut self.buffer, self.cursor).map(
            |mut point_device| {
                // pos from cosmic_text is in DEVICE pixels
                // Adjust by horizontal scroll (device px)
                point_device.x -= horizontal_scroll_device;
                // Convert to logical
                Point::new(point_device.x / scale, point_device.y / scale)
            },
        )
    }

    fn align_vertically(&mut self) {
        if matches!(self.style().vertical_alignment, VerticalTextAlignment::None) {
            return;
        }

        let mut scroll = self.buffer.scroll();
        let text_area_size = self.params.size();
        let vertical_scroll_to_align_text_logical =
            calculate_vertical_offset(self.params.style(), text_area_size, self.inner_dimensions);
        let scale = self.params.scale_factor().max(0.01);
        let target_vertical_device = vertical_scroll_to_align_text_logical * scale;
        if (scroll.vertical - target_vertical_device).abs() > SIZE_EPSILON {
            scroll.vertical = target_vertical_device;
            self.buffer.set_scroll(scroll);
            // Vertical alignment scroll change affects raster
            self.raster_dirty = true;
        }
    }

    /// Buffer needs to be shaped before calling this function, as it relies on the buffer's layout
    /// and dimensions.
    fn adjust_scroll_if_cursor_moved(
        &mut self,
        update_reason: UpdateReason,
        font_system: &mut FontSystem,
    ) -> Option<()> {
        if update_reason.is_cursor_updated() {
            let text_area_size = self.params.size();
            let scale = self.params.scale_factor().max(0.01);
            let old_scroll = self.buffer.scroll();
            let old_relative_caret_x_logical = self.relative_caret_position.map_or(0.0, |p| p.x);
            // Convert old absolute caret to logical coords
            let old_absolute_caret_x_logical =
                old_relative_caret_x_logical + old_scroll.horizontal / scale;

            let caret_position_relative_to_buffer = adjust_vertical_scroll_to_make_caret_visible(
                &mut self.buffer,
                self.cursor,
                font_system,
                self.params.size(),
                self.params.style(),
                scale,
            )?;
            let mut new_scroll = self.buffer.scroll();
            let text_area_width = text_area_size.x;

            // TODO: there was some other implementation that took horizontal alignment into account,
            //  check if it is needed
            let new_absolute_caret_offset = caret_position_relative_to_buffer.x; // logical

            // TODO: A little hack to set horizontal scroll
            let current_absolute_visible_text_area = (
                old_scroll.horizontal / scale,
                old_scroll.horizontal / scale + text_area_width,
            );
            let min = current_absolute_visible_text_area.0;
            let max = current_absolute_visible_text_area.1;
            let is_new_caret_visible =
                new_absolute_caret_offset >= min && new_absolute_caret_offset <= max;

            // If the caret is within the visible text area, we don't need to scroll.
            //  In that case, we should return the old scroll and modify the caret offset
            if is_new_caret_visible {
                let is_moving_caret_without_updating_the_text =
                    matches!(update_reason, UpdateReason::MoveCaret);
                if !is_moving_caret_without_updating_the_text {
                    let text_shift_logical =
                        old_absolute_caret_x_logical - new_absolute_caret_offset;

                    // If a text was deleted (caret moved left), adjust the scroll to compensate
                    if text_shift_logical > 0.0 {
                        // Adjust scroll to keep the caret visually in the same position
                        new_scroll.horizontal =
                            (old_scroll.horizontal - text_shift_logical * scale).max(0.0);

                        // Ensure we don't scroll beyond the text boundaries
                        let inner_dimensions = self.inner_size();
                        let area_width = self.outer_size().x;

                        if inner_dimensions.x > area_width {
                            // Text is larger than viewport - clamp scroll to valid range
                            let max_scroll_device =
                                (inner_dimensions.x - area_width + self.caret_width) * scale;
                            new_scroll.horizontal = new_scroll.horizontal.min(max_scroll_device);
                        } else {
                            // Text fits within the viewport - no scroll needed
                            new_scroll.horizontal = 0.0;
                        }
                    }
                }
            } else if new_absolute_caret_offset > max {
                new_scroll.horizontal =
                    (new_absolute_caret_offset - text_area_width + self.caret_width) * scale;
            } else if new_absolute_caret_offset < min {
                new_scroll.horizontal = new_absolute_caret_offset * scale;
            } else if new_absolute_caret_offset < 0.0 {
                new_scroll.horizontal = 0.0;
            } else {
                // Do nothing?
            }

            // Apply only if changed
            let old = self.buffer.scroll();
            if (old.horizontal - new_scroll.horizontal).abs() > SIZE_EPSILON
                || (old.vertical - new_scroll.vertical).abs() > SIZE_EPSILON
                || old.line != new_scroll.line
            {
                self.buffer.set_scroll(new_scroll);
                // Scroll changes affect raster
                self.raster_dirty = true;
            }
        }

        None
    }

    /// Reshapes the text buffer if parameters have changed since the last reshape.
    ///
    /// This method checks if any text parameters (content, style, size) have changed
    /// and only performs the expensive reshape operation if necessary.
    fn reshape_if_params_changed(&mut self, ctx: &mut TextContext) {
        let font_query_changed = self.params.font_query_changed_since_last_shape();
        if font_query_changed {
            let new_font_family = ctx.font_family_cache.resolve_font_family_query(
                self.params.style().font_family_query(),
                &mut ctx.font_system,
            );
            self.resolved_font_family = new_font_family;
            self.params.reset_font_query_changed();
        }
        let params_changed = self.params.changed_since_last_shape();
        if params_changed {
            let new_size = update_buffer(
                &self.params,
                &mut self.buffer,
                &mut ctx.font_system,
                &self.resolved_font_family,
            );
            self.inner_dimensions = new_size;
            self.params.reset_changed();
            // Any layout/text/style/size change requires re-rasterization
            self.raster_dirty = true;
        }
    }

    /// Rasterizes the current text buffer into an RGBA8 CPU texture using device-pixel dimensions.
    ///
    /// Returns true if rasterization was performed (and texture updated), false if skipped
    /// (e.g., zero-sized target).
    pub(crate) fn rasterize_into_texture(
        &mut self,
        ctx: &mut TextContext,
        alpha_mode: AlphaMode,
    ) -> bool {
        // Compute device-pixel texture size from the logical outer size and scale factor
        let size = self.outer_size();
        let scale = ctx.scale_factor.max(0.01);
        let width = (size.x * scale).ceil().max(0.0) as u32;
        let height = (size.y * scale).ceil().max(0.0) as u32;
        if width == 0 || height == 0 {
            // No room to rasterize; clear texture and mark clean
            self.rasterized_texture.width = 0;
            self.rasterized_texture.height = 0;
            self.rasterized_texture.pixels.clear();
            self.raster_dirty = false;
            return false;
        }

        let dims_changed =
            self.rasterized_texture.width != width || self.rasterized_texture.height != height;

        // Skip if nothing changed and dimensions match
        if !dims_changed && !self.raster_dirty {
            return false;
        }

        let required_len = width as usize * height as usize * 4;
        // Ensure capacity and set length; reuse allocation when possible
        if self.rasterized_texture.pixels.len() != required_len {
            self.rasterized_texture.pixels.resize(required_len, 0);
        }

        // Clear to transparent before drawing (fast fill)
        self.rasterized_texture.pixels.fill(0);

        let base_color = cosmic_text::Color::rgba(0, 0, 0, 0);
        let requested_font_alpha = self.params.style().font_color.0.a();
        let text_width = width;
        let text_height = height;
        let horizontal_scroll_device = self.buffer.scroll().horizontal.round() as i64;
        // TODO: make an atlas via an adapter trait or something that can be passed to here from the renderer
        self.buffer.draw(
            &mut ctx.font_system,
            &mut ctx.swash_cache,
            base_color,
            |x, y, mut w, mut h, color| {
                if w == 0 || h == 0 {
                    return;
                }

                // Use signed clipping first because scrolled glyphs can produce negative device
                // coordinates. Casting negatives to unsigned would incorrectly wrap and skip
                // visible glyph portions near the viewport edge.
                // Cosmic-text horizontal scroll is not reflected in draw callback coordinates,
                // so apply it explicitly here to keep rasterized output in sync with the buffer.
                let mut x_device = x as i64 - horizontal_scroll_device;
                let mut y_device = y as i64;
                let mut width_device = w as i64;
                let mut height_device = h as i64;

                if x_device < 0 {
                    let cut = -x_device;
                    if cut >= width_device {
                        return;
                    }
                    x_device = 0;
                    width_device -= cut;
                }
                if y_device < 0 {
                    let cut = -y_device;
                    if cut >= height_device {
                        return;
                    }
                    y_device = 0;
                    height_device -= cut;
                }

                if x_device >= text_width as i64 || y_device >= text_height as i64 {
                    return;
                }
                let max_width = text_width as i64 - x_device;
                let max_height = text_height as i64 - y_device;
                width_device = width_device.min(max_width);
                height_device = height_device.min(max_height);

                if width_device <= 0 || height_device <= 0 {
                    return;
                }

                let x0 = x_device as u32;
                let y0 = y_device as u32;
                w = width_device as u32;
                h = height_device as u32;

                // Precompute the 4-byte pixel once per rectangle and use row-wise fills
                let mut packed_px = [0u8; 4];
                // IMPORTANT: cosmic-text's mask glyph path replaces alpha with glyph coverage and does not
                // apply the requested font alpha. Reapply the style alpha here so semi-transparent
                // text survives rasterization.
                let effective_alpha =
                    ((u16::from(color.a()) * u16::from(requested_font_alpha) + 127) / 255) as u8;
                match alpha_mode {
                    AlphaMode::Premultiplied => {
                        let r_lin = srgb_to_linear_u8(color.r());
                        let g_lin = srgb_to_linear_u8(color.g());
                        let b_lin = srgb_to_linear_u8(color.b());
                        let a = effective_alpha as f32 / 255.0;
                        let r_pma = r_lin * a;
                        let g_pma = g_lin * a;
                        let b_pma = b_lin * a;
                        packed_px[0] = linear_to_srgb_u8(r_pma);
                        packed_px[1] = linear_to_srgb_u8(g_pma);
                        packed_px[2] = linear_to_srgb_u8(b_pma);
                        packed_px[3] = effective_alpha;
                    }
                    AlphaMode::Unmultiplied => {
                        packed_px[0] = color.r();
                        packed_px[1] = color.g();
                        packed_px[2] = color.b();
                        packed_px[3] = effective_alpha;
                    }
                }

                // Fill each destination row with the precomputed pixel
                for row in 0..h {
                    let dst_row_start = ((y0 + row) * text_width * 4 + x0 * 4) as usize;
                    let row_slice = &mut self.rasterized_texture.pixels
                        [dst_row_start..dst_row_start + (w as usize) * 4];

                    // Repeat-copy packed_px across the row
                    // Avoid per-pixel math; just copy the 4-byte pattern
                    let mut i = 0usize;
                    while i + 4 <= row_slice.len() {
                        row_slice[i..i + 4].copy_from_slice(&packed_px);
                        i += 4;
                    }
                }
            },
        );

        // Update texture dimensions and clear dirty flag
        self.rasterized_texture.width = width;
        self.rasterized_texture.height = height;
        self.raster_dirty = false;

        true
    }

    /// Updates the internal scale factor in params; will trigger reshape on next recalc if changed.
    pub fn set_scale_factor(&mut self, scale: f32) {
        self.params.set_scale_factor(scale);
    }

    fn copy_selected_text(&mut self) -> ActionResult {
        let selected_text = self.selected_text().unwrap_or("");
        ActionResult::TextCopied(selected_text.to_string())
    }

    fn paste_text_at_cursor(&mut self, ctx: &mut TextContext, text: &str) -> ActionResult {
        if !text.is_empty() {
            self.reset_selection_end();
        }

        self.params
            .insert_str(self.cursor.byte_character_start, text);
        self.recalculate_with_update_reason(ctx, UpdateReason::InsertedText);
        ActionResult::TextChanged
    }

    fn select_all_recalculate(&mut self, ctx: &mut TextContext) -> ActionResult {
        self.select_all();
        self.recalculate_with_update_reason(ctx, UpdateReason::SelectionChanged);
        ActionResult::CursorUpdated
    }

    fn cut_selected_text(&mut self, ctx: &mut TextContext) -> ActionResult {
        let selected_text = self.selected_text().unwrap_or("").to_string();
        self.remove_selected_text();
        self.recalculate_with_update_reason(ctx, UpdateReason::DeletedTextAtCursor);
        ActionResult::TextCut(selected_text)
    }

    fn delete_selected_text_or_text_before_cursor(
        &mut self,
        ctx: &mut TextContext,
    ) -> ActionResult {
        if self.is_text_selected() {
            self.remove_selected_text();
        } else {
            self.remove_char_at_cursor();
        }
        self.recalculate_with_update_reason(ctx, UpdateReason::DeletedTextAtCursor);
        ActionResult::TextChanged
    }

    fn move_cursor_right_recalculate(&mut self, ctx: &mut TextContext) -> ActionResult {
        if self.is_text_selected() {
            self.move_cursor_to_selection_right();
        } else {
            self.move_cursor(ctx, Motion::Right);
        }
        self.reset_selection();
        self.recalculate_with_update_reason(ctx, UpdateReason::MoveCaret);
        ActionResult::CursorUpdated
    }

    fn move_cursor_left_recalculate(&mut self, ctx: &mut TextContext) -> ActionResult {
        if self.is_text_selected() {
            self.move_cursor_to_selection_left();
        } else {
            self.move_cursor(ctx, Motion::Left);
        }
        self.reset_selection();
        self.recalculate_with_update_reason(ctx, UpdateReason::MoveCaret);
        ActionResult::CursorUpdated
    }

    fn move_cursor(&mut self, ctx: &mut TextContext, motion: Motion) -> ActionResult {
        let buffer = &mut self.buffer;
        let old_cursor = self.cursor.cursor;
        let mut edit = Editor::new(buffer);
        edit.set_cursor(self.cursor.cursor);
        edit.action(&mut ctx.font_system, cosmic_text::Action::Motion(motion));
        let new_cursor = edit.cursor();
        self.update_cursor_before_glyph_with_cursor(new_cursor);

        if self.cursor.cursor == old_cursor {
            return ActionResult::None;
        }

        ActionResult::CursorUpdated
    }

    fn move_cursor_recalculate(&mut self, ctx: &mut TextContext, motion: Motion) -> ActionResult {
        let res = self.move_cursor(ctx, motion);
        self.reset_selection();
        self.recalculate_with_update_reason(ctx, UpdateReason::MoveCaret);
        res
    }

    fn insert_character(&mut self, character: &SmolStr, ctx: &mut TextContext) -> ActionResult {
        if self.is_text_selected() {
            self.move_cursor(ctx, Motion::Left);
            self.remove_selected_text();
        }
        for character in character.chars() {
            self.insert_char_at_cursor(character, ctx);
            self.reset_selection_end();
        }

        self.recalculate_with_update_reason(ctx, UpdateReason::InsertedText);
        ActionResult::TextChanged
    }

    /// Applies a text editing action and returns the result.
    ///
    /// This is the main method for processing text editing operations like inserting text,
    /// moving the cursor, copying/pasting, etc. The method respects the current text state
    /// configuration (editable, selectable, actions enabled).
    ///
    /// # Arguments
    /// * `ctx` - Mutable reference to the text context for processing
    /// * `action` - The action to apply
    ///
    /// # Returns
    /// An `ActionResult` indicating what happened as a result of the action
    ///
    /// # Examples
    /// ```
    /// # use protextinator::{TextState, TextContext, Action, ActionResult};
    /// # use cosmic_text::FontSystem;
    /// # let mut font_system = FontSystem::new();
    /// # let mut state = TextState::new_with_text("Hello", &mut font_system, ());
    /// # let mut ctx = TextContext::default();
    /// # state.is_editable = true;
    /// # state.are_actions_enabled = true;
    /// let result = state.apply_action(&mut ctx, &Action::InsertChar("x".into()));
    /// match result {
    ///     ActionResult::TextChanged => println!("Text was modified"),
    ///     ActionResult::CursorUpdated => println!("Cursor position changed"),
    ///     _ => {}
    /// }
    /// ```
    pub fn apply_action(&mut self, ctx: &mut TextContext, action: &Action) -> ActionResult {
        if !self.are_actions_enabled {
            return ActionResult::ActionsDisabled;
        }

        if self.is_selectable {
            let res = if self.is_editable {
                match action {
                    Action::Paste(text) => self.paste_text_at_cursor(ctx, text),
                    Action::Cut => self.cut_selected_text(ctx),
                    Action::DeleteBackward => self.delete_selected_text_or_text_before_cursor(ctx),
                    Action::MoveCursorRight => self.move_cursor_right_recalculate(ctx),
                    Action::MoveCursorLeft => self.move_cursor_left_recalculate(ctx),
                    Action::MoveCursorUp => self.move_cursor_recalculate(ctx, Motion::Up),
                    Action::MoveCursorDown => self.move_cursor_recalculate(ctx, Motion::Down),
                    Action::InsertChar(character) => self.insert_character(character, ctx),
                    _ => ActionResult::None,
                }
            } else {
                ActionResult::None
            };

            if res.is_none() {
                match action {
                    Action::CopySelectedText => self.copy_selected_text(),
                    Action::SelectAll => self.select_all_recalculate(ctx),
                    _ => ActionResult::None,
                }
            } else {
                res
            }
        } else {
            ActionResult::None
        }
    }

    // TODO: make it an action
    /// Handles a mouse press event on the text area.
    ///
    /// This method processes mouse clicks for cursor positioning and selection start.
    /// It converts the click position to a character position in the text and updates
    /// the cursor accordingly.
    ///
    /// # Arguments
    /// * `text_context` - Mutable reference to the text context
    /// * `click_position_relative_to_area` - The click position relative to the text area
    ///
    /// # Returns
    /// `Some(())` if the press was handled, `None` otherwise
    ///
    /// # Examples
    /// ```
    /// # use protextinator::{TextState, TextContext, math::Point};
    /// # use cosmic_text::FontSystem;
    /// # let mut font_system = FontSystem::new();
    /// # let mut state = TextState::new_with_text("Hello", &mut font_system, ());
    /// # let mut ctx = TextContext::default();
    /// # state.is_selectable = true;
    /// let click_pos = Point::new(10.0, 5.0);
    /// state.handle_press(&mut ctx, click_pos);
    /// ```
    pub fn handle_press(
        &mut self,
        text_context: &mut TextContext,
        click_position_relative_to_area: Point,
    ) -> Option<()> {
        if self.is_selectable || self.is_editable {
            self.reset_selection();

            let byte_offset_cursor = char_under_position(
                &self.buffer,
                click_position_relative_to_area,
                self.params.scale_factor(),
            )?;
            self.update_cursor_before_glyph_with_cursor(byte_offset_cursor);

            // Reset selection to start at the press location
            self.selection.origin_character_byte_cursor = Some(self.cursor);
            self.selection.ends_before_character_byte_cursor = None;

            self.recalculate_with_update_reason(text_context, UpdateReason::MoveCaret);
        }

        None
    }

    /// Handles mouse drag events for text selection.
    ///
    /// This method processes mouse drag operations to create and update text selections.
    /// It includes automatic scrolling when dragging beyond the visible text area.
    ///
    /// # Arguments
    /// * `ctx` - Mutable reference to the text context
    /// * `is_dragging` - Whether a drag operation is currently in progress
    /// * `pointer_relative_position` - The current pointer position relative to the text area
    ///
    /// # Returns
    /// `Some(())` if the drag was handled, `None` otherwise
    ///
    /// # Examples
    /// ```
    /// # use protextinator::{TextState, TextContext, math::Point};
    /// # use cosmic_text::FontSystem;
    /// # let mut font_system = FontSystem::new();
    /// # let mut state = TextState::new_with_text("Hello", &mut font_system, ());
    /// # let mut ctx = TextContext::default();
    /// # state.is_selectable = true;
    /// let drag_pos = Point::new(50.0, 10.0);
    /// state.handle_drag(&mut ctx, true, drag_pos);
    /// ```
    pub fn handle_drag(
        &mut self,
        ctx: &mut TextContext,
        is_dragging: bool,
        pointer_relative_position: Point,
    ) -> Option<()> {
        if !is_dragging {
            return None;
        }
        if self.is_selectable {
            let byte_cursor_under_position = char_under_position(
                &self.buffer,
                pointer_relative_position,
                self.params.scale_factor(),
            )?;

            if let Some(_origin) = self.selection.origin_character_byte_cursor {
                self.selection.ends_before_character_byte_cursor = ByteCursor::from_cursor(
                    byte_cursor_under_position,
                    self.params.text_for_internal_use(),
                );
            }

            // Simple debounce to make scroll speed consistent
            let now = std::time::Instant::now();
            if now > self.last_scroll_timestamp + self.scroll_interval && is_dragging {
                let element_area = self.params.size();
                let is_dragging_to_the_right = pointer_relative_position.x > 0.0;
                let is_dragging_to_the_left = pointer_relative_position.x < element_area.x;

                if is_dragging_to_the_right || is_dragging_to_the_left {
                    self.update_cursor_before_glyph_with_cursor(byte_cursor_under_position);
                    self.last_scroll_timestamp = now;
                }
            }

            self.recalculate_with_update_reason(ctx, UpdateReason::MoveCaret);
        }

        None
    }

    #[cfg(test)]
    pub fn first_glyph(&mut self) -> Option<&LayoutGlyph> {
        self.buffer
            .layout_runs()
            .next()
            .and_then(|run| run.glyphs.first())
    }
}

/// Takes element height, text buffer height, and vertical alignment and returns the vertical offset
/// needed to align the text vertically.
///
/// This function calculates the appropriate vertical offset for text alignment based on
/// the text area size, buffer dimensions, and vertical alignment settings.
///
/// # Arguments
/// * `text_style` - The text style containing alignment information
/// * `text_area_size` - The size of the text area container
/// * `buffer_inner_dimensions` - The actual dimensions of the text content
///
/// # Returns
/// The vertical offset needed to achieve the desired alignment
pub(crate) fn calculate_vertical_offset(
    text_style: &TextStyle,
    text_area_size: Size,
    buffer_inner_dimensions: Size,
) -> f32 {
    let text_area_rect = Rect::new((0.0, 0.0).into(), text_area_size);
    let style = text_style;

    let vertical_alignment = style.vertical_alignment;
    // TODO: fix scaling
    let buffer_height = buffer_inner_dimensions.y;
    // TODO: FIX TOP.
    let vertical_offset = vertical_offset(vertical_alignment, text_area_rect, buffer_height);

    0.0 - vertical_offset
}

/// Describes the reason for a text state update operation.
///
/// This enum is used internally to optimize recalculation operations by providing
/// context about what type of change triggered the update, allowing for more
/// targeted and efficient updates.
pub enum UpdateReason {
    /// Text content was inserted at the cursor position.
    InsertedText,
    /// The cursor position was moved.
    MoveCaret,
    /// Text was deleted at or around the cursor position.
    DeletedTextAtCursor,
    /// The text selection was modified.
    SelectionChanged,
    /// The reason for the update is unknown or doesn't fit other categories.
    Unknown,
}

impl UpdateReason {
    /// Returns `true` if this update reason indicates a selection change.
    pub fn is_selection_changed(&self) -> bool {
        matches!(self, UpdateReason::SelectionChanged)
    }

    /// Returns `true` if this update reason indicates text was inserted.
    pub fn is_inserted_text(&self) -> bool {
        matches!(self, UpdateReason::InsertedText)
    }

    /// Returns `true` if this update reason indicates the cursor was moved.
    pub fn is_move_caret(&self) -> bool {
        matches!(self, UpdateReason::MoveCaret)
    }

    /// Returns `true` if this update reason indicates text was deleted.
    pub fn is_deleted_text_at_cursor(&self) -> bool {
        matches!(self, UpdateReason::DeletedTextAtCursor)
    }

    /// Returns `true` if this update reason indicates any cursor-related change.
    ///
    /// This includes cursor movement, text insertion, and text deletion operations.
    pub fn is_cursor_updated(&self) -> bool {
        matches!(
            self,
            UpdateReason::MoveCaret
                | UpdateReason::InsertedText
                | UpdateReason::DeletedTextAtCursor
        )
    }
}

#[derive(Debug, Copy, Clone)]
pub enum AlphaMode {
    /// Use premultiplied alpha for rendering. This is generally preferred for performance
    /// and quality, especially when blending with other premultiplied content.
    Premultiplied,
    /// Use unmultiplied alpha for rendering. This may be necessary when compositing
    /// with non-premultiplied content, but can lead to artifacts and is less efficient.
    Unmultiplied,
}