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
use std::any::TypeId;

use bevy_ecs::{component::ComponentId, system::System, world::World};
use bevy_render::color::Color;

use super::system_style::{color_to_hex, system_to_style, SystemStyle};

#[derive(Default, Clone, Copy)]
pub enum RankDir {
    TopDown,
    #[default]
    LeftRight,
}
impl RankDir {
    pub(crate) fn as_dot(&self) -> &'static str {
        match self {
            RankDir::TopDown => "TD",
            RankDir::LeftRight => "LR",
        }
    }
}

#[derive(Default, Clone, Copy)]
pub enum EdgeStyle {
    None,
    Line,
    Polyline,
    Curved,
    Ortho,
    #[default]
    Spline,
}
impl EdgeStyle {
    pub fn as_dot(&self) -> &'static str {
        match self {
            EdgeStyle::None => "none",
            EdgeStyle::Line => "line",
            EdgeStyle::Polyline => "polyline",
            EdgeStyle::Curved => "curved",
            EdgeStyle::Ortho => "ortho",
            EdgeStyle::Spline => "spline",
        }
    }
}

#[derive(Clone)]
pub struct Style {
    pub schedule_rankdir: RankDir,
    pub edge_style: EdgeStyle,

    pub fontname: String,

    pub color_background: String,
    pub color_set: String,
    pub color_set_label: String,
    pub color_set_border: String,
    pub color_edge: Vec<String>,
    pub multiple_set_edge_color: String,

    pub ambiguity_color: String,
    pub ambiguity_bgcolor: String,

    pub penwidth_edge: f32,
}
// colors are from https://iamkate.com/data/12-bit-rainbow/, without the #cc6666
impl Style {
    pub fn light() -> Style {
        Style {
            schedule_rankdir: RankDir::default(),
            edge_style: EdgeStyle::default(),
            fontname: "Helvetica".into(),
            color_background: "white".into(),
            color_set: "#00000008".into(),
            color_set_border: "#00000040".into(),
            color_set_label: "#000000".into(),
            color_edge: vec![
                "#eede00".into(),
                "#881877".into(),
                "#00b0cc".into(),
                "#aa3a55".into(),
                "#44d488".into(),
                "#0090cc".into(),
                "#ee9e44".into(),
                "#663699".into(),
                "#3363bb".into(),
                "#22c2bb".into(),
                "#99d955".into(),
            ],
            multiple_set_edge_color: "blue".into(),
            ambiguity_color: "#c93526".into(),
            ambiguity_bgcolor: "#d3d3d3".into(),
            penwidth_edge: 2.0,
        }
    }

    pub fn dark_discord() -> Style {
        Style {
            schedule_rankdir: RankDir::default(),
            edge_style: EdgeStyle::default(),
            fontname: "Helvetica".into(),
            color_background: "#35393f".into(),
            color_set: "#ffffff44".into(),
            color_set_border: "#ffffff50".into(),
            color_set_label: "#ffffff".into(),
            color_edge: vec![
                "#eede00".into(),
                "#881877".into(),
                "#00b0cc".into(),
                "#aa3a55".into(),
                "#44d488".into(),
                "#0090cc".into(),
                "#ee9e44".into(),
                "#663699".into(),
                "#3363bb".into(),
                "#22c2bb".into(),
                "#99d955".into(),
            ],
            ambiguity_color: "#c93526".into(),
            ambiguity_bgcolor: "#c5daeb".into(),
            multiple_set_edge_color: "blue".into(),
            penwidth_edge: 2.0,
        }
    }

    pub fn dark_github() -> Style {
        Style {
            schedule_rankdir: RankDir::default(),
            edge_style: EdgeStyle::default(),
            fontname: "Helvetica".into(),
            color_background: "#0d1117".into(),
            color_set: "#ffffff44".into(),
            color_set_border: "#ffffff50".into(),
            color_set_label: "#ffffff".into(),
            color_edge: vec![
                "#eede00".into(),
                "#881877".into(),
                "#00b0cc".into(),
                "#aa3a55".into(),
                "#44d488".into(),
                "#0090cc".into(),
                "#ee9e44".into(),
                "#663699".into(),
                "#3363bb".into(),
                "#22c2bb".into(),
                "#99d955".into(),
            ],
            ambiguity_color: "#c93526".into(),
            ambiguity_bgcolor: "#c6e6ff".into(),
            multiple_set_edge_color: "blue".into(),
            penwidth_edge: 2.0,
        }
    }
}
impl Default for Style {
    fn default() -> Self {
        Style::dark_github()
    }
}

