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
//! This is a tool to experiment with the concept of 15-minute neighborhoods. Can you access your
//! daily needs (like groceries, a cafe, a library) within a 15-minute walk, bike ride, or public
//! transit ride of your home?
//!
//! See https://github.com/dabreegster/abstreet/issues/393 for more context.

use abstutil::prettyprint_usize;
use geom::{Distance, Duration, Pt2D};
use map_gui::tools::{
    amenity_type, nice_map_name, open_browser, CityPicker, ColorLegend, PopupMsg,
};
use map_gui::{Cached, ID};
use map_model::connectivity::WalkingOptions;
use map_model::{Building, BuildingID};
use widgetry::table::{Col, Filter, Table};
use widgetry::{
    lctrl, Btn, Checkbox, Color, DrawBaselayer, Drawable, EventCtx, GeomBatch, GfxCtx,
    HorizontalAlignment, Key, Line, Outcome, Panel, RewriteColor, State, Text, TextExt, Transition,
    VerticalAlignment, Widget,
};

use crate::isochrone::{Isochrone, Options};
use crate::App;

/// This is the UI state for exploring the isochrone/walkshed from a single building.
pub struct Viewer {
    panel: Panel,
    highlight_start: Drawable,
    isochrone: Isochrone,

    hovering_on_bldg: Cached<HoverKey, HoverOnBuilding>,
}

impl Viewer {
    /// Start with a random building
    pub fn random_start(ctx: &mut EventCtx, app: &App) -> Box<dyn State<App>> {
        let bldgs = app.map.all_buildings();
        let start = bldgs[bldgs.len() / 2].id;
        Viewer::new(ctx, app, start)
    }

    pub fn new(ctx: &mut EventCtx, app: &App, start: BuildingID) -> Box<dyn State<App>> {
        let options = Options::Walking(WalkingOptions::default());
        let start = app.map.get_b(start);
        let isochrone = Isochrone::new(ctx, app, start.id, options);
        let highlight_start = draw_star(ctx, start.polygon.center());
        let panel = build_panel(ctx, app, start, &isochrone);

        Box::new(Viewer {
            panel,
            highlight_start: highlight_start,
            isochrone,
            hovering_on_bldg: Cached::new(),
        })
    }
}

impl State<App> for Viewer {
    fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Transition<App> {
        // Allow panning and zooming
        ctx.canvas_movement();

        if ctx.redo_mouseover() {
            let isochrone = &self.isochrone;
            self.hovering_on_bldg
                .update(HoverOnBuilding::key(ctx, app), |key| {
                    HoverOnBuilding::value(ctx, app, key, isochrone)
                });
            // Also update this to conveniently get an outline drawn. Note we don't want to do this
            // inside the callback above, because it doesn't run when the key becomes None.
            app.current_selection = self.hovering_on_bldg.key().map(|(b, _)| ID::Building(b));
        }

        // Don't call normal_left_click unless we're hovering on something in map-space; otherwise
        // panel.event never sees clicks.
        if let Some((hover_id, _)) = self.hovering_on_bldg.key() {
            if ctx.normal_left_click() {
                let start = app.map.get_b(hover_id);
                self.isochrone = Isochrone::new(ctx, app, start.id, self.isochrone.options.clone());
                self.highlight_start = draw_star(ctx, start.polygon.center());
                self.panel = build_panel(ctx, app, start, &self.isochrone);
                // Any previous hover is from the perspective of the old `highlight_start`.
                // Remove it so we don't have a dotted line to the previous isochrone's origin
                self.hovering_on_bldg.clear();
            }
        }

        match self.panel.event(ctx) {
            Outcome::Clicked(x) => match x.as_ref() {
                "change map" => {
                    return Transition::Push(CityPicker::new(
                        ctx,
                        app,
                        Box::new(|ctx, app| {
                            Transition::Multi(vec![
                                Transition::Pop,
                                Transition::Replace(Self::random_start(ctx, app)),
                            ])
                        }),
                    ));
                }
                "close" => {
                    return Transition::Pop;
                }
                "About" => {
                    return Transition::Push(PopupMsg::new(
                        ctx,
                        "15-minute neighborhood explorer",
                        vec![
                            "What if you could access most of your daily needs with a 15-minute \
                             walk or bike ride from your house?",
                            "Wouldn't it be nice to not rely on a climate unfriendly motor \
                             vehicle and get stuck in traffic for these simple errands?",
                            "Different cities around the world are talking about what design and \
                             policy changes could lead to 15-minute neighborhoods.",
                            "This tool lets you see what commercial amenities are near you right \
                             now, using data from OpenStreetMap.",
                            "",
                            "Note that sidewalks and crosswalks are assumed on most roads.",
                            "Especially around North Seattle, many roads lack sidewalks and \
                             aren't safe for some people to use.",
                            "We're working to improve the accuracy of the map.",
                        ],
                    ));
                }
                // If we reach here, we must've clicked one of the buttons for an amenity
                category => {
                    return Transition::Push(ExploreAmenities::new(
                        ctx,
                        app,
                        &self.isochrone,
                        category,
                    ));
                }
            },
            Outcome::Changed => {
                let options = options_from_controls(&self.panel);
                self.isochrone = Isochrone::new(ctx, app, self.isochrone.start, options);
                self.panel = build_panel(
                    ctx,
                    app,
                    app.map.get_b(self.isochrone.start),
                    &self.isochrone,
                );
            }
            _ => {}
        }

        Transition::Keep
    }

