Skip to main content

strata/runtime/
selection.rs

1//! Text input layout synchronization, caret offset calculation, and caret rendering.
2
3use super::*;
4
5impl AppRuntime {
6    /// Resets the caret blink cycle so the insertion caret is immediately solid and visible.
7    #[inline]
8    pub fn reset_caret_blink(&mut self) {
9        self.caret_blink_epoch = std::time::Instant::now();
10        self.last_caret_blink_state = true;
11    }
12
13    /// Polls caret blink cycle and returns true if blink state toggled (requiring a redraw).
14    pub fn poll_caret_blink(&mut self) -> bool {
15        if self.active_focus.is_none() {
16            return false;
17        }
18        let elapsed_ms = self.caret_blink_epoch.elapsed().as_millis();
19        let is_blink_on = (elapsed_ms / 530).is_multiple_of(2);
20        if is_blink_on != self.last_caret_blink_state {
21            self.last_caret_blink_state = is_blink_on;
22            true
23        } else {
24            false
25        }
26    }
27
28    /// Synchronizes the active focused text input's live buffer and styling into the layout tree.
29    pub fn sync_active_input_layout(&mut self) {
30        let Some(ref active) = self.active_focus else {
31            return;
32        };
33        let target_idx = active.input_index;
34        let target_id = active.input_id.clone();
35        let target_entity_id = active.entity_id;
36        let mut counter = 0;
37        let text_val = active.state.text.get();
38
39        let layout_by_entity = if let Some(eid) = target_entity_id {
40            self.layout_root.find_by_entity_id_mut(eid)
41        } else {
42            None
43        };
44        let layout_match = match layout_by_entity {
45            Some(l) => Some(l),
46            None => Self::find_input_layout_mut(
47                &self.root_blueprint,
48                &mut self.layout_root,
49                target_idx,
50                target_id.as_deref(),
51                &mut counter,
52            ),
53        };
54
55        if let Some(layout) = layout_match {
56            let is_mono = strata_layout::is_monospace_family(layout.style.font_family);
57            if !text_val.is_empty() {
58                layout.text = Some(text_val.clone());
59                if let Some(c) = layout.style.caret_color {
60                    layout.style.color = c;
61                }
62                let (tw, th) = strata_layout::text::measure_text_bounds_with_family(
63                    &text_val,
64                    layout.style.font_size,
65                    layout.style.line_height,
66                    None,
67                    is_mono,
68                    layout.style.font_family,
69                );
70                layout.geometry.content_box.width = tw.max(layout.geometry.content_box.width);
71                layout.geometry.content_box.height = th.max(layout.geometry.content_box.height);
72            } else {
73                let mut ph = None;
74                let mut bp_counter = 0;
75                let bp_match = if let Some(eid) = target_entity_id {
76                    self.root_blueprint.find_by_entity_id(eid)
77                } else {
78                    None
79                };
80                let bp_match = bp_match.or_else(|| {
81                    Self::find_input_blueprint(
82                        &self.root_blueprint,
83                        target_idx,
84                        target_id.as_deref(),
85                        &mut bp_counter,
86                    )
87                });
88                if let Some(bp) = bp_match {
89                    if let NodeBlueprint::Element { attributes, .. } = bp {
90                        for attr in attributes {
91                            if let strata_dom::Attribute::Property { key, value } = attr {
92                                if key == "placeholder" && !value.is_empty() {
93                                    ph = Some(value.clone());
94                                }
95                            }
96                        }
97                    }
98                }
99                if let Some(ph_str) = ph {
100                    layout.text = Some(ph_str);
101                    layout.style.color = strata_style::types::Color::new(140, 145, 155, 255);
102                } else {
103                    layout.text = Some(String::new());
104                }
105            }
106        }
107
108        self.update_gtk_ime_location();
109    }
110
111    /// Calculates the exact character index from an x offset within an input using active font metrics and character advances.
112    pub fn calculate_exact_char_index_at_offset(
113        text: &str,
114        rel_x: f32,
115        font_size: f32,
116        line_height: f32,
117        is_mono: bool,
118        font_family: strata_primitives::AtomId,
119    ) -> usize {
120        if rel_x <= 0.0 || text.is_empty() {
121            return 0;
122        }
123        let chars: Vec<char> = text.chars().collect();
124        let total = chars.len();
125
126        let (full_w, _) = strata_layout::text::measure_text_bounds_with_family(
127            text,
128            font_size,
129            line_height,
130            None,
131            is_mono,
132            font_family,
133        );
134        if rel_x >= full_w {
135            return total;
136        }
137
138        let mut prev_w = 0.0f32;
139        for i in 1..=total {
140            let prefix: String = chars[..i].iter().collect();
141            let (w, _) = strata_layout::text::measure_text_bounds_with_family(
142                &prefix,
143                font_size,
144                line_height,
145                None,
146                is_mono,
147                font_family,
148            );
149            let mid = (prev_w + w) / 2.0;
150            if rel_x < mid {
151                return i - 1;
152            } else if rel_x <= w {
153                return i;
154            }
155            prev_w = w;
156        }
157        total
158    }
159
160    /// Renders the visible insertion caret cursor and selection highlight for the currently focused text input.
161    pub fn render_active_input_caret(&mut self) {
162        let Some(ref active) = self.active_focus else {
163            return;
164        };
165
166        let mut current_idx = 0;
167        let target_idx = active.input_index;
168        let target_id = active.input_id.as_deref();
169
170        let layout_by_entity = if let Some(eid) = active.entity_id {
171            self.layout_root.find_by_entity_id(eid)
172        } else {
173            None
174        };
175        let Some(layout) = layout_by_entity.or_else(|| {
176            Self::find_input_layout(
177                &self.root_blueprint,
178                &self.layout_root,
179                target_idx,
180                target_id,
181                &mut current_idx,
182            )
183        }) else {
184            return;
185        };
186
187        let content_box = layout.geometry.content_box;
188        if content_box.width <= 0.0 || content_box.height <= 0.0 {
189            return;
190        }
191
192        let font_size = layout.style.font_size;
193        let line_height = layout.style.line_height;
194        let is_mono = strata_layout::is_monospace_family(layout.style.font_family);
195        let font_family = layout.style.font_family;
196        let text_color = layout.style.color;
197        let mut caret_color = layout.style.caret_color.unwrap_or(text_color);
198        if caret_color.a == 0 {
199            caret_color = strata_style::types::Color::new(236, 233, 225, 255);
200        }
201        let text = active.state.text.get();
202        let total_chars = text.chars().count();
203        let cursor_idx = active.state.cursor_index.get().min(total_chars);
204
205        // Alignment offset for text-align: center / right
206        let align_offset = match layout.style.text_align {
207            strata_style::types::TextAlign::Center => {
208                let (tw, _) = strata_layout::text::measure_text_bounds_with_family(
209                    &text,
210                    font_size,
211                    line_height,
212                    None,
213                    is_mono,
214                    font_family,
215                );
216                ((content_box.width - tw) / 2.0).max(0.0)
217            }
218            strata_style::types::TextAlign::Right => {
219                let (tw, _) = strata_layout::text::measure_text_bounds_with_family(
220                    &text,
221                    font_size,
222                    line_height,
223                    None,
224                    is_mono,
225                    font_family,
226                );
227                (content_box.width - tw).max(0.0)
228            }
229            _ => 0.0,
230        };
231
232        let caret_w = 2.0f32;
233        let caret_h = (font_size * 1.2).min(content_box.height).max(14.0);
234        let caret_y = content_box.y + ((content_box.height - caret_h) / 2.0).max(0.0);
235
236        // 1. Selection range highlight (CSS ::selection)
237        if let Some((start, end)) = active.state.selection_range() {
238            let start_clamped = start.min(total_chars);
239            let end_clamped = end.min(total_chars);
240            if start_clamped < end_clamped {
241                let start_prefix: String = text.chars().take(start_clamped).collect();
242                let (start_w, _) = strata_layout::text::measure_text_bounds_with_family(
243                    &start_prefix,
244                    font_size,
245                    line_height,
246                    None,
247                    is_mono,
248                    font_family,
249                );
250                let sel_slice: String = text
251                    .chars()
252                    .skip(start_clamped)
253                    .take(end_clamped - start_clamped)
254                    .collect();
255                let (sel_w, _) = strata_layout::text::measure_text_bounds_with_family(
256                    &sel_slice,
257                    font_size,
258                    line_height,
259                    None,
260                    is_mono,
261                    font_family,
262                );
263
264                let sel_h = (font_size * 1.25).min(content_box.height);
265                let sel_y = content_box.y + ((content_box.height - sel_h) / 2.0).max(0.0);
266                let sel_x = content_box.x + align_offset + start_w;
267
268                self.display_list
269                    .push(strata_render::compositor::DrawCommand::DrawRect {
270                        bounds: strata_layout::Rect::new(sel_x, sel_y, sel_w, sel_h),
271                        color: strata_style::types::Color::rgba(59, 130, 246, 120), // Standard CSS selection blue
272                    });
273            }
274        }
275
276        // 2. Visible Caret Line Cursor (CSS caret-color, blinking, and insertion cursor)
277        let has_sel = active.state.has_selection();
278        let elapsed_ms = self.caret_blink_epoch.elapsed().as_millis();
279        let is_blink_on = (elapsed_ms / 530).is_multiple_of(2);
280
281        if !has_sel && is_blink_on {
282            let prefix: String = text.chars().take(cursor_idx).collect();
283            let (cursor_w, _) = strata_layout::text::measure_text_bounds_with_family(
284                &prefix,
285                font_size,
286                line_height,
287                None,
288                is_mono,
289                font_family,
290            );
291            let caret_x = (content_box.x + align_offset + cursor_w)
292                .min(content_box.x + content_box.width - caret_w);
293
294            self.display_list
295                .push(strata_render::compositor::DrawCommand::DrawRect {
296                    bounds: strata_layout::Rect::new(caret_x, caret_y, caret_w, caret_h),
297                    color: caret_color,
298                });
299        }
300    }
301
302    /// Computes the exact bounding box of the active text caret if an input is currently focused.
303    pub fn active_caret_rect(&self) -> Option<strata_layout::Rect> {
304        let active = self.active_focus.as_ref()?;
305        let mut current_idx = 0;
306        let target_idx = active.input_index;
307        let target_id = active.input_id.as_deref();
308
309        let layout_by_entity = if let Some(eid) = active.entity_id {
310            self.layout_root.find_by_entity_id(eid)
311        } else {
312            None
313        };
314        let layout = layout_by_entity.or_else(|| {
315            Self::find_input_layout(
316                &self.root_blueprint,
317                &self.layout_root,
318                target_idx,
319                target_id,
320                &mut current_idx,
321            )
322        })?;
323
324        let content_box = layout.geometry.content_box;
325        if content_box.width <= 0.0 || content_box.height <= 0.0 {
326            return None;
327        }
328
329        let font_size = layout.style.font_size;
330        let line_height = layout.style.line_height;
331        let is_mono = strata_layout::is_monospace_family(layout.style.font_family);
332        let font_family = layout.style.font_family;
333        let text = active.state.text.get();
334        let total_chars = text.chars().count();
335        let cursor_idx = active.state.cursor_index.get().min(total_chars);
336
337        let align_offset = match layout.style.text_align {
338            strata_style::types::TextAlign::Center => {
339                let (tw, _) = strata_layout::text::measure_text_bounds_with_family(
340                    &text,
341                    font_size,
342                    line_height,
343                    None,
344                    is_mono,
345                    font_family,
346                );
347                ((content_box.width - tw) / 2.0).max(0.0)
348            }
349            strata_style::types::TextAlign::Right => {
350                let (tw, _) = strata_layout::text::measure_text_bounds_with_family(
351                    &text,
352                    font_size,
353                    line_height,
354                    None,
355                    is_mono,
356                    font_family,
357                );
358                (content_box.width - tw).max(0.0)
359            }
360            _ => 0.0,
361        };
362
363        let caret_w = 2.0f32;
364        let caret_h = (font_size * 1.2).min(content_box.height).max(14.0);
365        let caret_y = content_box.y + ((content_box.height - caret_h) / 2.0).max(0.0);
366        let prefix: String = text.chars().take(cursor_idx).collect();
367        let (cursor_w, _) = strata_layout::text::measure_text_bounds_with_family(
368            &prefix,
369            font_size,
370            line_height,
371            None,
372            is_mono,
373            font_family,
374        );
375        let caret_x = (content_box.x + align_offset + cursor_w)
376            .min(content_box.x + content_box.width - caret_w);
377
378        Some(strata_layout::Rect::new(caret_x, caret_y, caret_w, caret_h))
379    }
380
381    /// Synchronizes the IME candidate window location with the active caret position.
382    pub fn sync_ime_cursor_location<W: strata_platform::PlatformWindow>(&self, window: &mut W) {
383        if let Some(rect) = self.active_caret_rect() {
384            window.set_ime_cursor_location(
385                rect.x.round() as i32,
386                rect.y.round() as i32,
387                rect.width.round() as i32,
388                rect.height.round() as i32,
389            );
390            if let Some(ref active) = self.active_focus {
391                window.set_ime_surrounding_text(
392                    &active.state.text.get(),
393                    active.state.cursor_index.get() as i32,
394                );
395            }
396        } else {
397            window.reset_ime();
398        }
399    }
400
401    /// Directly updates GTK IME context with current caret location if running on Linux GTK.
402    pub fn update_gtk_ime_location(&self) {
403        #[cfg(target_os = "linux")]
404        {
405            if let Some(rect) = self.active_caret_rect() {
406                strata_platform::gtk_set_ime_cursor_location(
407                    rect.x.round() as i32,
408                    rect.y.round() as i32,
409                    rect.width.round() as i32,
410                    rect.height.round() as i32,
411                );
412                if let Some(ref active) = self.active_focus {
413                    strata_platform::gtk_set_ime_surrounding_text(
414                        &active.state.text.get(),
415                        active.state.cursor_index.get() as i32,
416                    );
417                }
418            } else {
419                strata_platform::gtk_reset_ime();
420            }
421        }
422    }
423}