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
use maplit::btreeset;

use geom::Speed;
use map_model::{LaneType, RoadID};
use widgetry::{
    hotkeys, Btn, Choice, Color, Drawable, EventCtx, GfxCtx, HorizontalAlignment, Key, Line,
    Outcome, Panel, State, Text, TextExt, VerticalAlignment, Widget,
};

use crate::app::App;
use crate::edit::select::RoadSelector;
use crate::edit::{apply_map_edits, speed_limit_choices, try_change_lt, ConfirmDiscard};
use crate::game::{PopupMsg, Transition};

pub struct BulkSelect {
    panel: Panel,
    selector: RoadSelector,
}

impl BulkSelect {
    pub fn new(ctx: &mut EventCtx, app: &mut App, start: RoadID) -> Box<dyn State<App>> {
        let selector = RoadSelector::new(ctx, app, btreeset! {start});
        let panel = make_select_panel(ctx, &selector);
        Box::new(BulkSelect { panel, selector })
    }
}

fn make_select_panel(ctx: &mut EventCtx, selector: &RoadSelector) -> Panel {
    Panel::new(Widget::col(vec![
        Line("Edit many roads").small_heading().draw(ctx),
        selector.make_controls(ctx),
        Widget::row(vec![
            if selector.roads.is_empty() {
                Btn::text_fg("Edit 0 roads").inactive(ctx)
            } else {
                Btn::text_fg(format!("Edit {} roads", selector.roads.len())).build(
                    ctx,
                    "edit roads",
                    hotkeys(vec![Key::E, Key::Enter]),
                )
            },
            Btn::text_fg(format!(
                "Export {} roads to shared-row",
                selector.roads.len()
            ))
            .build(ctx, "export roads to shared-row", None),
            Btn::text_fg("export one road to Streetmix").build_def(ctx, None),
            Btn::text_fg("Cancel").build_def(ctx, Key::Escape),
        ])
        .evenly_spaced(),
    ]))
    .aligned(HorizontalAlignment::Center, VerticalAlignment::Top)
    .build(ctx)
}

impl State<App> for BulkSelect {
    fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Transition {
        match self.panel.event(ctx) {
            Outcome::Clicked(x) => match x.as_ref() {
                "Cancel" => {
                    return Transition::Pop;
                }
                "edit roads" => {
                    return Transition::Replace(crate::edit::bulk::BulkEdit::new(
                        ctx,
                        app,
                        self.selector.roads.iter().cloned().collect(),
                        self.selector.preview.take().unwrap(),
                    ));
                }
                "export roads to shared-row" => {
                    let path = crate::debug::shared_row::export(
                        self.selector.roads.iter().cloned().collect(),
                        &app.primary.map,
                    );
                    return Transition::Push(PopupMsg::new(
                        ctx,
                        "Roads exported",
                        vec![format!("Roads exported to shared-row format at {}", path)],
                    ));
                }
                "export one road to Streetmix" => {
                    let path = crate::debug::streetmix::export(
                        *self.selector.roads.iter().next().unwrap(),
                        &app.primary.map,
                    );
                    return Transition::Push(PopupMsg::new(
                        ctx,
                        "One road exported",
                        vec![format!(
                            "One arbitrary road from your selection exported to Streetmix format \
                             at {}",
                            path
                        )],
                    ));
                }
                x => {
                    if self.selector.event(ctx, app, Some(x)) {
                        self.panel = make_select_panel(ctx, &self.selector);
                    }
                }
            },
            _ => {
                if self.selector.event(ctx, app, None) {
                    self.panel = make_select_panel(ctx, &self.selector);
                }
            }
        }

        Transition::Keep
    }

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

struct BulkEdit {
    panel: Panel,
    roads: Vec<RoadID>,
    preview: Drawable,
}

impl BulkEdit {
    fn new(
        ctx: &mut EventCtx,
        app: &App,
        roads: Vec<RoadID>,
        preview: Drawable,
    ) -> Box<dyn State<App>> {
        Box::new(BulkEdit {
            panel: Panel::new(Widget::col(vec![
                Line(format!("Editing {} roads", roads.len()))
                    .small_heading()
                    .draw(ctx),
                "Lane types".draw_text(ctx),
                make_lt_switcher(ctx, vec![(None, None)]).named("lt transformations"),
                {
                    let mut choices = vec![Choice::new("don't change", None)];
                    for c in speed_limit_choices(app) {
                        choices.push(Choice::new(c.label, Some(c.data)));
                    }
                    Widget::row(vec![
                        "Change speed limit:".draw_text(ctx).centered_vert(),
                        Widget::dropdown(ctx, "speed limit", None, choices),
                    ])
                },
                Widget::row(vec![
                    Btn::text_bg2("Finish").build_def(ctx, Key::Enter),
                    Btn::plaintext_custom(
                        "Cancel",
                        Text::from(Line("Cancel").fg(Color::hex("#FF5E5E"))),
                    )
                    .build_def(ctx, Key::Escape)
                    .align_right(),
                ]),
            ]))
            .aligned(HorizontalAlignment::Center, VerticalAlignment::Top)
            .build(ctx),
            roads,
            preview,
        })
    }
}

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

