mitsuami-headless 2.3.0

In-memory mitsuami backend with deterministic measurement, for tests
Documentation
//! Performing accessibility actions, as assistive technology does.

use mitsuami_core::a11y::{A11yAction, ActionError};
use mitsuami_core::services::menu_item_by_id;
use mitsuami_core::{
    ColumnSort, EventValue, NodeId, Prop, SelectionMode, SortOrder, UiEvent, WidgetKind, find_prop, moved_index,
};

use super::HeadlessBackend;

impl HeadlessBackend {
    pub(super) fn perform_action(&mut self, id: NodeId, action: &A11yAction) -> Result<(), ActionError> {
        let mut state = self.state.borrow_mut();
        let node = state.nodes.get(&id).ok_or(ActionError::UnknownNode)?;
        if find_prop!(node.props, Enabled) == Some(false) {
            return Err(ActionError::Disabled);
        }
        let kind = node.kind;
        // A menu button's own menu, or any node's context menu.
        let chosen = match action {
            // A sidebar's items each have theirs, which share its ids.
            A11yAction::ContextMenuItem(item) if kind == WidgetKind::Sidebar => {
                let sections = find_prop!(node.props, Sections).unwrap_or_default();
                let menus = sections.into_iter().flat_map(|s| s.items).map(|i| i.menu);
                let menu = menus.into_iter().find(|m| menu_item_by_id(m, *item).is_some());
                Some((menu, *item, UiEvent::ContextMenuItem(*item)))
            }
            A11yAction::ContextMenuItem(item) => {
                Some((find_prop!(node.props, ContextMenu), *item, UiEvent::ContextMenuItem(*item)))
            }
            A11yAction::MenuItem(item) if matches!(kind, WidgetKind::MenuButton | WidgetKind::SplitButton) => {
                Some((find_prop!(node.props, Menu), *item, UiEvent::MenuItem(*item)))
            }
            _ => None,
        };
        if let Some((menu, item, event)) = chosen {
            let menu = menu.unwrap_or_default();
            return match menu_item_by_id(&menu, item).map(|item| item.enabled) {
                Some(true) => {
                    state.emit(id, event);
                    Ok(())
                }
                Some(false) => Err(ActionError::Disabled),
                None => Err(ActionError::Unsupported),
            };
        }
        match (action, kind) {
            // A suggestion of the list under the field.
            (A11yAction::ChooseSuggestion(index), WidgetKind::SearchInput) => {
                let count = find_prop!(state.nodes[&id].props, Suggestions).map_or(0, |s| s.len());
                if *index >= count {
                    return Err(ActionError::Unsupported);
                }
                state.emit(id, UiEvent::SuggestionChosen(*index));
            }
            (A11yAction::Activate, WidgetKind::Button | WidgetKind::SplitButton) => {
                state.focus(id);
                state.emit(id, UiEvent::Click);
            }
            (A11yAction::Activate, WidgetKind::Checkbox | WidgetKind::Switch | WidgetKind::ToggleButton) => {
                // Out of the mixed state, a click checks the box, as on
                // AppKit and Qt.
                let props = &state.nodes[&id].props;
                let checked = find_prop!(props, Mixed) == Some(true) || !find_prop!(props, Checked).unwrap_or(false);
                if find_prop!(props, Mixed) == Some(true) {
                    state.set_prop(id, Prop::Mixed(false));
                }
                state.set_prop(id, Prop::Checked(checked));
                state.focus(id);
                state.emit(id, UiEvent::Changed(EventValue::Bool(checked)));
            }
            (
                A11yAction::SetValue(text),
                WidgetKind::TextInput | WidgetKind::PasswordInput | WidgetKind::SearchInput | WidgetKind::TextArea,
            ) => {
                if find_prop!(state.nodes[&id].props, ReadOnly) == Some(true) {
                    return Err(ActionError::ReadOnly);
                }
                // New text puts the caret at its end, so a selection of the
                // old text isn't typed over.
                if state.focused == Some(id) {
                    state.selection = None;
                }
                state.set_prop(id, Prop::Value(text.clone()));
                state.emit(id, UiEvent::Changed(EventValue::Text(text.clone())));
                let on_return = find_prop!(state.nodes[&id].props, SearchOnReturn) == Some(true);
                if kind == WidgetKind::SearchInput && (!on_return || text.is_empty()) {
                    state.emit(id, UiEvent::Search(text.clone()));
                }
            }
            (A11yAction::SetValue(_) | A11yAction::Increment | A11yAction::Decrement, WidgetKind::Slider) => {
                let props = &state.nodes[&id].props;
                let (min, max) = props
                    .iter()
                    .find_map(|p| match p {
                        Prop::Range { min, max } => Some((*min, *max)),
                        _ => None,
                    })
                    .unwrap_or((0.0, 1.0));
                let value = find_prop!(props, Number).unwrap_or(min);
                // Steps by the step, or a tenth of the range without one.
                let step = find_prop!(props, Step).flatten().unwrap_or((max - min) / 10.0);
                let value = match action {
                    A11yAction::SetValue(text) => text.trim().parse().map_err(|_| ActionError::Unsupported)?,
                    A11yAction::Increment => value + step,
                    _ => value - step,
                };
                // Not `clamp`, which panics on a range given upside down,
                // or with an end that isn't a number.
                let value = value.max(min).min(max);
                state.set_prop(id, Prop::Number(value));
                state.emit(id, UiEvent::Changed(EventValue::Number(value)));
            }
            // As assistive technology sets one: its picker never opens.
            (A11yAction::SetValue(text), WidgetKind::ColorWell) => {
                let color = mitsuami_core::Color::from_hex(text).ok_or(ActionError::Unsupported)?;
                state.set_prop(id, Prop::ColorValue(color));
                state.emit(id, UiEvent::Changed(EventValue::Color(color)));
            }
            // Moves the divider, as assistive technology sets a splitter's
            // value: no further than the panes' least sizes let it.
            (A11yAction::SetValue(text), WidgetKind::Split) => {
                let node = &state.nodes[&id];
                // No divider while a pane is hidden.
                if find_prop!(node.props, PanesShown).is_some_and(|shown| shown != [true, true]) {
                    return Err(ActionError::Unsupported);
                }
                let position: f32 = text.trim().parse().map_err(|_| ActionError::Unsupported)?;
                let [first, second] = find_prop!(node.props, PaneMinimums).unwrap_or_default();
                let vertical = find_prop!(node.props, Orientation).is_some_and(|o| o.vertical());
                let length = if vertical { node.frame.height() } else { node.frame.width() };
                let position = position.min(length - super::metrics::SPLIT_DIVIDER - second).max(first);
                state.set_prop(id, Prop::Number(f64::from(position)));
                state.emit(id, UiEvent::Changed(EventValue::Number(f64::from(position))));
            }
            (A11yAction::SetValue(_) | A11yAction::Increment | A11yAction::Decrement, WidgetKind::NumberInput) => {
                let props = &state.nodes[&id].props;
                let (min, max) = props
                    .iter()
                    .find_map(|p| match p {
                        Prop::Range { min, max } => Some((*min, *max)),
                        _ => None,
                    })
                    .unwrap_or((0.0, 100.0));
                let value = find_prop!(props, Number).unwrap_or(min);
                let step = find_prop!(props, Step).flatten().unwrap_or(1.0);
                let wraps = find_prop!(props, WrapAround) == Some(true);
                // Whole numbers, clamped at the ends, as GTK, Qt and WinUI
                // do it; stepped past one end of a range that wraps, the
                // other end, as every platform's wrapping does it.
                let value = match action {
                    A11yAction::SetValue(text) => {
                        text.trim().parse::<f64>().map_err(|_| ActionError::Unsupported)?.round()
                    }
                    A11yAction::Increment if wraps && value + step > max => min,
                    A11yAction::Decrement if wraps && value - step < min => max,
                    A11yAction::Increment => value + step,
                    _ => value - step,
                };
                let value = value.max(min).min(max);
                state.set_prop(id, Prop::Number(value));
                state.emit(id, UiEvent::Changed(EventValue::Number(value)));
            }
            (A11yAction::SetValue(text), WidgetKind::Select) => {
                let options = find_prop!(state.nodes[&id].props, Options).unwrap_or_default();
                let index = options.iter().position(|o| o == text).ok_or(ActionError::Unsupported)?;
                state.set_prop(id, Prop::SelectedIndex(Some(index)));
                state.emit(id, UiEvent::Changed(EventValue::Index(index)));
            }
            // A radio button, by its option, as a screen reader presses one.
            (A11yAction::SetValue(text), WidgetKind::RadioGroup) => {
                let options = find_prop!(state.nodes[&id].props, Options).unwrap_or_default();
                let index = options.iter().position(|o| o == text).ok_or(ActionError::Unsupported)?;
                if find_prop!(state.nodes[&id].props, SelectedIndex).flatten() != Some(index) {
                    state.set_prop(id, Prop::SelectedIndex(Some(index)));
                    state.emit(id, UiEvent::Changed(EventValue::Index(index)));
                }
            }
            // An item, by its title, as a screen reader selects one.
            (A11yAction::SetValue(title), WidgetKind::Sidebar) => {
                let sections = find_prop!(state.nodes[&id].props, Sections).unwrap_or_default();
                let mut titles = sections.iter().flat_map(|s| s.items.iter().map(|i| &i.title));
                let index = titles.position(|t| t == title).ok_or(ActionError::Unsupported)?;
                if find_prop!(state.nodes[&id].props, SelectedIndex).flatten() != Some(index) {
                    state.set_prop(id, Prop::SelectedIndex(Some(index)));
                    state.emit(id, UiEvent::Changed(EventValue::Index(index)));
                }
            }
            // The chosen item, as Enter on it does.
            (A11yAction::Activate, WidgetKind::Sidebar) => {
                let index = find_prop!(state.nodes[&id].props, SelectedIndex).flatten();
                let Some(index) = index else { return Err(ActionError::Unsupported) };
                state.emit(id, UiEvent::SidebarItemActivated(index));
            }
            // A tab, by its title, as a screen reader picks one.
            (A11yAction::SetValue(title), WidgetKind::Tabs) => {
                let titles = find_prop!(state.nodes[&id].props, TabTitles).unwrap_or_default();
                let index = titles.iter().position(|t| t == title).ok_or(ActionError::Unsupported)?;
                if find_prop!(state.nodes[&id].props, SelectedIndex).flatten() != Some(index) {
                    state.set_prop(id, Prop::SelectedIndex(Some(index)));
                    state.emit(id, UiEvent::Changed(EventValue::Index(index)));
                }
            }
            // A tab, by its title, as a screen reader picks one.
            (A11yAction::SetValue(title), WidgetKind::DocumentTabs) => {
                let titles = find_prop!(state.nodes[&id].props, TabTitles).unwrap_or_default();
                let index = titles.iter().position(|t| t == title).ok_or(ActionError::Unsupported)?;
                if find_prop!(state.nodes[&id].props, SelectedIndex).flatten() != Some(index) {
                    state.set_prop(id, Prop::SelectedIndex(Some(index)));
                    state.emit(id, UiEvent::Changed(EventValue::Index(index)));
                }
            }
            // Its close button asks; the tab stays.
            (A11yAction::CloseTab(index), WidgetKind::DocumentTabs) => {
                let props = &state.nodes[&id].props;
                let count = find_prop!(props, TabTitles).unwrap_or_default().len();
                if find_prop!(props, TabsClosable) != Some(true) || *index >= count {
                    return Err(ActionError::Unsupported);
                }
                state.emit(id, UiEvent::TabCloseRequested(*index));
            }
            // Dragged there: the strip shows it moved, the chosen tab still
            // chosen, before the app hears.
            (A11yAction::MoveTab { from, to }, WidgetKind::DocumentTabs) => {
                let props = &state.nodes[&id].props;
                let mut titles = find_prop!(props, TabTitles).unwrap_or_default();
                if find_prop!(props, TabsReorderable) != Some(true) || *from >= titles.len() || *to >= titles.len() {
                    return Err(ActionError::Unsupported);
                }
                if from == to {
                    return Ok(());
                }
                let chosen = find_prop!(props, SelectedIndex).flatten().map(|i| moved_index(i, *from, *to));
                let title = titles.remove(*from);
                titles.insert(*to, title);
                state.set_prop(id, Prop::TabTitles(titles));
                state.set_prop(id, Prop::SelectedIndex(chosen));
                state.emit(id, UiEvent::TabMoved { from: *from, to: *to });
            }
            // Its new-tab button.
            (A11yAction::Activate, WidgetKind::DocumentTabs) => {
                if find_prop!(state.nodes[&id].props, NewTabButton) != Some(true) {
                    return Err(ActionError::Unsupported);
                }
                state.emit(id, UiEvent::NewTabRequested);
            }
            (
                A11yAction::Focus,
                WidgetKind::Button
                | WidgetKind::SplitButton
                | WidgetKind::ToggleButton
                | WidgetKind::TextInput
                | WidgetKind::PasswordInput
                | WidgetKind::SearchInput
                | WidgetKind::TextArea
                | WidgetKind::Checkbox
                | WidgetKind::Switch
                | WidgetKind::Select
                | WidgetKind::RadioGroup
                | WidgetKind::Slider
                | WidgetKind::NumberInput
                | WidgetKind::ColorWell
                | WidgetKind::List
                | WidgetKind::Table
                | WidgetKind::Sidebar
                | WidgetKind::Tabs
                | WidgetKind::DocumentTabs,
            ) => state.focus(id),
            // A header sorts by its column: the same one the other way
            // round, another one ascending, as native tables do.
            (A11yAction::PressHeader(column), WidgetKind::Table) => {
                let props = &state.nodes[&id].props;
                let columns = find_prop!(props, Columns).unwrap_or_default();
                if !columns.get(*column).is_some_and(|c| c.sortable) {
                    return Err(ActionError::Unsupported);
                }
                let order = match find_prop!(props, Sort).flatten() {
                    Some(sort) if sort.column == *column => sort.order.reversed(),
                    _ => SortOrder::Ascending,
                };
                let sort = ColumnSort { column: *column, order };
                state.set_prop(id, Prop::Sort(Some(sort)));
                state.emit(id, UiEvent::Changed(EventValue::Sort(sort)));
            }
            (A11yAction::Select | A11yAction::Activate, WidgetKind::Container) => {
                let props = &state.nodes[&id].props;
                let row = find_prop!(props, Row).or_else(|| find_prop!(props, Cell).map(|c| c.row));
                let list = state.nodes[&id].parent.filter(|p| state.nodes[p].kind.has_rows());
                let (Some(row), Some(list)) = (row, list) else { return Err(ActionError::Unsupported) };
                if *action == A11yAction::Activate {
                    state.emit(list, UiEvent::RowActivated(row));
                } else if find_prop!(state.nodes[&list].props, SelectionMode).unwrap_or_default() == SelectionMode::None
                {
                    return Err(ActionError::Unsupported);
                } else {
                    state.select(list, vec![row]);
                }
            }
            // A tree's row, as assistive technology opens and closes one.
            (A11yAction::Expand | A11yAction::Collapse, WidgetKind::Container) => {
                let row = find_prop!(state.nodes[&id].props, Row);
                let tree = state.nodes[&id].parent.filter(|p| state.nodes[p].kind == WidgetKind::Tree);
                let (Some(row), Some(tree)) = (row, tree) else { return Err(ActionError::Unsupported) };
                state.expand(tree, row, *action == A11yAction::Expand).map_err(|()| ActionError::Unsupported)?;
            }
            (A11yAction::ScrollIntoView, _) => {}
            _ => return Err(ActionError::Unsupported),
        }
        Ok(())
    }
}