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
use std::collections::BTreeSet;

use abstutil::prettyprint_usize;
use geom::{Circle, Distance, Pt2D, Time};
use map_gui::tools::{checkbox_per_mode, make_heatmap, HeatmapOptions};
use sim::{Problem, TripInfo};
use synthpop::TripMode;
use widgetry::mapspace::ToggleZoomed;
use widgetry::{
    Color, EventCtx, GfxCtx, Line, Outcome, Panel, PanelDims, Slider, Text, TextExt, Toggle, Widget,
};

use crate::app::App;
use crate::layer::{header, problems_diff, Layer, LayerOutcome, PANEL_PLACEMENT};

pub struct ProblemMap {
    time: Time,
    opts: Options,
    draw: ToggleZoomed,
    panel: Panel,
}

impl Layer for ProblemMap {
    fn name(&self) -> Option<&'static str> {
        Some("problem map")
    }
    fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Option<LayerOutcome> {
        if app.primary.sim.time() != self.time {
            let mut new = ProblemMap::new(ctx, app, self.opts.clone());
            new.panel.restore(ctx, &self.panel);
            *self = new;
        }

        match self.panel.event(ctx) {
            Outcome::Clicked(x) => match x.as_ref() {
                "close" => {
                    return Some(LayerOutcome::Close);
                }
                _ => unreachable!(),
            },
            Outcome::Changed(x) => {
                if x == "Compare before proposal" {
                    return Some(LayerOutcome::Replace(Box::new(
                        problems_diff::RelativeProblemMap::new(
                            ctx,
                            app,
                            problems_diff::Options::new(),
                        ),
                    )));
                }

                let new_opts = self.options(app);
                if self.opts != new_opts {
                    *self = ProblemMap::new(ctx, app, new_opts);
                }
            }
            _ => {}
        }
        None
    }
    fn draw(&self, g: &mut GfxCtx, _: &App) {
        self.panel.draw(g);
        self.draw.draw(g);
    }
    fn draw_minimap(&self, g: &mut GfxCtx) {
        g.redraw(&self.draw.unzoomed);
    }
}

impl ProblemMap {
    pub fn new(ctx: &mut EventCtx, app: &App, opts: Options) -> ProblemMap {
        let mut pts = Vec::new();
        for (trip, problems) in &app.primary.sim.get_analytics().problems_per_trip {
            for (time, problem) in problems {
                if opts.show(app.primary.sim.trip_info(*trip), *time, problem) {
                    pts.push(problem.point(&app.primary.map));
                }
            }
        }
        let num_pts = pts.len();

        let mut draw = ToggleZoomed::builder();
        let legend = if let Some(ref o) = opts.heatmap {
            Some(make_heatmap(
                ctx,
                &mut draw.unzoomed,
                app.primary.map.get_bounds(),
                pts,
                o,
            ))
        } else {
            let circle = Circle::new(Pt2D::new(0.0, 0.0), Distance::meters(10.0)).to_polygon();
            // TODO Different colors per problem type
            for pt in pts {
                draw.unzoomed
                    .push(Color::PURPLE.alpha(0.8), circle.translate(pt.x(), pt.y()));
            }
            None
        };
        let controls = make_controls(ctx, app, &opts, legend, num_pts);
        ProblemMap {
            time: app.primary.sim.time(),
            opts,
            draw: draw.build(ctx),
            panel: controls,
        }
    }

    fn options(&self, app: &App) -> Options {
        let heatmap = if self.panel.is_checked("Show heatmap") {
            Some(HeatmapOptions::from_controls(&self.panel))
        } else {
            None
        };
        let mut modes = BTreeSet::new();
        for m in TripMode::all() {
            if self.panel.is_checked(m.ongoing_verb()) {
                modes.insert(m);
            }
        }
        let end_of_day = app.primary.sim.get_end_of_day();
        Options {
            heatmap,
            modes,
            time1: end_of_day.percent_of(self.panel.slider("time1").get_percent()),
            time2: end_of_day.percent_of(self.panel.slider("time2").get_percent()),
            show_delays: self.panel.is_checked("show delays"),
            show_complex_crossings: self
                .panel
                .is_checked("show where cyclists cross complex intersections"),
            show_overtakes: self
                .panel
                .is_checked("show where cars want to overtake cyclists"),
            show_arterial_crossings: self
                .panel
                .is_checked("show where pedestrians cross arterial intersections"),
            show_overcrowding: self
                .panel
                .is_checked("show where pedestrians are over-crowded"),
        }
    }
}

