Struct winit::window::Window

source ·
pub struct Window { /* private fields */ }
Expand description

Represents a window.

The window is closed when dropped.

§Threading

This is Send + Sync, meaning that it can be freely used from other threads.

However, some platforms (macOS, Web and iOS) only allow user interface interactions on the main thread, so on those platforms, if you use the window from a thread other than the main, the code is scheduled to run on the main thread, and your thread may be blocked until that completes.

§Platform-specific

Web: The Window, which is represented by a HTMLElementCanvas, can not be closed by dropping the Window.

Implementations§

source§

impl Window

Base Window functions.

source

pub fn default_attributes() -> WindowAttributes

Create a new WindowAttributes which allows modifying the window’s attributes before creation.

Examples found in repository?
examples/pump_events.rs (line 26)
25
26
27
28
        fn resumed(&mut self, event_loop: &ActiveEventLoop) {
            let window_attributes = Window::default_attributes().with_title("A fantastic window!");
            self.window = Some(event_loop.create_window(window_attributes).unwrap());
        }
More examples
Hide additional examples
examples/control_flow.rs (line 71)
70
71
72
73
74
75
    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
        let window_attributes = Window::default_attributes().with_title(
            "Press 1, 2, 3 to change control flow mode. Press R to toggle redraw requests.",
        );
        self.window = Some(event_loop.create_window(window_attributes).unwrap());
    }
examples/run_on_demand.rs (line 32)
31
32
33
34
35
36
37
38
        fn resumed(&mut self, event_loop: &ActiveEventLoop) {
            let window_attributes = Window::default_attributes()
                .with_title("Fantastic window number one!")
                .with_inner_size(winit::dpi::LogicalSize::new(128.0, 128.0));
            let window = event_loop.create_window(window_attributes).unwrap();
            self.window_id = Some(window.id());
            self.window = Some(window);
        }
examples/child_window.rs (line 17)
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
fn main() -> Result<(), impl std::error::Error> {
    use std::collections::HashMap;

    use winit::dpi::{LogicalPosition, LogicalSize, Position};
    use winit::event::{ElementState, Event, KeyEvent, WindowEvent};
    use winit::event_loop::{ActiveEventLoop, EventLoop};
    use winit::raw_window_handle::HasRawWindowHandle;
    use winit::window::Window;

    #[path = "util/fill.rs"]
    mod fill;

    fn spawn_child_window(parent: &Window, event_loop: &ActiveEventLoop) -> Window {
        let parent = parent.raw_window_handle().unwrap();
        let mut window_attributes = Window::default_attributes()
            .with_title("child window")
            .with_inner_size(LogicalSize::new(200.0f32, 200.0f32))
            .with_position(Position::Logical(LogicalPosition::new(0.0, 0.0)))
            .with_visible(true);
        // `with_parent_window` is unsafe. Parent window must be a valid window.
        window_attributes = unsafe { window_attributes.with_parent_window(Some(parent)) };

        event_loop.create_window(window_attributes).unwrap()
    }

    let mut windows = HashMap::new();

    let event_loop: EventLoop<()> = EventLoop::new().unwrap();
    let mut parent_window_id = None;

    event_loop.run(move |event: Event<()>, event_loop| {
        match event {
            Event::Resumed => {
                let attributes = Window::default_attributes()
                    .with_title("parent window")
                    .with_position(Position::Logical(LogicalPosition::new(0.0, 0.0)))
                    .with_inner_size(LogicalSize::new(640.0f32, 480.0f32));
                let window = event_loop.create_window(attributes).unwrap();

                parent_window_id = Some(window.id());

                println!("Parent window id: {parent_window_id:?})");
                windows.insert(window.id(), window);
            },
            Event::WindowEvent { window_id, event } => match event {
                WindowEvent::CloseRequested => {
                    windows.clear();
                    event_loop.exit();
                },
                WindowEvent::CursorEntered { device_id: _ } => {
                    // On x11, println when the cursor entered in a window even if the child window
                    // is created by some key inputs.
                    // the child windows are always placed at (0, 0) with size (200, 200) in the
                    // parent window, so we also can see this log when we move
                    // the cursor around (200, 200) in parent window.
                    println!("cursor entered in the window {window_id:?}");
                },
                WindowEvent::KeyboardInput {
                    event: KeyEvent { state: ElementState::Pressed, .. },
                    ..
                } => {
                    let parent_window = windows.get(&parent_window_id.unwrap()).unwrap();
                    let child_window = spawn_child_window(parent_window, event_loop);
                    let child_id = child_window.id();
                    println!("Child window created with id: {child_id:?}");
                    windows.insert(child_id, child_window);
                },
                WindowEvent::RedrawRequested => {
                    if let Some(window) = windows.get(&window_id) {
                        fill::fill_window(window);
                    }
                },
                _ => (),
            },
            _ => (),
        }
    })
}
examples/window.rs (line 131)
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
    fn create_window(
        &mut self,
        event_loop: &ActiveEventLoop,
        _tab_id: Option<String>,
    ) -> Result<WindowId, Box<dyn Error>> {
        // TODO read-out activation token.

        #[allow(unused_mut)]
        let mut window_attributes = Window::default_attributes()
            .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(macos_platform)]
        if let Some(tab_id) = _tab_id {
            window_attributes = window_attributes.with_tabbing_identifier(&tab_id);
        }

        #[cfg(web_platform)]
        {
            use winit::platform::web::WindowAttributesExtWebSys;
            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)
    }
source

pub fn id(&self) -> WindowId

Returns an identifier unique to the window.

Examples found in repository?
examples/run_on_demand.rs (line 36)
31
32
33
34
35
36
37
38
        fn resumed(&mut self, event_loop: &ActiveEventLoop) {
            let window_attributes = Window::default_attributes()
                .with_title("Fantastic window number one!")
                .with_inner_size(winit::dpi::LogicalSize::new(128.0, 128.0));
            let window = event_loop.create_window(window_attributes).unwrap();
            self.window_id = Some(window.id());
            self.window = Some(window);
        }
More examples
Hide additional examples
examples/util/fill.rs (line 58)
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
        fn create_surface(
            &mut self,
            window: &Window,
        ) -> &mut Surface<&'static Window, &'static Window> {
            self.surfaces.entry(window.id()).or_insert_with(|| {
                Surface::new(&self.context.borrow(), unsafe {
                    mem::transmute::<&'_ Window, &'static Window>(window)
                })
                .expect("Failed to create a softbuffer surface")
            })
        }

        fn destroy_surface(&mut self, window: &Window) {
            self.surfaces.remove(&window.id());
        }
examples/window.rs (line 166)
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
    fn create_window(
        &mut self,
        event_loop: &ActiveEventLoop,
        _tab_id: Option<String>,
    ) -> Result<WindowId, Box<dyn Error>> {
        // TODO read-out activation token.

        #[allow(unused_mut)]
        let mut window_attributes = Window::default_attributes()
            .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(macos_platform)]
        if let Some(tab_id) = _tab_id {
            window_attributes = window_attributes.with_tabbing_identifier(&tab_id);
        }

        #[cfg(web_platform)]
        {
            use winit::platform::web::WindowAttributesExtWebSys;
            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(&mut self, event_loop: &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(),
            Action::ToggleMaximize => window.toggle_maximize(),
            Action::ToggleImeInput => window.toggle_ime(),
            Action::Minimize => window.minimize(),
            Action::NextCursor => window.next_cursor(),
            Action::NextCustomCursor => window.next_custom_cursor(&self.custom_cursors),
            #[cfg(web_platform)]
            Action::UrlCustomCursor => window.url_custom_cursor(event_loop),
            #[cfg(web_platform)]
            Action::AnimationCustomCursor => {
                window.animation_custom_cursor(event_loop, &self.custom_cursors)
            },
            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(),
            #[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(),
        }
    }

    fn dump_monitors(&self, event_loop: &ActiveEventLoop) {
        info!("Monitors information");
        let primary_monitor = event_loop.primary_monitor();
        for monitor in event_loop.available_monitors() {
            let intro = if primary_monitor.as_ref() == Some(&monitor) {
                "Primary monitor"
            } else {
                "Monitor"
            };

            if let Some(name) = monitor.name() {
                info!("{intro}: {name}");
            } else {
                info!("{intro}: [no name]");
            }

            let PhysicalSize { width, height } = monitor.size();
            info!(
                "  Current mode: {width}x{height}{}",
                if let Some(m_hz) = monitor.refresh_rate_millihertz() {
                    format!(" @ {}.{} Hz", m_hz / 1000, m_hz % 1000)
                } else {
                    String::new()
                }
            );

            let PhysicalPosition { x, y } = monitor.position();
            info!("  Position: {x},{y}");

            info!("  Scale factor: {}", monitor.scale_factor());

            info!("  Available modes (width x height x bit-depth):");
            for mode in monitor.video_modes() {
                let PhysicalSize { width, height } = mode.size();
                let bits = mode.bit_depth();
                let m_hz = mode.refresh_rate_millihertz();
                info!("    {width}x{height}x{bits} @ {}.{} Hz", m_hz / 1000, m_hz % 1000);
            }
        }
    }

    /// Process the key binding.
    fn process_key_binding(key: &str, mods: &ModifiersState) -> Option<Action> {
        KEY_BINDINGS
            .iter()
            .find_map(|binding| binding.is_triggered_by(&key, mods).then_some(binding.action))
    }

    /// Process mouse binding.
    fn process_mouse_binding(button: MouseButton, mods: &ModifiersState) -> Option<Action> {
        MOUSE_BINDINGS
            .iter()
            .find_map(|binding| binding.is_triggered_by(&button, mods).then_some(binding.action))
    }

    fn print_help(&self) {
        info!("Keyboard bindings:");
        for binding in KEY_BINDINGS {
            info!(
                "{}{:<10} - {} ({})",
                modifiers_to_string(binding.mods),
                binding.trigger,
                binding.action,
                binding.action.help(),
            );
        }
        info!("Mouse bindings:");
        for binding in MOUSE_BINDINGS {
            info!(
                "{}{:<10} - {} ({})",
                modifiers_to_string(binding.mods),
                mouse_button_to_string(binding.trigger),
                binding.action,
                binding.action.help(),
            );
        }
    }
}

impl ApplicationHandler<UserEvent> for Application {
    fn user_event(&mut self, _event_loop: &ActiveEventLoop, event: UserEvent) {
        info!("User event: {event:?}");
    }

