egui_struct 0.4.2

EguiStruct is a rust derive macro that creates egui UI's from arbitrary structs and enums.
Documentation
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
//! Crate consists of 4 traits ([`EguiStructImut`] & [`EguiStruct`]: [`EguiStructEq`]+[`EguiStructClone`]) and two derive macros (`EguiStruct` to derive [`macro@EguiStructImut`] & [`macro@EguiStruct`] to derive the other three).
//!
//! See [demo](https://github.com/PingPongun/egui_struct/tree/master/demo)

use egui::{Button, Grid, Id, Response, ScrollArea, Ui, Widget, WidgetText};
pub use egui_struct_macros::*;
use std::hash::Hash;
use std::ops::{Deref, DerefMut};

#[cfg(feature = "egui21")]
use egui21 as egui;
#[cfg(feature = "egui22")]
use egui22 as egui;
#[cfg(feature = "egui23")]
use egui23 as egui;
#[cfg(feature = "egui24")]
use egui24 as egui;
#[cfg(feature = "egui25")]
use egui25 as egui;
#[cfg(feature = "egui26")]
use egui26 as egui;
#[cfg(feature = "egui27")]
use egui27 as egui;
#[cfg(feature = "egui28")]
use egui28 as egui;

macro_rules! generate_show {
    ($top_name:ident, $collapsing_name:ident, $show_collapsing_inner:ident, $primitive_name:ident, $childs_name:ident, $start_collapsed:ident,
         $typ:ty, $config:ident, $COLUMN_COUNT:ident, $SIMPLE:ident, $has_childs:ident, $has_primitive:ident) => {
        /// Type that will pass some data to customise how data is shown, in most cases this will be () (eg. for numerics this is [ConfigNum])
        type $config<'a>: Default;

        #[doc(hidden)]
        const $COLUMN_COUNT: usize = 2;

        /// Flag that indicates that data can be shown in the same line as parent (set to true if data is shown as single&simple widget)
        const $SIMPLE: bool = true;

        /// Indicates if data has childs section at the moment
        fn $has_childs(&self) -> bool {
            false
        }

        /// Indicates if data has primitive section at the moment
        fn $has_primitive(&self) -> bool {
            !self.$has_childs()
        }

        /// Show data in view contained ScrollArea&Grid
        ///
        /// You should rather not need to override default impl
        fn $top_name(
            self: $typ,
            ui: &mut Ui,
            label: impl Into<WidgetText> + Clone,
            reset2: Option<&Self>,
        ) -> Response
        where
            Self: 'static,
        {
            let label: WidgetText = label.into();
            let id =
                ui.make_persistent_id((label.text().to_string(), std::any::TypeId::of::<Self>()));
            ScrollArea::vertical()
                .show(ui, |ui| {
                    Grid::new(id)
                        .num_columns(Self::$COLUMN_COUNT)
                        .show(ui, |ui| {
                            self.$collapsing_name(ui, label, "", -1, Default::default(), reset2, id)
                        })
                        .inner
                })
                .inner
        }

        #[doc(hidden)]
        fn $show_collapsing_inner(
            self: $typ,
            ui: &mut Ui,
            label: impl Into<WidgetText> + Clone,
            hint: impl Into<WidgetText> + Clone,
            indent_level: isize,
            config: Self::$config<'_>,
            _reset2: Option<&Self>,
            parent_id: Id,
            start_collapsed: Option<bool>,
        ) -> Response {
            let mut collapsed = false;
            let has_childs = self.$has_childs();
            let id = parent_id.with(label.clone().into().text());
            ui.horizontal(|ui| {
                if indent_level >= 0 {
                    for _ in 0..indent_level {
                        ui.separator();
                    }
                    if has_childs {
                        let id = id.with("__EguiStruct_collapsing_state");
                        collapsed = ui.data_mut(|d| {
                            d.get_temp_mut_or_insert_with(id, || {
                                start_collapsed.unwrap_or(self.$start_collapsed())
                            })
                            .clone()
                        });
                        let icon = if collapsed { "" } else { "" };
                        if Button::new(icon).frame(false).small().ui(ui).clicked() {
                            ui.data_mut(|d| d.insert_temp(id, !collapsed));
                        }
                    }
                }
                let mut lab = ui.label(label.into());
                let hint = hint.into();
                if !hint.is_empty() {
                    lab = lab.on_hover_text(hint);
                }
                lab
            });

            let mut ret = ui
                .horizontal(|ui| {
                    let id = id.with("__EguiStruct_primitive");
                    #[allow(unused_mut)]
                    let mut ret = self.$primitive_name(ui, config, id);
                    macro_rules! reset {
                        (show_collapsing_imut) => {
                            ret
                        };
                        (show_collapsing) => {
                            if let Some(reset2) = _reset2 {
                                if !reset2.eguis_eq(self) {
                                    let mut r = ui.button("");
                                    if r.clicked() {
                                        self.eguis_clone(reset2);
                                        r.mark_changed();
                                    }
                                    ret |= r;
                                }
                            }
                            ret
                        };
                    }
                    reset! {$collapsing_name}
                })
                .inner;
            ui.end_row();

            if has_childs && !collapsed {
                ret = self.$childs_name(ui, indent_level + 1, ret, _reset2, id);
            }
            ret
        }

        /// Do not overide this method.
        ///
        /// Use it when implementing [.show_childs()](EguiStruct::show_childs) to display single nested element
        fn $collapsing_name(
            self: $typ,
            ui: &mut Ui,
            label: impl Into<WidgetText> + Clone,
            hint: impl Into<WidgetText> + Clone,
            indent_level: isize,
            config: Self::$config<'_>,
            reset2: Option<&Self>,
            parent_id: Id,
        ) -> Response {
            self.$show_collapsing_inner(
                ui,
                label,
                hint,
                indent_level,
                config,
                reset2,
                parent_id,
                None,
            )
        }

        /// UI elements shown in the same line as label
        ///
        /// If data element view is fully contained in childs section(does not have primitive section), leave this & [.has_primitive()](EguiStruct::has_primitive) with default impl
        fn $primitive_name(
            self: $typ,
            ui: &mut Ui,
            _config: Self::$config<'_>,
            _id: impl Hash + Clone,
        ) -> Response {
            ui.label("")
        }

        /// UI elements related to nested data, that is show inside collapsible rows
        ///
        /// If data element view is simple & can fully be contained in primitive section, leave this & [.has_childs()](EguiStruct::has_childs) with default impl
        fn $childs_name(
            self: $typ,
            _ui: &mut Ui,
            _indent_level: isize,
            _response: Response,
            _reset2: Option<&Self>,
            _parent_id: Id,
        ) -> Response {
            unreachable!()
        }

        /// Controls if struct is initally collapsed/uncollapsed (if "show_childs" is shown by default)
        ///
        /// eg. Collections (vecs, slices, hashmaps, ..) are initially collapsed if they have more than 16 elements
        fn $start_collapsed(&self) -> bool {
            false
        }
    };
}
/// Similar to std [`Clone`] trait, but they respect `#[eguis(skip)]`.
///
/// Necessary to implement [`EguiStruct`]. Used to provide reset functionality.
///
/// If type is [`Clone`] can be implemented with [`impl_eclone!`]/[`impl_eeqclone!`].
pub trait EguiStructClone {
    fn eguis_clone(&mut self, source: &Self);
}

