DEVELOPMENT ENVIRONMENT

~liljamo/gandalf

ref: gandalf-v0 gandalf/src/gandalf.rs -rw-r--r-- 9.1 KiB
6b9e1364Jonni Liljamo fix: disable exit on unfocus, broken on sway 1 year, 9 months ago
                                                                                
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
use iced::{
    self, alignment, executor, keyboard, subscription,
    widget::{column, container, image, row, text, text_input},
    window, Alignment, Application, Command, ContentFit, Event, Length, Subscription,
};

use cpc;
use rand::{self, seq::SliceRandom};

use crate::{input, programs, theme, FONT_BOLD};

pub type Renderer = iced::Renderer<theme::GTheme>;
pub type Element<'a, Message> = iced::Element<'a, Message, Renderer>;
pub type Column<'a, Message> = iced::widget::Column<'a, Message, Renderer>;

enum GandalfState {
    Exec,
    Calc,
}

pub struct Gandalf {
    state: GandalfState,
    image: image::Handle,
    image_width: u16,
    prompt: String,
    prompt_input_id: text_input::Id,
    output: String,
    calc_output: Option<cpc::Number>,
    programs: Vec<programs::Program>,
    filtered_programs: Vec<programs::Program>,
    /// cursor position
    c_pos: usize,
    /// cursor page
    c_page: usize,
    /// entries visible per page, entries per page
    epp: usize,
}

#[derive(Debug, Clone)]
pub enum Message {
    PromptChanged(String),
    FocusPromptInput(Vec<programs::Program>),
    MoveCursor(bool),
    Execute,
    Exit,
}

impl Application for Gandalf {
    type Executor = executor::Default;
    type Message = Message;
    type Theme = theme::GTheme;
    type Flags = ();

    fn new(_flags: ()) -> (Self, Command<Message>) {
        // FIXME: why yes, i am indeed hard coding the images and their widths.
        // i was not able to come up with a way to do it dynamically, but give me a break, its 1 am right now.
        let images = vec![
            (
                image::Handle::from_memory(include_bytes!("../assets/001.jpg").as_slice()),
                1200,
            ),
            (
                image::Handle::from_memory(include_bytes!("../assets/002.jpg").as_slice()),
                479,
            ),
            (
                image::Handle::from_memory(include_bytes!("../assets/003.jpg").as_slice()),
                471,
            ),
            (
                image::Handle::from_memory(include_bytes!("../assets/004.jpg").as_slice()),
                510,
            ),
        ];

        let (image_handle, image_width) = images.choose(&mut rand::thread_rng()).unwrap();

        let gandalf = Gandalf {
            state: GandalfState::Exec,
            image: image_handle.clone(),
            image_width: *image_width as u16,
            prompt: String::from(""),
            prompt_input_id: text_input::Id::unique(),
            output: String::from(""),
            calc_output: None,
            programs: vec![],
            filtered_programs: vec![],
            c_pos: 0,
            c_page: 0,
            epp: 9,
        };
        (
            gandalf,
            Command::batch(vec![
                window::set_mode(window::Mode::Fullscreen),
                Command::perform(programs::fetch(), Message::FocusPromptInput),
            ]),
        )
    }

    fn title(&self) -> String {
        String::from("gandalf")
    }

    fn theme(&self) -> Self::Theme {
        theme::GTheme::Light
    }

