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
use crate::conversion;
use crate::core::{mouse, window};
use crate::core::{Color, Size};
use crate::graphics::Viewport;
use crate::program::{self, Program};
use std::fmt::{Debug, Formatter};

use winit::dpi::LogicalPosition;
use winit::event::{Touch, WindowEvent};
use winit::window::Window;

/// The state of a multi-windowed [`Program`].
pub struct State<P: Program>
where
    P::Theme: program::DefaultStyle,
{
    pub(crate) title: String,
    scale_factor: f64,
    viewport: Viewport,
    viewport_version: u64,
    cursor_position: Option<winit::dpi::PhysicalPosition<f64>>,
    modifiers: winit::keyboard::ModifiersState,
    theme: P::Theme,
    appearance: program::Appearance,
}

impl<P: Program> Debug for State<P>
where
    P::Theme: program::DefaultStyle,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("multi_window::State")
            .field("title", &self.title)
            .field("scale_factor", &self.scale_factor)
            .field("viewport", &self.viewport)
            .field("viewport_version", &self.viewport_version)
            .field("cursor_position", &self.cursor_position)
            .field("appearance", &self.appearance)
            .finish()
    }
}

impl<P: Program> State<P>
where
    P::Theme: program::DefaultStyle,
{
    /// Creates a new [`State`] for the provided [`Program`]'s `window`.
    pub fn new(
        application: &P,
        window_id: window::Id,
        window: &dyn Window,
    ) -> Self {
        let title = application.title(window_id);
        let scale_factor = application.scale_factor(window_id);
        let theme = application.theme(window_id);
        let appearance = application.style(&theme);

        let viewport = {
            let physical_size = window.surface_size();

            Viewport::with_physical_size(
                Size::new(physical_size.width, physical_size.height),
                window.scale_factor() * scale_factor,
            )
        };

        Self {
            title,
            scale_factor,
            viewport,
            viewport_version: 0,
            cursor_position: None,
            modifiers: winit::keyboard::ModifiersState::default(),
            theme,
            appearance,
        }
    }

    /// Returns the current [`Viewport`] of the [`State`].
    pub fn viewport(&self) -> &Viewport {
        &self.viewport
    }

    /// Returns the version of the [`Viewport`] of the [`State`].
    ///
    /// The version is incremented every time the [`Viewport`] changes.
    pub fn viewport_version(&self) -> u64 {
        self.viewport_version
    }

    /// Returns the physical [`Size`] of the [`Viewport`] of the [`State`].
    pub fn physical_size(&self) -> Size<u32> {
        self.viewport.physical_size()
    }

    /// Returns the logical [`Size`] of the [`Viewport`] of the [`State`].
    pub fn logical_size(&self) -> Size<f32> {
        self.viewport.logical_size()
    }

    /// Returns the current scale factor of the [`Viewport`] of the [`State`].
    pub fn scale_factor(&self) -> f64 {
        self.viewport.scale_factor()
    }

    pub fn set_logical_cursor_pos(&mut self, pos: LogicalPosition<f64>) {
        let physical = pos.to_physical(self.scale_factor());
        self.cursor_position = Some(physical);
    }

    /// Returns the current cursor position of the [`State`].
    pub fn cursor(&self) -> mouse::Cursor {
        self.cursor_position
            .map(|cursor_position| {
                conversion::cursor_position(
                    cursor_position,
                    self.viewport.scale_factor(),
                )
            })
            .map(mouse::Cursor::Available)
            .unwrap_or(mouse::Cursor::Unavailable)
    }

    /// Returns the current keyboard modifiers of the [`State`].
    pub fn modifiers(&self) -> winit::keyboard::ModifiersState {
        self.modifiers
    }

    /// Returns the current theme of the [`State`].
    pub fn theme(&self) -> &P::Theme {
        &self.theme
    }

    /// Returns the current background [`Color`] of the [`State`].
    pub fn background_color(&self) -> Color {
        self.appearance.background_color
    }

    /// Returns the current text [`Color`] of the [`State`].
    pub fn text_color(&self) -> Color {
        self.appearance.text_color
    }

    /// Returns the current icon [`Color`] of the [`State`].
    pub fn icon_color(&self) -> Color {
        self.appearance.icon_color
    }

    /// Update the scale factor
    pub(crate) fn update_scale_factor(&mut self, new_scale_factor: f64) {
        let size = self.viewport.physical_size();

        self.viewport = Viewport::with_physical_size(
            size,
            new_scale_factor * self.scale_factor,
        );

        self.viewport_version = self.viewport_version.wrapping_add(1);
    }

    /// Processes the provided window event and updates the [`State`] accordingly.
    pub fn update(
        &mut self,
        window: &dyn Window,
        event: &WindowEvent,
        _debug: &mut crate::runtime::Debug,
    ) {
        match event {
            WindowEvent::SurfaceResized(new_size) => {
                let size = Size::new(new_size.width, new_size.height);

                self.viewport = Viewport::with_physical_size(
                    size,
                    window.scale_factor() * self.scale_factor,
                );

                self.viewport_version = self.viewport_version.wrapping_add(1);
            }
            WindowEvent::ScaleFactorChanged {
                scale_factor: new_scale_factor,
                ..
            } => {
                self.update_scale_factor(*new_scale_factor);
            }
            WindowEvent::CursorMoved { position, .. }
            | WindowEvent::Touch(Touch {
                location: position, ..
            }) => {
                self.cursor_position = Some(*position);
            }
            WindowEvent::CursorLeft { .. } => {
                self.cursor_position = None;
            }
            WindowEvent::ModifiersChanged(new_modifiers) => {
                self.modifiers = new_modifiers.state();
            }
            #[cfg(feature = "debug")]
            WindowEvent::KeyboardInput {
                event:
                    winit::event::KeyEvent {
                        logical_key:
                            winit::keyboard::Key::Named(
                                winit::keyboard::NamedKey::F12,
                            ),
                        state: winit::event::ElementState::Pressed,
                        ..
                    },
                ..
            } => _debug.toggle(),
            _ => {}
        }
    }

    /// Synchronizes the [`State`] with its [`Program`] and its respective
    /// window.
    ///
    /// Normally, a [`Program`] should be synchronized with its [`State`]
    /// and window after calling [`State::update`].
    pub fn synchronize(
        &mut self,
        application: &P,
        window_id: window::Id,
        window: &dyn Window,
    ) {
        // Update window title
        let new_title = application.title(window_id);

        if self.title != new_title {
            window.set_title(&new_title);
            self.title = new_title;
        }

        // Update scale factor and size
        let new_scale_factor = application.scale_factor(window_id);
        let mut new_size = window.surface_size();
        let current_size = self.viewport.physical_size();
        if self.scale_factor != new_scale_factor
            || (current_size.width, current_size.height)
                != (new_size.width, new_size.height)
                && !(new_size.width == 0 && new_size.height == 0)
        {
            if new_size.width == 0 {
                new_size.width = current_size.width;
            }
            if new_size.height == 0 {
                new_size.height = current_size.height;
            }
            self.viewport = Viewport::with_physical_size(
                Size::new(new_size.width, new_size.height),
                window.scale_factor() * new_scale_factor,
            );
            self.viewport_version = self.viewport_version.wrapping_add(1);

            self.scale_factor = new_scale_factor;
        }

        // Update theme and appearance
        self.theme = application.theme(window_id);
        self.appearance = application.style(&self.theme);
    }
}