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
// TODO This doesn't really belong in gameplay/freeform

use map_gui::load::FutureLoader;
use map_gui::tools::{find_exe, RunCommand};
use widgetry::EventCtx;

use crate::app::{App, Transition};
use crate::sandbox::gameplay::GameplayMode;
use crate::sandbox::SandboxMode;

pub fn import(ctx: &mut EventCtx) -> Transition {
    let (_, outer_progress_rx) = futures_channel::mpsc::channel(1);
    let (_, inner_progress_rx) = futures_channel::mpsc::channel(1);
    Transition::Push(FutureLoader::<App, Option<String>>::new(
        ctx,
        Box::pin(async {
            let result = rfd::AsyncFileDialog::new()
                .pick_file()
                .await
                .map(|x| x.path().display().to_string());
            let wrap: Box<dyn Send + FnOnce(&App) -> Option<String>> =
                Box::new(move |_: &App| result);
            Ok(wrap)
        }),
        outer_progress_rx,
        inner_progress_rx,
        "Waiting for a file to be chosen",
        Box::new(|ctx, app, maybe_path| {
            if let Ok(Some(path)) = maybe_path {
                Transition::Replace(RunCommand::new(
                    ctx,
                    app,
                    vec![
                        find_exe("import_grid2demand"),
                        format!("--map={}", app.primary.map.get_name().path()),
                        format!("--input={}", path),
                    ],
                    Box::new(|_, app, success, _| {
                        if success {
                            // Clear out the cached scenario. If we repeatedly use this import, the
                            // scenario name is always the same, but the file is changing.
                            app.primary.scenario = None;
                            Transition::Replace(SandboxMode::simple_new(
                                app,
                                GameplayMode::PlayScenario(
                                    app.primary.map.get_name().clone(),
                                    "grid2demand".to_string(),
                                    Vec::new(),
                                ),
                            ))
                        } else {
                            // The popup already explained the failure
                            Transition::Keep
                        }
                    }),
                ))
            } else {
                // The user didn't pick a file, so stay on the scenario picker
                Transition::Pop
            }
        }),
    ))
}