    fn window_event(
        &mut self,
        event_loop: &ActiveEventLoop,
        window_id: WindowId,
        event: WindowEvent,
    ) {
        let window = match self.windows.get_mut(&window_id) {
            Some(window) => window,
            None => return,
        };

        match event {
            WindowEvent::Resized(size) => {
                window.resize(size);
            },
            WindowEvent::Focused(focused) => {
                if focused {
                    info!("Window={window_id:?} focused");
                } else {
                    info!("Window={window_id:?} unfocused");
                }
            },
            WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
                info!("Window={window_id:?} changed scale to {scale_factor}");
            },
            WindowEvent::ThemeChanged(theme) => {
                info!("Theme changed to {theme:?}");
                window.set_theme(theme);
            },
            WindowEvent::RedrawRequested => {
                if let Err(err) = window.draw() {
                    error!("Error drawing window: {err}");
                }
            },
            WindowEvent::Occluded(occluded) => {
                window.set_occluded(occluded);
            },
            WindowEvent::CloseRequested => {
                info!("Closing Window={window_id:?}");
                self.windows.remove(&window_id);
            },
            WindowEvent::ModifiersChanged(modifiers) => {
                window.modifiers = modifiers.state();
                info!("Modifiers changed to {:?}", window.modifiers);
            },
            WindowEvent::MouseWheel { delta, .. } => match delta {
                MouseScrollDelta::LineDelta(x, y) => {
                    info!("Mouse wheel Line Delta: ({x},{y})");
                },
                MouseScrollDelta::PixelDelta(px) => {
                    info!("Mouse wheel Pixel Delta: ({},{})", px.x, px.y);
                },
            },
            WindowEvent::KeyboardInput { event, is_synthetic: false, .. } => {
                let mods = window.modifiers;

                // Dispatch actions only on press.
                if event.state.is_pressed() {
                    let action = if let Key::Character(ch) = event.logical_key.as_ref() {
                        Self::process_key_binding(&ch.to_uppercase(), &mods)
                    } else {
                        None
                    };

                    if let Some(action) = action {
                        self.handle_action(event_loop, window_id, action);
                    }
                }
            },
            WindowEvent::MouseInput { button, state, .. } => {
                let mods = window.modifiers;
                if let Some(action) =
                    state.is_pressed().then(|| Self::process_mouse_binding(button, &mods)).flatten()
                {
                    self.handle_action(event_loop, window_id, action);
                }
            },
            WindowEvent::CursorLeft { .. } => {
                info!("Cursor left Window={window_id:?}");
                window.cursor_left();
            },
            WindowEvent::CursorMoved { position, .. } => {
                info!("Moved cursor to {position:?}");
                window.cursor_moved(position);
            },
            WindowEvent::ActivationTokenDone { token: _token, .. } => {
                #[cfg(any(x11_platform, wayland_platform))]
                {
                    startup_notify::set_activation_token_env(_token);
                    if let Err(err) = self.create_window(event_loop, None) {
                        error!("Error creating new window: {err}");
                    }
                }
            },
            WindowEvent::Ime(event) => match event {
                Ime::Enabled => info!("IME enabled for Window={window_id:?}"),
                Ime::Preedit(text, caret_pos) => {
                    info!("Preedit: {}, with caret at {:?}", text, caret_pos);
                },
                Ime::Commit(text) => {
                    info!("Committed: {}", text);
                },
                Ime::Disabled => info!("IME disabled for Window={window_id:?}"),
            },
            WindowEvent::PinchGesture { delta, .. } => {
                window.zoom += delta;
                let zoom = window.zoom;
                if delta > 0.0 {
                    info!("Zoomed in {delta:.5} (now: {zoom:.5})");
                } else {
                    info!("Zoomed out {delta:.5} (now: {zoom:.5})");
                }
            },
            WindowEvent::RotationGesture { delta, .. } => {
                window.rotated += delta;
                let rotated = window.rotated;
                if delta > 0.0 {
                    info!("Rotated counterclockwise {delta:.5} (now: {rotated:.5})");
                } else {
                    info!("Rotated clockwise {delta:.5} (now: {rotated:.5})");
                }
            },
            WindowEvent::PanGesture { delta, phase, .. } => {
                window.panned.x += delta.x;
                window.panned.y += delta.y;
                info!("Panned ({delta:?})) (now: {:?}), {phase:?}", window.panned);
            },
            WindowEvent::DoubleTapGesture { .. } => {
                info!("Smart zoom");
            },
            WindowEvent::TouchpadPressure { .. }
            | WindowEvent::HoveredFileCancelled
            | WindowEvent::KeyboardInput { .. }
            | WindowEvent::CursorEntered { .. }
            | WindowEvent::AxisMotion { .. }
            | WindowEvent::DroppedFile(_)
            | WindowEvent::HoveredFile(_)
            | WindowEvent::Destroyed
            | WindowEvent::Touch(_)
            | WindowEvent::Moved(_) => (),
        }
    }

    fn device_event(
        &mut self,
        _event_loop: &ActiveEventLoop,
        device_id: DeviceId,
        event: DeviceEvent,
    ) {
        info!("Device {device_id:?} event: {event:?}");
    }

    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
        info!("Resumed the event loop");
        self.dump_monitors(event_loop);

        // Create initial window.
        self.create_window(event_loop, None).expect("failed to create initial window");

        self.print_help();
    }

    fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
        if self.windows.is_empty() {
            info!("No windows left, exiting...");
            event_loop.exit();
        }
    }

    #[cfg(not(any(android_platform, ios_platform)))]
    fn exiting(&mut self, _event_loop: &ActiveEventLoop) {
        // We must drop the context here.
        self.context = None;
    }
}

/// State of the window.
struct WindowState {
    /// IME input.
    ime: bool,
    /// Render surface.
    ///
    /// NOTE: This surface must be dropped before the `Window`.
    #[cfg(not(any(android_platform, ios_platform)))]
    surface: Surface<DisplayHandle<'static>, Arc<Window>>,
    /// The actual winit Window.
    window: Arc<Window>,
    /// The window theme we're drawing with.
    theme: Theme,
    /// Cursor position over the window.
    cursor_position: Option<PhysicalPosition<f64>>,
    /// Window modifiers state.
    modifiers: ModifiersState,
    /// Occlusion state of the window.
    occluded: bool,
    /// Current cursor grab mode.
    cursor_grab: CursorGrabMode,
    /// The amount of zoom into window.
    zoom: f64,
    /// The amount of rotation of the window.
    rotated: f32,
    /// The amount of pan of the window.
    panned: PhysicalPosition<f32>,

    #[cfg(macos_platform)]
    option_as_alt: OptionAsAlt,

    // Cursor states.
    named_idx: usize,
    custom_idx: usize,
    cursor_hidden: bool,
}

impl WindowState {
    fn new(app: &Application, window: Window) -> Result<Self, Box<dyn Error>> {
        let window = Arc::new(window);

        // SAFETY: the surface is dropped before the `window` which provided it with handle, thus
        // it doesn't outlive it.
        #[cfg(not(any(android_platform, ios_platform)))]
        let surface = Surface::new(app.context.as_ref().unwrap(), Arc::clone(&window))?;

        let theme = window.theme().unwrap_or(Theme::Dark);
        info!("Theme: {theme:?}");
        let named_idx = 0;
        window.set_cursor(CURSORS[named_idx]);

        // Allow IME out of the box.
        let ime = true;
        window.set_ime_allowed(ime);

        let size = window.inner_size();
        let mut state = Self {
            #[cfg(macos_platform)]
            option_as_alt: window.option_as_alt(),
            custom_idx: app.custom_cursors.len() - 1,
            cursor_grab: CursorGrabMode::None,
            named_idx,
            #[cfg(not(any(android_platform, ios_platform)))]
            surface,
            window,
            theme,
            ime,
            cursor_position: Default::default(),
            cursor_hidden: Default::default(),
            modifiers: Default::default(),
            occluded: Default::default(),
            rotated: Default::default(),
            panned: Default::default(),
            zoom: Default::default(),
        };

        state.resize(size);
        Ok(state)
    }

    pub fn toggle_ime(&mut self) {
        self.ime = !self.ime;
        self.window.set_ime_allowed(self.ime);
        if let Some(position) = self.ime.then_some(self.cursor_position).flatten() {
            self.window.set_ime_cursor_area(position, PhysicalSize::new(20, 20));
        }
    }

    pub fn minimize(&mut self) {
        self.window.set_minimized(true);
    }

    pub fn cursor_moved(&mut self, position: PhysicalPosition<f64>) {
        self.cursor_position = Some(position);
        if self.ime {
            self.window.set_ime_cursor_area(position, PhysicalSize::new(20, 20));
        }
    }

    pub fn cursor_left(&mut self) {
        self.cursor_position = None;
    }

    /// Toggle maximized.
    fn toggle_maximize(&self) {
        let maximized = self.window.is_maximized();
        self.window.set_maximized(!maximized);
    }

    /// Toggle window decorations.
    fn toggle_decorations(&self) {
        let decorated = self.window.is_decorated();
        self.window.set_decorations(!decorated);
    }

    /// Toggle window resizable state.
    fn toggle_resizable(&self) {
        let resizable = self.window.is_resizable();
        self.window.set_resizable(!resizable);
    }

    /// Toggle cursor visibility
    fn toggle_cursor_visibility(&mut self) {
        self.cursor_hidden = !self.cursor_hidden;
        self.window.set_cursor_visible(!self.cursor_hidden);
    }

    /// Toggle resize increments on a window.
    fn toggle_resize_increments(&mut self) {
        let new_increments = match self.window.resize_increments() {
            Some(_) => None,
            None => Some(LogicalSize::new(25.0, 25.0)),
        };
        info!("Had increments: {}", new_increments.is_none());
        self.window.set_resize_increments(new_increments);
    }

    /// Toggle fullscreen.
    fn toggle_fullscreen(&self) {
        let fullscreen = if self.window.fullscreen().is_some() {
            None
        } else {
            Some(Fullscreen::Borderless(None))
        };

        self.window.set_fullscreen(fullscreen);
    }

    /// Cycle through the grab modes ignoring errors.
    fn cycle_cursor_grab(&mut self) {
        self.cursor_grab = match self.cursor_grab {
            CursorGrabMode::None => CursorGrabMode::Confined,
            CursorGrabMode::Confined => CursorGrabMode::Locked,
            CursorGrabMode::Locked => CursorGrabMode::None,
        };
        info!("Changing cursor grab mode to {:?}", self.cursor_grab);
        if let Err(err) = self.window.set_cursor_grab(self.cursor_grab) {
            error!("Error setting cursor grab: {err}");
        }
    }

    #[cfg(macos_platform)]
    fn cycle_option_as_alt(&mut self) {
        self.option_as_alt = match self.option_as_alt {
            OptionAsAlt::None => OptionAsAlt::OnlyLeft,
            OptionAsAlt::OnlyLeft => OptionAsAlt::OnlyRight,
            OptionAsAlt::OnlyRight => OptionAsAlt::Both,
            OptionAsAlt::Both => OptionAsAlt::None,
        };
        info!("Setting option as alt {:?}", self.option_as_alt);
        self.window.set_option_as_alt(self.option_as_alt);
    }

    /// Swap the window dimensions with `request_inner_size`.
    fn swap_dimensions(&mut self) {
        let old_inner_size = self.window.inner_size();
        let mut inner_size = old_inner_size;

        mem::swap(&mut inner_size.width, &mut inner_size.height);
        info!("Requesting resize from {old_inner_size:?} to {inner_size:?}");

        if let Some(new_inner_size) = self.window.request_inner_size(inner_size) {
            if old_inner_size == new_inner_size {
                info!("Inner size change got ignored");
            } else {
                self.resize(new_inner_size);
            }
        } else {
            info!("Request inner size is asynchronous");
        }
    }

    /// Pick the next cursor.
    fn next_cursor(&mut self) {
        self.named_idx = (self.named_idx + 1) % CURSORS.len();
        info!("Setting cursor to \"{:?}\"", CURSORS[self.named_idx]);
        self.window.set_cursor(Cursor::Icon(CURSORS[self.named_idx]));
    }

    /// Pick the next custom cursor.
    fn next_custom_cursor(&mut self, custom_cursors: &[CustomCursor]) {
        self.custom_idx = (self.custom_idx + 1) % custom_cursors.len();
        let cursor = Cursor::Custom(custom_cursors[self.custom_idx].clone());
        self.window.set_cursor(cursor);
    }

    /// Custom cursor from an URL.
    #[cfg(web_platform)]
    fn url_custom_cursor(&mut self, event_loop: &ActiveEventLoop) {
        let cursor = event_loop.create_custom_cursor(url_custom_cursor());

        self.window.set_cursor(cursor);
    }

    /// Custom cursor from a URL.
    #[cfg(web_platform)]
    fn animation_custom_cursor(
        &mut self,
        event_loop: &ActiveEventLoop,
        custom_cursors: &[CustomCursor],
    ) {
        use std::time::Duration;
        use winit::platform::web::CustomCursorExtWebSys;

        let cursors = vec![
            custom_cursors[0].clone(),
            custom_cursors[1].clone(),
            event_loop.create_custom_cursor(url_custom_cursor()),
        ];
        let cursor = CustomCursor::from_animation(Duration::from_secs(3), cursors).unwrap();
        let cursor = event_loop.create_custom_cursor(cursor);

        self.window.set_cursor(cursor);
    }

    /// Resize the window to the new size.
    fn resize(&mut self, size: PhysicalSize<u32>) {
        info!("Resized to {size:?}");
        #[cfg(not(any(android_platform, ios_platform)))]
        {
            let (width, height) = match (NonZeroU32::new(size.width), NonZeroU32::new(size.height))
            {
                (Some(width), Some(height)) => (width, height),
                _ => return,
            };
            self.surface.resize(width, height).expect("failed to resize inner buffer");
        }
        self.window.request_redraw();
    }