#[derive(Clone, PartialEq)]
pub struct Options {
    // If None, just a dot map
    heatmap: Option<HeatmapOptions>,
    modes: BTreeSet<TripMode>,
    time1: Time,
    time2: Time,
    show_delays: bool,
    show_complex_crossings: bool,
    show_overtakes: bool,
    show_arterial_crossings: bool,
    show_overcrowding: bool,
}

impl Options {
    pub fn new(app: &App) -> Options {
        Options {
            heatmap: Some(HeatmapOptions::new()),
            modes: TripMode::all().into_iter().collect(),
            time1: Time::START_OF_DAY,
            time2: app.primary.sim.get_end_of_day(),
            show_delays: true,
            show_complex_crossings: true,
            show_overtakes: true,
            show_arterial_crossings: true,
            show_overcrowding: true,
        }
    }

    fn show(&self, trip: TripInfo, time: Time, problem: &Problem) -> bool {
        if !self.modes.contains(&trip.mode) || time < self.time1 || time > self.time2 {
            return false;
        }
        match problem {
            Problem::IntersectionDelay(_, _) => self.show_delays,
            Problem::ComplexIntersectionCrossing(_) => self.show_complex_crossings,
            Problem::OvertakeDesired(_) => self.show_overtakes,
            Problem::ArterialIntersectionCrossing(_) => self.show_arterial_crossings,
            Problem::PedestrianOvercrowding(_) => self.show_overcrowding,
        }
    }
}

fn make_controls(
    ctx: &mut EventCtx,
    app: &App,
    opts: &Options,
    legend: Option<Widget>,
    num_problems: usize,
) -> Panel {
    let mut col = vec![
        header(ctx, "Problems encountered"),
        Text::from_all(vec![
            Line("Matching problems: ").secondary(),
            Line(prettyprint_usize(num_problems)),
        ])
        .into_widget(ctx),
    ];
    if app.has_prebaked().is_some() {
        col.push(Toggle::switch(ctx, "Compare before proposal", None, false));
    }

    // TODO You can't drag the sliders, since we don't remember that we're dragging a particular
    // slider when we recreate it here. Use panel.replace?
    let end_of_day = app.primary.sim.get_end_of_day();
    col.push(Widget::row(vec![
        "Happening between:".text_widget(ctx).margin_right(20),
        Slider::area(
            ctx,
            0.15 * ctx.canvas.window_width,
            opts.time1.to_percent(end_of_day),
            "time1",
        )
        .align_right(),
    ]));
    col.push(Widget::row(vec![
        "and:".text_widget(ctx).margin_right(20),
        Slider::area(
            ctx,
            0.15 * ctx.canvas.window_width,
            opts.time2.to_percent(end_of_day),
            "time2",
        )
        .align_right(),
    ]));
    col.push(checkbox_per_mode(ctx, app, &opts.modes));
    col.push(Toggle::checkbox(ctx, "show delays", None, opts.show_delays));
    col.push(Toggle::checkbox(
        ctx,
        "show where cyclists cross complex intersections",
        None,
        opts.show_complex_crossings,
    ));
    col.push(Toggle::checkbox(
        ctx,
        "show where cars want to overtake cyclists",
        None,
        opts.show_overtakes,
    ));
    col.push(Toggle::checkbox(
        ctx,
        "show where pedestrians cross arterial intersections",
        None,
        opts.show_arterial_crossings,
    ));
    col.push(Toggle::checkbox(
        ctx,
        "show where pedestrians are over-crowded",
        None,
        opts.show_overcrowding,
    ));

    col.push(Toggle::choice(
        ctx,
        "Show heatmap",
        "Heatmap",
        "Points",
        None,
        opts.heatmap.is_some(),
    ));
    if let Some(ref o) = opts.heatmap {
        col.push(Line("Heatmap Options").small_heading().into_widget(ctx));
        col.extend(o.to_controls(ctx, legend.unwrap()));
    }

    Panel::new_builder(Widget::col(col))
        .aligned_pair(PANEL_PLACEMENT)
        // TODO Tune and use more widely
        .dims_height(PanelDims::MaxPercent(0.6))
        // TODO Not sure why needed -- if you leave the mouse on the right spot,
        // Outcome::Changed(time1) happens?
        .ignore_initial_events()
        .build(ctx)
}