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
//! Generic UI tools. Some of this should perhaps be lifted to widgetry.

use anyhow::Result;

use geom::Polygon;
use widgetry::{
    hotkeys, Choice, Color, DrawBaselayer, EventCtx, GfxCtx, Key, Line, Menu, Outcome, Panel,
    State, Text, TextBox, Transition, Widget,
};

use crate::load::FutureLoader;
use crate::tools::grey_out_map;
use crate::AppLike;

/// Choose something from a menu, then feed the answer to a callback.
pub struct ChooseSomething<A: AppLike, T> {
    panel: Panel,
    // Wrapped in an Option so that we can consume it once
    cb: Option<Box<dyn FnOnce(T, &mut EventCtx, &mut A) -> Transition<A>>>,
}

impl<A: AppLike + 'static, T: 'static> ChooseSomething<A, T> {
    pub fn new_state<I: Into<String>>(
        ctx: &mut EventCtx,
        query: I,
        choices: Vec<Choice<T>>,
        cb: Box<dyn FnOnce(T, &mut EventCtx, &mut A) -> Transition<A>>,
    ) -> Box<dyn State<A>> {
        Box::new(ChooseSomething {
            panel: Panel::new_builder(Widget::col(vec![
                Widget::row(vec![
                    Line(query).small_heading().into_widget(ctx),
                    ctx.style().btn_close_widget(ctx),
                ]),
                Menu::widget(ctx, choices).named("menu"),
            ]))
            .build(ctx),
            cb: Some(cb),
        })
    }
}

impl<A: AppLike + 'static, T: 'static> State<A> for ChooseSomething<A, T> {
    fn event(&mut self, ctx: &mut EventCtx, app: &mut A) -> Transition<A> {
        match self.panel.event(ctx) {
            Outcome::Clicked(x) => match x.as_ref() {
                "close" => Transition::Pop,
                _ => {
                    let data = self.panel.take_menu_choice::<T>("menu");
                    // If the callback doesn't replace or pop this ChooseSomething state, then
                    // it'll break when the user tries to interact with the menu again.
                    (self.cb.take().unwrap())(data, ctx, app)
                }
            },
            _ => {
                if ctx.normal_left_click() && ctx.canvas.get_cursor_in_screen_space().is_none() {
                    return Transition::Pop;
                }
                Transition::Keep
            }
        }
    }

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

    fn draw(&self, g: &mut GfxCtx, app: &A) {
        grey_out_map(g, app);
        self.panel.draw(g);
    }
}

/// Prompt for arbitrary text input, then feed the answer to a callback.
pub struct PromptInput<A: AppLike> {
    panel: Panel,
    cb: Option<Box<dyn FnOnce(String, &mut EventCtx, &mut A) -> Transition<A>>>,
}

impl<A: AppLike + 'static> PromptInput<A> {
    pub fn new_state(
        ctx: &mut EventCtx,
        query: &str,
        initial: String,
        cb: Box<dyn FnOnce(String, &mut EventCtx, &mut A) -> Transition<A>>,
    ) -> Box<dyn State<A>> {
        Box::new(PromptInput {
            panel: Panel::new_builder(Widget::col(vec![
                Widget::row(vec![
                    Line(query).small_heading().into_widget(ctx),
                    ctx.style().btn_close_widget(ctx),
                ]),
                TextBox::default_widget(ctx, "input", initial),
                ctx.style()
                    .btn_outline
                    .text("confirm")
                    .hotkey(Key::Enter)
                    .build_def(ctx),
            ]))
            .build(ctx),
            cb: Some(cb),
        })
    }
}

impl<A: AppLike + 'static> State<A> for PromptInput<A> {
    fn event(&mut self, ctx: &mut EventCtx, app: &mut A) -> Transition<A> {
        match self.panel.event(ctx) {
            Outcome::Clicked(x) => match x.as_ref() {
                "close" => Transition::Pop,
                "confirm" => {
                    let data = self.panel.text_box("input");
                    (self.cb.take().unwrap())(data, ctx, app)
                }
                _ => unreachable!(),
            },
            _ => {
                if ctx.normal_left_click() && ctx.canvas.get_cursor_in_screen_space().is_none() {
                    return Transition::Pop;
                }
                Transition::Keep
            }
        }
    }

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

    fn draw(&self, g: &mut GfxCtx, app: &A) {
        grey_out_map(g, app);
        self.panel.draw(g);
    }
}

/// Display a message dialog.
pub struct PopupMsg {
    panel: Panel,
}

impl PopupMsg {
    pub fn new_state<A: AppLike>(
        ctx: &mut EventCtx,
        title: &str,
        lines: Vec<impl AsRef<str>>,
    ) -> Box<dyn State<A>> {
        let mut txt = Text::new();
        txt.add_line(Line(title).small_heading());
        for l in lines {
            txt.add_line(l);
        }
        Box::new(PopupMsg {
            panel: Panel::new_builder(Widget::col(vec![
                txt.into_widget(ctx),
                ctx.style()
                    .btn_solid_primary
                    .text("OK")
                    .hotkey(hotkeys(vec![Key::Enter, Key::Escape]))
                    .build_def(ctx),
            ]))
            .build(ctx),
        })
    }
}

impl<A: AppLike> State<A> for PopupMsg {
    fn event(&mut self, ctx: &mut EventCtx, _: &mut A) -> Transition<A> {
        match self.panel.event(ctx) {
            Outcome::Clicked(x) => match x.as_ref() {
                "OK" => Transition::Pop,
                _ => unreachable!(),
            },
            _ => {
                if ctx.normal_left_click() && ctx.canvas.get_cursor_in_screen_space().is_none() {
                    return Transition::Pop;
                }
                Transition::Keep
            }
        }
    }

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

    fn draw(&self, g: &mut GfxCtx, _: &A) {
        // This is a copy of grey_out_map from map_gui, with no dependencies on App
        g.fork_screenspace();
        g.draw_polygon(
            Color::BLACK.alpha(0.6),
            Polygon::rectangle(g.canvas.window_width, g.canvas.window_height),
        );
        g.unfork();

        self.panel.draw(g);
    }
}

pub struct FilePicker;

impl FilePicker {
    pub fn new_state<A: 'static + AppLike>(
        ctx: &mut EventCtx,
        start_dir: Option<String>,
        on_load: Box<dyn FnOnce(&mut EventCtx, &mut A, Result<Option<String>>) -> Transition<A>>,
    ) -> Box<dyn State<A>> {
        let (_, outer_progress_rx) = futures_channel::mpsc::channel(1);
        let (_, inner_progress_rx) = futures_channel::mpsc::channel(1);
        FutureLoader::<A, Option<String>>::new_state(
            ctx,
            Box::pin(async move {
                let mut builder = rfd::AsyncFileDialog::new();
                if let Some(dir) = start_dir {
                    builder = builder.set_directory(&dir);
                }
                let result = builder.pick_file().await.map(|x| {
                    #[cfg(not(target_arch = "wasm32"))]
                    {
                        x.path().display().to_string()
                    }
                    #[cfg(target_arch = "wasm32")]
                    {
                        format!("TODO rfd on wasm: {:?}", x)
                    }
                });
                let wrap: Box<dyn Send + FnOnce(&A) -> Option<String>> =
                    Box::new(move |_: &A| result);
                Ok(wrap)
            }),
            outer_progress_rx,
            inner_progress_rx,
            "Waiting for a file to be chosen",
            on_load,
        )
    }
}