        match self.panel.event(ctx) {
            Outcome::Clicked(x) => match x.as_ref() {
                "Cancel" => {
                    if self
                        .panel
                        .dropdown_value::<Option<Speed>, _>("speed limit")
                        .is_none()
                        && get_lt_transformations(&self.panel)
                            .into_iter()
                            .all(|(lt1, lt2)| lt1.is_none() && lt2.is_none())
                    {
                        return Transition::Pop;
                    }
                    return Transition::Push(ConfirmDiscard::new(ctx, Box::new(move |_| {})));
                }
                "Finish" => {
                    return Transition::Replace(make_bulk_edits(
                        ctx,
                        app,
                        &self.roads,
                        self.panel.dropdown_value("speed limit"),
                        get_lt_transformations(&self.panel),
                    ));
                }
                "add another lane type transformation" => {
                    let mut pairs = get_lt_transformations(&self.panel);
                    pairs.push((None, None));
                    let switcher = make_lt_switcher(ctx, pairs);
                    self.panel.replace(ctx, "lt transformations", switcher);
                }
                _ => unreachable!(),
            },
            _ => {}
        }

        Transition::Keep
    }

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

fn get_lt_transformations(panel: &Panel) -> Vec<(Option<LaneType>, Option<LaneType>)> {
    let mut pairs = Vec::new();
    let mut idx = 0;
    loop {
        if let Some(from) = panel.maybe_dropdown_value(format!("from lt #{}", idx)) {
            let to = panel.dropdown_value(format!("to lt #{}", idx));
            pairs.push((from, to));
            idx += 1;
        } else {
            break;
        }
    }
    pairs
}

fn make_lt_switcher(
    ctx: &mut EventCtx,
    pairs: Vec<(Option<LaneType>, Option<LaneType>)>,
) -> Widget {
    let mut col = Vec::new();
    for (idx, (from, to)) in pairs.into_iter().enumerate() {
        col.push(Widget::row(vec![
            "Change all".draw_text(ctx).centered_vert(),
            Widget::dropdown(
                ctx,
                format!("from lt #{}", idx),
                from,
                vec![
                    Choice::new("---", None),
                    Choice::new("driving", Some(LaneType::Driving)),
                    Choice::new("parking", Some(LaneType::Parking)),
                    Choice::new("bike", Some(LaneType::Biking)),
                    Choice::new("bus", Some(LaneType::Bus)),
                    Choice::new("construction", Some(LaneType::Construction)),
                ],
            ),
            "lanes to".draw_text(ctx).centered_vert(),
            Widget::dropdown(
                ctx,
                format!("to lt #{}", idx),
                to,
                vec![
                    Choice::new("---", None),
                    Choice::new("driving", Some(LaneType::Driving)),
                    Choice::new("parking", Some(LaneType::Parking)),
                    Choice::new("bike", Some(LaneType::Biking)),
                    Choice::new("bus", Some(LaneType::Bus)),
                    Choice::new("construction", Some(LaneType::Construction)),
                ],
            ),
            Btn::plaintext_custom(
                "add another lane type transformation",
                Text::from(Line("+ Add").fg(Color::hex("#4CA7E9"))),
            )
            .build_def(ctx, None),
        ]));
    }
    Widget::col(col)
}

fn make_bulk_edits(
    ctx: &mut EventCtx,
    app: &mut App,
    roads: &Vec<RoadID>,
    speed_limit: Option<Speed>,
    lt_transformations: Vec<(Option<LaneType>, Option<LaneType>)>,
) -> Box<dyn State<App>> {
    let mut speed_changes = 0;
    let mut lt_changes = 0;
    let mut errors = Vec::new();
    ctx.loading_screen("change lane types", |ctx, timer| {
        if let Some(speed) = speed_limit {
            let mut edits = app.primary.map.get_edits().clone();
            for r in roads {
                if app.primary.map.get_r(*r).speed_limit != speed {
                    edits
                        .commands
                        .push(app.primary.map.edit_road_cmd(*r, |new| {
                            new.speed_limit = speed;
                        }));
                    speed_changes += 1;
                }
            }
            apply_map_edits(ctx, app, edits);
        }

        for (maybe_from, maybe_to) in lt_transformations {
            let from = if let Some(lt) = maybe_from {
                lt
            } else {
                continue;
            };
            let to = if let Some(lt) = maybe_to {
                lt
            } else {
                continue;
            };
            timer.start_iter(format!("change {:?} to {:?}", from, to), roads.len());
            for r in roads {
                timer.next();
                for l in app.primary.map.get_r(*r).all_lanes() {
                    if app.primary.map.get_l(l).lane_type == from {
                        match try_change_lt(ctx, &mut app.primary.map, l, to) {
                            Ok(cmd) => {
                                let mut edits = app.primary.map.get_edits().clone();
                                edits.commands.push(cmd);
                                // Do this immediately, so the next lane we consider sees the true
                                // state of the world.
                                apply_map_edits(ctx, app, edits);
                                lt_changes += 1;
                            }
                            Err(err) => {
                                errors.push(err);
                            }
                        }
                    }
                }
            }
        }
    });

    // TODO Need to express the errors in some form that we can union here.

    let mut results = Vec::new();
    if let Some(speed) = speed_limit {
        results.push(format!(
            "Changed {} roads to have a speed limit of {}",
            speed_changes,
            speed.to_string(&app.opts.units)
        ));
    }
    results.push(format!(
        "Changed {} lane types, encountered {} problems",
        lt_changes,
        errors.len()
    ));

    PopupMsg::new(ctx, "Edited roads", results)
}