michiu_ui 0.0.3

The michiu library handles layout and rendering.
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
use crate::{
    ActiveInteractionStates, ActiveMasksSecondary, BaseVisualPropertiesSecondary, ByteIndex,
    CapacityConfig, CharIndex, Color, ComponentMask, Context, DEFAULT_FLEX, DebugStore,
    DirtyLayoutEntitiesVec, DirtyRenderEntitiesVec, EntityId, InputContents, InputContentsSparse,
    LayoutPoint, LayoutRect, LayoutSize, MichiuSoA, MichiuString, ParentsSecondary, RectsSecondary,
    RenderStore, ResolvedBasicSecondary, ResolvedFlexSecondary, ResolvedGeometry,
    ResolvedGridSparse, ScrollOffsetsSecondary, ScrollSizesSecondary, ScrollStore,
    ScrollbarStylesSparse, SystemStore, TaffyNodesSecondary, TaffyTreeEntityId, TextBufferSparse,
    TextContentsSparse, TextEngine, TextLayoutSize, TextSpansSparse, TopologyStore, UserSelect,
    VisualPropertiesSecondary, define_sparse_secondary,
};
use cosmic_text::Buffer;
use slotmap::SparseSecondaryMap;
use std::{ops::Range, rc::Rc};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InputOp {
    // 初期化用
    Init,
    // シグナル監視エフェクト同期用
    TextEffect,
    MousePress,
    ArrowMove,
    SelectAll,
    CharTyped,
    Backspace,
    Delete,
    ImeUpdated,
    Paste,
    Cut,
    Undo,
    Redo,
}

define_sparse_secondary!(pub struct SelectedRectsSparse(Vec<LayoutRect>));
define_sparse_secondary!(pub struct TextSelectionsSparse(Range<ByteIndex>));
define_sparse_secondary!(pub struct SelectionStartIndexSparse(ByteIndex));

pub(crate) struct TextEditStore {
    pub(crate) edit_selections: TextSelectionsSparse,
    pub(crate) edit_selection_start_index: SelectionStartIndexSparse,
    pub(crate) edit_selected_rects: SelectedRectsSparse,
}

impl Default for TextEditStore {
    fn default() -> Self {
        Self::new()
    }
}

impl TextEditStore {
    #[inline]
    #[must_use]
    pub(crate) fn new() -> Self {
        Self {
            edit_selections: TextSelectionsSparse(SparseSecondaryMap::new()),
            edit_selection_start_index: SelectionStartIndexSparse(SparseSecondaryMap::new()),
            edit_selected_rects: SelectedRectsSparse(SparseSecondaryMap::new()),
        }
    }

    #[inline]
    #[must_use]
    pub(crate) fn with_capacity(c: &CapacityConfig) -> Self {
        Self {
            edit_selections: TextSelectionsSparse(SparseSecondaryMap::with_capacity(
                c.edit_selections,
            )),
            edit_selected_rects: SelectedRectsSparse(SparseSecondaryMap::with_capacity(
                c.edit_selected_rects,
            )),
            edit_selection_start_index: SelectionStartIndexSparse(
                SparseSecondaryMap::with_capacity(c.edit_selection_start_index),
            ),
        }
    }

    #[inline]
    pub(crate) fn clear(&mut self) {
        self.edit_selections.clear();
        self.edit_selection_start_index.clear();
        self.edit_selected_rects.clear();
    }

    #[inline]
    pub(crate) fn despawn(&mut self, id: EntityId) {
        self.edit_selections.remove(id);
        self.edit_selection_start_index.remove(id);
        self.edit_selected_rects.remove(id);
    }
}

impl TextEditStore {
    #[inline]
    pub(crate) fn truncate_unconfirmed_text(
        text_val: &MichiuString,
        contents: &InputContents,
        max: CharIndex,
        filtered_comp_text: MichiuString,
    ) -> MichiuString {
        let range = &contents.selected_range;

        // 選択範囲削除後の文字数
        let selected_chars = text_val.slice(range.clone()).chars().count();
        let current_len_after_delete = text_val.char_count() - selected_chars;

        if current_len_after_delete >= max {
            // すでに確定文字数が制限に達している場合は空の MichiuString を返す
            MichiuString::default()
        } else {
            // 許容文字数
            let allowed_chars = max - current_len_after_delete;

            if filtered_comp_text.char_count().0 > allowed_chars {
                // 制限に収まるよう安全に文字数で切り詰め
                let truncated: String = filtered_comp_text.chars().take(allowed_chars).collect();
                MichiuString::from(truncated)
            } else {
                filtered_comp_text
            }
        }
    }

    #[inline]
    pub(crate) fn clear_selection_highlight_rect(
        id: EntityId,
        topo_active_masks: &mut ActiveMasksSecondary,
        cont_input_contents: &mut InputContentsSparse,
        cont_text_spans: &mut TextSpansSparse,
        edit_selections: &mut TextSelectionsSparse,
        edit_selected_rects: &mut SelectedRectsSparse,
    ) {
        edit_selections.remove(id);
        edit_selected_rects.remove(id);
        if let Some(contents) = cont_input_contents.find_mut(id) {
            contents.selected_range = ByteIndex(0)..ByteIndex(0);
            // 進行中の IME コンポジションをリセットして波線を消去
            contents.ime_state = None;
            contents.marked_range = None;
        }
        cont_text_spans.remove(id);
        let mask = topo_active_masks.at_mut(id);
        mask.unset(ComponentMask::STYLE_TEXT_SPANS);
    }

