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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
use traits::*;
use rin::graphics::*;
use rin::events::*;
use rin::math::*;
use rin::color::*;
use rin::color::consts::*;
use rin::window::{self, Events, MouseEvents};
use std::rc::Rc;
use control_shape::ControlShape;
use utils;

pub struct GroupH{
    rendered: Sender<'static, ()>,
    controls: Vec<Box<Control>>,
    controls_width_pcts: Vec<Option<Property<'static, f32>>>,
    name: String,
    font: Rc<Ttf>,
    color: Rgb<f32>,
    non_attended: StreamRc<'static, window::Event>,
    width: Property<'static, f32>,
    height: Property<'static, f32>,
    position: Property<'static, Pnt2>,
    events: StreamRc<'static, window::Event>,
    // over: Property<'static, bool>,
    // controls_width: Property<'static, f32>,
    // left_margin: Property<'static, f32>,
    h_margin: f32,
    v_margin: f32,
}

impl ControlGeometry for GroupH{
    fn flexible() -> bool{
        true
    }

    fn geometry(&self, container: Option<&Rect<f32>>) -> Option<Vec<Vertex2DColor>>{
        self.rendered.send(());
        let rect = self.rect();
        let rect = container.map(|container| container.intersection(&rect)).unwrap_or(rect);
        let geometry = self.controls.iter()
            .skip_while(|control| !control.rect().overlaps(&rect))
            .take_while(|control| control.rect().overlaps(&rect))
            .filter_map(|control| control.geometry(Some(&rect)))
            .flat_map(|geometry| geometry.into_iter())
            .collect::<Vec<_>>();
        if geometry.is_empty(){
            None
        }else{
            Some(geometry)
        }
    }

    fn text_geometry(&self, container: Option<&Rect<f32>>) -> Option<Vec<Vertex2DTex>>{
        let rect = self.rect();
        let rect = container.map(|container| container.intersection(&rect)).unwrap_or(rect);
        let geometry = self.controls.iter()
            .skip_while(|control| !control.rect().overlaps(&rect))
            .take_while(|control| control.rect().overlaps(&rect))
            .filter_map(|control| control.text_geometry(Some(&rect)))
            .flat_map(|geometry| geometry.into_iter())
            .collect::<Vec<_>>();
        if geometry.is_empty(){
            None
        }else{
            Some(geometry)
        }
    }

    fn texture_geometry(&self, container: Option<&Rect<f32>>) -> Option<Vec<Vertex2DTex>>{
        let rect = self.rect();
        let rect = container.map(|container| container.intersection(&rect)).unwrap_or(rect);
        let geometry = self.controls.iter()
            .skip_while(|control| !control.rect().overlaps(&rect))
            .take_while(|control| control.rect().overlaps(&rect))
            .filter_map(|control| control.texture_geometry(Some(&rect)))
            .flat_map(|geometry| geometry.into_iter())
            .collect::<Vec<_>>();
        if geometry.is_empty(){
            None
        }else{
            Some(geometry)
        }
    }

    fn font(&self) -> Option<&Ttf>{
        Some(&self.font)
    }

    fn color(&self) -> &Rgb<f32>{
        &self.color
    }

    fn position(&self) -> &Property<'static, Pnt2>{
        &self.position
    }

    fn width(&self) -> &Property<'static, f32>{
        &self.width
    }

    fn height(&self) -> &Property<'static, f32>{
        &self.height
    }
}

impl ControlEvents for GroupH{
    fn non_attended(&self) -> StreamRc<'static, window::Event>{
        self.non_attended.clone()
    }
}

impl Control for GroupH{
    fn name(&self) -> &str{
        &self.name
    }
}

impl GroupH{
    pub fn control<C: Control>(&self, idx: usize) -> Option<&C>{
        self.controls[idx].downcast_ref()
    }

    pub fn control_mut<C: Control>(&mut self, idx: usize) -> Option<&mut C>{
        self.controls[idx].downcast_mut()
    }

    pub fn add<P,S>(&mut self, name: &str, parameter: S) -> &mut GroupH
        where S: IntoStyled<Property = P>,
              P: ControlDefaultProperty,
    {
        self.new_control(name, parameter);
        self
    }

