egui: UI language and bidi text runs in the AccessKit tree

`Context::set_language` sets the UI language (a BCP 47 tag, in `Options::language`),
which goes on the root of the AccessKit tree. Content in another language says so with
`UiBuilder::language`, which sets it on that `Ui`'s node and in `Ui::language`, or with
`Response::accessible_language` for a single widget.

Text runs follow the galley's bidi levels: a row is split into one run per stretch of
one level, with its real direction and its logical text. Character positions of a
right-to-left run count from its right edge, as AccessKit expects.
This commit is contained in:
aiongg committed 2026-10-21 05:28:17 +00:00
1 parent f7e89e23a1
commit 520435dfb0
9 files changed
+394 -129

No files matched your search

+27 -1
View File
@@ -2595,6 +2595,25 @@ impl Context {
self.options_mut(|opt| opt.theme_preference = theme_preference.into());
}
/// The language of the user interface, as a BCP 47 tag.
///
/// See [`Options::language`].
pub fn language(&self) -> Option<String> {
self.options(|opt| opt.language.clone())
}
/// Set the language of the user interface, as a BCP 47 tag (`"ar"`, `"pt-BR"`).
///
/// See [`Options::language`].
///
/// ```
/// # let ctx = egui::Context::default();
/// ctx.set_language(Some("ar".to_owned()));
/// ```
pub fn set_language(&self, language: Option<String>) {
self.options_mut(|opt| opt.language = language);
}
/// The currently active [`Style`] used by all subsequent popups, menus, etc.
pub fn global_style(&self) -> Arc<Style> {
self.options(|opt| Arc::clone(opt.style()))
@@ -3179,7 +3198,14 @@ impl ContextImpl {
{
profiling::scope!("accesskit");
let state = viewport.this_pass.accesskit_state.take();
if let Some(state) = state {
if let Some(mut state) = state {
// Set here rather than when the root node is made, so a language set during
// the pass applies to it.
if let Some(language) = &self.memory.options.language
&& let Some(root) = state.nodes.get_mut(&crate::accesskit_root_id())
{
root.set_language(language.clone());
}
let root_id = crate::accesskit_root_id().accesskit_id();
// A widget can have focus without a node, e.g. if it requested focus while invisible.
let focus_id = self
+13
View File
@@ -301,6 +301,17 @@ pub struct Options {
/// which is supported by `eframe`.
pub screen_reader: bool,
/// The language of the user interface, as a BCP 47 tag (`"ar"`, `"pt-BR"`).
///
/// egui puts it on the root of the AccessKit tree, so screen readers pick a voice for it.
/// Integrations and widgets can read it too.
/// Content in another language can say so with [`crate::UiBuilder::language`]
/// or [`crate::Response::accessible_language`].
///
/// Set it with [`crate::Context::set_language`]. Default: `None` (unknown).
#[cfg_attr(feature = "serde", serde(skip))]
pub language: Option<String>,
/// Check reusing of [`Id`]s, and show a visual warning on screen when one is found.
///
/// By default this is `true` in debug builds.
@@ -344,6 +355,7 @@ impl Default for Options {
#[expect(clippy::unwrap_used)]
max_passes: NonZeroUsize::new(2).unwrap(),
screen_reader: false,
language: None,
warn_on_id_clash: cfg!(debug_assertions),
// Input:
@@ -403,6 +415,7 @@ impl Options {
repaint_on_widget_change,
max_passes,
screen_reader: _, // needs to come from the integration
language: _, // set by the app
warn_on_id_clash,
input_options,
reduce_texture_memory,
+19
View File
@@ -1092,6 +1092,25 @@ impl Response {
self
}
/// The language of this widget's content, as a BCP 47 tag (`"ja"`, `"en-GB"`),
/// when it differs from the language around it, e.g. a book title or a name in another script.
///
/// A screen reader reads the widget in that language.
/// For a whole region, use [`crate::UiBuilder::language`].
///
/// ```
/// # egui::__run_test_ui(|ui| {
/// ui.label("Привет").accessible_language("ru");
/// # });
/// ```
pub fn accessible_language(self, language: impl Into<String>) -> Self {
let language = language.into();
self.ctx.accesskit_node_builder(self.id, |builder| {
builder.set_language(language);
});
self
}
/// Response to secondary clicks (right-clicks) by showing the given menu.
///
/// Make sure the widget senses clicks (e.g. [`crate::Button`] does, [`crate::Label`] does not).
+288 -117
View File
@@ -1,5 +1,7 @@
use core::ops::Range;
use emath::TSTransform;
use epaint::text::CharIndex;
use epaint::text::{CharIndex, PlacedRow};
use crate::{Context, Galley, Id};
@@ -8,21 +10,55 @@ use super::{CCursorRange, text_cursor_state::is_word_char};
/// AccessKit's `word_starts` uses `u8` indices, so text runs cannot exceed this length.
pub(crate) const MAX_CHARS_PER_TEXT_RUN: usize = 255;
/// Convert a (row, column) layout cursor position to a text run node ID and character index,
/// accounting for rows that are split into multiple text runs.
fn text_run_position(parent_id: Id, row: usize, column: CharIndex) -> accesskit::TextPosition {
/// The text runs of a row, as ranges of its columns, in logical order.
///
/// A run is a stretch of chars with the same bidi level, so it reads in one direction and is
/// contiguous on screen, at most [`MAX_CHARS_PER_TEXT_RUN`] long.
/// The row's trailing newline, if any, belongs to the last run.
/// A row always has at least one run, even when empty.
pub(crate) fn row_text_runs(row: &PlacedRow) -> Vec<Range<usize>> {
let glyph_count = row.glyphs.len();
let total_chars = glyph_count + usize::from(row.ends_with_newline);
let mut runs = Vec::new();
let mut start = 0;
for i in 1..glyph_count {
if row.glyphs[i].bidi_level != row.glyphs[i - 1].bidi_level
|| i - start == MAX_CHARS_PER_TEXT_RUN
{
runs.push(start..i);
start = i;
}
}
if total_chars - start > MAX_CHARS_PER_TEXT_RUN {
runs.push(start..glyph_count);
start = glyph_count;
}
runs.push(start..total_chars);
runs
}
fn text_run_id(parent_id: Id, row: usize, run: usize) -> Id {
parent_id.with(row).with(run)
}
/// Convert a (row, column) layout cursor position to a text run node ID and character index.
fn text_run_position(
parent_id: Id,
galley: &Galley,
row: usize,
column: CharIndex,
) -> accesskit::TextPosition {
let column = column.0;
// When column lands exactly on a chunk boundary (e.g., 255), it refers to
// the end of the previous chunk, not the start of a new one.
let chunk_index = if column > 0 && column.is_multiple_of(MAX_CHARS_PER_TEXT_RUN) {
column / MAX_CHARS_PER_TEXT_RUN - 1
} else {
column / MAX_CHARS_PER_TEXT_RUN
};
let character_index = column - chunk_index * MAX_CHARS_PER_TEXT_RUN;
let runs = galley.rows.get(row).map(row_text_runs).unwrap_or_default();
// A column on the boundary between two runs is the end of the first one.
let run_index = runs
.iter()
.position(|run| column <= run.end)
.unwrap_or_else(|| runs.len().saturating_sub(1));
let run_start = runs.get(run_index).map_or(0, |run| run.start);
accesskit::TextPosition {
node: parent_id.with(row).with(chunk_index).accesskit_id(),
character_index,
node: text_run_id(parent_id, row, run_index).accesskit_id(),
character_index: column - run_start,
}
}
@@ -32,6 +68,10 @@ fn text_run_position(parent_id: Id, row: usize, column: CharIndex) -> accesskit:
/// current text selection. It never touches the role of the widget itself: that
/// is set from the [`crate::WidgetInfo`] the widget reports, so a link stays a
/// link and a button stays a button.
///
/// Each run holds the logical text of a stretch of one bidi level, with its direction.
/// Its character positions run from its left edge for left-to-right text and from
/// its right edge for right-to-left text, as AccessKit expects.
pub fn update_accesskit_for_text_widget(
ctx: &Context,
widget_id: Id,
@@ -46,8 +86,8 @@ pub fn update_accesskit_for_text_widget(
let anchor = galley.layout_from_cursor(cursor_range.secondary);
let focus = galley.layout_from_cursor(cursor_range.primary);
builder.set_text_selection(accesskit::TextSelection {
anchor: text_run_position(parent_id, anchor.row, anchor.column),
focus: text_run_position(parent_id, focus.row, focus.column),
anchor: text_run_position(parent_id, galley, anchor.row, anchor.column),
focus: text_run_position(parent_id, galley, focus.row, focus.column),
});
}
@@ -61,51 +101,88 @@ pub fn update_accesskit_for_text_widget(
let mut prev_row_ended_with_newline = true;
for (row_index, row) in galley.rows.iter().enumerate() {
let glyph_count = row.glyphs.len();
let mut value = String::with_capacity(glyph_count);
let mut character_lengths = Vec::<u8>::with_capacity(glyph_count);
let mut character_positions = Vec::<f32>::with_capacity(glyph_count);
let mut character_widths = Vec::<f32>::with_capacity(glyph_count);
let mut word_starts = Vec::<usize>::new();
// For soft-wrapped continuation rows, treat the start as a word
// boundary so the first word character gets a `word_starts` entry.
// Paragraph-starting runs (first row or after a newline) get an
// implicit word start from AccessKit, so they don't need this.
let mut was_at_word_end = !prev_row_ended_with_newline;
for glyph in &row.glyphs {
let mut word_starts = Vec::<usize>::new();
for (i, glyph) in row.glyphs.iter().enumerate() {
let is_word_char = is_word_char(glyph.chr);
if is_word_char && was_at_word_end {
word_starts.push(character_lengths.len());
word_starts.push(i);
}
was_at_word_end = !is_word_char;
let old_len = value.len();
value.push(glyph.chr);
character_lengths.push((value.len() - old_len) as _);
character_positions.push(glyph.pos.x - row.pos.x);
character_widths.push(glyph.advance_width);
}
if row.ends_with_newline {
value.push('\n');
character_lengths.push(1);
character_positions.push(row.size.x);
character_widths.push(0.0);
}
let runs = row_text_runs(row);
let row_rect = row.rect_without_leading_space();
let total_chars = character_lengths.len();
for (run_index, run) in runs.iter().enumerate() {
let glyphs = &row.glyphs[run.start..run.end.min(row.glyphs.len())];
let is_rtl = glyphs.first().is_some_and(|glyph| glyph.is_rtl());
if total_chars <= MAX_CHARS_PER_TEXT_RUN {
let run_id = parent_id.with(row_index).with(0usize);
// The run's horizontal extent, row-relative:
let (x0, x1) = if glyphs.is_empty() {
(row_rect.min.x - row.pos.x, row_rect.max.x - row.pos.x)
} else {
glyphs
.iter()
.fold((f32::INFINITY, f32::NEG_INFINITY), |(x0, x1), glyph| {
(x0.min(glyph.pos.x), x1.max(glyph.max_x()))
})
};
let mut value = String::with_capacity(run.len());
let mut character_lengths = Vec::<u8>::with_capacity(run.len());
let mut character_positions = Vec::<f32>::with_capacity(run.len());
let mut character_widths = Vec::<f32>::with_capacity(run.len());
for glyph in glyphs {
let old_len = value.len();
value.push(glyph.chr);
character_lengths.push((value.len() - old_len) as _);
character_positions.push(if is_rtl {
x1 - glyph.max_x()
} else {
glyph.pos.x - x0
});
character_widths.push(glyph.advance_width);
}
if glyphs.len() < run.len() {
// The newline, at the end of the run:
value.push('\n');
character_lengths.push(1);
character_positions.push(x1 - x0);
character_widths.push(0.0);
}
let run_id = text_run_id(parent_id, row_index, run_index);
ctx.register_accesskit_parent(run_id, parent_id);
ctx.accesskit_node_builder(run_id, |builder| {
builder.set_role(accesskit::Role::TextRun);
builder.set_text_direction(accesskit::TextDirection::LeftToRight);
builder.set_text_direction(if is_rtl {
accesskit::TextDirection::RightToLeft
} else {
accesskit::TextDirection::LeftToRight
});
// TODO(mwcampbell): Set more node fields for the row
// once AccessKit adapters expose text formatting info.
let rect = global_from_galley * row.rect_without_leading_space();
if run_index > 0 {
let prev_id = text_run_id(parent_id, row_index, run_index - 1);
builder.set_previous_on_line(prev_id.accesskit_id());
}
if run_index + 1 < runs.len() {
let next_id = text_run_id(parent_id, row_index, run_index + 1);
builder.set_next_on_line(next_id.accesskit_id());
}
let run_rect = emath::Rect::from_min_max(
emath::pos2(row.pos.x + x0, row_rect.min.y),
emath::pos2(row.pos.x + x1, row_rect.max.y),
);
let rect = global_from_galley * run_rect;
builder.set_bounds(accesskit::Rect {
x0: rect.min.x.into(),
y0: rect.min.y.into(),
@@ -114,88 +191,182 @@ pub fn update_accesskit_for_text_widget(
});
builder.set_value(value);
builder.set_character_lengths(character_lengths);
let pos_offset = character_positions.first().copied().unwrap_or(0.0);
for p in &mut character_positions {
*p -= pos_offset;
}
builder.set_character_positions(character_positions);
builder.set_character_widths(character_widths);
let chunk_word_starts: Vec<u8> = word_starts.iter().map(|&ws| ws as u8).collect();
builder.set_word_starts(chunk_word_starts);
});
} else {
let num_chunks = total_chars.div_ceil(MAX_CHARS_PER_TEXT_RUN);
let mut byte_offset = 0usize;
for chunk_idx in 0..num_chunks {
let char_start = chunk_idx * MAX_CHARS_PER_TEXT_RUN;
let char_end = (char_start + MAX_CHARS_PER_TEXT_RUN).min(total_chars);
let byte_start = byte_offset;
let chunk_byte_len: usize = character_lengths[char_start..char_end]
let run_word_starts: Vec<u8> = word_starts
.iter()
.map(|&l| l as usize)
.sum();
let byte_end = byte_start + chunk_byte_len;
byte_offset = byte_end;
let run_id = parent_id.with(row_index).with(chunk_idx);
ctx.register_accesskit_parent(run_id, parent_id);
ctx.accesskit_node_builder(run_id, |builder| {
builder.set_role(accesskit::Role::TextRun);
builder.set_text_direction(accesskit::TextDirection::LeftToRight);
// TODO(mwcampbell): Set more node fields for the row
// once AccessKit adapters expose text formatting info.
if chunk_idx > 0 {
let prev_id = parent_id.with(row_index).with(chunk_idx - 1);
builder.set_previous_on_line(prev_id.accesskit_id());
}
if chunk_idx + 1 < num_chunks {
let next_id = parent_id.with(row_index).with(chunk_idx + 1);
builder.set_next_on_line(next_id.accesskit_id());
}
let row_rect = row.rect_without_leading_space();
let chunk_x0 = row.pos.x + character_positions[char_start];
let chunk_x1 = row.pos.x
+ character_positions[char_end - 1]
+ character_widths[char_end - 1];
let chunk_rect = emath::Rect::from_min_max(
emath::pos2(chunk_x0, row_rect.min.y),
emath::pos2(chunk_x1, row_rect.max.y),
);
let rect = global_from_galley * chunk_rect;
builder.set_bounds(accesskit::Rect {
x0: rect.min.x.into(),
y0: rect.min.y.into(),
x1: rect.max.x.into(),
y1: rect.max.y.into(),
});
builder.set_value(value[byte_start..byte_end].to_owned());
builder.set_character_lengths(character_lengths[char_start..char_end].to_vec());
let pos_offset = character_positions[char_start];
let chunk_positions: Vec<f32> = character_positions[char_start..char_end]
.iter()
.map(|&p| p - pos_offset)
.collect();
builder.set_character_positions(chunk_positions);
builder.set_character_widths(character_widths[char_start..char_end].to_vec());
let chunk_word_starts: Vec<u8> = word_starts
.iter()
.filter(|&&ws| ws >= char_start && ws < char_end)
.map(|&ws| (ws - char_start) as u8)
.collect();
builder.set_word_starts(chunk_word_starts);
});
}
.filter(|&&ws| run.contains(&ws))
.map(|&ws| (ws - run.start) as u8)
.collect();
builder.set_word_starts(run_word_starts);
});
}
prev_row_ended_with_newline = row.ends_with_newline;
}
}
#[cfg(test)]
mod tests {
use accesskit::{Node, NodeId, Role, TextDirection, TreeUpdate};
use epaint::text::cursor::CCursor;
use super::{row_text_runs, text_run_position};
use crate::{Color32, Context, FontId, Id, RawInput, Ui, UiBuilder};
fn accesskit_update(ctx: &Context, mut add_contents: impl FnMut(&mut Ui)) -> TreeUpdate {
ctx.enable_accesskit();
let mut output = ctx.run_ui(RawInput::default(), |ui| add_contents(ui));
output.textures_delta.clear();
output
.platform_output
.accesskit_update
.expect("Missing accesskit update")
}
fn node(update: &TreeUpdate, id: NodeId) -> &Node {
&update
.nodes
.iter()
.find(|(node_id, _)| *node_id == id)
.unwrap()
.1
}
fn label<'a>(update: &'a TreeUpdate, text: &str) -> &'a Node {
&update
.nodes
.iter()
.find(|(_, node)| node.role() == Role::Label && node.value() == Some(text))
.unwrap_or_else(|| panic!("No label {text:?}"))
.1
}
/// `(value, direction)` of each text run of a label, in order.
fn runs(update: &TreeUpdate, text: &str) -> Vec<(String, TextDirection)> {
label(update, text)
.children()
.iter()
.map(|&id| node(update, id))
.filter(|run| run.role() == Role::TextRun)
.map(|run| {
(
run.value().unwrap().to_owned(),
run.text_direction().unwrap(),
)
})
.collect()
}
#[test]
fn ui_language_on_the_root_and_overrides_on_widgets() {
let ctx = Context::default();
ctx.set_language(Some("ar".to_owned()));
let update = accesskit_update(&ctx, |ui| {
assert_eq!(ui.language().as_deref(), Some("ar"));
ui.label("مرحبا");
ui.label("Bonjour").accessible_language("fr");
ui.scope_builder(UiBuilder::new().id_salt("hebrew").language("he"), |ui| {
assert_eq!(ui.language().as_deref(), Some("he"));
ui.label("שלום");
});
});
let root = node(&update, update.tree.as_ref().unwrap().root);
assert_eq!(root.language(), Some("ar"));
assert_eq!(
label(&update, "مرحبا").language(),
None,
"inherits the root's"
);
assert_eq!(label(&update, "Bonjour").language(), Some("fr"));
let hebrew = label(&update, "שלום").language();
assert_eq!(hebrew, None, "inherits its Ui's");
let hebrew_id = update
.nodes
.iter()
.find(|(_, node)| node.value() == Some("שלום"))
.unwrap()
.0;
let scope = &update
.nodes
.iter()
.find(|(_, node)| node.children().contains(&hebrew_id))
.unwrap()
.1;
assert_eq!(scope.language(), Some("he"));
}
#[test]
fn text_runs_have_their_direction_and_logical_text() {
let ctx = Context::default();
let arabic = "مرحبا بالعالم";
let mixed = "Hello שלום world";
let update = accesskit_update(&ctx, |ui| {
ui.label(arabic);
ui.label(mixed);
});
assert_eq!(
runs(&update, arabic),
[(arabic.to_owned(), TextDirection::RightToLeft)]
);
assert_eq!(
runs(&update, mixed),
[
("Hello ".to_owned(), TextDirection::LeftToRight),
("שלום".to_owned(), TextDirection::RightToLeft),
(" world".to_owned(), TextDirection::LeftToRight),
]
);
// Positions of a right-to-left run count from its right edge,
// so they grow in logical order and stay inside the run.
let run = node(&update, label(&update, arabic).children()[0]);
let positions = run.character_positions().unwrap();
let widths = run.character_widths().unwrap();
let bounds = run.bounds().unwrap();
assert_eq!(positions.len(), arabic.chars().count());
assert!(positions[0].abs() < 0.01, "{positions:?}");
assert!(positions.is_sorted(), "{positions:?}");
let end = positions.last().unwrap() + widths.last().unwrap();
assert!(
(f64::from(end) - bounds.width()).abs() < 0.01,
"{end} vs {}",
bounds.width()
);
// Runs on one line link to each other in logical order:
let ids = label(&update, mixed).children();
assert_eq!(node(&update, ids[0]).next_on_line(), Some(ids[1]));
assert_eq!(node(&update, ids[2]).previous_on_line(), Some(ids[1]));
}
#[test]
fn text_positions_round_trip_through_runs() {
let ctx = Context::default();
let id = Id::unique("text");
accesskit_update(&ctx, |ui| {
let text = "abc אבג 12 def\nשלום";
let galley = ui.painter().layout_no_wrap(
text.to_owned(),
FontId::proportional(14.0),
Color32::WHITE,
);
assert!(row_text_runs(&galley.rows[0]).len() >= 3);
for index in 0..=text.chars().count() {
let cursor = CCursor::new(index);
let layout = galley.layout_from_cursor(cursor);
let position = text_run_position(id, &galley, layout.row, layout.column);
let back =
crate::text_selection::cursor_range::ccursor_from_accesskit_text_position(
id, &galley, &position,
)
.unwrap();
assert_eq!(back.index, cursor.index, "{position:?}");
}
});
}
}
+5 -10
View File
@@ -222,26 +222,21 @@ impl CCursorRange {
// ----------------------------------------------------------------------------
fn ccursor_from_accesskit_text_position(
pub(super) fn ccursor_from_accesskit_text_position(
id: Id,
galley: &Galley,
position: &accesskit::TextPosition,
) -> Option<CCursor> {
use super::accesskit_text::MAX_CHARS_PER_TEXT_RUN;
use super::accesskit_text::row_text_runs;
let mut total_length = 0usize;
for (i, row) in galley.rows.iter().enumerate() {
let row_chars = row.glyphs.len() + (row.ends_with_newline as usize);
let num_chunks = if row_chars == 0 {
1
} else {
row_chars.div_ceil(MAX_CHARS_PER_TEXT_RUN)
};
for chunk_idx in 0..num_chunks {
let run_id = id.with(i).with(chunk_idx);
for (run_index, run) in row_text_runs(row).into_iter().enumerate() {
let run_id = id.with(i).with(run_index);
if run_id.accesskit_id() == position.node {
let column = chunk_idx * MAX_CHARS_PER_TEXT_RUN + position.character_index;
let column = run.start + position.character_index;
return Some(CCursor {
index: CharIndex(total_length + column),
prefer_next_row: !(column == row.glyphs.len()
+1 -1
View File
@@ -2,7 +2,7 @@
pub mod accesskit_text;
mod cursor_range;
pub(crate) mod cursor_range;
mod label_text_selection;
pub mod text_cursor_state;
pub mod visuals;
+20
View File
@@ -106,6 +106,7 @@ impl Ui {
accessibility_parent,
accessibility_label,
accessibility_role,
language,
classes,
} = ui_builder;
@@ -138,6 +139,7 @@ impl Ui {
min_rect: placer.min_rect(),
max_rect: placer.max_rect(),
classes,
language: language.clone(),
};
let mut ui = Ui {
@@ -193,6 +195,9 @@ impl Ui {
if let Some(label) = accessibility_label {
node.set_label(label);
}
if let Some(language) = language {
node.set_language(language);
}
});
ui
@@ -222,6 +227,7 @@ impl Ui {
accessibility_parent,
accessibility_label,
accessibility_role,
language,
classes,
} = ui_builder;
@@ -274,6 +280,7 @@ impl Ui {
min_rect: placer.min_rect(),
max_rect: placer.max_rect(),
classes,
language: language.clone(),
};
let mut child_ui = Ui {
@@ -329,6 +336,9 @@ impl Ui {
if let Some(label) = accessibility_label {
node.set_label(label);
}
if let Some(language) = language {
node.set_language(language);
}
});
child_ui
@@ -473,6 +483,16 @@ impl Ui {
&self.stack
}
/// The language of this `Ui`'s content, as a BCP 47 tag:
/// the nearest [`UiBuilder::language`] up the stack, or else the
/// language of the user interface ([`Context::language`]).
pub fn language(&self) -> Option<String> {
match self.stack.language() {
Some(language) => Some(language.to_owned()),
None => self.ctx().language(),
}
}
/// Get a reference to the parent [`Context`].
#[inline]
pub fn ctx(&self) -> &Context {
+13
View File
@@ -30,6 +30,7 @@ pub struct UiBuilder {
pub accessibility_parent: Option<Id>,
pub accessibility_label: Option<String>,
pub accessibility_role: Option<crate::accesskit::Role>,
pub language: Option<String>,
pub classes: Classes,
}
@@ -223,6 +224,18 @@ impl UiBuilder {
self.accessibility_role = Some(role);
self
}
/// The language of the content of this [`Ui`], as a BCP 47 tag (`"he"`, `"zh-Hant"`),
/// when it differs from the language of the user interface
/// ([`crate::Context::set_language`]).
///
/// It goes on this `Ui`'s node in the accessibility tree, which the widgets inside inherit,
/// so a screen reader reads them in that language. Widgets read it with [`Ui::language`].
#[inline]
pub fn language(mut self, language: impl Into<String>) -> Self {
self.language = Some(language.into());
self
}
}
impl HasClasses for UiBuilder {
+8
View File
@@ -250,6 +250,9 @@ pub struct UiStack {
pub max_rect: Rect,
pub parent: Option<Arc<Self>>,
pub classes: Classes,
/// The language of this [`crate::Ui`]'s content, if set with [`crate::UiBuilder::language`].
pub language: Option<String>,
}
// these methods act on this specific node
@@ -322,6 +325,11 @@ impl UiStack {
UiStackIterator { next: Some(self) }
}
/// The language set with [`crate::UiBuilder::language`] on this node or the nearest one up the stack.
pub fn language(&self) -> Option<&str> {
self.iter().find_map(|node| node.language.as_deref())
}
/// Check if this node is or is contained in a [`crate::Ui`] of a specific kind.
pub fn contained_in(&self, kind: UiKind) -> bool {
self.iter().any(|frame| frame.kind() == Some(kind))