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
use abstio::{CityName, MapName};
use geom::{Distance, Percent, Polygon, Pt2D};
use map_model::City;
use widgetry::{
    Autocomplete, Color, ControlState, DrawBaselayer, EventCtx, GeomBatch, GfxCtx, Key, Line,
    Outcome, Panel, ScreenPt, State, StyledButtons, Text, TextExt, Transition, Widget,
};

use crate::load::{FileLoader, MapLoader};
use crate::render::DrawArea;
use crate::tools::{grey_out_map, nice_map_name, open_browser};
use crate::AppLike;

/// Lets the player switch maps.
pub struct CityPicker<A: AppLike> {
    panel: Panel,
    // In untranslated screen-space
    districts: Vec<(MapName, Color, Polygon)>,
    selected: Option<usize>,
    // Wrapped in an Option just to make calling from event() work.
    on_load: Option<Box<dyn FnOnce(&mut EventCtx, &mut A) -> Transition<A>>>,
}

impl<A: AppLike + 'static> CityPicker<A> {
    pub fn new(
        ctx: &mut EventCtx,
        app: &mut A,
        on_load: Box<dyn FnOnce(&mut EventCtx, &mut A) -> Transition<A>>,
    ) -> Box<dyn State<A>> {
        let city = app.map().get_city_name().clone();
        CityPicker::new_in_city(ctx, on_load, city)
    }

    fn new_in_city(
        ctx: &mut EventCtx,
        on_load: Box<dyn FnOnce(&mut EventCtx, &mut A) -> Transition<A>>,
        city_name: CityName,
    ) -> Box<dyn State<A>> {
        FileLoader::<A, City>::new(
            ctx,
            abstio::path(format!(
                "system/{}/{}/city.bin",
                city_name.country, city_name.city
            )),
            Box::new(move |ctx, app, _, maybe_city| {
                let mut batch = GeomBatch::new();
                let mut districts = Vec::new();
                let mut this_city = vec![];

                // If this city overview doesn't exist, we assume this map is the only one in the
                // city.
                if let Ok(city) = maybe_city {
                    let bounds = city.boundary.get_bounds();

                    let zoom = (0.8 * ctx.canvas.window_width / bounds.width())
                        .min(0.8 * ctx.canvas.window_height / bounds.height());

                    batch.push(app.cs().map_background.clone(), city.boundary);
                    for (area_type, polygon) in city.areas {
                        batch.push(DrawArea::fill(area_type, app.cs()), polygon);
                    }

                    for (name, polygon) in city.regions {
                        let color = app.cs().rotating_color_agents(districts.len());

                        let btn = ctx
                            .style()
                            .btn_outline_light_text(nice_map_name(&name))
                            .label_color(color, ControlState::Default)
                            .no_tooltip();

                        let action = name.path();
                        if &name == app.map().get_name() {
                            let btn = btn.disabled(true);
                            this_city.push(btn.build_widget(ctx, &action));
                        } else {
                            this_city.push(btn.build_widget(ctx, &action));
                            batch.push(color, polygon.to_outline(Distance::meters(200.0)).unwrap());
                            districts.push((name, color, polygon.scale(zoom)));
                        }
                    }
                    batch = batch.scale(zoom);

                    this_city.insert(
                        0,
                        format!("More districts in {}", city_name.describe()).draw_text(ctx),
                    );
                }

                let mut other_cities = vec![Line("Other cities").draw(ctx)];
                for city in CityName::list_all_cities_from_system_data() {
                    if city == city_name {
                        continue;
                    }
                    // If there's only one map in the city, make the button directly load it.
                    let city_path = city.to_path();
                    let button = ctx.style().btn_outline_light_text(&city_path);
                    let maps = MapName::list_all_maps_in_city(&city);
                    if maps.len() == 1 {
                        other_cities.push(button.build_widget(ctx, &maps[0].path()));
                    } else {
                        other_cities.push(button.no_tooltip().build_def(ctx));
                    }
                }
                other_cities.push(
                    ctx.style()
                        .btn_solid_dark_text("Search all maps")
                        .hotkey(Key::Tab)
                        .build_def(ctx),
                );

                Transition::Replace(Box::new(CityPicker {
                    districts,
                    selected: None,
                    on_load: Some(on_load),
                    panel: Panel::new(Widget::col(vec![
                        Widget::row(vec![
                            Line("Select a district").small_heading().draw(ctx),
                            ctx.style().btn_close_widget(ctx),
                        ]),
                        Widget::row(vec![
                            Widget::col(other_cities).centered_vert(),
                            Widget::draw_batch(ctx, batch).named("picker"),
                            Widget::col(this_city).centered_vert(),
                        ]),
                        Widget::custom_row(vec![
                            "Don't see the city you want?"
                                .draw_text(ctx)
                                .centered_vert(),
                            ctx.style()
                                .btn_plain_light()
                                .label_styled_text(
                                    Text::from(
                                        Line("Import a new city into A/B Street")
                                            .fg(Color::hex("#4CA4E5"))
                                            .underlined(),
                                    ),
                                    ControlState::Default,
                                )
                                .build_widget(ctx, "import new city"),
                        ]),
                        if cfg!(not(target_arch = "wasm32")) {
                            ctx.style()
                                .btn_outline_light_text("Download more cities")
                                .build_def(ctx)
                        } else {
                            Widget::nothing()
                        },
                    ]))
                    .build(ctx),
                }))
            }),
        )
    }
}