    /// Change the theme.
    fn set_theme(&mut self, theme: Theme) {
        self.theme = theme;
        self.window.request_redraw();
    }

    /// Show window menu.
    fn show_menu(&self) {
        if let Some(position) = self.cursor_position {
            self.window.show_window_menu(position);
        }
    }

    /// Drag the window.
    fn drag_window(&self) {
        if let Err(err) = self.window.drag_window() {
            info!("Error starting window drag: {err}");
        } else {
            info!("Dragging window Window={:?}", self.window.id());
        }
    }

    /// Drag-resize the window.
    fn drag_resize_window(&self) {
        let position = match self.cursor_position {
            Some(position) => position,
            None => {
                info!("Drag-resize requires cursor to be inside the window");
                return;
            },
        };

        let win_size = self.window.inner_size();
        let border_size = BORDER_SIZE * self.window.scale_factor();

        let x_direction = if position.x < border_size {
            ResizeDirection::West
        } else if position.x > (win_size.width as f64 - border_size) {
            ResizeDirection::East
        } else {
            // Use arbitrary direction instead of None for simplicity.
            ResizeDirection::SouthEast
        };

        let y_direction = if position.y < border_size {
            ResizeDirection::North
        } else if position.y > (win_size.height as f64 - border_size) {
            ResizeDirection::South
        } else {
            // Use arbitrary direction instead of None for simplicity.
            ResizeDirection::SouthEast
        };

        let direction = match (x_direction, y_direction) {
            (ResizeDirection::West, ResizeDirection::North) => ResizeDirection::NorthWest,
            (ResizeDirection::West, ResizeDirection::South) => ResizeDirection::SouthWest,
            (ResizeDirection::West, _) => ResizeDirection::West,
            (ResizeDirection::East, ResizeDirection::North) => ResizeDirection::NorthEast,
            (ResizeDirection::East, ResizeDirection::South) => ResizeDirection::SouthEast,
            (ResizeDirection::East, _) => ResizeDirection::East,
            (_, ResizeDirection::South) => ResizeDirection::South,
            (_, ResizeDirection::North) => ResizeDirection::North,
            _ => return,
        };

        if let Err(err) = self.window.drag_resize_window(direction) {
            info!("Error starting window drag-resize: {err}");
        } else {
            info!("Drag-resizing window Window={:?}", self.window.id());
        }
    }

    /// Change window occlusion state.
    fn set_occluded(&mut self, occluded: bool) {
        self.occluded = occluded;
        if !occluded {
            self.window.request_redraw();
        }
    }

    /// Draw the window contents.
    #[cfg(not(any(android_platform, ios_platform)))]
    fn draw(&mut self) -> Result<(), Box<dyn Error>> {
        if self.occluded {
            info!("Skipping drawing occluded window={:?}", self.window.id());
            return Ok(());
        }

        const WHITE: u32 = 0xffffffff;
        const DARK_GRAY: u32 = 0xff181818;

        let color = match self.theme {
            Theme::Light => WHITE,
            Theme::Dark => DARK_GRAY,
        };

        let mut buffer = self.surface.buffer_mut()?;
        buffer.fill(color);
        self.window.pre_present_notify();
        buffer.present()?;
        Ok(())
    }
examples/child_window.rs (line 42)
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
fn main() -> Result<(), impl std::error::Error> {
    use std::collections::HashMap;

    use winit::dpi::{LogicalPosition, LogicalSize, Position};
    use winit::event::{ElementState, Event, KeyEvent, WindowEvent};
    use winit::event_loop::{ActiveEventLoop, EventLoop};
    use winit::raw_window_handle::HasRawWindowHandle;
    use winit::window::Window;

    #[path = "util/fill.rs"]
    mod fill;

    fn spawn_child_window(parent: &Window, event_loop: &ActiveEventLoop) -> Window {
        let parent = parent.raw_window_handle().unwrap();
        let mut window_attributes = Window::default_attributes()
            .with_title("child window")
            .with_inner_size(LogicalSize::new(200.0f32, 200.0f32))
            .with_position(Position::Logical(LogicalPosition::new(0.0, 0.0)))
            .with_visible(true);
        // `with_parent_window` is unsafe. Parent window must be a valid window.
        window_attributes = unsafe { window_attributes.with_parent_window(Some(parent)) };

        event_loop.create_window(window_attributes).unwrap()
    }

    let mut windows = HashMap::new();

    let event_loop: EventLoop<()> = EventLoop::new().unwrap();
    let mut parent_window_id = None;

    event_loop.run(move |event: Event<()>, event_loop| {
        match event {
            Event::Resumed => {
                let attributes = Window::default_attributes()
                    .with_title("parent window")
                    .with_position(Position::Logical(LogicalPosition::new(0.0, 0.0)))
                    .with_inner_size(LogicalSize::new(640.0f32, 480.0f32));
                let window = event_loop.create_window(attributes).unwrap();

                parent_window_id = Some(window.id());

                println!("Parent window id: {parent_window_id:?})");
                windows.insert(window.id(), window);
            },
            Event::WindowEvent { window_id, event } => match event {
                WindowEvent::CloseRequested => {
                    windows.clear();
                    event_loop.exit();
                },
                WindowEvent::CursorEntered { device_id: _ } => {
                    // On x11, println when the cursor entered in a window even if the child window
                    // is created by some key inputs.
                    // the child windows are always placed at (0, 0) with size (200, 200) in the
                    // parent window, so we also can see this log when we move
                    // the cursor around (200, 200) in parent window.
                    println!("cursor entered in the window {window_id:?}");
                },
                WindowEvent::KeyboardInput {
                    event: KeyEvent { state: ElementState::Pressed, .. },
                    ..
                } => {
                    let parent_window = windows.get(&parent_window_id.unwrap()).unwrap();
                    let child_window = spawn_child_window(parent_window, event_loop);
                    let child_id = child_window.id();
                    println!("Child window created with id: {child_id:?}");
                    windows.insert(child_id, child_window);
                },
                WindowEvent::RedrawRequested => {
                    if let Some(window) = windows.get(&window_id) {
                        fill::fill_window(window);
                    }
                },
                _ => (),
            },
            _ => (),
        }
    })
}
source

pub fn scale_factor(&self) -> f64

Returns the scale factor that can be used to map logical pixels to physical pixels, and vice versa.

Note that this value can change depending on user action (for example if the window is moved to another screen); as such, tracking WindowEvent::ScaleFactorChanged events is the most robust way to track the DPI you need to use to draw.

This value may differ from MonitorHandle::scale_factor.

See the dpi crate for more information.

§Platform-specific

The scale factor is calculated differently on different platforms:

  • Windows: On Windows 8 and 10, per-monitor scaling is readily configured by users from the display settings. While users are free to select any option they want, they’re only given a selection of “nice” scale factors, i.e. 1.0, 1.25, 1.5… on Windows 7. The scale factor is global and changing it requires logging out. See this article for technical details.

  • macOS: Recent macOS versions allow the user to change the scaling factor for specific displays. When available, the user may pick a per-monitor scaling factor from a set of pre-defined settings. All “retina displays” have a scaling factor above 1.0 by default, but the specific value varies across devices.

  • X11: Many man-hours have been spent trying to figure out how to handle DPI in X11. Winit currently uses a three-pronged approach:

    • Use the value in the WINIT_X11_SCALE_FACTOR environment variable if present.
    • If not present, use the value set in Xft.dpi in Xresources.
    • Otherwise, calculate the scale factor based on the millimeter monitor dimensions provided by XRandR.

    If WINIT_X11_SCALE_FACTOR is set to randr, it’ll ignore the Xft.dpi field and use the XRandR scaling method. Generally speaking, you should try to configure the standard system variables to do what you want before resorting to WINIT_X11_SCALE_FACTOR.

  • Wayland: The scale factor is suggested by the compositor for each window individually by using the wp-fractional-scale protocol if available. Falls back to integer-scale factors otherwise.

    The monitor scale factor may differ from the window scale factor.

  • iOS: Scale factors are set by Apple to the value that best suits the device, and range from 1.0 to 3.0. See this article and this article for more information.

    This uses the underlying UIView’s contentScaleFactor.

  • Android: Scale factors are set by the manufacturer to the value that best suits the device, and range from 1.0 to 4.0. See this article for more information.

    This is currently unimplemented, and this function always returns 1.0.

  • Web: The scale factor is the ratio between CSS pixels and the physical device pixels. In other words, it is the value of window.devicePixelRatio. It is affected by both the screen scaling and the browser zoom level and can go below 1.0.

  • Orbital: This is currently unimplemented, and this function always returns 1.0.

Examples found in repository?
examples/window.rs (line 769)
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
    fn drag_resize_window(&self) {
        let position = match self.cursor_position {
            Some(position) => position,
            None => {
                info!("Drag-resize requires cursor to be inside the window");
                return;
            },
        };

        let win_size = self.window.inner_size();
        let border_size = BORDER_SIZE * self.window.scale_factor();

        let x_direction = if position.x < border_size {
            ResizeDirection::West
        } else if position.x > (win_size.width as f64 - border_size) {
            ResizeDirection::East
        } else {
            // Use arbitrary direction instead of None for simplicity.
            ResizeDirection::SouthEast
        };

        let y_direction = if position.y < border_size {
            ResizeDirection::North
        } else if position.y > (win_size.height as f64 - border_size) {
            ResizeDirection::South
        } else {
            // Use arbitrary direction instead of None for simplicity.
            ResizeDirection::SouthEast
        };

        let direction = match (x_direction, y_direction) {
            (ResizeDirection::West, ResizeDirection::North) => ResizeDirection::NorthWest,
            (ResizeDirection::West, ResizeDirection::South) => ResizeDirection::SouthWest,
            (ResizeDirection::West, _) => ResizeDirection::West,
            (ResizeDirection::East, ResizeDirection::North) => ResizeDirection::NorthEast,
            (ResizeDirection::East, ResizeDirection::South) => ResizeDirection::SouthEast,
            (ResizeDirection::East, _) => ResizeDirection::East,
            (_, ResizeDirection::South) => ResizeDirection::South,
            (_, ResizeDirection::North) => ResizeDirection::North,
            _ => return,
        };

        if let Err(err) = self.window.drag_resize_window(direction) {
            info!("Error starting window drag-resize: {err}");
        } else {
            info!("Drag-resizing window Window={:?}", self.window.id());
        }
    }
source

pub fn request_redraw(&self)

Queues a WindowEvent::RedrawRequested event to be emitted that aligns with the windowing system drawing loop.

This is the strongly encouraged method of redrawing windows, as it can integrate with OS-requested redraws (e.g. when a window gets resized). To improve the event delivery consider using Window::pre_present_notify as described in docs.

Applications should always aim to redraw whenever they receive a RedrawRequested event.

There are no strong guarantees about when exactly a RedrawRequest event will be emitted with respect to other events, since the requirements can vary significantly between windowing systems.

However as the event aligns with the windowing system drawing loop, it may not arrive in same or even next event loop iteration.

§Platform-specific
  • Windows This API uses RedrawWindow to request a WM_PAINT message and RedrawRequested is emitted in sync with any WM_PAINT messages.
  • iOS: Can only be called on the main thread.
  • Wayland: The events are aligned with the frame callbacks when Window::pre_present_notify is used.
  • Web: WindowEvent::RedrawRequested will be aligned with the requestAnimationFrame.
Examples found in repository?
examples/run_on_demand.rs (line 27)
25
26
27
28
29
        fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) {
            if let Some(window) = self.window.as_ref() {
                window.request_redraw();
            }
        }
