1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
//! This module implement entity selection / focusing based on user
//! interactions and events.

use bevy::{
    ecs::{
        query::{QueryData, QueryFilter, QueryItem},
        system::SystemParam,
    },
    prelude::*,
    ui::UiSystem,
};

pub(crate) struct FocusPlugin;

impl Plugin for FocusPlugin {
    fn build(&self, app: &mut App) {
        app.init_resource::<UiFocus>()
            .add_event::<SetFocusEvent>()
            .add_systems(PreUpdate, focus_system.after(UiSystem::Focus));
    }
}

/// Send this event to (de)select an entity.
#[derive(Event)]
pub struct SetFocusEvent(Option<Entity>);

impl SetFocusEvent {
    pub fn some(entity: Entity) -> Self {
        Self(Some(entity))
    }
}

/// This system parameter implements the query of selected / focused UI
/// entities.
///
/// An entity can be (de)selected / (de)focused by multiple means:
///
/// * Selected via [`Interaction::Pressed`].
/// * (De)selected via [`SetFocusEvent`].
/// * Deselected by despawning.
/// * Deselected by clicking outside of it.
#[derive(SystemParam)]
pub(super) struct FocusedQuery<'w, 's, Q, F = ()>
where
    Q: QueryData + Sync + Send + 'static,
    F: QueryFilter + Sync + Send + 'static,
{
    focus: Res<'w, UiFocus>,
    query: Query<'w, 's, Q, F>,
}

impl<'w, 's, Q, F> FocusedQuery<'w, 's, Q, F>
where
    Q: QueryData + Sync + Send + 'static,
    F: QueryFilter + Sync + Send + 'static,
{
    pub(super) fn is_changed(&self) -> bool {
        self.focus.is_changed()
    }

    /// Returns the query item for previously selected entity, id est the
    /// entity selected before the current one.
    pub(super) fn get_previous_mut(&mut self) -> Option<QueryItem<'_, Q>> {
        self.get_mut(self.focus.previous)
    }

    /// Returns the query item for currently selected entity.
    pub(super) fn get_current_mut(&mut self) -> Option<QueryItem<'_, Q>> {
        self.get_mut(self.focus.current)
    }

    fn get_mut(&mut self, entity: Option<Entity>) -> Option<QueryItem<'_, Q>> {
        match entity {
            Some(entity) => match self.query.get_mut(entity) {
                Ok(item) => Some(item),
                Err(_) => None,
            },
            None => None,
        }
    }
}

#[derive(Resource, Default)]
pub(super) struct UiFocus {
    previous: Option<Entity>,
    current: Option<Entity>,
}

fn focus_system(
    mut focus: ResMut<UiFocus>,
    mut removals: RemovedComponents<Interaction>,
    mouse: Res<ButtonInput<MouseButton>>,
    touch: Res<Touches>,
    interactions: Query<(Entity, &Interaction), Changed<Interaction>>,
    mut events: EventReader<SetFocusEvent>,
) {
    let mut current = focus.current;

    if let Some(current_entity) = current {
        if removals.read().any(|e| e == current_entity) {
            current = None;
        }
    }

    if mouse.just_pressed(MouseButton::Left) || touch.any_just_pressed() {
        current = None;
    }

    for (entity, &interaction) in interactions.iter() {
        if matches!(interaction, Interaction::Pressed) {
            current = Some(entity);
        }
    }

    if let Some(event) = events.read().last() {
        current = event.0;
    }

    // do not when unnecessarily trigger change detection
    if focus.current != current {
        focus.previous = focus.current;
        focus.current = current;
    }

    if let Some(previous_entity) = focus.previous {
        if removals.read().any(|e| e == previous_entity) {
            focus.previous = None;
        }
    }
}