Struct EventLoopProxy

Source
pub struct EventLoopProxy { /* private fields */ }
Expand description

Control the EventLoop, possibly from a different thread, without referencing it directly.

Implementations§

Source§

impl EventLoopProxy

Source

pub fn wake_up(&self)

Wake up the EventLoop, resulting in ApplicationHandler::proxy_wake_up() being called.

Calls to this method are coalesced into a single call to proxy_wake_up, see the documentation on that for details.

If the event loop is no longer running, this is a no-op.

§Platform-specific
  • Windows: The wake-up may be ignored under high contention, see #3687.
Examples found in repository?
examples/window.rs (line 67)
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
fn main() -> Result<(), Box<dyn Error>> {
    #[cfg(web_platform)]
    console_error_panic_hook::set_once();

    tracing::init();

    let event_loop = EventLoop::new()?;
    let (sender, receiver) = mpsc::channel();

    // Wire the user event from another thread.
    #[cfg(not(web_platform))]
    {
        let event_loop_proxy = event_loop.create_proxy();
        let sender = sender.clone();
        std::thread::spawn(move || {
            // Wake up the `event_loop` once every second and dispatch a custom event
            // from a different thread.
            info!("Starting to send user event every second");
            loop {
                let _ = sender.send(Action::Message);
                event_loop_proxy.wake_up();
                std::thread::sleep(std::time::Duration::from_secs(1));
            }
        });
    }

    let app = Application::new(&event_loop, receiver, sender);
    Ok(event_loop.run_app(app)?)
}

/// Application state and event handling.
struct Application {
    /// Trigger actions through proxy wake up.
    receiver: Receiver<Action>,
    sender: Sender<Action>,
    /// Custom cursors assets.
    custom_cursors: Result<Vec<CustomCursor>, RequestError>,
    /// Application icon.
    icon: Icon,
    windows: HashMap<WindowId, WindowState>,
    /// Drawing context.
    ///
    /// With OpenGL it could be EGLDisplay.
    #[cfg(not(android_platform))]
    context: Option<Context<DisplayHandle<'static>>>,
}

impl Application {
    fn new(event_loop: &EventLoop, receiver: Receiver<Action>, sender: Sender<Action>) -> Self {
        // SAFETY: we drop the context right before the event loop is stopped, thus making it safe.
        #[cfg(not(android_platform))]
        let context = Some(
            Context::new(unsafe {
                std::mem::transmute::<DisplayHandle<'_>, DisplayHandle<'static>>(
                    event_loop.display_handle().unwrap(),
                )
            })
            .unwrap(),
        );

        // You'll have to choose an icon size at your own discretion. On X11, the desired size
        // varies by WM, and on Windows, you still have to account for screen scaling. Here
        // we use 32px, since it seems to work well enough in most cases. Be careful about
        // going too high, or you'll be bitten by the low-quality downscaling built into the
        // WM.
        let icon = load_icon(include_bytes!("data/icon.png"));

        info!("Loading cursor assets");
        let custom_cursors = [
            event_loop.create_custom_cursor(decode_cursor(include_bytes!("data/cross.png"))),
            event_loop.create_custom_cursor(decode_cursor(include_bytes!("data/cross2.png"))),
            event_loop.create_custom_cursor(decode_cursor(include_bytes!("data/gradient.png"))),
        ]
        .into_iter()
        .collect();

        Self {
            receiver,
            sender,
            #[cfg(not(android_platform))]
            context,
            custom_cursors,
            icon,
            windows: Default::default(),
        }
    }

    fn create_window(
        &mut self,
        event_loop: &dyn ActiveEventLoop,
        _tab_id: Option<String>,
    ) -> Result<WindowId, Box<dyn Error>> {
        // TODO read-out activation token.

        #[allow(unused_mut)]
        let mut window_attributes = WindowAttributes::default()
            .with_title("Winit window")
            .with_transparent(true)
            .with_window_icon(Some(self.icon.clone()));

        #[cfg(any(x11_platform, wayland_platform))]
        if let Some(token) = event_loop.read_token_from_env() {
            startup_notify::reset_activation_token_env();
            info!("Using token {:?} to activate a window", token);
            window_attributes = window_attributes.with_activation_token(token);
        }

        #[cfg(x11_platform)]
        match std::env::var("X11_VISUAL_ID") {
            Ok(visual_id_str) => {
                info!("Using X11 visual id {visual_id_str}");
                let visual_id = visual_id_str.parse()?;
                window_attributes = window_attributes.with_x11_visual(visual_id);
            },
            Err(_) => info!("Set the X11_VISUAL_ID env variable to request specific X11 visual"),
        }

        #[cfg(x11_platform)]
        match std::env::var("X11_SCREEN_ID") {
            Ok(screen_id_str) => {
                info!("Placing the window on X11 screen {screen_id_str}");
                let screen_id = screen_id_str.parse()?;
                window_attributes = window_attributes.with_x11_screen(screen_id);
            },
            Err(_) => info!(
                "Set the X11_SCREEN_ID env variable to place the window on non-default screen"
            ),
        }

        #[cfg(macos_platform)]
        if let Some(tab_id) = _tab_id {
            window_attributes = window_attributes.with_tabbing_identifier(&tab_id);
        }

        #[cfg(web_platform)]
        {
            window_attributes = window_attributes.with_append(true);
        }

        let window = event_loop.create_window(window_attributes)?;

        #[cfg(ios_platform)]
        {
            use winit::platform::ios::WindowExtIOS;
            window.recognize_doubletap_gesture(true);
            window.recognize_pinch_gesture(true);
            window.recognize_rotation_gesture(true);
            window.recognize_pan_gesture(true, 2, 2);
        }

        let window_state = WindowState::new(self, window)?;
        let window_id = window_state.window.id();
        info!("Created new window with id={window_id:?}");
        self.windows.insert(window_id, window_state);
        Ok(window_id)
    }