type IncludeAmbiguityFn = dyn Fn(
    &dyn System<In = (), Out = ()>,
    &dyn System<In = (), Out = ()>,
    &[ComponentId],
    &World,
) -> bool;

pub struct NodeStyle {
    pub bg_color: String,
    pub text_color: String,
    pub border_color: String,
    pub border_width: String,
}

// Function that maps `System` to `T`
type SystemMapperFn<T> = Box<dyn Fn(&dyn System<In = (), Out = ()>) -> T>;

pub struct Settings {
    pub style: Style,
    pub system_style: SystemMapperFn<SystemStyle>,

    /// When set to `Some`, will only include systems matching the predicate, and their ancestor sets
    pub include_system: Option<SystemMapperFn<bool>>,
    pub collapse_single_system_sets: bool,

    pub ambiguity_enable: bool,
    pub ambiguity_enable_on_world: bool,
    pub include_ambiguity: Option<Box<IncludeAmbiguityFn>>,

    pub prettify_system_names: bool,
}

impl Settings {
    /// Set the `include_system` predicate to match only systems for which their names matches `filter`
    pub fn filter_name(mut self, filter: impl Fn(&str) -> bool + 'static) -> Self {
        self.include_system = Some(Box::new(move |system| {
            let name = system.name();
            filter(&name)
        }));
        self
    }
    /// Set the `include_system` predicate to only match systems from the specified crate
    pub fn filter_in_crate(mut self, crate_: &str) -> Self {
        let crate_ = crate_.to_owned();
        self.include_system = Some(Box::new(move |system| {
            let name = system.name();
            name.starts_with(&crate_)
        }));
        self
    }
    /// Set the `include_system` predicate to only match systems from the specified crates
    pub fn filter_in_crates(mut self, crates: &[&str]) -> Self {
        let crates: Vec<_> = crates.iter().map(|&s| s.to_owned()).collect();
        self.include_system = Some(Box::new(move |system| {
            let name = system.name();
            crates.iter().any(|crate_| name.starts_with(crate_))
        }));
        self
    }

    pub fn get_system_style(&self, system: &dyn System<In = (), Out = ()>) -> NodeStyle {
        let style = (self.system_style)(system);

        // Check if bg is dark
        let [h, s, l, _] = style.bg_color.as_hsla_f32();
        // TODO Fix following: https://ux.stackexchange.com/q/107318
        let is_dark = l < 0.6;

        // Calculate text color based on bg
        let text_color = style.text_color.unwrap_or_else(|| {
            if is_dark {
                Color::hsl(h, s, 0.9)
            } else {
                Color::hsl(h, s, 0.1)
            }
        });

        // Calculate border color based on bg
        let border_color = style.border_color.unwrap_or_else(|| {
            let offset = if is_dark { 0.2 } else { -0.2 };
            let border_l = (l + offset).clamp(0.0, 1.0);

            Color::hsl(h, s, border_l)
        });

        NodeStyle {
            bg_color: color_to_hex(style.bg_color),
            text_color: color_to_hex(text_color),
            border_color: color_to_hex(border_color),
            border_width: style.border_width.to_string(),
        }
    }

    /// Specifies `include_ambiguity` to ignore ambiguities that are only ambiguous with regard to `T`
    pub fn without_single_ambiguities_on<T: 'static>(mut self) -> Self {
        self.include_ambiguity = Some(Box::new(move |_, _, conflicts, world| {
            let &[conflict] = conflicts else { return true };
            let Some(type_id) = world
                .components()
                .get_info(conflict)
                .and_then(|info| info.type_id())
            else {
                return true;
            };
            type_id != TypeId::of::<T>()
        }));
        self
    }

    /// Specifies `include_ambiguity` to ignore ambiguities that are exactly one of the given `type_ids`
    pub fn without_single_ambiguities_on_one_of(mut self, type_ids: &[TypeId]) -> Self {
        let type_ids = type_ids.to_vec();
        self.include_ambiguity = Some(Box::new(move |_, _, conflicts, world| {
            let &[conflict] = conflicts else { return true };
            let Some(type_id) = world
                .components()
                .get_info(conflict)
                .and_then(|info| info.type_id())
            else {
                return true;
            };
            !type_ids.contains(&type_id)
        }));
        self
    }
}

impl Default for Settings {
    fn default() -> Self {
        Self {
            style: Style::default(),
            system_style: Box::new(system_to_style),

            include_system: None,
            collapse_single_system_sets: false,

            ambiguity_enable: true,
            ambiguity_enable_on_world: false,
            include_ambiguity: None,

            prettify_system_names: true,
        }
    }
}