    pub(crate) fn calculate_caret_rect(
        geom: &ResolvedGeometry,
        contents: &InputContents,
        scale: f32,
        align_offset: LayoutPoint,
    ) -> LayoutRect {
        let logical_x = geom.rect.x
            + geom.border.left
            + geom.padding.left
            + align_offset.x
            + contents.measured_caret.x
            - geom.scroll.x;
        let aligned_x = (logical_x * scale).round() / scale;

        let line_height = contents.caret_line_height;
        let caret_width = contents.caret_width.unwrap_or(contents.default_caret_width);
        let caret_height = contents.caret_height.unwrap_or(line_height);

        let vertical_center_offset = if contents.caret_height.is_some() {
            (line_height - caret_height) * 0.5
        } else {
            0.0
        };

        let logical_y = geom.rect.y
            + geom.border.top
            + geom.padding.top
            + align_offset.y
            + contents.measured_caret.y
            + contents.caret_offset
            - geom.scroll.y;

        let aligned_y = ((logical_y + vertical_center_offset) * scale).round() / scale;
        let aligned_width = (caret_width * scale).round().max(1.0) / scale;
        let aligned_height = (caret_height * scale).round().max(1.0) / scale;

        LayoutRect::new(aligned_x, aligned_y, aligned_width, aligned_height)
    }

    pub(crate) fn calc_selection_rects(
        buffer: &Buffer,
        range: Range<ByteIndex>,
    ) -> Vec<LayoutRect> {
        // 範囲が空(選択なし)の場合は即座に空Vecを返す
        if range.start == range.end {
            return Vec::new();
        }

        let (start_idx, end_idx) = if range.start <= range.end {
            (range.start, range.end)
        } else {
            (range.end, range.start)
        };

        let mut cursor_start = TextEngine::flat_idx_to_cursor(buffer, start_idx);
        let mut cursor_end = TextEngine::flat_idx_to_cursor(buffer, end_idx);

        if (cursor_start.line > cursor_end.line)
            || (cursor_start.line == cursor_end.line && cursor_start.index > cursor_end.index)
        {
            std::mem::swap(&mut cursor_start, &mut cursor_end);
        }

        let mut out_rects = Vec::new();
        for run in buffer.layout_runs() {
            let line_i = run.line_i;

            // 選択範囲より前の行、または後の行はスキップ
            if line_i < cursor_start.line || line_i > cursor_end.line {
                continue;
            }

            // この行(run)における選択の始点と終点
            let line_len = buffer.lines.get(line_i).map_or(0, |l| l.text().len());

            // 開始行なら cursor_start.index、それ以降の行なら行頭(0)
            let run_cursor_start = if line_i == cursor_start.line {
                cursor_start
            } else {
                cosmic_text::Cursor {
                    line: line_i,
                    index: 0,
                    affinity: cosmic_text::Affinity::Before,
                }
            };

            // 終了行なら cursor_end.index、それ以前の行なら行末(line_len)
            let run_cursor_end = if line_i == cursor_end.line {
                cursor_end
            } else {
                cosmic_text::Cursor {
                    line: line_i,
                    index: line_len,
                    affinity: cosmic_text::Affinity::Before,
                }
            };

            // highlight を計算
            for (x, w) in run.highlight(run_cursor_start, run_cursor_end) {
                out_rects.push(LayoutRect::new(x, run.line_top, w, run.line_height));
            }
        }

        out_rects
    }

    /// 現在の選択範囲に基づき描画用の物理選択矩形を計算してキャッシュを更新
    #[inline]
    pub(crate) fn update_selection_rects(
        id: EntityId,
        buffer: &Rc<Buffer>,
        edit_selected_rects: &mut SelectedRectsSparse,
        edit_selections: &TextSelectionsSparse,
        cont_input_contents: &InputContentsSparse,
    ) {
        if let Some(range) = edit_selections.get(id).cloned()
            && range.start < range.end
        {
            // 生テキストの選択範囲を、表示テキスト(マスク文字)の選択範囲へ変換
            let display_range = if let Some(contents) = cont_input_contents.get(id) {
                let raw_text = contents.to_michiu();
                contents.raw_range_to_display_range(range, &raw_text)
            } else {
                range
            };

            let out_rects = TextEditStore::calc_selection_rects(buffer, display_range);
            edit_selected_rects.insert(id, out_rects);
            return;
        }
        // 範囲が 0、または選択なしの時は自動クリーンアップ
        edit_selected_rects.remove(id);
    }