More examples
Hide additional examples
examples/window.rs (line 733)
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
    fn resize(&mut self, size: PhysicalSize<u32>) {
        info!("Resized to {size:?}");
        #[cfg(not(any(android_platform, ios_platform)))]
        {
            let (width, height) = match (NonZeroU32::new(size.width), NonZeroU32::new(size.height))
            {
                (Some(width), Some(height)) => (width, height),
                _ => return,
            };
            self.surface.resize(width, height).expect("failed to resize inner buffer");
        }
        self.window.request_redraw();
    }

    /// Change the theme.
    fn set_theme(&mut self, theme: Theme) {
        self.theme = theme;
        self.window.request_redraw();
    }

    /// Show window menu.
    fn show_menu(&self) {
        if let Some(position) = self.cursor_position {
            self.window.show_window_menu(position);
        }
    }

    /// Drag the window.
    fn drag_window(&self) {
        if let Err(err) = self.window.drag_window() {
            info!("Error starting window drag: {err}");
        } else {
            info!("Dragging window Window={:?}", self.window.id());
        }
    }

    /// Drag-resize the window.
    fn drag_resize_window(&self) {
        let position = match self.cursor_position {
            Some(position) => position,
            None => {
                info!("Drag-resize requires cursor to be inside the window");
                return;
            },
        };

        let win_size = self.window.inner_size();
        let border_size = BORDER_SIZE * self.window.scale_factor();

        let x_direction = if position.x < border_size {
            ResizeDirection::West
        } else if position.x > (win_size.width as f64 - border_size) {
            ResizeDirection::East
        } else {
            // Use arbitrary direction instead of None for simplicity.
            ResizeDirection::SouthEast
        };

        let y_direction = if position.y < border_size {
            ResizeDirection::North
        } else if position.y > (win_size.height as f64 - border_size) {
            ResizeDirection::South
        } else {
            // Use arbitrary direction instead of None for simplicity.
            ResizeDirection::SouthEast
        };

        let direction = match (x_direction, y_direction) {
            (ResizeDirection::West, ResizeDirection::North) => ResizeDirection::NorthWest,
            (ResizeDirection::West, ResizeDirection::South) => ResizeDirection::SouthWest,
            (ResizeDirection::West, _) => ResizeDirection::West,
            (ResizeDirection::East, ResizeDirection::North) => ResizeDirection::NorthEast,
            (ResizeDirection::East, ResizeDirection::South) => ResizeDirection::SouthEast,
            (ResizeDirection::East, _) => ResizeDirection::East,
            (_, ResizeDirection::South) => ResizeDirection::South,
            (_, ResizeDirection::North) => ResizeDirection::North,
            _ => return,
        };

        if let Err(err) = self.window.drag_resize_window(direction) {
            info!("Error starting window drag-resize: {err}");
        } else {
            info!("Drag-resizing window Window={:?}", self.window.id());
        }
    }

    /// Change window occlusion state.
    fn set_occluded(&mut self, occluded: bool) {
        self.occluded = occluded;
        if !occluded {
            self.window.request_redraw();
        }
    }
examples/pump_events.rs (line 47)
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
        fn window_event(
            &mut self,
            event_loop: &ActiveEventLoop,
            _window_id: WindowId,
            event: WindowEvent,
        ) {
            println!("{event:?}");

            let window = match self.window.as_ref() {
                Some(window) => window,
                None => return,
            };

            match event {
                WindowEvent::CloseRequested => event_loop.exit(),
                WindowEvent::RedrawRequested => {
                    fill::fill_window(window);
                    window.request_redraw();
                },
                _ => (),
            }
        }
examples/control_flow.rs (line 127)
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
    fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
        if self.request_redraw && !self.wait_cancelled && !self.close_requested {
            self.window.as_ref().unwrap().request_redraw();
        }

        match self.mode {
            Mode::Wait => event_loop.set_control_flow(ControlFlow::Wait),
            Mode::WaitUntil => {
                if !self.wait_cancelled {
                    event_loop
                        .set_control_flow(ControlFlow::WaitUntil(time::Instant::now() + WAIT_TIME));
                }
            },
            Mode::Poll => {
                thread::sleep(POLL_SLEEP_TIME);
                event_loop.set_control_flow(ControlFlow::Poll);
            },
        };

        if self.close_requested {
            event_loop.exit();
        }
    }
source

pub fn pre_present_notify(&self)

Notify the windowing system before presenting to the window.

You should call this event after your drawing operations, but before you submit the buffer to the display or commit your drawings. Doing so will help winit to properly schedule and make assumptions about its internal state. For example, it could properly throttle WindowEvent::RedrawRequested.

§Example

This example illustrates how it looks with OpenGL, but it applies to other graphics APIs and software rendering.

// Do the actual drawing with OpenGL.

// Notify winit that we're about to submit buffer to the windowing system.
window.pre_present_notify();

// Submit buffer to the windowing system.
swap_buffers();
§Platform-specific

Wayland: - schedules a frame callback to throttle WindowEvent::RedrawRequested.

Examples found in repository?
examples/window.rs (line 834)
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
    fn draw(&mut self) -> Result<(), Box<dyn Error>> {
        if self.occluded {
            info!("Skipping drawing occluded window={:?}", self.window.id());
            return Ok(());
        }

        const WHITE: u32 = 0xffffffff;
        const DARK_GRAY: u32 = 0xff181818;

        let color = match self.theme {
            Theme::Light => WHITE,
            Theme::Dark => DARK_GRAY,
        };

        let mut buffer = self.surface.buffer_mut()?;
        buffer.fill(color);
        self.window.pre_present_notify();
        buffer.present()?;
        Ok(())
    }
More examples
Hide additional examples
examples/control_flow.rs (line 118)
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
    fn window_event(
        &mut self,
        _event_loop: &ActiveEventLoop,
        _window_id: WindowId,
        event: WindowEvent,
    ) {
        info!("{event:?}");

        match event {
            WindowEvent::CloseRequested => {
                self.close_requested = true;
            },
            WindowEvent::KeyboardInput {
                event: KeyEvent { logical_key: key, state: ElementState::Pressed, .. },
                ..
            } => match key.as_ref() {
                // WARNING: Consider using `key_without_modifiers()` if available on your platform.
                // See the `key_binding` example
                Key::Character("1") => {
                    self.mode = Mode::Wait;
                    warn!("mode: {:?}", self.mode);
                },
                Key::Character("2") => {
                    self.mode = Mode::WaitUntil;
                    warn!("mode: {:?}", self.mode);
                },
                Key::Character("3") => {
                    self.mode = Mode::Poll;
                    warn!("mode: {:?}", self.mode);
                },
                Key::Character("r") => {
                    self.request_redraw = !self.request_redraw;
                    warn!("request_redraw: {}", self.request_redraw);
                },
                Key::Named(NamedKey::Escape) => {
                    self.close_requested = true;
                },
                _ => (),
            },
            WindowEvent::RedrawRequested => {
                let window = self.window.as_ref().unwrap();
                window.pre_present_notify();
                fill::fill_window(window);
            },
            _ => (),
        }
    }
source

pub fn reset_dead_keys(&self)

Reset the dead key state of the keyboard.

This is useful when a dead key is bound to trigger an action. Then this function can be called to reset the dead key state so that follow-up text input won’t be affected by the dead key.

§Platform-specific
  • Web, macOS: Does nothing
source§

impl Window

Position and size functions.

source

pub fn inner_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError>

Returns the position of the top-left hand corner of the window’s client area relative to the top-left hand corner of the desktop.

The same conditions that apply to Window::outer_position apply to this method.

§Platform-specific
  • iOS: Can only be called on the main thread. Returns the top left coordinates of the window’s safe area in the screen space coordinate system.
  • Web: Returns the top-left coordinates relative to the viewport. Note: this returns the same value as Window::outer_position.
  • Android / Wayland: Always returns NotSupportedError.
source

pub fn outer_position(&self) -> Result<PhysicalPosition<i32>, NotSupportedError>

Returns the position of the top-left hand corner of the window relative to the top-left hand corner of the desktop.

Note that the top-left hand corner of the desktop is not necessarily the same as the screen. If the user uses a desktop with multiple monitors, the top-left hand corner of the desktop is the top-left hand corner of the monitor at the top-left of the desktop.

The coordinates can be negative if the top-left hand corner of the window is outside of the visible screen region.

§Platform-specific
  • iOS: Can only be called on the main thread. Returns the top left coordinates of the window in the screen space coordinate system.
  • Web: Returns the top-left coordinates relative to the viewport.
  • Android / Wayland: Always returns NotSupportedError.
source

pub fn set_outer_position<P: Into<Position>>(&self, position: P)

Modifies the position of the window.

See Window::outer_position for more information about the coordinates. This automatically un-maximizes the window if it’s maximized.

// Specify the position in logical dimensions like this:
window.set_outer_position(LogicalPosition::new(400.0, 200.0));

// Or specify the position in physical dimensions like this:
window.set_outer_position(PhysicalPosition::new(400, 200));
§Platform-specific
  • iOS: Can only be called on the main thread. Sets the top left coordinates of the window in the screen space coordinate system.
  • Web: Sets the top-left coordinates relative to the viewport. Doesn’t account for CSS transform.
  • Android / Wayland: Unsupported.
source

pub fn inner_size(&self) -> PhysicalSize<u32>

Returns the physical size of the window’s client area.

The client area is the content of the window, excluding the title bar and borders.

§Platform-specific
  • iOS: Can only be called on the main thread. Returns the PhysicalSize of the window’s safe area in screen space coordinates.
  • Web: Returns the size of the canvas element. Doesn’t account for CSS transform.
Examples found in repository?
examples/util/fill.rs (line 73)
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
    pub fn fill_window(window: &Window) {
        GC.with(|gc| {
            let size = window.inner_size();
            let (Some(width), Some(height)) =
                (NonZeroU32::new(size.width), NonZeroU32::new(size.height))
            else {
                return;
            };

            // Either get the last context used or create a new one.
            let mut gc = gc.borrow_mut();
            let surface =
                gc.get_or_insert_with(|| GraphicsContext::new(window)).create_surface(window);

            // Fill a buffer with a solid color.
            const DARK_GRAY: u32 = 0xff181818;

            surface.resize(width, height).expect("Failed to resize the softbuffer surface");

            let mut buffer = surface.buffer_mut().expect("Failed to get the softbuffer buffer");
            buffer.fill(DARK_GRAY);
            buffer.present().expect("Failed to present the softbuffer buffer");
        })
    }