/// Similar to std [`PartialEq`] trait, but they respect `#[eguis(skip)]`.
///
/// Necessary to implement [`EguiStruct`]. Used to provide reset functionality (if reset is not used, may be blank impl).
///
/// If type is [`PartialEq`] can be implemented with [`impl_eeq!`]/[`impl_eeqclone!`].
pub trait EguiStructEq {
    fn eguis_eq(&self, _rhs: &Self) -> bool {
        //default implementation can be used if reset button is not required
        true
    }
}

#[macro_export]
/// Generate [EguiStructClone] implementation based on [Clone]
macro_rules! impl_eclone {
    ([$($generics:tt)*], $type:ty) => {
        impl<$($generics)*> EguiStructClone for $type {
            fn eguis_clone(&mut self, source: &Self) {
                self.clone_from(source);
            }
        }
    };
}

#[macro_export]
/// Generate [EguiStructEq] implementation based on [PartialEq]
macro_rules! impl_eeq {
    ([$($generics:tt)*], $type:ty) => {
        impl<$($generics)*> EguiStructEq for $type {
            fn eguis_eq(&self, rhs: &Self) -> bool {
                self == rhs
            }
        }
    };
}

#[macro_export]
/// Wrapper for both [impl_eeq!] & [impl_eclone!]
///
/// Generate [EguiStructClone] & [EguiStructEq] implementation based on [Clone] & [PartialEq]
///
/// Usage:
/// ```
/// impl_eeqclone!(MyType)
/// impl_eeqclone!([T], MyType2) //for MyType2<T>
/// ```
macro_rules! impl_eeqclone {
    ([$($generics:tt)*], $type:ty) => {
        impl_eeq!{[$($generics)*], $type}
        impl_eclone!{[$($generics)*], $type}
    };
    ($type:ty) => {impl_eeqclone!{[],$type}}
}