    /// 現在フォーカスされている要素で範囲選択されている文字列を取得します。
    #[track_caller]
    pub(crate) fn get_selected_text(
        evt_interaction_states: &ActiveInteractionStates,
        cont_text_contents: &TextContentsSparse,
        rnd_visual: &VisualPropertiesSecondary,
        edit_selections: &TextSelectionsSparse,
    ) -> Option<MichiuString> {
        // フォーカスされている要素を最優先とし、
        // 無い場合は現在有効な空ではない選択範囲を持つ最初の要素を逆引き
        let target_id = evt_interaction_states.focused.or_else(|| {
            edit_selections
                .iter()
                .find(|(_, range)| range.start < range.end)
                .map(|(id, _)| id)
        })?;

        let user_select = rnd_visual.user_select(target_id);

        if user_select == UserSelect::Text {
            // テキストを選択してるなら Some のはず
            let range = edit_selections.at(target_id);
            if range.start < range.end {
                let text = cont_text_contents.at(target_id);
                let byte_range = range.clone();
                return Some(text.slice(byte_range).to_string().into());
            }
        }
        None
    }

    #[track_caller]
    pub(crate) fn handle_user_select_text(
        id: EntityId,
        pointer_pos: LayoutPoint,
        pressed_shift: bool,
        sys_text_engine: &mut TextEngine,
        sys_text_buffers: &TextBufferSparse,
        cont_text_contents: &TextContentsSparse,
        cont_text_spans: &TextSpansSparse,
        cont_input_contents: &InputContentsSparse,
        topo_active_masks: &mut ActiveMasksSecondary,
        lay_resolved_basic: &ResolvedBasicSecondary,
        lay_resolved_flex: &ResolvedFlexSecondary,
        rnd_dirty_entities: &mut DirtyRenderEntitiesVec,
        rnd_visual: &VisualPropertiesSecondary,
        edit_selections: &mut TextSelectionsSparse,
        edit_selection_start_index: &mut SelectionStartIndexSparse,
        edit_selected_rects: &mut SelectedRectsSparse,
        out_rects: &RectsSecondary,
        sc_offsets: &ScrollOffsetsSecondary,
        debug: &mut DebugStore,
    ) {
        let flex = lay_resolved_flex.find_or(id, &DEFAULT_FLEX, debug);
        let auto_wrap = rnd_visual.auto_wrap(id);

        let resolved_geom =
            ResolvedGeometry::resolved(id, sc_offsets, lay_resolved_basic, out_rects, debug);

        let content_width = resolved_geom.content_width();
        let max_width_opt = (auto_wrap && content_width > 0.0).then_some(content_width);

        let buffer =
            SystemStore::get_or_create_text_buffer(id, max_width_opt, sys_text_buffers, || {
                let text = cont_text_contents.at(id);
                let font = rnd_visual.font(id);

                let spans = cont_text_spans.span(id);
                sys_text_engine.create_buffer(
                    text,
                    &font,
                    flex.text_align,
                    max_width_opt,
                    auto_wrap,
                    spans,
                )
            });

        let text_size = if let Some(c) = cont_input_contents.find(id) {
            let size = c
                .last_layout
                .map_or(LayoutSize::ZERO, |r| LayoutSize::new(r.width, r.height));
            TextLayoutSize::new(size.width, size.height, Some(c.is_multiline))
        } else {
            TextEngine::get_layout_size(&buffer).set_multiline(Some(false))
        };

        let local = resolved_geom.pressed_local_point(
            pointer_pos,
            flex.text_align,
            flex.align_items,
            text_size,
        );
        let (clicked_index, is_trailing) = TextEngine::hit_test_point(&buffer, local);

        let final_index = if is_trailing {
            clicked_index + 1
        } else {
            clicked_index
        };

        if pressed_shift {
            // 共通の Shift選択拡張
            let anchor = edit_selection_start_index
                .get(id)
                .copied()
                .unwrap_or(final_index);
            if !edit_selection_start_index.contains_key(id) {
                edit_selection_start_index.insert(id, final_index);
            }
            let range = if anchor <= final_index {
                anchor..final_index
            } else {
                final_index..anchor
            };
            edit_selections.insert(id, range);
            TextEditStore::update_selection_rects(
                id,
                &buffer,
                edit_selected_rects,
                edit_selections,
                cont_input_contents,
            );
        } else {
            // 共通の通常クリックリセット
            edit_selection_start_index.insert(id, final_index);
            edit_selections.insert(id, final_index..final_index);
            edit_selected_rects.remove(id);
        }

        RenderStore::mark_render_dirty(id, topo_active_masks, rnd_dirty_entities);
    }