More examples
Hide additional examples
examples/window.rs (line 541)
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
    fn new(app: &Application, window: Window) -> Result<Self, Box<dyn Error>> {
        let window = Arc::new(window);

        // SAFETY: the surface is dropped before the `window` which provided it with handle, thus
        // it doesn't outlive it.
        #[cfg(not(any(android_platform, ios_platform)))]
        let surface = Surface::new(app.context.as_ref().unwrap(), Arc::clone(&window))?;

        let theme = window.theme().unwrap_or(Theme::Dark);
        info!("Theme: {theme:?}");
        let named_idx = 0;
        window.set_cursor(CURSORS[named_idx]);

        // Allow IME out of the box.
        let ime = true;
        window.set_ime_allowed(ime);

        let size = window.inner_size();
        let mut state = Self {
            #[cfg(macos_platform)]
            option_as_alt: window.option_as_alt(),
            custom_idx: app.custom_cursors.len() - 1,
            cursor_grab: CursorGrabMode::None,
            named_idx,
            #[cfg(not(any(android_platform, ios_platform)))]
            surface,
            window,
            theme,
            ime,
            cursor_position: Default::default(),
            cursor_hidden: Default::default(),
            modifiers: Default::default(),
            occluded: Default::default(),
            rotated: Default::default(),
            panned: Default::default(),
            zoom: Default::default(),
        };

        state.resize(size);
        Ok(state)
    }

    pub fn toggle_ime(&mut self) {
        self.ime = !self.ime;
        self.window.set_ime_allowed(self.ime);
        if let Some(position) = self.ime.then_some(self.cursor_position).flatten() {
            self.window.set_ime_cursor_area(position, PhysicalSize::new(20, 20));
        }
    }

    pub fn minimize(&mut self) {
        self.window.set_minimized(true);
    }

    pub fn cursor_moved(&mut self, position: PhysicalPosition<f64>) {
        self.cursor_position = Some(position);
        if self.ime {
            self.window.set_ime_cursor_area(position, PhysicalSize::new(20, 20));
        }
    }

    pub fn cursor_left(&mut self) {
        self.cursor_position = None;
    }

    /// Toggle maximized.
    fn toggle_maximize(&self) {
        let maximized = self.window.is_maximized();
        self.window.set_maximized(!maximized);
    }

    /// Toggle window decorations.
    fn toggle_decorations(&self) {
        let decorated = self.window.is_decorated();
        self.window.set_decorations(!decorated);
    }

    /// Toggle window resizable state.
    fn toggle_resizable(&self) {
        let resizable = self.window.is_resizable();
        self.window.set_resizable(!resizable);
    }

    /// Toggle cursor visibility
    fn toggle_cursor_visibility(&mut self) {
        self.cursor_hidden = !self.cursor_hidden;
        self.window.set_cursor_visible(!self.cursor_hidden);
    }

    /// Toggle resize increments on a window.
    fn toggle_resize_increments(&mut self) {
        let new_increments = match self.window.resize_increments() {
            Some(_) => None,
            None => Some(LogicalSize::new(25.0, 25.0)),
        };
        info!("Had increments: {}", new_increments.is_none());
        self.window.set_resize_increments(new_increments);
    }

    /// Toggle fullscreen.
    fn toggle_fullscreen(&self) {
        let fullscreen = if self.window.fullscreen().is_some() {
            None
        } else {
            Some(Fullscreen::Borderless(None))
        };

        self.window.set_fullscreen(fullscreen);
    }

    /// Cycle through the grab modes ignoring errors.
    fn cycle_cursor_grab(&mut self) {
        self.cursor_grab = match self.cursor_grab {
            CursorGrabMode::None => CursorGrabMode::Confined,
            CursorGrabMode::Confined => CursorGrabMode::Locked,
            CursorGrabMode::Locked => CursorGrabMode::None,
        };
        info!("Changing cursor grab mode to {:?}", self.cursor_grab);
        if let Err(err) = self.window.set_cursor_grab(self.cursor_grab) {
            error!("Error setting cursor grab: {err}");
        }
    }

    #[cfg(macos_platform)]
    fn cycle_option_as_alt(&mut self) {
        self.option_as_alt = match self.option_as_alt {
            OptionAsAlt::None => OptionAsAlt::OnlyLeft,
            OptionAsAlt::OnlyLeft => OptionAsAlt::OnlyRight,
            OptionAsAlt::OnlyRight => OptionAsAlt::Both,
            OptionAsAlt::Both => OptionAsAlt::None,
        };
        info!("Setting option as alt {:?}", self.option_as_alt);
        self.window.set_option_as_alt(self.option_as_alt);
    }

    /// Swap the window dimensions with `request_inner_size`.
    fn swap_dimensions(&mut self) {
        let old_inner_size = self.window.inner_size();
        let mut inner_size = old_inner_size;

        mem::swap(&mut inner_size.width, &mut inner_size.height);
        info!("Requesting resize from {old_inner_size:?} to {inner_size:?}");

        if let Some(new_inner_size) = self.window.request_inner_size(inner_size) {
            if old_inner_size == new_inner_size {
                info!("Inner size change got ignored");
            } else {
                self.resize(new_inner_size);
            }
        } else {
            info!("Request inner size is asynchronous");
        }
    }

    /// Pick the next cursor.
    fn next_cursor(&mut self) {
        self.named_idx = (self.named_idx + 1) % CURSORS.len();
        info!("Setting cursor to \"{:?}\"", CURSORS[self.named_idx]);
        self.window.set_cursor(Cursor::Icon(CURSORS[self.named_idx]));
    }

    /// Pick the next custom cursor.
    fn next_custom_cursor(&mut self, custom_cursors: &[CustomCursor]) {
        self.custom_idx = (self.custom_idx + 1) % custom_cursors.len();
        let cursor = Cursor::Custom(custom_cursors[self.custom_idx].clone());
        self.window.set_cursor(cursor);
    }

    /// Custom cursor from an URL.
    #[cfg(web_platform)]
    fn url_custom_cursor(&mut self, event_loop: &ActiveEventLoop) {
        let cursor = event_loop.create_custom_cursor(url_custom_cursor());

        self.window.set_cursor(cursor);
    }

    /// Custom cursor from a URL.
    #[cfg(web_platform)]
    fn animation_custom_cursor(
        &mut self,
        event_loop: &ActiveEventLoop,
        custom_cursors: &[CustomCursor],
    ) {
        use std::time::Duration;
        use winit::platform::web::CustomCursorExtWebSys;

        let cursors = vec![
            custom_cursors[0].clone(),
            custom_cursors[1].clone(),
            event_loop.create_custom_cursor(url_custom_cursor()),
        ];
        let cursor = CustomCursor::from_animation(Duration::from_secs(3), cursors).unwrap();
        let cursor = event_loop.create_custom_cursor(cursor);

        self.window.set_cursor(cursor);
    }

    /// Resize the window to the new size.
    fn resize(&mut self, size: PhysicalSize<u32>) {
        info!("Resized to {size:?}");
        #[cfg(not(any(android_platform, ios_platform)))]
        {
            let (width, height) = match (NonZeroU32::new(size.width), NonZeroU32::new(size.height))
            {
                (Some(width), Some(height)) => (width, height),
                _ => return,
            };
            self.surface.resize(width, height).expect("failed to resize inner buffer");
        }
        self.window.request_redraw();
    }

    /// Change the theme.
    fn set_theme(&mut self, theme: Theme) {
        self.theme = theme;
        self.window.request_redraw();
    }

    /// Show window menu.
    fn show_menu(&self) {
        if let Some(position) = self.cursor_position {
            self.window.show_window_menu(position);
        }
    }

    /// Drag the window.
    fn drag_window(&self) {
        if let Err(err) = self.window.drag_window() {
            info!("Error starting window drag: {err}");
        } else {
            info!("Dragging window Window={:?}", self.window.id());
        }
    }

    /// Drag-resize the window.
    fn drag_resize_window(&self) {
        let position = match self.cursor_position {
            Some(position) => position,
            None => {
                info!("Drag-resize requires cursor to be inside the window");
                return;
            },
        };

        let win_size = self.window.inner_size();
        let border_size = BORDER_SIZE * self.window.scale_factor();

        let x_direction = if position.x < border_size {
            ResizeDirection::West
        } else if position.x > (win_size.width as f64 - border_size) {
            ResizeDirection::East
        } else {
            // Use arbitrary direction instead of None for simplicity.
            ResizeDirection::SouthEast
        };

        let y_direction = if position.y < border_size {
            ResizeDirection::North
        } else if position.y > (win_size.height as f64 - border_size) {
            ResizeDirection::South
        } else {
            // Use arbitrary direction instead of None for simplicity.
            ResizeDirection::SouthEast
        };

        let direction = match (x_direction, y_direction) {
            (ResizeDirection::West, ResizeDirection::North) => ResizeDirection::NorthWest,
            (ResizeDirection::West, ResizeDirection::South) => ResizeDirection::SouthWest,
            (ResizeDirection::West, _) => ResizeDirection::West,
            (ResizeDirection::East, ResizeDirection::North) => ResizeDirection::NorthEast,
            (ResizeDirection::East, ResizeDirection::South) => ResizeDirection::SouthEast,
            (ResizeDirection::East, _) => ResizeDirection::East,
            (_, ResizeDirection::South) => ResizeDirection::South,
            (_, ResizeDirection::North) => ResizeDirection::North,
            _ => return,
        };

        if let Err(err) = self.window.drag_resize_window(direction) {
            info!("Error starting window drag-resize: {err}");
        } else {
            info!("Drag-resizing window Window={:?}", self.window.id());
        }
    }
source

pub fn request_inner_size<S: Into<Size>>( &self, size: S ) -> Option<PhysicalSize<u32>>

Request the new size for the window.

On platforms where the size is entirely controlled by the user the applied size will be returned immediately, resize event in such case may not be generated.

On platforms where resizing is disallowed by the windowing system, the current inner size is returned immediately, and the user one is ignored.

When None is returned, it means that the request went to the display system, and the actual size will be delivered later with the WindowEvent::Resized.

See Window::inner_size for more information about the values.

The request could automatically un-maximize the window if it’s maximized.

// Specify the size in logical dimensions like this:
let _ = window.request_inner_size(LogicalSize::new(400.0, 200.0));

// Or specify the size in physical dimensions like this:
let _ = window.request_inner_size(PhysicalSize::new(400, 200));
§Platform-specific
  • Web: Sets the size of the canvas element. Doesn’t account for CSS transform.
Examples found in repository?
examples/window.rs (line 667)
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
    fn swap_dimensions(&mut self) {
        let old_inner_size = self.window.inner_size();
        let mut inner_size = old_inner_size;

        mem::swap(&mut inner_size.width, &mut inner_size.height);
        info!("Requesting resize from {old_inner_size:?} to {inner_size:?}");

        if let Some(new_inner_size) = self.window.request_inner_size(inner_size) {
            if old_inner_size == new_inner_size {
                info!("Inner size change got ignored");
            } else {
                self.resize(new_inner_size);
            }
        } else {
            info!("Request inner size is asynchronous");
        }
    }
source

pub fn outer_size(&self) -> PhysicalSize<u32>

Returns the physical size of the entire window.

These dimensions include the title bar and borders. If you don’t want that (and you usually don’t), use Window::inner_size instead.

§Platform-specific
  • iOS: Can only be called on the main thread. Returns the PhysicalSize of the window in screen space coordinates.
  • Web: Returns the size of the canvas element. Note: this returns the same value as Window::inner_size.
source

pub fn set_min_inner_size<S: Into<Size>>(&self, min_size: Option<S>)

Sets a minimum dimension size for the window.

// Specify the size in logical dimensions like this:
window.set_min_inner_size(Some(LogicalSize::new(400.0, 200.0)));

// Or specify the size in physical dimensions like this:
window.set_min_inner_size(Some(PhysicalSize::new(400, 200)));
§Platform-specific
  • iOS / Android / Orbital: Unsupported.
source

pub fn set_max_inner_size<S: Into<Size>>(&self, max_size: Option<S>)

Sets a maximum dimension size for the window.

// Specify the size in logical dimensions like this:
window.set_max_inner_size(Some(LogicalSize::new(400.0, 200.0)));

// Or specify the size in physical dimensions like this:
window.set_max_inner_size(Some(PhysicalSize::new(400, 200)));
§Platform-specific
  • iOS / Android / Orbital: Unsupported.
source

pub fn resize_increments(&self) -> Option<PhysicalSize<u32>>

Returns window resize increments if any were set.

§Platform-specific
  • iOS / Android / Web / Wayland / Orbital: Always returns None.
Examples found in repository?
examples/window.rs (line 615)
614
615
616
617
618
619
620
621
    fn toggle_resize_increments(&mut self) {
        let new_increments = match self.window.resize_increments() {
            Some(_) => None,
            None => Some(LogicalSize::new(25.0, 25.0)),
        };
        info!("Had increments: {}", new_increments.is_none());
        self.window.set_resize_increments(new_increments);
    }
source

pub fn set_resize_increments<S: Into<Size>>(&self, increments: Option<S>)

Sets window resize increments.

This is a niche constraint hint usually employed by terminal emulators and other apps that need “blocky” resizes.

§Platform-specific
  • macOS: Increments are converted to logical size and then macOS rounds them to whole numbers.
  • Wayland: Not implemented.
  • iOS / Android / Web / Orbital: Unsupported.
Examples found in repository?
examples/window.rs (line 620)
614
615
616
617
618
619
620
621
    fn toggle_resize_increments(&mut self) {
        let new_increments = match self.window.resize_increments() {
            Some(_) => None,
            None => Some(LogicalSize::new(25.0, 25.0)),
        };
        info!("Had increments: {}", new_increments.is_none());
        self.window.set_resize_increments(new_increments);
    }
source§

impl Window

Misc. attribute functions.