    pub fn new_control<P,S>(&mut self, name: &str, parameter: S) -> &mut <<P as ControlDefaultProperty>::Builder as ControlBuilder>::Control
        where S: for<'a> IntoStyled<Property = P>,
              P: ControlDefaultProperty,
    {
        self.create_control::<P, P::Builder>(name, parameter.into_styled())
    }

    fn create_control<P, B>(&mut self, name: &str, styled: Styled<P>) -> &mut B::Control
        where P: IntoControlBuilder<B>,
              B: ControlBuilder
    {
        let h_margin = self.h_margin;
        let position = if let Some(control) = self.controls.last(){
            control.position().clone().zip(control.width().clone())
                .map(move |(p,w)| pnt2(p.x + w + h_margin, p.y))
        }else{
            self.position.clone()
        };
        let (width, width_pct) = if !B::Control::flexible(){
            (None, None)
        }else{
            let num_flexibles = self.controls_width_pcts.iter()
                .filter(|pct| pct.is_some())
                .count();
            let non_flexible_width = self.controls_width_pcts.iter()
                .zip(self.controls.iter())
                .filter_map(|(pct, control)| if pct.is_none(){
                    Some(**control.width())
                }else{
                    None
                }).sum::<f32>();

            let num_controls = self.controls.len();
            let rem_pct = self.width.clone().map(move |w| {
                let w = w - h_margin * (num_controls + 1) as f32;
                (w - non_flexible_width) / w
            });
            let pct = if num_flexibles == 0 {
                rem_pct
            }else{
                let pct_per_element = rem_pct.map(move |pct| pct / num_flexibles as f32);
                for pct in self.controls_width_pcts.iter_mut(){
                    if let Some(pct) = pct.as_mut(){
                        pct.swap_parent(pct_per_element.clone().stream());
                        pct.set(*pct_per_element);
                    }
                }
                pct_per_element
            };

            let control_width = self.width.clone().zip(pct.clone()).map(|(w, pct)| clamp(w * pct, 0., w));
            (Some(control_width), Some(pct))
        };

        // println!("adding {} with width {:?} pct {:?}, flexible: {}", name, width, width_pct, B::Control::flexible());

        let c = styled.parameter.into_builder(name, self.events.clone())
            .position_property(position)
            .height_property(self.height.clone())
            .width_property_opt(width)
            .h_margin(self.h_margin)
            .v_margin(self.v_margin)
            .color(self.color)
            .font(self.font.clone())
            .hide_label()
            .from_json_style(&styled.style)
            .create();
        self.controls.push(Box::new(c));
        self.controls_width_pcts.push(width_pct);
        let control: &mut B::Control = self.controls.last_mut().unwrap().downcast_mut().unwrap();
        control
    }
}

pub struct GroupHBuilder {
    control_shape: ControlShape,
    name: String,
    events: StreamRc<'static, window::Event>,
}

impl GroupHBuilder{
    pub fn new<S: StreamT<'static, window::Event>>(name: &str, pos: Property<'static, Pnt2>, events: S) -> GroupHBuilder{
        let width = Property::new(200.);
        let height = Property::new(15.);
        let margin = 0.;
        GroupHBuilder{
            name: name.to_string(),
            events: events.rc(),
            control_shape: ControlShape::new(pos, width, height, margin, margin, WHITE),
        }
    }
}


impl ControlBuilder for GroupHBuilder{
    type Control = GroupH;

    fn shape(&mut self) -> &mut ControlShape {
        &mut self.control_shape
    }

