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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
#![doc=include_str!("../README.md")]
#![allow(clippy::type_complexity)]
use bevy_app::{App, First, Plugin, PostUpdate, PreUpdate, Update};
use bevy_ecs::component::Component;
use bevy_ecs::event::Event;
use bevy_ecs::schedule::States;
use bevy_time::TimeSystem;
use bevy_utils::intern::Interned;
use std::pin::Pin;

pub mod access;
pub mod async_systems;
pub mod cancellation;
mod commands;
mod entity_commands;
mod errors;
mod executor;
pub mod ext;
mod queue;
pub mod reactors;
pub mod signals;
pub mod sync;
pub mod tween;
#[allow(deprecated)]
pub use crate::executor::world;
#[allow(deprecated)]
pub use crate::executor::{in_async_context, spawn, spawn_scoped};
pub use access::async_event::EventBuffer;
pub use access::async_query::OwnedQueryState;
pub use access::traits::AsyncAccess;
pub use access::AsyncWorld;
use bevy_ecs::{
    schedule::{IntoSystemConfigs, ScheduleLabel, SystemSet},
    system::{Command, Commands},
    world::World,
};
use bevy_reflect::std_traits::ReflectDefault;
pub use errors::{AccessError, CustomError, MessageError};
pub use executor::AsyncExecutor;
pub use queue::QueryQueue;
use reactors::Reactors;

pub mod systems {
    //! Systems in `bevy_defer`.
    //!
    //! Systems named `react_to_*` must be added manually.
    pub use crate::access::async_event::react_to_event;
    pub use crate::async_systems::push_async_systems;
    pub use crate::executor::run_async_executor;
    pub use crate::queue::{run_fixed_queue, run_time_series, run_watch_queries};
    pub use crate::reactors::{react_to_component_change, react_to_state};

    #[cfg(feature = "bevy_animation")]
    pub use crate::ext::anim::react_to_animation;
    #[cfg(feature = "bevy_ui")]
    pub use crate::ext::picking::react_to_ui;
    #[cfg(feature = "bevy_scene")]
    pub use crate::ext::scene::react_to_scene_load;
}

pub use crate::sync::oneshot::channel;
use std::future::Future;

pub(crate) static CHANNEL_CLOSED: &str = "channel closed unexpectedly";

#[doc(hidden)]
pub use bevy_ecs::entity::Entity;
#[doc(hidden)]
pub use bevy_ecs::system::{NonSend, Res, SystemParam};
#[doc(hidden)]
pub use bevy_log::error;
#[doc(hidden)]
pub use ref_cast::RefCast;

use queue::run_fixed_queue;
use signals::{Signal, SignalId, Signals};

#[cfg(feature = "derive")]
pub use bevy_defer_derive::async_access;

/// Deprecated access error.
#[deprecated = "Use AccessError instead."]
pub type AsyncFailure = AccessError;

/// Deprecated access result.
#[deprecated = "Use AccessResult instead."]
pub type AsyncResult<T = ()> = Result<T, AccessError>;

/// Result type of spawned tasks.
pub type AccessResult<T = ()> = Result<T, AccessError>;

#[derive(Debug, Default, Clone, Copy)]

/// The core `bevy_defer` plugin that does not run its executors.
///
/// You should almost always use [`AsyncPlugin::empty`] or [`AsyncPlugin::default_settings`] instead.
pub struct CoreAsyncPlugin;

impl Plugin for CoreAsyncPlugin {
    fn build(&self, app: &mut App) {
        app.init_non_send_resource::<QueryQueue>()
            .init_non_send_resource::<AsyncExecutor>()
            .init_resource::<Reactors>()
            .register_type::<async_systems::AsyncSystems>()
            .register_type_data::<async_systems::AsyncSystems, ReflectDefault>()
            .register_type::<Signals>()
            .register_type_data::<Signals, ReflectDefault>()
            .init_schedule(BeforeAsyncExecutor)
            .add_systems(First, systems::run_time_series.after(TimeSystem))
            .add_systems(First, systems::push_async_systems)
            .add_systems(Update, run_fixed_queue)
            .add_systems(BeforeAsyncExecutor, systems::run_watch_queries);

        #[cfg(feature = "bevy_scene")]
        app.add_systems(BeforeAsyncExecutor, systems::react_to_scene_load);
        #[cfg(feature = "bevy_ui")]
        app.add_systems(BeforeAsyncExecutor, systems::react_to_ui);
        #[cfg(feature = "bevy_animation")]
        app.add_systems(BeforeAsyncExecutor, systems::react_to_animation);
    }
}

