nativeview-engine 0.1.0-rc.1

Framework-agnostic scene engine traits, hot-reload cdylib loader, and Frame-0 snapshot codecs.
Documentation
//! Single-line HarfBuzz + Unicode BiDi text layout, grapheme-safe visual hit-testing,
//! logical-to-visual caret X mapping, visual arrow navigation, and disjoint multi-run
//! selection geometry powered by `cosmic-text`.






use crate::editing::grapheme::{
    clamp_grapheme_boundary, grapheme_boundaries, next_grapheme_boundary, prev_grapheme_boundary,
};

/// One UAX #29 extended grapheme cluster positioned in visual left-to-right line coordinates.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct VisualGraphemeCluster {
    /// Logical UTF-8 start byte offset in the source string (always a grapheme boundary).
    pub byte_start: usize,
    /// Logical UTF-8 end byte offset in the source string (always a grapheme boundary).
    pub byte_end: usize,
    /// Visual left edge in logical pixels relative to line origin.
    pub x_left: f32,
    /// Visual right edge in logical pixels relative to line origin.
    pub x_right: f32,
    /// `true` when this cluster belongs to an odd BiDi embedding level (RTL run).
    pub is_rtl: bool,
}

/// Shaped single-line BiDi layout containing visual left-to-right grapheme cluster geometry.
#[derive(Debug, Clone, PartialEq)]
pub struct ShapedLineLayout {
    /// `true` when the resolved Unicode BiDi paragraph direction is RTL.
    pub rtl: bool,
    /// Total visual advance width of the line in logical pixels (including trailing spaces).
    pub line_width: f32,
    /// Grapheme clusters ordered left-to-right by visual X coordinate.
    pub clusters: Vec<VisualGraphemeCluster>,
}

impl ShapedLineLayout {
    /// Returns `true` if the paragraph or any shaped cluster is RTL.
    #[inline]
    pub fn has_rtl(&self) -> bool {
        self.rtl || self.clusters.iter().any(|c| c.is_rtl)
    }

    /// Maps a logical UTF-8 byte offset (clamped to a UAX #29 grapheme boundary) to its visual
    /// caret X offset in logical pixels relative to line origin.
    ///
    /// At LTR/RTL run boundaries, paragraph-direction-matching clusters take precedence so caret
    /// motion remains monotonic within every run.
    pub fn caret_x_at(&self, text: &str, byte_index: usize) -> f32 {
        if text.is_empty() || self.clusters.is_empty() {
            return 0.0;
        }
        let idx = clamp_grapheme_boundary(text, byte_index);

        let mut start_match: Option<&VisualGraphemeCluster> = None;
        let mut end_match: Option<&VisualGraphemeCluster> = None;
        for c in &self.clusters {
            if c.byte_start == idx && start_match.is_none() {
                start_match = Some(c);
            }
            if c.byte_end == idx && end_match.is_none() {
                end_match = Some(c);
            }
        }

        let leading_edge = |c: &VisualGraphemeCluster| if c.is_rtl { c.x_right } else { c.x_left };
        let trailing_edge = |c: &VisualGraphemeCluster| if c.is_rtl { c.x_left } else { c.x_right };

        match (end_match, start_match) {
            (Some(end_c), Some(start_c)) => {
                if end_c.is_rtl == self.rtl && start_c.is_rtl != self.rtl {
                    trailing_edge(end_c)
                } else if start_c.is_rtl == self.rtl {
                    leading_edge(start_c)
                } else {
                    trailing_edge(end_c)
                }
            }
            (None, Some(start_c)) => leading_edge(start_c),
            (Some(end_c), None) => trailing_edge(end_c),
            (None, None) => {
                if idx == 0 {
                    if self.rtl { self.line_width } else { 0.0 }
                } else if self.rtl {
                    0.0
                } else {
                    self.line_width
                }
            }
        }
    }