/// Trait, that allows generating mutable view of data (takes `&mut data`)
///
///  For end user (if you implement trait with macro & not manualy) ofers one function [`.show_top()`](Self::show_top), which displays struct inside scroll area.
pub trait EguiStruct: EguiStructClone + EguiStructEq {
    generate_show! { show_top, show_collapsing, show_collapsing_inner, show_primitive, show_childs, start_collapsed,
    &mut Self, ConfigType, COLUMN_COUNT, SIMPLE, has_childs, has_primitive }
}
/// Trait, that allows generating immutable view of data (takes `&data`)
pub trait EguiStructImut {
    generate_show! { show_top_imut, show_collapsing_imut, show_collapsing_inner_imut, show_primitive_imut, show_childs_imut, start_collapsed_imut,
    &Self, ConfigTypeImut, COLUMN_COUNT_IMUT, SIMPLE_IMUT, has_childs_imut, has_primitive_imut }
}

/// Config structure for mutable view of Numerics
#[derive(Default)]
pub enum ConfigNum<'a, T: 'a> {
    /// Default: DragValue (without limits)
    #[default]
    NumDefault,

    /// DragValue(min, max)
    DragValue(T, T),

    /// Slider(min, max)
    Slider(T, T),

    /// Slider(min, max, step)
    SliderStep(T, T, T),

    /// Combobox with available options specified by included iterator
    ComboBox(&'a mut dyn Iterator<Item = T>),
}
macro_rules! impl_num_primitives {
    ($($typ:ty)*) => {
        $(
            impl EguiStruct for $typ {
                type ConfigType<'a> = ConfigNum<'a, $typ>;
                fn show_primitive(&mut self, ui: &mut Ui, config: Self::ConfigType<'_>, id: impl Hash  + Clone) -> Response {
                    match config{
                        Self::ConfigType::NumDefault        =>  egui::DragValue::new(self).ui(ui),
                        #[cfg(feature = "egui28")]
                        Self::ConfigType::DragValue(min,max)=>  egui::DragValue::new(self).range(min..=max).ui(ui),
                        #[cfg(not(feature = "egui28"))]
                        Self::ConfigType::DragValue(min,max)=>  egui::DragValue::new(self).clamp_range(min..=max).ui(ui),
                        Self::ConfigType::Slider(min,max)   =>  egui::Slider::new(self, min..=max).ui(ui),
                        Self::ConfigType::SliderStep(min,max,step)   =>  egui::Slider::new(self, min..=max).step_by(step as f64).ui(ui),
                        Self::ConfigType::ComboBox(iter) => show_combobox(self, ui, Some(iter), id),
                    }
                }
            }
            impl EguiStructImut for $typ {
                type ConfigTypeImut<'a> = ConfigStrImut;
                fn show_primitive_imut(&self, ui: &mut Ui, config: Self::ConfigTypeImut<'_>, _id: impl Hash  + Clone) -> Response {
                    self.to_string().as_str().show_primitive_imut(ui, config, ())
                }
            }
            impl_eeqclone!{$typ}
        )*
    };
}

impl_num_primitives!(i8 i16 i32 i64 u8 u16 u32 u64 usize isize f32 f64);

impl EguiStruct for bool {
    type ConfigType<'a> = ();
    fn show_primitive(
        &mut self,
        ui: &mut Ui,
        _config: Self::ConfigType<'_>,
        _id: impl Hash + Clone,
    ) -> Response {
        egui::Checkbox::without_text(self).ui(ui)
    }
}
impl EguiStructImut for bool {
    type ConfigTypeImut<'a> = ();
    fn show_primitive_imut(
        &self,
        ui: &mut Ui,
        _config: Self::ConfigTypeImut<'_>,
        _id: impl Hash + Clone,
    ) -> Response {
        ui.add_enabled(false, egui::Checkbox::without_text(&mut self.clone()))
    }
}
impl_eeqclone! {bool}
/////////////////////////////////////////////////////////
///Config structure for mutable view of String
#[derive(Default)]
pub enum ConfigStr<'a> {
    ///Default: single line `egui::TextEdit`
    #[default]
    SingleLine,

