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
use abstutil::Tags;
use map_gui::tools::PopupMsg;
use map_model::{
    BufferType, Direction, DrivingSide, EditCmd, EditRoad, LaneSpec, LaneType, RoadID,
};
use widgetry::{Choice, EventCtx, GfxCtx, Key, Outcome, Panel, State, TextExt, Widget};

use crate::app::{App, Transition};
use crate::common::RouteSketcher;
use crate::edit::apply_map_edits;
use crate::ungap::{Layers, Tab, TakeLayers};

pub struct QuickSketch {
    top_panel: Panel,
    layers: Layers,
    route_sketcher: RouteSketcher,
}

impl TakeLayers for QuickSketch {
    fn take_layers(self) -> Layers {
        self.layers
    }
}

impl QuickSketch {
    pub fn new_state(ctx: &mut EventCtx, app: &mut App, layers: Layers) -> Box<dyn State<App>> {
        let mut qs = QuickSketch {
            top_panel: Panel::empty(ctx),
            layers,
            route_sketcher: RouteSketcher::new(ctx, app),
        };
        qs.update_top_panel(ctx, app);
        Box::new(qs)
    }

    fn update_top_panel(&mut self, ctx: &mut EventCtx, app: &App) {
        let mut col = vec![self.route_sketcher.get_widget_to_describe(ctx)];

        if self.route_sketcher.is_route_started() {
            // We're usually replacing an existing panel, except the very first time.
            let default_buffer = if self.top_panel.has_widget("buffer type") {
                self.top_panel.dropdown_value("buffer type")
            } else {
                Some(BufferType::FlexPosts)
            };
            col.push(Widget::row(vec![
                "Protect the new bike lanes?"
                    .text_widget(ctx)
                    .centered_vert(),
                Widget::dropdown(
                    ctx,
                    "buffer type",
                    default_buffer,
                    vec![
                        // TODO Width / cost summary?
                        Choice::new("diagonal stripes", Some(BufferType::Stripes)),
                        Choice::new("flex posts", Some(BufferType::FlexPosts)),
                        Choice::new("planters", Some(BufferType::Planters)),
                        // Omit the others for now
                        Choice::new("no -- just paint", None),
                    ],
                ),
            ]));
            col.push(
                Widget::custom_row(vec![ctx
                    .style()
                    .btn_solid_primary
                    .text("Add bike lanes")
                    .hotkey(Key::Enter)
                    .disabled(!self.route_sketcher.is_route_started())
                    .build_def(ctx)])
                .evenly_spaced(),
            );
        }

        self.top_panel = Tab::Create.make_left_panel(ctx, app, Widget::col(col));
    }
}

impl State<App> for QuickSketch {
    fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Transition {
        if let Outcome::Clicked(x) = self.top_panel.event(ctx) {
            match x.as_ref() {
                "Add bike lanes" => {
                    let messages = make_quick_changes(
                        ctx,
                        app,
                        self.route_sketcher.all_roads(app),
                        self.top_panel.dropdown_value("buffer type"),
                    );
                    return Transition::ConsumeState(Box::new(|state, ctx, app| {
                        let state = state.downcast::<QuickSketch>().ok().unwrap();
                        vec![
                            crate::ungap::ExploreMap::new_state(ctx, app, state.layers),
                            PopupMsg::new_state(ctx, "Changes made", messages),
                        ]
                    }));
                }
                x => {
                    return Tab::Create
                        .handle_action::<QuickSketch>(ctx, app, x)
                        .unwrap();
                }
            }
        }

        if self.route_sketcher.event(ctx, app) {
            self.update_top_panel(ctx, app);
        }

        if let Some(t) = self.layers.event(ctx, app) {
            return t;
        }

        Transition::Keep
    }

    fn draw(&self, g: &mut GfxCtx, app: &App) {
        self.top_panel.draw(g);
        self.layers.draw(g, app);
        self.route_sketcher.draw(g);
    }
}

fn make_quick_changes(
    ctx: &mut EventCtx,
    app: &mut App,
    roads: Vec<RoadID>,
    buffer_type: Option<BufferType>,
) -> Vec<String> {
    // TODO Erasing changes

    let mut edits = app.primary.map.get_edits().clone();
    let already_modified_roads = edits.changed_roads.clone();
    let mut num_changes = 0;
    for r in roads {
        if already_modified_roads.contains(&r) {
            continue;
        }
        let old = app.primary.map.get_r_edit(r);
        let mut new = old.clone();
        maybe_add_bike_lanes(
            &mut new,
            buffer_type,
            app.primary.map.get_config().driving_side,
        );
        if old != new {
            num_changes += 1;
            edits.commands.push(EditCmd::ChangeRoad { r, old, new });
        }
    }
    apply_map_edits(ctx, app, edits);

    vec![format!("Changed {} segments", num_changes)]
}