impl<A: AppLike + 'static> State<A> for CityPicker<A> {
    fn event(&mut self, ctx: &mut EventCtx, app: &mut A) -> Transition<A> {
        match self.panel.event(ctx) {
            Outcome::Clicked(x) => match x.as_ref() {
                "close" => {
                    return Transition::Pop;
                }
                "Search all maps" => {
                    return Transition::Replace(AllCityPicker::new(
                        ctx,
                        self.on_load.take().unwrap(),
                    ));
                }
                "import new city" => {
                    open_browser("https://a-b-street.github.io/docs/howto/new_city.html");
                }
                "Download more cities" => {
                    let _ = "just stop this from counting as an attribute on an expression";
                    #[cfg(not(target_arch = "wasm32"))]
                    {
                        return Transition::Replace(crate::tools::updater::Picker::new(
                            ctx,
                            self.on_load.take().unwrap(),
                        ));
                    }
                }
                x => {
                    if let Some(name) = MapName::from_path(x) {
                        return Transition::Replace(MapLoader::new(
                            ctx,
                            app,
                            name,
                            self.on_load.take().unwrap(),
                        ));
                    }
                    // Browse maps for another city without loading any map there
                    return Transition::Replace(CityPicker::new_in_city(
                        ctx,
                        self.on_load.take().unwrap(),
                        CityName::parse(x).unwrap(),
                    ));
                }
            },
            _ => {}
        }

        if ctx.redo_mouseover() {
            self.selected = None;
            if let Some(cursor) = ctx.canvas.get_cursor_in_screen_space() {
                let rect = self.panel.rect_of("picker");
                if rect.contains(cursor) {
                    let pt = Pt2D::new(cursor.x - rect.x1, cursor.y - rect.y1);
                    for (idx, (_, _, poly)) in self.districts.iter().enumerate() {
                        if poly.contains_pt(pt) {
                            self.selected = Some(idx);
                            break;
                        }
                    }
                } else if let Some(btn) = self.panel.currently_hovering() {
                    for (idx, (name, _, _)) in self.districts.iter().enumerate() {
                        if &name.map == btn {
                            self.selected = Some(idx);
                            break;
                        }
                    }
                }
            }
        }
        if let Some(idx) = self.selected {
            let name = &self.districts[idx].0;
            if ctx.normal_left_click() {
                return Transition::Replace(MapLoader::new(
                    ctx,
                    app,
                    name.clone(),
                    self.on_load.take().unwrap(),
                ));
            }
        }

        Transition::Keep
    }

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

    fn draw(&self, g: &mut GfxCtx, app: &A) {
        grey_out_map(g, app);
        self.panel.draw(g);

        if let Some(idx) = self.selected {
            let (name, color, poly) = &self.districts[idx];
            let rect = self.panel.rect_of("picker");
            g.fork(
                Pt2D::new(0.0, 0.0),
                ScreenPt::new(rect.x1, rect.y1),
                1.0,
                None,
            );
            g.draw_polygon(color.alpha(0.5), poly.clone());
            g.unfork();

            g.draw_mouse_tooltip(Text::from(Line(nice_map_name(name))));
        }
    }
}

struct AllCityPicker<A: AppLike> {
    panel: Panel,
    // Wrapped in an Option just to make calling from event() work.
    on_load: Option<Box<dyn FnOnce(&mut EventCtx, &mut A) -> Transition<A>>>,
}

impl<A: AppLike + 'static> AllCityPicker<A> {
    fn new(
        ctx: &mut EventCtx,
        on_load: Box<dyn FnOnce(&mut EventCtx, &mut A) -> Transition<A>>,
    ) -> Box<dyn State<A>> {
        let mut autocomplete_entries = Vec::new();
        let mut buttons = Vec::new();

        for name in MapName::list_all_maps() {
            buttons.push(
                ctx.style()
                    .btn_outline_light_text(&name.describe())
                    .build_widget(ctx, &name.path())
                    .margin_right(10)
                    .margin_below(10),
            );
            autocomplete_entries.push((name.describe(), name.path()));
        }

        Box::new(AllCityPicker {
            on_load: Some(on_load),
            panel: Panel::new(Widget::col(vec![
                Widget::row(vec![
                    Line("Select a district").small_heading().draw(ctx),
                    ctx.style().btn_close_widget(ctx),
                ]),
                Widget::row(vec![
                    Widget::draw_svg(ctx, "system/assets/tools/search.svg"),
                    Autocomplete::new(ctx, autocomplete_entries).named("search"),
                ])
                .padding(8),
                Widget::custom_row(buttons).flex_wrap(ctx, Percent::int(70)),
            ]))
            .exact_size_percent(80, 80)
            .build(ctx),
        })
    }
}

impl<A: AppLike + 'static> State<A> for AllCityPicker<A> {
    fn event(&mut self, ctx: &mut EventCtx, app: &mut A) -> Transition<A> {
        match self.panel.event(ctx) {
            Outcome::Clicked(x) => match x.as_ref() {
                "close" => {
                    return Transition::Pop;
                }
                path => {
                    return Transition::Replace(MapLoader::new(
                        ctx,
                        app,
                        MapName::from_path(path).unwrap(),
                        self.on_load.take().unwrap(),
                    ));
                }
            },
            _ => {}
        }
        if let Some(mut paths) = self.panel.autocomplete_done::<String>("search") {
            if !paths.is_empty() {
                return Transition::Replace(MapLoader::new(
                    ctx,
                    app,
                    MapName::from_path(&paths.remove(0)).unwrap(),
                    self.on_load.take().unwrap(),
                ));
            }
        }

        Transition::Keep
    }

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

    fn draw(&self, g: &mut GfxCtx, app: &A) {
        grey_out_map(g, app);
        self.panel.draw(g);
    }
}