    /// Hit-tests a visual `local_x` (logical pixels from line origin) into the closest valid
    /// UAX #29 logical grapheme byte boundary.
    pub fn hit_test_x(&self, text: &str, local_x: f32) -> usize {
        if text.is_empty() || !local_x.is_finite() || self.clusters.is_empty() {
            return 0;
        }
        let first = &self.clusters[0];
        if local_x <= first.x_left {
            return if first.is_rtl {
                first.byte_end
            } else {
                first.byte_start
            };
        }
        let last = &self.clusters[self.clusters.len() - 1];
        if local_x >= self.line_width.max(last.x_right) {
            return if last.is_rtl {
                last.byte_start
            } else {
                last.byte_end
            };
        }

        let mut best_cluster = first;
        let mut best_dist = f32::INFINITY;
        for c in &self.clusters {
            if local_x >= c.x_left && local_x <= c.x_right {
                best_cluster = c;
                break;
            }
            let dist = if local_x < c.x_left {
                c.x_left - local_x
            } else {
                local_x - c.x_right
            };
            if dist < best_dist {
                best_dist = dist;
                best_cluster = c;
            }
        }

        let mid = (best_cluster.x_left + best_cluster.x_right) * 0.5;
        let chosen = if best_cluster.is_rtl {
            if local_x < mid {
                best_cluster.byte_end
            } else {
                best_cluster.byte_start
            }
        } else if local_x <= mid {
            best_cluster.byte_start
        } else {
            best_cluster.byte_end
        };
        clamp_grapheme_boundary(text, chosen)
    }

    /// Computes visual `(x_left, width)` selection spans for logical range `start..end`.
    ///
    /// Pure LTR/RTL selections produce one contiguous span; mixed BiDi selections that cross
    /// an LTR/RTL reversal produce disjoint visual spans ordered left-to-right.
    pub fn selection_spans_for_range(
        &self,
        text: &str,
        start: usize,
        end: usize,
    ) -> Vec<(f32, f32)> {
        if text.is_empty() || self.clusters.is_empty() {
            return Vec::new();
        }
        let lo = clamp_grapheme_boundary(text, start.min(end));
        let hi = clamp_grapheme_boundary(text, start.max(end));
        if lo >= hi {
            return Vec::new();
        }

        let mut spans: Vec<(f32, f32)> = Vec::new();
        let mut active: Option<(f32, f32)> = None;

        for c in &self.clusters {
            let selected = c.byte_end > lo && c.byte_start < hi;
            if selected {
                active = Some(match active {
                    Some((min_x, max_x)) if c.x_left <= max_x + 0.5 => {
                        (min_x.min(c.x_left), max_x.max(c.x_right))
                    }
                    Some((min_x, max_x)) => {
                        let w = max_x - min_x;
                        if w > 0.0 {
                            spans.push((min_x, w));
                        }
                        (c.x_left, c.x_right)
                    }
                    None => (c.x_left, c.x_right),
                });
            } else if let Some((min_x, max_x)) = active.take() {
                let w = max_x - min_x;
                if w > 0.0 {
                    spans.push((min_x, w));
                }
            }
        }

        if let Some((min_x, max_x)) = active {
            let w = max_x - min_x;
            if w > 0.0 {
                spans.push((min_x, w));
            }
        }

        spans
    }

    /// Steps the caret visually left (`delta < 0`) or right (`delta > 0`) by one grapheme stop
    /// across mixed LTR/RTL runs without ever landing mid-UTF-8 or mid-grapheme.
    pub fn move_caret_visual(&self, text: &str, caret: usize, delta: i32) -> usize {
        let idx = clamp_grapheme_boundary(text, caret);
        if delta == 0 || text.is_empty() {
            return idx;
        }
        if !self.has_rtl() {
            return if delta < 0 {
                prev_grapheme_boundary(text, idx)
            } else {
                next_grapheme_boundary(text, idx)
            };
        }

        let mut stops: Vec<(f32, usize)> = grapheme_boundaries(text)
            .into_iter()
            .map(|b| (self.caret_x_at(text, b), b))
            .collect();
        stops.sort_by(|a, b| a.0.total_cmp(&b.0).then_with(|| a.1.cmp(&b.1)));

        let Some(pos) = stops.iter().position(|&(_, b)| b == idx) else {
            return idx;
        };
        let next_pos = if delta < 0 {
            pos.saturating_sub(1)
        } else {
            (pos + 1).min(stops.len() - 1)
        };
        stops[next_pos].1
    }
}