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
use crate::base::*;
use alloc::boxed::Box;
use components_arena::{Component, ComponentId, Id, Arena, RawId, NewtypeComponentId};
use core::fmt::Debug;
use downcast_rs::{Downcast, impl_downcast};
use dyn_clone::{DynClone, clone_trait_object};
use dyn_context::state::{SelfState, State, StateExt};
use educe::Educe;
use macro_attr_2018::macro_attr;
use phantom_type::PhantomType;
pub trait Target<T: Convenient>: Debug + DynClone {
    fn execute(&self, state: &mut dyn State, value: T);
    fn clear(&self, state: &mut dyn State);
}
clone_trait_object!(<T: Convenient> Target<T>);
pub trait AnyHandler: Debug {
    fn clear(&self, state: &mut dyn State);
}
pub trait Handler<T: Convenient>: Debug + DynClone + Send + Sync {
    fn into_any(self: Box<Self>) -> Box<dyn AnyHandler>;
    fn execute(&self, state: &mut dyn State, value: T);
}
clone_trait_object!(<T: Convenient> Handler<T>);
#[derive(Educe)]
#[educe(Debug, Clone)]
pub struct FnTarget<Context: Debug + Clone, T: Convenient> {
    context: Context,
    #[educe(Debug(ignore))]
    execute: fn(state: &mut dyn State, context: Context, value: T)
}
impl<Context: Debug + Clone, T: Convenient> Target<T> for FnTarget<Context, T> {
    fn execute(&self, state: &mut dyn State, value: T) {
        (self.execute)(state, self.context.clone(), value);
    }
    fn clear(&self, _state: &mut dyn State) { }
}
pub trait Source<T: Convenient>: Debug {
    fn handle(&self, state: &mut dyn State, handler: Box<dyn Handler<T>>) -> HandledSource<T>;
}
pub trait HandlerId: Debug {
    fn unhandle(&self, state: &mut dyn State);
}
#[derive(Debug)]
pub struct HandledSource<T: Convenient> {
    pub handler_id: Box<dyn HandlerId>,
    pub value: T,
}
trait AnyBindingNode: Debug + Downcast {
    fn unhandle_sources_and_clear_target(&mut self, state: &mut dyn State);
}
impl_downcast!(AnyBindingNode);
macro_attr! {
    #[doc(hidden)]
    #[derive(Debug, Component!)]
    pub struct BoxedBindingNode(Box<dyn AnyBindingNode>);
}
#[derive(Debug)]
pub struct Bindings(Arena<BoxedBindingNode>);
impl SelfState for Bindings { }
impl Bindings {
    pub const fn new() -> Self { Bindings(Arena::new()) }
}
impl Drop for Bindings {
    fn drop(&mut self) {
        debug_assert!(self.0.items().is_empty(), "there are non-dropped bindings (count: {})", self.0.items().len());
    }
}
trait AnyBindingNodeSources: Debug + Downcast {
    type Value: Convenient;
    fn unhandle(&mut self, state: &mut dyn State);
    fn get_value(&self) -> Option<Self::Value>;
}
impl_downcast!(AnyBindingNodeSources assoc Value where Value: Convenient);
#[derive(Educe)]
#[educe(Debug)]
struct BindingNode<T: Convenient> {
    sources: Box<dyn AnyBindingNodeSources<Value=T>>,
    target: Option<Box<dyn Target<T>>>,
}
impl<T: Convenient> AnyBindingNode for BindingNode<T> {
    fn unhandle_sources_and_clear_target(&mut self, state: &mut dyn State) {
        self.sources.unhandle(state);
        self.target.as_ref().map(|x| x.clear(state));
    }
}
macro_attr! {
    #[derive(Educe, NewtypeComponentId!)]
    #[educe(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
    pub struct AnyBinding(Id<BoxedBindingNode>);
}
impl AnyBinding {
    pub fn drop_binding(self, state: &mut dyn State) {
        let bindings: &mut Bindings = state.get_mut();
        let mut node = bindings.0.remove(self.0);
        node.0.unhandle_sources_and_clear_target(state);
    }
}
macro_attr! {
    #[derive(Educe, NewtypeComponentId!)]
    #[educe(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
    pub struct Binding<T: Convenient>(Id<BoxedBindingNode>, PhantomType<T>);
}
impl<T: Convenient> Binding<T> {
    pub fn set_target(self, state: &mut dyn State, target: Box<dyn Target<T>>) {
        let bindings: &mut Bindings = state.get_mut();
        let node = bindings.0[self.0].0.downcast_mut::<BindingNode<T>>().unwrap();
        node.target = Some(target);
        self.knoke_target(state);
    }
    pub fn set_target_fn<Context: Debug + Clone + 'static>(
        self,
        state: &mut dyn State,
        context: Context,
        execute: fn(state: &mut dyn State, context: Context, value: T)
    ) {
        self.set_target(state, Box::new(FnTarget { context, execute }));
    }
    pub fn drop_binding(self, state: &mut dyn State) {
        let bindings: &mut Bindings = state.get_mut();
        let node = bindings.0.remove(self.0);
        let mut node = node.0.downcast::<BindingNode<T>>().unwrap();
        node.unhandle_sources_and_clear_target(state);
    }
    pub fn get_value(self, state: &dyn State) -> Option<T> {
        let bindings: &Bindings = state.get();
        let node = bindings.0[self.0].0.downcast_ref::<BindingNode<T>>().unwrap();
        node.sources.get_value()
    }
    fn knoke_target(self, state: &mut dyn State) {
        let bindings: &Bindings = state.get();
        let node = bindings.0[self.0].0.downcast_ref::<BindingNode<T>>().unwrap();
        if let Some(value) = node.sources.get_value() {
            if let Some(target) = node.target.clone() {
                target.execute(state, value);
            }
        }
    }
}
impl<T: Convenient> From<Binding<T>> for AnyBinding {
    fn from(v: Binding<T>) -> AnyBinding {
        AnyBinding(v.0)
    }
}
macro_rules! binding_n {
    ($n:tt; $($i:tt),+ $(,)?) => {
        binding_n! { @unwrap [] [$n] [$($i)+] [$($i)+] }
    };
    (@unwrap [$($r:tt)*] [$n:tt] [] [$($j:tt)+]) => {
        binding_n! { @done [$n] $($r)* }
    };
    (@unwrap [$($r:tt)*] [$n:tt] [$i0:tt $($i:tt)*] [$($j:tt)+]) => {
        binding_n! { @unwrap [$($r)* [$i0 $($j)+]] [$n] [$($i)*] [$($j)+] }
    };
    (@unwrap $($x:tt)*) => {
        compile_error!(stringify! { $($x)* });
    };
    (@done [$n:tt] $([$i:tt $($j:tt)+])+) => {
        $crate::paste_paste! {
            #[derive(Educe)]
            #[educe(Debug)]
            struct [< Binding $n NodeSources >] < $( [< S $i >] : Convenient, )+ T: Convenient> {
                $(
                    [< source_ $i >] : Option<HandledSource< [< S $i >] >>,
                )+
                #[educe(Debug(ignore))]
                filter_map: fn( $( [< S $i >] ),+ ) -> Option<T>,
            }
            impl<
                $( [< S $i >] : Convenient, )+
                T: Convenient
            > AnyBindingNodeSources for [< Binding $n NodeSources >] <$( [< S $i >] , )+ T> {
                type Value = T;
                fn unhandle(&mut self, state: &mut dyn State) {
                    $(
                        if let Some(source) = self. [< source_ $i >] .take() {
                            source.handler_id.unhandle(state);
                        }
                    )+
                }
                fn get_value(&self) -> Option<T> {
                    $(
                        let [< value_ $i >] ;
                        if let Some(source) = self. [< source_ $i >] .as_ref() {
                            [< value_ $i >] = source.value.clone();
                        } else {
                            return None;
                        }
                    )+
                    (self.filter_map)($( [< value_ $i >] ),+)
                }
            }
            macro_attr! {
                #[derive(Educe, NewtypeComponentId!)]
                #[educe(Debug, Eq, PartialEq, Copy, Clone, Ord, PartialOrd, Hash)]
                pub struct [< Binding $n >] < $( [< S $i >] : Convenient, )+ T: Convenient>(
                    Id<BoxedBindingNode>,
                    PhantomType<($( [< S $i >] ),+ , T)>
                );
            }
            impl<
                $( [< S $i >] : Convenient, )+
                T: Convenient
            > [< Binding $n >] < $( [< S $i >] , )+ T> {
                pub fn new(
                    state: &mut dyn State,
                    filter_map: fn( $( [< S $i >] ),+ ) -> Option<T>
                ) -> Self {
                    let bindings: &mut Bindings = state.get_mut();
                    let id = bindings.0.insert(|id| {
                        let sources: [< Binding $n NodeSources >] <$( [< S $i >] ),+ , T> = [< Binding $n NodeSources >] {
                            $(
                                [< source_ $i >] : None,
                            )+
                            filter_map,
                        };
                        let node: BindingNode<T> = BindingNode {
                            sources: Box::new(sources),
                            target: None,
                        };
                        (BoxedBindingNode(Box::new(node)), id)
                    });
                    [< Binding $n >] (id, PhantomType::new())
                }
                pub fn set_target(self, state: &mut dyn State, target: Box<dyn Target<T>>) {
                    Binding::from(self).set_target(state, target);
                }
                pub fn set_target_fn<Context: Debug + Clone + 'static>(
                    self,
                    state: &mut dyn State,
                    context: Context,
                    execute: fn(state: &mut dyn State, context: Context, value: T)
                ) {
                    Binding::from(self).set_target_fn(state, context, execute);
                }
                pub fn drop_binding(self, state: &mut dyn State) {
                    Binding::from(self).drop_binding(state);
                }
                pub fn get_value(self, state: &dyn State) -> Option<T> {
                    Binding::from(self).get_value(state)
                }
                $(
                    pub fn [< set_source_ $i >] (self, state: &mut dyn State, source: &mut dyn Source< [< S $i >] >) {
                        let handler: [< Binding $n Source $i Handler >] ::<$( [< S $j >] ),+ , T>  = [< Binding $n Source $i Handler >] {
                            binding: self.into_raw(),
                            phantom: PhantomType::new()
                        };
                        let source = source.handle(
                            state,
                            Box::new(handler)
                        );
                        let bindings: &mut Bindings = state.get_mut();
                        let node = bindings.0[self.0].0.downcast_mut::<BindingNode<T>>().unwrap();
                        let sources = node.sources.downcast_mut::< [< Binding $n NodeSources >] <$( [< S $j >] ),+ , T>>().unwrap();
                        if let Some(source) = sources. [< source_ $i >] .replace(source) {
                            source.handler_id.unhandle(state);
                        }
                        Binding::from(self).knoke_target(state);
                    }
                )+
            }
            impl<
                $( [< S $i >] : Convenient, )+
                T: Convenient
            > From< [< Binding $n >] < $( [< S $i >] , )+ T> > for Binding<T> {
                fn from(v: [< Binding $n >] < $( [< S $i >] , )+ T> ) -> Binding<T> {
                    Binding(v.0, PhantomType::new())
                }
            }
            impl<
                $( [< S $i >] : Convenient, )+
                T: Convenient
            > From< [< Binding $n >] < $( [< S $i >] , )+ T> > for AnyBinding {
                fn from(v: [< Binding $n >] < $( [< S $i >] , )+ T> ) -> AnyBinding {
                    AnyBinding(v.0)
                }
            }
            $(
                #[derive(Debug, Clone)]
                struct [< Binding $n Source $i Handler >] <
                    $( [< S $j >] : Convenient, )+
                    T: Convenient
                > {
                    binding: RawId,
                    phantom: PhantomType<($( [< S $j >] ),+ , T)>
                }
                impl<
                    $( [< S $j >] : Convenient, )+
                    T: Convenient
                > AnyHandler for [< Binding $n Source $i Handler >] < $( [< S $j >] , )+ T >  {
                    fn clear(&self, state: &mut dyn State) {
                        let binding: [< Binding $n >] <$( [< S $j >] ),+ , T> = [< Binding $n >] ::from_raw(self.binding);
                        let bindings: &mut Bindings = state.get_mut();
                        let node = bindings.0[binding.0].0.downcast_mut::<BindingNode<T>>().unwrap();
                        let sources = node.sources.downcast_mut::< [< Binding $n NodeSources >] <$( [< S $j >] ),+ , T>>().unwrap();
                        sources. [< source_ $i >] .take();
                    }
                }
                impl<
                    $( [< S $j >] : Convenient, )+
                    T: Convenient
                > Handler< [< S $i >] > for [< Binding $n Source $i Handler >] < $( [< S $j >] , )+ T >  {
                    fn into_any(self: Box<Self>) -> Box<dyn AnyHandler> {
                        self
                    }
                    fn execute(&self, state: &mut dyn State, value: [< S $i >] ) {
                        let binding: [< Binding $n >] <$( [< S $j >] ),+ , T> = [< Binding $n >] ::from_raw(self.binding);
                        let bindings: &mut Bindings = state.get_mut();
                        let node = bindings.0[binding.0].0.downcast_mut::<BindingNode<T>>().unwrap();
                        let sources = node.sources.downcast_mut::< [< Binding $n NodeSources >] <$( [< S $j >] ),+ , T>>().unwrap();
                        sources. [< source_ $i >] .as_mut().unwrap().value = value.clone();
                        Binding::from(binding).knoke_target(state);
                    }
                }
            )+
        }
    };
}
binding_n!(1; 1);
binding_n!(2; 1, 2);
binding_n!(3; 1, 2, 3);
binding_n!(4; 1, 2, 3, 4);
binding_n!(5; 1, 2, 3, 4, 5);
binding_n!(6; 1, 2, 3, 4, 5, 6);
binding_n!(7; 1, 2, 3, 4, 5, 6, 7);
binding_n!(8; 1, 2, 3, 4, 5, 6, 7, 8);
binding_n!(9; 1, 2, 3, 4, 5, 6, 7, 8, 9);
binding_n!(10; 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
binding_n!(11; 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
binding_n!(12; 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
binding_n!(13; 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);
binding_n!(14; 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14);
binding_n!(15; 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
binding_n!(16; 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);