ltn/save/
proposals_ui.rs

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
use abstutil::Timer;
use map_gui::tools::{FilePicker, FileSaver, FileSaverContents};
use widgetry::tools::{ChooseSomething, PopupMsg};
use widgetry::{lctrl, Choice, EventCtx, Key, MultiKey, State, Widget};

use super::save_dialog::SaveDialog;
use super::share::ShareProposal;
use super::{PreserveState, Proposal, Proposals};
use crate::{App, Transition};

impl Proposals {
    pub fn to_widget_expanded(&self, ctx: &EventCtx) -> Widget {
        let mut col = Vec::new();
        for (action, icon, hotkey) in [
            ("New", "pencil", None),
            ("Load", "folder", None),
            ("Save", "save", Some(MultiKey::from(lctrl(Key::S)))),
            ("Share", "share", None),
            ("Export GeoJSON", "export", None),
        ] {
            col.push(
                ctx.style()
                    .btn_plain
                    .icon_text(&format!("system/assets/tools/{icon}.svg"), action)
                    .hotkey(hotkey)
                    .build_def(ctx),
            );
        }

        for (idx, proposal) in self.list.iter().enumerate() {
            let button = ctx
                .style()
                .btn_solid_primary
                .text(if idx == 0 {
                    "1 - existing LTNs".to_string()
                } else {
                    format!("{} - {}", idx + 1, proposal.edits.edits_name)
                })
                .hotkey(Key::NUM_KEYS[idx])
                .disabled(idx == self.current)
                .build_widget(ctx, &format!("switch to proposal {}", idx));
            col.push(Widget::row(vec![
                button,
                // The first proposal (usually "existing LTNs", unless we're in a special consultation
                // mode) is special and can't ever be removed
                if idx != 0 {
                    ctx.style()
                        .btn_close()
                        .disabled(self.list.len() == 1)
                        .build_widget(ctx, &format!("hide proposal {}", idx))
                } else {
                    Widget::nothing()
                },
            ]));
            // If somebody tries to load too many proposals, just stop
            if idx == 9 {
                break;
            }
        }
        Widget::col(col)
    }

    pub fn to_widget_collapsed(&self, ctx: &EventCtx) -> Widget {
        let mut col = Vec::new();
        for (action, icon) in [
            ("New", "pencil"),
            ("Load", "folder"),
            ("Save", "save"),
            ("Share", "share"),
            ("Export GeoJSON", "export"),
        ] {
            col.push(
                ctx.style()
                    .btn_plain
                    .icon(&format!("system/assets/tools/{icon}.svg"))
                    .build_widget(ctx, action),
            );
        }
        Widget::col(col)
    }

    pub fn handle_action(
        ctx: &mut EventCtx,
        app: &mut App,
        preserve_state: &PreserveState,
        action: &str,
    ) -> Option<Transition> {
        match action {
            "New" => {
                // Fork a new proposal from the first one
                if app.per_map.proposals.current != 0 {
                    switch_to_existing_proposal(ctx, app, 0);
                }
            }
            "Load" => {
                return Some(Transition::Push(load_picker_ui(
                    ctx,
                    app,
                    preserve_state.clone(),
                )));
            }
            "Save" => {
                return Some(Transition::Push(SaveDialog::new_state(
                    ctx,
                    app,
                    preserve_state.clone(),
                )));
            }
            "Share" => {
                return Some(Transition::Push(ShareProposal::new_state(ctx, app)));
            }
            "Export GeoJSON" => {
                return Some(Transition::Push(match crate::export::geojson_string(app) {
                    Ok(contents) => FileSaver::with_default_messages(
                        ctx,
                        format!("ltn_{}.geojson", app.per_map.map.get_name().map),
                        super::start_dir(),
                        FileSaverContents::String(contents),
                    ),
                    Err(err) => PopupMsg::new_state(ctx, "Export failed", vec![err.to_string()]),
                }));
            }
            _ => {
                if let Some(x) = action.strip_prefix("switch to proposal ") {
                    let idx = x.parse::<usize>().unwrap();
                    switch_to_existing_proposal(ctx, app, idx);
                } else if let Some(x) = action.strip_prefix("hide proposal ") {
                    let idx = x.parse::<usize>().unwrap();
                    if idx == app.per_map.proposals.current {
                        // First make sure we're not hiding the current proposal
                        switch_to_existing_proposal(ctx, app, if idx == 0 { 1 } else { idx - 1 });
                    }

                    // Remove it
                    app.per_map.proposals.list.remove(idx);

                    // Fix up indices
                    if idx < app.per_map.proposals.current {
                        app.per_map.proposals.current -= 1;
                    }
                } else {
                    return None;
                }
            }
        }

        Some(preserve_state.clone().switch_to_state(ctx, app))
    }
}

fn switch_to_existing_proposal(ctx: &mut EventCtx, app: &mut App, idx: usize) {
    app.per_map.proposals.current = idx;
    app.per_map.map.must_apply_edits(
        app.per_map.proposals.get_current().edits.clone(),
        &mut Timer::throwaway(),
    );
    crate::redraw_all_icons(ctx, app);
}

fn load_picker_ui(
    ctx: &mut EventCtx,
    app: &App,
    preserve_state: PreserveState,
) -> Box<dyn State<App>> {
    // Don't bother trying to filter out proposals currently loaded -- by loading twice, somebody
    // effectively makes a copy to modify a bit
    ChooseSomething::new_state(
        ctx,
        "Load which proposal?",
        // basename (and thus list_all_objects) turn "foo.json.gz" into "foo.json", so further
        // strip out the extension.
        // TODO Fix basename, but make sure nothing downstream breaks
        {
            let mut choices = vec!["Load from file on your computer".to_string()];
            choices.extend(
                abstio::list_all_objects(abstio::path_all_ltn_proposals(
                    app.per_map.map.get_name(),
                ))
                .into_iter()
                .map(abstutil::basename),
            );
            Choice::strings(choices)
        },
        Box::new(move |name, ctx, app| {
            if name == "Load from file on your computer" {
                Transition::Replace(FilePicker::new_state(
                    ctx,
                    super::start_dir(),
                    Box::new(move |ctx, app, maybe_file| {
                        match maybe_file {
                            Ok(Some((path, bytes))) => {
                                match Proposal::load_from_bytes(ctx, app, &path, Ok(bytes)) {
                                    Some(err_state) => Transition::Replace(err_state),
                                    None => preserve_state.switch_to_state(ctx, app),
                                }
                            }
                            // No file chosen, just quit the picker
                            Ok(None) => Transition::Pop,
                            Err(err) => Transition::Replace(PopupMsg::new_state(
                                ctx,
                                "Error",
                                vec![err.to_string()],
                            )),
                        }
                    }),
                ))
            } else {
                match Proposal::load_from_path(
                    ctx,
                    app,
                    abstio::path_ltn_proposals(app.per_map.map.get_name(), &name),
                ) {
                    Some(err_state) => Transition::Replace(err_state),
                    None => preserve_state.switch_to_state(ctx, app),
                }
            }
        }),
    )
}