summaryrefslogtreecommitdiffstats
path: root/examples/image.rs
blob: a64c07822d885236f37838a2731b23b8fb191c23 (plain) (blame)
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
use iced::{
    button, image, Align, Application, Background, Button, Color, Column,
    Command, Container, Element, HorizontalAlignment, Image, Length, Row,
    Settings, Text,
};
use serde::Deserialize;

pub fn main() {
    Example::run(Settings::default())
}

#[derive(Default)]
struct Example {
    cats_button: button::State,
    dogs_button: button::State,
    image: Option<image::Handle>,
    state: State,
}

enum State {
    Idle,
    Loading(Pet),
    Error(LoadError),
}

impl Default for State {
    fn default() -> State {
        State::Idle
    }
}

#[derive(Debug, Clone)]
enum Message {
    PetChosen(Pet),
    ImageLoaded(Result<image::Handle, LoadError>),
}

#[derive(Debug, Clone, Copy)]
enum Pet {
    Cat,
    Dog,
}

impl Application for Example {
    type Message = Message;

    fn new() -> (Self, Command<Message>) {
        (Self::default(), Command::none())
    }

    fn title(&self) -> String {
        String::from("Image viewer - Iced")
    }

    fn update(&mut self, message: Message) -> Command<Message> {
        match message {
            Message::PetChosen(pet) => match self.state {
                State::Loading(_) => Command::none(),
                _ => {
                    self.state = State::Loading(pet);

                    Command::perform(get_pet_image(pet), Message::ImageLoaded)
                }
            },
            Message::ImageLoaded(Ok(image)) => {
                self.image = Some(image);
                self.state = State::Idle;

                Command::none()
            }
            Message::ImageLoaded(Err(error)) => {
                self.state = State::Error(error);

                Command::none()
            }
        }
    }

    fn view(&mut self) -> Element<Message> {
        let Example {
            cats_button,
            dogs_button,
            state,
            image,
        } = self;

        let choose: Element<_> = match state {
            State::Loading(pet) => Text::new(format!(
                "Getting your {} ready...",
                match pet {
                    Pet::Cat => "cat",
                    Pet::Dog => "dog",
                }
            ))
            .width(Length::Shrink)
            .color([0.4, 0.4, 0.4])
            .into(),
            _ => Row::new()
                .width(Length::Shrink)
                .spacing(20)
                .push(
                    button(
                        cats_button,
                        "Cats",
                        Color::from_rgb8(0x89, 0x80, 0xF5),
                    )
                    .on_press(Message::PetChosen(Pet::Cat)),
                )
                .push(
                    button(
                        dogs_button,
                        "Dogs",
                        Color::from_rgb8(0x21, 0xD1, 0x9F),
                    )
                    .on_press(Message::PetChosen(Pet::Dog)),
                )
                .into(),
        };

        let content = Column::new()
            .width(Length::Shrink)
            .padding(20)
            .spacing(20)
            .align_items(Align::Center)
            .push(
                Text::new("What do you want to see?")
                    .width(Length::Shrink)
                    .horizontal_alignment(HorizontalAlignment::Center)
                    .size(40),
            )
            .push(choose);

        let content = if let Some(image) = image {
            content.push(Image::new(image.clone()).height(Length::Fill))
        } else {
            content
        };

        Container::new(content)
            .width(Length::Fill)
            .height(Length::Fill)
            .center_x()
            .center_y()
            .into()
    }
}

fn button<'a, Message>(
    state: &'a mut button::State,
    label: &str,
    color: Color,
) -> Button<'a, Message> {
    Button::new(
        state,
        Text::new(label)
            .horizontal_alignment(HorizontalAlignment::Center)
            .color(Color::WHITE)
            .size(30),
    )
    .padding(10)
    .min_width(100)
    .border_radius(10)
    .background(Background::Color(color))
}

#[derive(Debug, Deserialize)]
pub struct SearchResult {
    url: String,
}

#[derive(Debug, Clone)]
enum LoadError {
    RequestError,
}

async fn get_pet_image(pet: Pet) -> Result<image::Handle, LoadError> {
    use std::io::Read;

    let search = match pet {
        Pet::Cat => "https://api.thecatapi.com/v1/images/search?limit=1&mime_types=jpg,png",
        Pet::Dog => "https://api.thedogapi.com/v1/images/search?limit=1&mime_types=jpg,png",
    };

    let results: Vec<SearchResult> = reqwest::get(search)?.json()?;
    let url = &results.first().unwrap().url;

    let mut image = reqwest::get(url)?;
    let mut bytes = Vec::new();

    image
        .read_to_end(&mut bytes)
        .map_err(|_| LoadError::RequestError)?;

    Ok(image::Handle::from_bytes(bytes))
}

impl From<reqwest::Error> for LoadError {
    fn from(error: reqwest::Error) -> LoadError {
        dbg!(&error);
        LoadError::RequestError
    }
}