iced-cube 0.0.20

Themeable application components for the iced GUI library, with Lucide icons
Documentation
//! Shortcuts a component resolves itself while it has keyboard focus or was
//! the last thing pressed, so several on one screen never fight over keys.

use iced::advanced::widget::operation::Focusable;
use iced::{Event, Rectangle, mouse, touch};

use super::State;

/// Whether a component's shortcuts apply: it has keyboard focus, or the
/// last pointer press landed on it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) struct Scope {
    focus: State,
    pressed: bool,
}

impl Scope {
    pub(crate) fn is_focused(self) -> bool {
        self.focus.is_focused()
    }

    pub(crate) fn has_keys(self) -> bool {
        self.pressed || self.focus.is_focused()
    }

    /// Follows pointer presses: one inside `area` gives the component its
    /// keys, any press takes keyboard focus away, and one elsewhere hands
    /// the keys back to the app. Returns whether anything changed.
    pub(crate) fn update(&mut self, event: &Event, cursor: mouse::Cursor, area: Rectangle) -> bool {
        let before = *self;
        let _ = self.focus.update(event);
        if let Some(inside) = press_inside(event, cursor, area) {
            self.pressed = inside;
        }
        *self != before
    }

    /// Gives up focus and keys, for a component that can no longer take
    /// them, such as one that became disabled. Returns whether it changed.
    #[cfg(any(feature = "image-compare", feature = "timeline"))]
    pub(crate) fn release(&mut self) -> bool {
        let before = *self;
        *self = Self::default();
        *self != before
    }
}

/// Reported to focus operations in place of the plain focus state, so focus
/// moving elsewhere, as Tab moves it, also hands the keys back.
impl Focusable for Scope {
    fn is_focused(&self) -> bool {
        self.focus.is_focused()
    }

    fn focus(&mut self) {
        self.focus.focus();
    }

    fn unfocus(&mut self) {
        *self = Self::default();
    }
}

/// Whether a pointer press landed in `area`, or `None` for other events.
fn press_inside(event: &Event, cursor: mouse::Cursor, area: Rectangle) -> Option<bool> {
    match event {
        Event::Mouse(mouse::Event::ButtonPressed(_)) => Some(cursor.is_over(area)),
        Event::Touch(touch::Event::FingerPressed { position, .. }) => {
            Some(area.contains(*position))
        }
        _ => None,
    }
}

#[cfg(any(feature = "slider", feature = "tabs"))]
pub(crate) use widget::keyed;

#[cfg(any(feature = "slider", feature = "tabs"))]
mod widget {
    use iced::advanced::layout::{self, Layout};
    use iced::advanced::widget::{Operation, Tree, Widget, tree};
    use iced::advanced::{Clipboard, Shell, overlay, renderer};
    use iced::keyboard;
    use iced::{Element, Event, Length, Rectangle, Renderer, Size, Theme, Vector, mouse};

    use super::Scope;
    use crate::focus::{draw_ring, report};
    use crate::keys::Keymap;