/// A schedule that runs before [`run_async_executor`](systems::run_async_executor).
///
/// By default this runs `watch` queries and reactors.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, ScheduleLabel)]
pub struct BeforeAsyncExecutor;

/// Runs the [`BeforeAsyncExecutor`] schedule.
///
/// By default this runs `watch` queries and reactors.
pub fn run_before_async_executor(world: &mut World) {
    world.run_schedule(BeforeAsyncExecutor)
}

/// An `bevy_defer` plugin that can run the executor through user configuration.
///
/// This plugin is not unique and can be used repeatedly to add runs.
#[derive(Debug)]
pub struct AsyncPlugin {
    schedules: Vec<(Interned<dyn ScheduleLabel>, Option<Interned<dyn SystemSet>>)>,
}

impl AsyncPlugin {
    /// Equivalent to [`CoreAsyncPlugin`].
    ///
    /// Use [`AsyncPlugin::run_in`] and [`AsyncPlugin::run_in_set`] to add runs.
    pub fn empty() -> Self {
        AsyncPlugin {
            schedules: Vec::new(),
        }
    }

    /// Run in [`Update`] once.
    ///
    /// This is usually enough, be sure to order your
    /// systems against [`run_async_executor`](systems::run_async_executor) correctly if needed.
    pub fn default_settings() -> Self {
        AsyncPlugin {
            schedules: vec![(Interned(Box::leak(Box::new(Update))), None)],
        }
    }

    /// Run in [`PreUpdate`], [`Update`] and [`PostUpdate`].
    pub fn busy_schedule() -> Self {
        AsyncPlugin {
            schedules: vec![
                (Interned(Box::leak(Box::new(PreUpdate))), None),
                (Interned(Box::leak(Box::new(Update))), None),
                (Interned(Box::leak(Box::new(PostUpdate))), None),
            ],
        }
    }
}

impl AsyncPlugin {
    /// Run the executor in a specific `Schedule`.
    pub fn run_in(mut self, schedule: impl ScheduleLabel) -> Self {
        self.schedules
            .push((Interned(Box::leak(Box::new(schedule))), None));
        self
    }

    /// Run the executor in a specific `Schedule` and `SystemSet`.
    pub fn run_in_set(mut self, schedule: impl ScheduleLabel, set: impl SystemSet) -> Self {
        self.schedules.push((
            Interned(Box::leak(Box::new(schedule))),
            Some(Interned(Box::leak(Box::new(set)))),
        ));
        self
    }
}

impl Plugin for AsyncPlugin {
    fn build(&self, app: &mut App) {
        use crate::systems::*;
        if !app.is_plugin_added::<CoreAsyncPlugin>() {
            app.add_plugins(CoreAsyncPlugin);
        }
        for (schedule, set) in &self.schedules {
            if let Some(set) = set {
                app.add_systems(
                    *schedule,
                    (
                        run_before_async_executor.before(run_async_executor),
                        run_async_executor,
                    )
                        .in_set(*set),
                );
            } else {
                app.add_systems(
                    *schedule,
                    (
                        run_before_async_executor.before(run_async_executor),
                        run_async_executor,
                    ),
                );
            }
        }
    }

    fn is_unique(&self) -> bool {
        false
    }
}

/// Extension for [`World`] and [`App`].
pub trait AsyncExtension {
    /// Spawn a task to be run on the [`AsyncExecutor`].
    fn spawn_task(&mut self, f: impl Future<Output = AccessResult> + 'static) -> &mut Self;

    /// Obtain a named signal.
    fn typed_signal<T: SignalId>(&mut self) -> Signal<T::Data>;

    /// Obtain a named signal.
    fn named_signal<T: SignalId>(&mut self, name: &str) -> Signal<T::Data>;
}

impl AsyncExtension for World {
    fn spawn_task(&mut self, f: impl Future<Output = AccessResult> + 'static) -> &mut Self {
        self.non_send_resource::<AsyncExecutor>().spawn(async move {
            match f.await {
                Ok(()) => (),
                Err(err) => error!("Async Failure: {err}."),
            }
        });
        self
    }

    fn typed_signal<T: SignalId>(&mut self) -> Signal<T::Data> {
        self.get_resource_or_insert_with::<Reactors>(Default::default)
            .get_typed::<T>()
    }

