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
282
283
284
285
286
287
288
289
290
291
292
293
294
use iced_core::widget::operation::{OperationWrapper, Outcome};
use iced_core::widget::OperationOutputWrapper;

use crate::core::event::{self, Event};
use crate::core::mouse;
use crate::core::renderer;
use crate::core::widget::operation::{self, Operation};
use crate::core::{Clipboard, Size};
use crate::user_interface::{self, UserInterface};
use crate::{command::Action, Command, Debug, Program};

/// The execution state of a [`Program`]. It leverages caching, event
/// processing, and rendering primitive storage.
#[allow(missing_debug_implementations)]
pub struct State<P>
where
    P: Program + 'static,
{
    program: P,
    cache: Option<user_interface::Cache>,
    queued_events: Vec<Event>,
    queued_messages: Vec<P::Message>,
    mouse_interaction: mouse::Interaction,
}

impl<P> State<P>
where
    P: Program + 'static,
{
    /// Creates a new [`State`] with the provided [`Program`], initializing its
    /// primitive with the given logical bounds and renderer.
    pub fn new(
        id: crate::window::Id,
        mut program: P,
        bounds: Size,
        renderer: &mut P::Renderer,
        debug: &mut Debug,
    ) -> Self {
        let user_interface = build_user_interface(
            id,
            &mut program,
            user_interface::Cache::default(),
            renderer,
            bounds,
            debug,
        );

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

        State {
            program,
            cache,
            queued_events: Vec::new(),
            queued_messages: Vec::new(),
            mouse_interaction: mouse::Interaction::Idle,
        }
    }

    /// Returns a reference to the [`Program`] of the [`State`].
    pub fn program(&self) -> &P {
        &self.program
    }

    /// Queues an event in the [`State`] for processing during an [`update`].
    ///
    /// [`update`]: Self::update
    pub fn queue_event(&mut self, event: Event) {
        self.queued_events.push(event);
    }

    /// Queues a message in the [`State`] for processing during an [`update`].
    ///
    /// [`update`]: Self::update
    pub fn queue_message(&mut self, message: P::Message) {
        self.queued_messages.push(message);
    }

    /// Returns whether the event queue of the [`State`] is empty or not.
    pub fn is_queue_empty(&self) -> bool {
        self.queued_events.is_empty() && self.queued_messages.is_empty()
    }

    /// Returns the current [`mouse::Interaction`] of the [`State`].
    pub fn mouse_interaction(&self) -> mouse::Interaction {
        self.mouse_interaction
    }

    /// Processes all the queued events and messages, rebuilding and redrawing
    /// the widgets of the linked [`Program`] if necessary.
    ///
    /// Returns a list containing the instances of [`Event`] that were not
    /// captured by any widget, and the [`Command`] obtained from [`Program`]
    /// after updating it, only if an update was necessary.
    pub fn update(
        &mut self,
        id: crate::window::Id,
        bounds: Size,
        cursor: mouse::Cursor,
        renderer: &mut P::Renderer,
        theme: &P::Theme,
        style: &renderer::Style,
        clipboard: &mut dyn Clipboard,
        debug: &mut Debug,
    ) -> (Vec<Event>, Vec<Action<P::Message>>) {
        let mut user_interface = build_user_interface(
            id,
            &mut self.program,
            self.cache.take().unwrap(),
            renderer,
            bounds,
            debug,
        );

        debug.event_processing_started();
        let mut messages = Vec::new();

        let (_, event_statuses) = user_interface.update(
            &self.queued_events,
            cursor,
            renderer,
            clipboard,
            &mut messages,
        );

        let uncaptured_events = self
            .queued_events
            .iter()
            .zip(event_statuses)
            .filter_map(|(event, status)| {
                matches!(status, event::Status::Ignored).then_some(event)
            })
            .cloned()
            .collect();

        self.queued_events.clear();
        messages.append(&mut self.queued_messages);
        debug.event_processing_finished();

        let actions = if messages.is_empty() {
            debug.draw_started();
            self.mouse_interaction =
                user_interface.draw(renderer, theme, style, cursor);
            debug.draw_finished();

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

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

            let (actions, widget_actions) =
                Command::batch(messages.into_iter().map(|message| {
                    debug.log_message(&message);

                    debug.update_started();
                    let command = self.program.update(message);
                    debug.update_finished();

                    command
                }))
                .actions()
                .into_iter()
                .partition::<Vec<_>, _>(|action| {
                    !matches!(action, Action::Widget(_))
                });

            let mut user_interface = build_user_interface(
                id,
                &mut self.program,
                temp_cache,
                renderer,
                bounds,
                debug,
            );

            let had_operations = !widget_actions.is_empty();
            for operation in widget_actions
                .into_iter()
                .map(|action| match action {
                    Action::Widget(widget_action) => widget_action,
                    _ => unreachable!(),
                })
                .map(OperationWrapper::Message)
            {
                let mut current_operation = Some(operation);
                while let Some(mut operation) = current_operation.take() {
                    user_interface.operate(renderer, &mut operation);
                    match operation.finish() {
                        Outcome::Some(OperationOutputWrapper::Message(
                            message,
                        )) => self.queued_messages.push(message),
                        Outcome::Chain(op) => {
                            current_operation =
                                Some(OperationWrapper::Wrapper(op));
                        }
                        _ => {}
                    };
                }
            }

            let mut user_interface = if had_operations {
                // When there were operations, we are forced to rebuild thrice ...
                let temp_cache = user_interface.into_cache();

                build_user_interface(
                    id,
                    &mut self.program,
                    temp_cache,
                    renderer,
                    bounds,
                    debug,
                )
            } else {
                user_interface
            };

            debug.draw_started();
            self.mouse_interaction =
                user_interface.draw(renderer, theme, style, cursor);
            debug.draw_finished();

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

            actions
        };

        (uncaptured_events, actions)
    }

    /// Applies [`Operation`]s to the [`State`]
    pub fn operate(
        &mut self,
        id: crate::window::Id,
        renderer: &mut P::Renderer,
        operations: impl Iterator<
            Item = Box<dyn Operation<OperationOutputWrapper<P::Message>>>,
        >,
        bounds: Size,
        debug: &mut Debug,
    ) {
        let mut user_interface = build_user_interface(
            id,
            &mut self.program,
            self.cache.take().unwrap(),
            renderer,
            bounds,
            debug,
        );

        for operation in operations {
            let mut current_operation = Some(operation);

            while let Some(mut operation) = current_operation.take() {
                user_interface.operate(renderer, operation.as_mut());

                match operation.finish() {
                    operation::Outcome::None => {}
                    operation::Outcome::Some(
                        OperationOutputWrapper::Message(message),
                    ) => {
                        self.queued_messages.push(message);
                    }
                    operation::Outcome::Chain(next) => {
                        current_operation = Some(next);
                    }
                    _ => {}
                };
            }
        }

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

fn build_user_interface<'a, P: Program>(
    _id: crate::window::Id,
    program: &'a mut P,
    cache: user_interface::Cache,
    renderer: &mut P::Renderer,
    size: Size,
    debug: &mut Debug,
) -> UserInterface<'a, P::Message, P::Theme, P::Renderer> {
    debug.view_started();
    let view = program.view();
    debug.view_finished();

    debug.layout_started();
    let user_interface = UserInterface::build(view, size, cache, renderer);
    debug.layout_finished();

    user_interface
}