    fn draw(&self, g: &mut GfxCtx, _: &App) {
        g.redraw(&self.isochrone.draw);
        g.redraw(&self.highlight_start);
        self.panel.draw(g);
        if let Some(ref hover) = self.hovering_on_bldg.value() {
            g.draw_mouse_tooltip(hover.tooltip.clone());
            g.redraw(&hover.drawn_route);
        }
    }
}

fn options_to_controls(ctx: &mut EventCtx, opts: &Options) -> Widget {
    let mut rows = vec![Checkbox::toggle(
        ctx,
        "walking / biking",
        "walking",
        "biking",
        None,
        match opts {
            Options::Walking(_) => true,
            Options::Biking => false,
        },
    )];
    match opts {
        Options::Walking(ref opts) => {
            rows.push(Checkbox::switch(
                ctx,
                "Allow walking on the shoulder of the road without a sidewalk",
                None,
                opts.allow_shoulders,
            ));
        }
        Options::Biking => {}
    }
    Widget::col(rows)
}

fn options_from_controls(panel: &Panel) -> Options {
    if panel.is_checked("walking / biking") {
        Options::Walking(WalkingOptions {
            allow_shoulders: panel
                .maybe_is_checked("Allow walking on the shoulder of the road without a sidewalk")
                .unwrap_or(true),
        })
    } else {
        Options::Biking
    }
}

fn draw_star(ctx: &mut EventCtx, center: Pt2D) -> Drawable {
    ctx.upload(
        GeomBatch::load_svg(ctx, "system/assets/tools/star.svg")
            .centered_on(center)
            .color(RewriteColor::ChangeAll(Color::BLACK)),
    )
}

fn build_panel(ctx: &mut EventCtx, app: &App, start: &Building, isochrone: &Isochrone) -> Panel {
    let mut rows = Vec::new();

    rows.push(Widget::row(vec![
        Line("15-minute neighborhood explorer")
            .small_heading()
            .draw(ctx),
        Btn::close(ctx),
    ]));

    rows.push(Widget::row(vec![
        "Map:".draw_text(ctx),
        Btn::pop_up(ctx, Some(nice_map_name(app.map.get_name()))).build(
            ctx,
            "change map",
            lctrl(Key::L),
        ),
    ]));

    rows.push(
        Text::from_all(vec![
            Line("Starting from: ").secondary(),
            Line(&start.address),
        ])
        .draw(ctx),
    );

    rows.push(
        Text::from_all(vec![
            Line("Estimated population: ").secondary(),
            Line(prettyprint_usize(isochrone.population)),
        ])
        .draw(ctx),
    );

    rows.push(
        Text::from_all(vec![
            Line("Estimated street parking spots: ").secondary(),
            Line(prettyprint_usize(isochrone.onstreet_parking_spots)),
        ])
        .draw(ctx),
    );

    rows.push(ColorLegend::categories(
        ctx,
        vec![
            (Color::GREEN, "5 mins"),
            (Color::ORANGE, "10 mins"),
            (Color::RED, "15 mins"),
        ],
    ));

    for (amenity, buildings) in isochrone.amenities_reachable.borrow() {
        rows.push(
            Btn::text_fg(format!("{}: {}", amenity, buildings.len())).build(ctx, *amenity, None),
        );
    }

    // Start of toolbar
    rows.push(Widget::horiz_separator(ctx, 0.3).margin_above(10));

    rows.push(options_to_controls(ctx, &isochrone.options));
    rows.push(Btn::plaintext("About").build_def(ctx, None));

    Panel::new(Widget::col(rows))
        .aligned(HorizontalAlignment::Right, VerticalAlignment::Top)
        .build(ctx)
}

struct HoverOnBuilding {
    tooltip: Text,
    drawn_route: Drawable,
}
/// (building, scale factor)
type HoverKey = (BuildingID, f64);

impl HoverOnBuilding {
    fn key(ctx: &EventCtx, app: &App) -> Option<HoverKey> {
        match app.mouseover_unzoomed_buildings(ctx) {
            Some(ID::Building(b)) => {
                let scale_factor = if ctx.canvas.cam_zoom >= app.opts.min_zoom_for_detail {
                    1.0
                } else {
                    10.0
                };
                Some((b, scale_factor))
            }
            _ => None,
        }
    }