    fn handle_action_from_proxy(&mut self, _event_loop: &dyn ActiveEventLoop, action: Action) {
        match action {
            #[cfg(web_platform)]
            Action::DumpMonitors => self.dump_monitors(_event_loop),
            Action::Message => {
                info!("User wake up");
            },
            _ => unreachable!("Tried to execute invalid action without `WindowId`"),
        }
    }

    fn handle_action_with_window(
        &mut self,
        event_loop: &dyn ActiveEventLoop,
        window_id: WindowId,
        action: Action,
    ) {
        // let cursor_position = self.cursor_position;
        let window = self.windows.get_mut(&window_id).unwrap();
        info!("Executing action: {action:?}");
        match action {
            Action::CloseWindow => {
                let _ = self.windows.remove(&window_id);
            },
            Action::CreateNewWindow => {
                #[cfg(any(x11_platform, wayland_platform))]
                if let Err(err) = window.window.request_activation_token() {
                    info!("Failed to get activation token: {err}");
                } else {
                    return;
                }

                if let Err(err) = self.create_window(event_loop, None) {
                    error!("Error creating new window: {err}");
                }
            },
            Action::ToggleResizeIncrements => window.toggle_resize_increments(),
            Action::ToggleCursorVisibility => window.toggle_cursor_visibility(),
            Action::ToggleResizable => window.toggle_resizable(),
            Action::ToggleDecorations => window.toggle_decorations(),
            Action::ToggleFullscreen => window.toggle_fullscreen(),
            #[cfg(macos_platform)]
            Action::ToggleSimpleFullscreen => {
                window.window.set_simple_fullscreen(!window.window.simple_fullscreen());
            },
            Action::ToggleMaximize => window.toggle_maximize(),
            Action::ToggleImeInput => window.toggle_ime(),
            Action::Minimize => window.minimize(),
            Action::NextCursor => window.next_cursor(),
            Action::NextCustomCursor => {
                if let Err(err) = self.custom_cursors.as_ref().map(|c| window.next_custom_cursor(c))
                {
                    error!("Error creating custom cursor: {err}");
                }
            },
            #[cfg(web_platform)]
            Action::UrlCustomCursor => {
                if let Err(err) = window.url_custom_cursor(event_loop) {
                    error!("Error creating custom cursor from URL: {err}");
                }
            },
            #[cfg(web_platform)]
            Action::AnimationCustomCursor => {
                if let Err(err) = self
                    .custom_cursors
                    .as_ref()
                    .map(|c| window.animation_custom_cursor(event_loop, c))
                {
                    error!("Error creating animated custom cursor: {err}");
                }
            },
            Action::CycleCursorGrab => window.cycle_cursor_grab(),
            Action::DragWindow => window.drag_window(),
            Action::DragResizeWindow => window.drag_resize_window(),
            Action::ShowWindowMenu => window.show_menu(),
            Action::PrintHelp => self.print_help(),
            #[cfg(macos_platform)]
            Action::CycleOptionAsAlt => window.cycle_option_as_alt(),
            Action::SetTheme(theme) => {
                window.window.set_theme(theme);
                // Get the resulting current theme to draw with
                let actual_theme = theme.or_else(|| window.window.theme()).unwrap_or(Theme::Dark);
                window.set_draw_theme(actual_theme);
            },
            #[cfg(macos_platform)]
            Action::CreateNewTab => {
                let tab_id = window.window.tabbing_identifier();
                if let Err(err) = self.create_window(event_loop, Some(tab_id)) {
                    error!("Error creating new window: {err}");
                }
            },
            Action::RequestResize => window.swap_dimensions(),
            #[cfg(web_platform)]
            Action::DumpMonitors => {
                let future = event_loop.request_detailed_monitor_permission();
                let proxy = event_loop.create_proxy();
                let sender = self.sender.clone();
                wasm_bindgen_futures::spawn_local(async move {
                    if let Err(error) = future.await {
                        error!("{error}")
                    }

                    let _ = sender.send(Action::DumpMonitors);
                    proxy.wake_up();
                });
            },
            #[cfg(not(web_platform))]
            Action::DumpMonitors => self.dump_monitors(event_loop),
            Action::Message => {
                self.sender.send(Action::Message).unwrap();
                event_loop.create_proxy().wake_up();
            },
        }
    }

Trait Implementations§

Source§

impl Clone for EventLoopProxy

Source§

fn clone(&self) -> EventLoopProxy

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for EventLoopProxy

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more