    #[track_caller]
    pub(crate) fn handle_text_selection_click(
        id: EntityId,
        start_pos: ByteIndex,
        local: LayoutPoint,
        buffer: &Rc<Buffer>,
        win_scale_factor: f32,
        win_last_size: Option<LayoutSize>,
        sys_text_engine: &mut TextEngine,
        sys_text_buffers: &TextBufferSparse,
        cont_text_contents: &mut TextContentsSparse,
        cont_input_contents: &mut InputContentsSparse,
        cont_text_spans: &TextSpansSparse,
        topo_active_masks: &mut ActiveMasksSecondary,
        topo_parents: &ParentsSecondary,
        lay_dirty_entities: &mut DirtyLayoutEntitiesVec,
        lay_taffy_tree: &mut TaffyTreeEntityId,
        bar_styles: &mut ScrollbarStylesSparse,
        lay_taffy_nodes: &TaffyNodesSecondary,
        lay_resolved_basic: &ResolvedBasicSecondary,
        lay_resolved_flex: &ResolvedFlexSecondary,
        lay_resolved_grid: &ResolvedGridSparse,
        rnd_dirty_entities: &mut DirtyRenderEntitiesVec,
        rnd_visual: &mut VisualPropertiesSecondary,
        rnd_base_visual: &BaseVisualPropertiesSecondary,
        sc_offsets: &mut ScrollOffsetsSecondary,
        edit_selections: &mut TextSelectionsSparse,
        edit_selected_rects: &mut SelectedRectsSparse,
        out_rects: &RectsSecondary,
        sc_sizes: &ScrollSizesSecondary,
        debug: &mut DebugStore,
    ) {
        let (display_index, is_trailing) = TextEngine::hit_test_point(buffer, local);

        // 表示テキストの文字境界を進める
        let display_text = cont_text_contents.at(id);
        let final_display_index = if is_trailing {
            display_text.next_char_boundary(display_index)
        } else {
            display_index
        };

        // 生テキストのバイト位置に逆算
        let final_raw_index = if let Some(contents) = cont_input_contents.get(id) {
            let raw_text = contents.to_michiu();
            contents.display_byte_to_raw_byte(final_display_index, &raw_text)
        } else {
            final_display_index
        };

        // 生テキスト基準で選択範囲を作成
        let (range, is_reversed) = if start_pos <= final_raw_index {
            (start_pos..final_raw_index, false)
        } else {
            (final_raw_index..start_pos, true)
        };

        edit_selections.insert(id, range.clone());

        TextEditStore::update_selection_rects(
            id,
            buffer,
            edit_selected_rects,
            edit_selections,
            cont_input_contents,
        );

        if let Some(contents) = cont_input_contents.find_mut(id) {
            contents.selection_reversed = is_reversed;
            contents.selected_range = range;

            TextEditStore::apply_input_update(
                id,
                InputOp::MousePress,
                win_scale_factor,
                win_last_size,
                sys_text_engine,
                sys_text_buffers,
                cont_text_contents,
                cont_input_contents,
                cont_text_spans,
                topo_active_masks,
                topo_parents,
                lay_dirty_entities,
                lay_taffy_tree,
                bar_styles,
                lay_taffy_nodes,
                lay_resolved_basic,
                lay_resolved_flex,
                lay_resolved_grid,
                rnd_dirty_entities,
                rnd_visual,
                rnd_base_visual,
                sc_offsets,
                edit_selections,
                edit_selected_rects,
                out_rects,
                sc_sizes,
                debug,
            );
        } else {
            RenderStore::mark_render_dirty(id, topo_active_masks, rnd_dirty_entities);
        }
    }

    /// 指定されたテキスト要素の内容をすべて選択状態に
    #[track_caller]
    pub(crate) fn handle_select_all(
        id: EntityId,
        win_scale_factor: f32,
        win_last_size: Option<LayoutSize>,
        sys_text_engine: &mut TextEngine,
        sys_text_buffers: &TextBufferSparse,
        cont_text_contents: &mut TextContentsSparse,
        cont_input_contents: &mut InputContentsSparse,
        cont_text_spans: &TextSpansSparse,
        topo_active_masks: &mut ActiveMasksSecondary,
        topo_parents: &ParentsSecondary,
        lay_dirty_entities: &mut DirtyLayoutEntitiesVec,
        lay_taffy_tree: &mut TaffyTreeEntityId,
        bar_styles: &mut ScrollbarStylesSparse,
        lay_taffy_nodes: &TaffyNodesSecondary,
        lay_resolved_basic: &ResolvedBasicSecondary,
        lay_resolved_flex: &ResolvedFlexSecondary,
        lay_resolved_grid: &ResolvedGridSparse,
        rnd_dirty_entities: &mut DirtyRenderEntitiesVec,
        rnd_visual: &mut VisualPropertiesSecondary,
        rnd_base_visual: &BaseVisualPropertiesSecondary,
        sc_offsets: &mut ScrollOffsetsSecondary,
        edit_selections: &mut TextSelectionsSparse,
        edit_selected_rects: &mut SelectedRectsSparse,
        out_rects: &RectsSecondary,
        sc_sizes: &ScrollSizesSecondary,
        debug: &mut DebugStore,
    ) {
        let auto_wrap = rnd_visual.auto_wrap(id);
        let resolved_geom =
            ResolvedGeometry::resolved(id, sc_offsets, lay_resolved_basic, out_rects, debug);

        let max_width_opt = resolved_geom.calc_max_width(auto_wrap);

        let buffer =
            SystemStore::get_or_create_text_buffer(id, max_width_opt, sys_text_buffers, || {
                let text = cont_text_contents.at(id);
                let font = rnd_visual.font(id);
                let spans = cont_text_spans.span(id);
                let flex = lay_resolved_flex.find_or(id, &DEFAULT_FLEX, debug);

                sys_text_engine.create_buffer(
                    text,
                    &font,
                    flex.text_align,
                    max_width_opt,
                    auto_wrap,
                    spans,
                )
            });

        // Input 要素の場合は生テキストの長さで全選択範囲を作る
        let input_full_range = if let Some(contents) = cont_input_contents.find_mut(id) {
            let raw_text = contents.to_michiu();
            let full_range = ByteIndex(0)..raw_text.byte_len();

            contents.selected_range = full_range.clone();
            contents.selection_reversed = false;
            Some(full_range)
        } else {
            None
        };

        if let Some(full_range) = input_full_range {
            edit_selections.insert(id, full_range);

            TextEditStore::update_selection_rects(
                id,
                &buffer,
                edit_selected_rects,
                edit_selections,
                cont_input_contents,
            );

            TextEditStore::apply_input_update(
                id,
                InputOp::SelectAll,
                win_scale_factor,
                win_last_size,
                sys_text_engine,
                sys_text_buffers,
                cont_text_contents,
                cont_input_contents,
                cont_text_spans,
                topo_active_masks,
                topo_parents,
                lay_dirty_entities,
                lay_taffy_tree,
                bar_styles,
                lay_taffy_nodes,
                lay_resolved_basic,
                lay_resolved_flex,
                lay_resolved_grid,
                rnd_dirty_entities,
                rnd_visual,
                rnd_base_visual,
                sc_offsets,
                edit_selections,
                edit_selected_rects,
                out_rects,
                sc_sizes,
                debug,
            );
        } else {
            // 通常のテキスト要素
            let text_len = cont_text_contents.at(id).byte_len();
            edit_selections.insert(id, ByteIndex(0)..text_len);
            TextEditStore::update_selection_rects(
                id,
                &buffer,
                edit_selected_rects,
                edit_selections,
                cont_input_contents,
            );
            RenderStore::mark_render_dirty(id, topo_active_masks, rnd_dirty_entities);
        }
    }