    fn value(
        ctx: &mut EventCtx,
        app: &App,
        key: HoverKey,
        isochrone: &Isochrone,
    ) -> HoverOnBuilding {
        debug!("Calculating route for {:?}", key);

        let (hover_id, scale_factor) = key;
        let mut batch = GeomBatch::new();
        if let Some(polyline) = isochrone
            .path_to(&app.map, hover_id)
            .and_then(|path| path.trace(&app.map))
        {
            let dashed_lines = polyline.dashed_lines(
                Distance::meters(0.75 * scale_factor),
                Distance::meters(1.0 * scale_factor),
                Distance::meters(0.4 * scale_factor),
            );
            batch.extend(Color::BLACK, dashed_lines);
        }

        HoverOnBuilding {
            tooltip: if let Some(time) = isochrone.time_to_reach_building.get(&hover_id) {
                Text::from(Line(format!("{} away", time)))
            } else {
                Text::from(Line("This is more than 15 minutes away"))
            },
            drawn_route: ctx.upload(batch),
        }
    }
}

struct ExploreAmenities {
    category: String,
    table: Table<App, Entry, ()>,
    panel: Panel,
}

struct Entry {
    bldg: BuildingID,
    name: String,
    category: String,
    address: String,
    duration_away: Duration,
}

impl ExploreAmenities {
    fn new(
        ctx: &mut EventCtx,
        app: &App,
        isochrone: &Isochrone,
        category: &str,
    ) -> Box<dyn State<App>> {
        let mut entries = Vec::new();
        for b in isochrone.amenities_reachable.get(category) {
            let bldg = app.map.get_b(*b);
            for amenity in &bldg.amenities {
                if amenity_type(&amenity.amenity_type) == Some(category) {
                    entries.push(Entry {
                        bldg: bldg.id,
                        name: amenity.names.get(app.opts.language.as_ref()).to_string(),
                        category: amenity.amenity_type.clone(),
                        address: bldg.address.clone(),
                        duration_away: isochrone.time_to_reach_building[&bldg.id],
                    });
                }
            }
        }

        let mut table: Table<App, Entry, ()> = Table::new(
            entries,
            // The label has extra junk to avoid crashing when one building has two stores
            Box::new(|x| format!("{}: {}", x.bldg.0, x.name)),
            "Time to reach",
            Filter::empty(),
        );
        table.column(
            "Category",
            Box::new(|ctx, _, x| Text::from(Line(&x.category)).render(ctx)),
            Col::Sortable(Box::new(|rows| rows.sort_by_key(|x| x.category.clone()))),
        );
        table.static_col("Name", Box::new(|x| x.name.clone()));
        table.static_col("Address", Box::new(|x| x.address.clone()));
        table.column(
            "Time to reach",
            Box::new(|ctx, app, x| {
                Text::from(Line(x.duration_away.to_string(&app.opts.units))).render(ctx)
            }),
            Col::Sortable(Box::new(|rows| rows.sort_by_key(|x| x.duration_away))),
        );

        let panel = Panel::new(Widget::col(vec![
            Widget::row(vec![
                Line(format!("{} within 15 minutes", category))
                    .small_heading()
                    .draw(ctx),
                Btn::close(ctx),
            ]),
            table.render(ctx, app),
        ]))
        .build(ctx);

        Box::new(ExploreAmenities {
            category: category.to_string(),
            table,
            panel,
        })
    }

    fn recalc(&mut self, ctx: &mut EventCtx, app: &App) {
        let mut new = Panel::new(Widget::col(vec![
            Widget::row(vec![
                Line(format!("{} within 15 minutes", self.category))
                    .small_heading()
                    .draw(ctx),
                Btn::close(ctx),
            ]),
            self.table.render(ctx, app),
        ]))
        .build(ctx);
        new.restore(ctx, &self.panel);
        self.panel = new;
    }
}

impl State<App> for ExploreAmenities {
    fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Transition<App> {
        ctx.canvas_movement();

        match self.panel.event(ctx) {
            Outcome::Clicked(x) => {
                if self.table.clicked(&x) {
                    self.recalc(ctx, app);
                } else if x == "close" {
                    return Transition::Pop;
                } else if let Some(idx) = x.split(":").next().and_then(|x| x.parse::<usize>().ok())
                {
                    let b = app.map.get_b(BuildingID(idx));
                    open_browser(b.orig_id.to_string());
                } else {
                    unreachable!()
                }
            }
            Outcome::Changed => {
                self.table.panel_changed(&self.panel);
                self.recalc(ctx, app);
            }
            _ => {}
        }

        Transition::Keep
    }

    fn draw_baselayer(&self) -> DrawBaselayer {
        DrawBaselayer::PreviousState
    }

    fn draw(&self, g: &mut GfxCtx, _: &App) {
        self.panel.draw(g);
    }
}