#[allow(clippy::unnecessary_unwrap)]
fn maybe_add_bike_lanes(
    r: &mut EditRoad,
    buffer_type: Option<BufferType>,
    driving_side: DrivingSide,
) {
    let dummy_tags = Tags::empty();

    // First decompose the existing lanes back into a fwd_side and back_side. This is not quite the
    // inverse of assemble_ltr -- lanes on the OUTERMOST side of the road are first.
    let mut fwd_side = Vec::new();
    let mut back_side = Vec::new();
    for spec in r.lanes_ltr.drain(..) {
        if spec.dir == Direction::Fwd {
            fwd_side.push(spec);
        } else {
            back_side.push(spec);
        }
    }
    if driving_side == DrivingSide::Right {
        fwd_side.reverse();
    } else {
        back_side.reverse();
    }

    for (dir, side) in [
        (Direction::Fwd, &mut fwd_side),
        (Direction::Back, &mut back_side),
    ] {
        // For each side, start searching outer->inner. If there's parking, replace it. If there's
        // multiple driving lanes, fallback to changing the rightmost. If there's a bus lane, put
        // the bike lanes on the outside of it.
        let mut parking_lane = None;
        let mut first_driving_lane = None;
        let mut bus_lane = None;
        let mut num_driving_lanes = 0;
        for (idx, spec) in side.iter().enumerate() {
            if spec.lt == LaneType::Parking && parking_lane.is_none() {
                parking_lane = Some(idx);
            }
            if spec.lt == LaneType::Driving && first_driving_lane.is_none() {
                first_driving_lane = Some(idx);
            }
            if spec.lt == LaneType::Driving {
                num_driving_lanes += 1;
            }
            if spec.lt == LaneType::Bus && bus_lane.is_none() {
                bus_lane = Some(idx);
            }
        }
        // So if a road is one-way, this shouldn't add a bike lane to the off-side.
        let idx = if let Some(idx) = parking_lane {
            if num_driving_lanes == 0 {
                None
            } else {
                Some(idx)
            }
        } else if bus_lane.is_some() && num_driving_lanes > 1 {
            // Nuke the driving lane
            side.remove(first_driving_lane.unwrap());
            // Copy the bus lane (because the code below always overwrites idx)
            let bus_idx = bus_lane.unwrap();
            side.insert(bus_idx, side[bus_idx].clone());
            // Then put the bike lane on the outside of the bus lane
            Some(bus_idx)
        } else if num_driving_lanes > 1 {
            first_driving_lane
        } else {
            None
        };
        if let Some(idx) = idx {
            side[idx] = LaneSpec {
                lt: LaneType::Biking,
                dir,
                width: LaneSpec::typical_lane_widths(LaneType::Biking, &dummy_tags)[0].0,
            };
            if let Some(buffer) = buffer_type {
                side.insert(
                    idx + 1,
                    LaneSpec {
                        lt: LaneType::Buffer(buffer),
                        dir,
                        width: LaneSpec::typical_lane_widths(LaneType::Buffer(buffer), &dummy_tags)
                            [0]
                        .0,
                    },
                );
            }
        }
    }

    // Now re-assemble...
    if driving_side == DrivingSide::Right {
        r.lanes_ltr = back_side;
        fwd_side.reverse();
        r.lanes_ltr.extend(fwd_side);
    } else {
        r.lanes_ltr = fwd_side;
        back_side.reverse();
        r.lanes_ltr.extend(back_side);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_maybe_add_bike_lanes() {
        let with_buffers = true;
        let no_buffers = false;

        let mut ok = true;
        for (
            description,
            url,
            driving_side,
            input_lt,
            input_dir,
            buffer,
            expected_lt,
            expected_dir,
        ) in vec![
            (
                "Two-way without room",
                "https://www.openstreetmap.org/way/537698750",
                DrivingSide::Right,
                "sdds",
                "vv^^",
                no_buffers,
                "sdds",
                "vv^^",
            ),
            (
                "Two-way with parking, adding buffers",
                "https://www.openstreetmap.org/way/40790122",
                DrivingSide::Right,
                "spddps",
                "vvv^^^",
                with_buffers,
                "sb|dd|bs",
                "vvvv^^^^",
            ),
            (
                "Two-way with parking, no buffers",
                "https://www.openstreetmap.org/way/40790122",
                DrivingSide::Right,
                "spddps",
                "vvv^^^",
                no_buffers,
                "sbddbs",
                "vvv^^^",
            ),
            (
                "Two-way without parking but many lanes",
                "https://www.openstreetmap.org/way/394737309",
                DrivingSide::Right,
                "sddddds",
                "vvv^^^^",
                with_buffers,
                "sb|ddd|bs",
                "vvvv^^^^^",
            ),
            (
                "One-way with parking on both sides",
                "https://www.openstreetmap.org/way/559660378",
                DrivingSide::Right,
                "spddps",
                "vv^^^^",
                with_buffers,
                "spdd|bs",
                "vv^^^^^",
            ),
            (
                "One-way with bus lanes",
                "https://www.openstreetmap.org/way/52840106",
                DrivingSide::Right,
                "ddBs",
                "^^^^",
                with_buffers,
                "dB|bs",
                "^^^^^",
            ),
            (
                "Two-way with bus lanes",
                "https://www.openstreetmap.org/way/368670632",
                DrivingSide::Right,
                "sBddCddBs",
                "vvvv^^^^^",
                with_buffers,
                "sb|BdCdB|bs",
                "vvvvv^^^^^^",
            ),
            (
                "Two-way without room, on a left-handed map",
                "https://www.openstreetmap.org/way/436838877",
                DrivingSide::Left,
                "sdds",
                "^^vv",
                no_buffers,
                "sdds",
                "^^vv",
            ),
            (
                "Two-way, on a left-handed map",
                "https://www.openstreetmap.org/way/312457180",
                DrivingSide::Left,
                "sdddds",
                "^^^vvv",
                no_buffers,
                "sbddbs",
                "^^^vvv",
            ),
        ] {
            let input = EditRoad::create_for_test(input_lt, input_dir);
            let mut actual_output = input.clone();
            maybe_add_bike_lanes(
                &mut actual_output,
                if buffer {
                    Some(BufferType::FlexPosts)
                } else {
                    None
                },
                driving_side,
            );
            actual_output.check_lanes_ltr(
                format!("{} (example from {})", description, url),
                input_lt,
                input_dir,
                expected_lt,
                expected_dir,
                &mut ok,
            );
        }
        assert!(ok);
    }
}