summaryrefslogtreecommitdiffstats
path: root/winit/src/application.rs
blob: 8c7d8c3745ee88ee43f871d9e65f2b6dfdffff3b (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
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
use crate::{
    column, conversion,
    input::{keyboard, mouse},
    renderer::{Target, Windowed},
    Cache, Column, Element, Event, Length, MouseCursor, UserInterface,
};

pub trait Application {
    type Renderer: Windowed + column::Renderer;

    type Message;

    fn update(&mut self, message: Self::Message);

    fn view(&mut self) -> Element<Self::Message, Self::Renderer>;

    fn run(mut self)
    where
        Self: 'static + Sized,
    {
        use winit::{
            event::{self, WindowEvent},
            event_loop::{ControlFlow, EventLoop},
            window::WindowBuilder,
        };

        let event_loop = EventLoop::new();

        // TODO: Ask for window settings and configure this properly
        let window = WindowBuilder::new()
            .with_inner_size(winit::dpi::LogicalSize {
                width: 1280.0,
                height: 1024.0,
            })
            .build(&event_loop)
            .expect("Open window");

        let mut size: Size = window
            .inner_size()
            .to_physical(window.hidpi_factor())
            .into();
        let mut new_size: Option<Size> = None;

        let mut renderer = Self::Renderer::new();

        let mut target = <Self::Renderer as Windowed>::Target::new(
            &window,
            size.width,
            size.height,
            &renderer,
        );

        let user_interface = UserInterface::build(
            document(&mut self, size),
            Cache::default(),
            &renderer,
        );

        let mut primitive = user_interface.draw(&mut renderer);
        let mut cache = Some(user_interface.into_cache());
        let mut events = Vec::new();
        let mut mouse_cursor = MouseCursor::OutOfBounds;

        window.request_redraw();

        event_loop.run(move |event, _, control_flow| match event {
            event::Event::MainEventsCleared => {
                // TODO: We should be able to keep a user interface alive
                // between events once we remove state references.
                //
                // This will allow us to rebuild it only when a message is
                // handled.
                let mut user_interface = UserInterface::build(
                    document(&mut self, size),
                    cache.take().unwrap(),
                    &renderer,
                );

                let messages =
                    user_interface.update(&renderer, events.drain(..));

                if messages.is_empty() {
                    primitive = user_interface.draw(&mut renderer);

                    cache = Some(user_interface.into_cache());
                } else {
                    // When there are messages, we are forced to rebuild twice
                    // for now :^)
                    let temp_cache = user_interface.into_cache();

                    for message in messages {
                        log::debug!("Updating");

                        self.update(message);
                    }

                    let user_interface = UserInterface::build(
                        document(&mut self, size),
                        temp_cache,
                        &renderer,
                    );

                    primitive = user_interface.draw(&mut renderer);

                    cache = Some(user_interface.into_cache());
                }

                window.request_redraw();
            }
            event::Event::RedrawRequested(_) => {
                if let Some(new_size) = new_size.take() {
                    target.resize(new_size.width, new_size.height, &renderer);

                    size = new_size;
                }

                let new_mouse_cursor =
                    renderer.draw(&primitive, None, &mut target);

                if new_mouse_cursor != mouse_cursor {
                    window.set_cursor_icon(conversion::mouse_cursor(
                        new_mouse_cursor,
                    ));

                    mouse_cursor = new_mouse_cursor;
                }

                // TODO: Handle animations!
                // Maybe we can use `ControlFlow::WaitUntil` for this.
            }
            event::Event::WindowEvent {
                event: window_event,
                ..
            } => match window_event {
                WindowEvent::CursorMoved { position, .. } => {
                    // TODO: Remove when renderer supports HiDPI
                    let physical_position =
                        position.to_physical(window.hidpi_factor());

                    events.push(Event::Mouse(mouse::Event::CursorMoved {
                        x: physical_position.x as f32,
                        y: physical_position.y as f32,
                    }));
                }
                WindowEvent::MouseInput { button, state, .. } => {
                    events.push(Event::Mouse(mouse::Event::Input {
                        button: conversion::mouse_button(button),
                        state: conversion::button_state(state),
                    }));
                }
                WindowEvent::MouseWheel { delta, .. } => match delta {
                    winit::event::MouseScrollDelta::LineDelta(
                        delta_x,
                        delta_y,
                    ) => {
                        events.push(Event::Mouse(
                            mouse::Event::WheelScrolled {
                                delta: mouse::ScrollDelta::Lines {
                                    x: delta_x,
                                    y: delta_y,
                                },
                            },
                        ));
                    }
                    winit::event::MouseScrollDelta::PixelDelta(position) => {
                        // TODO: Remove when renderer supports HiDPI
                        let physical_position =
                            position.to_physical(window.hidpi_factor());

                        events.push(Event::Mouse(
                            mouse::Event::WheelScrolled {
                                delta: mouse::ScrollDelta::Pixels {
                                    x: physical_position.x as f32,
                                    y: physical_position.y as f32,
                                },
                            },
                        ));
                    }
                },
                WindowEvent::ReceivedCharacter(c) => {
                    events.push(Event::Keyboard(
                        keyboard::Event::CharacterReceived(c),
                    ));
                }
                WindowEvent::KeyboardInput {
                    input:
                        winit::event::KeyboardInput {
                            virtual_keycode: Some(virtual_keycode),
                            state,
                            ..
                        },
                    ..
                } => {
                    events.push(Event::Keyboard(keyboard::Event::Input {
                        key_code: conversion::key_code(virtual_keycode),
                        state: conversion::button_state(state),
                    }));
                }
                WindowEvent::CloseRequested => {
                    *control_flow = ControlFlow::Exit;
                }
                WindowEvent::Resized(size) => {
                    new_size =
                        Some(size.to_physical(window.hidpi_factor()).into());

                    log::debug!("Resized: {:?}", new_size);
                }
                _ => {}
            },
            _ => {
                *control_flow = ControlFlow::Wait;
            }
        })
    }
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
struct Size {
    width: u16,
    height: u16,
}

impl From<winit::dpi::PhysicalSize> for Size {
    fn from(physical_size: winit::dpi::PhysicalSize) -> Self {
        Self {
            width: physical_size.width.round() as u16,
            height: physical_size.height.round() as u16,
        }
    }
}

fn document<Application>(
    application: &mut Application,
    size: Size,
) -> Element<Application::Message, Application::Renderer>
where
    Application: self::Application,
    Application::Message: 'static,
{
    Column::new()
        .width(Length::Units(size.width))
        .height(Length::Units(size.height))
        .push(application.view())
        .into()
}