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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
use geom::{Bounds, CornerRadii, Distance, UnitFmt};
use map_gui::render::{Renderable, OUTLINE_THICKNESS};
use map_gui::tools::PopupMsg;
use map_gui::ID;
use map_model::{
    BufferType, Direction, EditCmd, EditRoad, LaneID, LaneSpec, LaneType, MapEdits, Road, RoadID,
};
use widgetry::{
    lctrl, Choice, Color, ControlState, DragDrop, Drawable, EdgeInsets, EventCtx, GeomBatch,
    GeomBatchStack, GfxCtx, HorizontalAlignment, Image, Key, Line, Outcome, Panel, Spinner, State,
    Text, TextExt, VerticalAlignment, Widget, DEFAULT_CORNER_RADIUS,
};

use crate::app::{App, Transition};
use crate::common::Warping;
use crate::edit::heuristics::add_new_lane;
use crate::edit::zones::ZoneEditor;
use crate::edit::{apply_map_edits, can_edit_lane, speed_limit_choices};

pub struct RoadEditor {
    r: RoadID,
    selected_lane: Option<LaneID>,
    hovering_on_lane: Option<LaneID>,
    top_panel: Panel,
    main_panel: Panel,

    // (cache_key: (selected, hovering), Drawable)
    lane_highlights: ((Option<LaneID>, Option<LaneID>), Drawable),

    // Immediately after modifying the map but before the mouse moves, we should recalculate
    // mouseover
    recalculate_mouseover: bool,

    // Undo/redo management
    num_edit_cmds_originally: usize,
    redo_stack: Vec<EditCmd>,
    orig_road_state: EditRoad,
}

impl RoadEditor {
    /// Always starts focused on a certain lane.
    pub fn new_state(ctx: &mut EventCtx, app: &mut App, l: LaneID) -> Box<dyn State<App>> {
        RoadEditor::create(ctx, app, app.primary.map.get_l(l).parent, Some(l))
    }

    pub fn new_state_without_lane(
        ctx: &mut EventCtx,
        app: &mut App,
        r: RoadID,
    ) -> Box<dyn State<App>> {
        RoadEditor::create(ctx, app, r, None)
    }

    fn create(
        ctx: &mut EventCtx,
        app: &mut App,
        r: RoadID,
        selected_lane: Option<LaneID>,
    ) -> Box<dyn State<App>> {
        app.primary.current_selection = None;

        let mut editor = RoadEditor {
            r,
            selected_lane,
            top_panel: Panel::empty(ctx),
            main_panel: Panel::empty(ctx),
            lane_highlights: ((None, None), Drawable::empty(ctx)),
            hovering_on_lane: None,

            recalculate_mouseover: false,

            num_edit_cmds_originally: app.primary.map.get_edits().commands.len(),
            redo_stack: Vec::new(),
            orig_road_state: app.primary.map.get_r_edit(r),
        };
        editor.recalc_all_panels(ctx, app);
        Box::new(editor)
    }

    fn lane_for_idx(&self, app: &App, idx: usize) -> LaneID {
        app.primary.map.get_r(self.r).lanes_ltr()[idx].0
    }

    fn modify_current_lane<F: Fn(&mut EditRoad, usize)>(
        &mut self,
        ctx: &mut EventCtx,
        app: &mut App,
        select_new_lane_offset: Option<isize>,
        f: F,
    ) -> Transition {
        let idx = app
            .primary
            .map
            .get_r(self.r)
            .offset(self.selected_lane.unwrap());
        let cmd = app.primary.map.edit_road_cmd(self.r, |new| (f)(new, idx));

        // Special check here -- this invalid state can be reached in many ways.
        if let EditCmd::ChangeRoad { ref new, .. } = cmd {
            let mut parking = 0;
            let mut driving = 0;
            for spec in &new.lanes_ltr {
                if spec.lt == LaneType::Parking {
                    parking += 1;
                } else if spec.lt == LaneType::Driving {
                    driving += 1;
                }
            }
            if parking > 0 && driving == 0 {
                return Transition::Push(PopupMsg::new_state(
                    ctx,
                    "Error",
                    vec!["Parking can't exist without a driving lane to access it."],
                ));
            }
        }

        let mut edits = app.primary.map.get_edits().clone();
        edits.commands.push(cmd);
        apply_map_edits(ctx, app, edits);
        self.redo_stack.clear();

        self.selected_lane = select_new_lane_offset
            .map(|offset| self.lane_for_idx(app, (idx as isize + offset) as usize));

        self.recalc_all_panels(ctx, app);
        self.recalculate_mouseover = true;

        Transition::Keep
    }