    #[track_caller]
    pub(crate) fn apply_input_update(
        id: EntityId,
        op: InputOp,
        win_scale_factor: f32,
        win_last_size: Option<LayoutSize>,
        sys_text_engine: &mut TextEngine,
        sys_text_buffers: &TextBufferSparse,
        cont_text_contents: &mut TextContentsSparse,
        cont_input_contents: &mut InputContentsSparse,
        cont_text_spans: &TextSpansSparse,
        topo_active_masks: &mut ActiveMasksSecondary,
        topo_parents: &ParentsSecondary,
        lay_dirty_entities: &mut DirtyLayoutEntitiesVec,
        lay_taffy_tree: &mut TaffyTreeEntityId,
        bar_styles: &mut ScrollbarStylesSparse,
        lay_taffy_nodes: &TaffyNodesSecondary,
        lay_resolved_basic: &ResolvedBasicSecondary,
        lay_resolved_flex: &ResolvedFlexSecondary,
        lay_resolved_grid: &ResolvedGridSparse,
        rnd_dirty_entities: &mut DirtyRenderEntitiesVec,
        rnd_visual: &mut VisualPropertiesSecondary,
        rnd_base_visual: &BaseVisualPropertiesSecondary,
        sc_offsets: &mut ScrollOffsetsSecondary,
        edit_selections: &mut TextSelectionsSparse,
        edit_selected_rects: &mut SelectedRectsSparse,
        out_rects: &RectsSecondary,
        sc_sizes: &ScrollSizesSecondary,
        debug: &mut DebugStore,
    ) {
        // 直前までハイライトが描画されていたか
        let has_selection_before = edit_selected_rects.contains_key(id);

        // 現在(操作後)に範囲選択されているか
        let has_selection_after = cont_input_contents
            .get(id)
            .is_some_and(|c| c.selected_range.start != c.selected_range.end);

        // 選択範囲の描画を更新
        if has_selection_before || has_selection_after {
            let auto_wrap = rnd_visual.auto_wrap(id);
            let resolved_geom =
                ResolvedGeometry::resolved(id, sc_offsets, lay_resolved_basic, out_rects, debug);
            let max_width_opt = resolved_geom.calc_max_width(auto_wrap);

            let buffer =
                SystemStore::get_or_create_text_buffer(id, max_width_opt, sys_text_buffers, || {
                    let text = cont_text_contents.at(id);
                    let font = rnd_visual.font(id);
                    let spans = cont_text_spans.span(id);
                    let flex = lay_resolved_flex.find_or(id, &DEFAULT_FLEX, debug);
                    sys_text_engine.create_buffer(
                        text,
                        &font,
                        flex.text_align,
                        max_width_opt,
                        auto_wrap,
                        spans,
                    )
                });
            TextEditStore::update_selection_rects(
                id,
                &buffer,
                edit_selected_rects,
                edit_selections,
                cont_input_contents,
            );
        }

        if let Some(c) = cont_input_contents.find_mut(id) {
            c.needs_scroll_to_caret = true;
        }

        match op {
            // コンテンツのサイズに変動がない(Taffyレイアウトの再計算が不要)操作
            InputOp::MousePress | InputOp::ArrowMove | InputOp::SelectAll => {
                TextEditStore::update_input_caret_position(
                    id,
                    win_scale_factor,
                    win_last_size,
                    sys_text_engine,
                    sys_text_buffers,
                    cont_text_contents,
                    cont_input_contents,
                    cont_text_spans,
                    topo_active_masks,
                    topo_parents,
                    lay_dirty_entities,
                    lay_taffy_tree,
                    bar_styles,
                    lay_taffy_nodes,
                    lay_resolved_basic,
                    lay_resolved_flex,
                    lay_resolved_grid,
                    rnd_visual,
                    rnd_base_visual,
                    sc_offsets,
                    edit_selections,
                    out_rects,
                    sc_sizes,
                    debug,
                );
                RenderStore::mark_render_dirty(id, topo_active_masks, rnd_dirty_entities);
            }

            // Taffy計算前に表示用テキストの同期が必須
            // 未確定文字の伸縮時はシグナルが更新されないため ImeUpdated を含める
            InputOp::Init | InputOp::TextEffect | InputOp::ImeUpdated => {
                // IMEやタイピング中の古いキャッシュを破棄
                SystemStore::clear_text_buffer_cache(id, sys_text_buffers);
                TextEditStore::update_input_caret_position(
                    id,
                    win_scale_factor,
                    win_last_size,
                    sys_text_engine,
                    sys_text_buffers,
                    cont_text_contents,
                    cont_input_contents,
                    cont_text_spans,
                    topo_active_masks,
                    topo_parents,
                    lay_dirty_entities,
                    lay_taffy_tree,
                    bar_styles,
                    lay_taffy_nodes,
                    lay_resolved_basic,
                    lay_resolved_flex,
                    lay_resolved_grid,
                    rnd_visual,
                    rnd_base_visual,
                    sc_offsets,
                    edit_selections,
                    out_rects,
                    sc_sizes,
                    debug,
                );
                TopologyStore::mark_dirty(
                    id,
                    topo_active_masks,
                    topo_parents,
                    lay_dirty_entities,
                    lay_taffy_tree,
                    lay_taffy_nodes,
                    rnd_dirty_entities,
                    debug,
                );
            }

            // シグナルエフェクト側で update_input_caret_position が走るが、
            // 不具合によってエフェクト自体がスキップされることも考慮してフラグを立てる
            InputOp::CharTyped
            | InputOp::Backspace
            | InputOp::Delete
            | InputOp::Paste
            | InputOp::Cut
            | InputOp::Undo
            | InputOp::Redo => {
                // IMEやタイピング中の古いキャッシュを破棄
                SystemStore::clear_text_buffer_cache(id, sys_text_buffers);
                TopologyStore::mark_dirty(
                    id,
                    topo_active_masks,
                    topo_parents,
                    lay_dirty_entities,
                    lay_taffy_tree,
                    lay_taffy_nodes,
                    rnd_dirty_entities,
                    debug,
                );
            }
        }
    }