source

pub fn set_title(&self, title: &str)

Modifies the title of the window.

§Platform-specific
  • iOS / Android: Unsupported.
source

pub fn set_transparent(&self, transparent: bool)

Change the window transparency state.

This is just a hint that may not change anything about the window transparency, however doing a mismatch between the content of your window and this hint may result in visual artifacts.

The default value follows the WindowAttributes::with_transparent.

§Platform-specific
  • macOS: If you’re not drawing to the window yourself, you might have to set the background color of the window to enable transparency.
  • Web / iOS / Android: Unsupported.
  • X11: Can only be set while building the window, with WindowAttributes::with_transparent.
source

pub fn set_blur(&self, blur: bool)

Change the window blur state.

If true, this will make the transparent window background blurry.

§Platform-specific
  • Android / iOS / X11 / Web / Windows: Unsupported.
  • Wayland: Only works with org_kde_kwin_blur_manager protocol.
source

pub fn set_visible(&self, visible: bool)

Modifies the window’s visibility.

If false, this will hide the window. If true, this will show the window.

§Platform-specific
  • Android / Wayland / Web: Unsupported.
  • iOS: Can only be called on the main thread.
source

pub fn is_visible(&self) -> Option<bool>

Gets the window’s current visibility state.

None means it couldn’t be determined, so it is not recommended to use this to drive your rendering backend.

§Platform-specific
  • X11: Not implemented.
  • Wayland / iOS / Android / Web: Unsupported.
source

pub fn set_resizable(&self, resizable: bool)

Sets whether the window is resizable or not.

Note that making the window unresizable doesn’t exempt you from handling WindowEvent::Resized, as that event can still be triggered by DPI scaling, entering fullscreen mode, etc. Also, the window could still be resized by calling Window::request_inner_size.

§Platform-specific

This only has an effect on desktop platforms.

  • X11: Due to a bug in XFCE, this has no effect on Xfwm.
  • iOS / Android / Web: Unsupported.
Examples found in repository?
examples/window.rs (line 604)
602
603
604
605
    fn toggle_resizable(&self) {
        let resizable = self.window.is_resizable();
        self.window.set_resizable(!resizable);
    }
source

pub fn is_resizable(&self) -> bool

Gets the window’s current resizable state.

§Platform-specific
  • X11: Not implemented.
  • iOS / Android / Web: Unsupported.
Examples found in repository?
examples/window.rs (line 603)
602
603
604
605
    fn toggle_resizable(&self) {
        let resizable = self.window.is_resizable();
        self.window.set_resizable(!resizable);
    }
source

pub fn set_enabled_buttons(&self, buttons: WindowButtons)

Sets the enabled window buttons.

§Platform-specific
  • Wayland / X11 / Orbital: Not implemented.
  • Web / iOS / Android: Unsupported.
source

pub fn enabled_buttons(&self) -> WindowButtons

Gets the enabled window buttons.

§Platform-specific
source

pub fn set_minimized(&self, minimized: bool)

Sets the window to minimized or back

§Platform-specific
  • iOS / Android / Web / Orbital: Unsupported.
  • Wayland: Un-minimize is unsupported.
Examples found in repository?
examples/window.rs (line 575)
574
575
576
    pub fn minimize(&mut self) {
        self.window.set_minimized(true);
    }
source

pub fn is_minimized(&self) -> Option<bool>

Gets the window’s current minimized state.

None will be returned, if the minimized state couldn’t be determined.

§Note
  • You shouldn’t stop rendering for minimized windows, however you could lower the fps.
§Platform-specific
  • Wayland: always None.
  • iOS / Android / Web / Orbital: Unsupported.
source

pub fn set_maximized(&self, maximized: bool)

Sets the window to maximized or back.

§Platform-specific
  • iOS / Android / Web: Unsupported.
Examples found in repository?
examples/window.rs (line 592)
590
591
592
593
    fn toggle_maximize(&self) {
        let maximized = self.window.is_maximized();
        self.window.set_maximized(!maximized);
    }
source

pub fn is_maximized(&self) -> bool

Gets the window’s current maximized state.

§Platform-specific
  • iOS / Android / Web: Unsupported.
Examples found in repository?
examples/window.rs (line 591)
590
591
592
593
    fn toggle_maximize(&self) {
        let maximized = self.window.is_maximized();
        self.window.set_maximized(!maximized);
    }
source

pub fn set_fullscreen(&self, fullscreen: Option<Fullscreen>)

Sets the window to fullscreen or back.

§Platform-specific
  • macOS: Fullscreen::Exclusive provides true exclusive mode with a video mode change. Caveat! macOS doesn’t provide task switching (or spaces!) while in exclusive fullscreen mode. This mode should be used when a video mode change is desired, but for a better user experience, borderless fullscreen might be preferred.

    Fullscreen::Borderless provides a borderless fullscreen window on a separate space. This is the idiomatic way for fullscreen games to work on macOS. See WindowExtMacOs::set_simple_fullscreen if separate spaces are not preferred.

    The dock and the menu bar are disabled in exclusive fullscreen mode.

  • iOS: Can only be called on the main thread.

  • Wayland: Does not support exclusive fullscreen mode and will no-op a request.

  • Windows: Screen saver is disabled in fullscreen mode.

  • Android / Orbital: Unsupported.

  • Web: Does nothing without a transient activation.

Examples found in repository?
examples/window.rs (line 631)
624
625
626
627
628
629
630
631
632
    fn toggle_fullscreen(&self) {
        let fullscreen = if self.window.fullscreen().is_some() {
            None
        } else {
            Some(Fullscreen::Borderless(None))
        };

        self.window.set_fullscreen(fullscreen);
    }
source

pub fn fullscreen(&self) -> Option<Fullscreen>

Gets the window’s current fullscreen state.

§Platform-specific
  • iOS: Can only be called on the main thread.
  • Android / Orbital: Will always return None.
  • Wayland: Can return Borderless(None) when there are no monitors.
  • Web: Can only return None or Borderless(None).
Examples found in repository?
examples/window.rs (line 625)
624
625
626
627
628
629
630
631
632
    fn toggle_fullscreen(&self) {
        let fullscreen = if self.window.fullscreen().is_some() {
            None
        } else {
            Some(Fullscreen::Borderless(None))
        };

        self.window.set_fullscreen(fullscreen);
    }
source

pub fn set_decorations(&self, decorations: bool)

Turn window decorations on or off.

Enable/disable window decorations provided by the server or Winit. By default this is enabled. Note that fullscreen windows and windows on mobile and web platforms naturally do not have decorations.

§Platform-specific
  • iOS / Android / Web: No effect.
Examples found in repository?
examples/window.rs (line 598)
596
597
598
599
    fn toggle_decorations(&self) {
        let decorated = self.window.is_decorated();
        self.window.set_decorations(!decorated);
    }
source

pub fn is_decorated(&self) -> bool

Gets the window’s current decorations state.

Returns true when windows are decorated (server-side or by Winit). Also returns true when no decorations are required (mobile, web).

§Platform-specific
  • iOS / Android / Web: Always returns true.
Examples found in repository?
examples/window.rs (line 597)
596
597
598
599
    fn toggle_decorations(&self) {
        let decorated = self.window.is_decorated();
        self.window.set_decorations(!decorated);
    }
source

pub fn set_window_level(&self, level: WindowLevel)

Change the window level.

This is just a hint to the OS, and the system could ignore it.

See WindowLevel for details.

source

pub fn set_window_icon(&self, window_icon: Option<Icon>)

Sets the window icon.

On Windows and X11, this is typically the small icon in the top-left corner of the titlebar.

§Platform-specific
  • iOS / Android / Web / Wayland / macOS / Orbital: Unsupported.

  • Windows: Sets ICON_SMALL. The base size for a window icon is 16x16, but it’s recommended to account for screen scaling and pick a multiple of that, i.e. 32x32.

  • X11: Has no universal guidelines for icon sizes, so you’re at the whims of the WM. That said, it’s usually in the same ballpark as on Windows.

source

pub fn set_ime_cursor_area<P: Into<Position>, S: Into<Size>>( &self, position: P, size: S )

Set the IME cursor editing area, where the position is the top left corner of that area and size is the size of this area starting from the position. An example of such area could be a input field in the UI or line in the editor.

The windowing system could place a candidate box close to that area, but try to not obscure the specified area, so the user input to it stays visible.

The candidate box is the window / popup / overlay that allows you to select the desired characters. The look of this box may differ between input devices, even on the same platform.

(Apple’s official term is “candidate window”, see their chinese and japanese guides).

§Example
// Specify the position in logical dimensions like this:
window.set_ime_cursor_area(LogicalPosition::new(400.0, 200.0), LogicalSize::new(100, 100));

// Or specify the position in physical dimensions like this:
window.set_ime_cursor_area(PhysicalPosition::new(400, 200), PhysicalSize::new(100, 100));
§Platform-specific
  • X11: - area is not supported, only position.
  • iOS / Android / Web / Orbital: Unsupported.
Examples found in repository?
examples/window.rs (line 570)
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
    pub fn toggle_ime(&mut self) {
        self.ime = !self.ime;
        self.window.set_ime_allowed(self.ime);
        if let Some(position) = self.ime.then_some(self.cursor_position).flatten() {
            self.window.set_ime_cursor_area(position, PhysicalSize::new(20, 20));
        }
    }

    pub fn minimize(&mut self) {
        self.window.set_minimized(true);
    }

    pub fn cursor_moved(&mut self, position: PhysicalPosition<f64>) {
        self.cursor_position = Some(position);
        if self.ime {
            self.window.set_ime_cursor_area(position, PhysicalSize::new(20, 20));
        }
    }
source

pub fn set_ime_allowed(&self, allowed: bool)

Sets whether the window should get IME events

When IME is allowed, the window will receive Ime events, and during the preedit phase the window will NOT get KeyboardInput events. The window should allow IME while it is expecting text input.

When IME is not allowed, the window won’t receive Ime events, and will receive KeyboardInput events for every keypress instead. Not allowing IME is useful for games for example.

IME is not allowed by default.

§Platform-specific
  • macOS: IME must be enabled to receive text-input where dead-key sequences are combined.
  • iOS / Android / Web / Orbital: Unsupported.
  • X11: Enabling IME will disable dead keys reporting during compose.
Examples found in repository?
examples/window.rs (line 539)
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
    fn new(app: &Application, window: Window) -> Result<Self, Box<dyn Error>> {
        let window = Arc::new(window);

        // SAFETY: the surface is dropped before the `window` which provided it with handle, thus
        // it doesn't outlive it.
        #[cfg(not(any(android_platform, ios_platform)))]
        let surface = Surface::new(app.context.as_ref().unwrap(), Arc::clone(&window))?;

        let theme = window.theme().unwrap_or(Theme::Dark);
        info!("Theme: {theme:?}");
        let named_idx = 0;
        window.set_cursor(CURSORS[named_idx]);

        // Allow IME out of the box.
        let ime = true;
        window.set_ime_allowed(ime);

        let size = window.inner_size();
        let mut state = Self {
            #[cfg(macos_platform)]
            option_as_alt: window.option_as_alt(),
            custom_idx: app.custom_cursors.len() - 1,
            cursor_grab: CursorGrabMode::None,
            named_idx,
            #[cfg(not(any(android_platform, ios_platform)))]
            surface,
            window,
            theme,
            ime,
            cursor_position: Default::default(),
            cursor_hidden: Default::default(),
            modifiers: Default::default(),
            occluded: Default::default(),
            rotated: Default::default(),
            panned: Default::default(),
            zoom: Default::default(),
        };

        state.resize(size);
        Ok(state)
    }

    pub fn toggle_ime(&mut self) {
        self.ime = !self.ime;
        self.window.set_ime_allowed(self.ime);
        if let Some(position) = self.ime.then_some(self.cursor_position).flatten() {
            self.window.set_ime_cursor_area(position, PhysicalSize::new(20, 20));
        }
    }
source

pub fn set_ime_purpose(&self, purpose: ImePurpose)

Sets the IME purpose for the window using ImePurpose.

