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