    /// 現在のテキスト・IME状態・フォントサイズから、
    /// キャレットの物理座標や最終表示テキスト、レイアウト矩形を正確に再計算して `SoA` を更新。
    pub(crate) fn update_input_caret_position(
        id: EntityId,
        win_scale_factor: f32,
        win_last_size: Option<LayoutSize>,
        sys_text_engine: &mut TextEngine,
        sys_text_buffers: &TextBufferSparse,
        cont_text_contents: &mut TextContentsSparse,
        cont_input_contents: &mut InputContentsSparse,
        cont_text_spans: &TextSpansSparse,
        topo_active_masks: &mut ActiveMasksSecondary,
        topo_parents: &ParentsSecondary,
        lay_dirty_entities: &mut DirtyLayoutEntitiesVec,
        lay_taffy_tree: &mut TaffyTreeEntityId,
        bar_styles: &mut ScrollbarStylesSparse,
        lay_taffy_nodes: &TaffyNodesSecondary,
        lay_resolved_basic: &ResolvedBasicSecondary,
        lay_resolved_flex: &ResolvedFlexSecondary,
        lay_resolved_grid: &ResolvedGridSparse,
        rnd_visual: &mut VisualPropertiesSecondary,
        rnd_base_visual: &BaseVisualPropertiesSecondary,
        sc_offsets: &mut ScrollOffsetsSecondary,
        edit_selections: &mut TextSelectionsSparse,
        out_rects: &RectsSecondary,
        sc_sizes: &ScrollSizesSecondary,
        debug: &mut DebugStore,
    ) {
        let ime_caret_info = TextEditStore::ime_caret_info(
            id,
            sys_text_engine,
            sys_text_buffers,
            cont_text_contents,
            cont_input_contents,
            cont_text_spans,
            lay_resolved_basic,
            lay_resolved_flex,
            rnd_visual,
            rnd_base_visual,
            edit_selections,
            out_rects,
            sc_offsets,
            debug,
        );

        let Some((caret, caret_offset, is_multiline)) = ime_caret_info else {
            return;
        };
        let flex = lay_resolved_flex.find_or(id, &DEFAULT_FLEX, debug);
        let _grid = lay_resolved_grid.find_or_default(id, debug);

        let resolved_geom =
            ResolvedGeometry::resolved(id, sc_offsets, lay_resolved_basic, out_rects, debug);

        // キャレットがあるなら Some のはず
        let contents = cont_input_contents.at_mut(id);

        let should_scroll = contents.needs_scroll_to_caret;

        let mut scroll_offset = sc_offsets.find_or_default(id, debug);

        if should_scroll && resolved_geom.rect.width > 0.0 && resolved_geom.rect.height > 0.0 {
            let viewport = resolved_geom.viewport_size();

            let text_size = if let Some(layout_rect) = contents.last_layout {
                TextLayoutSize::new(layout_rect.width, layout_rect.height, None)
            } else {
                TextLayoutSize::DEFAULT
            };

            let align_offset =
                resolved_geom.calc_align_offset(text_size, flex.text_align, flex.align_items);

            let aligned_caret_x = caret.x + align_offset.x;
            let aligned_caret_y = caret.y + align_offset.y;

            // マージンを設定するとキー移動時にキャレット位置がずれるため削除
            // let margin_x = 0.0; // 左右端のあそび(マージン)

            // 1. 横方向スクロール (X軸)
            if aligned_caret_x < scroll_offset.x {
                scroll_offset.x = aligned_caret_x.max(0.0);
            } else if aligned_caret_x + caret.width > scroll_offset.x + viewport.width {
                scroll_offset.x = (aligned_caret_x + caret.width - viewport.width).max(0.0);
            }

            // 2. 縦方向スクロール (Y軸 - マルチラインのみ)
            if is_multiline {
                if aligned_caret_y < scroll_offset.y {
                    scroll_offset.y = aligned_caret_y.max(0.0);
                } else if aligned_caret_y + caret.height > scroll_offset.y + viewport.height {
                    scroll_offset.y = (aligned_caret_y + caret.height - viewport.height).max(0.0);
                }
            } else {
                scroll_offset.y = 0.0;
            }

            ScrollStore::scroll_to(
                id,
                scroll_offset.x,
                scroll_offset.y,
                win_last_size,
                topo_active_masks,
                topo_parents,
                lay_dirty_entities,
                lay_taffy_tree,
                bar_styles,
                lay_taffy_nodes,
                lay_resolved_basic,
                sc_offsets,
                out_rects,
                sc_sizes,
                debug,
            );

            contents.needs_scroll_to_caret = false;
        }

        // IMM32 による IME 変換候補ウィンドウの位置同期を自動実行
        SystemStore::sync_imm_window_position(
            &resolved_geom,
            win_scale_factor,
            caret,
            caret_offset,
            scroll_offset,
        );
    }

