fix(mobile): use grapheme boundaries in field hit tests

This commit is contained in:
DarkSky committed 2026-12-05 05:52:18 +09:00
1 parent 720873989d
commit b4548df803
8 files changed
+707 -296

No files matched your search

+1
View File
@@ -141,6 +141,7 @@ dependencies = [
"ui",
"ui-kit",
"ui-tokens",
"unicode-segmentation",
]
[[package]]
+3 -1
View File
@@ -17,7 +17,9 @@
A row without a backing service shows a read-only value (the workspace sync status, where the workspace is stored) instead of a switch that changes nothing.
- The `Search` query and the `WorkspaceDrawer` filter take text through the one `EntityInputHandler` of `MobileShellView` and the shared `state::TextFieldMut` edit rules.
A line longer than its field scrolls (`state::FieldScroll`) only as far as it must to keep the caret, or the end of the IME composition, in view.
The renderer, the scroll, and the IME rects and touch offsets of the input handler all read one shaped layout of the line (`views::field_text::FieldLine`), never an estimated character width, and place it in the field with one transform: a line that fits sits at the start edge of the locale, a longer one scrolls, and its glyphs always run left to right in text order.
One `ShapedLine` for the whole field preserves bidirectional clusters and joining glyphs.
Painting, scroll, IME bounds, and touch offsets use this layout and the same transform.
The line sits at the start edge of the locale when it fits and scrolls when it is wider than the field.
- The bottom TabBar shows on the four tab routes only while the software keyboard is down (`MobileRoute::shows_tabbar`), as `0.27.5` `AppTabs` hides itself while `VirtualKeyboardService.visible$` is true. The accessibility tree follows the same rule.
- On the `Page` route the embedded editor in Page mode owns the bottom edge: the shell pads no bottom safe area or keyboard inset, and passes its resolved keyboard height to the editor (`set_host_ime_bottom`), so the `KeyboardToolbar` sits directly on the keyboard. In Edgeless mode the shell keeps the bottom padding, because the canvas places its controls inside the bounds it gets.
An overlay sheet over the page (all sheets except `WorkspaceDrawer`) moves the focus from the editor to the shell, so the keyboard goes down.
+1
View File
@@ -29,6 +29,7 @@ serde_json.workspace = true
ui = { path = "../../ui/ui" }
ui-kit = { path = "../../ui/kit" }
ui-tokens = { path = "../../ui/tokens" }
unicode-segmentation.workspace = true
[target.'cfg(not(target_family = "wasm"))'.dependencies]
image.workspace = true
+2 -3
View File
@@ -529,9 +529,8 @@ fn render_filter_field(
let entity = cx.entity();
let handle = text_focus.clone();
field = field
.on_click(cx.listener(|this, _, window, cx| {
window.focus(&this.search_focus, cx);
cx.notify();
.on_click(cx.listener(|this, event, window, cx| {
this.click_field(event, window, cx);
}))
.child(
canvas(
+335 -197
View File
@@ -1,27 +1,21 @@
//! Text line of a single-line field (`Search` query, `WorkspaceDrawer` filter): the placeholder,
//! the IME composition underline, and while focused the caret at the active end of the
//! selection with the selected text highlighted. A line longer than the field scrolls toward
//! its end so that the caret, or the end of the composition, stays in view.
//!
//! [`FieldLine`] lays the line out once for the renderer, the scroll, and the platform input
//! handler, and places it in the field with one transform ([`FieldLine::inset`]), so the caret
//! that shows, the IME candidate bounds, and the index under a touch agree glyph for glyph in
//! LTR and RTL locales.
//! Layout, paint, and hit tests for the Search query and WorkspaceDrawer filter.
use std::{ops::Range, sync::Arc};
use std::ops::Range;
use ui::{
Context, Direction, Font, Hsla, InteractiveElement, IntoElement, LineLayout, ParentElement,
Styled, TextRun, Window, canvas, div, px,
BaseDirection, Bounds, CaretAffinity, Context, Direction, Font, Hsla, InteractiveElement,
ParentElement, Pixels, ShapedLine, Styled, TextAlign, TextRun, UnderlineStyle, Window, canvas,
div, fill, point, px, size,
};
use ui_kit::LogicalStyled;
use ui_tokens::FONT_SANS;
use unicode_segmentation::UnicodeSegmentation;
use crate::state::{FieldScroll, MobileAppState, TextFieldMut};
use super::{MobileFlexExt, MobilePalette, MobileShellView, row_dir, utf16_to_byte};
const CARET_WIDTH: f32 = 2.0;
pub(super) const CARET_HEIGHT: f32 = 18.0;
/// The text state of one field line.
#[derive(Clone)]
@@ -60,198 +54,341 @@ pub(super) struct FieldText<'a> {
pub scroll_slot: fn(&mut MobileAppState) -> &mut FieldScroll,
}
/// One run of a laid out line: its byte range, its start in the line, and its glyphs.
struct Run {
/// One editable unit inside a shaped cluster, in visual coordinates.
struct SubCluster {
bytes: Range<usize>,
underline: bool,
highlight: bool,
x: f32,
layout: Option<Arc<LineLayout>>,
x: Range<Pixels>,
rtl: bool,
}
impl Run {
fn width(&self) -> f32 {
self.layout.as_ref().map_or(0.0, |l| f32::from(l.width))
impl SubCluster {
fn leading_x(&self) -> Pixels {
if self.rtl { self.x.end } else { self.x.start }
}
fn trailing_x(&self) -> Pixels {
if self.rtl { self.x.start } else { self.x.end }
}
fn byte_at(&self, x: Pixels) -> usize {
let left = x <= self.x.start || x < (self.x.start + self.x.end) / 2.0;
if left == self.rtl {
self.bytes.end
} else {
self.bytes.start
}
}
}
/// A field line laid out as the renderer places it: up to three runs (before, inside, and
/// after the selection or composition), each shaped on its own, and the caret between two of
/// them. Positions are in the line's own space, before the scroll.
/// Project shaped glyph clusters onto whole-line grapheme boundaries.
/// Split ligatures that cover multiple graphemes. Join clusters inside one grapheme.
fn visual_subclusters(shaped: &ShapedLine, text: &str) -> Vec<SubCluster> {
let mut starts = Vec::new();
let mut clusters: Vec<SubCluster> = Vec::new();
for run in &shaped.runs {
for glyph in &run.glyphs {
let start = glyph.index;
let x = glyph.position.x;
let rtl = run.is_rtl();
if let Some(last) = clusters.last_mut()
&& last.bytes.start == start
&& last.rtl == rtl
{
last.x.start = last.x.start.min(x);
} else {
starts.push(start);
clusters.push(SubCluster {
bytes: start..start,
x: x..x,
rtl,
});
}
}
}
starts.sort_unstable();
starts.dedup();
clusters.sort_by(|a, b| {
a.x.start
.partial_cmp(&b.x.start)
.unwrap_or(std::cmp::Ordering::Equal)
});
let boundaries: Vec<_> = text
.grapheme_indices(true)
.map(|(byte, _)| byte)
.chain(std::iter::once(shaped.text.len()))
.collect();
let mut units: Vec<Option<SubCluster>> = (1..boundaries.len()).map(|_| None).collect();
for (i, cluster) in clusters.iter().enumerate() {
let start = cluster.bytes.start;
let next = starts.partition_point(|&byte| byte <= start);
let end = starts.get(next).copied().unwrap_or(text.len());
if start >= end {
continue;
}
let first = boundaries
.partition_point(|&byte| byte <= start)
.saturating_sub(1);
let past_last = boundaries.partition_point(|&byte| byte < end);
let covered = &mut units[first..past_last];
let count = covered.len();
let left = cluster.x.start;
let right = clusters
.get(i + 1)
.map_or(shaped.width, |next| next.x.start)
.max(left);
let step = (right - left) / count as f32;
for (logical, slot) in covered.iter_mut().enumerate() {
let visual = if cluster.rtl {
count - 1 - logical
} else {
logical
};
let x_start = left + step * visual as f32;
let x_end = if visual + 1 == count {
right
} else {
left + step * (visual + 1) as f32
};
let byte = first + logical;
let bytes = boundaries[byte]..boundaries[byte + 1];
if let Some(unit) = slot {
unit.x.start = unit.x.start.min(x_start);
unit.x.end = unit.x.end.max(x_end);
if start <= bytes.start {
unit.rtl = cluster.rtl;
}
} else {
*slot = Some(SubCluster {
bytes,
x: x_start..x_end,
rtl: cluster.rtl,
});
}
}
}
let mut subclusters: Vec<_> = units.into_iter().flatten().collect();
subclusters.sort_by(|a, b| {
a.x.start
.partial_cmp(&b.x.start)
.unwrap_or(std::cmp::Ordering::Equal)
});
subclusters
}
/// The glyphs and decorations of the entire line, before alignment and scroll.
pub(super) struct FieldLine {
runs: [Run; 3],
/// Index of the run that the caret precedes, and the start of the caret.
caret: Option<(usize, f32)>,
width: f32,
text: String,
shaped: ShapedLine,
subclusters: Vec<SubCluster>,
selected: Range<usize>,
marked: Option<Range<usize>>,
caret: Option<Pixels>,
}
impl FieldLine {
pub(super) fn layout(line: &LineText<'_>, window: &Window) -> Self {
let text = line.text;
let total = text.encode_utf16().count();
let bytes = |r: &Range<usize>| {
let start = utf16_to_byte(text, r.start.min(total));
start..utf16_to_byte(text, r.end.min(total)).max(start)
pub(super) fn layout(line: &LineText<'_>, color: Hsla, window: &Window) -> Self {
let bytes = |range: &Range<usize>| {
let start = utf16_to_byte(line.text, range.start);
start..utf16_to_byte(line.text, range.end).max(start)
};
let len = text.len();
let (spans, caret_before) = match &line.preedit {
Some(pre) => {
let marked = bytes(pre);
(
[
(0..marked.start, false, false),
(marked.clone(), true, false),
(marked.end..len, false, false),
],
None,
)
}
None if line.focused => {
let selected = bytes(&line.selection);
(
[
(0..selected.start, false, false),
(selected.clone(), false, true),
(selected.end..len, false, false),
],
Some(if line.reversed { 1 } else { 2 }),
)
}
None => (
[
(0..len, false, false),
(len..len, false, false),
(len..len, false, false),
],
None,
),
};
let font = Font {
family: FONT_SANS.into(),
..Font::default()
};
let mut x = 0.0;
let mut caret = None;
let mut idx = 0;
let runs = spans.map(|(range, underline, highlight)| {
if caret_before == Some(idx) {
caret = Some((idx, x));
x += CARET_WIDTH;
}
idx += 1;
let run = &text[range.clone()];
let layout = (!run.is_empty()).then(|| {
let style = TextRun {
len: run.len(),
font: font.clone(),
color: Hsla::default(),
background_color: None,
underline: None,
strikethrough: None,
};
window
.text_system()
.layout_line(run, px(line.text_size), &[style], None)
});
let run = Run {
bytes: range,
underline,
highlight,
x,
layout,
let selected = bytes(&line.selection);
let marked = line.preedit.as_ref().map(bytes);
let shaped = if line.text.is_empty() {
ShapedLine::default()
} else {
// Display pasted line breaks as spaces with the same UTF-8 and UTF-16 offsets.
let text = if line.text.contains(['\r', '\n']) {
line.text.replace(['\r', '\n'], " ").into()
} else {
line.text.into()
};
x += run.width();
run
});
Self {
runs,
caret,
width: x,
text: text.to_string(),
let style = TextRun {
len: line.text.len(),
font: Font {
family: FONT_SANS.into(),
..Font::default()
},
color,
background_color: None,
underline: None,
strikethrough: None,
};
window.text_system().shape_line_with_direction(
text,
px(line.text_size),
&[style],
None,
BaseDirection::AutoFirstStrong,
)
};
let subclusters = visual_subclusters(&shaped, line.text);
let mut field = Self {
shaped,
subclusters,
selected,
marked,
caret: None,
};
if line.focused && field.marked.is_none() {
let index = if line.reversed {
field.selected.start
} else {
field.selected.end
};
field.caret = Some(field.caret_x(index, CaretAffinity::Downstream));
} else {
field.selected = 0..0;
}
field
}
/// Start of UTF-16 offset `index` in the line. An offset between two runs is placed at the
/// end of the earlier run, where the caret shows. An empty line places it at the caret.
fn x_for_utf16(&self, index: usize) -> f32 {
let byte = utf16_to_byte(&self.text, index);
self.runs
fn caret_x(&self, byte: usize, affinity: CaretAffinity) -> Pixels {
if affinity == CaretAffinity::Upstream
&& let Some(unit) = self
.subclusters
.iter()
.find(|unit| unit.bytes.start < byte && byte <= unit.bytes.end)
{
return unit.trailing_x();
}
if let Some(unit) = self
.subclusters
.iter()
.find(|run| byte <= run.bytes.end && !run.bytes.is_empty())
.map_or(self.caret.map_or(0.0, |(_, x)| x), |run| {
let local = byte.saturating_sub(run.bytes.start);
run.x
+ run
.layout
.as_ref()
.map_or(0.0, |l| f32::from(l.x_for_index(local)))
})
}
/// The UTF-16 offset closest to `x` in the line.
fn utf16_for_x(&self, x: f32) -> usize {
let byte = self
.runs
.find(|unit| unit.bytes.contains(&byte))
{
return unit.leading_x();
}
self.subclusters
.iter()
.filter(|run| !run.bytes.is_empty())
.find(|run| x < run.x + run.width())
.map_or(self.text.len(), |run| {
let local = run
.layout
.as_ref()
.map_or(0, |l| l.closest_index_for_x(px(x - run.x)));
run.bytes.start + local
});
self.text[..byte.min(self.text.len())]
.encode_utf16()
.count()
.find(|unit| unit.bytes.end == self.shaped.text.len())
.map_or(px(0.0), SubCluster::trailing_x)
}
/// The span that must stay in view: the caret when one shows, else the end of the
/// composition, else the start of the text.
fn active_span(&self) -> (f32, f32) {
match self.caret {
Some((_, x)) => (x, x + CARET_WIDTH),
None if self.runs[1].underline => {
let end = self.runs[1].x + self.runs[1].width();
(end, end)
/// Keep disjoint spans in visual order. Join adjacent units in the same direction.
fn selection_spans(&self, bytes: &Range<usize>) -> Vec<Range<Pixels>> {
let mut spans: Vec<Range<Pixels>> = Vec::new();
let mut direction = None;
if bytes.is_empty() {
return spans;
}
for unit in &self.subclusters {
if unit.bytes.start < bytes.end && unit.bytes.end > bytes.start {
if let Some(last) = spans.last_mut()
&& direction == Some(unit.rtl)
{
last.end = unit.x.end;
} else {
spans.push(unit.x.clone());
}
direction = Some(unit.rtl);
} else {
direction = None;
}
None => (0.0, 0.0),
}
spans
}
/// The scroll of the line that keeps its active span in view.
fn width(&self) -> f32 {
f32::from(self.shaped.width) + CARET_WIDTH
}
/// Keep the caret or the composition end in view.
fn offset(&self, scroll: FieldScroll) -> f32 {
let (start, end) = self.active_span();
scroll.revealing(start, end, self.width)
let (start, end) = if let Some(x) = self.caret {
(f32::from(x), f32::from(x) + CARET_WIDTH)
} else if let Some(marked) = &self.marked {
let x = self.caret_x(marked.end, CaretAffinity::Upstream);
let x = f32::from(x) + CARET_WIDTH / 2.0;
(x, x)
} else {
(0.0, 0.0)
};
scroll.revealing(start, end, self.width())
}
/// Start of the line from the left edge of the field. A line that fits sits at the start
/// edge of `dir`; a longer one scrolls by [`Self::offset`]. The glyphs of the line always
/// run left to right in text order.
fn inset(&self, scroll: FieldScroll, dir: Direction) -> f32 {
/// Place the glyph origin at the locale's start edge, with room for the centered caret.
/// Scroll the line when it is wider than the field.
fn glyph_inset(&self, scroll: FieldScroll, dir: Direction) -> f32 {
let align = if dir.is_rtl() {
(scroll.visible_width - self.width).max(0.0)
(scroll.visible_width - self.width()).max(0.0)
} else {
0.0
};
align - self.offset(scroll)
align - self.offset(scroll) + CARET_WIDTH / 2.0
}
/// Window x of UTF-16 offset `index` when the field is at `scroll`.
pub(super) fn screen_x_for_utf16(
/// The window-space extent of a range, or the caret rectangle for an insertion point.
pub(super) fn screen_span(
&self,
index: usize,
range: Range<usize>,
scroll: FieldScroll,
dir: Direction,
) -> f32 {
scroll.origin_x + self.inset(scroll, dir) + self.x_for_utf16(index)
) -> Range<f32> {
let text = self.shaped.text.as_ref();
let start = utf16_to_byte(text, range.start);
let end = utf16_to_byte(text, range.end);
let origin = scroll.origin_x + self.glyph_inset(scroll, dir);
let spans = self.selection_spans(&(start..end));
if let (Some(first), Some(last)) = (spans.first(), spans.last()) {
return origin + f32::from(first.start)..origin + f32::from(last.end);
}
let left =
origin + f32::from(self.caret_x(start, CaretAffinity::Downstream)) - CARET_WIDTH / 2.0;
left..left + CARET_WIDTH
}
/// The UTF-16 offset closest to window x `x` when the field is at `scroll`.
pub(super) fn utf16_for_screen_x(&self, x: f32, scroll: FieldScroll, dir: Direction) -> usize {
self.utf16_for_x(x - scroll.origin_x - self.inset(scroll, dir))
let local_x = px(x - scroll.origin_x - self.glyph_inset(scroll, dir));
let byte = self
.subclusters
.iter()
.find(|unit| local_x <= unit.x.end)
.or_else(|| self.subclusters.last())
.map_or(0, |unit| unit.byte_at(local_x));
self.shaped.text[..byte].encode_utf16().count()
}
fn paint(
&self,
bounds: Bounds<Pixels>,
inset: Pixels,
line_height: Pixels,
palette: MobilePalette,
window: &mut Window,
cx: &mut ui::App,
) {
let origin = point(bounds.left() + inset, bounds.center().y - line_height / 2.0);
let selection_height =
(self.shaped.ascent + self.shaped.descent).max(self.shaped.font_size);
let selection_top = bounds.center().y - selection_height / 2.0;
for span in self.selection_spans(&self.selected) {
let selection = Bounds::new(
point(origin.x + span.start, selection_top),
size(span.end - span.start, selection_height),
);
window.paint_quad(fill(selection, palette.accent_soft));
}
let _ = self
.shaped
.paint(origin, line_height, TextAlign::Left, None, window, cx);
if let Some(marked) = &self.marked {
let style = UnderlineStyle {
color: Some(palette.accent),
thickness: px(1.0),
wavy: false,
};
let y =
(origin.y + self.shaped.ascent + px(1.0)).min(bounds.bottom() - style.thickness);
for span in self.selection_spans(marked) {
window.paint_underline(
point(origin.x + span.start, y),
span.end - span.start,
&style,
);
}
}
}
}
@@ -268,18 +405,15 @@ pub(super) fn field_text(
.id(caret_id.clone())
.snapshot(caret_id.clone(), Some(field.id))
.w(px(CARET_WIDTH))
.h(px(18.0))
.h(px(CARET_HEIGHT))
.flex_shrink(0.0)
.rounded(px(1.0))
.bg(palette.accent)
.into_any_element()
};
let text_size = field.line.text_size;
let laid_out = FieldLine::layout(&field.line, window);
let laid_out = FieldLine::layout(&field.line, palette.text_primary, window);
let offset = laid_out.offset(field.scroll);
let inset = laid_out.inset(field.scroll, dir);
// Keep the offset and the measured line for the next frame and the input handler. A new
// width moves the caret in or out of view, so it draws once more.
// Save the viewport for input and scroll. If its width changes, draw again.
let shell = cx.entity().downgrade();
let slot = field.scroll_slot;
let probe = canvas(
@@ -307,7 +441,6 @@ pub(super) fn field_text(
.inset_0();
if field.line.text.is_empty() {
// The caret of an empty line sits at the start edge of `dir`, where `inset` puts it.
let mut line = row_dir(dir)
.flex_1()
.min_w(px(0.0))
@@ -329,33 +462,38 @@ pub(super) fn field_text(
);
}
let ltr_row = || div().flex().flex_row().items_center().dir_ltr();
let mut content = ltr_row().flex_shrink(0.0).ms(px(inset), Direction::Ltr);
for (idx, run) in laid_out.runs.iter().enumerate() {
if laid_out.caret.is_some_and(|(before, _)| before == idx) {
content = content.child(caret());
}
if run.bytes.is_empty() {
continue;
}
let mut el = div()
.flex_shrink(0.0)
.text_size(px(text_size))
.text_color(palette.text_primary)
.child(field.line.text[run.bytes.clone()].to_string());
if run.underline {
el = el.border_b_1().border_color(palette.accent);
}
if run.highlight {
el = el.bg(palette.accent_soft);
}
content = content.child(el);
}
ltr_row()
let inset = px(laid_out.glyph_inset(field.scroll, dir));
let line_height = window
.text_style()
.line_height
.to_pixels(px(text_size).into(), window.rem_size())
.round();
let height = line_height.max(px(CARET_HEIGHT));
let caret_x = laid_out.caret;
let content = canvas(
|_, _, _| (),
move |bounds, (), window, cx| {
laid_out.paint(bounds, inset, line_height, palette, window, cx);
},
)
.absolute()
.inset_0();
let mut line = div()
.dir_ltr()
.flex_1()
.min_w(px(0.0))
.h(height)
.overflow_hidden()
.relative()
.child(probe)
.child(content)
.child(content);
if let Some(x) = caret_x {
line = line.child(
caret()
.absolute()
.left(inset + x - px(CARET_WIDTH / 2.0))
.top((height - px(CARET_HEIGHT)) / 2.0),
);
}
line
}
+24 -8
View File
@@ -36,7 +36,7 @@ use std::{
use affine_client::{AccessibilityTree, PlatformAccessibility};
use ui::{
App, Bounds, Context, Direction, EntityInputHandler, FocusHandle, Focusable,
App, Bounds, Context, Direction, EntityInputHandler, FocusHandle, Focusable, Hsla,
InteractiveElement, IntoElement, KeyDownEvent, ParentElement, Pixels, Point, Render, Styled,
TextAlign, UTF16Selection, Window, WindowInsets, canvas, div, px, size,
};
@@ -288,6 +288,17 @@ impl MobileShellView {
cx.stop_propagation();
cx.notify();
}
fn click_field(&mut self, event: &ui::ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
if !matches!(event, ui::ClickEvent::Keyboard(_))
&& let Some(index) = self.character_index_for_point(event.position(), window, cx)
&& let Some(mut field) = self.state.active_text_field()
{
field.select(index..index);
}
window.focus(&self.search_focus, cx);
cx.notify();
}
}
impl Focusable for MobileShellView {
@@ -398,15 +409,18 @@ impl EntityInputHandler for MobileShellView {
) -> Option<Bounds<Pixels>> {
let dir = self.state.locale().direction();
let field = self.state.active_text_field()?;
let line = field_text::FieldLine::layout(&field_text::LineText::of_input(&field), window);
let start = line.screen_x_for_utf16(range_utf16.start, field.scroll, dir);
let end = line.screen_x_for_utf16(range_utf16.end, field.scroll, dir);
let height = 20.0;
let line = field_text::FieldLine::layout(
&field_text::LineText::of_input(&field),
Hsla::default(),
window,
);
let span = line.screen_span(range_utf16, field.scroll, dir);
let height = field_text::CARET_HEIGHT;
let top = f32::from(element_bounds.origin.y)
+ (f32::from(element_bounds.size.height) - height) / 2.0;
Some(Bounds::new(
Point::new(px(start), px(top)),
size(px((end - start).max(2.0)), px(height)),
Point::new(px(span.start), px(top)),
size(px(span.end - span.start), px(height)),
))
}
@@ -418,7 +432,9 @@ impl EntityInputHandler for MobileShellView {
) -> Option<usize> {
let dir = self.state.locale().direction();
let field = self.state.active_text_field()?;
let line = field_text::FieldLine::layout(&field_text::LineText::of_input(&field), window);
let mut input = field_text::LineText::of_input(&field);
input.focused = self.search_focus.is_focused(window);
let line = field_text::FieldLine::layout(&input, Hsla::default(), window);
Some(line.utf16_for_screen_x(f32::from(point.x), field.scroll, dir))
}
}
+2 -3
View File
@@ -73,9 +73,8 @@ pub(super) fn render_search(
.gap(px(4.0))
.justify_between()
.overflow_hidden()
.on_click(cx.listener(|this, _, window, cx| {
window.focus(&this.search_focus, cx);
cx.notify();
.on_click(cx.listener(|this, event, window, cx| {
this.click_field(event, window, cx);
}))
.child(a11y_bounds_probe(
"mobile.search.input",
@@ -2777,27 +2777,42 @@ fn long_field_text_scrolls_to_keep_the_caret_inside_the_field() {
}
#[test]
fn field_ime_rects_and_touch_offsets_follow_the_shaped_glyphs_in_ltr_and_rtl() {
const QUERY: &str = "Quarterly database planning and synchronization notes";
let len = QUERY.encode_utf16().count();
for locale in [MobileLocale::En, MobileLocale::Ar] {
fn field_ime_rects_and_touch_offsets_follow_shaped_glyphs_in_both_fields() {
const ARABIC: &str = "بحث عربي";
const MIXED: &str = "AFFiNE بحث notes";
const QUERY: &str = "mobile shell breadcrumb architecture sync design note";
assert_eq!(QUERY.len(), 53);
for (locale, drawer) in [
(MobileLocale::En, false),
(MobileLocale::Ar, false),
(MobileLocale::En, true),
(MobileLocale::Ar, true),
] {
let t = TestApp::launch(390, 844, locale);
t.click_id("mobile.home.doc.doc-arch");
t.click_id("mobile.page.drawer_btn");
t.click_id("mobile.drawer.filter_bar");
let (fx, fy, fw, fh) = element_bounds(&t, "mobile.drawer.filter_bar").unwrap();
let field = Bounds::new(point(px(fx), px(fy)), size(px(fw), px(fh)));
let edit = |f: &dyn Fn(
&mut MobileShellView,
&mut ui::Window,
&mut ui::Context<MobileShellView>,
)| {
let field_id = if drawer {
t.click_id("mobile.home.doc.doc-arch");
t.click_id("mobile.page.drawer_btn");
"mobile.drawer.filter_bar"
} else {
t.click_id("mobile.tab.search");
t.click_id("mobile.search.clear_btn");
"mobile.search.input"
};
t.click_id(field_id);
let field_bounds = || {
let (x, y, w, h) = element_bounds(&t, field_id).unwrap();
Bounds::new(point(px(x), px(y)), size(px(w), px(h)))
};
let caret_id = format!("{field_id}.caret");
let context = format!("{locale:?} {field_id}");
let edit = |f: &dyn Fn(&mut MobileShellView, &mut ui::Window, &mut ui::Context<_>)| {
t.app
.update(|cx| t.window_handle.update(cx, |v, window, cx| f(v, window, cx)))
.unwrap();
};
// The first frame measures the line, the next ones settle its scroll.
let settle = || {
// A frame measures the text viewport and schedules a redraw if its width changes.
for _ in 0..3 {
t.headless_win.request_frame();
t.platform.run_until_parked();
@@ -2805,93 +2820,333 @@ fn field_ime_rects_and_touch_offsets_follow_the_shaped_glyphs_in_ltr_and_rtl() {
};
let set_text = |text: &str| {
edit(&|v, window, cx| {
let len = v.text_length_utf16(window, cx).unwrap_or(0);
let len = v.text_length_utf16(window, cx).unwrap();
v.replace_text_in_range(Some(0..len), text, window, cx);
})
});
settle();
};
let rect_x = |offset: usize| {
let rect = |offset| {
let field = field_bounds();
t.app
.update(|cx| {
t.window_handle.update(cx, |v, window, cx| {
let b = v.bounds_for_range(offset..offset, field, window, cx);
f32::from(b.expect("caret rect").origin.x)
v.bounds_for_range(offset..offset, field, window, cx)
.expect("caret rect")
})
})
.unwrap()
};
let touch = |x: f32| {
t.app
.update(|cx| {
t.window_handle.update(cx, |v, window, cx| {
v.character_index_for_point(point(px(x), px(fy + fh / 2.0)), window, cx)
})
})
.unwrap()
};
let caret_x = || {
element_bounds(&t, "mobile.drawer.filter_bar.caret")
.unwrap()
.0
};
// The caret rect is where the caret shows, up to the rounding of the layout to whole
// pixels, and inside the field.
let agrees = |what: &str, rect: f32| {
let shown = caret_x();
let agrees = |rect: Bounds<ui::Pixels>| {
let (x, y, w, h) = element_bounds(&t, &caret_id).unwrap();
for (expected, shown) in [
(rect.left(), x),
(rect.top(), y),
(rect.size.width, w),
(rect.size.height, h),
] {
assert!(
(f32::from(expected) - shown).abs() <= 1.0,
"{context} IME {rect:?}, rendered caret ({x}, {y}, {w}, {h})"
);
}
let field = field_bounds();
assert!(
(rect - shown).abs() <= 1.0 && rect >= fx && rect <= fx + fw,
"{locale:?} {what}: rect {rect}, caret {shown}, field {fx}..{}",
fx + fw
field.contains(&point(px(x), px(y)))
&& field.contains(&point(px(x + w), px(y + h))),
"{context} caret ({x}, {y}, {w}, {h}) in {field:?}"
);
point(px(x + w / 2.0), px(y + h / 2.0))
};
let hit = |position| {
t.app
.update(|cx| {
t.window_handle.update(cx, |v, window, cx| {
v.character_index_for_point(position, window, cx)
})
})
.unwrap()
};
agrees("empty field", rect_x(0));
agrees(rect(0));
// Four narrow and four wide glyphs: the caret after them is where the caret shows, and
// the rects of the line ends hold the shaped width of the glyphs.
let mut widths = Vec::new();
for text in ["iiii", "WWWW"] {
let widths = ["iiii", "WWWW"].map(|text| {
set_text(text);
settle();
let end = rect_x(4);
agrees(text, end);
widths.push(end - rect_x(0));
}
assert!(widths[1] > widths[0] + 20.0, "{locale:?} {widths:?}");
// A line longer than the field, with the caret at its end, inside a word, and early in
// it: a touch at the center of the caret that shows lands on its offset.
set_text(QUERY);
for offset in [len, len - 5, 10] {
edit(&|v, window, cx| v.set_selected_text_range(offset..offset, window, cx));
settle();
let rect = rect_x(offset);
agrees(&format!("offset {offset}"), rect);
assert_eq!(
touch(caret_x() + 1.0),
Some(offset),
"{locale:?} offset {offset}"
);
}
edit(&|v, window, cx| v.set_selected_text_range(len..len, window, cx));
settle();
let end = touch(caret_x() + 1.0).expect("offset");
edit(&|v, window, cx| {
v.set_selected_text_range(end..end, window, cx);
v.replace_text_in_range(None, "!", window, cx);
let end = rect(4);
agrees(end);
f32::from(end.left() - rect(0).left())
});
assert_eq!(
t.read(|v, _| v.state.drawer_filter.clone()),
format!("{QUERY}!"),
"{locale:?}"
);
assert!(widths[1] > widths[0] + 20.0, "{context} {widths:?}");
// Clearing the scrolled line: the rect asked before the next frame is already where
// the caret of the empty field shows.
for (text, offsets, insert) in [
(ARABIC, &[0, 2, 4, 8][..], Some((2, "بح!ث عربي"))),
("لا", &[0, 1, 2], Some((1, "ل!ا"))),
("سلام", &[0, 1, 2, 3, 4], Some((2, "سل!ام"))),
(MIXED, &[0, 2, 9, 16], None),
(
QUERY,
&[QUERY.len(), QUERY.len() - 5, 10, QUERY.len()],
None,
),
] {
set_text(text);
let len = text.encode_utf16().count();
for &offset in offsets {
edit(&|v, window, cx| v.set_selected_text_range(offset..offset, window, cx));
settle();
let position = agrees(rect(offset));
assert_eq!(
hit(position),
Some(offset),
"{context} {text:?} at {offset}"
);
if let Some((target, expected)) = insert
&& offset == target
{
edit(&|v, window, cx| v.set_selected_text_range(len..len, window, cx));
settle();
t.headless_win.simulate_click(position);
edit(&|v, window, cx| {
v.replace_text_in_range(None, "!", window, cx);
let mut adjusted = None;
assert_eq!(
v.text_for_range(0..len + 1, &mut adjusted, window, cx)
.as_deref(),
Some(expected),
"{context}"
);
});
set_text(text);
}
}
if text == "لا" {
let [start, middle, end] = [0, 1, 2].map(|offset| rect(offset).center().x);
assert!(
end < middle && middle < start,
"{context} {start:?} {middle:?} {end:?}"
);
let field = field_bounds();
edit(&|v, window, cx| {
for (range, left, right) in [(0..1, middle, start), (1..2, end, middle)] {
let span = v.bounds_for_range(range, field, window, cx).unwrap();
assert!((span.left() - left).abs() <= px(0.25), "{context} {span:?}");
assert!(
(span.right() - right).abs() <= px(0.25),
"{context} {span:?}"
);
}
});
}
}
// Ask for the empty caret rectangle in the edit that clears a scrolled line.
let field = field_bounds();
let before_frame = t
.app
.update(|cx| {
t.window_handle.update(cx, |v, window, cx| {
v.replace_text_in_range(Some(0..QUERY.len()), "", window, cx);
v.bounds_for_range(0..0, field, window, cx).unwrap()
})
})
.unwrap();
assert_eq!(before_frame.center().y, field.center().y, "{context}");
settle();
set_text("");
let before_frame = rect_x(0);
let empty = rect(0);
assert!(
(before_frame.left() - empty.left()).abs() <= px(1.0),
"{context}"
);
agrees(empty);
// Test the edges of the text viewport, within the icon and clear button.
set_text(ARABIC);
edit(&|v, window, cx| v.set_selected_text_range(4..4, window, cx));
settle();
agrees("cleared field before its frame", before_frame);
agrees("cleared field", rect_x(0));
let scroll = t.read(|v, _| {
if drawer {
v.state.drawer_filter_scroll
} else {
v.state.search_scroll
}
});
for (x, expected) in [
(scroll.origin_x + 0.25, 8),
(scroll.origin_x + scroll.visible_width - 0.25, 0),
] {
let position = point(px(x), field_bounds().center().y);
assert_eq!(hit(position), Some(expected), "{context} x={x}");
t.headless_win.simulate_click(position);
t.app
.update(|cx| {
t.window_handle.update(cx, |v, window, cx| {
let selection = v.selected_text_range(false, window, cx).unwrap();
assert_eq!(selection.range, expected..expected, "{context} x={x}");
})
})
.unwrap();
}
}
}
#[test]
fn drawer_ime_underlines_are_visible_for_ltr_rtl_and_mixed_text() {
for locale in [MobileLocale::En, MobileLocale::Ar] {
let t = TestApp::launch(390, 844, locale);
let field_id = "mobile.drawer.filter_bar";
t.click_id("mobile.home.doc.doc-arch");
t.click_id("mobile.page.drawer_btn");
t.click_id(field_id);
let frame = || {
for _ in 0..3 {
t.headless_win.request_frame();
t.platform.run_until_parked();
}
t.app
.update(|cx| {
t.window_handle
.update(cx, |_, window, _| window.render_to_image().unwrap())
})
.unwrap()
};
for (text, marked, segments) in
[("abcd", 1..3, 1), ("بحث", 0..2, 1), ("ab بحث cd", 1..4, 2)]
{
t.app
.update(|cx| {
t.window_handle.update(cx, |v, window, cx| {
let len = v.text_length_utf16(window, cx).unwrap();
v.replace_text_in_range(Some(0..len), text, window, cx);
})
})
.unwrap();
let plain = frame();
let (x, y, w, h) = element_bounds(&t, "mobile.drawer.filter_bar.caret").unwrap();
let accent = plain.get_pixel((x + w / 2.0) as u32, (y + h / 2.0) as u32);
let start = text.char_indices().nth(marked.start).unwrap().0;
let end = text.char_indices().nth(marked.end).unwrap().0;
t.app
.update(|cx| {
t.window_handle.update(cx, |v, window, cx| {
v.replace_and_mark_text_in_range(
Some(marked.clone()),
&text[start..end],
None,
window,
cx,
);
assert_eq!(v.marked_text_range(window, cx), Some(marked.clone()));
})
})
.unwrap();
let composition = frame();
let (x, y, w, h) = element_bounds(&t, field_id).unwrap();
let mut visible_segments = Vec::new();
let mut previous = None;
for col in x as u32..(x + w) as u32 {
let ink = (y as u32..(y + h) as u32).any(|row| {
composition.get_pixel(col, row) == accent && plain.get_pixel(col, row) != accent
});
if ink {
if previous == Some(col - 1) {
*visible_segments.last_mut().unwrap() += 1;
} else {
visible_segments.push(1);
}
previous = Some(col);
}
}
assert_eq!(
visible_segments.len(),
segments,
"{locale:?} {text:?}: {visible_segments:?}"
);
assert!(
visible_segments.iter().all(|&width| width >= 3),
"{locale:?} {text:?}: {visible_segments:?}"
);
}
}
}
#[test]
fn field_pointer_clicks_stop_at_extended_grapheme_boundaries() {
for (locale, drawer) in [
(MobileLocale::En, false),
(MobileLocale::Ar, false),
(MobileLocale::En, true),
(MobileLocale::Ar, true),
] {
let t = TestApp::launch(390, 844, locale);
let field_id = if drawer {
t.click_id("mobile.home.doc.doc-arch");
t.click_id("mobile.page.drawer_btn");
"mobile.drawer.filter_bar"
} else {
t.click_id("mobile.tab.search");
t.click_id("mobile.search.clear_btn");
"mobile.search.input"
};
t.click_id(field_id);
for text in [
"🇯🇵",
"か\u{3099}",
"कि",
"가",
"e\u{0301}",
"👍🏽",
"👨‍👩‍👧",
"ب\u{064E}",
"\r\n",
] {
let len = text.encode_utf16().count();
t.app
.update(|cx| {
t.window_handle.update(cx, |v, window, cx| {
let previous = v.text_length_utf16(window, cx).unwrap();
v.replace_text_in_range(Some(0..previous), text, window, cx);
})
})
.unwrap();
for _ in 0..3 {
t.headless_win.request_frame();
t.platform.run_until_parked();
}
let (x, y, w, h) = element_bounds(&t, field_id).unwrap();
let field = Bounds::new(point(px(x), px(y)), size(px(w), px(h)));
let span = t
.app
.update(|cx| {
t.window_handle.update(cx, |v, window, cx| {
v.bounds_for_range(0..len, field, window, cx).unwrap()
})
})
.unwrap();
let first = f32::from(span.left()).floor() as i32 - 2;
let last = f32::from(span.right()).ceil() as i32 + 2;
let mut seen = [false; 2];
for x in first..=last {
let position = point(px(x as f32), field.center().y);
t.headless_win.simulate_click(position);
t.app
.update(|cx| {
t.window_handle.update(cx, |v, window, cx| {
let found = v.character_index_for_point(position, window, cx).unwrap();
let clicked = v.selected_text_range(false, window, cx).unwrap();
assert!(
found == 0 || found == len,
"{locale:?} {field_id} {text:?} at x={x}: {found}"
);
assert_eq!(
clicked.range,
found..found,
"{locale:?} {field_id} {text:?} at x={x}"
);
seen[usize::from(found == len)] = true;
})
})
.unwrap();
}
assert_eq!(seen, [true; 2], "{locale:?} {field_id} {text:?}");
}
}
}