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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
use super::{WorldInspectorParams, WorldUIContext};
use crate::Inspectable;
use bevy::{
    ecs::query::{Fetch, FilterFetch, WorldQuery},
    prelude::*,
};
use bevy_egui::egui::CollapsingHeader;
use std::marker::PhantomData;

impl Inspectable for World {
    type Attributes = WorldInspectorParams;

    fn ui(
        &mut self,
        ui: &mut bevy_egui::egui::Ui,
        mut options: Self::Attributes,
        context: &mut crate::Context,
    ) -> bool {
        let mut world_ui_ctx = WorldUIContext::new(self, context.ui_ctx);
        world_ui_ctx.world_ui::<()>(ui, &mut options)
    }
}

#[derive(Clone)]
/// Inspectable Attributes for `Entity`
pub struct EntityAttributes {
    /// Whether a button for despawning the entity should be shown
    pub despawnable: bool,
}
impl Default for EntityAttributes {
    fn default() -> Self {
        EntityAttributes { despawnable: true }
    }
}

impl Inspectable for Entity {
    type Attributes = EntityAttributes;

    fn ui(
        &mut self,
        ui: &mut bevy_egui::egui::Ui,
        options: Self::Attributes,
        context: &mut crate::Context,
    ) -> bool {
        unsafe {
            context.world_scope_unchecked(ui, "Entity", |world, ui, context| {
                let mut world_inspector_params =
                    world.get_resource_or_insert_with(WorldInspectorParams::default);
                let params =
                    std::mem::replace(&mut *world_inspector_params, WorldInspectorParams::empty());

                let mut world_ui_ctx = WorldUIContext::new(world, context.ui_ctx);
                let changed = ui
                    .vertical(|ui| {
                        world_ui_ctx.entity_ui_inner(ui, *self, &params, context.id(), &options)
                    })
                    .inner;
                drop(world_ui_ctx);

                *world.get_resource_mut::<WorldInspectorParams>().unwrap() = params;

                changed
            })
        }
    }
}

/// Executes [Queries](bevy::ecs::system::Query) and displays the result.
///
/// You can use any types and filters which are allowed in regular bevy queries,
/// however you may need to specify a `'static` lifetime since you can't elide them in structs.
///
/// ```rust,no_run
/// use bevy::prelude::*;
/// use bevy_inspector_egui::{Inspectable, InspectorPlugin};
/// use bevy_inspector_egui::widgets::InspectorQuery;
///
/// #[derive(Component)]
/// struct Collider;
///
/// #[derive(Inspectable, Default)]
/// struct Queries {
///   colliders: InspectorQuery<Entity, With<Collider>>,
///   root_entities: InspectorQuery<Entity, Without<Parent>>,
///   transforms: InspectorQuery<&'static mut Transform>,
/// }
///
/// fn main() {
///     App::new()
///         .add_plugins(DefaultPlugins)
///         .add_plugin(InspectorPlugin::<Queries>::new())
///         .run();
/// }
/// ```
pub struct InspectorQuery<Q, F = ()>(PhantomData<(Q, F)>);

impl<Q, F> Default for InspectorQuery<Q, F> {
    fn default() -> Self {
        InspectorQuery(PhantomData)
    }
}

type WorldQueryItem<'w, 's, Q> = <<Q as WorldQuery>::Fetch as Fetch<'w, 's>>::Item;

unsafe fn extend_lifetime<'w, 's, Q>(
    item: &<WorldQueryItem<'static, 'static, Q> as Inspectable>::Attributes,
) -> <WorldQueryItem<'w, 's, Q> as Inspectable>::Attributes
where
    Q: WorldQuery,
    for<'world, 'state> WorldQueryItem<'world, 'state, Q>: Inspectable,
{
    std::mem::transmute_copy(item)
}

impl<Q: 'static, F: 'static> Inspectable for InspectorQuery<Q, F>
where
    Q: WorldQuery,
    F: WorldQuery,
    F::Fetch: FilterFetch,
    for<'w, 's> WorldQueryItem<'w, 's, Q>: Inspectable,
{
    type Attributes = <WorldQueryItem<'static, 'static, Q> as Inspectable>::Attributes;

    fn ui(
        &mut self,
        ui: &mut bevy_egui::egui::Ui,
        options: Self::Attributes,
        context: &mut crate::Context,
    ) -> bool {
        unsafe {
            context.world_scope_unchecked(ui, "InspectorQuery", |world, ui, context| {
                let mut changed = false;

                ui.vertical(move |ui| {
                    let mut query_state = world.query_filtered::<Q, F>();

                    for (i, mut value) in query_state.iter_mut(world).enumerate() {
                        let name = pretty_type_name::pretty_type_name::<Q>();
                        CollapsingHeader::new(name)
                            .id_source(context.id().with(i))
                            .show(ui, |ui| {
                                let options = extend_lifetime::<Q>(&options);
                                changed |= value.ui(ui, options, &mut context.with_id(i as u64));
                            });
                    }
                });

                changed
            })
        }
    }
}

/// Executes [Queries](bevy::ecs::system::Query) and displays the only result.
///
/// You can use any types and filters which are allowed in regular bevy queries,
/// however you may need to specify a `'static` lifetime since you can't elide them in structs.
///
/// ```rust,no_run
/// use bevy::prelude::*;
/// use bevy_inspector_egui::{Inspectable, InspectorPlugin};
/// use bevy_inspector_egui::widgets::InspectorQuerySingle;
///
/// #[derive(Component)]
/// struct Player;
///
/// #[derive(Inspectable, Default)]
/// struct Queries {
///   player: InspectorQuerySingle<Entity, With<Player>>
/// }
///
/// fn main() {
///     App::new()
///         .add_plugins(DefaultPlugins)
///         .add_plugin(InspectorPlugin::<Queries>::new())
///         .run();
/// }
/// ```
pub struct InspectorQuerySingle<Q, F = ()>(PhantomData<(Q, F)>);

impl<Q, F> Default for InspectorQuerySingle<Q, F> {
    fn default() -> Self {
        InspectorQuerySingle(PhantomData)
    }
}

impl<Q, F> Inspectable for InspectorQuerySingle<Q, F>
where
    Q: WorldQuery + 'static,
    F: WorldQuery + 'static,
    F::Fetch: FilterFetch,
    for<'w, 's> WorldQueryItem<'w, 's, Q>: Inspectable,
{
    type Attributes = <WorldQueryItem<'static, 'static, Q> as Inspectable>::Attributes;

    fn ui(
        &mut self,
        ui: &mut bevy_egui::egui::Ui,
        options: Self::Attributes,
        context: &mut crate::Context,
    ) -> bool {
        unsafe {
            context.world_scope_unchecked(ui, "InspectorQuerySingle", |world, ui, context| {
                let mut changed = false;
                ui.vertical(move |ui| {
                    let mut query_state = world.query_filtered::<Q, F>();
                    let mut iter = query_state.iter_mut(world);
                    let value = iter.next();
                    let has_more = iter.next().is_some();

                    match (value, has_more) {
                        (None, _) => {
                            ui.label("No entity matches the query.");
                        }
                        (Some(_), true) => {
                            ui.label("More than one entity matches the query.");
                        }
                        (Some(mut value), false) => {
                            let name = pretty_type_name::pretty_type_name::<Q>();
                            CollapsingHeader::new(name)
                                .id_source(context.id())
                                .show(ui, |ui| {
                                    let options = extend_lifetime::<Q>(&options);
                                    changed |= value.ui(ui, options, context);
                                });
                        }
                    };
                });

                changed
            })
        }
    }
}