    #[inline]
    pub(crate) fn ime_caret_info(
        id: EntityId,
        sys_text_engine: &mut TextEngine,
        sys_text_buffers: &TextBufferSparse,
        cont_text_contents: &mut TextContentsSparse,
        cont_input_contents: &mut InputContentsSparse,
        cont_text_spans: &TextSpansSparse,
        lay_resolved_basic: &ResolvedBasicSecondary,
        lay_resolved_flex: &ResolvedFlexSecondary,
        rnd_visual: &mut VisualPropertiesSecondary,
        rnd_base_visual: &BaseVisualPropertiesSecondary,
        edit_selections: &mut TextSelectionsSparse,
        out_rects: &RectsSecondary,
        sc_offsets: &ScrollOffsetsSecondary,
        debug: &mut DebugStore,
    ) -> Option<(LayoutRect, f32, bool)> {
        let contents = cont_input_contents.find_mut(id)?;
        // 入力エンジン側の最新カーソル位置を描画SoA側に同期
        edit_selections.insert(id, contents.selected_range.clone());

        let text_val = contents.to_michiu();

        // IME未確定文字列が入力されている際、numeric_only が有効であれば数値を事前にフィルタリング
        // is_password が有効であればマスク処理を適用した中間文字列を生成
        let mut filtered_comp_text = if let Some(ref ime) = contents.ime_state
            && !ime.composition_text.is_empty()
        {
            if contents.numeric_only {
                let filtered: String = ime
                    .composition_text
                    .chars()
                    .filter(|&c| c.is_numeric() || c == '.' || c == '-')
                    .collect();
                MichiuString::from(filtered)
            } else {
                ime.composition_text.clone()
            }
        } else {
            MichiuString::default()
        };

        // 文字数制限(max_length)による未確定文字列の事前切り詰め
        if let Some(max) = contents.max_length
            && !filtered_comp_text.is_empty()
        {
            filtered_comp_text = TextEditStore::truncate_unconfirmed_text(
                &text_val,
                contents,
                max,
                filtered_comp_text,
            );
        }

        // 未確定テキストのマスク
        if !filtered_comp_text.is_empty() {
            filtered_comp_text = contents.mask_if_password(&filtered_comp_text);
        }

        // 確定済みテキストのマスク
        let text_val_for_display = contents.mask_if_password(&text_val);

        // 描画表示用テキストの生成
        // is_password が true の場合、未確定中であっても
        // すでに確定されている文字列部分が一時的に生テキストとして露出してしまわないよう
        // マスクを維持した一時文字列を生成してベースとして使用
        let display_text = if !filtered_comp_text.is_empty() {
            // 未確定文字がある場合:[マスク済み確定テキスト] + [マスク済み未確定文字]
            text_val_for_display.inserted(contents.selected_range.start, &filtered_comp_text)
        } else if text_val.is_empty() {
            // 文字列が完全に空の場合はプレースホルダー
            contents
                .placeholder
                .as_ref()
                .map(std::string::ToString::to_string)
                .unwrap_or_default()
                .into()
        } else {
            text_val_for_display.to_string().into()
        };

        cont_text_contents.insert(id, display_text.clone());

        let auto_wrap = rnd_visual.auto_wrap(id);
        let resolved_geom =
            ResolvedGeometry::resolved(id, sc_offsets, lay_resolved_basic, out_rects, debug);
        let max_width_opt = resolved_geom.calc_max_width(auto_wrap);

        let buffer =
            SystemStore::get_or_create_text_buffer(id, max_width_opt, sys_text_buffers, || {
                let text = cont_text_contents.at(id);
                let font = rnd_visual.font(id);
                let spans = cont_text_spans.span(id);
                let flex = lay_resolved_flex.find_or(id, &DEFAULT_FLEX, debug);
                sys_text_engine.create_buffer(
                    text,
                    &font,
                    flex.text_align,
                    max_width_opt,
                    auto_wrap,
                    spans,
                )
            });

        let text_size = TextEngine::get_layout_size(&buffer);
        contents.last_layout = Some(LayoutRect::new(0.0, 0.0, text_size.width, text_size.height));

        let composition_offset = if let Some(ref ime) = contents.ime_state
            && !ime.composition_text.is_empty()
        {
            // 組成文字全体の文字数をオフセットとして適用
            ime.composition_text.byte_len()
        } else {
            ByteIndex(0)
        };

        // ドラッグの方向を判定しマウス位置にキャレットを固定
        let current_caret_relative = if contents.selection_reversed {
            contents.selected_range.start // 逆方向(左ドラッグ)時は左端がマウス位置
        } else {
            contents.selected_range.end // 順方向(右ドラッグ)時は右端がマウス位置
        };

        // キャレット位(caret_index)の計算
        let caret_index = if contents.is_password {
            let mask = contents.mask_text.as_deref().unwrap_or("●");

            let base_chars = text_val.to_char_index(current_caret_relative);
            let comp_chars = contents
                .ime_state
                .as_ref()
                .map_or(CharIndex(0), |ime| ime.composition_text.char_count());

            let total_chars = base_chars.0 + comp_chars.0;
            ByteIndex(total_chars * mask.len())
        } else {
            current_caret_relative + composition_offset
        };

        // プレースホルダーに干渉されない純粋なキャレット位置を算出
        let (cx_offset, cy_offset, ch_height) =
            TextEngine::get_caret_position(&buffer, caret_index);

        contents.measured_caret = LayoutPoint::new(cx_offset, cy_offset);
        contents.caret_line_height = ch_height;

        // 行情報の計算
        let (curr_line, _tot_lines) = display_text.line_indices(caret_index);
        contents.current_line_index = curr_line;

        // 最終表示用テキストを Context 側に反映
        cont_text_contents.insert(id, display_text);

        let visual = rnd_visual.find_mut(id)?;
        let is_ime_active = contents
            .ime_state
            .as_ref()
            .is_some_and(|ime| !ime.composition_text.is_empty());

        if text_val.is_empty() && !is_ime_active {
            // 確定文字列が空で、かつ未確定文字列も存在しない状態のみグレー表示
            visual.text_color = contents.placeholder_color;
        } else {
            let base_color = rnd_base_visual
                .get(id)
                .and_then(|v| v.text_color)
                .unwrap_or(Color::WHITE);
            visual.text_color = Some(base_color);
        }

        Some((
            LayoutRect {
                x: cx_offset,
                y: cy_offset,
                width: contents.caret_width.unwrap_or(contents.default_caret_width),
                height: ch_height,
            },
            contents.caret_offset,
            contents.is_multiline,
        ))
    }
}