    fn create(self) -> GroupH{
        let (rendered_sender, rendered_stream) = utils::rendered_stream(self.events.clone().unique());
        let rendered = rendered_stream.to_property(false);

        let font = self.control_shape.font().unwrap_or_else(|| ::utils::default_font());

        let h_margin = self.control_shape.h_margin();
        let v_margin = self.control_shape.v_margin();

        let rect = self.control_shape.position()
            .zip(self.control_shape.width())
            .zip(self.control_shape.height())
            .flatten()
            .map(|(pos, width, height)| Rect{
                pos: convert(pos),
                width: width as f64,
                height: height as f64
            });


        let is_over = self.events.clone()
            .mouse()
            .moved()
            .map(move |p| p.inside(&rect))
            .to_property(false);
        let non_attended = self.events.clone()
            .filter(move |e|{
                if let window::Event::MousePressed{..} = e {
                    !*rendered || !*is_over
                }else{
                    true
                }
            }).rc();

        GroupH {
            controls: vec![],
            controls_width_pcts: vec![],
            name: self.name,
            color: self.control_shape.color(),
            font,
            position: self.control_shape.position(),
            width: self.control_shape.width(),
            height: self.control_shape.height(),
            h_margin,
            v_margin,
            events: self.events,
            rendered: rendered_sender,
            non_attended,
        }
    }
}


pub struct Tuple<T>{
    param: T,
    names: &'static [&'static str],
}

impl<T> Tuple<T>{
    pub fn new(param: T, names: &'static [&'static str]) -> Tuple<T>{
        Tuple{
            param,
            names
        }
    }
}

pub struct TupleBuilder<T>{
    group: Tuple<T>,
    builder: GroupHBuilder,
}

macro_rules! impl_group {
    ($($p: ident),*) => {
        impl<$($p),*> $crate::ControlBuilder for $crate::group_h::TupleBuilder<($($p),*)>
        where $($p: $crate::IntoStyled,)*
              $(<$p as $crate::IntoStyled>::Property: ControlDefaultProperty),*
        {
            type Control = $crate::GroupH;
            fn shape(&mut self) -> &mut ControlShape {
                self.builder.shape()
            }

            fn create(self) -> $crate::GroupH {
                let mut group = self.builder
                    .v_margin(0.)
                    .h_margin(0.)
                    // .transparent()
                    .hide_label()
                    .create();
                #[allow(non_snake_case)]
                let ($($p),*) = self.group.param;
                let mut i = 0;
                $(
                    group.add(self.group.names[i], $p);
                    #[allow(unused_assignments)]
                    {
                        i += 1;
                    }
                )*

                group
            }
        }

        impl<$($p),*> $crate::ControlDefaultProperty for $crate::group_h::Tuple<($($p),*)>
        where $($p: $crate::IntoStyled,)*
              $(<$p as $crate::IntoStyled>::Property: ControlDefaultProperty),*
        {
            type Builder = $crate::group_h::TupleBuilder<($($p),*)>;
        }

        impl<$($p),*> $crate::BuilderFromProperty<$crate::group_h::Tuple<($($p),*)>> for $crate::group_h::TupleBuilder<($($p),*)>
        where $($p: $crate::IntoStyled,)*
              $(<$p as $crate::IntoStyled>::Property: ControlDefaultProperty),*
        {
            fn from_parameter<S>(group: $crate::group_h::Tuple<($($p),*)>, name: &str, events: S) -> $crate::group_h::TupleBuilder<($($p),*)>
            where S: StreamT<'static, window::Event>
            {
                $crate::group_h::TupleBuilder{
                    builder: $crate::GroupHBuilder::new(name, Property::new(origin()), events),
                    group,
                }
            }
        }
    };
}

impl_group!(A, B);
impl_group!(A, B, C);
impl_group!(A, B, C, D);
impl_group!(A, B, C, D, E);
impl_group!(A, B, C, D, E, F);
impl_group!(A, B, C, D, E, F, G);
impl_group!(A, B, C, D, E, F, G, H);
impl_group!(A, B, C, D, E, F, G, H, I);
impl_group!(A, B, C, D, E, F, G, H, I, J);
impl_group!(A, B, C, D, E, F, G, H, I, J, K);
impl_group!(A, B, C, D, E, F, G, H, I, J, K, L);
impl_group!(A, B, C, D, E, F, G, H, I, J, K, L, M);
impl_group!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);
impl_group!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
impl_group!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);

#[macro_export]
macro_rules! group_h {
    ($p1: expr, $($p: expr),*) => {
        $crate::group_h::Tuple::new(($p1, $($p),*), &[stringify!($p1), $(stringify!($p)),*])
    };
}