    fn recalc_all_panels(&mut self, ctx: &mut EventCtx, app: &App) {
        self.main_panel = make_main_panel(
            ctx,
            app,
            app.primary.map.get_r(self.r),
            self.selected_lane,
            self.hovering_on_lane,
        );

        let drag_drop = self.main_panel.find::<DragDrop<LaneID>>("lane cards");
        let selected = drag_drop.selected_value().or(self.selected_lane);
        let hovering = drag_drop.hovering_value().or(self.hovering_on_lane);
        if (selected, hovering) != self.lane_highlights.0 {
            self.lane_highlights = build_lane_highlights(ctx, app, self.r, selected, hovering);
        }

        self.top_panel = make_top_panel(
            ctx,
            app,
            self.num_edit_cmds_originally,
            self.redo_stack.is_empty(),
            self.r,
            self.orig_road_state.clone(),
        );
    }

    fn compress_edits(&self, app: &App) -> Option<MapEdits> {
        // Compress all of the edits, unless there were 0 or 1 changes
        if app.primary.map.get_edits().commands.len() > self.num_edit_cmds_originally + 2 {
            let mut edits = app.primary.map.get_edits().clone();
            let last_edit = match edits.commands.pop().unwrap() {
                EditCmd::ChangeRoad { new, .. } => new,
                _ => unreachable!(),
            };
            edits.commands.truncate(self.num_edit_cmds_originally + 1);
            match edits.commands.last_mut().unwrap() {
                EditCmd::ChangeRoad { ref mut new, .. } => {
                    *new = last_edit;
                }
                _ => unreachable!(),
            }
            return Some(edits);
        }
        None
    }
}

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

        let mut panels_need_recalc = false;

        if let Outcome::Clicked(x) = self.top_panel.event(ctx) {
            match x.as_ref() {
                "Finish" => {
                    if let Some(edits) = self.compress_edits(app) {
                        apply_map_edits(ctx, app, edits);
                    }
                    return Transition::Pop;
                }
                "Cancel" => {
                    let mut edits = app.primary.map.get_edits().clone();
                    if edits.commands.len() != self.num_edit_cmds_originally {
                        edits.commands.truncate(self.num_edit_cmds_originally);
                        apply_map_edits(ctx, app, edits);
                    }
                    return Transition::Pop;
                }
                "Revert" => {
                    let mut edits = app.primary.map.get_edits().clone();
                    edits.commands.push(EditCmd::ChangeRoad {
                        r: self.r,
                        old: app.primary.map.get_r_edit(self.r),
                        new: EditRoad::get_orig_from_osm(
                            app.primary.map.get_r(self.r),
                            app.primary.map.get_config(),
                        ),
                    });
                    self.selected_lane = None;
                    self.hovering_on_lane = None;
                    apply_map_edits(ctx, app, edits);
                    self.redo_stack.clear();
                    panels_need_recalc = true;
                }
                "undo" => {
                    let mut edits = app.primary.map.get_edits().clone();
                    self.redo_stack.push(edits.commands.pop().unwrap());
                    apply_map_edits(ctx, app, edits);

                    self.selected_lane = None;
                    panels_need_recalc = true;
                }
                "redo" => {
                    let mut edits = app.primary.map.get_edits().clone();
                    edits.commands.push(self.redo_stack.pop().unwrap());
                    apply_map_edits(ctx, app, edits);

                    self.selected_lane = None;
                    panels_need_recalc = true;
                }
                "jump to road" => {
                    return Transition::Push(Warping::new_state(
                        ctx,
                        app.primary.canonical_point(ID::Road(self.r)).unwrap(),
                        Some(10.0),
                        Some(ID::Road(self.r)),
                        &mut app.primary,
                    ));
                }
                "Apply to multiple road segments" => {
                    return Transition::Push(
                        crate::edit::multiple_roads::SelectSegments::new_state(
                            ctx,
                            app,
                            self.r,
                            self.orig_road_state.clone(),
                            app.primary.map.get_r_edit(self.r),
                            self.compress_edits(app)
                                .unwrap_or_else(|| app.primary.map.get_edits().clone()),
                        ),
                    );
                }
                _ => unreachable!(),
            }
        }

        match self.main_panel.event(ctx) {
            Outcome::Clicked(x) => {
                if let Some(idx) = x.strip_prefix("modify Lane #") {
                    self.selected_lane = Some(LaneID(idx.parse().unwrap()));
                    panels_need_recalc = true;
                } else if x == "delete lane" {
                    return self.modify_current_lane(ctx, app, None, |new, idx| {
                        new.lanes_ltr.remove(idx);
                    });
                } else if x == "flip direction" {
                    return self.modify_current_lane(ctx, app, Some(0), |new, idx| {
                        new.lanes_ltr[idx].dir = new.lanes_ltr[idx].dir.opposite();
                    });
                } else if let Some(lt) = x.strip_prefix("change to ") {
                    let lt = LaneType::from_short_name(lt).unwrap();
                    let width =
                        LaneSpec::typical_lane_widths(lt, &app.primary.map.get_r(self.r).osm_tags)
                            [0]
                        .0;
                    return self.modify_current_lane(ctx, app, Some(0), |new, idx| {
                        new.lanes_ltr[idx].lt = lt;
                        new.lanes_ltr[idx].width = width;
                    });
                } else if let Some(lt) = x.strip_prefix("add ") {
                    let lt = LaneType::from_short_name(lt).unwrap();

                    // Special check here
                    if lt == LaneType::Parking
                        && app
                            .primary
                            .map
                            .get_r(self.r)
                            .lanes_ltr()
                            .into_iter()
                            .all(|(_, _, lt)| lt != LaneType::Driving)
                    {
                        return Transition::Push(PopupMsg::new_state(ctx, "Error", vec!["Add a driving lane first. Parking can't exist without a way to access it."]));
                    }

                    let mut edits = app.primary.map.get_edits().clone();
                    let old = app.primary.map.get_r_edit(self.r);
                    let mut new = old.clone();
                    let idx = add_new_lane(&mut new, lt, &app.primary.map.get_r(self.r).osm_tags);
                    edits.commands.push(EditCmd::ChangeRoad {
                        r: self.r,
                        old,
                        new,
                    });
                    apply_map_edits(ctx, app, edits);
                    self.redo_stack.clear();

                    assert!(self.selected_lane.is_none());
                    self.selected_lane = Some(self.lane_for_idx(app, idx));
                    panels_need_recalc = true;
                } else if x == "Access restrictions" {
                    // The RoadEditor maintains an undo/redo stack for a single road, but the
                    // ZoneEditor usually operates on multiple roads. So before we switch over to
                    // it, compress and save the current edits.
                    if let Some(edits) = self.compress_edits(app) {
                        apply_map_edits(ctx, app, edits);
                    }
                    return Transition::Replace(ZoneEditor::new_state(ctx, app, self.r));
                } else {
                    unreachable!()
                }
            }
            Outcome::Changed(x) => match x.as_ref() {
                "speed limit" => {
                    let speed_limit = self.main_panel.dropdown_value("speed limit");
                    return self.modify_current_lane(ctx, app, Some(0), |new, _| {
                        new.speed_limit = speed_limit;
                    });
                }
                "width preset" => {
                    let width = self.main_panel.dropdown_value("width preset");
                    return self.modify_current_lane(ctx, app, Some(0), |new, idx| {
                        new.lanes_ltr[idx].width = width;
                    });
                }
                "width custom" => {
                    let width = self.main_panel.spinner("width custom");
                    return self.modify_current_lane(ctx, app, Some(0), |new, idx| {
                        new.lanes_ltr[idx].width = width;
                    });
                }
                "lane cards" => {
                    // hovering index changed
                    panels_need_recalc = true;
                }
                _ => unreachable!(),
            },
            Outcome::DragDropReleased(_, old_idx, new_idx) => {
                if old_idx != new_idx {
                    let mut edits = app.primary.map.get_edits().clone();
                    edits
                        .commands
                        .push(app.primary.map.edit_road_cmd(self.r, |new| {
                            new.lanes_ltr.swap(old_idx, new_idx);
                        }));
                    apply_map_edits(ctx, app, edits);
                    self.redo_stack.clear();
                }

                self.selected_lane = Some(self.lane_for_idx(app, new_idx));
                self.hovering_on_lane = self.selected_lane;
                panels_need_recalc = true;
            }
            Outcome::Nothing => {}
            _ => debug!("main_panel had unhandled outcome"),
        }

        // let prev_hovering_on_lane = self.hovering_on_lane.take();
        if ctx.canvas.get_cursor_in_map_space().is_some() {
            self.recalculate_mouseover = false;
            app.recalculate_current_selection(ctx);

            let hovering = match app.primary.current_selection.take() {
                Some(ID::Lane(l)) if can_edit_lane(app, l) => Some(l),
                _ => None,
            };

            if let Some(l) = hovering {
                if self.hovering_on_lane != Some(l) {
                    self.hovering_on_lane = Some(l);
                    panels_need_recalc = true;
                }

                if ctx.normal_left_click() {
                    if app.primary.map.get_l(l).parent == self.r {
                        self.selected_lane = Some(l);
                        panels_need_recalc = true;
                    } else {
                        // Switch to editing another road, first compressing the edits here if
                        // needed.
                        if let Some(edits) = self.compress_edits(app) {
                            apply_map_edits(ctx, app, edits);
                        }
                        return Transition::Replace(RoadEditor::new_state(ctx, app, l));
                    }
                }
            } else {
                if self.hovering_on_lane.is_some() {
                    self.hovering_on_lane = None;
                    panels_need_recalc = true;
                }

                if self.selected_lane.is_some() && ctx.normal_left_click() {
                    // Deselect the current lane
                    self.selected_lane = None;
                    self.hovering_on_lane = None;
                    panels_need_recalc = true;
                }
            }
        } else {
            // If we're not hovering on the map, then we're not hovering on a lane.
            if self.hovering_on_lane.is_some() {
                self.hovering_on_lane = None;
                panels_need_recalc = true;
            }
        }

        if panels_need_recalc {
            self.recalc_all_panels(ctx, app);
        }

        Transition::Keep
    }

    fn draw(&self, g: &mut GfxCtx, _: &App) {
        g.redraw(&self.lane_highlights.1);
        self.top_panel.draw(g);
        self.main_panel.draw(g);
    }
}