§Platform-specific
  • iOS / Android / Web / Windows / X11 / macOS / Orbital: Unsupported.
source

pub fn focus_window(&self)

Brings the window to the front and sets input focus. Has no effect if the window is already in focus, minimized, or not visible.

This method steals input focus from other applications. Do not use this method unless you are certain that’s what the user wants. Focus stealing can cause an extremely disruptive user experience.

§Platform-specific
  • iOS / Android / Wayland / Orbital: Unsupported.
source

pub fn has_focus(&self) -> bool

Gets whether the window has keyboard focus.

This queries the same state information as WindowEvent::Focused.

source

pub fn request_user_attention(&self, request_type: Option<UserAttentionType>)

Requests user attention to the window, this has no effect if the application is already focused. How requesting for user attention manifests is platform dependent, see UserAttentionType for details.

Providing None will unset the request for user attention. Unsetting the request for user attention might not be done automatically by the WM when the window receives input.

§Platform-specific
  • iOS / Android / Web / Orbital: Unsupported.
  • macOS: None has no effect.
  • X11: Requests for user attention must be manually cleared.
  • Wayland: Requires xdg_activation_v1 protocol, None has no effect.
source

pub fn set_theme(&self, theme: Option<Theme>)

Sets the current window theme. Use None to fallback to system default.

§Platform-specific
  • macOS: This is an app-wide setting.
  • Wayland: Sets the theme for the client side decorations. Using None will use dbus to get the system preference.
  • X11: Sets _GTK_THEME_VARIANT hint to dark or light and if None is used, it will default to Theme::Dark.
  • iOS / Android / Web / Orbital: Unsupported.
source

pub fn theme(&self) -> Option<Theme>

Returns the current window theme.

§Platform-specific
  • macOS: This is an app-wide setting.
  • iOS / Android / Wayland / x11 / Orbital: Unsupported.
Examples found in repository?
examples/window.rs (line 532)
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
    fn new(app: &Application, window: Window) -> Result<Self, Box<dyn Error>> {
        let window = Arc::new(window);

        // SAFETY: the surface is dropped before the `window` which provided it with handle, thus
        // it doesn't outlive it.
        #[cfg(not(any(android_platform, ios_platform)))]
        let surface = Surface::new(app.context.as_ref().unwrap(), Arc::clone(&window))?;

        let theme = window.theme().unwrap_or(Theme::Dark);
        info!("Theme: {theme:?}");
        let named_idx = 0;
        window.set_cursor(CURSORS[named_idx]);

        // Allow IME out of the box.
        let ime = true;
        window.set_ime_allowed(ime);

        let size = window.inner_size();
        let mut state = Self {
            #[cfg(macos_platform)]
            option_as_alt: window.option_as_alt(),
            custom_idx: app.custom_cursors.len() - 1,
            cursor_grab: CursorGrabMode::None,
            named_idx,
            #[cfg(not(any(android_platform, ios_platform)))]
            surface,
            window,
            theme,
            ime,
            cursor_position: Default::default(),
            cursor_hidden: Default::default(),
            modifiers: Default::default(),
            occluded: Default::default(),
            rotated: Default::default(),
            panned: Default::default(),
            zoom: Default::default(),
        };

        state.resize(size);
        Ok(state)
    }
source

pub fn set_content_protected(&self, protected: bool)

Prevents the window contents from being captured by other apps.

§Platform-specific
  • macOS: if false, NSWindowSharingNone is used but doesn’t completely prevent all apps from reading the window content, for instance, QuickTime.
  • iOS / Android / x11 / Wayland / Web / Orbital: Unsupported.
source

pub fn title(&self) -> String

Gets the current title of the window.

§Platform-specific
  • iOS / Android / x11 / Wayland / Web: Unsupported. Always returns an empty string.
source§

impl Window

Cursor functions.

source

pub fn set_cursor(&self, cursor: impl Into<Cursor>)

Modifies the cursor icon of the window.

§Platform-specific
  • iOS / Android / Orbital: Unsupported.
  • Web: Custom cursors have to be loaded and decoded first, until then the previous cursor is shown.
Examples found in repository?
examples/window.rs (line 535)
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
    fn new(app: &Application, window: Window) -> Result<Self, Box<dyn Error>> {
        let window = Arc::new(window);

        // SAFETY: the surface is dropped before the `window` which provided it with handle, thus
        // it doesn't outlive it.
        #[cfg(not(any(android_platform, ios_platform)))]
        let surface = Surface::new(app.context.as_ref().unwrap(), Arc::clone(&window))?;

        let theme = window.theme().unwrap_or(Theme::Dark);
        info!("Theme: {theme:?}");
        let named_idx = 0;
        window.set_cursor(CURSORS[named_idx]);

        // Allow IME out of the box.
        let ime = true;
        window.set_ime_allowed(ime);

        let size = window.inner_size();
        let mut state = Self {
            #[cfg(macos_platform)]
            option_as_alt: window.option_as_alt(),
            custom_idx: app.custom_cursors.len() - 1,
            cursor_grab: CursorGrabMode::None,
            named_idx,
            #[cfg(not(any(android_platform, ios_platform)))]
            surface,
            window,
            theme,
            ime,
            cursor_position: Default::default(),
            cursor_hidden: Default::default(),
            modifiers: Default::default(),
            occluded: Default::default(),
            rotated: Default::default(),
            panned: Default::default(),
            zoom: Default::default(),
        };

        state.resize(size);
        Ok(state)
    }

    pub fn toggle_ime(&mut self) {
        self.ime = !self.ime;
        self.window.set_ime_allowed(self.ime);
        if let Some(position) = self.ime.then_some(self.cursor_position).flatten() {
            self.window.set_ime_cursor_area(position, PhysicalSize::new(20, 20));
        }
    }

    pub fn minimize(&mut self) {
        self.window.set_minimized(true);
    }

    pub fn cursor_moved(&mut self, position: PhysicalPosition<f64>) {
        self.cursor_position = Some(position);
        if self.ime {
            self.window.set_ime_cursor_area(position, PhysicalSize::new(20, 20));
        }
    }

    pub fn cursor_left(&mut self) {
        self.cursor_position = None;
    }

    /// Toggle maximized.
    fn toggle_maximize(&self) {
        let maximized = self.window.is_maximized();
        self.window.set_maximized(!maximized);
    }

    /// Toggle window decorations.
    fn toggle_decorations(&self) {
        let decorated = self.window.is_decorated();
        self.window.set_decorations(!decorated);
    }

    /// Toggle window resizable state.
    fn toggle_resizable(&self) {
        let resizable = self.window.is_resizable();
        self.window.set_resizable(!resizable);
    }

    /// Toggle cursor visibility
    fn toggle_cursor_visibility(&mut self) {
        self.cursor_hidden = !self.cursor_hidden;
        self.window.set_cursor_visible(!self.cursor_hidden);
    }

    /// Toggle resize increments on a window.
    fn toggle_resize_increments(&mut self) {
        let new_increments = match self.window.resize_increments() {
            Some(_) => None,
            None => Some(LogicalSize::new(25.0, 25.0)),
        };
        info!("Had increments: {}", new_increments.is_none());
        self.window.set_resize_increments(new_increments);
    }

    /// Toggle fullscreen.
    fn toggle_fullscreen(&self) {
        let fullscreen = if self.window.fullscreen().is_some() {
            None
        } else {
            Some(Fullscreen::Borderless(None))
        };

        self.window.set_fullscreen(fullscreen);
    }

    /// Cycle through the grab modes ignoring errors.
    fn cycle_cursor_grab(&mut self) {
        self.cursor_grab = match self.cursor_grab {
            CursorGrabMode::None => CursorGrabMode::Confined,
            CursorGrabMode::Confined => CursorGrabMode::Locked,
            CursorGrabMode::Locked => CursorGrabMode::None,
        };
        info!("Changing cursor grab mode to {:?}", self.cursor_grab);
        if let Err(err) = self.window.set_cursor_grab(self.cursor_grab) {
            error!("Error setting cursor grab: {err}");
        }
    }

    #[cfg(macos_platform)]
    fn cycle_option_as_alt(&mut self) {
        self.option_as_alt = match self.option_as_alt {
            OptionAsAlt::None => OptionAsAlt::OnlyLeft,
            OptionAsAlt::OnlyLeft => OptionAsAlt::OnlyRight,
            OptionAsAlt::OnlyRight => OptionAsAlt::Both,
            OptionAsAlt::Both => OptionAsAlt::None,
        };
        info!("Setting option as alt {:?}", self.option_as_alt);
        self.window.set_option_as_alt(self.option_as_alt);
    }

    /// Swap the window dimensions with `request_inner_size`.
    fn swap_dimensions(&mut self) {
        let old_inner_size = self.window.inner_size();
        let mut inner_size = old_inner_size;

        mem::swap(&mut inner_size.width, &mut inner_size.height);
        info!("Requesting resize from {old_inner_size:?} to {inner_size:?}");

        if let Some(new_inner_size) = self.window.request_inner_size(inner_size) {
            if old_inner_size == new_inner_size {
                info!("Inner size change got ignored");
            } else {
                self.resize(new_inner_size);
            }
        } else {
            info!("Request inner size is asynchronous");
        }
    }

    /// Pick the next cursor.
    fn next_cursor(&mut self) {
        self.named_idx = (self.named_idx + 1) % CURSORS.len();
        info!("Setting cursor to \"{:?}\"", CURSORS[self.named_idx]);
        self.window.set_cursor(Cursor::Icon(CURSORS[self.named_idx]));
    }

    /// Pick the next custom cursor.
    fn next_custom_cursor(&mut self, custom_cursors: &[CustomCursor]) {
        self.custom_idx = (self.custom_idx + 1) % custom_cursors.len();
        let cursor = Cursor::Custom(custom_cursors[self.custom_idx].clone());
        self.window.set_cursor(cursor);
    }
source

pub fn set_cursor_icon(&self, icon: CursorIcon)

👎Deprecated: Renamed to set_cursor

Deprecated! Use Window::set_cursor() instead.

source

pub fn set_cursor_position<P: Into<Position>>( &self, position: P ) -> Result<(), ExternalError>

Changes the position of the cursor in window coordinates.

// Specify the position in logical dimensions like this:
window.set_cursor_position(LogicalPosition::new(400.0, 200.0));

// Or specify the position in physical dimensions like this:
window.set_cursor_position(PhysicalPosition::new(400, 200));
§Platform-specific
source

pub fn set_cursor_grab(&self, mode: CursorGrabMode) -> Result<(), ExternalError>

Set grabbing mode on the cursor preventing it from leaving the window.

§Example

First try confining the cursor, and if that fails, try locking it instead.

window
    .set_cursor_grab(CursorGrabMode::Confined)
    .or_else(|_e| window.set_cursor_grab(CursorGrabMode::Locked))
    .unwrap();
Examples found in repository?
examples/window.rs (line 642)
635
636
637
638
639
640
641
642
643
644
645
    fn cycle_cursor_grab(&mut self) {
        self.cursor_grab = match self.cursor_grab {
            CursorGrabMode::None => CursorGrabMode::Confined,
            CursorGrabMode::Confined => CursorGrabMode::Locked,
            CursorGrabMode::Locked => CursorGrabMode::None,
        };
        info!("Changing cursor grab mode to {:?}", self.cursor_grab);
        if let Err(err) = self.window.set_cursor_grab(self.cursor_grab) {
            error!("Error setting cursor grab: {err}");
        }
    }
source

pub fn set_cursor_visible(&self, visible: bool)

Modifies the cursor’s visibility.

If false, this will hide the cursor. If true, this will show the cursor.

§Platform-specific
  • Windows: The cursor is only hidden within the confines of the window.
  • X11: The cursor is only hidden within the confines of the window.
  • Wayland: The cursor is only hidden within the confines of the window.
  • macOS: The cursor is hidden as long as the window has input focus, even if the cursor is outside of the window.
  • iOS / Android: Unsupported.
