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
//local shortcuts
use crate::prelude::*;

//third-party shortcuts
use bevy::prelude::*;

//standard shortcuts


//-------------------------------------------------------------------------------------------------------------------

/// Records a cleanup callback that can be injected into system commands for cleanup after the system command
/// runs but before its `apply_deferred` is called.
///
/// For efficiency, only function pointer callbacks are supported.
#[derive(Debug, Default, Copy, Clone)]
pub struct SystemCommandCleanup
{
    cleanup: Option<fn(&mut World)>,
}

impl SystemCommandCleanup
{
    /// Makes a new system cleanup.
    pub fn new(cleanup: fn(&mut World)) -> Self
    {
        Self{ cleanup: Some(cleanup) }
    }

    /// Runs the system cleanup on the world.
    ///
    /// Does nothing if no callback is stored.
    pub(crate) fn run(self, world: &mut World)
    {
        let Some(cleanup) = self.cleanup else { return; };
        (cleanup)(world);
    }
}

//-------------------------------------------------------------------------------------------------------------------

/// Owns a system command callback.
///
/// The callback should own the actual system that you want to run. The [`SystemCommandCleanup`] callback must be invoked
/// between running your system and calling `apply_deferred` on that system.
//todo: wrap the callback in a trait that lets you reassign the injected callback if it is the same type
pub struct SystemCommandCallback
{
    inner: Box<dyn FnMut(&mut World, SystemCommandCleanup) + Send + Sync + 'static>,
}

impl SystemCommandCallback
{
    /// Makes a new system command callback from a system.
    pub fn new<S, M>(system: S) -> Self
    where
        S: IntoSystem<(), (), M> + Send + Sync + 'static
    {
        let mut callback = CallbackSystem::new(system);
        let command = move |world: &mut World, cleanup: SystemCommandCleanup|
        {
            callback.run_with_cleanup(world, (), move |world: &mut World| cleanup.run(world));
        };
        Self::with(command)
    }

    /// Makes a new system command callback from a pre-defined callback.
    pub fn with(callback: impl FnMut(&mut World, SystemCommandCleanup) + Send + Sync + 'static) -> Self
    {
        Self{ inner: Box::new(callback) }
    }

    /// Runs the system command callback.
    ///
    /// The `cleanup` should be invoked between running the callback's inner system and
    /// calling `apply_deferred` on the inner system.
    pub(crate) fn run(&mut self, world: &mut World, cleanup: SystemCommandCleanup)
    {
        (self.inner)(world, cleanup);
    }
}

//-------------------------------------------------------------------------------------------------------------------

/// Stores a system command's callback.
///
/// We store the callback in an option in order to avoid archetype moves when taking/reinserting the callback in order to
/// call it.
#[derive(Component)]
pub(crate) struct SystemCommandStorage
{
    callback: Option<SystemCommandCallback>,
}

impl SystemCommandStorage
{
    pub(crate) fn new(callback: SystemCommandCallback) -> Self
    {
        Self{ callback: Some(callback) }
    }

    pub(crate) fn insert(&mut self, callback: SystemCommandCallback)
    {
        self.callback = Some(callback);
    }

    pub(crate) fn take(&mut self) -> Option<SystemCommandCallback>
    {
        self.callback.take()
    }
}

//-------------------------------------------------------------------------------------------------------------------

/// Spawns a system as a [`SystemCommand`].
///
/// Systems are not initialized until they are first run.
pub fn spawn_system_command<S, M>(world: &mut World, system: S) -> SystemCommand
where
    S: IntoSystem<(), (), M> + Send + Sync + 'static,
{
    spawn_system_command_from(world, SystemCommandCallback::new(system))
}

//-------------------------------------------------------------------------------------------------------------------

/// Spawns a [`SystemCommand`] from a pre-defined callback.
pub fn spawn_system_command_from(world: &mut World, callback: SystemCommandCallback) -> SystemCommand
{
    SystemCommand(world.spawn(SystemCommandStorage::new(callback)).id())
}

//-------------------------------------------------------------------------------------------------------------------

//todo: allow overwriting an existing command's callback

//-------------------------------------------------------------------------------------------------------------------

/// Spawns a ref-counted [`SystemCommand`] from a given raw system.
///
/// Systems are not initialized until they are first run.
///
/// Returns a cleanup handle. The system will be dropped when the last copy of the handle is dropped.
///
/// Panics if [`setup_auto_despawn()`](AutoDespawnAppExt::setup_auto_despawn) was not added to your app.
pub fn spawn_rc_system_command<S, M>(world: &mut World, system: S) -> AutoDespawnSignal
where
    S: IntoSystem<(), (), M> + Send + Sync + 'static,
{
    let system_command = spawn_system_command(world, system);
    world.resource::<AutoDespawner>().prepare(*system_command)
}

//-------------------------------------------------------------------------------------------------------------------

/// Spawns a ref-counted [`SystemCommand`] from a pre-defined callback.
///
/// Returns a cleanup handle. The system will be dropped when the last copy of the handle is dropped.
///
/// Panics if [`setup_auto_despawn()`](AutoDespawnAppExt::setup_auto_despawn) was not added to your app.
pub fn spawn_rc_system_command_from(world: &mut World, callback: SystemCommandCallback) -> AutoDespawnSignal
{
    let system_command = spawn_system_command_from(world, callback);
    world.resource::<AutoDespawner>().prepare(*system_command)
}

//-------------------------------------------------------------------------------------------------------------------