impl Context {
    #[inline]
    pub(crate) fn apply_input_update(&mut self, id: EntityId, op: InputOp) {
        TextEditStore::apply_input_update(
            id,
            op,
            self.window.win_scale_factor,
            self.window.win_last_size,
            &mut self.system.sys_text_engine,
            &self.system.sys_text_buffers,
            &mut self.contents.cont_text_contents,
            &mut self.contents.cont_input_contents,
            &self.contents.cont_text_spans,
            &mut self.topology.topo_active_masks,
            &self.topology.topo_parents,
            &mut self.layouts.lay_dirty_entities,
            &mut self.layouts.lay_taffy_tree,
            &mut self.layouts.scrollbar.bar_styles,
            &self.layouts.lay_taffy_nodes,
            &self.layouts.lay_resolved_basic,
            &self.layouts.lay_resolved_flex,
            &self.layouts.lay_resolved_grid,
            &mut self.renders.rnd_dirty_entities,
            &mut self.renders.rnd_visual,
            &self.renders.rnd_base_visual,
            &mut self.states.scroll.sc_offsets,
            &mut self.states.edit.edit_selections,
            &mut self.states.edit.edit_selected_rects,
            &self.outputs.out_rects,
            &self.states.scroll.sc_sizes,
            &mut self.debug,
        );
    }
}