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
use crate::{Context, Inspectable};
use bevy::app::Events;
use bevy::prelude::*;
use std::marker::PhantomData;

#[allow(missing_docs)]
#[derive(Clone)]
pub struct ButtonAttributes {
    pub text: String,
}
impl Default for ButtonAttributes {
    fn default() -> Self {
        ButtonAttributes {
            text: "Button".to_string(),
        }
    }
}

#[derive(Default)]
/// Button in the inspector. When clicking, the event `E::Default` will be sent.
///
/// Can be configured via `#[inspectable(text = "Button text")]`.
pub struct InspectableButton<E>(PhantomData<E>);
impl<E> InspectableButton<E> {
    /// Create a new `InspectableButton`
    pub fn new() -> Self {
        InspectableButton(PhantomData)
    }
}

impl<E> std::fmt::Debug for InspectableButton<E> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("InspectableButton").finish()
    }
}

impl<E: Send + Sync + 'static + Default> Inspectable for InspectableButton<E> {
    type Attributes = ButtonAttributes;

    fn ui(
        &mut self,
        ui: &mut bevy_egui::egui::Ui,
        options: Self::Attributes,
        context: &mut Context,
    ) -> bool {
        context.resource_scope(
            ui,
            "InspectableButton<E>",
            |ui, _, mut events: Mut<Events<E>>| {
                if ui.button(options.text).clicked() {
                    events.send(E::default());
                }
                false
            },
        )
    }

    fn setup(app: &mut App) {
        if !app.world.contains_resource::<Events<E>>() {
            app.add_event::<E>();
        }
    }
}