    ///multi line `egui::TextEdit`
    MultiLine,

    ///Combobox with available options specified by included iterator
    ComboBox(&'a mut dyn Iterator<Item = String>),
}

///Config structure for immutable view of many simple types like str, String & numerics
#[derive(Default)]
pub enum ConfigStrImut {
    ///`egui::Label`
    NonSelectable,

    ///Default: imutable `egui::TextEdit`
    #[default]
    Selectable,
}

impl EguiStruct for String {
    type ConfigType<'a> = ConfigStr<'a>;
    fn show_primitive(
        &mut self,
        ui: &mut Ui,
        config: Self::ConfigType<'_>,
        id: impl Hash + Clone,
    ) -> Response {
        match config {
            ConfigStr::SingleLine => ui.text_edit_singleline(self),
            ConfigStr::MultiLine => ui.text_edit_multiline(self),
            ConfigStr::ComboBox(iter) => show_combobox(self, ui, Some(iter), id),
        }
    }
}
impl EguiStructImut for String {
    type ConfigTypeImut<'a> = ConfigStrImut;
    fn show_primitive_imut(
        &self,
        ui: &mut Ui,
        config: Self::ConfigTypeImut<'_>,
        _id: impl Hash + Clone,
    ) -> Response {
        self.as_str().show_primitive_imut(ui, config, ())
    }
}
impl_eeqclone! {String}

impl EguiStructImut for str {
    type ConfigTypeImut<'a> = ConfigStrImut;
    fn show_primitive_imut(
        mut self: &Self,
        ui: &mut Ui,
        config: Self::ConfigTypeImut<'_>,
        _id: impl Hash + Clone,
    ) -> Response {
        match config {
            ConfigStrImut::NonSelectable => ui.label(self),
            ConfigStrImut::Selectable => ui.text_edit_singleline(&mut self),
        }
    }
}

/////////////////////////////////////////////////////////
impl<T: EguiStructImut + Default> EguiStructImut for Option<T> {
    const SIMPLE_IMUT: bool = false;
    type ConfigTypeImut<'a> = ();
    fn has_childs_imut(&self) -> bool {
        !T::SIMPLE_IMUT && self.is_some()
    }
    fn has_primitive_imut(&self) -> bool {
        true
    }
    fn show_primitive_imut(
        &self,
        ui: &mut Ui,
        _config: Self::ConfigTypeImut<'_>,
        id: impl Hash + Clone,
    ) -> Response {
        ui.horizontal(|ui| {
            let mut ret = self.is_some().show_primitive_imut(ui, (), ());
            match (T::SIMPLE_IMUT, self) {
                (true, Some(value)) => ret |= value.show_primitive_imut(ui, Default::default(), id),
                (true, None) => (),
                (false, _) => (),
            }
            ret
        })
        .inner
    }
    fn show_childs_imut(
        &self,
        ui: &mut Ui,
        indent_level: isize,
        mut response: Response,
        _reset2: Option<&Self>,
        id: Id,
    ) -> Response {
        if let Some(inner) = self {
            if inner.has_primitive_imut() {
                response |= inner.show_collapsing_imut(
                    ui,
                    "[0]",
                    "",
                    indent_level,
                    Default::default(),
                    None,
                    id,
                );
            } else {
                response |= inner.show_childs_imut(ui, indent_level, response.clone(), None, id)
            }
        }
        response
    }
}
impl<T: EguiStruct + Default> EguiStruct for Option<T> {
    const SIMPLE: bool = false;
    type ConfigType<'a> = ();
    fn has_childs(&self) -> bool {
        !T::SIMPLE && self.is_some()
    }
    fn has_primitive(&self) -> bool {
        true
    }
    fn show_primitive(
        &mut self,
        ui: &mut Ui,
        _config: Self::ConfigType<'_>,
        id: impl Hash + Clone,
    ) -> Response {
        ui.horizontal(|ui| {
            let mut checked = self.is_some();
            let mut ret = checked.show_primitive(ui, (), ());

            match (checked, T::SIMPLE, self.as_mut()) {
                (true, true, Some(value)) => {
                    ret |= value.show_primitive(ui, Default::default(), id)
                }
                (true, false, Some(_)) => (), //if inner is not simple, it will be shown below
                (true, _, None) => *self = Some(T::default()),
                (false, _, _) => *self = None,
            }
            ret
        })
        .inner
    }
    fn show_childs(
        &mut self,
        ui: &mut Ui,
        indent_level: isize,
        mut response: Response,
        reset2: Option<&Self>,
        id: Id,
    ) -> Response {
        if let Some(inner) = self {
            if inner.has_primitive() {
                response |= inner.show_collapsing(
                    ui,
                    "[0]",
                    "",
                    indent_level,
                    Default::default(),
                    reset2.unwrap_or(&None).as_ref(),
                    id,
                );
            } else {
                response |= inner.show_childs(
                    ui,
                    indent_level,
                    response.clone(),
                    reset2.unwrap_or(&None).as_ref(),
                    id,
                )
            }
        }
        response
    }
}
impl<T: EguiStructClone + Default> EguiStructClone for Option<T> {
    fn eguis_clone(&mut self, source: &Self) {
        if let Some(source) = source {
            if let Some(s) = self {
                s.eguis_clone(source);
            } else {
                let mut v: T = Default::default();
                v.eguis_clone(source);
                *self = Some(v);
            }
        } else {
            *self = None;
        }
    }
}
impl<T: EguiStructEq> EguiStructEq for Option<T> {
    fn eguis_eq(&self, rhs: &Self) -> bool {
        if let Some(s) = self {
            if let Some(r) = rhs {
                s.eguis_eq(r)
            } else {
                false
            }
        } else {
            false
        }
    }
}
///////////////////////////////////////////////////
macro_rules! impl_vec {
    ($Self:ty, $typ:ty, $iter:ident, $collapsing_name:ident, $childs_name:ident, $start_collapsed:ident,
        $trait:ident, $SIMPLE:ident, $ConfigType:ident, $has_childs_imut:ident, $has_primitive:ident) => {

        impl<T: $trait> $trait for $typ{
            const $SIMPLE: bool = false;
            type $ConfigType<'a> = ();
            fn $has_childs_imut(&self) -> bool {
                !self.is_empty()
            }
            fn $has_primitive(&self) -> bool {
                false
            }
            fn $childs_name(
                self: $Self,
                ui: &mut Ui,
                indent_level: isize,
                mut response: Response,
                _reset2: Option<&Self>,
                id: Id
            ) -> Response {
                self.$iter().enumerate().for_each(|(idx, x)| {
                    response |= x.$collapsing_name(ui, idx.to_string(), "", indent_level, Default::default(), None, id)
                });
                response
            }
            fn $start_collapsed(&self) -> bool {
                self.len() > 16
            }
        }
    };
    (IMUT, $($typ:ty)*) => { $(impl_vec! {&Self, $typ, iter, show_collapsing_imut, show_childs_imut, start_collapsed_imut,
        EguiStructImut, SIMPLE_IMUT, ConfigTypeImut, has_childs_imut, has_primitive_imut})* };
    ($($typ:ty)*) => {
        $(
            impl_vec! {IMUT, $typ}
            impl_vec! {&mut Self, $typ, iter_mut, show_collapsing, show_childs, start_collapsed,
                EguiStruct, SIMPLE, ConfigType, has_childs, has_primitive}

            impl<T: EguiStructClone> EguiStructClone for $typ {
                fn eguis_clone(&mut self, source: &Self) {
                    //TODO update this if vector length can change
                    self.iter_mut().zip(source.iter()).for_each(|(s,r)|s.eguis_clone(r))
                }
            }
            impl<T: EguiStructEq> EguiStructEq for $typ  {
                fn eguis_eq(&self, rhs: &Self) -> bool {
                    let mut ret = self.len()==rhs.len();
                    self.iter().zip(rhs.iter()).for_each(|(s,r)|ret &= s.eguis_eq(r));
                    ret
                }
            }
        )*
    };
}

impl_vec! {[T] Vec<T>}
impl_vec! {IMUT, std::collections::HashSet<T> }
#[cfg(feature = "indexmap")]
impl_vec! {IMUT, indexmap::IndexSet<T> }

/////////////////////////////////////////////////
macro_rules! impl_map {
    ($Self:ty, $typ:ty, [$( $Qbound:path),*], $iter:ident, $collapsing_name:ident, $childs_name:ident, $start_collapsed:ident,
        $trait:ident, $SIMPLE:ident, $ConfigType:ident, $has_childs_imut:ident, $has_primitive:ident) => {

        impl<Q: ToString $(+ $Qbound)*, V: $trait> $trait for $typ{
            const $SIMPLE: bool = false;
            type $ConfigType<'a> = ();
            fn $has_childs_imut(&self) -> bool {
                !self.is_empty()
            }
            fn $has_primitive(&self) -> bool {
                false
            }
            fn $childs_name(
                self: $Self,
                ui: &mut Ui,
                indent_level: isize,
                mut response: Response,
                _reset2: Option<&Self>,id:Id
            ) -> Response {
                self.$iter().for_each(|(q, v)| {
                    response |= v.$collapsing_name(
                        ui,
                        q.to_string(),
                        "",
                        indent_level,
                        Default::default(),
                        None,
                        id
                    )
                });
                response
            }
            fn $start_collapsed(&self) -> bool {
                self.len() > 16
            }
        }
    };
    ($typ:ty) => {
        impl_map! {&Self, $typ, [], iter, show_collapsing_imut, show_childs_imut, start_collapsed_imut,
            EguiStructImut, SIMPLE_IMUT, ConfigTypeImut, has_childs_imut, has_primitive_imut}
        impl_map! {&mut Self, $typ, [Eq, std::hash::Hash], iter_mut, show_collapsing, show_childs, start_collapsed,
            EguiStruct, SIMPLE, ConfigType, has_childs, has_primitive}

        impl<Q: ToString + Eq + std::hash::Hash, V: EguiStructClone> EguiStructClone for $typ {
            fn eguis_clone(&mut self, source: &Self) {
                //this is very simplified implementation, that asummes that lenghts & keys are the same
                self.iter_mut().for_each(|(q, v)| {
                    if let Some(r) = source.get(q) {
                        v.eguis_clone(r)
                    }
                })
            }
        }
        impl<Q: ToString + Eq + std::hash::Hash, V: EguiStructEq> EguiStructEq for $typ {
            fn eguis_eq(&self, rhs: &Self) -> bool {
                let mut ret = self.len() == rhs.len();
                self.iter().for_each(|(q, v)| {
                    if let Some(r) = rhs.get(q) {
                        ret &= v.eguis_eq(r)
                    } else {
                        ret = false
                    }
                });
                ret
            }
        }
    };
}

impl_map! { std::collections::HashMap<Q,V> }
#[cfg(feature = "indexmap")]
impl_map! { indexmap::IndexMap<Q,V> }
///////////////////////////////////////////////////////
macro_rules! impl_large_numerics {
    ($($t:ty)*) => ($(
        impl EguiStructImut for $t {
            type ConfigTypeImut<'a> = ();
            fn show_primitive_imut(&self, ui: &mut Ui, _config: Self::ConfigTypeImut<'_>, _id: impl Hash + Clone) -> Response {
                ui.label(self.to_string())
            }
        }
        impl EguiStruct for $t {
            type ConfigType<'a> = ();
            fn show_primitive(&mut self, ui: &mut Ui, _config: Self::ConfigType<'_>, _id: impl Hash + Clone)-> Response  {
                let mut text = self.to_string();
                let ret=ui.text_edit_singleline(&mut text);
                if let Ok(value) = text.parse() {
                    *self = value;
                }
                ret
            }
        }
        impl_eeqclone!{$t}
    )*)
}
impl_large_numerics!(i128 u128);

////////////////////////////////////////////////////////////

pub struct Combobox<T>(pub T);

impl<T: ToString> EguiStructImut for Combobox<T> {
    type ConfigTypeImut<'a> = ConfigStrImut;