    fn named_signal<T: SignalId>(&mut self, name: &str) -> Signal<T::Data> {
        self.get_resource_or_insert_with::<Reactors>(Default::default)
            .get_named::<T>(name)
    }
}

impl AsyncExtension for App {
    fn spawn_task(&mut self, f: impl Future<Output = AccessResult> + 'static) -> &mut Self {
        self.world
            .non_send_resource::<AsyncExecutor>()
            .spawn(async move {
                match f.await {
                    Ok(()) => (),
                    Err(err) => error!("Async Failure: {err}."),
                }
            });
        self
    }

    fn typed_signal<T: SignalId>(&mut self) -> Signal<T::Data> {
        self.world
            .get_resource_or_insert_with::<Reactors>(Default::default)
            .get_typed::<T>()
    }

    fn named_signal<T: SignalId>(&mut self, name: &str) -> Signal<T::Data> {
        self.world
            .get_resource_or_insert_with::<Reactors>(Default::default)
            .get_named::<T>(name)
    }
}

/// Extension for [`App`] to add reactors.
pub trait AppReactorExtension {
    /// React to changes in a [`Event`].
    fn react_to_event<E: Event + Clone>(&mut self) -> &mut Self;

    /// React to changes in a [`States`].
    fn react_to_state<S: States + Default>(&mut self) -> &mut Self;

    /// React to changes in a [`Component`].
    fn react_to_component_change<C: Component + Eq + Clone + Default>(&mut self) -> &mut Self;
}

impl AppReactorExtension for App {
    fn react_to_event<E: Event + Clone>(&mut self) -> &mut Self {
        self.add_systems(BeforeAsyncExecutor, systems::react_to_event::<E>);
        self
    }

    fn react_to_state<S: States + Default>(&mut self) -> &mut Self {
        self.add_systems(BeforeAsyncExecutor, systems::react_to_state::<S>);
        self
    }

    fn react_to_component_change<C: Component + Eq + Clone + Default>(&mut self) -> &mut Self {
        self.add_systems(BeforeAsyncExecutor, systems::react_to_component_change::<C>);
        self
    }
}

/// Extension for [`Commands`].
pub trait AsyncCommandsExtension {
    /// Spawn a task to be run on the [`AsyncExecutor`].
    fn spawn_task<F: Future<Output = AccessResult> + 'static>(
        &mut self,
        f: impl FnOnce() -> F + Send + 'static,
    ) -> &mut Self;
}

impl AsyncCommandsExtension for Commands<'_, '_> {
    fn spawn_task<F: Future<Output = AccessResult> + 'static>(
        &mut self,
        f: impl (FnOnce() -> F) + Send + 'static,
    ) -> &mut Self {
        self.add(SpawnFn::new(f));
        self
    }
}

/// [`Command`] for spawning a task.
pub struct SpawnFn(
    Box<dyn (FnOnce() -> Pin<Box<dyn Future<Output = AccessResult>>>) + Send + 'static>,
);

impl SpawnFn {
    fn new<F: Future<Output = AccessResult> + 'static>(
        f: impl (FnOnce() -> F) + Send + 'static,
    ) -> Self {
        Self(Box::new(move || Box::pin(f())))
    }
}

impl Command for SpawnFn {
    fn apply(self, world: &mut World) {
        world.spawn_task(self.0());
    }
}

#[doc(hidden)]
#[allow(unused)]
#[macro_export]
macro_rules! test_spawn {
    ($expr: expr) => {{
        use ::bevy::prelude::*;
        use ::bevy_defer::access::*;
        use ::bevy_defer::*;
        #[derive(Debug, Clone, Copy, Component, Resource, Event, Asset, TypePath)]
        pub struct Int(i32);

        #[derive(Debug, Clone, Copy, Component, Resource, Event, Asset, TypePath)]
        pub struct Str(&'static str);

        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, States)]
        pub enum MyState {
            A,
            B,
            C,
        };

        let mut app = ::bevy::app::App::new();
        app.add_plugins(MinimalPlugins);
        app.add_plugins(AssetPlugin::default());
        app.init_asset::<Image>();
        app.add_plugins(bevy_defer::AsyncPlugin::default_settings());
        app.world.spawn(Int(4));
        app.world.spawn(Str("Ferris"));
        app.insert_resource(Int(4));
        app.insert_resource(Str("Ferris"));
        app.insert_non_send_resource(Int(4));
        app.insert_non_send_resource(Str("Ferris"));
        app.insert_state(MyState::A);
        app.spawn_task(async move {
            $expr;
            AsyncWorld.quit();
            Ok(())
        });
        app.run();
    }};
}