fn make_top_panel(
    ctx: &mut EventCtx,
    app: &App,
    num_edit_cmds_originally: usize,
    no_redo_cmds: bool,
    r: RoadID,
    orig_road_state: EditRoad,
) -> Panel {
    let map = &app.primary.map;
    let current_state = map.get_r_edit(r);

    Panel::new_builder(Widget::col(vec![
        Widget::row(vec![
            Line(format!("Edit {}", r)).small_heading().into_widget(ctx),
            ctx.style()
                .btn_plain
                .icon("system/assets/tools/location.svg")
                .build_widget(ctx, "jump to road"),
            ctx.style()
                .btn_plain
                .text("+ Apply to multiple")
                .label_color(Color::hex("#4CA7E9"), ControlState::Default)
                .hotkey(Key::M)
                .disabled(current_state == orig_road_state)
                .disabled_tooltip("You have to edit one road segment first, then you can apply the changes to more segments.")
                .build_widget(ctx, "Apply to multiple road segments"),
        ]),
        Widget::row(vec![
            ctx.style()
                .btn_solid_primary
                .text("Finish")
                .hotkey(Key::Enter)
                .build_def(ctx),
            ctx.style()
                .btn_plain
                .icon("system/assets/tools/undo.svg")
                .disabled(map.get_edits().commands.len() == num_edit_cmds_originally)
                .hotkey(lctrl(Key::Z))
                .build_widget(ctx, "undo"),
            ctx.style()
                .btn_plain
                .icon("system/assets/tools/redo.svg")
                .disabled(no_redo_cmds)
                // TODO ctrl+shift+Z!
                .hotkey(lctrl(Key::Y))
                .build_widget(ctx, "redo"),
            ctx.style()
                .btn_plain_destructive
                .text("Revert")
                .disabled(current_state == EditRoad::get_orig_from_osm(map.get_r(r), map.get_config()))
                .build_def(ctx),
            ctx.style()
                .btn_plain
                .text("Cancel")
                .hotkey(Key::Escape)
                .build_def(ctx),
        ]),
    ]))
    .aligned(HorizontalAlignment::Center, VerticalAlignment::Top)
    .build(ctx)
}