    fn show_primitive_imut(
        self: &Self,
        ui: &mut Ui,
        config: Self::ConfigTypeImut<'_>,
        _id: impl Hash + Clone,
    ) -> Response {
        self.0.to_string().show_primitive_imut(ui, config, ())
    }
}

impl<T: Clone> EguiStructClone for Combobox<T> {
    fn eguis_clone(&mut self, source: &Self) {
        self.0.clone_from(&source.0)
    }
}
impl<T: PartialEq> EguiStructEq for Combobox<T> {
    fn eguis_eq(&self, rhs: &Self) -> bool {
        self.0.eq(&rhs.0)
    }
}
impl<T: Clone + ToString + PartialEq + 'static> EguiStruct for Combobox<T> {
    type ConfigType<'a> = Option<&'a mut dyn Iterator<Item = T>>;

    fn show_primitive(
        self: &mut Self,
        ui: &mut Ui,
        config: Self::ConfigType<'_>,
        id: impl Hash + Clone,
    ) -> Response {
        show_combobox(&mut self.0, ui, config, id)
    }
}

fn show_combobox<'a, T: Clone + ToString + PartialEq>(
    sel: &mut T,
    ui: &mut Ui,
    config: Option<&'a mut dyn Iterator<Item = T>>,
    id: impl Hash + Clone,
) -> Response {
    let defspacing = ui.spacing().item_spacing.clone();
    ui.spacing_mut().item_spacing = egui::vec2(0.0, 0.0);
    let egui::InnerResponse { inner, response } =
        egui::ComboBox::from_id_source((id, "__EguiStruct_combobox"))
            .selected_text(sel.to_string())
            .show_ui(ui, |ui| {
                let mut inner_response =
                    ui.allocate_response(egui::vec2(0.0, 0.0), egui::Sense::hover());
                ui.spacing_mut().item_spacing = defspacing;
                if let Some(config) = config {
                    for i in config {
                        let s = i.to_string();
                        inner_response |= ui.selectable_value(sel, i, s);
                    }
                }
                inner_response
            });
    ui.spacing_mut().item_spacing = defspacing;
    if let Some(mut iresp) = inner {
        iresp.layer_id = response.layer_id;
        response | iresp
    } else {
        response
    }
}
impl<T> Deref for Combobox<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
impl<T> DerefMut for Combobox<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}
impl<T: Default> Default for Combobox<T> {
    fn default() -> Self {
        Self(Default::default())
    }
}
impl<T: Clone> Clone for Combobox<T> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}
impl<T: Copy> Copy for Combobox<T> {}
impl<T: Eq> Eq for Combobox<T> {}
impl<T: Ord> Ord for Combobox<T> {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.0.cmp(&other.0)
    }
}
impl<T: PartialEq> PartialEq for Combobox<T> {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}
impl<T: PartialOrd> PartialOrd for Combobox<T> {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        self.0.partial_cmp(&other.0)
    }
}