    fn update(&mut self, message: Message) -> Command<Message> {
        match message {
            Message::PromptChanged(prompt) => {
                self.prompt = prompt;

                self.filter_programs();

                // if no programs, go to calc
                if self.filtered_programs.len() == 0 {
                    self.state = GandalfState::Calc;

                    let evald = cpc::eval(&self.prompt, true, cpc::units::Unit::Celsius, false);

                    match evald {
                        Ok(res) => {
                            self.calc_output = Some(res);
                        }
                        Err(res) => {
                            self.calc_output = None;
                            self.output = res.to_string();
                        }
                    }
                } else {
                    self.state = GandalfState::Exec;
                }

                // TODO: other things to check
                // if input starts with "set bl", show something like
                // set backlight to N
                // if input starts with "set vol", show something like
                // set volume to N

                Command::none()
            }
            Message::FocusPromptInput(programs) => {
                self.programs = programs.clone();
                self.filter_programs();

                text_input::focus(self.prompt_input_id.clone())
            }
            Message::MoveCursor(d) => {
                match d {
                    true => {
                        if self.c_pos > 0 {
                            if self.c_pos % self.epp == 0 {
                                self.c_page -= 1;
                            }
                            self.c_pos -= 1;
                        }
                    }
                    false => {
                        if self.c_pos < self.programs.len() - 1 {
                            if (self.c_pos + 1) % self.epp == 0 {
                                self.c_page += 1;
                            }
                            self.c_pos += 1;
                        }
                    }
                }

                Command::none()
            }
            Message::Execute => match self.state {
                GandalfState::Exec => {
                    let program = self.filtered_programs.get(self.c_pos).unwrap();
                    match programs::launch(&program.path) {
                        Ok(_) => {
                            // Shit was successful

                            // TODO: I guess we could save history here for remembering popular choices.

                            window::close()
                        }
                        Err(_) => {
                            println!("got fucked while launching '{}'", program.path);

                            window::close()
                        }
                    }
                }
                GandalfState::Calc => match self.calc_output.clone() {
                    Some(output) => iced::clipboard::write(output.value.to_string()),
                    None => Command::none(),
                },
            },
            Message::Exit => window::close(),
        }
    }

    fn subscription(&self) -> Subscription<Self::Message> {
        subscription::events_with(|event, _status| match event {
            Event::Keyboard(keyboard::Event::KeyPressed {
                modifiers: _,
                key_code,
            }) => input::handle(key_code),
            //Event::Window(window::Event::Unfocused) => Some(Message::Exit),
            _ => None,
        })
    }

    fn view(&self) -> Element<'_, Self::Message> {
        let info_col = column![
            container(text("prompt:").width(Length::Shrink))
                .width(Length::Units(self.image_width))
                .align_x(alignment::Horizontal::Right),
            image(self.image.clone()).content_fit(ContentFit::ScaleDown) //.height(Length::Units(300))
        ]
        .padding(15);

        let prompt_input = text_input("gandalf shall give", &self.prompt, Message::PromptChanged)
            .id(self.prompt_input_id.clone())
            .width(Length::Units(450));

        let main_col_content: Column<Message>;

        match self.state {
            GandalfState::Exec => {
                main_col_content = self
                    .filtered_programs
                    .iter()
                    .skip(self.c_page * self.epp)
                    .take(self.epp)
                    .enumerate()
                    .fold(Column::new(), |column, (i, program)| {
                        if (i + (self.c_page * self.epp)) == self.c_pos {
                            column.push(
                                text(program.exec.clone())
                                    .style(theme::Text::Selected)
                                    .font(FONT_BOLD),
                            )
                        } else {
                            column.push(text(program.exec.clone()))
                        }
                    })
                    .into();
            }
            GandalfState::Calc => {
                main_col_content = column![text({
                    if self.calc_output.is_some() {
                        self.calc_output.clone().unwrap().value.to_string()
                    } else {
                        self.output.clone()
                    }
                })];
            }
        }

        let main_col = column![row![prompt_input], row![main_col_content]].padding(10);

        let content = column![row![row![info_col, main_col,]]
            .height(Length::Fill)
            .align_items(Alignment::Center)]
        .width(Length::Fill)
        .height(Length::Fill)
        .align_items(Alignment::Center);

        content.into()
    }
}

impl Gandalf {
    fn filter_programs(&mut self) {
        self.filtered_programs = self
            .programs
            .iter()
            .filter(|program| program.exec.to_lowercase().contains(self.prompt.as_str()))
            .cloned()
            .collect();

        self.c_pos = 0;
        self.c_page = 0;
    }
}