fn make_main_panel(
    ctx: &mut EventCtx,
    app: &App,
    road: &Road,
    selected_lane: Option<LaneID>,
    hovering_on_lane: Option<LaneID>,
) -> Panel {
    let map = &app.primary.map;

    let modify_lane = if let Some(l) = selected_lane {
        let lane = map.get_l(l);
        Widget::row(vec![
            ctx.style()
                .btn_solid_destructive
                .icon("system/assets/tools/trash.svg")
                .disabled(road.lanes_ltr().len() == 1)
                .hotkey(Key::Backspace)
                .build_widget(ctx, "delete lane"),
            ctx.style()
                .btn_plain
                .text("flip direction")
                .disabled(!can_reverse(lane.lane_type))
                .hotkey(Key::F)
                .build_def(ctx),
            Line("Width").secondary().into_widget(ctx).centered_vert(),
            Widget::col(vec![
                Widget::dropdown(ctx, "width preset", lane.width, width_choices(app, l)),
                Spinner::widget_with_custom_rendering(
                    ctx,
                    "width custom",
                    (Distance::feet(1.0), Distance::feet(20.0)),
                    lane.width,
                    Distance::feet(0.5),
                    // Even if the user's settings are set to meters, our step size is in feet, so
                    // just render in feet.
                    Box::new(|x| {
                        x.to_string(&UnitFmt {
                            round_durations: false,
                            metric: false,
                        })
                    }),
                )
                .centered_horiz(),
            ]),
        ])
    } else {
        Widget::nothing()
    };
    let current_lt = selected_lane.map(|l| map.get_l(l).lane_type);

    let current_lts: Vec<LaneType> = road.lanes_ltr().into_iter().map(|(_, _, lt)| lt).collect();
    let mut available_lane_types_row = vec![
        (LaneType::Driving, Some(Key::D)),
        (LaneType::Biking, Some(Key::B)),
        (LaneType::Bus, Some(Key::T)),
        (LaneType::Parking, Some(Key::P)),
        (LaneType::Construction, Some(Key::C)),
        (LaneType::Sidewalk, Some(Key::S)),
        (LaneType::Buffer(BufferType::Stripes), None),
        (LaneType::Buffer(BufferType::FlexPosts), None),
        (LaneType::Buffer(BufferType::Planters), None),
        (LaneType::Buffer(BufferType::JerseyBarrier), None),
        (LaneType::Buffer(BufferType::Curb), None),
    ]
    .into_iter()
    .map(|(lt, key)| {
        let mut btn = ctx
            .style()
            .btn_plain
            .icon(lane_type_to_icon(lt).unwrap())
            .hotkey(key.map(|k| k.into()));
        if current_lt == Some(lt) {
            // If the selected lane is already this type, we can't change it. Hopefully no need to
            // explain this.
            btn = btn.disabled(true);
        } else if lt == LaneType::Parking
            && current_lts
                .iter()
                .filter(|x| **x == LaneType::Parking)
                .count()
                == 2
        {
            // Max 2 parking lanes per road.
            //
            // (I've seen cases in Ballard with angled parking in a median and also parking on both
            // shoulders. If this happens to be mapped as two adjacent one-way roads, it could
            // work. But the simulation layer doesn't understand 3 lanes on one road.)
            btn = btn
                .disabled(true)
                .disabled_tooltip("This road already has two parking lanes");
        } else if lt == LaneType::Sidewalk
            && current_lts.iter().filter(|x| x.is_walkable()).count() == 2
        {
            // Max 2 sidewalks or shoulders per road.
            //
            // (You could imagine some exceptions in reality, but this assumption of max 2 is
            // deeply baked into the map model and everything on top of it.)
            btn = btn
                .disabled(true)
                .disabled_tooltip("This road already has two sidewalks");
        }

        btn.build_widget(
            ctx,
            format!(
                "{} {}",
                if selected_lane.is_some() {
                    "change to"
                } else {
                    "add"
                },
                lt.short_name()
            ),
        )
    })
    .collect::<Vec<Widget>>();
    available_lane_types_row.insert(
        0,
        if selected_lane.is_some() {
            "change to"
        } else {
            "add new"
        }
        .text_widget(ctx)
        .centered_vert(),
    );
    let available_lane_types_row = Widget::row(available_lane_types_row);

    let mut drag_drop = DragDrop::new(ctx, "lane cards");

    let lanes_ltr = road.lanes_ltr();
    let lanes_len = lanes_ltr.len();
    for (idx, (id, dir, lt)) in lanes_ltr.into_iter().enumerate() {
        let mut icon_stack = GeomBatchStack::vertical(vec![
            Image::from_path(lane_type_to_icon(lt).unwrap())
                .build_batch(ctx)
                .unwrap()
                .0,
        ]);
        icon_stack.set_spacing(20.0);

        if can_reverse(lt) {
            icon_stack.push(
                Image::from_path(if dir == Direction::Fwd {
                    "system/assets/edit/forwards.svg"
                } else {
                    "system/assets/edit/backwards.svg"
                })
                .build_batch(ctx)
                .unwrap()
                .0,
            );
        }
        let icon_batch = icon_stack.batch();
        let icon_bounds = icon_batch.get_bounds();

        let mut rounding = CornerRadii::zero();
        if idx == 0 {
            rounding.top_left = DEFAULT_CORNER_RADIUS;
            rounding.bottom_left = DEFAULT_CORNER_RADIUS;
        }
        if idx == lanes_len - 1 {
            rounding.top_right = DEFAULT_CORNER_RADIUS;
            rounding.bottom_right = DEFAULT_CORNER_RADIUS;
        }

        let (card_bounds, default_batch, hovering_batch, selected_batch) = {
            let card_batch = |(icon_batch, hovering, selected)| -> (GeomBatch, Bounds) {
                Image::from_batch(icon_batch, icon_bounds)
                    // TODO: For selected/hover, rather than change the entire card's background, let's
                    // just add an outline to match the styling of the corresponding lane in the map
                    .bg_color(if selected {
                        ctx.style().primary_fg
                    } else if hovering {
                        app.cs.selected.tint(0.2)
                    } else {
                        ctx.style().section_bg
                    })
                    .color(ctx.style().btn_plain.fg)
                    .dims(60.0)
                    .padding(EdgeInsets {
                        top: 32.0,
                        left: 16.0,
                        bottom: 32.0,
                        right: 16.0,
                    })
                    .corner_rounding(rounding)
                    .build_batch(ctx)
                    .unwrap()
            };

            let (default_batch, bounds) = card_batch((icon_batch.clone(), false, false));
            let (hovering_batch, _) = card_batch((icon_batch.clone(), true, false));
            let (selected_batch, _) = card_batch((icon_batch, false, true));
            (bounds, default_batch, hovering_batch, selected_batch)
        };

        drag_drop.push_card(
            id,
            card_bounds.into(),
            default_batch,
            hovering_batch,
            selected_batch,
        );
    }
    drag_drop.set_initial_state(selected_lane, hovering_on_lane);

    let total_width = {
        let current_width = road.get_width(map);
        let line1 = Text::from_all(vec![
            Line("Total width ").secondary(),
            Line(current_width.to_string(&app.opts.units)),
        ])
        .into_widget(ctx);
        let orig_width = EditRoad::get_orig_from_osm(map.get_r(road.id), map.get_config())
            .lanes_ltr
            .into_iter()
            .map(|spec| spec.width)
            .sum();
        let line2 = ctx
            .style()
            .btn_plain
            .btn()
            .label_styled_text(
                Text::from(match current_width.cmp(&orig_width) {
                    std::cmp::Ordering::Equal => Line("No change").secondary(),
                    std::cmp::Ordering::Less => Line(format!(
                        "- {}",
                        (orig_width - current_width).to_string(&app.opts.units)
                    ))
                    .fg(Color::GREEN),
                    std::cmp::Ordering::Greater => Line(format!(
                        "+ {}",
                        (current_width - orig_width).to_string(&app.opts.units)
                    ))
                    .fg(Color::RED),
                }),
                ControlState::Default,
            )
            .disabled(true)
            .disabled_tooltip("The original road width is an estimate, so any changes might not require major construction.")
            .build_widget(ctx, "changes to total width")
            .align_right();
        Widget::col(vec![line1, line2])
    };

    let road_settings = Widget::row(vec![
        total_width,
        Line("Speed limit")
            .secondary()
            .into_widget(ctx)
            .centered_vert(),
        Widget::dropdown(
            ctx,
            "speed limit",
            road.speed_limit,
            speed_limit_choices(app, Some(road.speed_limit)),
        )
        .centered_vert(),
        ctx.style()
            .btn_outline
            .text("Access restrictions")
            .build_def(ctx)
            .centered_vert(),
    ]);

    Panel::new_builder(Widget::col(vec![
        modify_lane,
        available_lane_types_row,
        drag_drop
            .into_widget(ctx)
            .named("lane cards")
            .bg(ctx.style().text_primary_color.tint(0.3)),
        road_settings,
    ]))
    .aligned(HorizontalAlignment::Left, VerticalAlignment::Center)
    // If we're hovering on a lane card, we'll immediately produce Outcome::Changed. Since this
    // usually happens in recalc_all_panels, that's fine -- we'll look up the current lane card
    // there anyway.
    .ignore_initial_events()
    .build(ctx)
}

