Deprecate window creation with stale event loop
Creating window when event loop is not running generally doesn't work, since a bunch of events and sync OS requests can't be processed. This is also an issue on e.g. Android, since window can't be created outside event loop easily. Thus deprecate the window creation when event loop is not running, as well as other resource creation to running event loop. Given that all the examples use the bad pattern of creating the window when event loop is not running and also most example existence is questionable, since they show single thing and the majority of their code is window/event loop initialization, they wore merged into a single example 'window.rs' example that showcases very simple application using winit. Fixes #3399.
This commit is contained in:
parent
19190a95a0
commit
3fb93b4f83
90 changed files with 1594 additions and 3495 deletions
|
|
@ -1,10 +1,3 @@
|
|||
#[cfg(all(
|
||||
feature = "rwh_06",
|
||||
any(x11_platform, macos_platform, windows_platform)
|
||||
))]
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
#[cfg(all(
|
||||
feature = "rwh_06",
|
||||
any(x11_platform, macos_platform, windows_platform)
|
||||
|
|
@ -13,52 +6,51 @@ mod fill;
|
|||
fn main() -> Result<(), impl std::error::Error> {
|
||||
use std::collections::HashMap;
|
||||
|
||||
use winit::{
|
||||
dpi::{LogicalPosition, LogicalSize, Position},
|
||||
event::{ElementState, Event, KeyEvent, WindowEvent},
|
||||
event_loop::{EventLoop, EventLoopWindowTarget},
|
||||
raw_window_handle::HasRawWindowHandle,
|
||||
window::{Window, WindowId},
|
||||
};
|
||||
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;
|
||||
|
||||
fn spawn_child_window(
|
||||
parent: &Window,
|
||||
event_loop: &EventLoopWindowTarget,
|
||||
windows: &mut HashMap<WindowId, 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 builder = Window::builder()
|
||||
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.
|
||||
builder = unsafe { builder.with_parent_window(Some(parent)) };
|
||||
let child_window = builder.build(event_loop).unwrap();
|
||||
window_attributes = unsafe { window_attributes.with_parent_window(Some(parent)) };
|
||||
|
||||
let id = child_window.id();
|
||||
windows.insert(id, child_window);
|
||||
println!("child window created with id: {id:?}");
|
||||
event_loop.create_window(window_attributes).unwrap()
|
||||
}
|
||||
|
||||
let mut windows = HashMap::new();
|
||||
|
||||
let event_loop: EventLoop<()> = EventLoop::new().unwrap();
|
||||
let parent_window = Window::builder()
|
||||
.with_title("parent window")
|
||||
.with_position(Position::Logical(LogicalPosition::new(0.0, 0.0)))
|
||||
.with_inner_size(LogicalSize::new(640.0f32, 480.0f32))
|
||||
.build(&event_loop)
|
||||
.unwrap();
|
||||
let mut parent_window_id = None;
|
||||
|
||||
println!("parent window: {parent_window:?})");
|
||||
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();
|
||||
|
||||
event_loop.run(move |event: Event<()>, elwt| {
|
||||
if let Event::WindowEvent { event, window_id } = event {
|
||||
match event {
|
||||
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();
|
||||
elwt.exit();
|
||||
event_loop.exit();
|
||||
}
|
||||
WindowEvent::CursorEntered { device_id: _ } => {
|
||||
// On x11, println when the cursor entered in a window even if the child window is created
|
||||
|
|
@ -75,7 +67,11 @@ fn main() -> Result<(), impl std::error::Error> {
|
|||
},
|
||||
..
|
||||
} => {
|
||||
spawn_child_window(&parent_window, elwt, &mut windows);
|
||||
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) {
|
||||
|
|
@ -83,15 +79,16 @@ fn main() -> Result<(), impl std::error::Error> {
|
|||
}
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
},
|
||||
_ => (),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(not(all(
|
||||
#[cfg(all(
|
||||
feature = "rwh_06",
|
||||
any(x11_platform, macos_platform, windows_platform)
|
||||
)))]
|
||||
not(any(x11_platform, macos_platform, windows_platform))
|
||||
))]
|
||||
fn main() {
|
||||
panic!("This example is supported only on x11, macOS, and Windows, with the `rwh_06` feature enabled.");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -37,17 +37,14 @@ fn main() -> Result<(), impl std::error::Error> {
|
|||
println!("Press 'Esc' to close the window.");
|
||||
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
let window = Window::builder()
|
||||
.with_title("Press 1, 2, 3 to change control flow mode. Press R to toggle redraw requests.")
|
||||
.build(&event_loop)
|
||||
.unwrap();
|
||||
|
||||
let mut mode = Mode::Wait;
|
||||
let mut request_redraw = false;
|
||||
let mut wait_cancelled = false;
|
||||
let mut close_requested = false;
|
||||
|
||||
event_loop.run(move |event, elwt| {
|
||||
let mut window = None;
|
||||
event_loop.run(move |event, event_loop| {
|
||||
use winit::event::StartCause;
|
||||
println!("{event:?}");
|
||||
match event {
|
||||
|
|
@ -57,6 +54,12 @@ fn main() -> Result<(), impl std::error::Error> {
|
|||
_ => false,
|
||||
}
|
||||
}
|
||||
Event::Resumed => {
|
||||
let window_attributes = Window::default_attributes().with_title(
|
||||
"Press 1, 2, 3 to change control flow mode. Press R to toggle redraw requests.",
|
||||
);
|
||||
window = Some(event_loop.create_window(window_attributes).unwrap());
|
||||
}
|
||||
Event::WindowEvent { event, .. } => match event {
|
||||
WindowEvent::CloseRequested => {
|
||||
close_requested = true;
|
||||
|
|
@ -94,32 +97,34 @@ fn main() -> Result<(), impl std::error::Error> {
|
|||
_ => (),
|
||||
},
|
||||
WindowEvent::RedrawRequested => {
|
||||
fill::fill_window(&window);
|
||||
let window = window.as_ref().unwrap();
|
||||
window.pre_present_notify();
|
||||
fill::fill_window(window);
|
||||
}
|
||||
_ => (),
|
||||
},
|
||||
Event::AboutToWait => {
|
||||
if request_redraw && !wait_cancelled && !close_requested {
|
||||
window.request_redraw();
|
||||
window.as_ref().unwrap().request_redraw();
|
||||
}
|
||||
|
||||
match mode {
|
||||
Mode::Wait => elwt.set_control_flow(ControlFlow::Wait),
|
||||
Mode::Wait => event_loop.set_control_flow(ControlFlow::Wait),
|
||||
Mode::WaitUntil => {
|
||||
if !wait_cancelled {
|
||||
elwt.set_control_flow(ControlFlow::WaitUntil(
|
||||
event_loop.set_control_flow(ControlFlow::WaitUntil(
|
||||
time::Instant::now() + WAIT_TIME,
|
||||
));
|
||||
}
|
||||
}
|
||||
Mode::Poll => {
|
||||
thread::sleep(POLL_SLEEP_TIME);
|
||||
elwt.set_control_flow(ControlFlow::Poll);
|
||||
event_loop.set_control_flow(ControlFlow::Poll);
|
||||
}
|
||||
};
|
||||
|
||||
if close_requested {
|
||||
elwt.exit();
|
||||
event_loop.exit();
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
|
|
|
|||
|
|
@ -1,88 +0,0 @@
|
|||
#![allow(clippy::single_match)]
|
||||
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
event::{ElementState, Event, KeyEvent, WindowEvent},
|
||||
event_loop::EventLoop,
|
||||
window::{CursorIcon, Window},
|
||||
};
|
||||
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
fn main() -> Result<(), impl std::error::Error> {
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
|
||||
let window = Window::builder().build(&event_loop).unwrap();
|
||||
window.set_title("A fantastic window!");
|
||||
|
||||
let mut cursor_idx = 0;
|
||||
|
||||
event_loop.run(move |event, elwt| {
|
||||
if let Event::WindowEvent { event, .. } = event {
|
||||
match event {
|
||||
WindowEvent::KeyboardInput {
|
||||
event:
|
||||
KeyEvent {
|
||||
state: ElementState::Pressed,
|
||||
..
|
||||
},
|
||||
..
|
||||
} => {
|
||||
println!("Setting cursor to \"{:?}\"", CURSORS[cursor_idx]);
|
||||
window.set_cursor(CURSORS[cursor_idx]);
|
||||
if cursor_idx < CURSORS.len() - 1 {
|
||||
cursor_idx += 1;
|
||||
} else {
|
||||
cursor_idx = 0;
|
||||
}
|
||||
}
|
||||
WindowEvent::RedrawRequested => {
|
||||
fill::fill_window(&window);
|
||||
}
|
||||
WindowEvent::CloseRequested => {
|
||||
elwt.exit();
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const CURSORS: &[CursorIcon] = &[
|
||||
CursorIcon::Default,
|
||||
CursorIcon::Crosshair,
|
||||
CursorIcon::Pointer,
|
||||
CursorIcon::Move,
|
||||
CursorIcon::Text,
|
||||
CursorIcon::Wait,
|
||||
CursorIcon::Help,
|
||||
CursorIcon::Progress,
|
||||
CursorIcon::NotAllowed,
|
||||
CursorIcon::ContextMenu,
|
||||
CursorIcon::Cell,
|
||||
CursorIcon::VerticalText,
|
||||
CursorIcon::Alias,
|
||||
CursorIcon::Copy,
|
||||
CursorIcon::NoDrop,
|
||||
CursorIcon::Grab,
|
||||
CursorIcon::Grabbing,
|
||||
CursorIcon::AllScroll,
|
||||
CursorIcon::ZoomIn,
|
||||
CursorIcon::ZoomOut,
|
||||
CursorIcon::EResize,
|
||||
CursorIcon::NResize,
|
||||
CursorIcon::NeResize,
|
||||
CursorIcon::NwResize,
|
||||
CursorIcon::SResize,
|
||||
CursorIcon::SeResize,
|
||||
CursorIcon::SwResize,
|
||||
CursorIcon::WResize,
|
||||
CursorIcon::EwResize,
|
||||
CursorIcon::NsResize,
|
||||
CursorIcon::NeswResize,
|
||||
CursorIcon::NwseResize,
|
||||
CursorIcon::ColResize,
|
||||
CursorIcon::RowResize,
|
||||
];
|
||||
|
|
@ -1,73 +0,0 @@
|
|||
#![allow(clippy::single_match)]
|
||||
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
event::{DeviceEvent, ElementState, Event, KeyEvent, WindowEvent},
|
||||
event_loop::EventLoop,
|
||||
keyboard::{Key, ModifiersState, NamedKey},
|
||||
window::{CursorGrabMode, Window},
|
||||
};
|
||||
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
fn main() -> Result<(), impl std::error::Error> {
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
|
||||
let window = Window::builder()
|
||||
.with_title("Super Cursor Grab'n'Hide Simulator 9000")
|
||||
.build(&event_loop)
|
||||
.unwrap();
|
||||
|
||||
let mut modifiers = ModifiersState::default();
|
||||
|
||||
event_loop.run(move |event, elwt| match event {
|
||||
Event::WindowEvent { event, .. } => match event {
|
||||
WindowEvent::CloseRequested => elwt.exit(),
|
||||
WindowEvent::KeyboardInput {
|
||||
event:
|
||||
KeyEvent {
|
||||
logical_key: key,
|
||||
state: ElementState::Released,
|
||||
..
|
||||
},
|
||||
..
|
||||
} => {
|
||||
let result = match key {
|
||||
Key::Named(NamedKey::Escape) => {
|
||||
elwt.exit();
|
||||
Ok(())
|
||||
}
|
||||
Key::Character(ch) => match ch.to_lowercase().as_str() {
|
||||
"g" => window.set_cursor_grab(CursorGrabMode::Confined),
|
||||
"l" => window.set_cursor_grab(CursorGrabMode::Locked),
|
||||
"a" => window.set_cursor_grab(CursorGrabMode::None),
|
||||
"h" => {
|
||||
window.set_cursor_visible(modifiers.shift_key());
|
||||
Ok(())
|
||||
}
|
||||
_ => Ok(()),
|
||||
},
|
||||
_ => Ok(()),
|
||||
};
|
||||
|
||||
if let Err(err) = result {
|
||||
println!("error: {err}");
|
||||
}
|
||||
}
|
||||
WindowEvent::ModifiersChanged(new) => modifiers = new.state(),
|
||||
WindowEvent::RedrawRequested => fill::fill_window(&window),
|
||||
_ => (),
|
||||
},
|
||||
Event::DeviceEvent { event, .. } => match event {
|
||||
DeviceEvent::MouseMotion { delta } => println!("mouse moved: {delta:?}"),
|
||||
DeviceEvent::Button { button, state } => match state {
|
||||
ElementState::Pressed => println!("mouse button {button} pressed"),
|
||||
ElementState::Released => println!("mouse button {button} released"),
|
||||
},
|
||||
_ => (),
|
||||
},
|
||||
_ => (),
|
||||
})
|
||||
}
|
||||
|
|
@ -1,143 +0,0 @@
|
|||
#![allow(clippy::single_match, clippy::disallowed_methods)]
|
||||
|
||||
#[cfg(not(web_platform))]
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
event::{ElementState, Event, KeyEvent, WindowEvent},
|
||||
event_loop::{EventLoop, EventLoopWindowTarget},
|
||||
keyboard::Key,
|
||||
window::{CursorIcon, CustomCursor, Window},
|
||||
};
|
||||
#[cfg(web_platform)]
|
||||
use {
|
||||
std::sync::atomic::{AtomicU64, Ordering},
|
||||
std::time::Duration,
|
||||
winit::platform::web::CustomCursorExtWebSys,
|
||||
};
|
||||
|
||||
#[cfg(web_platform)]
|
||||
static COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
fn decode_cursor(bytes: &[u8], window_target: &EventLoopWindowTarget) -> CustomCursor {
|
||||
let img = image::load_from_memory(bytes).unwrap().to_rgba8();
|
||||
let samples = img.into_flat_samples();
|
||||
let (_, w, h) = samples.extents();
|
||||
let (w, h) = (w as u16, h as u16);
|
||||
let builder = CustomCursor::from_rgba(samples.samples, w, h, w / 2, h / 2).unwrap();
|
||||
|
||||
builder.build(window_target)
|
||||
}
|
||||
|
||||
#[cfg(not(web_platform))]
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
fn main() -> Result<(), impl std::error::Error> {
|
||||
#[cfg(not(web_platform))]
|
||||
SimpleLogger::new()
|
||||
.with_level(log::LevelFilter::Info)
|
||||
.init()
|
||||
.unwrap();
|
||||
#[cfg(web_platform)]
|
||||
console_log::init_with_level(log::Level::Debug).unwrap();
|
||||
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
let builder = Window::builder().with_title("A fantastic window!");
|
||||
#[cfg(web_platform)]
|
||||
let builder = {
|
||||
use winit::platform::web::WindowBuilderExtWebSys;
|
||||
builder.with_append(true)
|
||||
};
|
||||
let window = builder.build(&event_loop).unwrap();
|
||||
|
||||
let mut cursor_idx = 0;
|
||||
let mut cursor_visible = true;
|
||||
|
||||
let custom_cursors = [
|
||||
decode_cursor(include_bytes!("data/cross.png"), &event_loop),
|
||||
decode_cursor(include_bytes!("data/cross2.png"), &event_loop),
|
||||
decode_cursor(include_bytes!("data/gradient.png"), &event_loop),
|
||||
];
|
||||
|
||||
event_loop.run(move |event, _elwt| match event {
|
||||
Event::WindowEvent { event, .. } => match event {
|
||||
WindowEvent::KeyboardInput {
|
||||
event:
|
||||
KeyEvent {
|
||||
state: ElementState::Pressed,
|
||||
logical_key: key,
|
||||
..
|
||||
},
|
||||
..
|
||||
} => match key.as_ref() {
|
||||
Key::Character("1") => {
|
||||
log::debug!("Setting cursor to {:?}", cursor_idx);
|
||||
window.set_cursor(custom_cursors[cursor_idx].clone());
|
||||
cursor_idx = (cursor_idx + 1) % 3;
|
||||
}
|
||||
Key::Character("2") => {
|
||||
log::debug!("Setting cursor icon to default");
|
||||
window.set_cursor(CursorIcon::default());
|
||||
}
|
||||
Key::Character("3") => {
|
||||
cursor_visible = !cursor_visible;
|
||||
log::debug!("Setting cursor visibility to {:?}", cursor_visible);
|
||||
window.set_cursor_visible(cursor_visible);
|
||||
}
|
||||
#[cfg(web_platform)]
|
||||
Key::Character("4") => {
|
||||
log::debug!("Setting cursor to a random image from an URL");
|
||||
window.set_cursor(
|
||||
CustomCursor::from_url(
|
||||
format!(
|
||||
"https://picsum.photos/128?random={}",
|
||||
COUNTER.fetch_add(1, Ordering::Relaxed)
|
||||
),
|
||||
64,
|
||||
64,
|
||||
)
|
||||
.build(_elwt),
|
||||
);
|
||||
}
|
||||
#[cfg(web_platform)]
|
||||
Key::Character("5") => {
|
||||
log::debug!("Setting cursor to an animation");
|
||||
window.set_cursor(
|
||||
CustomCursor::from_animation(
|
||||
Duration::from_secs(3),
|
||||
vec![
|
||||
custom_cursors[0].clone(),
|
||||
custom_cursors[1].clone(),
|
||||
CustomCursor::from_url(
|
||||
format!(
|
||||
"https://picsum.photos/128?random={}",
|
||||
COUNTER.fetch_add(1, Ordering::Relaxed)
|
||||
),
|
||||
64,
|
||||
64,
|
||||
)
|
||||
.build(_elwt),
|
||||
],
|
||||
)
|
||||
.unwrap()
|
||||
.build(_elwt),
|
||||
);
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
WindowEvent::RedrawRequested => {
|
||||
#[cfg(not(web_platform))]
|
||||
fill::fill_window(&window);
|
||||
}
|
||||
WindowEvent::CloseRequested => {
|
||||
#[cfg(not(web_platform))]
|
||||
_elwt.exit();
|
||||
}
|
||||
_ => (),
|
||||
},
|
||||
Event::AboutToWait => {
|
||||
window.request_redraw();
|
||||
}
|
||||
_ => {}
|
||||
})
|
||||
}
|
||||
|
|
@ -1,60 +0,0 @@
|
|||
#![allow(clippy::single_match)]
|
||||
|
||||
#[cfg(not(web_platform))]
|
||||
fn main() -> Result<(), impl std::error::Error> {
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
event::{Event, WindowEvent},
|
||||
event_loop::EventLoop,
|
||||
window::Window,
|
||||
};
|
||||
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum CustomEvent {
|
||||
Timer,
|
||||
}
|
||||
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::<CustomEvent>::with_user_event().build().unwrap();
|
||||
|
||||
let window = Window::builder()
|
||||
.with_title("A fantastic window!")
|
||||
.build(&event_loop)
|
||||
.unwrap();
|
||||
|
||||
// `EventLoopProxy` allows you to dispatch custom events to the main Winit event
|
||||
// loop from any thread.
|
||||
let event_loop_proxy = event_loop.create_proxy();
|
||||
|
||||
std::thread::spawn(move || {
|
||||
// Wake up the `event_loop` once every second and dispatch a custom event
|
||||
// from a different thread.
|
||||
loop {
|
||||
std::thread::sleep(std::time::Duration::from_secs(1));
|
||||
event_loop_proxy.send_event(CustomEvent::Timer).ok();
|
||||
}
|
||||
});
|
||||
|
||||
event_loop.run(move |event, elwt| match event {
|
||||
Event::UserEvent(event) => println!("user event: {event:?}"),
|
||||
Event::WindowEvent {
|
||||
event: WindowEvent::CloseRequested,
|
||||
..
|
||||
} => elwt.exit(),
|
||||
Event::WindowEvent {
|
||||
event: WindowEvent::RedrawRequested,
|
||||
..
|
||||
} => {
|
||||
fill::fill_window(&window);
|
||||
}
|
||||
_ => (),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(web_platform)]
|
||||
fn main() {
|
||||
panic!("This example is not supported on web.");
|
||||
}
|
||||
|
Before Width: | Height: | Size: 2.9 KiB After Width: | Height: | Size: 2.9 KiB |
|
|
@ -1,105 +0,0 @@
|
|||
#![allow(clippy::single_match)]
|
||||
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
event::{ElementState, Event, KeyEvent, MouseButton, StartCause, WindowEvent},
|
||||
event_loop::EventLoop,
|
||||
keyboard::Key,
|
||||
window::{Window, WindowId},
|
||||
};
|
||||
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
fn main() -> Result<(), impl std::error::Error> {
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
|
||||
let window_1 = Window::builder().build(&event_loop).unwrap();
|
||||
let window_2 = Window::builder().build(&event_loop).unwrap();
|
||||
|
||||
let mut switched = false;
|
||||
let mut entered_id = window_2.id();
|
||||
let mut cursor_location = None;
|
||||
|
||||
event_loop.run(move |event, elwt| match event {
|
||||
Event::NewEvents(StartCause::Init) => {
|
||||
eprintln!("Switch which window is to be dragged by pressing \"x\".")
|
||||
}
|
||||
Event::WindowEvent { event, window_id } => match event {
|
||||
WindowEvent::CloseRequested => elwt.exit(),
|
||||
WindowEvent::CursorMoved { position, .. } => cursor_location = Some(position),
|
||||
WindowEvent::MouseInput { state, button, .. } => {
|
||||
let window = if (window_id == window_1.id() && switched)
|
||||
|| (window_id == window_2.id() && !switched)
|
||||
{
|
||||
&window_2
|
||||
} else {
|
||||
&window_1
|
||||
};
|
||||
|
||||
match (button, state) {
|
||||
(MouseButton::Left, ElementState::Pressed) => window.drag_window().unwrap(),
|
||||
(MouseButton::Right, ElementState::Released) => {
|
||||
if let Some(position) = cursor_location {
|
||||
window.show_window_menu(position);
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
WindowEvent::CursorEntered { .. } => {
|
||||
entered_id = window_id;
|
||||
name_windows(entered_id, switched, &window_1, &window_2)
|
||||
}
|
||||
WindowEvent::KeyboardInput {
|
||||
event:
|
||||
KeyEvent {
|
||||
state: ElementState::Released,
|
||||
logical_key: Key::Character(c),
|
||||
..
|
||||
},
|
||||
..
|
||||
} => match c.as_str() {
|
||||
"x" => {
|
||||
switched = !switched;
|
||||
name_windows(entered_id, switched, &window_1, &window_2);
|
||||
println!("Switched!")
|
||||
}
|
||||
"d" => {
|
||||
let window = if (window_id == window_1.id() && switched)
|
||||
|| (window_id == window_2.id() && !switched)
|
||||
{
|
||||
&window_2
|
||||
} else {
|
||||
&window_1
|
||||
};
|
||||
|
||||
window.set_decorations(!window.is_decorated());
|
||||
}
|
||||
_ => (),
|
||||
},
|
||||
WindowEvent::RedrawRequested => {
|
||||
if window_id == window_1.id() {
|
||||
fill::fill_window(&window_1);
|
||||
} else if window_id == window_2.id() {
|
||||
fill::fill_window(&window_2);
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
},
|
||||
|
||||
_ => (),
|
||||
})
|
||||
}
|
||||
|
||||
fn name_windows(window_id: WindowId, switched: bool, window_1: &Window, window_2: &Window) {
|
||||
let (drag_target, other) =
|
||||
if (window_id == window_1.id() && switched) || (window_id == window_2.id() && !switched) {
|
||||
(&window_2, &window_1)
|
||||
} else {
|
||||
(&window_1, &window_2)
|
||||
};
|
||||
drag_target.set_title("drag target");
|
||||
other.set_title("winit window");
|
||||
}
|
||||
|
|
@ -1,56 +0,0 @@
|
|||
#![allow(clippy::single_match)]
|
||||
|
||||
//! Example for focusing a window.
|
||||
|
||||
use simple_logger::SimpleLogger;
|
||||
#[cfg(not(web_platform))]
|
||||
use std::time;
|
||||
#[cfg(web_platform)]
|
||||
use web_time as time;
|
||||
use winit::{
|
||||
event::{Event, StartCause, WindowEvent},
|
||||
event_loop::EventLoop,
|
||||
window::Window,
|
||||
};
|
||||
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
fn main() -> Result<(), impl std::error::Error> {
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
|
||||
let window = Window::builder()
|
||||
.with_title("A fantastic window!")
|
||||
.with_inner_size(winit::dpi::LogicalSize::new(128.0, 128.0))
|
||||
.build(&event_loop)
|
||||
.unwrap();
|
||||
|
||||
let mut deadline = time::Instant::now() + time::Duration::from_secs(3);
|
||||
event_loop.run(move |event, elwt| {
|
||||
match event {
|
||||
Event::NewEvents(StartCause::ResumeTimeReached { .. }) => {
|
||||
// Timeout reached; focus the window.
|
||||
println!("Re-focusing the window.");
|
||||
deadline += time::Duration::from_secs(3);
|
||||
window.focus_window();
|
||||
}
|
||||
Event::WindowEvent { event, window_id } if window_id == window.id() => match event {
|
||||
WindowEvent::CloseRequested => elwt.exit(),
|
||||
WindowEvent::RedrawRequested => {
|
||||
// Notify the windowing system that we'll be presenting to the window.
|
||||
window.pre_present_notify();
|
||||
fill::fill_window(&window);
|
||||
}
|
||||
_ => (),
|
||||
},
|
||||
Event::AboutToWait => {
|
||||
window.request_redraw();
|
||||
}
|
||||
|
||||
_ => (),
|
||||
}
|
||||
|
||||
elwt.set_control_flow(winit::event_loop::ControlFlow::WaitUntil(deadline));
|
||||
})
|
||||
}
|
||||
|
|
@ -1,163 +0,0 @@
|
|||
#![allow(clippy::single_match)]
|
||||
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::dpi::LogicalSize;
|
||||
use winit::event::{ElementState, Event, KeyEvent, WindowEvent};
|
||||
use winit::event_loop::EventLoop;
|
||||
use winit::keyboard::{Key, NamedKey};
|
||||
use winit::window::{Fullscreen, Window};
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
use winit::platform::macos::WindowExtMacOS;
|
||||
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
fn main() -> Result<(), impl std::error::Error> {
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
|
||||
let mut decorations = true;
|
||||
let mut minimized = false;
|
||||
let mut with_min_size = false;
|
||||
let mut with_max_size = false;
|
||||
|
||||
let window = Window::builder()
|
||||
.with_title("Hello world!")
|
||||
.build(&event_loop)
|
||||
.unwrap();
|
||||
|
||||
let mut monitor_index = 0;
|
||||
let mut monitor = event_loop
|
||||
.available_monitors()
|
||||
.next()
|
||||
.expect("no monitor found!");
|
||||
println!("Monitor: {:?}", monitor.name());
|
||||
|
||||
let mut mode_index = 0;
|
||||
let mut mode = monitor.video_modes().next().expect("no mode found");
|
||||
println!("Mode: {mode}");
|
||||
|
||||
println!("Keys:");
|
||||
println!("- Esc\tExit");
|
||||
println!("- F\tToggle exclusive fullscreen mode");
|
||||
println!("- B\tToggle borderless mode");
|
||||
#[cfg(target_os = "macos")]
|
||||
println!("- C\tToggle simple fullscreen mode");
|
||||
println!("- S\tNext screen");
|
||||
println!("- M\tNext mode for this screen");
|
||||
println!("- D\tToggle window decorations");
|
||||
println!("- X\tMaximize window");
|
||||
println!("- Z\tMinimize window");
|
||||
println!("- I\tToggle mIn size limit");
|
||||
println!("- A\tToggle mAx size limit");
|
||||
|
||||
event_loop.run(move |event, elwt| {
|
||||
if let Event::WindowEvent { event, .. } = event {
|
||||
match event {
|
||||
WindowEvent::CloseRequested => elwt.exit(),
|
||||
WindowEvent::KeyboardInput {
|
||||
event:
|
||||
KeyEvent {
|
||||
logical_key: key,
|
||||
state: ElementState::Pressed,
|
||||
..
|
||||
},
|
||||
..
|
||||
} => match key {
|
||||
Key::Named(NamedKey::Escape) => elwt.exit(),
|
||||
// WARNING: Consider using `key_without_modifiers()` if available on your platform.
|
||||
// See the `key_binding` example
|
||||
Key::Character(ch) => match ch.to_lowercase().as_str() {
|
||||
"f" | "b" if window.fullscreen().is_some() => {
|
||||
window.set_fullscreen(None);
|
||||
}
|
||||
"f" => {
|
||||
let fullscreen = Some(Fullscreen::Exclusive(mode.clone()));
|
||||
println!("Setting mode: {fullscreen:?}");
|
||||
window.set_fullscreen(fullscreen);
|
||||
}
|
||||
"b" => {
|
||||
let fullscreen = Some(Fullscreen::Borderless(Some(monitor.clone())));
|
||||
println!("Setting mode: {fullscreen:?}");
|
||||
window.set_fullscreen(fullscreen);
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
"c" => {
|
||||
window.set_simple_fullscreen(!window.simple_fullscreen());
|
||||
}
|
||||
"s" => {
|
||||
monitor_index += 1;
|
||||
if let Some(mon) = elwt.available_monitors().nth(monitor_index) {
|
||||
monitor = mon;
|
||||
} else {
|
||||
monitor_index = 0;
|
||||
monitor =
|
||||
elwt.available_monitors().next().expect("no monitor found!");
|
||||
}
|
||||
println!("Monitor: {:?}", monitor.name());
|
||||
|
||||
mode_index = 0;
|
||||
mode = monitor.video_modes().next().expect("no mode found");
|
||||
println!("Mode: {mode}");
|
||||
}
|
||||
"m" => {
|
||||
mode_index += 1;
|
||||
if let Some(m) = monitor.video_modes().nth(mode_index) {
|
||||
mode = m;
|
||||
} else {
|
||||
mode_index = 0;
|
||||
mode = monitor.video_modes().next().expect("no mode found");
|
||||
}
|
||||
println!("Mode: {mode}");
|
||||
}
|
||||
"d" => {
|
||||
decorations = !decorations;
|
||||
window.set_decorations(decorations);
|
||||
}
|
||||
"x" => {
|
||||
let is_maximized = window.is_maximized();
|
||||
window.set_maximized(!is_maximized);
|
||||
}
|
||||
"z" => {
|
||||
minimized = !minimized;
|
||||
window.set_minimized(minimized);
|
||||
}
|
||||
"i" => {
|
||||
with_min_size = !with_min_size;
|
||||
let min_size = if with_min_size {
|
||||
Some(LogicalSize::new(100, 100))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
window.set_min_inner_size(min_size);
|
||||
eprintln!(
|
||||
"Min: {with_min_size}: {min_size:?} => {:?}",
|
||||
window.inner_size()
|
||||
);
|
||||
}
|
||||
"a" => {
|
||||
with_max_size = !with_max_size;
|
||||
let max_size = if with_max_size {
|
||||
Some(LogicalSize::new(200, 200))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
window.set_max_inner_size(max_size);
|
||||
eprintln!(
|
||||
"Max: {with_max_size}: {max_size:?} => {:?}",
|
||||
window.inner_size()
|
||||
);
|
||||
}
|
||||
_ => (),
|
||||
},
|
||||
_ => (),
|
||||
},
|
||||
WindowEvent::RedrawRequested => {
|
||||
fill::fill_window(&window);
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
@ -1,86 +0,0 @@
|
|||
#![allow(clippy::single_match)]
|
||||
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
event::{ElementState, Event, KeyEvent, WindowEvent},
|
||||
event_loop::EventLoop,
|
||||
keyboard::Key,
|
||||
window::Window,
|
||||
};
|
||||
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
fn main() -> Result<(), impl std::error::Error> {
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
|
||||
let window = Window::builder()
|
||||
.with_title("Your faithful window")
|
||||
.build(&event_loop)
|
||||
.unwrap();
|
||||
|
||||
let mut close_requested = false;
|
||||
|
||||
event_loop.run(move |event, elwt| {
|
||||
if let Event::WindowEvent { event, .. } = event {
|
||||
match event {
|
||||
WindowEvent::CloseRequested => {
|
||||
// `CloseRequested` is sent when the close button on the window is pressed (or
|
||||
// through whatever other mechanisms the window manager provides for closing a
|
||||
// window). If you don't handle this event, the close button won't actually do
|
||||
// anything.
|
||||
|
||||
// A common thing to do here is prompt the user if they have unsaved work.
|
||||
// Creating a proper dialog box for that is far beyond the scope of this
|
||||
// example, so here we'll just respond to the Y and N keys.
|
||||
println!("Are you ready to bid your window farewell? [Y/N]");
|
||||
close_requested = true;
|
||||
|
||||
// In applications where you can safely close the window without further
|
||||
// action from the user, this is generally where you'd handle cleanup before
|
||||
// closing the window. How to close the window is detailed in the handler for
|
||||
// the Y key.
|
||||
}
|
||||
WindowEvent::KeyboardInput {
|
||||
event:
|
||||
KeyEvent {
|
||||
logical_key: key,
|
||||
state: ElementState::Released,
|
||||
..
|
||||
},
|
||||
..
|
||||
} => {
|
||||
// WARNING: Consider using `key_without_modifiers()` if available on your platform.
|
||||
// See the `key_binding` example
|
||||
match key.as_ref() {
|
||||
Key::Character("y") => {
|
||||
if close_requested {
|
||||
// This is where you'll want to do any cleanup you need.
|
||||
println!("Buh-bye!");
|
||||
|
||||
// For a single-window application like this, you'd normally just
|
||||
// break out of the event loop here. If you wanted to keep running the
|
||||
// event loop (i.e. if it's a multi-window application), you need to
|
||||
// drop the window. That closes it, and results in `Destroyed` being
|
||||
// sent.
|
||||
elwt.exit();
|
||||
}
|
||||
}
|
||||
Key::Character("n") => {
|
||||
if close_requested {
|
||||
println!("Your window will continue to stay by your side.");
|
||||
close_requested = false;
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
WindowEvent::RedrawRequested => {
|
||||
fill::fill_window(&window);
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
@ -1,94 +0,0 @@
|
|||
#![allow(clippy::single_match)]
|
||||
|
||||
use log::LevelFilter;
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
dpi::{PhysicalPosition, PhysicalSize},
|
||||
event::{ElementState, Event, Ime, WindowEvent},
|
||||
event_loop::EventLoop,
|
||||
keyboard::NamedKey,
|
||||
window::{ImePurpose, Window},
|
||||
};
|
||||
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
fn main() -> Result<(), impl std::error::Error> {
|
||||
SimpleLogger::new()
|
||||
.with_level(LevelFilter::Trace)
|
||||
.init()
|
||||
.unwrap();
|
||||
|
||||
println!("IME position will system default");
|
||||
println!("Click to set IME position to cursor's");
|
||||
println!("Press F2 to toggle IME. See the documentation of `set_ime_allowed` for more info");
|
||||
println!("Press F3 to cycle through IME purposes.");
|
||||
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
|
||||
let window = Window::builder()
|
||||
.with_inner_size(winit::dpi::LogicalSize::new(256f64, 128f64))
|
||||
.build(&event_loop)
|
||||
.unwrap();
|
||||
|
||||
let mut ime_purpose = ImePurpose::Normal;
|
||||
let mut ime_allowed = true;
|
||||
window.set_ime_allowed(ime_allowed);
|
||||
|
||||
let mut may_show_ime = false;
|
||||
let mut cursor_position = PhysicalPosition::new(0.0, 0.0);
|
||||
let mut ime_pos = PhysicalPosition::new(0.0, 0.0);
|
||||
|
||||
event_loop.run(move |event, elwt| {
|
||||
if let Event::WindowEvent { event, .. } = event {
|
||||
match event {
|
||||
WindowEvent::CloseRequested => elwt.exit(),
|
||||
WindowEvent::CursorMoved { position, .. } => {
|
||||
cursor_position = position;
|
||||
}
|
||||
WindowEvent::MouseInput {
|
||||
state: ElementState::Released,
|
||||
..
|
||||
} => {
|
||||
println!(
|
||||
"Setting ime position to {}, {}",
|
||||
cursor_position.x, cursor_position.y
|
||||
);
|
||||
ime_pos = cursor_position;
|
||||
if may_show_ime {
|
||||
window.set_ime_cursor_area(ime_pos, PhysicalSize::new(10, 10));
|
||||
}
|
||||
}
|
||||
WindowEvent::Ime(event) => {
|
||||
println!("{event:?}");
|
||||
may_show_ime = event != Ime::Disabled;
|
||||
if may_show_ime {
|
||||
window.set_ime_cursor_area(ime_pos, PhysicalSize::new(10, 10));
|
||||
}
|
||||
}
|
||||
WindowEvent::KeyboardInput { event, .. } => {
|
||||
println!("key: {event:?}");
|
||||
|
||||
if event.state == ElementState::Pressed && event.logical_key == NamedKey::F2 {
|
||||
ime_allowed = !ime_allowed;
|
||||
window.set_ime_allowed(ime_allowed);
|
||||
println!("\nIME allowed: {ime_allowed}\n");
|
||||
}
|
||||
if event.state == ElementState::Pressed && event.logical_key == NamedKey::F3 {
|
||||
ime_purpose = match ime_purpose {
|
||||
ImePurpose::Normal => ImePurpose::Password,
|
||||
ImePurpose::Password => ImePurpose::Terminal,
|
||||
_ => ImePurpose::Normal,
|
||||
};
|
||||
window.set_ime_purpose(ime_purpose);
|
||||
println!("\nIME purpose: {ime_purpose:?}\n");
|
||||
}
|
||||
}
|
||||
WindowEvent::RedrawRequested => {
|
||||
fill::fill_window(&window);
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
@ -1,62 +0,0 @@
|
|||
#![allow(clippy::single_match)]
|
||||
|
||||
#[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))]
|
||||
use winit::{
|
||||
dpi::LogicalSize,
|
||||
event::{ElementState, Event, WindowEvent},
|
||||
event_loop::EventLoop,
|
||||
keyboard::{Key, ModifiersState},
|
||||
// WARNING: This is not available on all platforms (for example on the web).
|
||||
platform::modifier_supplement::KeyEventExtModifierSupplement,
|
||||
window::Window,
|
||||
};
|
||||
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
|
||||
fn main() {
|
||||
println!("This example is not supported on this platform");
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos", target_os = "windows", target_os = "linux"))]
|
||||
fn main() -> Result<(), impl std::error::Error> {
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
simple_logger::SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
|
||||
let window = Window::builder()
|
||||
.with_inner_size(LogicalSize::new(400.0, 200.0))
|
||||
.build(&event_loop)
|
||||
.unwrap();
|
||||
|
||||
let mut modifiers = ModifiersState::default();
|
||||
|
||||
event_loop.run(move |event, elwt| {
|
||||
if let Event::WindowEvent { event, .. } = event {
|
||||
match event {
|
||||
WindowEvent::CloseRequested => elwt.exit(),
|
||||
WindowEvent::ModifiersChanged(new) => {
|
||||
modifiers = new.state();
|
||||
}
|
||||
WindowEvent::KeyboardInput { event, .. } => {
|
||||
if event.state == ElementState::Pressed && !event.repeat {
|
||||
match event.key_without_modifiers().as_ref() {
|
||||
Key::Character("1") => {
|
||||
if modifiers.shift_key() {
|
||||
println!("Shift + 1 | logical_key: {:?}", event.logical_key);
|
||||
} else {
|
||||
println!("1");
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
WindowEvent::RedrawRequested => {
|
||||
fill::fill_window(&window);
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
};
|
||||
})
|
||||
}
|
||||
|
|
@ -1,58 +0,0 @@
|
|||
#![allow(clippy::single_match)]
|
||||
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::dpi::{PhysicalPosition, PhysicalSize};
|
||||
use winit::monitor::MonitorHandle;
|
||||
use winit::{event_loop::EventLoop, window::Window};
|
||||
|
||||
fn main() {
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
let window = Window::builder().build(&event_loop).unwrap();
|
||||
|
||||
if let Some(mon) = window.primary_monitor() {
|
||||
print_info("Primary output", mon);
|
||||
}
|
||||
|
||||
for mon in window.available_monitors() {
|
||||
if Some(&mon) == window.primary_monitor().as_ref() {
|
||||
continue;
|
||||
}
|
||||
|
||||
println!();
|
||||
print_info("Output", mon);
|
||||
}
|
||||
}
|
||||
|
||||
fn print_info(intro: &str, monitor: MonitorHandle) {
|
||||
if let Some(name) = monitor.name() {
|
||||
println!("{intro}: {name}");
|
||||
} else {
|
||||
println!("{intro}: [no name]");
|
||||
}
|
||||
|
||||
let PhysicalSize { width, height } = monitor.size();
|
||||
print!(" Current mode: {width}x{height}");
|
||||
if let Some(m_hz) = monitor.refresh_rate_millihertz() {
|
||||
println!(" @ {}.{} Hz", m_hz / 1000, m_hz % 1000);
|
||||
} else {
|
||||
println!();
|
||||
}
|
||||
|
||||
let PhysicalPosition { x, y } = monitor.position();
|
||||
println!(" Position: {x},{y}");
|
||||
|
||||
println!(" Scale factor: {}", monitor.scale_factor());
|
||||
|
||||
println!(" 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();
|
||||
println!(
|
||||
" {width}x{height}x{bits} @ {}.{} Hz",
|
||||
m_hz / 1000,
|
||||
m_hz % 1000
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,65 +0,0 @@
|
|||
#![allow(clippy::single_match)]
|
||||
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
event::{Event, WindowEvent},
|
||||
event_loop::EventLoop,
|
||||
window::Window,
|
||||
};
|
||||
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
fn main() -> Result<(), impl std::error::Error> {
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
|
||||
let window = Window::builder()
|
||||
.with_title("Mouse Wheel events")
|
||||
.build(&event_loop)
|
||||
.unwrap();
|
||||
|
||||
println!(
|
||||
r"
|
||||
When using so called 'natural scrolling' (scrolling that acts like on a touch screen), this is what to expect:
|
||||
|
||||
Moving your finger downwards on a scroll wheel should make the window move down, and you should see a positive Y scroll value.
|
||||
|
||||
When moving fingers on a trackpad down and to the right, you should see positive X and Y deltas, and the window should move down and to the right.
|
||||
|
||||
With reverse scrolling, you should see the inverse behavior.
|
||||
|
||||
In both cases the example window should move like the content of a scroll area in any other application.
|
||||
|
||||
In other words, the deltas indicate the direction in which to move the content (in this case the window)."
|
||||
);
|
||||
|
||||
event_loop.run(move |event, elwt| {
|
||||
if let Event::WindowEvent { event, .. } = event {
|
||||
match event {
|
||||
WindowEvent::CloseRequested => elwt.exit(),
|
||||
WindowEvent::MouseWheel { delta, .. } => match delta {
|
||||
winit::event::MouseScrollDelta::LineDelta(x, y) => {
|
||||
println!("mouse wheel Line Delta: ({x},{y})");
|
||||
let pixels_per_line = 120.0;
|
||||
let mut pos = window.outer_position().unwrap();
|
||||
pos.x += (x * pixels_per_line) as i32;
|
||||
pos.y += (y * pixels_per_line) as i32;
|
||||
window.set_outer_position(pos)
|
||||
}
|
||||
winit::event::MouseScrollDelta::PixelDelta(p) => {
|
||||
println!("mouse wheel Pixel Delta: ({},{})", p.x, p.y);
|
||||
let mut pos = window.outer_position().unwrap();
|
||||
pos.x += p.x as i32;
|
||||
pos.y += p.y as i32;
|
||||
window.set_outer_position(pos)
|
||||
}
|
||||
},
|
||||
WindowEvent::RedrawRequested => {
|
||||
fill::fill_window(&window);
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
@ -1,211 +0,0 @@
|
|||
#![allow(clippy::single_match)]
|
||||
|
||||
#[cfg(not(web_platform))]
|
||||
fn main() -> Result<(), impl std::error::Error> {
|
||||
use std::{collections::HashMap, sync::mpsc, thread, time::Duration};
|
||||
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
dpi::{PhysicalPosition, PhysicalSize, Position, Size},
|
||||
event::{ElementState, Event, KeyEvent, WindowEvent},
|
||||
event_loop::EventLoop,
|
||||
keyboard::{Key, ModifiersState, NamedKey},
|
||||
window::{CursorGrabMode, CursorIcon, Fullscreen, Window, WindowLevel},
|
||||
};
|
||||
|
||||
const WINDOW_COUNT: usize = 3;
|
||||
const WINDOW_SIZE: PhysicalSize<u32> = PhysicalSize::new(600, 400);
|
||||
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
let mut window_senders = HashMap::with_capacity(WINDOW_COUNT);
|
||||
for _ in 0..WINDOW_COUNT {
|
||||
let window = Window::builder()
|
||||
.with_inner_size(WINDOW_SIZE)
|
||||
.build(&event_loop)
|
||||
.unwrap();
|
||||
|
||||
let mut video_modes: Vec<_> = window.current_monitor().unwrap().video_modes().collect();
|
||||
let mut video_mode_id = 0usize;
|
||||
|
||||
let (tx, rx) = mpsc::channel();
|
||||
window_senders.insert(window.id(), tx);
|
||||
let mut modifiers = ModifiersState::default();
|
||||
thread::spawn(move || {
|
||||
while let Ok(event) = rx.recv() {
|
||||
match event {
|
||||
WindowEvent::Moved { .. } => {
|
||||
// We need to update our chosen video mode if the window
|
||||
// was moved to an another monitor, so that the window
|
||||
// appears on this monitor instead when we go fullscreen
|
||||
let previous_video_mode = video_modes.get(video_mode_id).cloned();
|
||||
video_modes = window.current_monitor().unwrap().video_modes().collect();
|
||||
video_mode_id = video_mode_id.min(video_modes.len());
|
||||
let video_mode = video_modes.get(video_mode_id);
|
||||
|
||||
// Different monitors may support different video modes,
|
||||
// and the index we chose previously may now point to a
|
||||
// completely different video mode, so notify the user
|
||||
if video_mode != previous_video_mode.as_ref() {
|
||||
println!(
|
||||
"Window moved to another monitor, picked video mode: {}",
|
||||
video_modes.get(video_mode_id).unwrap()
|
||||
);
|
||||
}
|
||||
}
|
||||
WindowEvent::ModifiersChanged(new) => {
|
||||
modifiers = new.state();
|
||||
}
|
||||
WindowEvent::KeyboardInput {
|
||||
event:
|
||||
KeyEvent {
|
||||
state: ElementState::Released,
|
||||
logical_key: key,
|
||||
..
|
||||
},
|
||||
..
|
||||
} => {
|
||||
use NamedKey::{ArrowLeft, ArrowRight};
|
||||
window.set_title(&format!("{key:?}"));
|
||||
let state = !modifiers.shift_key();
|
||||
match key {
|
||||
// Cycle through video modes
|
||||
Key::Named(ArrowRight) | Key::Named(ArrowLeft) => {
|
||||
if key == ArrowLeft {
|
||||
video_mode_id = video_mode_id.saturating_sub(1);
|
||||
} else if key == ArrowRight {
|
||||
video_mode_id = (video_modes.len() - 1).min(video_mode_id + 1);
|
||||
}
|
||||
println!("Picking video mode: {}", video_modes[video_mode_id]);
|
||||
}
|
||||
// WARNING: Consider using `key_without_modifiers()` if available on your platform.
|
||||
// See the `key_binding` example
|
||||
Key::Character(ch) => match ch.to_lowercase().as_str() {
|
||||
"1" => window.set_window_level(WindowLevel::AlwaysOnTop),
|
||||
"2" => window.set_window_level(WindowLevel::AlwaysOnBottom),
|
||||
"3" => window.set_window_level(WindowLevel::Normal),
|
||||
"c" => window.set_cursor(match state {
|
||||
true => CursorIcon::Progress,
|
||||
false => CursorIcon::Default,
|
||||
}),
|
||||
"d" => window.set_decorations(!state),
|
||||
"f" => window.set_fullscreen(match (state, modifiers.alt_key()) {
|
||||
(true, false) => Some(Fullscreen::Borderless(None)),
|
||||
(true, true) => Some(Fullscreen::Exclusive(
|
||||
video_modes[video_mode_id].clone(),
|
||||
)),
|
||||
(false, _) => None,
|
||||
}),
|
||||
ch @ ("g" | "l") => {
|
||||
let mode = match (ch, state) {
|
||||
("l", true) => CursorGrabMode::Locked,
|
||||
("g", true) => CursorGrabMode::Confined,
|
||||
(_, _) => CursorGrabMode::None,
|
||||
};
|
||||
if let Err(err) = window.set_cursor_grab(mode) {
|
||||
println!("error: {err}");
|
||||
}
|
||||
}
|
||||
"h" => window.set_cursor_visible(!state),
|
||||
"i" => {
|
||||
println!("Info:");
|
||||
println!("-> outer_position : {:?}", window.outer_position());
|
||||
println!("-> inner_position : {:?}", window.inner_position());
|
||||
println!("-> outer_size : {:?}", window.outer_size());
|
||||
println!("-> inner_size : {:?}", window.inner_size());
|
||||
println!("-> fullscreen : {:?}", window.fullscreen());
|
||||
}
|
||||
"m" => window.set_maximized(state),
|
||||
"p" => window.set_outer_position({
|
||||
let mut position = window.outer_position().unwrap();
|
||||
let sign = if state { 1 } else { -1 };
|
||||
position.x += 10 * sign;
|
||||
position.y += 10 * sign;
|
||||
position
|
||||
}),
|
||||
"q" => window.request_redraw(),
|
||||
"r" => window.set_resizable(state),
|
||||
"s" => {
|
||||
let _ = window.request_inner_size(match state {
|
||||
true => PhysicalSize::new(
|
||||
WINDOW_SIZE.width + 50,
|
||||
WINDOW_SIZE.height + 50,
|
||||
),
|
||||
false => WINDOW_SIZE,
|
||||
});
|
||||
}
|
||||
"k" => window.set_min_inner_size(match state {
|
||||
true => Some(PhysicalSize::new(
|
||||
WINDOW_SIZE.width - 100,
|
||||
WINDOW_SIZE.height - 100,
|
||||
)),
|
||||
false => None,
|
||||
}),
|
||||
"o" => window.set_max_inner_size(match state {
|
||||
true => Some(PhysicalSize::new(
|
||||
WINDOW_SIZE.width + 100,
|
||||
WINDOW_SIZE.height + 100,
|
||||
)),
|
||||
false => None,
|
||||
}),
|
||||
"w" => {
|
||||
if let Size::Physical(size) = WINDOW_SIZE.into() {
|
||||
window
|
||||
.set_cursor_position(Position::Physical(
|
||||
PhysicalPosition::new(
|
||||
size.width as i32 / 2,
|
||||
size.height as i32 / 2,
|
||||
),
|
||||
))
|
||||
.unwrap()
|
||||
}
|
||||
}
|
||||
"z" => {
|
||||
window.set_visible(false);
|
||||
thread::sleep(Duration::from_secs(1));
|
||||
window.set_visible(true);
|
||||
}
|
||||
_ => (),
|
||||
},
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
event_loop.run(move |event, elwt| {
|
||||
if window_senders.is_empty() {
|
||||
elwt.exit()
|
||||
}
|
||||
match event {
|
||||
Event::WindowEvent { event, window_id } => match event {
|
||||
WindowEvent::CloseRequested
|
||||
| WindowEvent::Destroyed
|
||||
| WindowEvent::KeyboardInput {
|
||||
event:
|
||||
KeyEvent {
|
||||
state: ElementState::Released,
|
||||
logical_key: Key::Named(NamedKey::Escape),
|
||||
..
|
||||
},
|
||||
..
|
||||
} => {
|
||||
window_senders.remove(&window_id);
|
||||
}
|
||||
_ => {
|
||||
if let Some(tx) = window_senders.get(&window_id) {
|
||||
tx.send(event).unwrap();
|
||||
}
|
||||
}
|
||||
},
|
||||
_ => {}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(web_platform)]
|
||||
fn main() {
|
||||
panic!("Example not supported on Web");
|
||||
}
|
||||
|
|
@ -1,64 +0,0 @@
|
|||
#![allow(clippy::single_match)]
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
event::{ElementState, Event, WindowEvent},
|
||||
event_loop::EventLoop,
|
||||
keyboard::{Key, NamedKey},
|
||||
window::Window,
|
||||
};
|
||||
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
fn main() -> Result<(), impl std::error::Error> {
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
|
||||
let mut windows = HashMap::new();
|
||||
for _ in 0..3 {
|
||||
let window = Window::new(&event_loop).unwrap();
|
||||
println!("Opened a new window: {:?}", window.id());
|
||||
windows.insert(window.id(), window);
|
||||
}
|
||||
|
||||
println!("Press N to open a new window.");
|
||||
|
||||
event_loop.run(move |event, elwt| {
|
||||
if let Event::WindowEvent { event, window_id } = event {
|
||||
match event {
|
||||
WindowEvent::CloseRequested => {
|
||||
println!("Window {window_id:?} has received the signal to close");
|
||||
|
||||
// This drops the window, causing it to close.
|
||||
windows.remove(&window_id);
|
||||
|
||||
if windows.is_empty() {
|
||||
elwt.exit();
|
||||
}
|
||||
}
|
||||
WindowEvent::KeyboardInput {
|
||||
event,
|
||||
is_synthetic: false,
|
||||
..
|
||||
} if event.state == ElementState::Pressed => match event.logical_key {
|
||||
Key::Named(NamedKey::Escape) => elwt.exit(),
|
||||
Key::Character(c) if c == "n" || c == "N" => {
|
||||
let window = Window::new(elwt).unwrap();
|
||||
println!("Opened a new window: {:?}", window.id());
|
||||
windows.insert(window.id(), window);
|
||||
}
|
||||
_ => (),
|
||||
},
|
||||
WindowEvent::RedrawRequested => {
|
||||
if let Some(window) = windows.get(&window_id) {
|
||||
fill::fill_window(window);
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
@ -25,38 +25,40 @@ fn main() -> std::process::ExitCode {
|
|||
let mut event_loop = EventLoop::new().unwrap();
|
||||
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let window = Window::builder()
|
||||
.with_title("A fantastic window!")
|
||||
.build(&event_loop)
|
||||
.unwrap();
|
||||
|
||||
'main: loop {
|
||||
let mut window = None;
|
||||
|
||||
loop {
|
||||
let timeout = Some(Duration::ZERO);
|
||||
let status = event_loop.pump_events(timeout, |event, elwt| {
|
||||
let status = event_loop.pump_events(timeout, |event, event_loop| {
|
||||
if let Event::WindowEvent { event, .. } = &event {
|
||||
// Print only Window events to reduce noise
|
||||
println!("{event:?}");
|
||||
}
|
||||
|
||||
match event {
|
||||
Event::WindowEvent {
|
||||
event: WindowEvent::CloseRequested,
|
||||
window_id,
|
||||
} if window_id == window.id() => elwt.exit(),
|
||||
Event::AboutToWait => {
|
||||
window.request_redraw();
|
||||
Event::Resumed => {
|
||||
let window_attributes =
|
||||
Window::default_attributes().with_title("A fantastic window!");
|
||||
window = Some(event_loop.create_window(window_attributes).unwrap());
|
||||
}
|
||||
Event::WindowEvent {
|
||||
event: WindowEvent::RedrawRequested,
|
||||
..
|
||||
} => {
|
||||
fill::fill_window(&window);
|
||||
Event::WindowEvent { event, .. } => {
|
||||
let window = window.as_ref().unwrap();
|
||||
match event {
|
||||
WindowEvent::CloseRequested => event_loop.exit(),
|
||||
WindowEvent::RedrawRequested => fill::fill_window(window),
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
Event::AboutToWait => {
|
||||
window.as_ref().unwrap().request_redraw();
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
});
|
||||
|
||||
if let PumpStatus::Exit(exit_code) = status {
|
||||
break 'main ExitCode::from(exit_code as u8);
|
||||
break ExitCode::from(exit_code as u8);
|
||||
}
|
||||
|
||||
// Sleep for 1/60 second to simulate application work
|
||||
|
|
@ -1,42 +0,0 @@
|
|||
#![allow(clippy::single_match)]
|
||||
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
event::{ElementState, Event, WindowEvent},
|
||||
event_loop::EventLoop,
|
||||
window::Window,
|
||||
};
|
||||
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
fn main() -> Result<(), impl std::error::Error> {
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
|
||||
let window = Window::builder()
|
||||
.with_title("A fantastic window!")
|
||||
.build(&event_loop)
|
||||
.unwrap();
|
||||
|
||||
event_loop.run(move |event, elwt| {
|
||||
println!("{event:?}");
|
||||
|
||||
if let Event::WindowEvent { event, .. } = event {
|
||||
match event {
|
||||
WindowEvent::CloseRequested => elwt.exit(),
|
||||
WindowEvent::MouseInput {
|
||||
state: ElementState::Released,
|
||||
..
|
||||
} => {
|
||||
window.request_redraw();
|
||||
}
|
||||
WindowEvent::RedrawRequested => {
|
||||
println!("\nredrawing!\n");
|
||||
fill::fill_window(&window);
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
@ -1,59 +0,0 @@
|
|||
#![allow(clippy::single_match)]
|
||||
|
||||
#[cfg(not(web_platform))]
|
||||
fn main() -> Result<(), impl std::error::Error> {
|
||||
use std::{sync::Arc, thread, time};
|
||||
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
event::{Event, WindowEvent},
|
||||
event_loop::EventLoop,
|
||||
window::Window,
|
||||
};
|
||||
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
|
||||
let window = {
|
||||
let window = Window::builder()
|
||||
.with_title("A fantastic window!")
|
||||
.build(&event_loop)
|
||||
.unwrap();
|
||||
Arc::new(window)
|
||||
};
|
||||
|
||||
thread::spawn({
|
||||
let window = window.clone();
|
||||
move || loop {
|
||||
thread::sleep(time::Duration::from_secs(1));
|
||||
window.request_redraw();
|
||||
}
|
||||
});
|
||||
|
||||
event_loop.run(move |event, elwt| {
|
||||
println!("{event:?}");
|
||||
|
||||
match event {
|
||||
Event::WindowEvent {
|
||||
event: WindowEvent::CloseRequested,
|
||||
..
|
||||
} => elwt.exit(),
|
||||
Event::WindowEvent {
|
||||
event: WindowEvent::RedrawRequested,
|
||||
..
|
||||
} => {
|
||||
println!("\nredrawing!\n");
|
||||
fill::fill_window(&window);
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(web_platform)]
|
||||
fn main() {
|
||||
unimplemented!() // `Window` can't be sent between threads
|
||||
}
|
||||
|
|
@ -1,54 +0,0 @@
|
|||
#![allow(clippy::single_match)]
|
||||
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
dpi::LogicalSize,
|
||||
event::{ElementState, Event, KeyEvent, WindowEvent},
|
||||
event_loop::EventLoop,
|
||||
keyboard::{KeyCode, PhysicalKey},
|
||||
window::Window,
|
||||
};
|
||||
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
fn main() -> Result<(), impl std::error::Error> {
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
|
||||
let mut resizable = false;
|
||||
|
||||
let window = Window::builder()
|
||||
.with_title("Hit space to toggle resizability.")
|
||||
.with_inner_size(LogicalSize::new(600.0, 300.0))
|
||||
.with_min_inner_size(LogicalSize::new(400.0, 200.0))
|
||||
.with_max_inner_size(LogicalSize::new(800.0, 400.0))
|
||||
.with_resizable(resizable)
|
||||
.build(&event_loop)
|
||||
.unwrap();
|
||||
|
||||
event_loop.run(move |event, elwt| {
|
||||
if let Event::WindowEvent { event, .. } = event {
|
||||
match event {
|
||||
WindowEvent::CloseRequested => elwt.exit(),
|
||||
WindowEvent::KeyboardInput {
|
||||
event:
|
||||
KeyEvent {
|
||||
physical_key: PhysicalKey::Code(KeyCode::Space),
|
||||
state: ElementState::Released,
|
||||
..
|
||||
},
|
||||
..
|
||||
} => {
|
||||
resizable = !resizable;
|
||||
println!("Resizable: {resizable}");
|
||||
window.set_resizable(resizable);
|
||||
}
|
||||
WindowEvent::RedrawRequested => {
|
||||
fill::fill_window(&window);
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
};
|
||||
})
|
||||
}
|
||||
|
|
@ -30,7 +30,7 @@ fn main() -> Result<(), impl std::error::Error> {
|
|||
fn run_app(event_loop: &mut EventLoop<()>, idx: usize) -> Result<(), EventLoopError> {
|
||||
let mut app = App::default();
|
||||
|
||||
event_loop.run_on_demand(move |event, elwt| {
|
||||
event_loop.run_on_demand(move |event, event_loop| {
|
||||
println!("Run {idx}: {:?}", event);
|
||||
|
||||
if let Some(window) = &app.window {
|
||||
|
|
@ -60,16 +60,15 @@ fn main() -> Result<(), impl std::error::Error> {
|
|||
} if id == window_id => {
|
||||
println!("--------------------------------------------------------- Window {idx} Destroyed");
|
||||
app.window_id = None;
|
||||
elwt.exit();
|
||||
event_loop.exit();
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
} else if let Event::Resumed = event {
|
||||
let window = Window::builder()
|
||||
let window_attributes = Window::default_attributes()
|
||||
.with_title("Fantastic window number one!")
|
||||
.with_inner_size(winit::dpi::LogicalSize::new(128.0, 128.0))
|
||||
.build(elwt)
|
||||
.unwrap();
|
||||
.with_inner_size(winit::dpi::LogicalSize::new(128.0, 128.0));
|
||||
let window = event_loop.create_window(window_attributes).unwrap();
|
||||
app.window_id = Some(window.id());
|
||||
app.window = Some(window);
|
||||
}
|
||||
|
|
@ -1,115 +0,0 @@
|
|||
//! Demonstrates the use of startup notifications on Linux.
|
||||
|
||||
#[cfg(any(x11_platform, wayland_platform))]
|
||||
#[path = "./util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
#[cfg(any(x11_platform, wayland_platform))]
|
||||
mod example {
|
||||
use std::collections::HashMap;
|
||||
use std::rc::Rc;
|
||||
|
||||
use winit::event::{ElementState, Event, KeyEvent, WindowEvent};
|
||||
use winit::event_loop::EventLoop;
|
||||
use winit::platform::startup_notify::{
|
||||
EventLoopExtStartupNotify, WindowBuilderExtStartupNotify, WindowExtStartupNotify,
|
||||
};
|
||||
use winit::window::{Window, WindowId};
|
||||
|
||||
pub(super) fn main() -> Result<(), impl std::error::Error> {
|
||||
// Create the event loop and get the activation token.
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
let mut current_token = match event_loop.read_token_from_env() {
|
||||
Some(token) => Some(token),
|
||||
None => {
|
||||
println!("No startup notification token found in environment.");
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
let mut windows: HashMap<WindowId, Rc<Window>> = HashMap::new();
|
||||
let mut counter = 0;
|
||||
let mut create_first_window = false;
|
||||
|
||||
event_loop.run(move |event, elwt| {
|
||||
match event {
|
||||
Event::Resumed => create_first_window = true,
|
||||
|
||||
Event::WindowEvent { window_id, event } => match event {
|
||||
WindowEvent::KeyboardInput {
|
||||
event:
|
||||
KeyEvent {
|
||||
logical_key,
|
||||
state: ElementState::Pressed,
|
||||
..
|
||||
},
|
||||
..
|
||||
} => {
|
||||
if logical_key == "n" {
|
||||
if let Some(window) = windows.get(&window_id) {
|
||||
// Request a new activation token on this window.
|
||||
// Once we get it we will use it to create a window.
|
||||
window
|
||||
.request_activation_token()
|
||||
.expect("Failed to request activation token.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
WindowEvent::CloseRequested => {
|
||||
// Remove the window from the map.
|
||||
windows.remove(&window_id);
|
||||
if windows.is_empty() {
|
||||
elwt.exit();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
WindowEvent::ActivationTokenDone { token, .. } => {
|
||||
current_token = Some(token);
|
||||
}
|
||||
|
||||
WindowEvent::RedrawRequested => {
|
||||
if let Some(window) = windows.get(&window_id) {
|
||||
super::fill::fill_window(window);
|
||||
}
|
||||
}
|
||||
|
||||
_ => {}
|
||||
},
|
||||
_ => (),
|
||||
}
|
||||
|
||||
// See if we've passed the deadline.
|
||||
if current_token.is_some() || create_first_window {
|
||||
// Create the initial window.
|
||||
let window = {
|
||||
let mut builder = Window::builder().with_title(format!("Window {}", counter));
|
||||
|
||||
if let Some(token) = current_token.take() {
|
||||
println!("Creating a window with token {token:?}");
|
||||
builder = builder.with_activation_token(token);
|
||||
}
|
||||
|
||||
Rc::new(builder.build(elwt).unwrap())
|
||||
};
|
||||
|
||||
// Add the window to the map.
|
||||
windows.insert(window.id(), window.clone());
|
||||
|
||||
counter += 1;
|
||||
create_first_window = false;
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(x11_platform, wayland_platform))]
|
||||
fn main() -> Result<(), impl std::error::Error> {
|
||||
example::main()
|
||||
}
|
||||
|
||||
#[cfg(not(any(x11_platform, wayland_platform)))]
|
||||
fn main() {
|
||||
println!("This example is only supported on X11 and Wayland platforms.");
|
||||
}
|
||||
|
|
@ -1,68 +0,0 @@
|
|||
#![allow(clippy::single_match)]
|
||||
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
event::{ElementState, Event, KeyEvent, WindowEvent},
|
||||
event_loop::EventLoop,
|
||||
keyboard::Key,
|
||||
window::{Theme, Window},
|
||||
};
|
||||
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
fn main() -> Result<(), impl std::error::Error> {
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
|
||||
let window = Window::builder()
|
||||
.with_title("A fantastic window!")
|
||||
.with_theme(Some(Theme::Dark))
|
||||
.build(&event_loop)
|
||||
.unwrap();
|
||||
|
||||
println!("Initial theme: {:?}", window.theme());
|
||||
println!("debugging keys:");
|
||||
println!(" (A) Automatic theme");
|
||||
println!(" (L) Light theme");
|
||||
println!(" (D) Dark theme");
|
||||
|
||||
event_loop.run(move |event, elwt| {
|
||||
if let Event::WindowEvent { window_id, event } = event {
|
||||
match event {
|
||||
WindowEvent::CloseRequested => elwt.exit(),
|
||||
WindowEvent::ThemeChanged(theme) if window_id == window.id() => {
|
||||
println!("Theme is changed: {theme:?}")
|
||||
}
|
||||
WindowEvent::KeyboardInput {
|
||||
event:
|
||||
KeyEvent {
|
||||
logical_key: key,
|
||||
state: ElementState::Pressed,
|
||||
..
|
||||
},
|
||||
..
|
||||
} => match key.as_ref() {
|
||||
Key::Character("A" | "a") => {
|
||||
println!("Theme was: {:?}", window.theme());
|
||||
window.set_theme(None);
|
||||
}
|
||||
Key::Character("L" | "l") => {
|
||||
println!("Theme was: {:?}", window.theme());
|
||||
window.set_theme(Some(Theme::Light));
|
||||
}
|
||||
Key::Character("D" | "d") => {
|
||||
println!("Theme was: {:?}", window.theme());
|
||||
window.set_theme(Some(Theme::Dark));
|
||||
}
|
||||
_ => (),
|
||||
},
|
||||
WindowEvent::RedrawRequested => {
|
||||
println!("\nredrawing!\n");
|
||||
fill::fill_window(&window);
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
@ -1,54 +0,0 @@
|
|||
#![allow(clippy::single_match)]
|
||||
|
||||
use std::time::Duration;
|
||||
#[cfg(not(web_platform))]
|
||||
use std::time::Instant;
|
||||
#[cfg(web_platform)]
|
||||
use web_time::Instant;
|
||||
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
event::{Event, StartCause, WindowEvent},
|
||||
event_loop::{ControlFlow, EventLoop},
|
||||
window::Window,
|
||||
};
|
||||
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
fn main() -> Result<(), impl std::error::Error> {
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
|
||||
let window = Window::builder()
|
||||
.with_title("A fantastic window!")
|
||||
.build(&event_loop)
|
||||
.unwrap();
|
||||
|
||||
let timer_length = Duration::new(1, 0);
|
||||
|
||||
event_loop.run(move |event, elwt| {
|
||||
println!("{event:?}");
|
||||
|
||||
match event {
|
||||
Event::NewEvents(StartCause::Init) => {
|
||||
elwt.set_control_flow(ControlFlow::WaitUntil(Instant::now() + timer_length));
|
||||
}
|
||||
Event::NewEvents(StartCause::ResumeTimeReached { .. }) => {
|
||||
elwt.set_control_flow(ControlFlow::WaitUntil(Instant::now() + timer_length));
|
||||
println!("\nTimer\n");
|
||||
}
|
||||
Event::WindowEvent {
|
||||
event: WindowEvent::CloseRequested,
|
||||
..
|
||||
} => elwt.exit(),
|
||||
Event::WindowEvent {
|
||||
event: WindowEvent::RedrawRequested,
|
||||
..
|
||||
} => {
|
||||
fill::fill_window(&window);
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
@ -1,62 +0,0 @@
|
|||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
event::{Event, WindowEvent},
|
||||
event_loop::EventLoop,
|
||||
window::Window,
|
||||
};
|
||||
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
fn main() -> Result<(), impl std::error::Error> {
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
|
||||
let window = Window::builder()
|
||||
.with_title("Touchpad gestures")
|
||||
.build(&event_loop)
|
||||
.unwrap();
|
||||
#[cfg(target_os = "ios")]
|
||||
{
|
||||
use winit::platform::ios::WindowExtIOS;
|
||||
window.recognize_doubletap_gesture(true);
|
||||
window.recognize_pinch_gesture(true);
|
||||
window.recognize_rotation_gesture(true);
|
||||
}
|
||||
|
||||
println!("Only supported on macOS/iOS at the moment.");
|
||||
|
||||
let mut zoom = 0.0;
|
||||
let mut rotated = 0.0;
|
||||
|
||||
event_loop.run(move |event, elwt| {
|
||||
if let Event::WindowEvent { event, .. } = event {
|
||||
match event {
|
||||
WindowEvent::CloseRequested => elwt.exit(),
|
||||
WindowEvent::PinchGesture { delta, .. } => {
|
||||
zoom += delta;
|
||||
if delta > 0.0 {
|
||||
println!("Zoomed in {delta:.5} (now: {zoom:.5})");
|
||||
} else {
|
||||
println!("Zoomed out {delta:.5} (now: {zoom:.5})");
|
||||
}
|
||||
}
|
||||
WindowEvent::DoubleTapGesture { .. } => {
|
||||
println!("Smart zoom");
|
||||
}
|
||||
WindowEvent::RotationGesture { delta, .. } => {
|
||||
rotated += delta;
|
||||
if delta > 0.0 {
|
||||
println!("Rotated counterclockwise {delta:.5} (now: {rotated:.5})");
|
||||
} else {
|
||||
println!("Rotated clockwise {delta:.5} (now: {rotated:.5})");
|
||||
}
|
||||
}
|
||||
WindowEvent::RedrawRequested => {
|
||||
fill::fill_window(&window);
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
@ -1,38 +0,0 @@
|
|||
#![allow(clippy::single_match)]
|
||||
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
event::{Event, WindowEvent},
|
||||
event_loop::EventLoop,
|
||||
window::Window,
|
||||
};
|
||||
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
fn main() -> Result<(), impl std::error::Error> {
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
|
||||
let window = Window::builder()
|
||||
.with_decorations(false)
|
||||
.with_transparent(true)
|
||||
.build(&event_loop)
|
||||
.unwrap();
|
||||
|
||||
window.set_title("A fantastic window!");
|
||||
|
||||
event_loop.run(move |event, elwt| {
|
||||
println!("{event:?}");
|
||||
|
||||
if let Event::WindowEvent { event, .. } = event {
|
||||
match event {
|
||||
WindowEvent::CloseRequested => elwt.exit(),
|
||||
WindowEvent::RedrawRequested => {
|
||||
fill::fill_window(&window);
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
@ -1,22 +0,0 @@
|
|||
#![allow(clippy::single_match)]
|
||||
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::event_loop::EventLoop;
|
||||
|
||||
fn main() {
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
let monitor = match event_loop.primary_monitor() {
|
||||
Some(monitor) => monitor,
|
||||
None => {
|
||||
println!("No primary monitor detected.");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
println!("Listing available video modes:");
|
||||
|
||||
for mode in monitor.video_modes() {
|
||||
println!("{mode}");
|
||||
}
|
||||
}
|
||||
147
examples/web.rs
147
examples/web.rs
|
|
@ -1,147 +0,0 @@
|
|||
#![allow(clippy::disallowed_methods, clippy::single_match)]
|
||||
|
||||
use winit::{
|
||||
event::{ElementState, Event, KeyEvent, WindowEvent},
|
||||
event_loop::EventLoop,
|
||||
keyboard::Key,
|
||||
window::{Fullscreen, Window},
|
||||
};
|
||||
|
||||
pub fn main() -> Result<(), impl std::error::Error> {
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
|
||||
let builder = Window::builder().with_title("A fantastic window!");
|
||||
#[cfg(wasm_platform)]
|
||||
let builder = {
|
||||
use winit::platform::web::WindowBuilderExtWebSys;
|
||||
builder.with_append(true)
|
||||
};
|
||||
let window = builder.build(&event_loop).unwrap();
|
||||
|
||||
#[cfg(web_platform)]
|
||||
let log_list = wasm::insert_canvas_and_create_log_list(&window);
|
||||
|
||||
event_loop.run(move |event, elwt| {
|
||||
#[cfg(web_platform)]
|
||||
wasm::log_event(&log_list, &event);
|
||||
|
||||
match event {
|
||||
Event::WindowEvent {
|
||||
event: WindowEvent::CloseRequested,
|
||||
window_id,
|
||||
} if window_id == window.id() => elwt.exit(),
|
||||
Event::AboutToWait => {
|
||||
window.request_redraw();
|
||||
}
|
||||
Event::WindowEvent {
|
||||
window_id,
|
||||
event:
|
||||
WindowEvent::KeyboardInput {
|
||||
event:
|
||||
KeyEvent {
|
||||
logical_key: Key::Character(c),
|
||||
state: ElementState::Released,
|
||||
..
|
||||
},
|
||||
..
|
||||
},
|
||||
} if window_id == window.id() && c == "f" => {
|
||||
if window.fullscreen().is_some() {
|
||||
window.set_fullscreen(None);
|
||||
} else {
|
||||
window.set_fullscreen(Some(Fullscreen::Borderless(None)));
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(web_platform)]
|
||||
mod wasm {
|
||||
use std::num::NonZeroU32;
|
||||
|
||||
use softbuffer::{Surface, SurfaceExtWeb};
|
||||
use wasm_bindgen::prelude::*;
|
||||
use winit::{
|
||||
event::{Event, WindowEvent},
|
||||
window::Window,
|
||||
};
|
||||
|
||||
#[wasm_bindgen(start)]
|
||||
pub fn run() {
|
||||
console_log::init_with_level(log::Level::Debug).expect("error initializing logger");
|
||||
|
||||
#[allow(clippy::main_recursion)]
|
||||
let _ = super::main();
|
||||
}
|
||||
|
||||
pub fn insert_canvas_and_create_log_list(window: &Window) -> web_sys::Element {
|
||||
use winit::platform::web::WindowExtWebSys;
|
||||
|
||||
let canvas = window.canvas().unwrap();
|
||||
let mut surface = Surface::from_canvas(canvas.clone()).unwrap();
|
||||
surface
|
||||
.resize(
|
||||
NonZeroU32::new(canvas.width()).unwrap(),
|
||||
NonZeroU32::new(canvas.height()).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let mut buffer = surface.buffer_mut().unwrap();
|
||||
buffer.fill(0xFFF0000);
|
||||
buffer.present().unwrap();
|
||||
|
||||
let window = web_sys::window().unwrap();
|
||||
let document = window.document().unwrap();
|
||||
let body = document.body().unwrap();
|
||||
|
||||
let style = &canvas.style();
|
||||
style.set_property("margin", "50px").unwrap();
|
||||
// Use to test interactions with border and padding.
|
||||
//style.set_property("border", "50px solid black").unwrap();
|
||||
//style.set_property("padding", "50px").unwrap();
|
||||
|
||||
let log_header = document.create_element("h2").unwrap();
|
||||
log_header.set_text_content(Some("Event Log"));
|
||||
body.append_child(&log_header).unwrap();
|
||||
|
||||
let log_list = document.create_element("ul").unwrap();
|
||||
body.append_child(&log_list).unwrap();
|
||||
log_list
|
||||
}
|
||||
|
||||
pub fn log_event(log_list: &web_sys::Element, event: &Event<()>) {
|
||||
log::debug!("{:?}", event);
|
||||
|
||||
// Getting access to browser logs requires a lot of setup on mobile devices.
|
||||
// So we implement this basic logging system into the page to give developers an easy alternative.
|
||||
// As a bonus its also kind of handy on desktop.
|
||||
let event = match event {
|
||||
Event::WindowEvent {
|
||||
event: WindowEvent::RedrawRequested,
|
||||
..
|
||||
} => None,
|
||||
Event::WindowEvent { event, .. } => Some(format!("{event:?}")),
|
||||
Event::Resumed | Event::Suspended => Some(format!("{event:?}")),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(event) = event {
|
||||
let window = web_sys::window().unwrap();
|
||||
let document = window.document().unwrap();
|
||||
let log = document.create_element("li").unwrap();
|
||||
|
||||
let date = js_sys::Date::new_0();
|
||||
log.set_text_content(Some(&format!(
|
||||
"{:02}:{:02}:{:02}.{:03}: {event}",
|
||||
date.get_hours(),
|
||||
date.get_minutes(),
|
||||
date.get_seconds(),
|
||||
date.get_milliseconds(),
|
||||
)));
|
||||
|
||||
log_list
|
||||
.insert_before(&log, log_list.first_child().as_ref())
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,101 +0,0 @@
|
|||
#![allow(clippy::disallowed_methods)]
|
||||
|
||||
pub fn main() {
|
||||
println!("This example must be run with cargo run-wasm --example web_aspect_ratio")
|
||||
}
|
||||
|
||||
#[cfg(web_platform)]
|
||||
mod wasm {
|
||||
use wasm_bindgen::prelude::*;
|
||||
use web_sys::HtmlCanvasElement;
|
||||
use winit::{
|
||||
dpi::PhysicalSize,
|
||||
event::{Event, WindowEvent},
|
||||
event_loop::EventLoop,
|
||||
platform::web::WindowBuilderExtWebSys,
|
||||
window::Window,
|
||||
};
|
||||
|
||||
const EXPLANATION: &str = "
|
||||
This example draws a circle in the middle of a 4/1 aspect ratio canvas which acts as a useful demonstration of winit's resize handling on web.
|
||||
Even when the browser window is resized or aspect-ratio of the canvas changed the circle should always:
|
||||
* Fill the entire width or height of the canvas (whichever is smaller) without exceeding it.
|
||||
* Be perfectly round
|
||||
* Not be blurry or pixelated (there is no antialiasing so you may still see jagged edges depending on the DPI of your monitor)
|
||||
|
||||
Currently winit does not handle resizes on web so the circle is rendered incorrectly.
|
||||
This example demonstrates the desired future functionality which will possibly be provided by https://github.com/rust-windowing/winit/pull/2074
|
||||
";
|
||||
|
||||
#[wasm_bindgen(start)]
|
||||
pub fn run() {
|
||||
console_log::init_with_level(log::Level::Debug).expect("error initializing logger");
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
|
||||
let window = Window::builder()
|
||||
.with_title("A fantastic window!")
|
||||
// When running in a non-wasm environment this would set the window size to 100x100.
|
||||
// However in this example it just sets a default initial size of 100x100 that is immediately overwritten due to the layout + styling of the page.
|
||||
.with_inner_size(PhysicalSize::new(100, 100))
|
||||
.with_append(true)
|
||||
.build(&event_loop)
|
||||
.unwrap();
|
||||
|
||||
let canvas = create_canvas(&window);
|
||||
|
||||
// Render once with the size info we currently have
|
||||
render_circle(&canvas, window.inner_size());
|
||||
|
||||
let _ = event_loop.run(move |event, _| match event {
|
||||
Event::WindowEvent {
|
||||
event: WindowEvent::Resized(resize),
|
||||
window_id,
|
||||
} if window_id == window.id() => {
|
||||
render_circle(&canvas, resize);
|
||||
}
|
||||
_ => (),
|
||||
});
|
||||
}
|
||||
|
||||
pub fn create_canvas(window: &Window) -> HtmlCanvasElement {
|
||||
use winit::platform::web::WindowExtWebSys;
|
||||
|
||||
let web_window = web_sys::window().unwrap();
|
||||
let document = web_window.document().unwrap();
|
||||
let body = document.body().unwrap();
|
||||
|
||||
// Set a background color for the canvas to make it easier to tell the where the canvas is for debugging purposes.
|
||||
let canvas = window.canvas().unwrap();
|
||||
canvas
|
||||
.style()
|
||||
.set_css_text("display: block; background-color: crimson; margin: auto; width: 50%; aspect-ratio: 4 / 1;");
|
||||
|
||||
let explanation = document.create_element("pre").unwrap();
|
||||
explanation.set_text_content(Some(EXPLANATION));
|
||||
body.append_child(&explanation).unwrap();
|
||||
|
||||
canvas
|
||||
}
|
||||
|
||||
pub fn render_circle(canvas: &HtmlCanvasElement, size: PhysicalSize<u32>) {
|
||||
log::info!("rendering circle with canvas size: {:?}", size);
|
||||
let context = canvas
|
||||
.get_context("2d")
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.dyn_into::<web_sys::CanvasRenderingContext2d>()
|
||||
.unwrap();
|
||||
|
||||
context.begin_path();
|
||||
context
|
||||
.arc(
|
||||
size.width as f64 / 2.0,
|
||||
size.height as f64 / 2.0,
|
||||
size.width.min(size.height) as f64 / 2.0,
|
||||
0.0,
|
||||
std::f64::consts::PI * 2.0,
|
||||
)
|
||||
.unwrap();
|
||||
context.fill();
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,68 +0,0 @@
|
|||
#![allow(clippy::single_match)]
|
||||
|
||||
// This example is used by developers to test various window functions.
|
||||
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
dpi::LogicalSize,
|
||||
event::{ElementState, Event, KeyEvent, WindowEvent},
|
||||
event_loop::{DeviceEvents, EventLoop},
|
||||
keyboard::Key,
|
||||
window::{Window, WindowButtons},
|
||||
};
|
||||
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
fn main() -> Result<(), impl std::error::Error> {
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
|
||||
let window = Window::builder()
|
||||
.with_title("A fantastic window!")
|
||||
.with_inner_size(LogicalSize::new(300.0, 300.0))
|
||||
.build(&event_loop)
|
||||
.unwrap();
|
||||
|
||||
eprintln!("Window Button keys:");
|
||||
eprintln!(" (F) Toggle close button");
|
||||
eprintln!(" (G) Toggle maximize button");
|
||||
eprintln!(" (H) Toggle minimize button");
|
||||
|
||||
event_loop.listen_device_events(DeviceEvents::Always);
|
||||
|
||||
event_loop.run(move |event, elwt| {
|
||||
if let Event::WindowEvent { window_id, event } = event {
|
||||
match event {
|
||||
WindowEvent::KeyboardInput {
|
||||
event:
|
||||
KeyEvent {
|
||||
logical_key: key,
|
||||
state: ElementState::Pressed,
|
||||
..
|
||||
},
|
||||
..
|
||||
} => match key.as_ref() {
|
||||
Key::Character("F" | "f") => {
|
||||
let buttons = window.enabled_buttons();
|
||||
window.set_enabled_buttons(buttons ^ WindowButtons::CLOSE);
|
||||
}
|
||||
Key::Character("G" | "g") => {
|
||||
let buttons = window.enabled_buttons();
|
||||
window.set_enabled_buttons(buttons ^ WindowButtons::MAXIMIZE);
|
||||
}
|
||||
Key::Character("H" | "h") => {
|
||||
let buttons = window.enabled_buttons();
|
||||
window.set_enabled_buttons(buttons ^ WindowButtons::MINIMIZE);
|
||||
}
|
||||
_ => (),
|
||||
},
|
||||
WindowEvent::CloseRequested if window_id == window.id() => elwt.exit(),
|
||||
WindowEvent::RedrawRequested => {
|
||||
fill::fill_window(&window);
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
@ -1,137 +0,0 @@
|
|||
#![allow(clippy::single_match)]
|
||||
|
||||
// This example is used by developers to test various window functions.
|
||||
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
dpi::{LogicalSize, PhysicalSize},
|
||||
event::{DeviceEvent, ElementState, Event, KeyEvent, RawKeyEvent, WindowEvent},
|
||||
event_loop::{DeviceEvents, EventLoop},
|
||||
keyboard::{Key, KeyCode, PhysicalKey},
|
||||
window::{Fullscreen, Window},
|
||||
};
|
||||
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
fn main() -> Result<(), impl std::error::Error> {
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
|
||||
let window = Window::builder()
|
||||
.with_title("A fantastic window!")
|
||||
.with_inner_size(LogicalSize::new(100.0, 100.0))
|
||||
.build(&event_loop)
|
||||
.unwrap();
|
||||
|
||||
eprintln!("debugging keys:");
|
||||
eprintln!(" (E) Enter exclusive fullscreen");
|
||||
eprintln!(" (F) Toggle borderless fullscreen");
|
||||
eprintln!(" (P) Toggle borderless fullscreen on system's preferred monitor");
|
||||
eprintln!(" (M) Toggle minimized");
|
||||
eprintln!(" (Q) Quit event loop");
|
||||
eprintln!(" (V) Toggle visibility");
|
||||
eprintln!(" (X) Toggle maximized");
|
||||
|
||||
let mut minimized = false;
|
||||
let mut visible = true;
|
||||
|
||||
event_loop.listen_device_events(DeviceEvents::Always);
|
||||
|
||||
event_loop.run(move |event, elwt| {
|
||||
match event {
|
||||
// This used to use the virtual key, but the new API
|
||||
// only provides the `physical_key` (`Code`).
|
||||
Event::DeviceEvent {
|
||||
event:
|
||||
DeviceEvent::Key(RawKeyEvent {
|
||||
physical_key,
|
||||
state: ElementState::Released,
|
||||
..
|
||||
}),
|
||||
..
|
||||
} => match physical_key {
|
||||
PhysicalKey::Code(KeyCode::KeyM) => {
|
||||
if minimized {
|
||||
minimized = !minimized;
|
||||
window.set_minimized(minimized);
|
||||
window.focus_window();
|
||||
}
|
||||
}
|
||||
PhysicalKey::Code(KeyCode::KeyV) => {
|
||||
if !visible {
|
||||
visible = !visible;
|
||||
window.set_visible(visible);
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
},
|
||||
Event::WindowEvent { window_id, event } => match event {
|
||||
WindowEvent::KeyboardInput {
|
||||
event:
|
||||
KeyEvent {
|
||||
logical_key: Key::Character(key_str),
|
||||
state: ElementState::Pressed,
|
||||
..
|
||||
},
|
||||
..
|
||||
} => match key_str.as_ref() {
|
||||
// WARNING: Consider using `key_without_modifiers()` if available on your platform.
|
||||
// See the `key_binding` example
|
||||
"e" => {
|
||||
fn area(size: PhysicalSize<u32>) -> u32 {
|
||||
size.width * size.height
|
||||
}
|
||||
|
||||
let monitor = window.current_monitor().unwrap();
|
||||
if let Some(mode) = monitor
|
||||
.video_modes()
|
||||
.max_by(|a, b| area(a.size()).cmp(&area(b.size())))
|
||||
{
|
||||
window.set_fullscreen(Some(Fullscreen::Exclusive(mode)));
|
||||
} else {
|
||||
eprintln!("no video modes available");
|
||||
}
|
||||
}
|
||||
"f" => {
|
||||
if window.fullscreen().is_some() {
|
||||
window.set_fullscreen(None);
|
||||
} else {
|
||||
let monitor = window.current_monitor();
|
||||
window.set_fullscreen(Some(Fullscreen::Borderless(monitor)));
|
||||
}
|
||||
}
|
||||
"p" => {
|
||||
if window.fullscreen().is_some() {
|
||||
window.set_fullscreen(None);
|
||||
} else {
|
||||
window.set_fullscreen(Some(Fullscreen::Borderless(None)));
|
||||
}
|
||||
}
|
||||
"m" => {
|
||||
minimized = !minimized;
|
||||
window.set_minimized(minimized);
|
||||
}
|
||||
"q" => {
|
||||
elwt.exit();
|
||||
}
|
||||
"v" => {
|
||||
visible = !visible;
|
||||
window.set_visible(visible);
|
||||
}
|
||||
"x" => {
|
||||
let is_maximized = window.is_maximized();
|
||||
window.set_maximized(!is_maximized);
|
||||
}
|
||||
_ => (),
|
||||
},
|
||||
WindowEvent::CloseRequested if window_id == window.id() => elwt.exit(),
|
||||
WindowEvent::RedrawRequested => {
|
||||
fill::fill_window(&window);
|
||||
}
|
||||
_ => (),
|
||||
},
|
||||
_ => (),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
@ -1,149 +0,0 @@
|
|||
//! Demonstrates capability to create in-app draggable regions for client-side decoration support.
|
||||
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
event::{ElementState, Event, KeyEvent, MouseButton, StartCause, WindowEvent},
|
||||
event_loop::EventLoop,
|
||||
keyboard::Key,
|
||||
window::{CursorIcon, ResizeDirection, Window},
|
||||
};
|
||||
|
||||
const BORDER: f64 = 8.0;
|
||||
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
fn main() -> Result<(), impl std::error::Error> {
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
|
||||
let window = Window::builder()
|
||||
.with_inner_size(winit::dpi::LogicalSize::new(600.0, 400.0))
|
||||
.with_min_inner_size(winit::dpi::LogicalSize::new(400.0, 200.0))
|
||||
.with_decorations(false)
|
||||
.build(&event_loop)
|
||||
.unwrap();
|
||||
|
||||
let mut border = false;
|
||||
let mut cursor_location = None;
|
||||
|
||||
event_loop.run(move |event, elwt| match event {
|
||||
Event::NewEvents(StartCause::Init) => {
|
||||
eprintln!("Press 'B' to toggle borderless")
|
||||
}
|
||||
Event::WindowEvent { event, .. } => match event {
|
||||
WindowEvent::CloseRequested => elwt.exit(),
|
||||
WindowEvent::CursorMoved { position, .. } => {
|
||||
if !window.is_decorated() {
|
||||
let new_location =
|
||||
cursor_resize_direction(window.inner_size(), position, BORDER);
|
||||
|
||||
if new_location != cursor_location {
|
||||
cursor_location = new_location;
|
||||
window.set_cursor(cursor_direction_icon(cursor_location))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
WindowEvent::MouseInput {
|
||||
state: ElementState::Pressed,
|
||||
button: MouseButton::Left,
|
||||
..
|
||||
} => {
|
||||
if let Some(dir) = cursor_location {
|
||||
let _res = window.drag_resize_window(dir);
|
||||
} else if !window.is_decorated() {
|
||||
let _res = window.drag_window();
|
||||
}
|
||||
}
|
||||
WindowEvent::KeyboardInput {
|
||||
event:
|
||||
KeyEvent {
|
||||
state: ElementState::Released,
|
||||
logical_key: Key::Character(c),
|
||||
..
|
||||
},
|
||||
..
|
||||
} if matches!(c.as_ref(), "B" | "b") => {
|
||||
border = !border;
|
||||
window.set_decorations(border);
|
||||
}
|
||||
WindowEvent::RedrawRequested => {
|
||||
fill::fill_window(&window);
|
||||
}
|
||||
_ => (),
|
||||
},
|
||||
|
||||
_ => (),
|
||||
})
|
||||
}
|
||||
|
||||
fn cursor_direction_icon(resize_direction: Option<ResizeDirection>) -> CursorIcon {
|
||||
match resize_direction {
|
||||
Some(resize_direction) => match resize_direction {
|
||||
ResizeDirection::East => CursorIcon::EResize,
|
||||
ResizeDirection::North => CursorIcon::NResize,
|
||||
ResizeDirection::NorthEast => CursorIcon::NeResize,
|
||||
ResizeDirection::NorthWest => CursorIcon::NwResize,
|
||||
ResizeDirection::South => CursorIcon::SResize,
|
||||
ResizeDirection::SouthEast => CursorIcon::SeResize,
|
||||
ResizeDirection::SouthWest => CursorIcon::SwResize,
|
||||
ResizeDirection::West => CursorIcon::WResize,
|
||||
},
|
||||
None => CursorIcon::Default,
|
||||
}
|
||||
}
|
||||
|
||||
fn cursor_resize_direction(
|
||||
win_size: winit::dpi::PhysicalSize<u32>,
|
||||
position: winit::dpi::PhysicalPosition<f64>,
|
||||
border_size: f64,
|
||||
) -> Option<ResizeDirection> {
|
||||
enum XDirection {
|
||||
West,
|
||||
East,
|
||||
Default,
|
||||
}
|
||||
|
||||
enum YDirection {
|
||||
North,
|
||||
South,
|
||||
Default,
|
||||
}
|
||||
|
||||
let xdir = if position.x < border_size {
|
||||
XDirection::West
|
||||
} else if position.x > (win_size.width as f64 - border_size) {
|
||||
XDirection::East
|
||||
} else {
|
||||
XDirection::Default
|
||||
};
|
||||
|
||||
let ydir = if position.y < border_size {
|
||||
YDirection::North
|
||||
} else if position.y > (win_size.height as f64 - border_size) {
|
||||
YDirection::South
|
||||
} else {
|
||||
YDirection::Default
|
||||
};
|
||||
|
||||
Some(match xdir {
|
||||
XDirection::West => match ydir {
|
||||
YDirection::North => ResizeDirection::NorthWest,
|
||||
YDirection::South => ResizeDirection::SouthWest,
|
||||
YDirection::Default => ResizeDirection::West,
|
||||
},
|
||||
|
||||
XDirection::East => match ydir {
|
||||
YDirection::North => ResizeDirection::NorthEast,
|
||||
YDirection::South => ResizeDirection::SouthEast,
|
||||
YDirection::Default => ResizeDirection::East,
|
||||
},
|
||||
|
||||
XDirection::Default => match ydir {
|
||||
YDirection::North => ResizeDirection::North,
|
||||
YDirection::South => ResizeDirection::South,
|
||||
YDirection::Default => return None,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
|
@ -1,60 +0,0 @@
|
|||
#![allow(clippy::single_match)]
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
event::{Event, WindowEvent},
|
||||
event_loop::EventLoop,
|
||||
window::{Icon, Window},
|
||||
};
|
||||
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
fn main() -> Result<(), impl std::error::Error> {
|
||||
SimpleLogger::new().init().unwrap();
|
||||
|
||||
// You'll have to choose an icon size at your own discretion. On X11, the desired size varies
|
||||
// by WM, and on Windows, you still have to account for screen scaling. Here we use 32px,
|
||||
// since it seems to work well enough in most cases. Be careful about going too high, or
|
||||
// you'll be bitten by the low-quality downscaling built into the WM.
|
||||
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/icon.png");
|
||||
|
||||
let icon = load_icon(Path::new(path));
|
||||
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
|
||||
let window = Window::builder()
|
||||
.with_title("An iconic window!")
|
||||
// At present, this only does anything on Windows and X11, so if you want to save load
|
||||
// time, you can put icon loading behind a function that returns `None` on other platforms.
|
||||
.with_window_icon(Some(icon))
|
||||
.build(&event_loop)
|
||||
.unwrap();
|
||||
|
||||
event_loop.run(move |event, elwt| {
|
||||
if let Event::WindowEvent { event, .. } = event {
|
||||
match event {
|
||||
WindowEvent::CloseRequested => elwt.exit(),
|
||||
WindowEvent::DroppedFile(path) => {
|
||||
window.set_window_icon(Some(load_icon(&path)));
|
||||
}
|
||||
WindowEvent::RedrawRequested => fill::fill_window(&window),
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn load_icon(path: &Path) -> Icon {
|
||||
let (icon_rgba, icon_width, icon_height) = {
|
||||
let image = image::open(path)
|
||||
.expect("Failed to open icon path")
|
||||
.into_rgba8();
|
||||
let (width, height) = image.dimensions();
|
||||
let rgba = image.into_raw();
|
||||
(rgba, width, height)
|
||||
};
|
||||
Icon::from_rgba(icon_rgba, icon_width, icon_height).expect("Failed to open icon")
|
||||
}
|
||||
|
|
@ -1,72 +0,0 @@
|
|||
#![allow(clippy::single_match)]
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
use winit::platform::macos::{OptionAsAlt, WindowExtMacOS};
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
use winit::{
|
||||
event::ElementState,
|
||||
event::{Event, MouseButton, WindowEvent},
|
||||
event_loop::EventLoop,
|
||||
window::Window,
|
||||
};
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
/// Prints the keyboard events characters received when option_is_alt is true versus false.
|
||||
/// A left mouse click will toggle option_is_alt.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn main() -> Result<(), impl std::error::Error> {
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
|
||||
let window = Window::builder()
|
||||
.with_title("A fantastic window!")
|
||||
.with_inner_size(winit::dpi::LogicalSize::new(128.0, 128.0))
|
||||
.build(&event_loop)
|
||||
.unwrap();
|
||||
|
||||
window.set_ime_allowed(true);
|
||||
|
||||
let mut option_as_alt = window.option_as_alt();
|
||||
|
||||
event_loop.run(move |event, elwt| match event {
|
||||
Event::WindowEvent {
|
||||
event: WindowEvent::CloseRequested,
|
||||
window_id,
|
||||
} if window_id == window.id() => elwt.exit(),
|
||||
Event::WindowEvent { event, .. } => match event {
|
||||
WindowEvent::MouseInput {
|
||||
state: ElementState::Pressed,
|
||||
button: MouseButton::Left,
|
||||
..
|
||||
} => {
|
||||
option_as_alt = match option_as_alt {
|
||||
OptionAsAlt::None => OptionAsAlt::OnlyLeft,
|
||||
OptionAsAlt::OnlyLeft => OptionAsAlt::OnlyRight,
|
||||
OptionAsAlt::OnlyRight => OptionAsAlt::Both,
|
||||
OptionAsAlt::Both => OptionAsAlt::None,
|
||||
};
|
||||
|
||||
println!("Received Mouse click, toggling option_as_alt to: {option_as_alt:?}");
|
||||
window.set_option_as_alt(option_as_alt);
|
||||
}
|
||||
WindowEvent::KeyboardInput { .. } => println!("KeyboardInput: {event:?}"),
|
||||
WindowEvent::RedrawRequested => {
|
||||
fill::fill_window(&window);
|
||||
}
|
||||
_ => (),
|
||||
},
|
||||
Event::AboutToWait => {
|
||||
window.request_redraw();
|
||||
}
|
||||
|
||||
_ => (),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn main() {
|
||||
println!("This example is only supported on MacOS");
|
||||
}
|
||||
|
|
@ -1,52 +0,0 @@
|
|||
use log::debug;
|
||||
use simple_logger::SimpleLogger;
|
||||
use winit::{
|
||||
dpi::LogicalSize,
|
||||
event::{ElementState, Event, WindowEvent},
|
||||
event_loop::EventLoop,
|
||||
keyboard::NamedKey,
|
||||
window::Window,
|
||||
};
|
||||
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
fn main() -> Result<(), impl std::error::Error> {
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
|
||||
let window = Window::builder()
|
||||
.with_title("A fantastic window!")
|
||||
.with_inner_size(LogicalSize::new(128.0, 128.0))
|
||||
.with_resize_increments(LogicalSize::new(25.0, 25.0))
|
||||
.build(&event_loop)
|
||||
.unwrap();
|
||||
|
||||
let mut has_increments = true;
|
||||
|
||||
event_loop.run(move |event, elwt| match event {
|
||||
Event::WindowEvent { event, window_id } if window_id == window.id() => match event {
|
||||
WindowEvent::CloseRequested => elwt.exit(),
|
||||
WindowEvent::KeyboardInput { event, .. }
|
||||
if event.logical_key == NamedKey::Space
|
||||
&& event.state == ElementState::Released =>
|
||||
{
|
||||
has_increments = !has_increments;
|
||||
|
||||
let new_increments = match window.resize_increments() {
|
||||
Some(_) => None,
|
||||
None => Some(LogicalSize::new(25.0, 25.0)),
|
||||
};
|
||||
debug!("Had increments: {}", new_increments.is_none());
|
||||
window.set_resize_increments(new_increments);
|
||||
}
|
||||
WindowEvent::RedrawRequested => {
|
||||
fill::fill_window(&window);
|
||||
}
|
||||
_ => (),
|
||||
},
|
||||
Event::AboutToWait => window.request_redraw(),
|
||||
|
||||
_ => (),
|
||||
})
|
||||
}
|
||||
|
|
@ -1,107 +0,0 @@
|
|||
#![allow(clippy::single_match)]
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::{collections::HashMap, num::NonZeroUsize};
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
use simple_logger::SimpleLogger;
|
||||
#[cfg(target_os = "macos")]
|
||||
use winit::{
|
||||
event::{ElementState, Event, KeyEvent, WindowEvent},
|
||||
event_loop::EventLoop,
|
||||
keyboard::{Key, NamedKey},
|
||||
platform::macos::{WindowBuilderExtMacOS, WindowExtMacOS},
|
||||
window::Window,
|
||||
};
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn main() -> Result<(), impl std::error::Error> {
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
|
||||
let mut windows = HashMap::new();
|
||||
let window = Window::new(&event_loop).unwrap();
|
||||
println!("Opened a new window: {:?}", window.id());
|
||||
windows.insert(window.id(), window);
|
||||
|
||||
println!("Press N to open a new window.");
|
||||
|
||||
event_loop.run(move |event, elwt| {
|
||||
if let Event::WindowEvent { event, window_id } = event {
|
||||
match event {
|
||||
WindowEvent::CloseRequested => {
|
||||
println!("Window {window_id:?} has received the signal to close");
|
||||
|
||||
// This drops the window, causing it to close.
|
||||
windows.remove(&window_id);
|
||||
|
||||
if windows.is_empty() {
|
||||
elwt.exit();
|
||||
}
|
||||
}
|
||||
WindowEvent::Resized(_) => {
|
||||
if let Some(window) = windows.get(&window_id) {
|
||||
window.request_redraw();
|
||||
}
|
||||
}
|
||||
WindowEvent::KeyboardInput {
|
||||
event:
|
||||
KeyEvent {
|
||||
state: ElementState::Pressed,
|
||||
logical_key,
|
||||
..
|
||||
},
|
||||
is_synthetic: false,
|
||||
..
|
||||
} => match logical_key.as_ref() {
|
||||
Key::Character("t") => {
|
||||
let tabbing_id = windows.get(&window_id).unwrap().tabbing_identifier();
|
||||
let window = Window::builder()
|
||||
.with_tabbing_identifier(&tabbing_id)
|
||||
.build(elwt)
|
||||
.unwrap();
|
||||
println!("Added a new tab: {:?}", window.id());
|
||||
windows.insert(window.id(), window);
|
||||
}
|
||||
Key::Character("w") => {
|
||||
let _ = windows.remove(&window_id);
|
||||
}
|
||||
Key::Named(NamedKey::ArrowRight) => {
|
||||
windows.get(&window_id).unwrap().select_next_tab();
|
||||
}
|
||||
Key::Named(NamedKey::ArrowLeft) => {
|
||||
windows.get(&window_id).unwrap().select_previous_tab();
|
||||
}
|
||||
Key::Character(ch) => {
|
||||
if let Ok(index) = ch.parse::<NonZeroUsize>() {
|
||||
let index = index.get();
|
||||
// Select the last tab when pressing `9`.
|
||||
let window = windows.get(&window_id).unwrap();
|
||||
if index == 9 {
|
||||
window.select_tab_at_index(window.num_tabs() - 1)
|
||||
} else {
|
||||
window.select_tab_at_index(index - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
},
|
||||
WindowEvent::RedrawRequested => {
|
||||
if let Some(window) = windows.get(&window_id) {
|
||||
fill::fill_window(window);
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn main() {
|
||||
println!("This example is only supported on MacOS");
|
||||
}
|
||||
|
|
@ -1,70 +1,62 @@
|
|||
//! A demonstration of embedding a winit window in an existing X11 application.
|
||||
use std::error::Error;
|
||||
|
||||
#[cfg(x11_platform)]
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
#[cfg(x11_platform)]
|
||||
mod imple {
|
||||
use super::fill;
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
use simple_logger::SimpleLogger;
|
||||
|
||||
use winit::{
|
||||
event::{Event, WindowEvent},
|
||||
event_loop::EventLoop,
|
||||
platform::x11::WindowBuilderExtX11,
|
||||
platform::x11::WindowAttributesExtX11,
|
||||
window::Window,
|
||||
};
|
||||
|
||||
pub(super) fn entry() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// First argument should be a 32-bit X11 window ID.
|
||||
let parent_window_id = std::env::args()
|
||||
.nth(1)
|
||||
.ok_or("Expected a 32-bit X11 window ID as the first argument.")?
|
||||
.parse::<u32>()?;
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new()?;
|
||||
// First argument should be a 32-bit X11 window ID.
|
||||
let parent_window_id = std::env::args()
|
||||
.nth(1)
|
||||
.ok_or("Expected a 32-bit X11 window ID as the first argument.")?
|
||||
.parse::<u32>()?;
|
||||
|
||||
let window = Window::builder()
|
||||
.with_title("An embedded window!")
|
||||
.with_inner_size(winit::dpi::LogicalSize::new(128.0, 128.0))
|
||||
.with_embed_parent_window(parent_window_id)
|
||||
.build(&event_loop)
|
||||
.unwrap();
|
||||
SimpleLogger::new().init().unwrap();
|
||||
let event_loop = EventLoop::new()?;
|
||||
|
||||
let mut window = None;
|
||||
event_loop.run(move |event, event_loop| match event {
|
||||
Event::Resumed => {
|
||||
let window_attributes = Window::default_attributes()
|
||||
.with_title("An embedded window!")
|
||||
.with_inner_size(winit::dpi::LogicalSize::new(128.0, 128.0))
|
||||
.with_embed_parent_window(parent_window_id);
|
||||
|
||||
window = Some(event_loop.create_window(window_attributes).unwrap());
|
||||
}
|
||||
Event::WindowEvent { event, .. } => {
|
||||
let window = window.as_ref().unwrap();
|
||||
|
||||
event_loop.run(move |event, elwt| {
|
||||
match event {
|
||||
Event::WindowEvent {
|
||||
event: WindowEvent::CloseRequested,
|
||||
window_id,
|
||||
} if window_id == window.id() => elwt.exit(),
|
||||
Event::AboutToWait => {
|
||||
window.request_redraw();
|
||||
}
|
||||
Event::WindowEvent {
|
||||
event: WindowEvent::RedrawRequested,
|
||||
..
|
||||
} => {
|
||||
// Notify the windowing system that we'll be presenting to the window.
|
||||
WindowEvent::CloseRequested => event_loop.exit(),
|
||||
WindowEvent::RedrawRequested => {
|
||||
window.pre_present_notify();
|
||||
fill::fill_window(&window);
|
||||
fill::fill_window(window);
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
})?;
|
||||
}
|
||||
Event::AboutToWait => {
|
||||
window.as_ref().unwrap().request_redraw();
|
||||
}
|
||||
_ => (),
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(x11_platform))]
|
||||
mod imple {
|
||||
pub(super) fn entry() -> Result<(), Box<dyn std::error::Error>> {
|
||||
println!("This example is only supported on X11 platforms.");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
imple::entry()
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
println!("This example is only supported on X11 platforms.");
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue