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
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
use std::collections::HashSet;

use abstio::MapName;
use abstutil::{Tags, Timer};
use geom::{ArrowCap, Circle, Distance, PolyLine, Pt2D};
use map_gui::colors::ColorSchemeChoice;
use map_gui::load::MapLoader;
use map_gui::options::OptionsPanel;
use map_gui::render::{calculate_corners, DrawMap, DrawOptions};
use map_gui::tools::{ChooseSomething, PromptInput};
use map_gui::{AppLike, ID};
use map_model::{
    osm, ControlTrafficSignal, IntersectionID, PathConstraints, Perimeter, Position, RoadID,
    NORMAL_LANE_THICKNESS,
};
use sim::Sim;
use synthpop::TripEndpoint;
use widgetry::tools::PopupMsg;
use widgetry::{
    lctrl, Cached, Choice, Color, DrawBaselayer, Drawable, EventCtx, GeomBatch, GfxCtx,
    HorizontalAlignment, Key, Line, Outcome, Panel, State, Text, Toggle, UpdateType,
    VerticalAlignment, Widget,
};

use crate::app::{App, ShowLayers, ShowObject, Transition};
use crate::common::{tool_panel, CommonState};
use crate::info::ContextualActions;
use crate::sandbox::GameplayMode;

pub use self::routes::PathCostDebugger;

mod blocked_by;
mod blockfinder;
mod floodfill;
mod objects;
pub mod path_counter;
mod polygons;
mod routes;
mod select_roads;
pub mod shared_row;
pub mod streetmix;
mod uber_turns;

pub struct DebugMode {
    panel: Panel,
    common: CommonState,
    tool_panel: Panel,
    objects: objects::ObjectDebugger,
    hidden: HashSet<ID>,
    layers: ShowLayers,
    search_results: Option<SearchResults>,
    all_routes: Option<(usize, Drawable)>,

    highlighted_agents: Cached<IntersectionID, Drawable>,
}

impl DebugMode {
    pub fn new_state(ctx: &mut EventCtx, app: &App) -> Box<dyn State<App>> {
        Box::new(DebugMode {
            panel: Panel::new_builder(Widget::col(vec![
                Widget::row(vec![
                    Line("Debug Mode").small_heading().into_widget(ctx),
                    ctx.style().btn_close_widget(ctx),
                ]),
                Text::new().into_widget(ctx).named("current info"),
                Toggle::switch(ctx, "show buildings", Key::Num1, true),
                Toggle::switch(ctx, "show intersections", Key::Num2, true),
                Toggle::switch(ctx, "show lanes", Key::Num3, true),
                Toggle::switch(ctx, "show areas", Key::Num4, true),
                Toggle::switch(ctx, "show labels", Key::Num5, false),
                Toggle::switch(ctx, "show route for all agents", lctrl(Key::R), false),
                Toggle::switch(
                    ctx,
                    "screen recording mode",
                    lctrl(Key::H),
                    app.opts.minimal_controls,
                ),
                Widget::col(vec![
                    ctx.style()
                        .btn_outline
                        .text("unhide everything")
                        .hotkey(lctrl(Key::H))
                        .build_def(ctx),
                    ctx.style()
                        .btn_outline
                        .text("screenshot all of the everything")
                        .build_def(ctx),
                    ctx.style()
                        .btn_outline
                        .text("search OSM metadata")
                        .hotkey(Key::Slash)
                        .build_def(ctx),
                    ctx.style()
                        .btn_outline
                        .text("clear OSM search results")
                        .hotkey(Key::Slash)
                        .build_def(ctx),
                    ctx.style()
                        .btn_outline
                        .text("save sim state")
                        .build_def(ctx),
                    ctx.style()
                        .btn_outline
                        .text("load previous sim state")
                        .build_def(ctx),
                    ctx.style()
                        .btn_outline
                        .text("load next sim state")
                        .build_def(ctx),
                    ctx.style()
                        .btn_outline
                        .text("pick a savestate to load")
                        .build_def(ctx),
                    ctx.style()
                        .btn_outline
                        .text("find bad traffic signals")
                        .build_def(ctx),
                    ctx.style()
                        .btn_outline
                        .text("find degenerate roads")
                        .build_def(ctx),
                    ctx.style()
                        .btn_outline
                        .text("find large intersections")
                        .build_def(ctx),
                    ctx.style()
                        .btn_outline
                        .text("sim internal stats")
                        .build_def(ctx),
                    ctx.style()
                        .btn_outline
                        .text("blocked-by graph")
                        .build_def(ctx),
                    ctx.style()
                        .btn_outline
                        .text("blockfinder")
                        .hotkey(lctrl(Key::B))
                        .build_def(ctx),
                    ctx.style()
                        .btn_outline
                        .text("render to GeoJSON")
                        .hotkey(Key::G)
                        .build_def(ctx),
                    ctx.style()
                        .btn_outline
                        .text("draw banned turns")
                        .hotkey(Key::T)
                        .build_def(ctx),
                    ctx.style()
                        .btn_outline
                        .text("draw arterial crosswalks")
                        .hotkey(Key::W)
                        .build_def(ctx),
                    ctx.style()
                        .btn_outline
                        .text("export color-scheme")
                        .build_def(ctx),
                    ctx.style()
                        .btn_outline
                        .text("import color-scheme")
                        .build_def(ctx),
                    ctx.style()
                        .btn_outline
                        .text("find bad intersection polygons")
                        .build_def(ctx),
                    if cfg!(not(target_arch = "wasm32")) {
                        ctx.style()
                            .btn_outline
                            .text("undo all merged roads")
                            .hotkey(lctrl(Key::M))
                            .build_def(ctx)
                    } else {
                        Widget::nothing()
                    },
                ]),
                Text::from_all(vec![
                    Line("Hold "),
                    Key::LeftControl.txt(ctx),
                    Line(" to show position"),
                ])
                .into_widget(ctx),
            ]))
            .aligned(HorizontalAlignment::Right, VerticalAlignment::Top)
            .build(ctx),
            common: CommonState::new(),
            tool_panel: tool_panel(ctx),
            objects: objects::ObjectDebugger,
            hidden: HashSet::new(),
            layers: ShowLayers::new(),
            search_results: None,
            all_routes: None,
            highlighted_agents: Cached::new(),
        })
    }

    fn reset_info(&mut self, ctx: &mut EventCtx) {
        let mut txt = Text::new();
        if !self.hidden.is_empty() {
            txt.add_line(format!("Hiding {} things", self.hidden.len()));
        }
        if let Some(ref results) = self.search_results {
            txt.add_line(format!(
                "Search for {} has {} results",
                results.query, results.num_matches
            ));
        }
        if let Some((n, _)) = self.all_routes {
            txt.add_line(format!("Showing {} routes", abstutil::prettyprint_usize(n)));
        }
        self.panel
            .replace(ctx, "current info", txt.into_widget(ctx));
    }
}

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

        if ctx.redo_mouseover() {
            app.primary.current_selection = app.mouseover_debug_mode(ctx, self);
        }

        match self.panel.event(ctx) {
            Outcome::Clicked(x) => match x.as_ref() {
                "close" => {
                    return Transition::Pop;
                }
                "save sim state" => {
                    ctx.loading_screen("savestate", |_, timer| {
                        timer.start("save sim state");
                        app.primary.sim.save();
                        timer.stop("save sim state");
                    });
                }
                "load previous sim state" => {
                    if let Some(t) = ctx.loading_screen("load previous savestate", |ctx, timer| {
                        let prev_state = app
                            .primary
                            .sim
                            .find_previous_savestate(app.primary.sim.time());
                        match prev_state
                            .clone()
                            .and_then(|path| Sim::load_savestate(path, timer).ok())
                        {
                            Some(new_sim) => {
                                app.primary.sim = new_sim;
                                app.recalculate_current_selection(ctx);
                                None
                            }
                            None => Some(Transition::Push(PopupMsg::new_state(
                                ctx,
                                "Error",
                                vec![format!("Couldn't load previous savestate {:?}", prev_state)],
                            ))),
                        }
                    }) {
                        return t;
                    }
                }
                "load next sim state" => {
                    if let Some(t) = ctx.loading_screen("load next savestate", |ctx, timer| {
                        let next_state =
                            app.primary.sim.find_next_savestate(app.primary.sim.time());
                        match next_state
                            .clone()
                            .and_then(|path| Sim::load_savestate(path, timer).ok())
                        {
                            Some(new_sim) => {
                                app.primary.sim = new_sim;
                                app.recalculate_current_selection(ctx);
                                None
                            }
                            None => Some(Transition::Push(PopupMsg::new_state(
                                ctx,
                                "Error",
                                vec![format!("Couldn't load next savestate {:?}", next_state)],
                            ))),
                        }
                    }) {
                        return t;
                    }
                }
                "pick a savestate to load" => {
                    return Transition::Push(ChooseSomething::new_state(
                        ctx,
                        "Load which savestate?",
                        Choice::strings(abstio::list_all_objects(app.primary.sim.save_dir())),
                        Box::new(|ss, ctx, app| {
                            // TODO Oh no, we have to do path construction here :(
                            let ss_path = format!("{}/{}.bin", app.primary.sim.save_dir(), ss);

                            ctx.loading_screen("load savestate", |ctx, timer| {
                                app.primary.sim = Sim::load_savestate(ss_path, timer)
                                    .expect("Can't load savestate");
                                app.recalculate_current_selection(ctx);
                            });
                            Transition::Pop
                        }),
                    ));
                }
                "unhide everything" => {
                    self.hidden.clear();
                    app.primary.current_selection = app.mouseover_debug_mode(ctx, self);
                    self.reset_info(ctx);
                }
                "search OSM metadata" => {
                    return Transition::Push(PromptInput::new_state(
                        ctx,
                        "Search for what?",
                        String::new(),
                        Box::new(search_osm),
                    ));
                }
                "clear OSM search results" => {
                    self.search_results = None;
                    self.reset_info(ctx);
                }
                "screenshot all of the everything" => {
                    return Transition::Push(ScreenshotTest::new_state(
                        ctx,
                        app,
                        vec![
                            MapName::seattle("downtown"),
                            MapName::seattle("montlake"),
                            MapName::new("gb", "london", "kennington"),
                            MapName::new("pl", "krakow", "center"),
                            MapName::new("us", "phoenix", "tempe"),
                        ],
                    ));
                }
                "find bad traffic signals" => {
                    find_bad_signals(app);
                }
                "find degenerate roads" => {
                    find_degenerate_roads(app);
                }
                "find large intersections" => {
                    find_large_intersections(app);
                }
                "sim internal stats" => {
                    return Transition::Push(PopupMsg::new_state(
                        ctx,
                        "Simulation internal stats",
                        app.primary.sim.describe_internal_stats(),
                    ));
                }
                "blocked-by graph" => {
                    return Transition::Push(blocked_by::Viewer::new_state(ctx, app));
                }
                "blockfinder" => {
                    app.primary.current_selection = None;
                    return Transition::Push(blockfinder::Blockfinder::new_state(ctx, app));
                }
                "render to GeoJSON" => {
                    // TODO Loading screen doesn't actually display anything because of the rules
                    // around hiding the first few draws
                    ctx.loading_screen("render to GeoJSON", |ctx, timer| {
                        timer.start("render");
                        let batch = DrawMap::zoomed_batch(ctx, app);
                        let features = batch.into_geojson(Some(app.primary.map.get_gps_bounds()));
                        let geojson = geojson::GeoJson::from(geojson::FeatureCollection {
                            bbox: None,
                            features,
                            foreign_members: None,
                        });
                        abstio::write_json("rendered_map.json".to_string(), &geojson);
                        timer.stop("render");
                    });
                }
                "draw banned turns" => {
                    // Abuse this just to draw
                    self.search_results = Some(SearchResults {
                        query: "banned turns".to_string(),
                        num_matches: 0,
                        draw: draw_banned_turns(ctx, app),
                    });
                    self.reset_info(ctx);
                }
                "draw arterial crosswalks" => {
                    self.search_results = Some(SearchResults {
                        query: "wide crosswalks".to_string(),
                        num_matches: 0,
                        draw: draw_arterial_crosswalks(ctx, app),
                    });
                    self.reset_info(ctx);
                }
                "export color-scheme" => {
                    app.cs.export("color_scheme").unwrap();
                }
                "import color-scheme" => {
                    app.cs.import("color_scheme").unwrap();
                    ctx.loading_screen("rerendering map colors", |ctx, timer| {
                        app.primary.draw_map =
                            DrawMap::new(ctx, &app.primary.map, &app.opts, &app.cs, timer);
                    });
                }
                "find bad intersection polygons" => {
                    self.search_results = Some(SearchResults {
                        query: "bad intersection polygons".to_string(),
                        num_matches: 0,
                        draw: draw_bad_intersections(ctx, app),
                    });
                    self.reset_info(ctx);
                }
                #[cfg(not(target_arch = "wasm32"))]
                "undo all merged roads" => {
                    if let Err(err) =
                        fs_err::rename("merge_osm_ways.json", "UNDO_merge_osm_ways.json")
                    {
                        warn!("No merged road file? {}", err);
                    }
                    return Transition::Push(reimport_map(ctx, app, None));
                }
                _ => unreachable!(),
            },
            Outcome::Changed(_) => {
                // TODO We should really recalculate current_selection when these change. Meh.
                self.layers.show_buildings = self.panel.is_checked("show buildings");
                self.layers.show_intersections = self.panel.is_checked("show intersections");
                self.layers.show_lanes = self.panel.is_checked("show lanes");
                self.layers.show_areas = self.panel.is_checked("show areas");
                self.layers.show_labels = self.panel.is_checked("show labels");
                app.opts.minimal_controls = self.panel.is_checked("screen recording mode");
                if self.panel.is_checked("show route for all agents") {
                    if self.all_routes.is_none() {
                        self.all_routes = Some(calc_all_routes(ctx, app));
                        self.reset_info(ctx);
                    }
                } else if self.all_routes.is_some() {
                    self.all_routes = None;
                    self.reset_info(ctx);
                }
            }
            _ => {}
        }

        self.highlighted_agents.update(
            match app.primary.current_selection {
                Some(ID::Intersection(i)) => Some(i),
                _ => None,
            },
            |key| {
                let mut batch = GeomBatch::new();
                for (a, _) in app.primary.sim.get_accepted_agents(key) {
                    if let Some(obj) = app.primary.draw_map.get_obj(
                        ctx,
                        ID::from_agent(a),
                        app,
                        &mut app.primary.agents.borrow_mut(),
                    ) {
                        batch.push(Color::PURPLE, obj.get_outline(&app.primary.map));
                    } else {
                        warn!(
                            "{} is accepted at or blocked by by {:?}, but no longer exists",
                            a, key
                        );
                    }
                }
                ctx.upload(batch)
            },
        );

        if let Some(t) = self.common.event(ctx, app, &mut Actions {}) {
            return t;
        }
        match self.tool_panel.event(ctx) {
            Outcome::Clicked(x) => match x.as_ref() {
                "back" => Transition::Pop,
                "settings" => Transition::Push(OptionsPanel::new_state(ctx, app)),
                _ => unreachable!(),
            },
            _ => Transition::Keep,
        }
    }

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

    fn draw(&self, g: &mut GfxCtx, app: &App) {
        let mut opts = DrawOptions::new();
        opts.label_buildings = self.layers.show_labels;
        app.draw(g, opts, self);

        if let Some(ref results) = self.search_results {
            g.redraw(&results.draw);
        }
        if let Some(draw) = self.highlighted_agents.value() {
            g.redraw(draw);
        }

        self.objects.draw(g, app);
        if let Some((_, ref draw)) = self.all_routes {
            g.redraw(draw);
        }

        if !g.is_screencap() {
            self.panel.draw(g);
            self.common.draw(g, app);
            self.tool_panel.draw(g);
        }
    }
}

impl ShowObject for DebugMode {
    fn show(&self, obj: &ID) -> bool {
        if self.hidden.contains(obj) {
            return false;
        }

        match obj {
            ID::Road(_) | ID::Lane(_) => self.layers.show_lanes,
            ID::Building(_) => self.layers.show_buildings,
            ID::Intersection(_) => self.layers.show_intersections,
            ID::Area(_) => self.layers.show_areas,
            _ => true,
        }
    }

    fn layers(&self) -> &ShowLayers {
        &self.layers
    }
}

fn search_osm(filter: String, ctx: &mut EventCtx, app: &mut App) -> Transition {
    let mut num_matches = 0;
    let mut batch = GeomBatch::new();

    // TODO Case insensitive
    let map = &app.primary.map;
    let color = Color::RED.alpha(0.8);
    for r in map.all_roads() {
        if r.osm_tags
            .inner()
            .iter()
            .any(|(k, v)| format!("{} = {}", k, v).contains(&filter))
        {
            num_matches += 1;
            batch.push(color, r.get_thick_polygon());
        }
    }
    for a in map.all_areas() {
        if a.osm_tags
            .inner()
            .iter()
            .any(|(k, v)| format!("{} = {}", k, v).contains(&filter))
        {
            num_matches += 1;
            batch.push(color, a.polygon.clone());
        }
    }

    let results = SearchResults {
        query: filter,
        num_matches,
        draw: batch.upload(ctx),
    };

    Transition::Multi(vec![
        Transition::Pop,
        Transition::ModifyState(Box::new(|state, ctx, _| {
            let mut mode = state.downcast_mut::<DebugMode>().unwrap();
            mode.search_results = Some(results);
            mode.reset_info(ctx);
        })),
    ])
}

struct SearchResults {
    query: String,
    num_matches: usize,
    draw: Drawable,
}

fn calc_all_routes(ctx: &EventCtx, app: &mut App) -> (usize, Drawable) {
    let agents = app.primary.sim.active_agents();
    let mut batch = GeomBatch::new();
    let mut cnt = 0;
    let sim = &app.primary.sim;
    let map = &app.primary.map;
    for trace in Timer::new("calculate all routes")
        .parallelize("route to geometry", agents, |id| {
            sim.trace_route(id, map)
                .map(|trace| trace.make_polygons(NORMAL_LANE_THICKNESS))
        })
        .into_iter()
        .flatten()
    {
        cnt += 1;
        batch.push(app.cs.route, trace);
    }
    (cnt, ctx.upload(batch))
}

struct Actions;
impl ContextualActions for Actions {
    fn actions(&self, app: &App, id: ID) -> Vec<(Key, String)> {
        let mut actions = vec![
            (Key::D, "debug".to_string()),
            (Key::J, "debug with JSON viewer".to_string()),
        ];
        match id {
            ID::Lane(l) => {
                actions.push((Key::H, "hide this".to_string()));
                if app.primary.map.get_l(l).lane_type.supports_any_movement() {
                    actions.push((Key::F, "floodfill from this lane".to_string()));
                    actions.push((Key::S, "show strongly-connected components".to_string()));
                }
                actions.push((Key::X, "debug lane geometry".to_string()));
                actions.push((Key::F2, "debug lane triangles geometry".to_string()));
                actions.push((Key::C, "export roads".to_string()));
                actions.push((Key::E, "show equiv_pos".to_string()));
                actions.push((Key::B, "trace this block".to_string()));
                if cfg!(not(target_arch = "wasm32")) {
                    actions.push((Key::M, "merge short segment".to_string()));
                }
            }
            ID::Intersection(i) => {
                actions.push((Key::H, "hide this".to_string()));
                actions.push((Key::X, "debug intersection geometry".to_string()));
                actions.push((Key::F2, "debug sidewalk corners".to_string()));
                if app.primary.map.get_i(i).roads.len() == 2 {
                    actions.push((Key::C, "collapse degenerate road?".to_string()));
                }
                if app.primary.map.get_i(i).is_border() {
                    actions.push((Key::R, "route from here".to_string()));
                }
                actions.push((Key::U, "explore uber-turns".to_string()));
            }
            ID::Car(_) => {
                actions.push((Key::Backspace, "forcibly delete this car".to_string()));
            }
            ID::Area(_) => {
                actions.push((Key::X, "debug area geometry".to_string()));
                actions.push((Key::F2, "debug area triangles".to_string()));
            }
            ID::ParkingLot(_) => {
                actions.push((Key::H, "hide this".to_string()));
            }
            ID::TransitStop(_) => {
                actions.push((Key::H, "hide this".to_string()));
            }
            ID::Building(_) => {
                actions.push((Key::R, "route from here".to_string()));
            }
            _ => {}
        }
        actions
    }

    fn execute(
        &mut self,
        ctx: &mut EventCtx,
        app: &mut App,
        id: ID,
        action: String,
        close_info: &mut bool,
    ) -> Transition {
        match (id, action.as_ref()) {
            (id, "hide this") => Transition::ModifyState(Box::new(|state, ctx, app| {
                let mode = state.downcast_mut::<DebugMode>().unwrap();
                println!("Hiding {:?}", id);
                app.primary.current_selection = None;
                mode.hidden.insert(id);
                mode.reset_info(ctx);
            })),
            (id, "debug") => {
                *close_info = false;
                objects::ObjectDebugger::dump_debug(id, &app.primary.map, &app.primary.sim);
                Transition::Keep
            }
            (id, "debug with JSON viewer") => {
                *close_info = false;
                objects::ObjectDebugger::debug_json(id, &app.primary.map, &app.primary.sim);
                Transition::Keep
            }
            (ID::Car(c), "forcibly delete this car") => {
                app.primary.sim.delete_car(c, &app.primary.map);
                app.primary
                    .sim
                    .tiny_step(&app.primary.map, &mut app.primary.sim_cb);
                app.primary.current_selection = None;
                Transition::Keep
            }
            (ID::Lane(l), "floodfill from this lane") => {
                Transition::Push(floodfill::Floodfiller::floodfill(ctx, app, l))
            }
            (ID::Lane(l), "show strongly-connected components") => {
                Transition::Push(floodfill::Floodfiller::scc(ctx, app, l))
            }
            (ID::Intersection(i), "debug intersection geometry") => {
                let pts = app.primary.map.get_i(i).polygon.points();
                let mut pts_without_last = pts.clone();
                pts_without_last.pop();
                Transition::Push(polygons::PolygonDebugger::new_state(
                    ctx,
                    "point",
                    pts.iter().map(|pt| polygons::Item::Point(*pt)).collect(),
                    Some(Pt2D::center(&pts_without_last)),
                ))
            }
            (ID::Intersection(i), "debug sidewalk corners") => {
                Transition::Push(polygons::PolygonDebugger::new_state(
                    ctx,
                    "corner",
                    calculate_corners(app.primary.map.get_i(i), &app.primary.map)
                        .into_iter()
                        .map(polygons::Item::Polygon)
                        .collect(),
                    None,
                ))
            }
            (ID::Intersection(i), "collapse degenerate road?") => {
                let i = app.primary.map.get_i(i);
                let (r1, r2) = {
                    let mut iter = i.roads.iter();
                    (*iter.next().unwrap(), *iter.next().unwrap())
                };
                diff_tags(
                    &app.primary.map.get_r(r1).osm_tags,
                    &app.primary.map.get_r(r2).osm_tags,
                );
                Transition::Keep
            }
            (ID::Intersection(i), "route from here") => Transition::Push(
                routes::RouteExplorer::new_state(ctx, app, TripEndpoint::Border(i)),
            ),
            (ID::Intersection(i), "explore uber-turns") => {
                Transition::Push(uber_turns::UberTurnPicker::new_state(ctx, app, i))
            }
            (ID::Lane(l), "debug lane geometry") => {
                Transition::Push(polygons::PolygonDebugger::new_state(
                    ctx,
                    "point",
                    app.primary
                        .map
                        .get_l(l)
                        .lane_center_pts
                        .points()
                        .iter()
                        .map(|pt| polygons::Item::Point(*pt))
                        .collect(),
                    None,
                ))
            }
            (ID::Lane(l), "debug lane triangles geometry") => {
                Transition::Push(polygons::PolygonDebugger::new_state(
                    ctx,
                    "triangle",
                    app.primary
                        .draw_map
                        .get_l(l)
                        .polygon
                        .triangles()
                        .into_iter()
                        .map(polygons::Item::Triangle)
                        .collect(),
                    None,
                ))
            }
            (ID::Lane(l), "export roads") => {
                Transition::Push(select_roads::BulkSelect::new_state(ctx, app, l.road))
            }
            (ID::Lane(l), "show equiv_pos") => {
                Transition::ModifyState(Box::new(move |state, ctx, app| {
                    if let Some(pt) = ctx.canvas.get_cursor_in_map_space() {
                        let map = &app.primary.map;
                        let pl = &map.get_l(l).lane_center_pts;
                        if let Some((dist, _)) = pl.dist_along_of_point(pl.project_pt(pt)) {
                            let base_pos = Position::new(l, dist);
                            let mut batch = GeomBatch::new();
                            for l in &map.get_parent(l).lanes {
                                let pt = base_pos.equiv_pos(l.id, map).pt(map);
                                batch.push(
                                    Color::RED,
                                    Circle::new(pt, Distance::meters(1.0)).to_polygon(),
                                );
                            }
                            let mut mode = state.downcast_mut::<DebugMode>().unwrap();
                            // Just abuse this to display the results
                            mode.search_results = Some(SearchResults {
                                query: format!("equiv_pos {}", base_pos),
                                num_matches: 0,
                                draw: ctx.upload(batch),
                            });
                        }
                    }
                }))
            }
            (ID::Lane(l), "trace this block") => {
                app.primary.current_selection = None;
                let map = &app.primary.map;
                return Transition::Push(
                    match Perimeter::single_block(
                        map,
                        l,
                        &Perimeter::find_roads_to_skip_tracing(map),
                    )
                    .and_then(|perim| perim.to_block(map))
                    {
                        Ok(block) => blockfinder::OneBlock::new_state(ctx, app, block),
                        Err(err) => {
                            // Rendering the error message is breaking
                            error!("Blockfinding failed: {}", err);
                            PopupMsg::new_state(ctx, "Error", vec!["See console"])
                        }
                    },
                );
            }
            #[cfg(not(target_arch = "wasm32"))]
            (ID::Lane(l), "merge short segment") => {
                let mut timer = Timer::throwaway();
                let mut ways: Vec<map_model::raw::OriginalRoad> =
                    abstio::maybe_read_json("merge_osm_ways.json".to_string(), &mut timer)
                        .unwrap_or_else(|_| Vec::new());
                let orig_ways = ways.clone();
                ways.push(app.primary.map.get_parent(l).orig_id);
                abstio::write_json("merge_osm_ways.json".to_string(), &ways);
                Transition::Push(reimport_map(ctx, app, Some(orig_ways)))
            }
            (ID::Area(a), "debug area geometry") => {
                let pts = &app.primary.map.get_a(a).polygon.points();
                let center = if pts[0] == *pts.last().unwrap() {
                    // TODO The center looks really wrong for Volunteer Park and others, but I
                    // think it's because they have many points along some edges.
                    Pt2D::center(&pts.iter().skip(1).cloned().collect::<Vec<_>>())
                } else {
                    Pt2D::center(pts)
                };
                Transition::Push(polygons::PolygonDebugger::new_state(
                    ctx,
                    "point",
                    pts.iter().map(|pt| polygons::Item::Point(*pt)).collect(),
                    Some(center),
                ))
            }
            (ID::Area(a), "debug area triangles") => {
                Transition::Push(polygons::PolygonDebugger::new_state(
                    ctx,
                    "triangle",
                    app.primary
                        .map
                        .get_a(a)
                        .polygon
                        .triangles()
                        .into_iter()
                        .map(polygons::Item::Triangle)
                        .collect(),
                    None,
                ))
            }
            (ID::Building(b), "route from here") => Transition::Push(
                routes::RouteExplorer::new_state(ctx, app, TripEndpoint::Building(b)),
            ),
            _ => unreachable!(),
        }
    }

    fn is_paused(&self) -> bool {
        true
    }

    fn gameplay_mode(&self) -> GameplayMode {
        // Hack so info panels can be opened in DebugMode
        GameplayMode::FixTrafficSignals
    }
}

fn find_bad_signals(app: &App) {
    error!("Bad traffic signals:");
    for i in app.primary.map.all_intersections() {
        if i.is_traffic_signal() {
            let first = &ControlTrafficSignal::get_possible_policies(&app.primary.map, i.id)[0].0;
            if first == "stage per road" || first == "arbitrary assignment" {
                error!("- {}", i.id);
            }
        }
    }
}

// Consider this a second pass to debug, after map_model/src/make/collapse_intersections.rs. Rules
// developed here will make their way there.
fn find_degenerate_roads(app: &App) {
    let map = &app.primary.map;
    for i in map.all_intersections() {
        if i.roads.len() != 2 {
            continue;
        }
        let (r1, r2) = {
            let mut iter = i.roads.iter();
            (*iter.next().unwrap(), *iter.next().unwrap())
        };
        let r1 = map.get_r(r1);
        let r2 = map.get_r(r2);
        if r1.zorder != r2.zorder {
            continue;
        }
        if r1
            .lanes
            .iter()
            .map(|l| (l.dir, l.lane_type))
            .collect::<Vec<_>>()
            != r2
                .lanes
                .iter()
                .map(|l| (l.dir, l.lane_type))
                .collect::<Vec<_>>()
        {
            continue;
        }

        println!("Maybe merge {}", i.id);
        diff_tags(&r1.osm_tags, &r2.osm_tags);
        println!();
    }
}

fn diff_tags(t1: &Tags, t2: &Tags) {
    for (k, v1, v2) in t1.diff(t2) {
        // Ignore the most common diff
        if k == osm::OSM_WAY_ID {
            continue;
        }
        println!("- {} = \"{}\" vs \"{}\"", k, v1, v2);
    }
}

fn find_large_intersections(app: &App) {
    let mut seen = HashSet::new();
    for t in app.primary.map.all_turns() {
        if !seen.contains(&t.id.parent) && t.geom.length() > Distance::meters(50.0) {
            println!("{} has a long turn", t.id.parent);
            seen.insert(t.id.parent);
        }
    }
}

// Because of the slightly odd control flow needed to ask widgetry to ScreenCaptureEverything, a
// separate state is the easiest way to automatically screenshot multiple maps.
struct ScreenshotTest {
    todo_maps: Vec<MapName>,
    screenshot_done: bool,
}

impl ScreenshotTest {
    fn new_state(
        ctx: &mut EventCtx,
        app: &mut App,
        mut todo_maps: Vec<MapName>,
    ) -> Box<dyn State<App>> {
        // Taking screenshots messes with options and doesn't restore them after. It's expected
        // whoever's taking screenshots (just Dustin so far) will just quit after taking them.
        app.change_color_scheme(ctx, ColorSchemeChoice::DayMode);
        ctx.canvas.settings.min_zoom_for_detail = 0.0;
        MapLoader::new_state(
            ctx,
            app,
            todo_maps.pop().unwrap(),
            Box::new(move |_, _| {
                Transition::Replace(Box::new(ScreenshotTest {
                    todo_maps,
                    screenshot_done: false,
                }))
            }),
        )
    }
}