Examples found in repository?
examples/window.rs (line 610)
608
609
610
611
    fn toggle_cursor_visibility(&mut self) {
        self.cursor_hidden = !self.cursor_hidden;
        self.window.set_cursor_visible(!self.cursor_hidden);
    }
source

pub fn drag_window(&self) -> Result<(), ExternalError>

Moves the window with the left mouse button until the button is released.

There’s no guarantee that this will work unless the left mouse button was pressed immediately before this function is called.

§Platform-specific
  • X11: Un-grabs the cursor.
  • Wayland: Requires the cursor to be inside the window to be dragged.
  • macOS: May prevent the button release event to be triggered.
  • iOS / Android / Web: Always returns an ExternalError::NotSupported.
Examples found in repository?
examples/window.rs (line 751)
750
751
752
753
754
755
756
    fn drag_window(&self) {
        if let Err(err) = self.window.drag_window() {
            info!("Error starting window drag: {err}");
        } else {
            info!("Dragging window Window={:?}", self.window.id());
        }
    }
source

pub fn drag_resize_window( &self, direction: ResizeDirection ) -> Result<(), ExternalError>

Resizes the window with the left mouse button until the button is released.

There’s no guarantee that this will work unless the left mouse button was pressed immediately before this function is called.

§Platform-specific
Examples found in repository?
examples/window.rs (line 801)
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
    fn drag_resize_window(&self) {
        let position = match self.cursor_position {
            Some(position) => position,
            None => {
                info!("Drag-resize requires cursor to be inside the window");
                return;
            },
        };

        let win_size = self.window.inner_size();
        let border_size = BORDER_SIZE * self.window.scale_factor();

        let x_direction = if position.x < border_size {
            ResizeDirection::West
        } else if position.x > (win_size.width as f64 - border_size) {
            ResizeDirection::East
        } else {
            // Use arbitrary direction instead of None for simplicity.
            ResizeDirection::SouthEast
        };

        let y_direction = if position.y < border_size {
            ResizeDirection::North
        } else if position.y > (win_size.height as f64 - border_size) {
            ResizeDirection::South
        } else {
            // Use arbitrary direction instead of None for simplicity.
            ResizeDirection::SouthEast
        };

        let direction = match (x_direction, y_direction) {
            (ResizeDirection::West, ResizeDirection::North) => ResizeDirection::NorthWest,
            (ResizeDirection::West, ResizeDirection::South) => ResizeDirection::SouthWest,
            (ResizeDirection::West, _) => ResizeDirection::West,
            (ResizeDirection::East, ResizeDirection::North) => ResizeDirection::NorthEast,
            (ResizeDirection::East, ResizeDirection::South) => ResizeDirection::SouthEast,
            (ResizeDirection::East, _) => ResizeDirection::East,
            (_, ResizeDirection::South) => ResizeDirection::South,
            (_, ResizeDirection::North) => ResizeDirection::North,
            _ => return,
        };

        if let Err(err) = self.window.drag_resize_window(direction) {
            info!("Error starting window drag-resize: {err}");
        } else {
            info!("Drag-resizing window Window={:?}", self.window.id());
        }
    }
source

pub fn show_window_menu(&self, position: impl Into<Position>)

Show window menu at a specified position .

This is the context menu that is normally shown when interacting with the title bar. This is useful when implementing custom decorations.

§Platform-specific

Android / iOS / macOS / Orbital / Wayland / Web / X11: Unsupported.

Examples found in repository?
examples/window.rs (line 745)
743
744
745
746
747
    fn show_menu(&self) {
        if let Some(position) = self.cursor_position {
            self.window.show_window_menu(position);
        }
    }
source

pub fn set_cursor_hittest(&self, hittest: bool) -> Result<(), ExternalError>

Modifies whether the window catches cursor events.

If true, the window will catch the cursor events. If false, events are passed through the window such that any other window behind it receives them. By default hittest is enabled.

§Platform-specific
source§

impl Window

Monitor info functions.

source

pub fn current_monitor(&self) -> Option<MonitorHandle>

Returns the monitor on which the window currently resides.

Returns None if current monitor can’t be detected.

source

pub fn available_monitors(&self) -> impl Iterator<Item = MonitorHandle>

Returns the list of all the monitors available on the system.

This is the same as ActiveEventLoop::available_monitors, and is provided for convenience.

source

pub fn primary_monitor(&self) -> Option<MonitorHandle>

Returns the primary monitor of the system.

Returns None if it can’t identify any monitor as a primary one.

This is the same as ActiveEventLoop::primary_monitor, and is provided for convenience.

§Platform-specific

Wayland / Web: Always returns None.

Trait Implementations§

source§

impl<W: Borrow<Window>> AsRef<Window> for AnyThread<W>

Available on windows_platform only.
source§

fn as_ref(&self) -> &Window

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl<W: Borrow<Window>> Borrow<Window> for AnyThread<W>

Available on windows_platform only.
source§

fn borrow(&self) -> &Window

Immutably borrows from an owned value. Read more
source§

impl Debug for Window

source§

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

Formats the value using the given formatter. Read more
source§

impl Drop for Window

source§

fn drop(&mut self)

This will close the Window.

See Window for more details.

source§

impl HasDisplayHandle for Window

Available on crate feature rwh_06 only.
source§

fn display_handle(&self) -> Result<DisplayHandle<'_>, HandleError>

Get a handle to the display controller of the windowing system.
source§

impl HasRawDisplayHandle for Window

Available on crate feature rwh_05 only.
source§

fn raw_display_handle(&self) -> RawDisplayHandle

Returns a rwh_05::RawDisplayHandle used by the EventLoop that created a window.

source§

impl HasRawWindowHandle for Window

Available on crate feature rwh_04 only.
source§

impl HasRawWindowHandle for Window

Available on crate feature rwh_05 only.
source§

impl HasWindowHandle for Window

Available on crate feature rwh_06 only.
source§

fn window_handle(&self) -> Result<WindowHandle<'_>, HandleError>

Get a handle to the window.
source§

impl WindowExtAndroid for Window

Available on android_platform only.
source§

fn content_rect(&self) -> Rect

source§

fn config(&self) -> ConfigurationRef

source§

impl WindowExtIOS for Window

Available on ios_platform only.
source§

fn set_scale_factor(&self, scale_factor: f64)

Sets the contentScaleFactor of the underlying UIWindow to scale_factor. Read more
source§

fn set_valid_orientations(&self, valid_orientations: ValidOrientations)

Sets the valid orientations for the Window. Read more
source§

fn set_prefers_home_indicator_hidden(&self, hidden: bool)

Sets whether the Window prefers the home indicator hidden. Read more
source§

fn set_preferred_screen_edges_deferring_system_gestures( &self, edges: ScreenEdge )

Sets the screen edges for which the system gestures will take a lower priority than the application’s touch handling. Read more
source§

fn set_prefers_status_bar_hidden(&self, hidden: bool)

Sets whether the Window prefers the status bar hidden. Read more
source§

fn set_preferred_status_bar_style(&self, status_bar_style: StatusBarStyle)

Sets the preferred status bar style for the Window. Read more
source§

fn recognize_pinch_gesture(&self, should_recognize: bool)

Sets whether the Window should recognize pinch gestures. Read more
source§

fn recognize_pan_gesture( &self, should_recognize: bool, minimum_number_of_touches: u8, maximum_number_of_touches: u8 )

Sets whether the Window should recognize pan gestures. Read more
source§

fn recognize_doubletap_gesture(&self, should_recognize: bool)

Sets whether the Window should recognize double tap gestures. Read more
source§

fn recognize_rotation_gesture(&self, should_recognize: bool)

Sets whether the Window should recognize rotation gestures. Read more
source§

impl WindowExtMacOS for Window

Available on macos_platform only.
source§

fn simple_fullscreen(&self) -> bool

Returns whether or not the window is in simple fullscreen mode.
source§

fn set_simple_fullscreen(&self, fullscreen: bool) -> bool

Toggles a fullscreen mode that doesn’t require a new macOS space. Returns a boolean indicating whether the transition was successful (this won’t work if the window was already in the native fullscreen). Read more
source§

fn has_shadow(&self) -> bool

Returns whether or not the window has shadow.
source§

fn set_has_shadow(&self, has_shadow: bool)

Sets whether or not the window has shadow.
source§

fn set_tabbing_identifier(&self, identifier: &str)

Group windows together by using the same tabbing identifier. Read more
source§

fn tabbing_identifier(&self) -> String

Returns the window’s tabbing identifier.
source§

fn select_next_tab(&self)

Select next tab.
source§

fn select_previous_tab(&self)

Select previous tab.
source§

fn select_tab_at_index(&self, index: usize)

Select the tab with the given index. Read more
source§

fn num_tabs(&self) -> usize

Get the number of tabs in the window tab group.
source§

fn is_document_edited(&self) -> bool

Get the window’s edit state. Read more
source§

fn set_document_edited(&self, edited: bool)

Put the window in a state which indicates a file save is required.
source§

fn set_option_as_alt(&self, option_as_alt: OptionAsAlt)

Set option as alt behavior as described in OptionAsAlt. Read more
source§

fn option_as_alt(&self) -> OptionAsAlt

source§

impl WindowExtStartupNotify for Window

Available on x11_platform or wayland_platform only.
source§

impl WindowExtWebSys for Window

Available on web_platform only.
source§

fn canvas(&self) -> Option<HtmlCanvasElement>

Only returns the canvas if called from inside the window context (the main thread).
source§

fn prevent_default(&self) -> bool

Returns true if calling event.preventDefault() is enabled. Read more
source§

fn set_prevent_default(&self, prevent_default: bool)

Sets whether event.preventDefault() should be called on events on the canvas that have side effects. Read more
source§

impl WindowExtWindows for Window

Available on windows_platform only.
source§

fn set_enable(&self, enabled: bool)

Enables or disables mouse and keyboard input to the specified window. Read more
source§

fn set_taskbar_icon(&self, taskbar_icon: Option<Icon>)

This sets ICON_BIG. A good ceiling here is 256x256.
source§

fn set_skip_taskbar(&self, skip: bool)

Whether to show or hide the window icon in the taskbar.
source§

fn set_undecorated_shadow(&self, shadow: bool)

Shows or hides the background drop shadow for undecorated windows. Read more
source§

fn set_system_backdrop(&self, backdrop_type: BackdropType)

Sets system-drawn backdrop type. Read more
source§

fn set_border_color(&self, color: Option<Color>)

Sets the color of the window border. Read more
source§

fn set_title_background_color(&self, color: Option<Color>)

Sets the background color of the title bar. Read more
source§

fn set_title_text_color(&self, color: Color)

Sets the color of the window title. Read more
source§

fn set_corner_preference(&self, preference: CornerPreference)

Sets the preferred style of the window corners. Read more
source§

unsafe fn window_handle_any_thread( &self ) -> Result<WindowHandle<'_>, HandleError>

Available on crate feature rwh_06 only.
Get the raw window handle for this Window without checking for thread affinity. Read more
source§

impl WindowExtWayland for Window

Available on wayland_platform only.
source§

impl WindowExtX11 for Window

Available on x11_platform only.

Auto Trait Implementations§

§

impl Freeze for Window

§

impl RefUnwindSafe for Window

§

impl Send for Window

§

impl Sync for Window

§

impl Unpin for Window

§

impl UnwindSafe for Window

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> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> HasRawDisplayHandle for T
where T: HasDisplayHandle + ?Sized,

source§

fn raw_display_handle(&self) -> Result<RawDisplayHandle, HandleError>

👎Deprecated: Use HasDisplayHandle instead
source§

impl<T> HasRawWindowHandle for T
where T: HasWindowHandle + ?Sized,

source§

fn raw_window_handle(&self) -> Result<RawWindowHandle, HandleError>

👎Deprecated: Use HasWindowHandle instead
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, U> TryFrom<U> for T
where U: Into<T>,

§

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>,

§

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<W> WindowBorrowExtWindows for W
where W: Borrow<Window>,

source§

unsafe fn any_thread(self) -> AnyThread<Self>

Available on windows_platform only.
Create an object that allows accessing the inner window handle in a thread-unsafe way. Read more
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