    /// Wraps a component built from other widgets so it takes keyboard
    /// focus, draws the ring and resolves `keymap` while it has keys.
    pub(crate) struct Keyed<'a, A, Message> {
        content: Element<'a, Message>,
        keymap: Keymap<A>,
        on_action: Box<dyn Fn(A) -> Vec<Message> + 'a>,
        radius: f32,
        hold_keys: bool,
    }

    /// Captures every key `keymap` binds while `content` has keys, sending
    /// the messages `on_action` returns for the action. No messages is fine:
    /// the key is still the component's.
    pub(crate) fn keyed<'a, A, Message>(
        content: impl Into<Element<'a, Message>>,
        keymap: Keymap<A>,
        on_action: impl Fn(A) -> Vec<Message> + 'a,
    ) -> Keyed<'a, A, Message> {
        Keyed {
            content: content.into(),
            keymap,
            on_action: Box::new(on_action),
            radius: 0.0,
            hold_keys: false,
        }
    }

    impl<A, Message> Keyed<'_, A, Message> {
        /// Corner radius of the focus ring.
        pub(crate) fn radius(mut self, radius: f32) -> Self {
            self.radius = radius;
            self
        }

        /// Keeps key presses from the content, for widgets whose own keys
        /// would otherwise act without focus.
        #[cfg(feature = "slider")]
        pub(crate) fn hold_keys(mut self) -> Self {
            self.hold_keys = true;
            self
        }
    }

    impl<A: Clone, Message> Widget<Message, Theme, Renderer> for Keyed<'_, A, Message> {
        fn size(&self) -> Size<Length> {
            self.content.as_widget().size()
        }

        fn size_hint(&self) -> Size<Length> {
            self.content.as_widget().size_hint()
        }

        fn tag(&self) -> tree::Tag {
            tree::Tag::of::<Scope>()
        }

        fn state(&self) -> tree::State {
            tree::State::new(Scope::default())
        }

        fn children(&self) -> Vec<Tree> {
            vec![Tree::new(&self.content)]
        }

        fn diff(&self, tree: &mut Tree) {
            tree.diff_children(std::slice::from_ref(&self.content));
        }

        fn layout(
            &mut self,
            tree: &mut Tree,
            renderer: &Renderer,
            limits: &layout::Limits,
        ) -> layout::Node {
            self.content
                .as_widget_mut()
                .layout(&mut tree.children[0], renderer, limits)
        }

        fn draw(
            &self,
            tree: &Tree,
            renderer: &mut Renderer,
            theme: &Theme,
            style: &renderer::Style,
            layout: Layout<'_>,
            cursor: mouse::Cursor,
            viewport: &Rectangle,
        ) {
            self.content.as_widget().draw(
                &tree.children[0],
                renderer,
                theme,
                style,
                layout,
                cursor,
                viewport,
            );
            if tree.state.downcast_ref::<Scope>().is_focused() {
                draw_ring(renderer, theme, layout.bounds(), self.radius);
            }
        }

        fn operate(
            &mut self,
            tree: &mut Tree,
            layout: Layout<'_>,
            renderer: &Renderer,
            operation: &mut dyn Operation,
        ) {
            let scope = tree.state.downcast_mut::<Scope>();
            report(operation, None, layout.bounds(), scope);
            // Under icedwright the content nests under the focus report, so
            // the recorder folds the focus into the component's annotation.
            #[cfg(feature = "icedwright")]
            {
                let content = &mut self.content;
                let child = &mut tree.children[0];
                operation.traverse(&mut |operation| {
                    content
                        .as_widget_mut()
                        .operate(child, layout, renderer, operation);
                });
            }
            #[cfg(not(feature = "icedwright"))]
            self.content.as_widget_mut().operate(
                &mut tree.children[0],
                layout,
                renderer,
                operation,
            );
        }

        fn update(
            &mut self,
            tree: &mut Tree,
            event: &Event,
            layout: Layout<'_>,
            cursor: mouse::Cursor,
            renderer: &Renderer,
            clipboard: &mut dyn Clipboard,
            shell: &mut Shell<'_, Message>,
            viewport: &Rectangle,
        ) {
            let scope = tree.state.downcast_mut::<Scope>();
            if scope.update(event, cursor, layout.bounds()) {
                shell.request_redraw();
            }
            if let Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, .. }) = event {
                if scope.has_keys()
                    && !shell.is_event_captured()
                    && let Some(action) = self.keymap.resolve(key, *modifiers)
                {
                    for message in (self.on_action)(action) {
                        shell.publish(message);
                    }
                    shell.capture_event();
                    return;
                }
                if self.hold_keys {
                    return;
                }
            }
            self.content.as_widget_mut().update(
                &mut tree.children[0],
                event,
                layout,
                cursor,
                renderer,
                clipboard,
                shell,
                viewport,
            );
        }

        fn mouse_interaction(
            &self,
            tree: &Tree,
            layout: Layout<'_>,
            cursor: mouse::Cursor,
            viewport: &Rectangle,
            renderer: &Renderer,
        ) -> mouse::Interaction {
            self.content.as_widget().mouse_interaction(
                &tree.children[0],
                layout,
                cursor,
                viewport,
                renderer,
            )
        }

        fn overlay<'b>(
            &'b mut self,
            tree: &'b mut Tree,
            layout: Layout<'b>,
            renderer: &Renderer,
            viewport: &Rectangle,
            translation: Vector,
        ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
            self.content.as_widget_mut().overlay(
                &mut tree.children[0],
                layout,
                renderer,
                viewport,
                translation,
            )
        }
    }

    impl<'a, A: Clone + 'a, Message: 'a> From<Keyed<'a, A, Message>> for Element<'a, Message> {
        fn from(keyed: Keyed<'a, A, Message>) -> Self {
            Element::new(keyed)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use iced::advanced::widget::operation::Focusable;
    use iced::{Point, Size};

    fn area() -> Rectangle {
        Rectangle::new(Point::new(10.0, 10.0), Size::new(100.0, 20.0))
    }

    fn press() -> Event {
        Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
    }

    fn finger(position: Point) -> Event {
        Event::Touch(touch::Event::FingerPressed {
            id: touch::Finger(0),
            position,
        })
    }

    #[test]
    fn a_press_inside_gives_the_keys_and_one_outside_takes_them() {
        let mut scope = Scope::default();
        assert!(!scope.has_keys());
        let inside = mouse::Cursor::Available(Point::new(20.0, 20.0));
        let outside = mouse::Cursor::Available(Point::new(200.0, 20.0));

        assert!(scope.update(&press(), inside, area()));
        assert!(scope.has_keys());
        assert!(!scope.update(&press(), inside, area()), "already pressed");
        assert!(scope.update(&press(), outside, area()));
        assert!(!scope.has_keys());
    }

    #[test]
    fn fingers_count_by_where_they_land() {
        let mut scope = Scope::default();
        assert!(scope.update(
            &finger(Point::new(20.0, 20.0)),
            mouse::Cursor::Unavailable,
            area()
        ));
        assert!(scope.has_keys());
        assert!(scope.update(
            &finger(Point::new(20.0, 90.0)),
            mouse::Cursor::Unavailable,
            area()
        ));
        assert!(!scope.has_keys());
    }

    #[test]
    fn focus_gives_the_keys_until_any_press() {
        let mut scope = Scope::default();
        scope.focus();
        assert!(scope.is_focused());
        assert!(scope.has_keys());

        let moved = Event::Mouse(mouse::Event::CursorMoved {
            position: Point::ORIGIN,
        });
        assert!(!scope.update(&moved, mouse::Cursor::Unavailable, area()));
        assert!(scope.has_keys());

        let inside = mouse::Cursor::Available(Point::new(20.0, 20.0));
        assert!(scope.update(&press(), inside, area()));
        assert!(!scope.is_focused(), "a press never keeps focus");
        assert!(scope.has_keys(), "but a press inside keeps the keys");
    }
}