fn build_lane_highlights(
    ctx: &mut EventCtx,
    app: &App,
    r: RoadID,
    selected_lane: Option<LaneID>,
    hovered_lane: Option<LaneID>,
) -> ((Option<LaneID>, Option<LaneID>), Drawable) {
    let mut batch = GeomBatch::new();
    let map = &app.primary.map;

    let selected_color = ctx.style().primary_fg;
    let hovered_color = app.cs.selected;

    if let Some(hovered_lane) = hovered_lane {
        batch.push(
            hovered_color,
            app.primary.draw_map.get_l(hovered_lane).get_outline(map),
        );
    }

    if let Some(selected_lane) = selected_lane {
        batch.push(
            selected_color,
            app.primary.draw_map.get_l(selected_lane).get_outline(map),
        );
    }

    let road = map.get_r(r);
    batch.push(
        selected_color.alpha(0.5),
        road.center_pts
            .to_thick_boundary(road.get_width(map), OUTLINE_THICKNESS)
            .unwrap_or_else(|| road.get_thick_polygon(map)),
    );

    ((selected_lane, hovered_lane), ctx.upload(batch))
}

fn lane_type_to_icon(lt: LaneType) -> Option<&'static str> {
    match lt {
        LaneType::Driving => Some("system/assets/edit/driving.svg"),
        LaneType::Parking => Some("system/assets/edit/parking.svg"),
        LaneType::Sidewalk | LaneType::Shoulder => Some("system/assets/edit/sidewalk.svg"),
        LaneType::Biking => Some("system/assets/edit/bike.svg"),
        LaneType::Bus => Some("system/assets/edit/bus.svg"),
        LaneType::SharedLeftTurn => Some("system/assets/map/shared_left_turn.svg"),
        LaneType::Construction => Some("system/assets/edit/construction.svg"),
        LaneType::Buffer(BufferType::Stripes) => Some("system/assets/edit/buffer/stripes.svg"),
        LaneType::Buffer(BufferType::FlexPosts) => Some("system/assets/edit/buffer/flex_posts.svg"),
        LaneType::Buffer(BufferType::Planters) => Some("system/assets/edit/buffer/planters.svg"),
        LaneType::Buffer(BufferType::JerseyBarrier) => {
            Some("system/assets/edit/buffer/jersey_barrier.svg")
        }
        LaneType::Buffer(BufferType::Curb) => Some("system/assets/edit/buffer/curb.svg"),
        // Don't allow creating these yet
        LaneType::LightRail => None,
    }
}

fn width_choices(app: &App, l: LaneID) -> Vec<Choice<Distance>> {
    let lane = app.primary.map.get_l(l);
    let mut choices =
        LaneSpec::typical_lane_widths(lane.lane_type, &app.primary.map.get_r(lane.parent).osm_tags);
    if !choices.iter().any(|(x, _)| *x == lane.width) {
        choices.push((lane.width, "custom"));
    }
    choices.sort();
    choices
        .into_iter()
        .map(|(x, label)| Choice::new(format!("{} - {}", x.to_string(&app.opts.units), label), x))
        .collect()
}

// TODO We need to automatically fix the direction of sidewalks and parking as we initially place
// them or shift them around. Until then, allow fixing in the UI manually.
fn can_reverse(_: LaneType) -> bool {
    true
}
/*fn can_reverse(lt: LaneType) -> bool {
    lt == LaneType::Driving || lt == LaneType::Biking || lt == LaneType::Bus
}*/