// pub struct GroupHBuilder2<A,B> {
//     control_shape: ControlShape,
//     control1: A,
//     control2: B,
//     name: String,
//     events: StreamRc<'static, window::Event>,
// }

// impl<A,B> GroupHBuilder2<A,B>{
//     pub fn new<S: StreamT<'static, window::Event>>(parameter: (A,B), name: &str, events: S) -> GroupHBuilder2<A,B>{
//         let pos = Property::new(origin());
//         let width = Property::new(200.);
//         let height = Property::new(15.);
//         let margin = 0.;
//         let (control1, control2) = parameter;
//         GroupHBuilder2{
//             name: name.to_string(),
//             control1,
//             control2,
//             events: events.rc(),
//             control_shape: ControlShape::new(pos, width, height, margin, margin, WHITE),
//         }
//     }
// }


// impl<A: ControlDefaultProperty, B: ControlDefaultProperty> ControlBuilder for GroupHBuilder2<A, B>{
//     type Control = GroupH;

//     fn shape(&mut self) -> &mut ControlShape {
//         &mut self.control_shape
//     }

//     fn create(self) -> GroupH{
//         fn create_control<P, CB>(
//             name: &str,
//             parameter: P,
//             position: Property<'static, Pnt2>,
//             width: Option<Property<'static, f32>>,
//             font: Rc<Ttf>,
//             control_shape: &ControlShape,
//             events: StreamRc<'static, window::Event>) -> CB::Control
//         where P: IntoControlBuilder<CB>,
//                 CB: ControlBuilder
//         {
//             let b = parameter.into_builder(name, events)
//                 .position_property(position)
//                 .height_property(control_shape.height())
//                 .h_margin(control_shape.h_margin())
//                 .v_margin(control_shape.v_margin())
//                 .color(control_shape.color())
//                 .font(font)
//                 .hide_label();

//             if let Some(width) = width {
//                 b.width_property(width).create()
//             }else{
//                 b.create()
//             }
//         }

//         let font = self.control_shape.font().unwrap_or_else(|| ::utils::default_font());

//         let control1 = create_control::<_, A::Builder>(
//             "",
//             self.control1,
//             self.control_shape.position(),
//             None,
//             font.clone(),
//             &self.control_shape,
//             self.events.clone());

//         let h_margin = self.control_shape.h_margin();
//         let v_margin = self.control_shape.v_margin();
//         let position = control1.position().clone()
//             .zip(control1.width().clone())
//             .map(move |(pos, w)| pnt2(pos.x + w + h_margin, pos.y));
//         let width = self.control_shape.width()
//         .zip(control1.width().clone())
//             .map(move |(w, cw)| w - cw - h_margin);
//         let control2 = create_control::<_, B::Builder>(
//             &self.name,
//             self.control2,
//             position,
//             Some(width),
//             font.clone(),
//             &self.control_shape,
//             self.events.clone());

//         let width = control1.width().clone()
//             .zip(control2.width().clone())
//             .map(|(w1, w2)| w1 + w2);
//         let height = control1.height().clone()
//             .zip(control2.height().clone())
//             .map(|(h1, h2)| h1.max(h2));

//         GroupH {
//             controls: vec![Box::new(control1), Box::new(control2)],
//             name: self.name,
//             color: self.control_shape.color(),
//             font,
//             non_attended: self.events.clone(),
//             position: self.control_shape.position(),
//             width,
//             height,
//             h_margin,
//             v_margin,
//             events: self.events,
//         }
//     }
// }

// impl<A: ControlDefaultProperty, B: ControlDefaultProperty> ControlDefaultProperty for (A,B) {
//     type Builder = GroupHBuilder2<A,B>;
// }

// impl<A: ControlDefaultProperty, B: ControlDefaultProperty> BuilderFromProperty<(A,B)> for GroupHBuilder2<A,B> {
//     fn from_parameter<S: StreamT<'static, window::Event>>(parameter: (A,B), name: &str, events: S) -> GroupHBuilder2<A,B>{
//         GroupHBuilder2::new(parameter, name, events)
//     }
// }