Newer
Older
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
use bevy::prelude::{Component, Entity, In, IntoSystem, System, World};
use std::fmt::{Debug, Formatter};
use std::sync::{Arc, RwLock};
use crate::layout::LayoutEvent;
/// A container for a function that handles layout
///
/// This differs from a standard [`Handler`](crate::Handler) in that it's sent directly
/// from the [`KayakContext`](crate::KayakContext) and gives the [`KayakContextRef`]
/// as a parameter.
#[derive(Component, Clone)]
pub struct OnLayout {
has_initialized: bool,
system: Arc<RwLock<dyn System<In = (LayoutEvent, Entity), Out = LayoutEvent>>>,
}
impl Default for OnLayout {
fn default() -> Self {
Self::new(|In((event, _entity))| event)
}
}
impl OnLayout {
/// Create a new layout handler
///
/// The handler should be a closure that takes the following arguments:
/// 1. The LayoutEvent
pub fn new<Params>(
system: impl IntoSystem<(LayoutEvent, Entity), LayoutEvent, Params>,
) -> Self {
Self {
has_initialized: false,
system: Arc::new(RwLock::new(IntoSystem::into_system(system))),
}
}
/// Call the layout event handler
///
/// Returns true if the handler was successfully invoked.
pub fn try_call(
&mut self,
entity: Entity,
mut event: LayoutEvent,
world: &mut World,
) -> LayoutEvent {
if let Ok(mut system) = self.system.try_write() {
if !self.has_initialized {
system.initialize(world);
self.has_initialized = true;
}
event = system.run((event, entity), world);
system.apply_deferred(world);
}
event
}
}
impl Debug for OnLayout {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("OnLayout").finish()
}
}
impl PartialEq for OnLayout {
fn eq(&self, _: &Self) -> bool {
// Never prevent "==" for being true because of this struct
true
}
}