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