impl State<App> for ScreenshotTest {
    fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Transition {
        if self.screenshot_done {
            if self.todo_maps.is_empty() {
                Transition::Pop
            } else {
                Transition::Replace(ScreenshotTest::new_state(
                    ctx,
                    app,
                    self.todo_maps.drain(..).collect(),
                ))
            }
        } else {
            self.screenshot_done = true;
            let name = app.primary.map.get_name();
            ctx.request_update(UpdateType::ScreenCaptureEverything {
                dir: format!(
                    "screenshots/{}/{}/{}",
                    name.city.country, name.city.city, name.map
                ),
                zoom: 3.0,
                dims: ctx.canvas.get_window_dims(),
            });
            // TODO Sometimes this still gets stuck and needs a mouse wiggle for input event?
            Transition::Keep
        }
    }
    fn draw(&self, _: &mut GfxCtx, _: &App) {}
}

fn draw_banned_turns(ctx: &mut EventCtx, app: &App) -> Drawable {
    let mut batch = GeomBatch::new();
    let map = &app.primary.map;
    for i in map.all_intersections() {
        let mut pairs: HashSet<(RoadID, RoadID)> = HashSet::new();
        // Don't call out one-ways, so use incoming/outgoing roads, and just for cars.
        for l1 in i.get_incoming_lanes(map, PathConstraints::Car) {
            for l2 in i.get_outgoing_lanes(map, PathConstraints::Car) {
                pairs.insert((l1.road, l2.road));
            }
        }
        for t in &i.turns {
            let r1 = t.id.src.road;
            let r2 = t.id.dst.road;
            pairs.remove(&(r1, r2));
        }

        for (r1, r2) in pairs {
            if let Ok(pl) = PolyLine::new(vec![
                map.get_r(r1).center_pts.middle(),
                map.get_r(r2).center_pts.middle(),
            ]) {
                batch.push(
                    Color::RED,
                    pl.make_arrow(Distance::meters(1.0), ArrowCap::Triangle),
                );
            }
        }
    }
    ctx.upload(batch)
}

fn draw_arterial_crosswalks(ctx: &mut EventCtx, app: &App) -> Drawable {
    let mut batch = GeomBatch::new();
    let map = &app.primary.map;
    for turn in map.all_turns() {
        if turn.is_crossing_arterial_intersection(map) {
            batch.push(
                Color::RED,
                turn.geom
                    .make_arrow(Distance::meters(2.0), ArrowCap::Triangle),
            );
        }
    }
    ctx.upload(batch)
}

#[cfg(not(target_arch = "wasm32"))]
fn reimport_map(
    ctx: &mut EventCtx,
    app: &App,
    rollback: Option<Vec<map_model::raw::OriginalRoad>>,
) -> Box<dyn State<App>> {
    map_gui::tools::RunCommand::new_state(
        ctx,
        false,
        vec![
            map_gui::tools::find_exe("cli"),
            "import".to_string(),
            "--map".to_string(),
            app.primary.map.get_name().map.clone(),
            format!("--city={}", app.primary.map.get_name().city.to_path()),
            "--skip-ch".to_string(),
        ],
        Box::new(|ctx, app, success, _| {
            if !success {
                if let Some(ways) = rollback {
                    if let Err(err) =
                        fs_err::copy("merge_osm_ways.json", "BROKEN_merge_osm_ways.json")
                    {
                        warn!("No merged road file? {}", err);
                    }
                    abstio::write_json("merge_osm_ways.json".to_string(), &ways);
                }
            }

            Transition::Push(MapLoader::force_reload(
                ctx,
                app.primary.map.get_name().clone(),
                Box::new(|_, _| Transition::Pop),
            ))
        }),
    )
}

fn draw_bad_intersections(ctx: &mut EventCtx, app: &App) -> Drawable {
    let mut batch = GeomBatch::new();
    for i in app.primary.map.all_intersections() {
        if let Some(ring) = i.polygon.get_outer_ring() {
            if ring.doubles_back() {
                batch.push(Color::RED.alpha(0.8), i.polygon.clone());
            }
        }
    }
    ctx.upload(batch)
}