Compare commits

...

29 Commits

Author SHA1 Message Date
Kirill Chibisov
e8bccfff4f Winit version 0.31.0-beta.1 2025-11-16 13:32:44 +09:00
Kirill Chibisov
0a59e4b905 chore: fix clippy on X11 2025-11-16 13:07:23 +09:00
ShikiSuen
d837c88855 winit-appkit: fix tests on systems without MonitorId(1)
Use `CGMainDisplayID` instead of `1` to make tests pass on systems
without `MonitorId(1)`.
2025-11-06 14:46:28 +09:00
Dan Harris
82eab465e0 macOS: fix a crash when dragging non-file content onto window
Winit only supports text, thus we should ignore the rest
instead of crashing.
2025-11-05 13:20:01 +09:00
Diggory Hardy
a9c189a423 winit-win32: prevent inner size reported as (0,0) when minimized 2025-11-01 23:39:57 +09:00
Diggory Hardy
9d9d21cfdb winit-core: revise MouseButton type
Unify the values of `MouseButton` and thus remove `Other` variant in
limit possible buttons to 32, which was picked based on platform
capabilities, where 32 is the highest.

For the reference, SDL has identical limit.
2025-11-01 21:00:39 +09:00
Kirill Chibisov
779f52a21f chore: latest typos 2025-11-01 21:00:39 +09:00
mfluehr
7a21858d29 windows: don't confine hidden cursor 2025-11-01 13:03:11 +09:00
Kirill Chibisov
a3f7e6566a ci: fix eslint version to 9.38.0
9.39.0 has an issue with unified-signatures.

Links: https://github.com/eslint/eslint/issues/20272
2025-11-01 12:52:30 +09:00
DorotaC
f41897cfa4 examples/ime: fix crash on wayland
When pressing Ctrl+Space, KeyEvent::text_with_all_modifiers would return
\0. That would get included in the text-input text. When an input method
gets activated, the invalid string returning \0 would get sent as
surrounding text, resulting in a Wayland protocol error and crashing the
application.
2025-10-29 13:40:30 +09:00
Timon
bd6fef1d80 wayland: add prefer_csd attribute 2025-10-24 21:35:51 +09:00
Kirill Chibisov
42d256e926 ci: fix version of smol_str 2025-10-24 21:01:20 +09:00
Pavel Strakhov
03dad26c43 x11: ignore mouse scroll button release events 2025-10-24 20:07:10 +09:00
Kirill Chibisov
1e7ab0cd25 wayland: handle wl_seat v10 repeated state
Fixes #4382.
2025-10-20 00:01:36 +09:00
Kirill Chibisov
c333003514 Bump MSRV to 1.85 and edition to 2024 2025-10-20 00:01:36 +09:00
Arthur Cosentino
10f21090ce x11: fix deadlock in request_ime_update 2025-10-09 16:57:20 +09:00
Timon
5575f51483 wayland: add wayland-csd-adwaita-notitlebar feature
Addition to already present `notitle` feature.
2025-10-08 12:11:55 +09:00
Ian Douglas Scott
2ede84ab2f wayland: handle axis_value120 scroll events
This can be tested with the `application` example, looking at the events
shown for mouse wheel movement.

`wl_pointer::axis_discrete` isn't sent in version 8 or higher of
`wl_pointer`. And `sctk` doesn't convert the `value120` events, so
on compositors advertising version 8, only pixel scroll events were
being sent.

This sends `MouseScrollDelta::LineDelta` with a fractional value,
without doing any accumulation. Given `LineDelta` contains `f32` values,
this presumably is expected?

Though it might be good to change the definition of `MouseScrollDelta`
to include both discrete and pixel values, when the compositor sends
both. I'm not familiar with how this works on non-Wayland backends
though.
2025-10-08 11:53:57 +09:00
Kirill Chibisov
f046e778aa winit-core:winit: add tablet input support
The API is integrated into the `WindowEvent::Pointer*` API and is
present in form of `TabletTool` variant on corresponding data entries.

For now implemented for Web, Windows, and with limitations for Wayland.

Fixes #99.

Co-authored-by: daxpedda <daxpedda@gmail.com>
2025-10-07 21:42:36 +09:00
sachharine
ffcdf80192 chore: fix typos causing dead links 2025-10-07 19:25:41 +09:00
Mads Marquart
b811e9d878 chore: update to objc2 frameworks v0.3.2 2025-10-07 17:56:05 +09:00
Kirill Chibisov
d815bc089c chore: fix nightly clippy 2025-10-07 17:56:05 +09:00
Kirill Chibisov
66283a79bd wayland: reduce amount of empty preedits
If we send empty preedit before, don't send it again.
2025-09-13 06:53:29 +09:00
Alan Everett
3be30affe4 wayland: support for pinch, rotation, and pan gestures
Co-Authored-By: linkmauve <linkmauve@linkmauve.fr>
Co-authored-by: Kirill Chibisov <contact@kchibisov.com>
2025-09-07 11:45:35 +09:00
Kirill Chibisov
a68f1a664b winit-wayland: bump sctk and sctk-adwaita 2025-09-06 22:25:24 +09:00
DorotaC
6de5041a94 winit-core/ime: add more purposes and content hints
Also move IME example into `ime.rs` thus making IME integrations more
easily comprehendible.

Co-authored-by: Kirill Chibisov <contact@kchibisov.com>
2025-09-06 13:27:55 +09:00
Mads Marquart
014fb68a26 Fix using Rust-Analyzer on non-macOS platforms (#4347) 2025-09-05 22:32:20 +02:00
Mads Marquart
9a03dacbde linux: align scancode conversions with Chromium 2025-09-05 10:17:34 +09:00
Jeremy Soller
4d9302b33c Add borderless fullscreen mode for orbital (#4343) 2025-09-04 22:14:41 +02:00
152 changed files with 3242 additions and 1751 deletions

View File

@@ -55,7 +55,7 @@ jobs:
strategy:
fail-fast: false
matrix:
toolchain: [stable, nightly, '1.80']
toolchain: [stable, nightly, '1.85']
platform:
# Note: Make sure that we test all the `docs.rs` targets defined in Cargo.toml!
- { name: 'Windows 64bit MSVC', target: x86_64-pc-windows-msvc, os: windows-latest, }
@@ -82,13 +82,13 @@ jobs:
- toolchain: nightly
platform: { name: 'Windows 32bit GNU' }
# Android is tested on stable-3
- toolchain: '1.80'
- toolchain: '1.85'
platform: { name: 'Android' }
# Redox OS doesn't follow MSRV
- toolchain: '1.80'
- toolchain: '1.85'
platform: { name: 'Redox OS' }
include:
- toolchain: '1.80'
- toolchain: '1.85'
platform: { name: 'Android', target: aarch64-linux-android, os: ubuntu-latest, options: '--package winit --features=android-native-activity', cmd: 'apk -- ' }
- toolchain: 'nightly'
platform: { name: 'Web', target: wasm32-unknown-unknown, os: ubuntu-latest, test-options: -Zdoctest-xcompile }
@@ -136,7 +136,7 @@ jobs:
- name: Generate lockfile
# Also updates the crates.io index
run: cargo generate-lockfile && cargo update -p ahash --precise 0.8.7 && cargo update -p bumpalo --precise 3.14.0
run: cargo generate-lockfile && cargo update -p smol_str --precise 0.3.2
- name: Install GCC Multilib
if: (matrix.platform.os == 'ubuntu-latest') && contains(matrix.platform.target, 'i686')
@@ -230,19 +230,19 @@ jobs:
- name: Test dpi crate
if: >
contains(matrix.platform.name, 'Linux 64bit') &&
matrix.toolchain != '1.80'
matrix.toolchain != '1.85'
run: cargo test -p dpi
- name: Check dpi crate (no_std)
if: >
contains(matrix.platform.name, 'Linux 64bit') &&
matrix.toolchain != '1.80'
matrix.toolchain != '1.85'
run: cargo check -p dpi --no-default-features
- name: Build tests
if: >
!contains(matrix.platform.target, 'redox') &&
matrix.toolchain != '1.80'
matrix.toolchain != '1.85'
run: cargo $CMD test --no-run $OPTIONS
- name: Run tests
@@ -251,7 +251,7 @@ jobs:
!contains(matrix.platform.target, 'ios') &&
(!contains(matrix.platform.target, 'wasm32') || matrix.toolchain == 'nightly') &&
!contains(matrix.platform.target, 'redox') &&
matrix.toolchain != '1.80'
matrix.toolchain != '1.85'
run: cargo $CMD test $OPTIONS
- name: Lint with clippy
@@ -261,7 +261,7 @@ jobs:
- name: Build tests with serde enabled
if: >
!contains(matrix.platform.target, 'redox') &&
matrix.toolchain != '1.80'
matrix.toolchain != '1.85'
run: cargo $CMD test --no-run $OPTIONS $TEST_OPTIONS --features serde
- name: Run tests with serde enabled
@@ -270,7 +270,7 @@ jobs:
!contains(matrix.platform.target, 'ios') &&
(!contains(matrix.platform.target, 'wasm32') || matrix.toolchain == 'nightly') &&
!contains(matrix.platform.target, 'redox') &&
matrix.toolchain != '1.80'
matrix.toolchain != '1.85'
run: cargo $CMD test $OPTIONS $TEST_OPTIONS --features serde
- name: Check docs.rs documentation
@@ -329,7 +329,7 @@ jobs:
- name: Setup NPM
run: npm install
- name: Run ESLint
run: npx eslint
run: npx eslint@9.38.0
swc:
name: Minimize JavaScript

View File

@@ -4,26 +4,26 @@ members = ["dpi", "winit*"]
resolver = "2"
[workspace.package]
edition = "2021"
edition = "2024"
license = "Apache-2.0"
repository = "https://github.com/rust-windowing/winit"
rust-version = "1.80"
version = "0.30.12"
rust-version = "1.85"
version = "0.31.0-beta.1"
[workspace.dependencies]
# Workspace dependencies.
# `winit` has no version here to allow using it in dev deps for docs.
winit = { path = "winit" }
winit-android = { version = "0.30.12", path = "winit-android" }
winit-appkit = { version = "0.30.12", path = "winit-appkit" }
winit-common = { version = "0.30.12", path = "winit-common" }
winit-core = { version = "0.30.12", path = "winit-core" }
winit-orbital = { version = "0.30.12", path = "winit-orbital" }
winit-uikit = { version = "0.30.12", path = "winit-uikit" }
winit-wayland = { version = "0.30.12", path = "winit-wayland", default-features = false }
winit-web = { version = "0.30.12", path = "winit-web" }
winit-win32 = { version = "0.30.12", path = "winit-win32" }
winit-x11 = { version = "0.30.12", path = "winit-x11" }
winit-android = { version = "=0.31.0-beta.1", path = "winit-android" }
winit-appkit = { version = "=0.31.0-beta.1", path = "winit-appkit" }
winit-common = { version = "=0.31.0-beta.1", path = "winit-common" }
winit-core = { version = "=0.31.0-beta.1", path = "winit-core" }
winit-orbital = { version = "=0.31.0-beta.1", path = "winit-orbital" }
winit-uikit = { version = "=0.31.0-beta.1", path = "winit-uikit" }
winit-wayland = { version = "=0.31.0-beta.1", path = "winit-wayland", default-features = false }
winit-web = { version = "=0.31.0-beta.1", path = "winit-web" }
winit-win32 = { version = "=0.31.0-beta.1", path = "winit-win32" }
winit-x11 = { version = "=0.31.0-beta.1", path = "winit-x11" }
# Core dependencies.
bitflags = "2"
@@ -55,12 +55,12 @@ ndk = { version = "0.9.0", features = ["rwh_06"], default-features = false }
block2 = "0.6.1"
dispatch2 = { version = "0.3.0", default-features = false, features = ["std", "objc2"] }
objc2 = { version = "0.6.1", features = ["relax-sign-encoding"] }
objc2-app-kit = { version = "0.3.1", default-features = false }
objc2-core-foundation = { version = "0.3.1", default-features = false }
objc2-core-graphics = { version = "0.3.1", default-features = false }
objc2-core-video = { version = "0.3.1", default-features = false }
objc2-foundation = { version = "0.3.1", default-features = false }
objc2-ui-kit = { version = "0.3.1", default-features = false }
objc2-app-kit = { version = "0.3.2", default-features = false }
objc2-core-foundation = { version = "0.3.2", default-features = false }
objc2-core-graphics = { version = "0.3.2", default-features = false }
objc2-core-video = { version = "0.3.2", default-features = false }
objc2-foundation = { version = "0.3.2", default-features = false }
objc2-ui-kit = { version = "0.3.2", default-features = false }
# Windows dependencies.
unicode-segmentation = "1.7.1"
@@ -69,19 +69,11 @@ windows-sys = "0.59.0"
# Linux dependencies.
ahash = { version = "0.8.7", features = ["no-rng"] }
bytemuck = { version = "1.13.1", default-features = false }
calloop = "0.13.0"
calloop = "0.14.3"
libc = "0.2.64"
memmap2 = "0.9.0"
percent-encoding = "2.0"
rustix = { version = "1.0.7", default-features = false }
sctk = { package = "smithay-client-toolkit", version = "0.19.2", default-features = false, features = [
"calloop",
] }
sctk-adwaita = { version = "0.10.1", default-features = false }
wayland-backend = { version = "0.3.10", default-features = false, features = ["client_system"] }
wayland-client = "0.31.10"
wayland-protocols = { version = "0.32.8", features = ["staging"] }
wayland-protocols-plasma = { version = "0.3.8", features = ["client"] }
x11-dl = "2.19.1"
x11rb = { version = "0.13.0", default-features = false }
xkbcommon-dl = "0.4.2"

View File

@@ -8,7 +8,7 @@
```toml
[dependencies]
winit = "0.30.12"
winit = "0.31.0-beta.1"
```
## [Documentation](https://docs.rs/winit)
@@ -39,7 +39,7 @@ For contributing guidelines see [CONTRIBUTING.md](./CONTRIBUTING.md).
## MSRV Policy
This crate's Minimum Supported Rust Version (MSRV) is **1.80**. Changes to
This crate's Minimum Supported Rust Version (MSRV) is **1.85**. Changes to
the MSRV will be accompanied by a minor version bump.
As a **tentative** policy, the upper bound of the MSRV is given by the following

View File

@@ -10,6 +10,9 @@ disallowed-methods = [
{ allow-invalid = true, path = "web_sys::HtmlCanvasElement::set_width", reason = "Winit shouldn't touch the internal canvas size" },
{ allow-invalid = true, path = "web_sys::HtmlCanvasElement::width", reason = "Winit shouldn't touch the internal canvas size" },
{ allow-invalid = true, path = "web_sys::HtmlElement::style", reason = "cache this to reduce calls to JS" },
{ allow-invalid = true, path = "web_sys::MouseEvent::buttons", reason = "Use `backend::event::cursor_buttons()` to avoid wrong conversions" },
{ allow-invalid = true, path = "web_sys::MouseEvent::button", reason = "Use `backend::event::cursor_button()` to avoid wrong conversions" },
{ allow-invalid = true, path = "web_sys::PointerEvent::pointer_type", reason = "Use `WebPointerType` to emit warnings" },
{ allow-invalid = true, path = "web_sys::Window::document", reason = "cache this to reduce calls to JS" },
{ allow-invalid = true, path = "web_sys::Window::get_computed_style", reason = "cache this to reduce calls to JS" },
{ allow-invalid = true, path = "web_sys::Window::navigator", reason = "cache this to reduce calls to JS" },

View File

@@ -59,6 +59,10 @@ crate = "android-activity"
allow-globs = ["ci/*", "githooks/*"]
crate = "zerocopy"
[[bans.build.bypass]]
allow-globs = ["cherry-pick-stable.sh"]
crate = "libc"
[[bans.build.bypass]]
allow-globs = ["freetype2/*"]
crate = "freetype-sys"

View File

@@ -64,7 +64,7 @@
//! [points]: https://en.wikipedia.org/wiki/Point_(typography)
//! [picas]: https://en.wikipedia.org/wiki/Pica_(typography)
#![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg_hide), doc(cfg_hide(doc, docsrs)))]
#![cfg_attr(docsrs, feature(doc_cfg), doc(auto_cfg(hide(doc, docsrs))))]
#![cfg_attr(feature = "std", forbid(unsafe_code))]
#![no_std]

1
examples Symbolic link
View File

@@ -0,0 +1 @@
winit/examples

View File

@@ -1,5 +1,5 @@
use android_activity::input::{KeyAction, KeyEvent, KeyMapChar, Keycode};
use android_activity::AndroidApp;
use android_activity::input::{KeyAction, KeyEvent, KeyMapChar, Keycode};
use winit_core::keyboard::{
Key, KeyCode, KeyLocation, NamedKey, NativeKey, NativeKeyCode, PhysicalKey,
};

View File

@@ -62,8 +62,8 @@
//! If your application is currently based on `NativeActivity` via the `ndk-glue` crate and building
//! with `cargo apk`, then the minimal changes would be:
//! 1. Remove `ndk-glue` from your `Cargo.toml`
//! 2. Enable the `"android-native-activity"` feature for Winit: `winit = { version = "0.30.12",
//! features = [ "android-native-activity" ] }`
//! 2. Enable the `"android-native-activity"` feature for Winit: `winit = { version =
//! "0.31.0-beta.1", features = [ "android-native-activity" ] }`
//! 3. Add an `android_main` entrypoint (as above), instead of using the '`[ndk_glue::main]` proc
//! macro from `ndk-macros` (optionally add a dependency on `android_logger` and initialize
//! logging as above).

View File

@@ -18,7 +18,6 @@ rwh_06.workspace = true
serde = { workspace = true, optional = true }
smol_str.workspace = true
tracing.workspace = true
winit-common = { workspace = true, features = ["core-foundation", "event-handler"] }
winit-core.workspace = true
# Platform-specific
@@ -107,6 +106,7 @@ objc2-foundation = { workspace = true, features = [
"NSThread",
"NSValue",
] }
winit-common = { workspace = true, features = ["core-foundation", "event-handler"] }
[dev-dependencies]
winit.workspace = true

View File

@@ -30,8 +30,8 @@ extern "C-unwind" fn send_event(app: &NSApplication, sel: Sel, event: &NSEvent)
// For posterity, there are some undocumented event types
// (https://github.com/servo/cocoa-rs/issues/155)
// but that doesn't really matter here.
let event_type = unsafe { event.r#type() };
let modifier_flags = unsafe { event.modifierFlags() };
let event_type = event.r#type();
let modifier_flags = event.modifierFlags();
if event_type == NSEventType::KeyUp && modifier_flags.contains(NSEventModifierFlags::Command) {
if let Some(key_window) = app.keyWindow() {
key_window.sendEvent(event);
@@ -98,15 +98,15 @@ pub(crate) fn override_send_event(global_app: &NSApplication) {
}
fn maybe_dispatch_device_event(app_state: &Rc<AppState>, event: &NSEvent) {
let event_type = unsafe { event.r#type() };
let event_type = event.r#type();
#[allow(non_upper_case_globals)]
match event_type {
NSEventType::MouseMoved
| NSEventType::LeftMouseDragged
| NSEventType::OtherMouseDragged
| NSEventType::RightMouseDragged => {
let delta_x = unsafe { event.deltaX() } as f64;
let delta_y = unsafe { event.deltaY() } as f64;
let delta_x = event.deltaX() as f64;
let delta_y = event.deltaY() as f64;
if delta_x != 0.0 || delta_y != 0.0 {
app_state.maybe_queue_with_handler(move |app, event_loop| {
@@ -117,7 +117,7 @@ fn maybe_dispatch_device_event(app_state: &Rc<AppState>, event: &NSEvent) {
}
},
NSEventType::LeftMouseDown | NSEventType::RightMouseDown | NSEventType::OtherMouseDown => {
let button = unsafe { event.buttonNumber() } as u32;
let button = event.buttonNumber() as u32;
app_state.maybe_queue_with_handler(move |app, event_loop| {
app.device_event(event_loop, None, DeviceEvent::Button {
button,
@@ -126,7 +126,7 @@ fn maybe_dispatch_device_event(app_state: &Rc<AppState>, event: &NSEvent) {
});
},
NSEventType::LeftMouseUp | NSEventType::RightMouseUp | NSEventType::OtherMouseUp => {
let button = unsafe { event.buttonNumber() } as u32;
let button = event.buttonNumber() as u32;
app_state.maybe_queue_with_handler(move |app, event_loop| {
app.device_event(event_loop, None, DeviceEvent::Button {
button,
@@ -141,7 +141,7 @@ fn maybe_dispatch_device_event(app_state: &Rc<AppState>, event: &NSEvent) {
#[cfg(test)]
mod tests {
use objc2::rc::Retained;
use objc2::{define_class, msg_send, ClassType};
use objc2::{ClassType, define_class, msg_send};
use objc2_app_kit::NSResponder;
use objc2_foundation::NSObject;
@@ -153,16 +153,14 @@ mod tests {
let Some(mtm) = MainThreadMarker::new() else { return };
// Create a new application, without making it the shared application.
let app = unsafe { NSApplication::new(mtm) };
let app = NSApplication::new(mtm);
override_send_event(&app);
// Test calling twice works.
override_send_event(&app);
// FIXME(madsmtm): Can't test this yet, need some way to mock AppState.
// unsafe {
// let event = super::super::event::dummy_event().unwrap();
// app.sendEvent(&event)
// }
// let event = super::super::event::dummy_event().unwrap();
// app.sendEvent(&event)
}
#[test]

View File

@@ -15,7 +15,7 @@ use winit_core::event::{StartCause, WindowEvent};
use winit_core::event_loop::ControlFlow;
use winit_core::window::WindowId;
use super::event_loop::{notify_windows_of_exit, stop_app_immediately, ActiveEventLoop};
use super::event_loop::{ActiveEventLoop, notify_windows_of_exit, stop_app_immediately};
use super::menu;
use super::observer::{EventLoopWaker, RunLoop};
@@ -117,7 +117,7 @@ impl AppState {
// - https://github.com/rust-windowing/winit/issues/261
// - https://github.com/rust-windowing/winit/issues/3958
let is_bundled =
unsafe { NSRunningApplication::currentApplication().bundleIdentifier().is_some() };
NSRunningApplication::currentApplication().bundleIdentifier().is_some();
if !is_bundled {
app.setActivationPolicy(NSApplicationActivationPolicy::Regular);
}

View File

@@ -4,10 +4,10 @@ use std::sync::OnceLock;
use objc2::rc::Retained;
use objc2::runtime::Sel;
use objc2::{available, msg_send, sel, AllocAnyThread, ClassType};
use objc2::{AllocAnyThread, ClassType, available, msg_send, sel};
use objc2_app_kit::{NSBitmapImageRep, NSCursor, NSDeviceRGBColorSpace, NSImage};
use objc2_foundation::{
ns_string, NSData, NSDictionary, NSNumber, NSObject, NSPoint, NSSize, NSString,
NSData, NSDictionary, NSNumber, NSObject, NSPoint, NSSize, NSString, ns_string,
};
use winit_core::cursor::{CursorIcon, CursorImage, CustomCursorProvider, CustomCursorSource};
use winit_core::error::{NotSupportedError, RequestError};
@@ -31,7 +31,7 @@ impl CustomCursor {
let cursor = match cursor {
CustomCursorSource::Image(cursor_image) => cursor_image,
CustomCursorSource::Animation { .. } | CustomCursorSource::Url { .. } => {
return Err(NotSupportedError::new("unsupported cursor kind").into())
return Err(NotSupportedError::new("unsupported cursor kind").into());
},
};
@@ -62,10 +62,8 @@ pub(crate) fn cursor_from_image(cursor: &CursorImage) -> Result<Retained<NSCurso
unsafe { slice::from_raw_parts_mut(bitmap.bitmapData(), cursor.buffer().len()) };
bitmap_data.copy_from_slice(cursor.buffer());
let image = unsafe {
NSImage::initWithSize(NSImage::alloc(), NSSize::new(width.into(), height.into()))
};
unsafe { image.addRepresentation(&bitmap) };
let image = NSImage::initWithSize(NSImage::alloc(), NSSize::new(width.into(), height.into()));
image.addRepresentation(&bitmap);
let hotspot = NSPoint::new(cursor.hotspot_x() as f64, cursor.hotspot_y() as f64);
@@ -140,12 +138,9 @@ unsafe fn load_webkit_cursor(name: &NSString) -> Retained<NSCursor> {
// TODO: Handle PLists better
let info_path = cursor_path.stringByAppendingPathComponent(ns_string!("info.plist"));
let info: Retained<NSDictionary<NSObject, NSObject>> = unsafe {
msg_send![
<NSDictionary<NSObject, NSObject>>::class(),
dictionaryWithContentsOfFile: &*info_path,
]
};
#[allow(deprecated)]
let info: Retained<NSDictionary<NSObject, NSObject>> =
unsafe { NSDictionary::dictionaryWithContentsOfFile(&info_path) }.unwrap();
let mut x = 0.0;
if let Some(n) = info.objectForKey(ns_string!("hotx")) {
if let Ok(n) = n.downcast::<NSNumber>() {
@@ -216,9 +211,9 @@ pub(crate) fn cursor_from_icon(icon: CursorIcon) -> Retained<NSCursor> {
CursorIcon::EwResize | CursorIcon::ColResize => NSCursor::resizeLeftRightCursor(),
CursorIcon::NsResize | CursorIcon::RowResize => NSCursor::resizeUpDownCursor(),
CursorIcon::Help => _helpCursor(),
CursorIcon::ZoomIn if available!(macos = 15.0) => unsafe { NSCursor::zoomInCursor() },
CursorIcon::ZoomIn if available!(macos = 15.0) => NSCursor::zoomInCursor(),
CursorIcon::ZoomIn => _zoomInCursor(),
CursorIcon::ZoomOut if available!(macos = 15.0) => unsafe { NSCursor::zoomOutCursor() },
CursorIcon::ZoomOut if available!(macos = 15.0) => NSCursor::zoomOutCursor(),
CursorIcon::ZoomOut => _zoomOutCursor(),
CursorIcon::NeResize => _windowResizeNorthEastCursor(),
CursorIcon::NwResize => _windowResizeNorthWestCursor(),

View File

@@ -67,9 +67,7 @@ pub fn get_modifierless_char(scancode: u16) -> Key {
// Ignores all modifiers except for SHIFT (yes, even ALT is ignored).
fn get_logical_key_char(ns_event: &NSEvent, modifierless_chars: &str) -> Key {
let string = unsafe { ns_event.charactersIgnoringModifiers() }
.map(|s| s.to_string())
.unwrap_or_default();
let string = ns_event.charactersIgnoringModifiers().map(|s| s.to_string()).unwrap_or_default();
if string.is_empty() {
// Probably a dead key
let first_char = modifierless_chars.chars().next();
@@ -85,7 +83,7 @@ pub(crate) fn create_key_event(ns_event: &NSEvent, is_press: bool, is_repeat: bo
use ElementState::{Pressed, Released};
let state = if is_press { Pressed } else { Released };
let scancode = unsafe { ns_event.keyCode() };
let scancode = ns_event.keyCode();
let mut physical_key = scancode_to_physicalkey(scancode as u32);
// NOTE: The logical key should heed both SHIFT and ALT if possible.
@@ -95,7 +93,7 @@ pub(crate) fn create_key_event(ns_event: &NSEvent, is_press: bool, is_repeat: bo
// * Pressing CTRL SHIFT A: logical key should also be "A"
// This is not easy to tease out of `NSEvent`, but we do our best.
let characters = unsafe { ns_event.characters() }.map(|s| s.to_string()).unwrap_or_default();
let characters = ns_event.characters().map(|s| s.to_string()).unwrap_or_default();
let text_with_all_modifiers = if characters.is_empty() {
None
} else {
@@ -111,13 +109,13 @@ pub(crate) fn create_key_event(ns_event: &NSEvent, is_press: bool, is_repeat: bo
// `get_modifierless_char/key_without_modifiers` ignores ALL modifiers.
let key_without_modifiers = get_modifierless_char(scancode);
let modifiers = unsafe { ns_event.modifierFlags() };
let modifiers = ns_event.modifierFlags();
let has_ctrl = modifiers.contains(NSEventModifierFlags::Control);
let has_cmd = modifiers.contains(NSEventModifierFlags::Command);
let logical_key = match text_with_all_modifiers.as_ref() {
// Only checking for ctrl and cmd here, not checking for alt because we DO want to
// include its effect in the key. For example if -on the Germay layout- one
// include its effect in the key. For example if -on the German layout- one
// presses alt+8, the logical key should be "{"
// Also not checking if this is a release event because then this issue would
// still affect the key release.
@@ -302,15 +300,15 @@ const NX_DEVICERALTKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x000000
const NX_DEVICERCTLKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00002000);
pub(super) fn lalt_pressed(event: &NSEvent) -> bool {
unsafe { event.modifierFlags() }.contains(NX_DEVICELALTKEYMASK)
event.modifierFlags().contains(NX_DEVICELALTKEYMASK)
}
pub(super) fn ralt_pressed(event: &NSEvent) -> bool {
unsafe { event.modifierFlags() }.contains(NX_DEVICERALTKEYMASK)
event.modifierFlags().contains(NX_DEVICERALTKEYMASK)
}
pub(super) fn event_mods(event: &NSEvent) -> Modifiers {
let flags = unsafe { event.modifierFlags() };
let flags = event.modifierFlags();
let mut state = ModifiersState::empty();
let mut pressed_mods = ModifiersKeys::empty();
@@ -334,8 +332,7 @@ pub(super) fn event_mods(event: &NSEvent) -> Modifiers {
}
pub(super) fn dummy_event() -> Option<Retained<NSEvent>> {
unsafe {
NSEvent::otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2(
NSEvent::otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2(
NSEventType::ApplicationDefined,
NSPoint::new(0.0, 0.0),
NSEventModifierFlags(0),
@@ -346,7 +343,6 @@ pub(super) fn dummy_event() -> Option<Retained<NSEvent>> {
0,
0,
)
}
}
pub fn physicalkey_to_scancode(physical_key: PhysicalKey) -> Option<u32> {

View File

@@ -2,9 +2,9 @@ use std::rc::Rc;
use std::sync::Arc;
use std::time::{Duration, Instant};
use objc2::rc::{autoreleasepool, Retained};
use objc2::rc::{Retained, autoreleasepool};
use objc2::runtime::ProtocolObject;
use objc2::{available, MainThreadMarker};
use objc2::{MainThreadMarker, available};
use objc2_app_kit::{
NSApplication, NSApplicationActivationPolicy, NSApplicationDidFinishLaunchingNotification,
NSApplicationWillTerminateNotification, NSWindow,
@@ -29,8 +29,8 @@ use super::event::dummy_event;
use super::monitor;
use super::notification_center::create_observer;
use super::observer::setup_control_flow_observers;
use crate::window::Window;
use crate::ActivationPolicy;
use crate::window::Window;
#[derive(Debug)]
pub struct ActiveEventLoop {
@@ -191,7 +191,7 @@ impl EventLoop {
// Override `sendEvent:` on the application to forward to our application state.
override_send_event(&app);
let center = unsafe { NSNotificationCenter::defaultCenter() };
let center = NSNotificationCenter::defaultCenter();
let weak_app_state = Rc::downgrade(&app_state);
let _did_finish_launching_observer = create_observer(

View File

@@ -6,7 +6,7 @@ use std::ffi::c_void;
use objc2::ffi::NSInteger;
use objc2::runtime::AnyObject;
use objc2_core_foundation::{cf_type, CFString, CFUUID};
use objc2_core_foundation::{CFString, CFUUID, cf_type};
use objc2_core_graphics::CGDirectDisplayID;
pub const IO16BitDirectPixels: &str = "-RRRRRGGGGGBBBBB";
@@ -22,14 +22,14 @@ pub const kIO64BitDirectPixels: &str = "-16R16G16B16";
// `ApplicationServices`, see:
// https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/OSX_Technology_Overview/SystemFrameworks/SystemFrameworks.html#//apple_ref/doc/uid/TP40001067-CH210-BBCFFIEG
#[link(name = "ApplicationServices", kind = "framework")]
extern "C" {
unsafe extern "C" {
pub fn CGDisplayCreateUUIDFromDisplayID(display: CGDirectDisplayID) -> *mut CFUUID;
pub fn CGDisplayGetDisplayIDFromUUID(uuid: &CFUUID) -> CGDirectDisplayID;
}
#[link(name = "CoreGraphics", kind = "framework")]
extern "C" {
unsafe extern "C" {
// Wildly used private APIs; Apple uses them for their Terminal.app.
pub fn CGSMainConnectionID() -> *mut AnyObject;
pub fn CGSSetWindowBackgroundBlurRadius(
@@ -60,7 +60,7 @@ pub const kUCKeyActionDisplay: u16 = 3;
pub const kUCKeyTranslateNoDeadKeysMask: OptionBits = 1;
#[link(name = "Carbon", kind = "framework")]
extern "C" {
unsafe extern "C" {
pub static kTISPropertyUnicodeKeyLayoutData: &'static CFString;
#[allow(non_snake_case)]

View File

@@ -20,7 +20,7 @@
//! ```
//! use objc2::rc::Retained;
//! use objc2::runtime::ProtocolObject;
//! use objc2::{define_class, msg_send, DefinedClass, MainThreadMarker, MainThreadOnly};
//! use objc2::{DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send};
//! use objc2_app_kit::{NSApplication, NSApplicationDelegate};
//! use objc2_foundation::{NSArray, NSObject, NSObjectProtocol, NSURL};
//! use winit::event_loop::EventLoop;

View File

@@ -1,8 +1,8 @@
use objc2::rc::Retained;
use objc2::runtime::Sel;
use objc2::{sel, MainThreadMarker};
use objc2::{MainThreadMarker, sel};
use objc2_app_kit::{NSApplication, NSEventModifierFlags, NSMenu, NSMenuItem};
use objc2_foundation::{ns_string, NSBundle, NSProcessInfo, NSString};
use objc2_foundation::{NSBundle, NSProcessInfo, NSString, ns_string};
struct KeyEquivalent<'a> {
key: &'a NSString,
@@ -82,7 +82,7 @@ pub fn initialize(app: &NSApplication) {
app_menu.addItem(&quit_item);
app_menu_item.setSubmenu(Some(&app_menu));
unsafe { app.setServicesMenu(Some(&services_menu)) };
app.setServicesMenu(Some(&services_menu));
app.setMainMenu(Some(&menubar));
}

View File

@@ -7,16 +7,16 @@ use std::{fmt, ptr};
use dispatch2::run_on_main;
use dpi::{LogicalPosition, PhysicalPosition, PhysicalSize};
use objc2::rc::Retained;
use objc2::MainThreadMarker;
use objc2::rc::Retained;
use objc2_app_kit::NSScreen;
use objc2_core_foundation::{CFArray, CFRetained, CFUUID};
use objc2_core_graphics::{
CGDirectDisplayID, CGDisplayBounds, CGDisplayCopyAllDisplayModes, CGDisplayCopyDisplayMode,
CGDisplayMode, CGDisplayModelNumber, CGGetActiveDisplayList, CGMainDisplayID,
};
use objc2_core_video::{kCVReturnSuccess, CVDisplayLink, CVTimeFlags};
use objc2_foundation::{ns_string, NSNumber, NSPoint, NSRect};
use objc2_core_video::{CVDisplayLink, CVTimeFlags, kCVReturnSuccess};
use objc2_foundation::{NSNumber, NSPoint, NSRect, ns_string};
use tracing::warn;
use winit_core::monitor::{MonitorHandleProvider, VideoMode};
@@ -65,35 +65,33 @@ impl VideoModeHandle {
native_mode: NativeDisplayMode,
refresh_rate_millihertz: Option<NonZeroU32>,
) -> Self {
unsafe {
// The bit-depth is basically always 32 since macOS 10.12.
#[allow(deprecated)]
let pixel_encoding =
CGDisplayMode::pixel_encoding(Some(&native_mode.0)).unwrap().to_string();
let bit_depth = if pixel_encoding.eq_ignore_ascii_case(ffi::IO32BitDirectPixels) {
NonZeroU16::new(32)
} else if pixel_encoding.eq_ignore_ascii_case(ffi::IO16BitDirectPixels) {
NonZeroU16::new(16)
} else if pixel_encoding.eq_ignore_ascii_case(ffi::kIO30BitDirectPixels) {
NonZeroU16::new(30)
} else if pixel_encoding.eq_ignore_ascii_case(ffi::kIO64BitDirectPixels) {
NonZeroU16::new(64)
} else {
warn!(?pixel_encoding, "unknown bit depth");
None
};
// The bit-depth is basically always 32 since macOS 10.12.
#[allow(deprecated)]
let pixel_encoding =
CGDisplayMode::pixel_encoding(Some(&native_mode.0)).unwrap().to_string();
let bit_depth = if pixel_encoding.eq_ignore_ascii_case(ffi::IO32BitDirectPixels) {
NonZeroU16::new(32)
} else if pixel_encoding.eq_ignore_ascii_case(ffi::IO16BitDirectPixels) {
NonZeroU16::new(16)
} else if pixel_encoding.eq_ignore_ascii_case(ffi::kIO30BitDirectPixels) {
NonZeroU16::new(30)
} else if pixel_encoding.eq_ignore_ascii_case(ffi::kIO64BitDirectPixels) {
NonZeroU16::new(64)
} else {
warn!(?pixel_encoding, "unknown bit depth");
None
};
let mode = VideoMode::new(
PhysicalSize::new(
CGDisplayMode::pixel_width(Some(&native_mode.0)) as u32,
CGDisplayMode::pixel_height(Some(&native_mode.0)) as u32,
),
bit_depth,
refresh_rate_millihertz,
);
let mode = VideoMode::new(
PhysicalSize::new(
CGDisplayMode::pixel_width(Some(&native_mode.0)) as u32,
CGDisplayMode::pixel_height(Some(&native_mode.0)) as u32,
),
bit_depth,
refresh_rate_millihertz,
);
VideoModeHandle { mode, monitor: monitor.clone(), native_mode }
}
Self { mode, monitor: monitor.clone(), native_mode }
}
}
@@ -137,11 +135,11 @@ impl MonitorHandle {
fn refresh_rate_millihertz(&self) -> Option<NonZeroU32> {
let current_display_mode =
NativeDisplayMode(unsafe { CGDisplayCopyDisplayMode(self.display_id()) }.unwrap());
NativeDisplayMode(CGDisplayCopyDisplayMode(self.display_id()).unwrap());
refresh_rate_millihertz(self.display_id(), &current_display_mode)
}
pub fn video_mode_handles(&self) -> impl Iterator<Item = VideoModeHandle> {
pub fn video_mode_handles(&self) -> impl Iterator<Item = VideoModeHandle> + 'static {
let refresh_rate_millihertz = self.refresh_rate_millihertz();
let monitor = self.clone();
@@ -159,7 +157,7 @@ impl MonitorHandle {
};
modes.into_iter().map(move |mode| {
let cg_refresh_rate_hertz = unsafe { CGDisplayMode::refresh_rate(Some(&mode)) };
let cg_refresh_rate_hertz = CGDisplayMode::refresh_rate(Some(&mode));
// CGDisplayModeGetRefreshRate returns 0.0 for any display that
// isn't a CRT
@@ -202,7 +200,7 @@ impl MonitorHandleProvider for MonitorHandle {
//
// <https://github.com/glfw/glfw/blob/57cbded0760a50b9039ee0cb3f3c14f60145567c/src/cocoa_monitor.m#L44-L126>
fn name(&self) -> Option<std::borrow::Cow<'_, str>> {
let screen_num = unsafe { CGDisplayModelNumber(self.display_id()) };
let screen_num = CGDisplayModelNumber(self.display_id());
Some(format!("Monitor #{screen_num}").into())
}
@@ -210,7 +208,7 @@ impl MonitorHandleProvider for MonitorHandle {
// This is already in screen coordinates. If we were using `NSScreen`,
// then a conversion would've been needed:
// flip_window_screen_coordinates(self.ns_screen(mtm)?.frame())
let bounds = unsafe { CGDisplayBounds(self.display_id()) };
let bounds = CGDisplayBounds(self.display_id());
let position = LogicalPosition::new(bounds.origin.x, bounds.origin.y);
Some(position.to_physical(self.scale_factor()))
}
@@ -225,8 +223,7 @@ impl MonitorHandleProvider for MonitorHandle {
}
fn current_video_mode(&self) -> Option<VideoMode> {
let mode =
NativeDisplayMode(unsafe { CGDisplayCopyDisplayMode(self.display_id()) }.unwrap());
let mode = NativeDisplayMode(CGDisplayCopyDisplayMode(self.display_id()).unwrap());
let refresh_rate_millihertz = refresh_rate_millihertz(self.display_id(), &mode);
Some(VideoModeHandle::new(self.clone(), mode, refresh_rate_millihertz).mode)
}
@@ -264,7 +261,7 @@ pub fn available_monitors() -> VecDeque<MonitorHandle> {
pub fn primary_monitor() -> MonitorHandle {
// Display ID just fetched from `CGMainDisplayID`, should be fine to unwrap.
MonitorHandle::new(unsafe { CGMainDisplayID() }).expect("invalid display ID")
MonitorHandle::new(CGMainDisplayID()).expect("invalid display ID")
}
impl fmt::Debug for MonitorHandle {
@@ -315,40 +312,38 @@ pub(crate) fn flip_window_screen_coordinates(frame: NSRect) -> NSPoint {
// It is intentional that we use `CGMainDisplayID` (as opposed to
// `NSScreen::mainScreen`), because that's what the screen coordinates
// are relative to, no matter which display the window is currently on.
let main_screen_height = unsafe { CGDisplayBounds(CGMainDisplayID()) }.size.height;
let main_screen_height = CGDisplayBounds(CGMainDisplayID()).size.height;
let y = main_screen_height - frame.size.height - frame.origin.y;
NSPoint::new(frame.origin.x, y)
}
fn refresh_rate_millihertz(id: CGDirectDisplayID, mode: &NativeDisplayMode) -> Option<NonZeroU32> {
unsafe {
let refresh_rate = CGDisplayMode::refresh_rate(Some(&mode.0));
if refresh_rate > 0.0 {
return NonZeroU32::new((refresh_rate * 1000.0).round() as u32);
}
let mut display_link = std::ptr::null_mut();
#[allow(deprecated)]
if CVDisplayLink::create_with_cg_display(id, NonNull::from(&mut display_link))
!= kCVReturnSuccess
{
return None;
}
let display_link = CFRetained::from_raw(NonNull::new(display_link).unwrap());
#[allow(deprecated)]
let time = display_link.nominal_output_video_refresh_period();
// This value is indefinite if an invalid display link was specified
if time.flags & CVTimeFlags::IsIndefinite.0 != 0 {
return None;
}
(time.timeScale as i64)
.checked_div(time.timeValue)
.map(|v| (v * 1000) as u32)
.and_then(NonZeroU32::new)
let refresh_rate = CGDisplayMode::refresh_rate(Some(&mode.0));
if refresh_rate > 0.0 {
return NonZeroU32::new((refresh_rate * 1000.0).round() as u32);
}
let mut display_link = std::ptr::null_mut();
#[allow(deprecated)]
if unsafe { CVDisplayLink::create_with_cg_display(id, NonNull::from(&mut display_link)) }
!= kCVReturnSuccess
{
return None;
}
let display_link = unsafe { CFRetained::from_raw(NonNull::new(display_link).unwrap()) };
#[allow(deprecated)]
let time = display_link.nominal_output_video_refresh_period();
// This value is indefinite if an invalid display link was specified
if time.flags & CVTimeFlags::IsIndefinite.0 != 0 {
return None;
}
(time.timeScale as i64)
.checked_div(time.timeValue)
.map(|v| (v * 1000) as u32)
.and_then(NonZeroU32::new)
}
#[cfg(test)]
@@ -357,8 +352,10 @@ mod tests {
#[test]
fn uuid_stable() {
let handle_a = MonitorHandle::new(1).unwrap();
let handle_b = MonitorHandle::new(1).unwrap();
let primary_id = CGMainDisplayID();
let handle_a = MonitorHandle::new(primary_id).unwrap();
let handle_b = MonitorHandle::new(primary_id).unwrap();
assert_eq!(handle_a, handle_b);
assert_eq!(handle_a.display_id(), handle_b.display_id());
assert_eq!(handle_a.uuid(), handle_b.uuid());
@@ -373,8 +370,10 @@ mod tests {
/// Test the MonitorHandle::new fallback.
#[test]
fn monitorhandle_from_zero() {
let primary_id = CGMainDisplayID();
let handle0 = MonitorHandle::new(0).unwrap();
let handle1 = MonitorHandle::new(1).unwrap();
let handle1 = MonitorHandle::new(primary_id).unwrap();
assert_eq!(handle0, handle1);
assert_eq!(handle0.display_id(), handle1.display_id());
assert_eq!(handle0.uuid(), handle1.uuid());
@@ -395,7 +394,7 @@ mod tests {
// Assertion failed: (did_initialize), function CGS_REQUIRE_INIT, file CGInitialization.c, line 44.
// ```
// See https://github.com/JXA-Cookbook/JXA-Cookbook/issues/27#issuecomment-277517668
let _ = unsafe { CGMainDisplayID() };
let _ = CGMainDisplayID();
let handle = MonitorHandle(CFUUID::new(None).unwrap());
assert_eq!(handle.display_id(), 0);

View File

@@ -9,9 +9,9 @@ use std::time::Instant;
use objc2::MainThreadMarker;
use objc2_core_foundation::{
kCFRunLoopCommonModes, kCFRunLoopDefaultMode, CFAbsoluteTimeGetCurrent, CFIndex, CFRetained,
CFRunLoop, CFRunLoopActivity, CFRunLoopObserver, CFRunLoopObserverCallBack,
CFRunLoopObserverContext, CFRunLoopTimer,
CFAbsoluteTimeGetCurrent, CFIndex, CFRetained, CFRunLoop, CFRunLoopActivity, CFRunLoopObserver,
CFRunLoopObserverCallBack, CFRunLoopObserverContext, CFRunLoopTimer, kCFRunLoopCommonModes,
kCFRunLoopDefaultMode,
};
use tracing::error;

View File

@@ -3,9 +3,7 @@ use tracing::trace;
use winit_core::error::OsError;
macro_rules! os_error {
($error:expr) => {{
winit_core::error::OsError::new(line!(), file!(), $error)
}};
($error:expr) => {{ winit_core::error::OsError::new(line!(), file!(), $error) }};
}
macro_rules! trace_scope {
@@ -36,9 +34,5 @@ impl Drop for TraceGuard {
#[track_caller]
pub(crate) fn cgerr(err: CGError) -> Result<(), OsError> {
if err == CGError::Success {
Ok(())
} else {
Err(os_error!(format!("CGError {err:?}")))
}
if err == CGError::Success { Ok(()) } else { Err(os_error!(format!("CGError {err:?}"))) }
}

View File

@@ -7,7 +7,7 @@ use std::rc::Rc;
use dpi::{LogicalPosition, LogicalSize};
use objc2::rc::Retained;
use objc2::runtime::{AnyObject, Sel};
use objc2::{define_class, msg_send, DefinedClass, MainThreadMarker};
use objc2::{DefinedClass, MainThreadMarker, define_class, msg_send};
use objc2_app_kit::{
NSApplication, NSCursor, NSEvent, NSEventPhase, NSResponder, NSTextInputClient,
NSTrackingRectTag, NSView, NSWindow,
@@ -292,7 +292,7 @@ define_class!(
self.queue_event(WindowEvent::Ime(Ime::Enabled));
}
if unsafe { self.hasMarkedText() } {
if self.hasMarkedText() {
self.ivars().ime_state.set(ImeState::Preedit);
} else {
// In case the preedit was cleared, set IME into the Ground state.
@@ -305,8 +305,8 @@ define_class!(
None
} else {
// Convert the selected range from UTF-16 indices to UTF-8 indices.
let sub_string_a = unsafe { string.substringToIndex(selected_range.location) };
let sub_string_b = unsafe { string.substringToIndex(selected_range.end()) };
let sub_string_a = string.substringToIndex(selected_range.location);
let sub_string_b = string.substringToIndex(selected_range.end());
let lowerbound_utf8 = sub_string_a.len();
let upperbound_utf8 = sub_string_b.len();
Some((lowerbound_utf8, upperbound_utf8))
@@ -391,7 +391,7 @@ define_class!(
let is_control = string.chars().next().is_some_and(|c| c.is_control());
// Commit only if we have marked text.
if unsafe { self.hasMarkedText() } && self.is_ime_enabled() && !is_control {
if self.hasMarkedText() && self.is_ime_enabled() && !is_control {
self.queue_event(WindowEvent::Ime(Ime::Preedit(String::new(), None)));
self.queue_event(WindowEvent::Ime(Ime::Commit(string)));
self.ivars().ime_state.set(ImeState::Committed);
@@ -414,8 +414,7 @@ define_class!(
self.ivars().forward_key_to_app.set(true);
if unsafe { self.hasMarkedText() } && self.ivars().ime_state.get() == ImeState::Preedit
{
if self.hasMarkedText() && self.ivars().ime_state.get() == ImeState::Preedit {
// Leave preedit so that we also report the key-up for this key.
self.ivars().ime_state.set(ImeState::Ground);
}
@@ -467,7 +466,7 @@ define_class!(
// is not handled by IME and should be handled by the application)
if self.ivars().ime_capabilities.get().is_some() {
let events_for_nsview = NSArray::from_slice(&[&*event]);
unsafe { self.interpretKeyEvents(&events_for_nsview) };
self.interpretKeyEvents(&events_for_nsview);
// If the text was committed we must treat the next keyboard event as IME related.
if self.ivars().ime_state.get() == ImeState::Committed {
@@ -490,7 +489,7 @@ define_class!(
};
if !had_ime_input || self.ivars().forward_key_to_app.get() {
let key_event = create_key_event(&event, true, unsafe { event.isARepeat() });
let key_event = create_key_event(&event, true, event.isARepeat());
self.queue_event(WindowEvent::KeyboardInput {
device_id: None,
event: key_event,
@@ -557,7 +556,7 @@ define_class!(
.expect("could not find current event");
self.update_modifiers(&event, false);
let event = create_key_event(&event, true, unsafe { event.isARepeat() });
let event = create_key_event(&event, true, event.isARepeat());
self.queue_event(WindowEvent::KeyboardInput {
device_id: None,
@@ -676,8 +675,8 @@ define_class!(
self.mouse_motion(event);
let delta = {
let (x, y) = unsafe { (event.scrollingDeltaX(), event.scrollingDeltaY()) };
if unsafe { event.hasPreciseScrollingDeltas() } {
let (x, y) = (event.scrollingDeltaX(), event.scrollingDeltaY());
if event.hasPreciseScrollingDeltas() {
let delta = LogicalPosition::new(x, y).to_physical(self.scale_factor());
MouseScrollDelta::PixelDelta(delta)
} else {
@@ -690,10 +689,10 @@ define_class!(
// momentum phase is recorded (or rather, the started/ended cases of the
// momentum phase) then we report the touch phase.
#[allow(non_upper_case_globals)]
let phase = match unsafe { event.momentumPhase() } {
let phase = match event.momentumPhase() {
NSEventPhase::MayBegin | NSEventPhase::Began => TouchPhase::Started,
NSEventPhase::Ended | NSEventPhase::Cancelled => TouchPhase::Ended,
_ => match unsafe { event.phase() } {
_ => match event.phase() {
NSEventPhase::MayBegin | NSEventPhase::Began => TouchPhase::Started,
NSEventPhase::Ended | NSEventPhase::Cancelled => TouchPhase::Ended,
_ => TouchPhase::Moved,
@@ -715,7 +714,7 @@ define_class!(
self.mouse_motion(event);
#[allow(non_upper_case_globals)]
let phase = match unsafe { event.phase() } {
let phase = match event.phase() {
NSEventPhase::Began => TouchPhase::Started,
NSEventPhase::Changed => TouchPhase::Moved,
NSEventPhase::Cancelled => TouchPhase::Cancelled,
@@ -725,7 +724,7 @@ define_class!(
self.queue_event(WindowEvent::PinchGesture {
device_id: None,
delta: unsafe { event.magnification() },
delta: event.magnification(),
phase,
});
}
@@ -746,7 +745,7 @@ define_class!(
self.mouse_motion(event);
#[allow(non_upper_case_globals)]
let phase = match unsafe { event.phase() } {
let phase = match event.phase() {
NSEventPhase::Began => TouchPhase::Started,
NSEventPhase::Changed => TouchPhase::Moved,
NSEventPhase::Cancelled => TouchPhase::Cancelled,
@@ -756,7 +755,7 @@ define_class!(
self.queue_event(WindowEvent::RotationGesture {
device_id: None,
delta: unsafe { event.rotation() },
delta: event.rotation(),
phase,
});
}
@@ -767,8 +766,8 @@ define_class!(
self.queue_event(WindowEvent::TouchpadPressure {
device_id: None,
pressure: unsafe { event.pressure() },
stage: unsafe { event.stage() } as i64,
pressure: event.pressure(),
stage: event.stage() as i64,
});
}
@@ -931,8 +930,8 @@ impl WinitView {
// later will work though, since the flags are attached to the event and contain valid
// information.
'send_event: {
if is_flags_changed_event && unsafe { ns_event.keyCode() } != 0 {
let scancode = unsafe { ns_event.keyCode() };
if is_flags_changed_event && ns_event.keyCode() != 0 {
let scancode = ns_event.keyCode();
let physical_key = scancode_to_physicalkey(scancode as u32);
let logical_key = code_to_key(physical_key, scancode);
@@ -1064,7 +1063,7 @@ impl WinitView {
|| view_point.x > frame.size.width
|| view_point.y > frame.size.height
{
let mouse_buttons_down = unsafe { NSEvent::pressedMouseButtons() };
let mouse_buttons_down = NSEvent::pressedMouseButtons();
if mouse_buttons_down == 0 {
// Point is outside of the client area (view) and no buttons are pressed
return;
@@ -1082,7 +1081,7 @@ impl WinitView {
}
fn mouse_view_point(&self, event: &NSEvent) -> LogicalPosition<f64> {
let window_point = unsafe { event.locationInWindow() };
let window_point = event.locationInWindow();
let view_point = self.convertPoint_fromView(window_point, None);
LogicalPosition::new(view_point.x, view_point.y)
@@ -1096,14 +1095,11 @@ fn mouse_button(event: &NSEvent) -> MouseButton {
// For the other events, it's always set to 0.
// MacOS only defines the left, right and middle buttons, 3..=31 are left as generic buttons,
// but 3 and 4 are very commonly used as Back and Forward by hardware vendors and applications.
match unsafe { event.buttonNumber() } {
0 => MouseButton::Left,
1 => MouseButton::Right,
2 => MouseButton::Middle,
3 => MouseButton::Back,
4 => MouseButton::Forward,
n => MouseButton::Other(n as u16),
}
let b: isize = event.buttonNumber();
b.try_into()
.ok()
.and_then(MouseButton::try_from_u8)
.expect("expected MacOS button number in the range 0..=31")
}
// NOTE: to get option as alt working we need to rewrite events
@@ -1120,12 +1116,10 @@ fn replace_event(event: &NSEvent, option_as_alt: OptionAsAlt) -> Retained<NSEven
&& !ev_mods.meta_key();
if ignore_alt_characters {
let ns_chars = unsafe {
event.charactersIgnoringModifiers().expect("expected characters to be non-null")
};
let ns_chars =
event.charactersIgnoringModifiers().expect("expected characters to be non-null");
unsafe {
NSEvent::keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode(
NSEvent::keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode(
event.r#type(),
event.locationInWindow(),
event.modifierFlags(),
@@ -1138,7 +1132,6 @@ fn replace_event(event: &NSEvent, option_as_alt: OptionAsAlt) -> Retained<NSEven
event.keyCode(),
)
.unwrap()
}
} else {
event.copy()
}

View File

@@ -4,8 +4,8 @@ use std::sync::Arc;
use dispatch2::MainThreadBound;
use dpi::{Position, Size};
use objc2::rc::{autoreleasepool, Retained};
use objc2::{define_class, MainThreadMarker, Message};
use objc2::rc::{Retained, autoreleasepool};
use objc2::{MainThreadMarker, Message, define_class};
use objc2_app_kit::{NSPanel, NSResponder, NSWindow};
use objc2_foundation::NSObject;
use winit_core::cursor::Cursor;

View File

@@ -10,34 +10,36 @@ use dpi::{
LogicalInsets, LogicalPosition, LogicalSize, PhysicalInsets, PhysicalPosition, PhysicalSize,
Position, Size,
};
use objc2::rc::{autoreleasepool, Retained};
use objc2::rc::{Retained, autoreleasepool};
use objc2::runtime::{AnyObject, ProtocolObject};
use objc2::{
available, define_class, msg_send, sel, ClassType, DefinedClass, MainThreadMarker,
MainThreadOnly, Message,
ClassType, DefinedClass, MainThreadMarker, MainThreadOnly, Message, available, define_class,
msg_send, sel,
};
use objc2_app_kit::{
NSAppKitVersionNumber, NSAppKitVersionNumber10_12, NSAppearance, NSAppearanceCustomization,
NSAppearanceNameAqua, NSApplication, NSApplicationPresentationOptions, NSBackingStoreType,
NSColor, NSDraggingDestination, NSDraggingInfo, NSFilenamesPboardType,
NSRequestUserAttentionType, NSScreen, NSToolbar, NSView, NSViewFrameDidChangeNotification,
NSWindow, NSWindowButton, NSWindowDelegate, NSWindowFullScreenButton, NSWindowLevel,
NSWindowOcclusionState, NSWindowOrderingMode, NSWindowSharingType, NSWindowStyleMask,
NSWindowTabbingMode, NSWindowTitleVisibility, NSWindowToolbarStyle,
NSColor, NSDraggingDestination, NSDraggingInfo, NSRequestUserAttentionType, NSScreen,
NSToolbar, NSView, NSViewFrameDidChangeNotification, NSWindow, NSWindowButton,
NSWindowDelegate, NSWindowLevel, NSWindowOcclusionState, NSWindowOrderingMode,
NSWindowSharingType, NSWindowStyleMask, NSWindowTabbingMode, NSWindowTitleVisibility,
NSWindowToolbarStyle,
};
#[allow(deprecated)]
use objc2_app_kit::{NSFilenamesPboardType, NSWindowFullScreenButton};
use objc2_core_foundation::{CGFloat, CGPoint};
use objc2_core_graphics::{
kCGDisplayBlendNormal, kCGDisplayBlendSolidColor, kCGDisplayFadeReservationInvalidToken,
kCGFloatingWindowLevel, kCGNormalWindowLevel, CGAcquireDisplayFadeReservation,
CGAssociateMouseAndMouseCursorPosition, CGDisplayCapture, CGDisplayFade, CGDisplayRelease,
CGDisplaySetDisplayMode, CGReleaseDisplayFadeReservation,
CGAcquireDisplayFadeReservation, CGAssociateMouseAndMouseCursorPosition, CGDisplayCapture,
CGDisplayFade, CGDisplayRelease, CGDisplaySetDisplayMode, CGReleaseDisplayFadeReservation,
CGRestorePermanentDisplayConfiguration, CGShieldingWindowLevel, CGWarpMouseCursorPosition,
kCGDisplayBlendNormal, kCGDisplayBlendSolidColor, kCGDisplayFadeReservationInvalidToken,
kCGFloatingWindowLevel, kCGNormalWindowLevel,
};
use objc2_foundation::{
ns_string, NSArray, NSDictionary, NSEdgeInsets, NSKeyValueChangeKey, NSKeyValueChangeNewKey,
NSArray, NSDictionary, NSEdgeInsets, NSKeyValueChangeKey, NSKeyValueChangeNewKey,
NSKeyValueChangeOldKey, NSKeyValueObservingOptions, NSNotificationCenter, NSObject,
NSObjectNSDelayedPerforming, NSObjectNSKeyValueObserverRegistration, NSObjectProtocol, NSPoint,
NSRect, NSSize, NSString,
NSRect, NSSize, NSString, ns_string,
};
use tracing::{trace, warn};
use winit_core::cursor::Cursor;
@@ -51,13 +53,13 @@ use winit_core::window::{
};
use super::app_state::AppState;
use super::cursor::{cursor_from_icon, CustomCursor};
use super::cursor::{CustomCursor, cursor_from_icon};
use super::ffi;
use super::monitor::{self, flip_window_screen_coordinates, get_display_id, MonitorHandle};
use super::monitor::{self, MonitorHandle, flip_window_screen_coordinates, get_display_id};
use super::observer::RunLoop;
use super::util::cgerr;
use super::view::WinitView;
use super::window::{window_id, WinitPanel, WinitWindow};
use super::window::{WinitPanel, WinitWindow, window_id};
use crate::{OptionAsAlt, WindowAttributesMacOS, WindowExtMacOS};
#[derive(Debug)]
@@ -350,18 +352,22 @@ define_class!(
use std::path::PathBuf;
let pb = unsafe { sender.draggingPasteboard() };
let filenames = pb
.propertyListForType(unsafe { NSFilenamesPboardType })
.unwrap()
let pb = sender.draggingPasteboard();
#[allow(deprecated)]
let property_list = match pb.propertyListForType(unsafe { NSFilenamesPboardType }) {
Some(property_list) => property_list,
None => return false.into(),
};
let paths = property_list
.downcast::<NSArray>()
.unwrap();
let paths = filenames
.unwrap()
.into_iter()
.map(|file| PathBuf::from(file.downcast::<NSString>().unwrap().to_string()))
.collect();
let dl = unsafe { sender.draggingLocation() };
let dl = sender.draggingLocation();
let dl = self.view().convertPoint_fromView(dl, None);
let position =
LogicalPosition::<f64>::from((dl.x, dl.y)).to_physical(self.scale_factor());
@@ -383,7 +389,7 @@ define_class!(
fn dragging_updated(&self, sender: &ProtocolObject<dyn NSDraggingInfo>) -> bool {
trace_scope!("draggingUpdated:");
let dl = unsafe { sender.draggingLocation() };
let dl = sender.draggingLocation();
let dl = self.view().convertPoint_fromView(dl, None);
let position =
LogicalPosition::<f64>::from((dl.x, dl.y)).to_physical(self.scale_factor());
@@ -407,18 +413,22 @@ define_class!(
use std::path::PathBuf;
let pb = unsafe { sender.draggingPasteboard() };
let filenames = pb
.propertyListForType(unsafe { NSFilenamesPboardType })
.unwrap()
let pb = sender.draggingPasteboard();
#[allow(deprecated)]
let property_list = match pb.propertyListForType(unsafe { NSFilenamesPboardType }) {
Some(property_list) => property_list,
None => return false.into(),
};
let paths = property_list
.downcast::<NSArray>()
.unwrap();
let paths = filenames
.unwrap()
.into_iter()
.map(|file| PathBuf::from(file.downcast::<NSString>().unwrap().to_string()))
.collect();
let dl = unsafe { sender.draggingLocation() };
let dl = sender.draggingLocation();
let dl = self.view().convertPoint_fromView(dl, None);
let position =
LogicalPosition::<f64>::from((dl.x, dl.y)).to_physical(self.scale_factor());
@@ -440,7 +450,7 @@ define_class!(
trace_scope!("draggingExited:");
let position = sender.map(|sender| {
let dl = unsafe { sender.draggingLocation() };
let dl = sender.draggingLocation();
let dl = self.view().convertPoint_fromView(dl, None);
LogicalPosition::<f64>::from((dl.x, dl.y)).to_physical(self.scale_factor())
});
@@ -477,12 +487,12 @@ define_class!(
let old = old.downcast::<NSAppearance>().unwrap();
let new = new.downcast::<NSAppearance>().unwrap();
trace!(old = %unsafe { old.name() }, new = %unsafe { new.name() }, "effectiveAppearance changed");
trace!(old = %old.name(), new = %new.name(), "effectiveAppearance changed");
// Ignore the change if the window's theme is customized by the user (since in that
// case the `effectiveAppearance` is only emitted upon said customization, and then
// it's triggered directly by a user action, and we don't want to emit the event).
if unsafe { self.window().appearance() }.is_some() {
if self.window().appearance().is_some() {
return;
}
@@ -505,9 +515,7 @@ define_class!(
impl Drop for WindowDelegate {
fn drop(&mut self) {
unsafe {
self.window().removeObserver_forKeyPath(self, ns_string!("effectiveAppearance"));
}
unsafe { self.window().removeObserver_forKeyPath(self, ns_string!("effectiveAppearance")) };
}
}
@@ -666,12 +674,10 @@ fn new_window(
window.setMovableByWindowBackground(true);
}
if macos_attrs.unified_titlebar {
unsafe {
// The toolbar style is ignored if there is no toolbar, so it is
// necessary to add one.
window.setToolbar(Some(&NSToolbar::new(mtm)));
window.setToolbarStyle(NSWindowToolbarStyle::Unified);
}
// The toolbar style is ignored if there is no toolbar, so it is
// necessary to add one.
window.setToolbar(Some(&NSToolbar::new(mtm)));
window.setToolbarStyle(NSWindowToolbarStyle::Unified);
}
if !attrs.enabled_buttons.contains(WindowButtons::MAXIMIZE) {
@@ -720,7 +726,7 @@ fn new_window(
view.setPostsFrameChangedNotifications(true);
// `setPostsFrameChangedNotifications` posts the notification immediately, so register the
// observer _after_, again so that the event isn't triggered initially.
let notification_center = unsafe { NSNotificationCenter::defaultCenter() };
let notification_center = NSNotificationCenter::defaultCenter();
unsafe {
notification_center.addObserver_selector_name_object(
&view,
@@ -733,10 +739,11 @@ fn new_window(
if attrs.transparent {
window.setOpaque(false);
// See `set_transparent` for details on why we do this.
window.setBackgroundColor(unsafe { Some(&NSColor::clearColor()) });
window.setBackgroundColor(Some(&NSColor::clearColor()));
}
// register for drag and drop operations.
#[allow(deprecated)]
window.registerForDraggedTypes(&NSArray::from_slice(&[unsafe { NSFilenamesPboardType }]));
Some(window)
@@ -790,7 +797,7 @@ impl WindowDelegate {
let scale_factor = window.backingScaleFactor() as _;
if let Some(appearance) = theme_to_appearance(attrs.preferred_theme) {
unsafe { window.setAppearance(Some(&appearance)) };
window.setAppearance(Some(&appearance));
}
let delegate = mtm.alloc().set_ivars(State {
@@ -945,11 +952,8 @@ impl WindowDelegate {
// transparent, as in that case, the transparent contents will just be drawn on top of
// the background color. As such, to allow the window to be transparent, we must also set
// the background color to one with an empty alpha channel.
let color = if transparent {
unsafe { NSColor::clearColor() }
} else {
unsafe { NSColor::windowBackgroundColor() }
};
let color =
if transparent { NSColor::clearColor() } else { NSColor::windowBackgroundColor() };
self.window().setBackgroundColor(Some(&color));
}
@@ -958,7 +962,7 @@ impl WindowDelegate {
// NOTE: in general we want to specify the blur radius, but the choice of 80
// should be a reasonable default.
let radius = if blur { 80 } else { 0 };
let window_number = unsafe { self.window().windowNumber() };
let window_number = self.window().windowNumber();
unsafe {
ffi::CGSSetWindowBackgroundBlurRadius(
ffi::CGSMainConnectionID(),
@@ -1017,7 +1021,7 @@ impl WindowDelegate {
NSPoint::new(position.x, position.y),
self.window().frame().size,
));
unsafe { self.window().setFrameOrigin(point) };
self.window().setFrameOrigin(point);
}
#[inline]
@@ -1039,17 +1043,15 @@ impl WindowDelegate {
let insets = if self.view().respondsToSelector(sel!(safeAreaInsets)) {
// Includes NSWindowStyleMask::FullSizeContentView by default, and the notch because
// we've set it up with `additionalSafeAreaInsets`.
unsafe { self.view().safeAreaInsets() }
self.view().safeAreaInsets()
} else {
// If `safeAreaInsets` is not available, we'll have to do the calculation ourselves.
let window_rect = unsafe {
self.window().convertRectFromScreen(
self.window().contentRectForFrameRect(self.window().frame()),
)
};
let window_rect = self.window().convertRectFromScreen(
self.window().contentRectForFrameRect(self.window().frame()),
);
// This includes NSWindowStyleMask::FullSizeContentView.
let layout_rect = unsafe { self.window().contentLayoutRect() };
let layout_rect = self.window().contentLayoutRect();
// Calculate the insets from window coordinates in AppKit's coordinate system.
NSEdgeInsets {
@@ -1079,7 +1081,7 @@ impl WindowDelegate {
let min_size = dimensions.to_logical::<CGFloat>(self.scale_factor());
let min_size = NSSize::new(min_size.width, min_size.height);
unsafe { self.window().setContentMinSize(min_size) };
self.window().setContentMinSize(min_size);
// If necessary, resize the window to match constraint
let mut current_size = self.window().contentRectForFrameRect(self.window().frame()).size;
@@ -1101,7 +1103,7 @@ impl WindowDelegate {
let max_size = dimensions.to_logical::<CGFloat>(scale_factor);
let max_size = NSSize::new(max_size.width, max_size.height);
unsafe { self.window().setContentMaxSize(max_size) };
self.window().setContentMaxSize(max_size);
// If necessary, resize the window to match constraint
let mut current_size = self.window().contentRectForFrameRect(self.window().frame()).size;
@@ -1241,12 +1243,12 @@ impl WindowDelegate {
CursorGrabMode::Locked => false,
CursorGrabMode::None => true,
CursorGrabMode::Confined => {
return Err(NotSupportedError::new("confined cursor is not supported").into())
return Err(NotSupportedError::new("confined cursor is not supported").into());
},
};
// TODO: Do this for real https://stackoverflow.com/a/40922095/5435443
cgerr(unsafe { CGAssociateMouseAndMouseCursorPosition(associate_mouse_cursor) })?;
cgerr(CGAssociateMouseAndMouseCursorPosition(associate_mouse_cursor))?;
Ok(())
}
@@ -1274,8 +1276,8 @@ impl WindowDelegate {
x: window_position.x + cursor_position.x,
y: window_position.y + cursor_position.y,
};
cgerr(unsafe { CGWarpMouseCursorPosition(point) })?;
cgerr(unsafe { CGAssociateMouseAndMouseCursorPosition(true) })?;
cgerr(CGWarpMouseCursorPosition(point))?;
cgerr(CGAssociateMouseAndMouseCursorPosition(true))?;
Ok(())
}
@@ -1356,7 +1358,7 @@ impl WindowDelegate {
if minimized {
self.window().miniaturize(Some(self));
} else {
unsafe { self.window().deminiaturize(Some(self)) };
self.window().deminiaturize(Some(self));
}
}
@@ -1450,7 +1452,7 @@ impl WindowDelegate {
let old_screen = self.window().screen().unwrap();
if old_screen != new_screen {
unsafe { self.window().setFrameOrigin(new_screen.frame().origin) };
self.window().setFrameOrigin(new_screen.frame().origin);
}
}
@@ -1475,25 +1477,23 @@ impl WindowDelegate {
self.ivars().save_presentation_opts.replace(Some(app.presentationOptions()));
}
unsafe {
// Fade to black (and wait for the fade to complete) to hide the
// flicker from capturing the display and switching display mode
if cgerr(CGAcquireDisplayFadeReservation(5.0, &mut fade_token)).is_ok() {
CGDisplayFade(
fade_token,
0.3,
kCGDisplayBlendNormal,
kCGDisplayBlendSolidColor,
0.0,
0.0,
0.0,
true,
);
}
cgerr(CGDisplayCapture(display_id)).unwrap();
// Fade to black (and wait for the fade to complete) to hide the
// flicker from capturing the display and switching display mode
if cgerr(unsafe { CGAcquireDisplayFadeReservation(5.0, &mut fade_token) }).is_ok() {
CGDisplayFade(
fade_token,
0.3,
kCGDisplayBlendNormal,
kCGDisplayBlendSolidColor,
0.0,
0.0,
0.0,
true,
);
}
cgerr(CGDisplayCapture(display_id)).unwrap();
let monitor = monitor.cast_ref::<MonitorHandle>().unwrap();
let video_mode =
match monitor.video_mode_handles().find(|mode| &mode.mode == video_mode) {
@@ -1501,25 +1501,25 @@ impl WindowDelegate {
None => return,
};
unsafe {
cgerr(CGDisplaySetDisplayMode(display_id, Some(&video_mode.native_mode.0), None))
.expect("failed to set video mode");
cgerr(unsafe {
CGDisplaySetDisplayMode(display_id, Some(&video_mode.native_mode.0), None)
})
.expect("failed to set video mode");
// After the display has been configured, fade back in
// asynchronously
if fade_token != kCGDisplayFadeReservationInvalidToken {
CGDisplayFade(
fade_token,
0.6,
kCGDisplayBlendSolidColor,
kCGDisplayBlendNormal,
0.0,
0.0,
0.0,
false,
);
CGReleaseDisplayFadeReservation(fade_token);
}
// After the display has been configured, fade back in
// asynchronously
if fade_token != kCGDisplayFadeReservationInvalidToken {
CGDisplayFade(
fade_token,
0.6,
kCGDisplayBlendSolidColor,
kCGDisplayBlendNormal,
0.0,
0.0,
0.0,
false,
);
CGReleaseDisplayFadeReservation(fade_token);
}
}
@@ -1582,7 +1582,7 @@ impl WindowDelegate {
| NSApplicationPresentationOptions::HideMenuBar;
app.setPresentationOptions(presentation_options);
let window_level = unsafe { CGShieldingWindowLevel() } as NSWindowLevel + 1;
let window_level = CGShieldingWindowLevel() as NSWindowLevel + 1;
self.window().setLevel(window_level);
},
(Some(Fullscreen::Exclusive(monitor, _)), Some(Fullscreen::Borderless(_))) => {
@@ -1797,9 +1797,8 @@ impl WindowDelegate {
}
pub fn theme(&self) -> Option<Theme> {
unsafe { self.window().appearance() }
.map(|appearance| appearance_to_theme(&appearance))
.or_else(|| {
self.window().appearance().map(|appearance| appearance_to_theme(&appearance)).or_else(
|| {
let mtm = MainThreadMarker::from(self);
let app = NSApplication::sharedApplication(mtm);
@@ -1808,11 +1807,12 @@ impl WindowDelegate {
} else {
Some(Theme::Light)
}
})
},
)
}
pub fn set_theme(&self, theme: Option<Theme>) {
unsafe { self.window().setAppearance(theme_to_appearance(theme).as_deref()) };
self.window().setAppearance(theme_to_appearance(theme).as_deref());
}
#[inline]
@@ -1836,10 +1836,8 @@ impl WindowDelegate {
fn restore_and_release_display(monitor: &MonitorHandle) {
let available_monitors = monitor::available_monitors();
if available_monitors.contains(monitor) {
unsafe {
CGRestorePermanentDisplayConfiguration();
cgerr(CGDisplayRelease(monitor.native_id() as _)).unwrap();
};
CGRestorePermanentDisplayConfiguration();
cgerr(CGDisplayRelease(monitor.native_id() as _)).unwrap();
} else {
warn!(
monitor = monitor.name().map(|name| name.to_string()),
@@ -1901,7 +1899,7 @@ impl WindowExtMacOS for WindowDelegate {
// Configure the safe area rectangle, to ensure that we don't obscure the notch.
if NSScreen::class().responds_to(sel!(safeAreaInsets)) {
unsafe { self.view().setAdditionalSafeAreaInsets(screen.safeAreaInsets()) };
self.view().setAdditionalSafeAreaInsets(screen.safeAreaInsets());
}
// Fullscreen windows can't be resized, minimized, or moved
@@ -1920,14 +1918,12 @@ impl WindowExtMacOS for WindowDelegate {
}
if NSScreen::class().responds_to(sel!(safeAreaInsets)) {
unsafe {
self.view().setAdditionalSafeAreaInsets(NSEdgeInsets {
top: 0.0,
left: 0.0,
bottom: 0.0,
right: 0.0,
});
}
self.view().setAdditionalSafeAreaInsets(NSEdgeInsets {
top: 0.0,
left: 0.0,
bottom: 0.0,
right: 0.0,
});
}
self.window().setFrame_display(frame, true);
@@ -1965,7 +1961,7 @@ impl WindowExtMacOS for WindowDelegate {
#[inline]
fn select_previous_tab(&self) {
unsafe { self.window().selectPreviousTab(None) }
self.window().selectPreviousTab(None)
}
#[inline]
@@ -1975,7 +1971,7 @@ impl WindowExtMacOS for WindowDelegate {
return;
}
if let Some(group) = self.window().tabGroup() {
if let Some(windows) = unsafe { self.window().tabbedWindows() } {
if let Some(windows) = self.window().tabbedWindows() {
if index < windows.len() {
group.setSelectedWindow(Some(&windows.objectAtIndex(index)));
}
@@ -1985,7 +1981,7 @@ impl WindowExtMacOS for WindowDelegate {
#[inline]
fn num_tabs(&self) -> usize {
unsafe { self.window().tabbedWindows() }.map(|windows| windows.len()).unwrap_or(1)
self.window().tabbedWindows().map(|windows| windows.len()).unwrap_or(1)
}
fn is_document_edited(&self) -> bool {
@@ -2018,26 +2014,20 @@ impl WindowExtMacOS for WindowDelegate {
if unified_titlebar {
let mtm = MainThreadMarker::from(self);
unsafe {
// The toolbar style is ignored if there is no toolbar, so it is
// necessary to add one.
window.setToolbar(Some(&NSToolbar::new(mtm)));
window.setToolbarStyle(NSWindowToolbarStyle::Unified);
}
// The toolbar style is ignored if there is no toolbar, so it is
// necessary to add one.
window.setToolbar(Some(&NSToolbar::new(mtm)));
window.setToolbarStyle(NSWindowToolbarStyle::Unified);
} else {
unsafe {
window.setToolbar(None);
window.setToolbarStyle(NSWindowToolbarStyle::Automatic);
}
window.setToolbar(None);
window.setToolbarStyle(NSWindowToolbarStyle::Automatic);
}
}
fn unified_titlebar(&self) -> bool {
let window = self.window();
unsafe {
window.toolbar().is_some() && window.toolbarStyle() == NSWindowToolbarStyle::Unified
}
window.toolbar().is_some() && window.toolbarStyle() == NSWindowToolbarStyle::Unified
}
}
@@ -2055,11 +2045,7 @@ pub fn appearance_to_theme(appearance: &NSAppearance) -> Theme {
dark_appearance_name(),
]));
if let Some(best_match) = best_match {
if *best_match == *dark_appearance_name() {
Theme::Dark
} else {
Theme::Light
}
if *best_match == *dark_appearance_name() { Theme::Dark } else { Theme::Light }
} else {
warn!(?appearance, "failed to determine the theme of the appearance");
// Default to light in this case

View File

@@ -3,7 +3,7 @@ use std::sync::Arc;
use objc2::MainThreadMarker;
use objc2_core_foundation::{
kCFRunLoopCommonModes, CFIndex, CFRetained, CFRunLoop, CFRunLoopSource, CFRunLoopSourceContext,
CFIndex, CFRetained, CFRunLoop, CFRunLoopSource, CFRunLoopSourceContext, kCFRunLoopCommonModes,
};
use winit_core::event_loop::EventLoopProxyProvider;

View File

@@ -114,7 +114,7 @@ impl EventHandler {
pub fn handle(&self, callback: impl FnOnce(&mut (dyn ApplicationHandler + '_))) {
match self.inner.try_borrow_mut().as_deref_mut() {
Ok(Some(ref mut user_app)) => {
Ok(Some(user_app)) => {
// It is important that we keep the reference borrowed here,
// so that `in_use` can properly detect that the handler is
// still in use.

View File

@@ -12,7 +12,7 @@ use xkbcommon_dl::{
xkb_compose_status, xkb_compose_table, xkb_keysym_t,
};
use super::{XkbContext, XKBCH};
use super::{XKBCH, XkbContext};
#[derive(Debug)]
pub struct XkbComposeTable {

View File

@@ -19,7 +19,7 @@ use {memmap2::MmapOptions, std::os::unix::io::OwnedFd};
#[cfg(feature = "x11")]
use super::XKBXH;
use super::{XkbContext, XKBH};
use super::{XKBH, XkbContext};
/// Map the raw X11-style keycode to the `KeyCode` enum.
///
@@ -37,8 +37,9 @@ pub fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
// are defined by the Linux kernel. If Winit programs end up being run on other Unix-likes,
// I can only hope they agree on what the keycodes mean.
//
// The mapping here is heavily influenced by Firefox' source:
// https://searchfox.org/mozilla-central/rev/c597e9c789ad36af84a0370d395be066b7dc94f4/widget/NativeKeyToDOMCodeName.h
// The mapping here is heavily influenced by Firefox' and Chromium's sources:
// - https://searchfox.org/mozilla-central/rev/c597e9c789ad36af84a0370d395be066b7dc94f4/widget/NativeKeyToDOMCodeName.h
// - https://chromium.googlesource.com/chromium/src.git/+/3e1a26c44c024d97dc9a4c09bbc6a2365398ca2c/ui/events/keycodes/dom/dom_code_data.inc
//
// Some of the keycodes are likely superfluous for our purposes, and some are ones which are
// difficult to test the correctness of, or discover the purpose of. Because of this, they've
@@ -159,11 +160,11 @@ pub fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
113 => KeyCode::AudioVolumeMute,
114 => KeyCode::AudioVolumeDown,
115 => KeyCode::AudioVolumeUp,
// 116 => KeyCode::POWER,
116 => KeyCode::Power,
117 => KeyCode::NumpadEqual,
// 118 => KeyCode::KPPLUSMINUS,
119 => KeyCode::Pause,
// 120 => KeyCode::SCALE,
120 => KeyCode::ShowAllWindows,
121 => KeyCode::NumpadComma,
122 => KeyCode::Lang1,
123 => KeyCode::Lang2,
@@ -185,7 +186,7 @@ pub fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
// 139 => KeyCode::MENU,
140 => KeyCode::LaunchApp2, // CALC
// 141 => KeyCode::SETUP,
// 142 => KeyCode::SLEEP,
142 => KeyCode::Sleep,
143 => KeyCode::WakeUp,
144 => KeyCode::LaunchApp1, // FILE
// 145 => KeyCode::SENDFILE,
@@ -210,8 +211,8 @@ pub fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
164 => KeyCode::MediaPlayPause,
165 => KeyCode::MediaTrackPrevious,
166 => KeyCode::MediaStop,
// 167 => KeyCode::RECORD,
// 168 => KeyCode::REWIND,
167 => KeyCode::MediaRecord,
168 => KeyCode::MediaRewind,
// 169 => KeyCode::PHONE,
// 170 => KeyCode::ISO,
171 => KeyCode::MediaSelect, // CONFIG
@@ -222,8 +223,8 @@ pub fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
// 176 => KeyCode::EDIT,
// 177 => KeyCode::SCROLLUP,
// 178 => KeyCode::SCROLLDOWN,
// 179 => KeyCode::KPLEFTPAREN,
// 180 => KeyCode::KPRIGHTPAREN,
179 => KeyCode::NumpadParenLeft,
180 => KeyCode::NumpadParenRight,
// 181 => KeyCode::NEW,
// 182 => KeyCode::REDO,
183 => KeyCode::F13,
@@ -239,14 +240,14 @@ pub fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
193 => KeyCode::F23,
194 => KeyCode::F24,
// 200 => KeyCode::PLAYCD,
// 201 => KeyCode::PAUSECD,
201 => KeyCode::MediaPause,
// 202 => KeyCode::PROG3,
// 203 => KeyCode::PROG4,
// 204 => KeyCode::DASHBOARD,
// 205 => KeyCode::SUSPEND,
// 206 => KeyCode::CLOSE,
// 207 => KeyCode::PLAY,
// 208 => KeyCode::FASTFORWARD,
207 => KeyCode::MediaPlay,
208 => KeyCode::MediaFastForward,
// 209 => KeyCode::BASSBOOST,
// 210 => KeyCode::PRINT,
// 211 => KeyCode::HP,
@@ -262,16 +263,16 @@ pub fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
// 221 => KeyCode::SHOP,
// 222 => KeyCode::ALTERASE,
// 223 => KeyCode::CANCEL,
// 224 => KeyCode::BRIGHTNESSDOW,
// 225 => KeyCode::BRIGHTNESSU,
224 => KeyCode::BrightnessDown,
225 => KeyCode::BrightnessUp,
// 226 => KeyCode::MEDIA,
// 227 => KeyCode::SWITCHVIDEOMODE,
// 228 => KeyCode::KBDILLUMTOGGLE,
227 => KeyCode::DisplayToggleIntExt,
228 => KeyCode::KeyboardBacklightToggle,
// 229 => KeyCode::KBDILLUMDOWN,
// 230 => KeyCode::KBDILLUMUP,
// 231 => KeyCode::SEND,
// 232 => KeyCode::REPLY,
// 233 => KeyCode::FORWARDMAIL,
231 => KeyCode::MailSend,
232 => KeyCode::MailReply,
233 => KeyCode::MailForward,
// 234 => KeyCode::SAVE,
// 235 => KeyCode::DOCUMENTS,
// 236 => KeyCode::BATTERY,
@@ -286,7 +287,14 @@ pub fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
// 245 => KeyCode::DISPLAY_OFF,
// 246 => KeyCode::WWAN,
// 247 => KeyCode::RFKILL,
// 248 => KeyCode::KEY_MICMUTE,
248 => KeyCode::MicrophoneMuteToggle,
372 => KeyCode::ZoomToggle,
579 => KeyCode::LaunchControlPanel,
580 => KeyCode::SelectTask,
581 => KeyCode::LaunchScreenSaver,
583 => KeyCode::LaunchAssistant,
584 => KeyCode::KeyboardLayoutSelect,
633 => KeyCode::PrivacyScreenToggle,
_ => return PhysicalKey::Unidentified(NativeKeyCode::Xkb(scancode)),
})
}
@@ -415,8 +423,10 @@ pub fn physicalkey_to_scancode(key: PhysicalKey) -> Option<u32> {
KeyCode::AudioVolumeMute => Some(113),
KeyCode::AudioVolumeDown => Some(114),
KeyCode::AudioVolumeUp => Some(115),
KeyCode::Power => Some(116),
KeyCode::NumpadEqual => Some(117),
KeyCode::Pause => Some(119),
KeyCode::ShowAllWindows => Some(120),
KeyCode::NumpadComma => Some(121),
KeyCode::Lang1 => Some(122),
KeyCode::Lang2 => Some(123),
@@ -436,6 +446,7 @@ pub fn physicalkey_to_scancode(key: PhysicalKey) -> Option<u32> {
KeyCode::Cut => Some(137),
KeyCode::Help => Some(138),
KeyCode::LaunchApp2 => Some(140),
KeyCode::Sleep => Some(142),
KeyCode::WakeUp => Some(143),
KeyCode::LaunchApp1 => Some(144),
KeyCode::LaunchMail => Some(155),
@@ -447,9 +458,13 @@ pub fn physicalkey_to_scancode(key: PhysicalKey) -> Option<u32> {
KeyCode::MediaPlayPause => Some(164),
KeyCode::MediaTrackPrevious => Some(165),
KeyCode::MediaStop => Some(166),
KeyCode::MediaRecord => Some(167),
KeyCode::MediaRewind => Some(168),
KeyCode::MediaSelect => Some(171),
KeyCode::BrowserHome => Some(172),
KeyCode::BrowserRefresh => Some(173),
KeyCode::NumpadParenLeft => Some(179),
KeyCode::NumpadParenRight => Some(180),
KeyCode::F13 => Some(183),
KeyCode::F14 => Some(184),
KeyCode::F15 => Some(185),
@@ -462,7 +477,26 @@ pub fn physicalkey_to_scancode(key: PhysicalKey) -> Option<u32> {
KeyCode::F22 => Some(192),
KeyCode::F23 => Some(193),
KeyCode::F24 => Some(194),
KeyCode::MediaPause => Some(201),
KeyCode::MediaPlay => Some(207),
KeyCode::MediaFastForward => Some(208),
KeyCode::BrowserSearch => Some(217),
KeyCode::BrightnessDown => Some(224),
KeyCode::BrightnessUp => Some(225),
KeyCode::DisplayToggleIntExt => Some(227),
KeyCode::KeyboardBacklightToggle => Some(228),
KeyCode::MailSend => Some(231),
KeyCode::MailReply => Some(232),
KeyCode::MailForward => Some(233),
// PhysicalKey::Unidentified(NativeKeyCode::Unidentified) => Some(240),
KeyCode::MicrophoneMuteToggle => Some(248),
KeyCode::ZoomToggle => Some(372),
KeyCode::LaunchControlPanel => Some(579),
KeyCode::SelectTask => Some(580),
KeyCode::LaunchScreenSaver => Some(581),
KeyCode::LaunchAssistant => Some(583),
KeyCode::KeyboardLayoutSelect => Some(584),
KeyCode::PrivacyScreenToggle => Some(633),
_ => None,
}
}
@@ -1018,11 +1052,7 @@ impl XkbKeymap {
&mut keysyms,
);
if count == 1 {
*keysyms
} else {
0
}
if count == 1 { *keysyms } else { 0 }
}
}
@@ -1066,10 +1096,6 @@ fn mod_index_for_name(keymap: NonNull<xkb_keymap>, name: &[u8]) -> Option<xkb_mo
unsafe {
let mod_index =
(XKBH.xkb_keymap_mod_get_index)(keymap.as_ptr(), name.as_ptr() as *const c_char);
if mod_index == XKB_MOD_INVALID {
None
} else {
Some(mod_index)
}
if mod_index == XKB_MOD_INVALID { None } else { Some(mod_index) }
}
}

View File

@@ -3,15 +3,15 @@ use std::os::raw::c_char;
#[cfg(feature = "wayland")]
use std::os::unix::io::OwnedFd;
use std::ptr::{self, NonNull};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::LazyLock;
use std::sync::atomic::{AtomicBool, Ordering};
use smol_str::SmolStr;
use winit_core::event::{ElementState, KeyEvent};
use winit_core::keyboard::{Key, KeyLocation};
use xkbcommon_dl::{
self as xkb, xkb_compose_status, xkb_context, xkb_context_flags, xkbcommon_compose_handle,
xkbcommon_handle, XkbCommon, XkbCommonCompose,
self as xkb, XkbCommon, XkbCommonCompose, xkb_compose_status, xkb_context, xkb_context_flags,
xkbcommon_compose_handle, xkbcommon_handle,
};
#[cfg(feature = "x11")]
use {x11_dl::xlib_xcb::xcb_connection_t, xkbcommon_dl::x11::xkbcommon_x11_handle};
@@ -21,9 +21,9 @@ mod keymap;
mod state;
use compose::{ComposeStatus, XkbComposeState, XkbComposeTable};
use keymap::XkbKeymap;
#[cfg(feature = "x11")]
pub use keymap::raw_keycode_to_physicalkey;
use keymap::XkbKeymap;
pub use keymap::{physicalkey_to_scancode, scancode_to_physicalkey};
pub use state::XkbState;
@@ -310,11 +310,7 @@ impl<'a, 'b> KeyEventResults<'a, 'b> {
fn keysym_to_key(&self, keysym: u32) -> Result<(Key, KeyLocation), (Key, KeyLocation)> {
let location = keymap::keysym_location(keysym);
let key = keymap::keysym_to_key(keysym);
if matches!(key, Key::Unidentified(_)) {
Err((key, location))
} else {
Ok((key, location))
}
if matches!(key, Key::Unidentified(_)) { Err((key, location)) } else { Ok((key, location)) }
}
pub fn text(&mut self) -> Option<SmolStr> {

View File

@@ -10,10 +10,10 @@ use xkbcommon_dl::{
self as xkb, xkb_keycode_t, xkb_keysym_t, xkb_layout_index_t, xkb_state, xkb_state_component,
};
use super::keymap::XkbKeymap;
#[cfg(feature = "x11")]
use super::XKBXH;
use super::{make_string_with, XKBH};
use super::keymap::XkbKeymap;
use super::{XKBH, make_string_with};
#[derive(Debug)]
pub struct XkbState {

View File

@@ -8,7 +8,7 @@ use std::time::Duration;
#[doc(inline)]
pub use cursor_icon::CursorIcon;
use crate::as_any::{impl_dyn_casting, AsAny};
use crate::as_any::AsAny;
/// The maximum width and height for a cursor when using [`CustomCursorSource::from_rgba`].
pub const MAX_CURSOR_SIZE: u16 = 2048;

View File

@@ -35,11 +35,7 @@ impl fmt::Display for EventLoopError {
impl Error for EventLoopError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
if let Self::Os(err) = self {
err.source()
} else {
None
}
if let Self::Os(err) = self { err.source() } else { None }
}
}
@@ -78,11 +74,7 @@ impl Display for RequestError {
}
impl Error for RequestError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
if let Self::Os(err) = self {
err.source()
} else {
None
}
if let Self::Os(err) = self { err.source() } else { None }
}
}
@@ -149,7 +141,5 @@ impl Error for OsError {
#[allow(unused_macros)]
macro_rules! os_error {
($error:expr) => {{
crate::error::OsError::new(line!(), file!(), $error)
}};
($error:expr) => {{ crate::error::OsError::new(line!(), file!(), $error) }};
}

View File

@@ -1,4 +1,7 @@
//! The event enums and assorted supporting types.
use std::cell::LazyCell;
use std::cmp::Ordering;
use std::f64;
use std::path::PathBuf;
use std::sync::{Mutex, Weak};
@@ -7,13 +10,13 @@ use dpi::{PhysicalPosition, PhysicalSize};
use serde::{Deserialize, Serialize};
use smol_str::SmolStr;
use crate::Instant;
use crate::error::RequestError;
use crate::event_loop::AsyncRequestSerial;
use crate::keyboard::{self, ModifiersKeyState, ModifiersKeys, ModifiersState};
#[cfg(doc)]
use crate::window::Window;
use crate::window::{ActivationToken, Theme};
use crate::Instant;
/// Describes the reason the event loop is resuming.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
@@ -264,7 +267,7 @@ pub enum WindowEvent {
///
/// ## Platform-specific
///
/// - Only available on **macOS** and **iOS**.
/// - Only available on **macOS**, **iOS**, and **Wayland**.
/// - On iOS, not recognized by default. It must be enabled when needed.
PinchGesture {
device_id: Option<DeviceId>,
@@ -280,7 +283,7 @@ pub enum WindowEvent {
///
/// ## Platform-specific
///
/// - Only available on **iOS**.
/// - Only available on **iOS** and **Wayland**.
/// - On iOS, not recognized by default. It must be enabled when needed.
PanGesture {
device_id: Option<DeviceId>,
@@ -316,7 +319,7 @@ pub enum WindowEvent {
///
/// ## Platform-specific
///
/// - Only available on **macOS** and **iOS**.
/// - Only available on **macOS**, **iOS**, and **Wayland**.
/// - On iOS, not recognized by default. It must be enabled when needed.
RotationGesture {
device_id: Option<DeviceId>,
@@ -435,6 +438,7 @@ pub enum PointerKind {
///
/// **macOS:** Unsupported.
Touch(FingerId),
TabletTool(TabletToolKind),
Unknown,
}
@@ -485,6 +489,13 @@ pub enum PointerSource {
/// force will be 0.5 when a button is pressed or 0.0 otherwise.
force: Option<Force>,
},
TabletTool {
/// Describes as which tool kind the interaction happened.
kind: TabletToolKind,
/// Describes how the tool was held and used.
data: TabletToolData,
},
Unknown,
}
@@ -493,6 +504,7 @@ impl From<PointerSource> for PointerKind {
match source {
PointerSource::Mouse => Self::Mouse,
PointerSource::Touch { finger_id, .. } => Self::Touch(finger_id),
PointerSource::TabletTool { kind, .. } => Self::TabletTool(kind),
PointerSource::Unknown => Self::Unknown,
}
}
@@ -502,7 +514,7 @@ impl From<PointerSource> for PointerKind {
///
/// **Wayland/X11:** [`Unknown`](Self::Unknown) device types are converted to known variants by the
/// system.
#[derive(Clone, Copy, Debug, PartialEq)]
#[derive(Clone, Debug, PartialEq)]
pub enum ButtonSource {
Mouse(MouseButton),
/// See [`PointerSource::Touch`] for more details.
@@ -514,25 +526,27 @@ pub enum ButtonSource {
finger_id: FingerId,
force: Option<Force>,
},
TabletTool {
kind: TabletToolKind,
button: TabletToolButton,
data: TabletToolData,
},
/// A pointer button of unknown source.
///
/// Codes are undefined and may not be reproducible across platforms or winit versions.
Unknown(u16),
}
impl ButtonSource {
/// Convert any [`ButtonSource`] to an equivalent [`MouseButton`]. If a pointer type has no
/// Try to convert a [`ButtonSource`] to an equivalent [`MouseButton`]. If a pointer type has no
/// special handling in an application, this method can be used to handle it like any generic
/// mouse input.
pub fn mouse_button(self) -> MouseButton {
pub fn mouse_button(self) -> Option<MouseButton> {
match self {
ButtonSource::Mouse(mouse) => mouse,
ButtonSource::Touch { .. } => MouseButton::Left,
ButtonSource::Unknown(button) => match button {
0 => MouseButton::Left,
1 => MouseButton::Middle,
2 => MouseButton::Right,
3 => MouseButton::Back,
4 => MouseButton::Forward,
_ => MouseButton::Other(button),
},
ButtonSource::Mouse(mouse) => Some(mouse),
ButtonSource::Touch { .. } => Some(MouseButton::Left),
ButtonSource::TabletTool { button, .. } => button.into(),
ButtonSource::Unknown(_) => None,
}
}
}
@@ -745,7 +759,7 @@ pub struct KeyEvent {
///
/// # Example
///
/// In games, you often want to ignore repated key events - this can be
/// In games, you often want to ignore repeated key events - this can be
/// done by ignoring events where this property is set.
///
/// ```no_run
@@ -770,9 +784,10 @@ pub struct KeyEvent {
/// ```
pub repeat: bool,
/// Similar to [`text`][Self::text], except that this is affected by <kbd>Ctrl</kbd>.
/// Similar to [`text`][Self::text], except that this is affected by <kbd>Ctrl</kbd> and may
/// produce ASCII control characters.
///
/// For example, pressing <kbd>Ctrl</kbd>+<kbd>a</kbd> produces `Some("\x01")`.
/// For example, pressing <kbd>Ctrl</kbd>+<kbd>space</kbd> produces `Some("\x00")`.
///
/// ## Platform-specific
///
@@ -981,6 +996,7 @@ pub enum TouchPhase {
/// Describes the force of a touch event
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[doc(alias = "Pressure")]
pub enum Force {
/// On iOS, the force is calibrated so that the same number corresponds to
/// roughly the same amount of pressure on the screen regardless of the
@@ -991,7 +1007,7 @@ pub enum Force {
///
/// The force reported by Apple Pencil is measured along the axis of the
/// pencil. If you want a force perpendicular to the device, you need to
/// calculate this value using the `altitude_angle` value.
/// calculate this value using the [`TabletToolAngle::altitude`] value.
force: f64,
/// The maximum possible force for a touch.
///
@@ -1012,9 +1028,17 @@ impl Force {
/// Instead of normalizing the force, you should prefer to handle
/// [`Force::Calibrated`] so that the amount of force the user has to apply is
/// consistent across devices.
pub fn normalized(&self) -> f64 {
///
/// Passing in a [`TabletToolAngle`], returns the perpendicular force.
pub fn normalized(&self, angle: Option<TabletToolAngle>) -> f64 {
match self {
Force::Calibrated { force, max_possible_force } => force / max_possible_force,
Force::Calibrated { force, max_possible_force } => {
let force = match angle {
Some(TabletToolAngle { altitude, .. }) => force / altitude.sin(),
None => *force,
};
force / max_possible_force
},
Force::Normalized(force) => *force,
}
}
@@ -1026,6 +1050,260 @@ pub type AxisId = u32;
/// Identifier for a specific button on some device.
pub type ButtonId = u32;
/// Tablet of the tablet tool.
#[derive(Default, Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
#[non_exhaustive]
pub enum TabletToolKind {
#[default]
Pen,
Eraser,
Brush,
Pencil,
Airbrush,
Finger,
Mouse,
Lens,
}
#[derive(Default, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct TabletToolData {
/// The force applied to the tool against the surface.
///
/// When the force information is not available, [`None`] is returned.
///
/// ## Platform-specific
///
/// **Web:** Has no mechanism to detect support, so this will always be [`Some`].
pub force: Option<Force>,
/// Represents normalized tangential pressure, also known as barrel pressure. In the range of
/// -1 to 1. 0 means no tangential pressure is applied. [`None`] means backend or device has no
/// support.
///
/// ## Platform-specific
///
/// **Web:** Has no mechanism to detect support, so this will always be [`Some`] with a value
/// of 0.
pub tangential_force: Option<f32>,
/// The clockwise rotation in degrees of a tool around its own major axis. E.g. twisting a pen
/// around its length. In the range of 0 to 359. [`None`] means backend or device has no
/// support.
///
/// ## Platform-specific
///
/// **Web:** Has no mechanism to detect support, so this will always be [`Some`] with a value
/// of 0.
pub twist: Option<u16>,
/// The plane angle in degrees. [`None`] means backend or device has no support.
///
/// ## Platform-specific
///
/// **Web:** Has no mechanism to detect support, so this will always be [`Some`] with default
/// values.
pub tilt: Option<TabletToolTilt>,
/// The angular position in radians. [`None`] means backend or device has no support.
///
/// ## Platform-specific
///
/// **Web:** Has no mechanism to detect device support, so this will always be [`Some`] with
/// default values unless browser support is lacking.
pub angle: Option<TabletToolAngle>,
}
impl TabletToolData {
/// Returns [`TabletToolTilt`] if present or calculates it from [`TabletToolAngle`].
pub fn tilt(self) -> Option<TabletToolTilt> {
if let Some(tilt) = self.tilt { Some(tilt) } else { self.angle.map(TabletToolAngle::tilt) }
}
/// Returns [`TabletToolAngle`] if present or calculates it from [`TabletToolTilt`].
pub fn angle(self) -> Option<TabletToolAngle> {
if let Some(angle) = self.angle {
Some(angle)
} else {
self.tilt.map(TabletToolTilt::angle)
}
}
}
/// The plane angle in degrees of a tool.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct TabletToolTilt {
/// The plane angle in degrees between the surface Y-Z plane and the plane containing the tool
/// and the surface Y axis. Positive values are to the right. In the range of -90 to 90. 0
/// means the tool is perpendicular to the surface and is the default.
///
/// ![Tilt X](https://raw.githubusercontent.com/rust-windowing/winit/master/winit/docs/res/tool_tilt_x.webp)
///
/// <sub>
/// For image attribution, see the
/// <a href="https://github.com/rust-windowing/winit/blob/master/winit/docs/ATTRIBUTION.md">
/// ATTRIBUTION.md
/// </a>
/// file.
/// </sub>
pub x: i8,
/// The plane angle in degrees between the surface X-Z plane and the plane containing the tool
/// and the surface X axis. Positive values are towards the user. In the range of -90 to
/// 90. 0 means the tool is perpendicular to the surface and is the default.
///
/// ![Tilt Y](https://raw.githubusercontent.com/rust-windowing/winit/master/winit/docs/res/tool_tilt_y.webp)
///
/// <sub>
/// For image attribution, see the
/// <a href="https://github.com/rust-windowing/winit/blob/master/winit/docs/ATTRIBUTION.md">
/// ATTRIBUTION.md
/// </a>
/// file.
/// </sub>
pub y: i8,
}
impl TabletToolTilt {
pub fn angle(self) -> TabletToolAngle {
// See <https://www.w3.org/TR/2024/WD-pointerevents3-20240326/#converting-between-tiltx-tilty-and-altitudeangle-azimuthangle>.
use std::f64::consts::*;
const PI_0_5: f64 = FRAC_PI_2;
const PI_1_5: f64 = 3. * FRAC_PI_2;
const PI_2: f64 = 2. * PI;
let x = LazyCell::new(|| f64::from(self.x).to_radians());
let y = LazyCell::new(|| f64::from(self.y).to_radians());
let mut azimuth = 0.;
if self.x == 0 {
match self.y.cmp(&0) {
Ordering::Greater => azimuth = PI_0_5,
Ordering::Less => azimuth = PI_1_5,
Ordering::Equal => (),
}
} else if self.y == 0 {
if self.x < 0 {
azimuth = PI;
}
} else if self.x.abs() == 90 || self.y.abs() == 90 {
// not enough information to calculate azimuth
azimuth = 0.;
} else {
// Non-boundary case: neither tiltX nor tiltY is equal to 0 or +-90
azimuth = f64::atan2(y.tan(), x.tan());
if azimuth < 0. {
azimuth += PI_2;
}
}
let altitude;
if self.x.abs() == 90 || self.y.abs() == 90 {
altitude = 0.;
} else if self.x == 0 {
altitude = PI_0_5 - y.abs();
} else if self.y == 0 {
altitude = PI_0_5 - x.abs();
} else {
// Non-boundary case: neither tiltX nor tiltY is equal to 0 or +-90
altitude = f64::atan(1. / f64::sqrt(x.tan().powi(2) + y.tan().powi(2)));
}
TabletToolAngle { altitude, azimuth }
}
}
/// The angular position in radians of a tool.
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct TabletToolAngle {
/// The altitude angle in radians between the tools perpendicular position to the surface and
/// the surface X-Y plane. In the range of 0, parallel to the surface, to π/2, perpendicular to
/// the surface. π/2 means the tool is perpendicular to the surface and is the default.
///
/// ![Altitude angle](https://raw.githubusercontent.com/rust-windowing/winit/master/docs/res/tool_altitude.webp)
///
/// <sub>
/// For image attribution, see the
/// <a href="https://github.com/rust-windowing/winit/blob/master/docs/res/ATTRIBUTION.md">
/// ATTRIBUTION.md
/// </a>
/// file.
/// </sub>
pub altitude: f64,
/// The azimuth angle in radiants representing the rotation between the major axis of the tool
/// and the surface X-Y plane. In the range of 0, 3 o'clock, progressively increasing clockwise
/// to 2π. 0 means the tool is at 3 o'clock or is perpendicular to the surface (`altitude` of
/// π/2) and is the default.
///
/// ![Azimuth angle](https://raw.githubusercontent.com/rust-windowing/winit/master/docs/res/tool_azimuth.webp)
///
/// <sub>
/// For image attribution, see the
/// <a href="https://github.com/rust-windowing/winit/blob/master/docs/res/ATTRIBUTION.md">
/// ATTRIBUTION.md
/// </a>
/// file.
/// </sub>
pub azimuth: f64,
}
impl Default for TabletToolAngle {
fn default() -> Self {
Self { altitude: f64::consts::FRAC_2_PI, azimuth: 0. }
}
}
impl TabletToolAngle {
pub fn tilt(self) -> TabletToolTilt {
// See <https://www.w3.org/TR/2024/WD-pointerevents3-20240326/#converting-between-tiltx-tilty-and-altitudeangle-azimuthangle>.
use std::f64::consts::*;
const PI_0_5: f64 = FRAC_PI_2;
const PI_1_5: f64 = 3. * FRAC_PI_2;
const PI_2: f64 = 2. * PI;
let mut x = 0.;
let mut y = 0.;
if self.altitude == 0. {
if self.azimuth == 0. || self.azimuth == PI_2 {
x = FRAC_PI_2;
} else if self.azimuth == PI_0_5 {
y = FRAC_PI_2;
} else if self.azimuth == PI {
x = -FRAC_PI_2;
} else if self.azimuth == PI_1_5 {
y = -FRAC_PI_2;
} else if self.azimuth > 0. && self.azimuth < PI_0_5 {
x = FRAC_PI_2;
y = FRAC_PI_2;
} else if self.azimuth > PI_0_5 && self.azimuth < PI {
x = -FRAC_PI_2;
y = FRAC_PI_2;
} else if self.azimuth > PI && self.azimuth < PI_1_5 {
x = -FRAC_PI_2;
y = -FRAC_PI_2;
} else if self.azimuth > PI_1_5 && self.azimuth < PI_2 {
x = FRAC_PI_2;
y = -FRAC_PI_2;
}
}
if self.altitude != 0. {
let altitude = self.altitude.tan();
x = f64::atan(f64::cos(self.azimuth) / altitude);
y = f64::atan(f64::sin(self.azimuth) / altitude);
}
TabletToolTilt { x: x.to_degrees().round() as i8, y: y.to_degrees().round() as i8 }
}
}
/// Describes the input state of a key.
#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
@@ -1041,23 +1319,138 @@ impl ElementState {
}
}
/// Describes a button of a mouse controller.
/// Identifies a button of a mouse controller.
///
/// ## Platform-specific
///
/// **macOS:** `Back` and `Forward` might not work with all hardware.
/// **Orbital:** `Back` and `Forward` are unsupported due to orbital not supporting them.
/// The first three buttons should be supported on all platforms.
/// [`Self::Back`] and [`Self::Forward`] are supported on most platforms
/// (when using a compatible mouse).
///
/// - **Android, iOS:** Currently not supported.
/// - **Orbital:** Only left/right/middle buttons are supported at this time.
/// - **Web, Windows:** Supports left/right/middle/back/forward buttons.
/// - **Wayland:** Supports buttons 0..=15.
/// - **macOS:** Supports all button variants.
/// - **X11:** Technically supports further buttons than this (0..=250), these are emitted in
/// `ButtonSource::Unknown`.
#[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[repr(u8)]
pub enum MouseButton {
Left,
Right,
Middle,
Back,
Forward,
/// The primary (usually left) button
Left = 0,
/// The secondary (usually right) button
Right = 1,
/// The tertiary (usually middle) button
Middle = 2,
/// The first side button, frequently assigned a back function
Back = 3,
/// The second side button, frequently assigned a forward function
Forward = 4,
/// The sixth button
Button6 = 5,
/// The seventh button
Button7 = 6,
/// The eighth button
Button8 = 7,
/// The ninth button
Button9 = 8,
/// The tenth button
Button10 = 9,
/// The eleventh button
Button11 = 10,
/// The twelfth button
Button12 = 11,
/// The thirteenth button
Button13 = 12,
/// The fourteenth button
Button14 = 13,
/// The fifteenth button
Button15 = 14,
/// The sixteenth button
Button16 = 15,
Button17 = 16,
Button18 = 17,
Button19 = 18,
Button20 = 19,
Button21 = 20,
Button22 = 21,
Button23 = 22,
Button24 = 23,
Button25 = 24,
Button26 = 25,
Button27 = 26,
Button28 = 27,
Button29 = 28,
Button30 = 29,
Button31 = 30,
Button32 = 31,
}
impl MouseButton {
/// Construct from a `u8` if within the range `0..=31`
pub fn try_from_u8(b: u8) -> Option<MouseButton> {
Some(match b {
0 => MouseButton::Left,
1 => MouseButton::Right,
2 => MouseButton::Middle,
3 => MouseButton::Back,
4 => MouseButton::Forward,
5 => MouseButton::Button6,
6 => MouseButton::Button7,
7 => MouseButton::Button8,
8 => MouseButton::Button9,
9 => MouseButton::Button10,
10 => MouseButton::Button11,
11 => MouseButton::Button12,
12 => MouseButton::Button13,
13 => MouseButton::Button14,
14 => MouseButton::Button15,
15 => MouseButton::Button16,
16 => MouseButton::Button17,
17 => MouseButton::Button18,
18 => MouseButton::Button19,
19 => MouseButton::Button20,
20 => MouseButton::Button21,
21 => MouseButton::Button22,
22 => MouseButton::Button23,
23 => MouseButton::Button24,
24 => MouseButton::Button25,
25 => MouseButton::Button26,
26 => MouseButton::Button27,
27 => MouseButton::Button28,
28 => MouseButton::Button29,
29 => MouseButton::Button30,
30 => MouseButton::Button31,
31 => MouseButton::Button32,
_ => return None,
})
}
}
/// Describes a button of a tool, e.g. a pen.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub enum TabletToolButton {
Contact,
Barrel,
Other(u16),
}
impl From<TabletToolButton> for Option<MouseButton> {
fn from(tool: TabletToolButton) -> Self {
Some(match tool {
TabletToolButton::Contact => MouseButton::Left,
TabletToolButton::Barrel => MouseButton::Right,
TabletToolButton::Other(1) => MouseButton::Middle,
TabletToolButton::Other(3) => MouseButton::Back,
TabletToolButton::Other(4) => MouseButton::Forward,
TabletToolButton::Other(_) => return None,
})
}
}
/// Describes a difference in the mouse scroll wheel state.
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
@@ -1188,7 +1581,7 @@ mod tests {
primary: true,
state: event::ElementState::Pressed,
position: (0, 0).into(),
button: event::MouseButton::Other(0).into(),
button: event::ButtonSource::Unknown(0),
});
with_window_event(PointerButton {
device_id: None,
@@ -1241,16 +1634,85 @@ mod tests {
});
}
#[test]
fn test_tilt_angle_conversions() {
use std::f64::consts::*;
use event::{TabletToolAngle, TabletToolTilt};
// See <https://github.com/web-platform-tests/wpt/blob/5af3e9c2a2aba76ade00f0dbc3486e50a74a4506/pointerevents/pointerevent_tiltX_tiltY_to_azimuth_altitude.html#L11-L23>.
const TILT_TO_ANGLE: &[(TabletToolTilt, TabletToolAngle)] = &[
(TabletToolTilt { x: 0, y: 0 }, TabletToolAngle { altitude: FRAC_PI_2, azimuth: 0. }),
(TabletToolTilt { x: 0, y: 90 }, TabletToolAngle { altitude: 0., azimuth: FRAC_PI_2 }),
(TabletToolTilt { x: 0, y: -90 }, TabletToolAngle {
altitude: 0.,
azimuth: 3. * FRAC_PI_2,
}),
(TabletToolTilt { x: 90, y: 0 }, TabletToolAngle { altitude: 0., azimuth: 0. }),
(TabletToolTilt { x: 90, y: 90 }, TabletToolAngle { altitude: 0., azimuth: 0. }),
(TabletToolTilt { x: 90, y: -90 }, TabletToolAngle { altitude: 0., azimuth: 0. }),
(TabletToolTilt { x: -90, y: 0 }, TabletToolAngle { altitude: 0., azimuth: PI }),
(TabletToolTilt { x: -90, y: 90 }, TabletToolAngle { altitude: 0., azimuth: 0. }),
(TabletToolTilt { x: -90, y: -90 }, TabletToolAngle { altitude: 0., azimuth: 0. }),
(TabletToolTilt { x: 0, y: 45 }, TabletToolAngle {
altitude: FRAC_PI_4,
azimuth: FRAC_PI_2,
}),
(TabletToolTilt { x: 0, y: -45 }, TabletToolAngle {
altitude: FRAC_PI_4,
azimuth: 3. * FRAC_PI_2,
}),
(TabletToolTilt { x: 45, y: 0 }, TabletToolAngle { altitude: FRAC_PI_4, azimuth: 0. }),
(TabletToolTilt { x: -45, y: 0 }, TabletToolAngle { altitude: FRAC_PI_4, azimuth: PI }),
];
for (tilt, angle) in TILT_TO_ANGLE {
assert_eq!(tilt.angle(), *angle, "{tilt:?}");
}
// See <https://github.com/web-platform-tests/wpt/blob/5af3e9c2a2aba76ade00f0dbc3486e50a74a4506/pointerevents/pointerevent_tiltX_tiltY_to_azimuth_altitude.html#L38-L46>.
const ANGLE_TO_TILT: &[(TabletToolAngle, TabletToolTilt)] = &[
(TabletToolAngle { altitude: 0., azimuth: 0. }, TabletToolTilt { x: 90, y: 0 }),
(TabletToolAngle { altitude: FRAC_PI_4, azimuth: 0. }, TabletToolTilt { x: 45, y: 0 }),
(TabletToolAngle { altitude: FRAC_PI_2, azimuth: 0. }, TabletToolTilt { x: 0, y: 0 }),
(TabletToolAngle { altitude: 0., azimuth: FRAC_PI_2 }, TabletToolTilt { x: 0, y: 90 }),
(TabletToolAngle { altitude: FRAC_PI_4, azimuth: FRAC_PI_2 }, TabletToolTilt {
x: 0,
y: 45,
}),
(TabletToolAngle { altitude: 0., azimuth: PI }, TabletToolTilt { x: -90, y: 0 }),
(TabletToolAngle { altitude: FRAC_PI_4, azimuth: PI }, TabletToolTilt { x: -45, y: 0 }),
(TabletToolAngle { altitude: 0., azimuth: 3. * FRAC_PI_2 }, TabletToolTilt {
x: 0,
y: -90,
}),
(TabletToolAngle { altitude: FRAC_PI_4, azimuth: 3. * FRAC_PI_2 }, TabletToolTilt {
x: 0,
y: -45,
}),
];
for (angle, tilt) in ANGLE_TO_TILT {
assert_eq!(angle.tilt(), *tilt, "{angle:?}");
}
}
#[test]
fn test_force_normalize() {
let force = event::Force::Normalized(0.0);
assert_eq!(force.normalized(), 0.0);
assert_eq!(force.normalized(None), 0.0);
let force2 = event::Force::Calibrated { force: 5.0, max_possible_force: 2.5 };
assert_eq!(force2.normalized(), 2.0);
assert_eq!(force2.normalized(None), 2.0);
let force3 = event::Force::Calibrated { force: 5.0, max_possible_force: 2.5 };
assert_eq!(force3.normalized(), 2.0);
assert_eq!(
force3.normalized(Some(event::TabletToolAngle {
altitude: std::f64::consts::PI / 2.0,
azimuth: 0.
})),
2.0
);
}
#[allow(clippy::clone_on_copy)]

View File

@@ -2,18 +2,18 @@ pub mod pump_events;
pub mod run_on_demand;
use std::fmt::{self, Debug};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use rwh_06::{DisplayHandle, HandleError, HasDisplayHandle};
use crate::Instant;
use crate::as_any::AsAny;
use crate::cursor::{CustomCursor, CustomCursorSource};
use crate::error::RequestError;
use crate::monitor::MonitorHandle;
use crate::window::{Theme, Window, WindowAttributes};
use crate::Instant;
pub trait ActiveEventLoop: AsAny + fmt::Debug {
/// Creates an [`EventLoopProxy`] that can be used to dispatch user events

View File

@@ -2,7 +2,7 @@ use crate::application::ApplicationHandler;
use crate::error::EventLoopError;
#[cfg(doc)]
use crate::{
event_loop::{pump_events::EventLoopExtPumpEvents, ActiveEventLoop},
event_loop::{ActiveEventLoop, pump_events::EventLoopExtPumpEvents},
window::Window,
};

View File

@@ -3,7 +3,7 @@ use std::ops::Deref;
use std::sync::Arc;
use std::{fmt, io, mem};
use crate::as_any::{impl_dyn_casting, AsAny};
use crate::as_any::AsAny;
pub(crate) const PIXEL_SIZE: usize = mem::size_of::<u32>();

View File

@@ -193,7 +193,7 @@ impl PartialEq<KeyCode> for PhysicalKey {
#[inline]
fn eq(&self, rhs: &KeyCode) -> bool {
match self {
PhysicalKey::Code(ref code) => code == rhs,
PhysicalKey::Code(code) => code == rhs,
_ => false,
}
}
@@ -210,7 +210,7 @@ impl PartialEq<NativeKeyCode> for PhysicalKey {
#[inline]
fn eq(&self, rhs: &NativeKeyCode) -> bool {
match self {
PhysicalKey::Unidentified(ref code) => code == rhs,
PhysicalKey::Unidentified(code) => code == rhs,
_ => false,
}
}
@@ -275,7 +275,7 @@ impl<Str> PartialEq<NamedKey> for Key<Str> {
#[inline]
fn eq(&self, rhs: &NamedKey) -> bool {
match self {
Key::Named(ref a) => a == rhs,
Key::Named(a) => a == rhs,
_ => false,
}
}
@@ -285,7 +285,7 @@ impl<Str: PartialEq<str>> PartialEq<str> for Key<Str> {
#[inline]
fn eq(&self, rhs: &str) -> bool {
match self {
Key::Character(ref s) => s == rhs,
Key::Character(s) => s == rhs,
_ => false,
}
}
@@ -302,7 +302,7 @@ impl<Str> PartialEq<NativeKey> for Key<Str> {
#[inline]
fn eq(&self, rhs: &NativeKey) -> bool {
match self {
Key::Unidentified(ref code) => code == rhs,
Key::Unidentified(code) => code == rhs,
_ => false,
}
}

View File

@@ -13,7 +13,7 @@ use std::sync::Arc;
use dpi::{PhysicalPosition, PhysicalSize};
use crate::as_any::{impl_dyn_casting, AsAny};
use crate::as_any::AsAny;
/// Handle to a monitor.
///

View File

@@ -328,7 +328,7 @@ impl WindowAttributes {
///
/// **Android / iOS / X11 / Wayland / Orbital:** Unsupported.
///
/// [`WindowEvent::Focused`]: crate::event::WindowEvent::Focused.
/// [`WindowEvent::Focused`]: crate::event::WindowEvent::Focused
#[inline]
pub fn with_active(mut self, active: bool) -> Self {
self.active = active;
@@ -996,7 +996,8 @@ pub trait Window: AsAny + Send + Sync + fmt::Debug {
/// separate spaces are not preferred.
///
/// The dock and the menu bar are disabled in exclusive fullscreen mode.
/// - **Wayland:** Does not support exclusive fullscreen mode and will no-op a request.
/// - **Orbital / Wayland:** Does not support exclusive fullscreen mode and will no-op a
/// request.
/// - **Windows:** Screen saver is disabled in fullscreen mode.
/// - **Web:** Passing a [`MonitorHandle`] or [`VideoMode`] that was not created with detailed
/// monitor permissions or calling without a [transient activation] does nothing.
@@ -1009,9 +1010,9 @@ pub trait Window: AsAny + Send + Sync + fmt::Debug {
///
/// ## Platform-specific
///
/// - **Android / Orbital:** Will always return `None`.
/// - **Android:** Will always return `None`.
/// - **Orbital / Web:** Can only return `None` or `Borderless(None)`.
/// - **Wayland:** Can return `Borderless(None)` when there are no monitors.
/// - **Web:** Can only return `None` or `Borderless(None)`.
fn fullscreen(&self) -> Option<Fullscreen>;
/// Turn window decorations on or off.
@@ -1135,9 +1136,9 @@ pub trait Window: AsAny + Send + Sync + fmt::Debug {
let action = if allowed {
let position = LogicalPosition::new(0, 0);
let size = LogicalSize::new(0, 0);
let ime_caps = ImeCapabilities::new().with_purpose().with_cursor_area();
let ime_caps = ImeCapabilities::new().without_hint_and_purpose().with_cursor_area();
let request_data = ImeRequestData {
purpose: Some(ImePurpose::Normal),
hint_and_purpose: Some((ImeHint::NONE, ImePurpose::Normal)),
// WARNING: there's nothing sensible to use here by default.
cursor_area: Some((position.into(), size.into())),
..ImeRequestData::default()
@@ -1159,9 +1160,9 @@ pub trait Window: AsAny + Send + Sync + fmt::Debug {
/// - **iOS / Android / Web / Windows / X11 / macOS / Orbital:** Unsupported.
#[deprecated = "use Window::request_ime_update instead"]
fn set_ime_purpose(&self, purpose: ImePurpose) {
if self.ime_capabilities().map(|caps| caps.purpose()).unwrap_or(false) {
if self.ime_capabilities().map(|caps| caps.hint_and_purpose()).unwrap_or(false) {
let _ = self.request_ime_update(ImeRequest::Update(ImeRequestData {
purpose: Some(purpose),
hint_and_purpose: Some((ImeHint::NONE, purpose)),
..ImeRequestData::default()
}));
}
@@ -1185,14 +1186,14 @@ pub trait Window: AsAny + Send + Sync + fmt::Debug {
///
/// ```no_run
/// # use dpi::{Position, Size};
/// # use winit_core::window::{Window, ImePurpose, ImeRequest, ImeCapabilities, ImeRequestData, ImeEnableRequest};
/// # use winit_core::window::{Window, ImeHint, ImePurpose, ImeRequest, ImeCapabilities, ImeRequestData, ImeEnableRequest};
/// # fn scope(window: &dyn Window, cursor_pos: Position, cursor_size: Size) {
/// // Clear previous state by switching off IME
/// window.request_ime_update(ImeRequest::Disable).expect("Disable cannot fail");
///
/// let ime_caps = ImeCapabilities::new().with_cursor_area().with_purpose();
/// let ime_caps = ImeCapabilities::new().with_cursor_area().with_hint_and_purpose();
/// let request_data = ImeRequestData::default()
/// .with_purpose(ImePurpose::Normal)
/// .with_hint_and_purpose(ImeHint::NONE, ImePurpose::Normal)
/// .with_cursor_area(cursor_pos, cursor_size);
/// let enable_ime = ImeEnableRequest::new(ime_caps, request_data.clone()).unwrap();
/// window.request_ime_update(ImeRequest::Enable(enable_ime)).expect("Enabling may fail if IME is not supported");
@@ -1597,29 +1598,86 @@ pub enum WindowLevel {
/// Generic IME purposes for use in [`Window::set_ime_purpose`].
///
/// The purpose should reflect the kind of data to be entered.
/// The purpose may improve UX by optimizing the IME for the specific use case,
/// for example showing relevant characters and hiding unneeded ones,
/// or changing the icon of the confirmation button,
/// if winit can express the purpose to the platform and the platform reacts accordingly.
///
/// ## Platform-specific
///
/// - **iOS / Android / Web / Windows / X11 / macOS / Orbital:** Unsupported.
#[non_exhaustive]
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum ImePurpose {
/// No special hints for the IME (default).
/// No special purpose for the IME (default).
#[default]
Normal,
/// The IME is used for password input.
/// The IME will treat the contents as sensitive.
Password,
/// The IME is used to input into a terminal.
///
/// For example, that could alter OSK on Wayland to show extra buttons.
Terminal,
/// Number (including decimal separator and sign)
Number,
/// Phone number
Phone,
/// URL
Url,
/// Email address
Email,
/// Password composed only of digits (treated as sensitive data)
Pin,
/// Date
Date,
/// Time
Time,
/// Date and time
DateTime,
}
impl Default for ImePurpose {
fn default() -> Self {
Self::Normal
bitflags! {
/// IME hints
///
/// The hint should reflect the desired behaviour of the IME
/// while entering text.
/// The purpose may improve UX by optimizing the IME for the specific use case,
/// beyond just the general data type specified in `ImePurpose`.
///
/// ## Platform-specific
///
/// - **iOS / Android / Web / Windows / X11 / macOS / Orbital:** Unsupported.
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct ImeHint: u32 {
/// No special behaviour.
const NONE = 0;
/// Suggest word completions.
const COMPLETION = 0x1;
/// Suggest word corrections.
const SPELLCHECK = 0x2;
/// Switch to uppercase letters at the start of a sentence.
const AUTO_CAPITALIZATION = 0x4;
/// Prefer lowercase letters.
const LOWERCASE = 0x8;
/// Prefer uppercase letters.
const UPPERCASE = 0x10;
/// Prefer casing for titles and headings (can be language dependent).
const TITLECASE = 0x20;
/// Characters should be hidden.
///
/// This may prevent e.g. layout switching with some IMEs, unless hint is disabled.
const HIDDEN_TEXT = 0x40;
/// Typed text should not be stored.
const SENSITIVE_DATA = 0x80;
/// Just Latin characters should be entered.
const LATIN = 0x100;
/// The text input is multiline.
const MULTILINE = 0x200;
}
}
@@ -1727,7 +1785,7 @@ pub enum ImeRequest {
///
/// **Requesting to update data matching not enabled capabilities will result in update
/// being ignored.** The winit backend in such cases is recommended to log a warning. This
/// appiles to both [`ImeRequest::Enable`] and [`ImeRequest::Update`]. For details on
/// applies to both [`ImeRequest::Enable`] and [`ImeRequest::Update`]. For details on
/// capabilities refer to [`ImeCapabilities`].
///
/// To update the [`ImeCapabilities`], the IME must be disabled and then re-enabled.
@@ -1758,7 +1816,7 @@ impl ImeEnableRequest {
return None;
}
if capabilities.purpose() ^ request_data.purpose.is_some() {
if capabilities.hint_and_purpose() ^ request_data.hint_and_purpose.is_some() {
return None;
}
@@ -1803,23 +1861,23 @@ impl ImeCapabilities {
Self::default()
}
/// Marks `purpose` as supported.
/// Marks `hint and purpose` as supported.
///
/// For more details see [`ImeRequestData::with_purpose`].
pub const fn with_purpose(self) -> Self {
Self(self.0.union(ImeCapabilitiesFlags::PURPOSE))
/// For more details see [`ImeRequestData::with_hint_and_purpose`].
pub const fn with_hint_and_purpose(self) -> Self {
Self(self.0.union(ImeCapabilitiesFlags::HINT_AND_PURPOSE))
}
/// Marks `purpose` as unsupported.
/// Marks `hint and purpose` as unsupported.
///
/// For more details see [`ImeRequestData::with_purpose`].
pub const fn without_purpose(self) -> Self {
Self(self.0.difference(ImeCapabilitiesFlags::PURPOSE))
/// For more details see [`ImeRequestData::with_hint_and_purpose`].
pub const fn without_hint_and_purpose(self) -> Self {
Self(self.0.difference(ImeCapabilitiesFlags::HINT_AND_PURPOSE))
}
/// Returns `true` if `purpose` is supported.
pub const fn purpose(&self) -> bool {
self.0.contains(ImeCapabilitiesFlags::PURPOSE)
/// Returns `true` if `hint and purpose` is supported.
pub const fn hint_and_purpose(&self) -> bool {
self.0.contains(ImeCapabilitiesFlags::HINT_AND_PURPOSE)
}
/// Marks `cursor_area` as supported.
@@ -1864,8 +1922,8 @@ impl ImeCapabilities {
bitflags! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub(crate) struct ImeCapabilitiesFlags : u8 {
/// Client supports setting IME purpose.
const PURPOSE = 1 << 0;
/// Client supports setting IME hint and purpose.
const HINT_AND_PURPOSE = 1 << 0;
/// Client supports reporting cursor area for IME popup to
/// appear.
const CURSOR_AREA = 1 << 1;
@@ -1883,24 +1941,24 @@ bitflags! {
#[derive(Debug, PartialEq, Clone, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ImeRequestData {
/// Text input purpose.
/// Text input hint and purpose.
///
/// To support updating it, enable [`ImeCapabilities::PURPOSE`].
pub purpose: Option<ImePurpose>,
/// To support updating it, enable [`ImeCapabilities::hint_and_purpose()`].
pub hint_and_purpose: Option<(ImeHint, ImePurpose)>,
/// The IME cursor area which should not be covered by the input method popup.
///
/// To support updating it, enable [`ImeCapabilities::CURSOR_AREA`].
/// To support updating it, enable [`ImeCapabilities::cursor_area()`].
pub cursor_area: Option<(Position, Size)>,
/// The text surrounding the caret
///
/// To support updating it, enable [`ImeCapabilities::SURROUNDING_TEXT`].
/// To support updating it, enable [`ImeCapabilities::surrounding_text()`].
pub surrounding_text: Option<ImeSurroundingText>,
}
impl ImeRequestData {
/// Sets the purpose hint of the current text input.
pub fn with_purpose(self, purpose: ImePurpose) -> Self {
Self { purpose: Some(purpose), ..self }
/// Sets the hint and purpose of the current text input content.
pub fn with_hint_and_purpose(self, hint: ImeHint, purpose: ImePurpose) -> Self {
Self { hint_and_purpose: Some((hint, purpose)), ..self }
}
/// Sets the IME cursor editing area.
@@ -2026,59 +2084,73 @@ mod tests {
ImeCapabilities, ImeEnableRequest, ImeRequestData, ImeSurroundingText,
ImeSurroundingTextError,
};
use crate::window::ImePurpose;
use crate::window::{ImeHint, ImePurpose};
#[test]
fn ime_initial_request_caps_match() {
let position: Position = LogicalPosition::new(0, 0).into();
let size: Size = LogicalSize::new(0, 0).into();
assert!(ImeEnableRequest::new(
ImeCapabilities::new().with_cursor_area(),
ImeRequestData::default()
)
.is_none());
assert!(ImeEnableRequest::new(
ImeCapabilities::new().with_purpose(),
ImeRequestData::default()
)
.is_none());
assert!(
ImeEnableRequest::new(
ImeCapabilities::new().with_cursor_area(),
ImeRequestData::default()
)
.is_none()
);
assert!(
ImeEnableRequest::new(
ImeCapabilities::new().with_hint_and_purpose(),
ImeRequestData::default()
)
.is_none()
);
assert!(ImeEnableRequest::new(
ImeCapabilities::new().with_cursor_area(),
ImeRequestData::default().with_purpose(ImePurpose::Normal)
)
.is_none());
assert!(
ImeEnableRequest::new(
ImeCapabilities::new().with_cursor_area(),
ImeRequestData::default().with_hint_and_purpose(ImeHint::NONE, ImePurpose::Normal)
)
.is_none()
);
assert!(ImeEnableRequest::new(
ImeCapabilities::new(),
ImeRequestData::default()
.with_purpose(ImePurpose::Normal)
.with_cursor_area(position, size)
)
.is_none());
assert!(
ImeEnableRequest::new(
ImeCapabilities::new(),
ImeRequestData::default()
.with_hint_and_purpose(ImeHint::NONE, ImePurpose::Normal)
.with_cursor_area(position, size)
)
.is_none()
);
assert!(ImeEnableRequest::new(
ImeCapabilities::new().with_cursor_area(),
ImeRequestData::default()
.with_purpose(ImePurpose::Normal)
.with_cursor_area(position, size)
)
.is_none());
assert!(
ImeEnableRequest::new(
ImeCapabilities::new().with_cursor_area(),
ImeRequestData::default()
.with_hint_and_purpose(ImeHint::NONE, ImePurpose::Normal)
.with_cursor_area(position, size)
)
.is_none()
);
assert!(ImeEnableRequest::new(
ImeCapabilities::new().with_cursor_area(),
ImeRequestData::default().with_cursor_area(position, size)
)
.is_some());
assert!(
ImeEnableRequest::new(
ImeCapabilities::new().with_cursor_area(),
ImeRequestData::default().with_cursor_area(position, size)
)
.is_some()
);
assert!(ImeEnableRequest::new(
ImeCapabilities::new().with_purpose().with_cursor_area(),
ImeRequestData::default()
.with_purpose(ImePurpose::Normal)
.with_cursor_area(position, size)
)
.is_some());
assert!(
ImeEnableRequest::new(
ImeCapabilities::new().with_hint_and_purpose().with_cursor_area(),
ImeRequestData::default()
.with_hint_and_purpose(ImeHint::NONE, ImePurpose::Normal)
.with_cursor_area(position, size)
)
.is_some()
);
let text: &[u8] = ['a' as u8; 8000].as_slice();
let text = std::str::from_utf8(text).unwrap();

View File

@@ -1,7 +1,7 @@
use std::cell::Cell;
use std::collections::VecDeque;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{mpsc, Arc, Mutex};
use std::sync::{Arc, Mutex, mpsc};
use std::time::Instant;
use std::{iter, mem, slice};
@@ -133,11 +133,7 @@ fn convert_scancode(scancode: u8) -> (PhysicalKey, Option<NamedKey>) {
}
fn element_state(pressed: bool) -> event::ElementState {
if pressed {
event::ElementState::Pressed
} else {
event::ElementState::Released
}
if pressed { event::ElementState::Pressed } else { event::ElementState::Released }
}
bitflags! {

View File

@@ -8,9 +8,7 @@ use std::{fmt, str};
pub use self::event_loop::{EventLoop, PlatformSpecificEventLoopAttributes};
macro_rules! os_error {
($error:expr) => {{
winit_core::error::OsError::new(line!(), file!(), $error)
}};
($error:expr) => {{ winit_core::error::OsError::new(line!(), file!(), $error) }};
}
pub mod event_loop;
@@ -41,20 +39,12 @@ impl RedoxSocket {
fn read(&self, buf: &mut [u8]) -> syscall::Result<()> {
let count = syscall::read(self.fd, buf)?;
if count == buf.len() {
Ok(())
} else {
Err(syscall::Error::new(syscall::EINVAL))
}
if count == buf.len() { Ok(()) } else { Err(syscall::Error::new(syscall::EINVAL)) }
}
fn write(&self, buf: &[u8]) -> syscall::Result<()> {
let count = syscall::write(self.fd, buf)?;
if count == buf.len() {
Ok(())
} else {
Err(syscall::Error::new(syscall::EINVAL))
}
if count == buf.len() { Ok(()) } else { Err(syscall::Error::new(syscall::EINVAL)) }
}
fn fpath<'a>(&self, buf: &'a mut [u8]) -> syscall::Result<&'a str> {

View File

@@ -19,6 +19,7 @@ const ORBITAL_FLAG_FRONT: char = 'f';
const ORBITAL_FLAG_HIDDEN: char = 'h';
const ORBITAL_FLAG_BORDERLESS: char = 'l';
const ORBITAL_FLAG_MAXIMIZED: char = 'm';
const ORBITAL_FLAG_FULLSCREEN: char = 'M';
const ORBITAL_FLAG_RESIZABLE: char = 'r';
const ORBITAL_FLAG_TRANSPARENT: char = 't';
@@ -55,7 +56,10 @@ impl Window {
// Async by default.
let mut flag_str = ORBITAL_FLAG_ASYNC.to_string();
if attrs.maximized {
// Fullscreen takes precedence over maximize
if let Some(Fullscreen::Borderless(_)) = attrs.fullscreen {
flag_str.push(ORBITAL_FLAG_FULLSCREEN);
} else if attrs.maximized {
flag_str.push(ORBITAL_FLAG_MAXIMIZED);
}
@@ -63,8 +67,6 @@ impl Window {
flag_str.push(ORBITAL_FLAG_RESIZABLE);
}
// TODO: fullscreen
if attrs.transparent {
flag_str.push(ORBITAL_FLAG_TRANSPARENT);
}
@@ -323,10 +325,28 @@ impl CoreWindow for Window {
self.get_flag(ORBITAL_FLAG_MAXIMIZED).unwrap_or(false)
}
fn set_fullscreen(&self, _monitor: Option<Fullscreen>) {}
fn set_fullscreen(&self, fullscreen: Option<Fullscreen>) {
match fullscreen {
Some(Fullscreen::Exclusive(..)) => {
// TODO: exclusive fullscreen not supported on orbital
},
Some(Fullscreen::Borderless(_monitor)) => {
// TODO: monitor selection not supported on orbital
let _ = self.set_flag(ORBITAL_FLAG_FULLSCREEN, true);
},
None => {
let _ = self.set_flag(ORBITAL_FLAG_FULLSCREEN, false);
},
}
}
fn fullscreen(&self) -> Option<Fullscreen> {
None
if self.get_flag(ORBITAL_FLAG_FULLSCREEN).unwrap_or(false) {
// TODO: monitor selection not supported on orbital
Some(Fullscreen::Borderless(None))
} else {
None
}
}
#[inline]

View File

@@ -18,7 +18,6 @@ rwh_06.workspace = true
serde = { workspace = true, optional = true }
smol_str.workspace = true
tracing.workspace = true
winit-common = { workspace = true, features = ["core-foundation", "event-handler"] }
winit-core.workspace = true
# Platform-specific
@@ -70,6 +69,7 @@ objc2-ui-kit = { workspace = true, features = [
"UIViewController",
"UIWindow",
] }
winit-common = { workspace = true, features = ["core-foundation", "event-handler"] }
[package.metadata.docs.rs]
all-features = true

View File

@@ -9,11 +9,11 @@ use std::{fmt, ptr};
use dispatch2::MainThreadBound;
use dpi::PhysicalSize;
use objc2::rc::Retained;
use objc2::MainThreadMarker;
use objc2::rc::Retained;
use objc2_core_foundation::{
kCFRunLoopCommonModes, CFAbsoluteTimeGetCurrent, CFRetained, CFRunLoop, CFRunLoopTimer, CGRect,
CGSize,
CFAbsoluteTimeGetCurrent, CFRetained, CFRunLoop, CFRunLoopTimer, CGRect, CGSize,
kCFRunLoopCommonModes,
};
use objc2_ui_kit::{UIApplication, UICoordinateSpace, UIView};
use winit_common::core_foundation::EventLoopProxy;

View File

@@ -4,9 +4,9 @@ use std::sync::Arc;
use objc2::rc::Retained;
use objc2::runtime::ProtocolObject;
use objc2::{msg_send, ClassType, MainThreadMarker};
use objc2::{ClassType, MainThreadMarker, msg_send};
use objc2_core_foundation::{
kCFRunLoopDefaultMode, CFIndex, CFRunLoop, CFRunLoopActivity, CFRunLoopObserver,
CFIndex, CFRunLoop, CFRunLoopActivity, CFRunLoopObserver, kCFRunLoopDefaultMode,
};
use objc2_foundation::{NSNotificationCenter, NSObjectProtocol};
use objc2_ui_kit::{
@@ -26,7 +26,7 @@ use winit_core::event_loop::{
use winit_core::monitor::MonitorHandle as CoreMonitorHandle;
use winit_core::window::{Theme, Window as CoreWindow};
use super::app_state::{send_occluded_event_for_all_windows, AppState};
use super::app_state::{AppState, send_occluded_event_for_all_windows};
use super::notification_center::create_observer;
use crate::monitor::MonitorHandle;
use crate::window::Window;
@@ -154,7 +154,7 @@ impl EventLoop {
// this line sets up the main run loop before `UIApplicationMain`
setup_control_flow_observers();
let center = unsafe { NSNotificationCenter::defaultCenter() };
let center = NSNotificationCenter::defaultCenter();
let _did_finish_launching_observer = create_observer(
&center,
@@ -181,7 +181,7 @@ impl EventLoop {
// `applicationWillEnterForeground:`
unsafe { UIApplicationWillEnterForegroundNotification },
move |notification| {
let app = unsafe { notification.object() }.expect(
let app = notification.object().expect(
"UIApplicationWillEnterForegroundNotification to have application object",
);
// The `object` in `UIApplicationWillEnterForegroundNotification` is documented to
@@ -195,7 +195,7 @@ impl EventLoop {
// `applicationDidEnterBackground:`
unsafe { UIApplicationDidEnterBackgroundNotification },
move |notification| {
let app = unsafe { notification.object() }.expect(
let app = notification.object().expect(
"UIApplicationDidEnterBackgroundNotification to have application object",
);
// The `object` in `UIApplicationDidEnterBackgroundNotification` is documented to be
@@ -209,7 +209,8 @@ impl EventLoop {
// `applicationWillTerminate:`
unsafe { UIApplicationWillTerminateNotification },
move |notification| {
let app = unsafe { notification.object() }
let app = notification
.object()
.expect("UIApplicationWillTerminateNotification to have application object");
// The `object` in `UIApplicationWillTerminateNotification` is (somewhat) documented
// to be `UIApplication`.

View File

@@ -4,10 +4,10 @@ use std::collections::VecDeque;
use std::num::NonZeroU32;
use std::{fmt, hash, ptr};
use dispatch2::{run_on_main, MainThreadBound};
use dispatch2::{MainThreadBound, run_on_main};
use dpi::PhysicalPosition;
use objc2::rc::Retained;
use objc2::{available, MainThreadMarker, Message};
use objc2::{MainThreadMarker, Message, available};
use objc2_foundation::NSInteger;
use objc2_ui_kit::{UIScreen, UIScreenMode};
use winit_core::monitor::{MonitorHandleProvider, VideoMode};
@@ -190,7 +190,7 @@ impl MonitorHandle {
Self { ui_screen: MainThreadBound::new(ui_screen, mtm) }
}
pub fn video_modes_handles(&self) -> impl Iterator<Item = VideoModeHandle> {
pub fn video_modes_handles(&self) -> impl Iterator<Item = VideoModeHandle> + 'static {
run_on_main(|mtm| {
let ui_screen = self.ui_screen(mtm);
@@ -203,7 +203,7 @@ impl MonitorHandle {
})
}
pub fn video_modes(&self) -> impl Iterator<Item = VideoMode> {
pub fn video_modes(&self) -> impl Iterator<Item = VideoMode> + 'static {
self.video_modes_handles().map(|handle| handle.mode)
}
@@ -271,8 +271,8 @@ mod tests {
let main = UIScreen::mainScreen(mtm);
assert!(UIScreen::screens(mtm).iter().any(|screen| ptr::eq(&*screen, &*main)));
assert!(unsafe {
assert!(
NSSet::setWithArray(&UIScreen::screens(mtm)).containsObject(&UIScreen::mainScreen(mtm))
});
);
}
}

View File

@@ -4,7 +4,7 @@ use std::cell::{Cell, RefCell};
use dpi::PhysicalPosition;
use objc2::rc::Retained;
use objc2::runtime::{NSObjectProtocol, ProtocolObject};
use objc2::{available, define_class, msg_send, sel, DefinedClass, MainThreadMarker};
use objc2::{DefinedClass, MainThreadMarker, available, define_class, msg_send, sel};
use objc2_core_foundation::{CGFloat, CGPoint, CGRect};
use objc2_foundation::{NSObject, NSSet, NSString};
use objc2_ui_kit::{
@@ -461,6 +461,10 @@ impl WinitView {
let window = self.window().unwrap();
let mut touch_events = Vec::new();
for touch in touches {
if let UITouchType::Pencil = touch.r#type() {
continue;
}
let logical_location = touch.locationInView(None);
let touch_type = touch.r#type();
let force = if let UITouchType::Pencil = touch_type {

View File

@@ -1,7 +1,7 @@
use std::cell::Cell;
use objc2::rc::Retained;
use objc2::{available, define_class, msg_send, DefinedClass, MainThreadMarker};
use objc2::{DefinedClass, MainThreadMarker, available, define_class, msg_send};
use objc2_foundation::NSObject;
use objc2_ui_kit::{
UIDevice, UIInterfaceOrientationMask, UIRectEdge, UIResponder, UIStatusBarStyle,

View File

@@ -9,7 +9,7 @@ use dpi::{
Position, Size,
};
use objc2::rc::Retained;
use objc2::{available, class, define_class, msg_send, MainThreadMarker};
use objc2::{MainThreadMarker, available, class, define_class, msg_send};
use objc2_core_foundation::{CGFloat, CGPoint, CGRect, CGSize};
use objc2_foundation::{NSObject, NSObjectProtocol};
use objc2_ui_kit::{
@@ -161,8 +161,7 @@ impl Inner {
pub fn surface_position(&self) -> PhysicalPosition<i32> {
let view_position = self.view.frame().origin;
let position =
unsafe { self.window.convertPoint_fromView(view_position, Some(&self.view)) };
let position = self.window.convertPoint_fromView(view_position, Some(&self.view));
let position = LogicalPosition::new(position.x, position.y);
position.to_physical(self.scale_factor())
}
@@ -393,9 +392,7 @@ impl Inner {
}
*current_caps = Some(capabilities);
unsafe {
self.view.becomeFirstResponder();
}
self.view.becomeFirstResponder();
},
ImeRequest::Update(_) => {
if current_caps.is_none() {
@@ -404,9 +401,7 @@ impl Inner {
},
ImeRequest::Disable => {
*current_caps = None;
unsafe {
self.view.resignFirstResponder();
}
self.view.resignFirstResponder();
},
}

View File

@@ -14,6 +14,7 @@ default = ["dlopen", "csd-adwaita"]
csd-adwaita = ["sctk-adwaita", "sctk-adwaita/ab_glyph"]
csd-adwaita-crossfont = ["sctk-adwaita", "sctk-adwaita/crossfont"]
csd-adwaita-notitle = ["sctk-adwaita"]
csd-adwaita-notitlebar = ["csd-adwaita-notitle"]
dlopen = ["wayland-backend/dlopen"]
serde = ["dep:serde", "bitflags/serde", "smol_str/serde", "dpi/serde"]
@@ -33,12 +34,14 @@ calloop.workspace = true
libc.workspace = true
memmap2.workspace = true
rustix = { workspace = true, features = ["std", "system", "thread", "process", "event", "pipe"] }
sctk.workspace = true
sctk-adwaita = { workspace = true, optional = true }
wayland-backend.workspace = true
wayland-client.workspace = true
wayland-protocols.workspace = true
wayland-protocols-plasma.workspace = true
sctk = { package = "smithay-client-toolkit", version = "0.20.0", default-features = false, features = [
"calloop",
] }
sctk-adwaita = { version = "0.11.0", default-features = false, optional = true }
wayland-backend = { version = "0.3.10", default-features = false, features = ["client_system"] }
wayland-client = "0.31.10"
wayland-protocols = { version = "0.32.8", features = ["staging"] }
wayland-protocols-plasma = { version = "0.3.8", features = ["client"] }
winit-common = { workspace = true, features = ["xkb", "wayland"] }
[package.metadata.docs.rs]

View File

@@ -15,7 +15,7 @@ use dpi::LogicalSize;
use rustix::event::{PollFd, PollFlags};
use rustix::pipe::{self, PipeFlags};
use sctk::reexports::calloop_wayland_source::WaylandSource;
use sctk::reexports::client::{globals, Connection, QueueHandle};
use sctk::reexports::client::{Connection, QueueHandle, globals};
use tracing::warn;
use winit_core::application::ApplicationHandler;
use winit_core::cursor::{CustomCursor as CoreCustomCursor, CustomCursorSource};
@@ -41,7 +41,7 @@ pub use winit_core::event_loop::EventLoopProxy as CoreEventLoopProxy;
use super::output::MonitorHandle;
use super::state::{WindowCompositorUpdate, WinitState};
use super::window::state::FrameCallbackState;
use super::{logical_to_physical_rounded, WindowId};
use super::{WindowId, logical_to_physical_rounded};
type WaylandDispatcher = calloop::Dispatcher<'static, WaylandSource<WinitState>, WinitState>;
@@ -639,7 +639,7 @@ impl RootActiveEventLoop for ActiveEventLoop {
let cursor_image = match cursor {
CustomCursorSource::Image(cursor_image) => cursor_image,
CustomCursorSource::Animation { .. } | CustomCursorSource::Url { .. } => {
return Err(NotSupportedError::new("unsupported cursor kind").into())
return Err(NotSupportedError::new("unsupported cursor kind").into());
},
};

View File

@@ -13,12 +13,13 @@
//! * `wayland-csd-adwaita` (default).
//! * `wayland-csd-adwaita-crossfont`.
//! * `wayland-csd-adwaita-notitle`.
//! * `wayland-csd-adwaita-notitlebar`.
use std::ffi::c_void;
use std::ptr::NonNull;
use dpi::{LogicalSize, PhysicalSize};
use sctk::reexports::client::protocol::wl_surface::WlSurface;
use sctk::reexports::client::Proxy;
use sctk::reexports::client::protocol::wl_surface::WlSurface;
use sctk::shm::slot::{Buffer, CreateBufferError, SlotPool};
use wayland_client::protocol::wl_shm::Format;
use winit_core::event_loop::ActiveEventLoop as CoreActiveEventLoop;
@@ -27,9 +28,7 @@ use winit_core::window::{
};
macro_rules! os_error {
($error:expr) => {{
winit_core::error::OsError::new(line!(), file!(), $error)
}};
($error:expr) => {{ winit_core::error::OsError::new(line!(), file!(), $error) }};
}
mod event_loop;
@@ -61,7 +60,7 @@ pub trait EventLoopExtWayland {
fn is_wayland(&self) -> bool;
}
/// Additional methods on [`EventLoopBuilder`] that are specific to Wayland.
/// Additional methods when building event loop that are specific to Wayland.
pub trait EventLoopBuilderExtWayland {
/// Force using Wayland.
fn with_wayland(&mut self) -> &mut Self;
@@ -99,6 +98,7 @@ pub(crate) struct ApplicationName {
pub struct WindowAttributesWayland {
pub(crate) name: Option<ApplicationName>,
pub(crate) activation_token: Option<ActivationToken>,
pub(crate) prefer_csd: bool,
}
impl WindowAttributesWayland {
@@ -120,6 +120,18 @@ impl WindowAttributesWayland {
self.activation_token = Some(token);
self
}
/// Builds the window with a given preference for client-side decorations.
///
/// When set to `true`, the window will tell the compositor that it prefers
/// client-side decorations, even if server-side decorations are available.
/// When set to `false` (the default), the window will indicate a preference
/// for server-side decorations.
#[inline]
pub fn with_prefer_csd(mut self, prefer_csd: bool) -> Self {
self.prefer_csd = prefer_csd;
self
}
}
impl PlatformWindowAttributes for WindowAttributesWayland {

View File

@@ -3,8 +3,8 @@ use std::num::NonZeroU32;
use dpi::{LogicalPosition, PhysicalPosition};
use sctk::output::{Mode, OutputData};
use sctk::reexports::client::protocol::wl_output::WlOutput;
use sctk::reexports::client::Proxy;
use sctk::reexports::client::protocol::wl_output::WlOutput;
use winit_core::monitor::{MonitorHandleProvider as CoreMonitorHandle, VideoMode};
#[derive(Clone, Debug)]

View File

@@ -15,9 +15,9 @@ use winit_common::xkb::Context;
use winit_core::event::{ElementState, WindowEvent};
use winit_core::keyboard::ModifiersState;
use crate::WindowId;
use crate::event_loop::sink::EventSink;
use crate::state::WinitState;
use crate::WindowId;
impl Dispatch<WlKeyboard, KeyboardData, WinitState> for WinitState {
fn event(
@@ -129,20 +129,23 @@ impl Dispatch<WlKeyboard, KeyboardData, WinitState> for WinitState {
state.events_sink.push_window_event(WindowEvent::Focused(false), window_id);
}
},
WlKeyboardEvent::Key { key, state: WEnum::Value(WlKeyState::Pressed), .. } => {
WlKeyboardEvent::Key { key, state: WEnum::Value(key_state), .. }
if matches!(key_state, WlKeyState::Repeated | WlKeyState::Pressed) =>
{
let key = key + 8;
key_input(
keyboard_state,
&mut state.events_sink,
data,
key,
ElementState::Pressed,
false,
key_state == WlKeyState::Repeated,
);
let delay = match keyboard_state.repeat_info {
RepeatInfo::Repeat { delay, .. } => delay,
// When compositor handles repeat, and thus we have `repeat = true`, we have
// repeat on our side disabled, if it's not true, it's a compositor bug.
RepeatInfo::Disable => return,
};

View File

@@ -12,6 +12,8 @@ use sctk::reexports::protocols::wp::text_input::zv3::client::zwp_text_input_v3::
use sctk::seat::pointer::{ThemeSpec, ThemedPointer};
use sctk::seat::{Capability as SeatCapability, SeatHandler, SeatState};
use tracing::warn;
use wayland_protocols::wp::pointer_gestures::zv1::client::zwp_pointer_gesture_pinch_v1::ZwpPointerGesturePinchV1;
use wayland_protocols::wp::tablet::zv2::client::zwp_tablet_seat_v2::ZwpTabletSeatV2;
use winit_core::event::WindowEvent;
use winit_core::keyboard::ModifiersState;
@@ -23,6 +25,7 @@ mod text_input;
mod touch;
use keyboard::{KeyboardData, KeyboardState};
pub use pointer::pointer_gesture::{PointerGestureData, PointerGesturesState};
pub use pointer::relative_pointer::RelativePointerState;
pub use pointer::{PointerConstraintsState, WinitPointerData, WinitPointerDataExt};
use text_input::TextInputData;
@@ -48,9 +51,15 @@ pub struct WinitSeatState {
/// The text input bound on the seat.
text_input: Option<Arc<ZwpTextInputV3>>,
/// The tablet input bound on the seat.
tablet: Option<Arc<ZwpTabletSeatV2>>,
/// The relative pointer bound on the seat.
relative_pointer: Option<ZwpRelativePointerV1>,
/// The pinch pointer gesture bound on the seat.
pointer_gesture_pinch: Option<ZwpPointerGesturePinchV1>,
/// The keyboard bound on the seat.
keyboard_state: Option<KeyboardState>,
@@ -124,6 +133,14 @@ impl SeatHandler for WinitState {
)
});
seat_state.pointer_gesture_pinch = self.pointer_gestures.as_ref().map(|manager| {
manager.get_pinch_gesture(
themed_pointer.pointer(),
queue_handle,
PointerGestureData::default(),
)
});
let themed_pointer = Arc::new(themed_pointer);
// Register cursor surface.
@@ -143,6 +160,12 @@ impl SeatHandler for WinitState {
TextInputData::default(),
)));
}
if let Some(tablet_state) =
seat_state.tablet.is_none().then_some(self.tablet_state.as_ref()).flatten()
{
seat_state.tablet = Some(Arc::new(tablet_state.get_tablet_seat(&seat, queue_handle)));
}
}
fn remove_capability(
@@ -164,6 +187,11 @@ impl SeatHandler for WinitState {
text_input.destroy();
}
// NOTE: figure out when this should actually be destroyed.
if let Some(tablet) = seat_state.tablet.take() {
tablet.destroy();
}
match capability {
SeatCapability::Touch => {
if let Some(touch) = seat_state.touch.take() {
@@ -177,6 +205,10 @@ impl SeatHandler for WinitState {
relative_pointer.destroy();
}
if let Some(pointer_gesture_pinch) = seat_state.pointer_gesture_pinch.take() {
pointer_gesture_pinch.destroy();
}
if let Some(pointer) = seat_state.pointer.take() {
let pointer_data = pointer.pointer().winit_data();

View File

@@ -30,12 +30,13 @@ use sctk::seat::SeatState;
use dpi::{LogicalPosition, PhysicalPosition};
use winit_core::event::{
ElementState, MouseButton, MouseScrollDelta, PointerKind, PointerSource, TouchPhase,
WindowEvent,
WindowEvent, ButtonSource,
};
use crate::state::WinitState;
use crate::WindowId;
pub mod pointer_gesture;
pub mod relative_pointer;
impl PointerHandler for WinitState {
@@ -107,8 +108,8 @@ impl PointerHandler for WinitState {
if parent_surface != surface =>
{
let click = match wayland_button_to_winit(button) {
MouseButton::Left => FrameClick::Normal,
MouseButton::Right => FrameClick::Alternate,
ButtonSource::Mouse(MouseButton::Left) => FrameClick::Normal,
ButtonSource::Mouse(MouseButton::Right) => FrameClick::Alternate,
_ => continue,
};
let pressed = matches!(kind, PointerEventKind::Press { .. });
@@ -185,7 +186,7 @@ impl PointerHandler for WinitState {
device_id: None,
state,
position,
button: button.into(),
button,
},
window_id,
);
@@ -194,6 +195,7 @@ impl PointerHandler for WinitState {
// Get the current phase.
let mut pointer_data = pointer.winit_data().inner.lock().unwrap();
let has_value120_scroll = horizontal.value120 != 0 || vertical.value120 != 0;
let has_discrete_scroll = horizontal.discrete != 0 || vertical.discrete != 0;
// Figure out what to do about start/ended phases here.
@@ -205,7 +207,7 @@ impl PointerHandler for WinitState {
} else {
match pointer_data.phase {
// Discrete scroll only results in moved events.
_ if has_discrete_scroll => TouchPhase::Moved,
_ if has_value120_scroll || has_discrete_scroll => TouchPhase::Moved,
TouchPhase::Started | TouchPhase::Moved => TouchPhase::Moved,
_ => TouchPhase::Started,
}
@@ -216,7 +218,13 @@ impl PointerHandler for WinitState {
// Mice events have both pixel and discrete delta's at the same time. So prefer
// the discrete values if they are present.
let delta = if has_discrete_scroll {
let delta = if has_value120_scroll {
// NOTE: Wayland sign convention is the inverse of winit.
MouseScrollDelta::LineDelta(
(-horizontal.value120) as f32 / 120.,
(-vertical.value120) as f32 / 120.,
)
} else if has_discrete_scroll {
// NOTE: Wayland sign convention is the inverse of winit.
MouseScrollDelta::LineDelta(
(-horizontal.discrete) as f32,
@@ -401,23 +409,16 @@ impl Default for WinitPointerDataInner {
}
/// Convert the Wayland button into winit.
fn wayland_button_to_winit(button: u32) -> MouseButton {
fn wayland_button_to_winit(button: u32) -> ButtonSource {
// These values are coming from <linux/input-event-codes.h>.
const BTN_LEFT: u32 = 0x110;
const BTN_RIGHT: u32 = 0x111;
const BTN_MIDDLE: u32 = 0x112;
const BTN_SIDE: u32 = 0x113;
const BTN_EXTRA: u32 = 0x114;
const BTN_FORWARD: u32 = 0x115;
const BTN_BACK: u32 = 0x116;
const BTN_MOUSE: u32 = 0x110;
const BTN_JOYSTICK: u32 = 0x120;
match button {
BTN_LEFT => MouseButton::Left,
BTN_RIGHT => MouseButton::Right,
BTN_MIDDLE => MouseButton::Middle,
BTN_BACK | BTN_SIDE => MouseButton::Back,
BTN_FORWARD | BTN_EXTRA => MouseButton::Forward,
button => MouseButton::Other(button as u16),
if (BTN_MOUSE..BTN_JOYSTICK).contains(&button) {
// Mapping orders match
MouseButton::try_from_u8((button - BTN_MOUSE) as u8).unwrap().into()
} else {
ButtonSource::Unknown(button as u16)
}
}

View File

@@ -0,0 +1,157 @@
use std::ops::Deref;
use std::sync::Mutex;
use dpi::{LogicalPosition, PhysicalPosition};
use sctk::compositor::SurfaceData;
use sctk::globals::GlobalData;
use sctk::reexports::client::globals::{BindError, GlobalList};
use sctk::reexports::client::{Connection, Dispatch, Proxy, QueueHandle, delegate_dispatch};
use sctk::reexports::protocols::wp::pointer_gestures::zv1::client::zwp_pointer_gesture_pinch_v1::{
Event, ZwpPointerGesturePinchV1,
};
use sctk::reexports::protocols::wp::pointer_gestures::zv1::client::zwp_pointer_gestures_v1::ZwpPointerGesturesV1;
use winit_core::event::{TouchPhase, WindowEvent};
use winit_core::window::WindowId;
use crate::state::WinitState;
/// Wrapper around the pointer gesture.
#[derive(Debug)]
pub struct PointerGesturesState {
pointer_gestures: ZwpPointerGesturesV1,
}
impl PointerGesturesState {
/// Create a new pointer gesture
pub fn new(
globals: &GlobalList,
queue_handle: &QueueHandle<WinitState>,
) -> Result<Self, BindError> {
let pointer_gestures = globals.bind(queue_handle, 1..=1, GlobalData)?;
Ok(Self { pointer_gestures })
}
}
#[derive(Debug, Default)]
pub struct PointerGestureData {
inner: Mutex<PointerGestureDataInner>,
}
#[derive(Debug)]
pub struct PointerGestureDataInner {
window_id: Option<WindowId>,
previous_pinch: f64,
}
impl Default for PointerGestureDataInner {
fn default() -> Self {
Self { window_id: Default::default(), previous_pinch: 1.0 }
}
}
impl Deref for PointerGesturesState {
type Target = ZwpPointerGesturesV1;
fn deref(&self) -> &Self::Target {
&self.pointer_gestures
}
}
impl Dispatch<ZwpPointerGesturesV1, GlobalData, WinitState> for PointerGesturesState {
fn event(
_state: &mut WinitState,
_proxy: &ZwpPointerGesturesV1,
_event: <ZwpPointerGesturesV1 as wayland_client::Proxy>::Event,
_data: &GlobalData,
_conn: &Connection,
_qhandle: &QueueHandle<WinitState>,
) {
unreachable!("zwp_pointer_gestures_v1 has no events")
}
}
impl Dispatch<ZwpPointerGesturePinchV1, PointerGestureData, WinitState> for PointerGesturesState {
fn event(
state: &mut WinitState,
_proxy: &ZwpPointerGesturePinchV1,
event: <ZwpPointerGesturePinchV1 as Proxy>::Event,
data: &PointerGestureData,
_conn: &Connection,
_qhandle: &QueueHandle<WinitState>,
) {
let mut pointer_gesture_data = data.inner.lock().unwrap();
let (window_id, phase, pan_delta, pinch_delta, rotation_delta) = match event {
Event::Begin { surface, fingers, .. } => {
// We only support two fingers for now.
if fingers != 2 {
return;
}
// Don't handle events from a subsurface.
if surface.data::<SurfaceData>().is_none_or(|data| data.parent_surface().is_some())
{
return;
}
let window_id = crate::make_wid(&surface);
pointer_gesture_data.window_id = Some(window_id);
pointer_gesture_data.previous_pinch = 1.;
(window_id, TouchPhase::Started, PhysicalPosition::new(0., 0.), 0., 0.)
},
Event::Update { dx, dy, scale: pinch, rotation, .. } => {
let window_id = match pointer_gesture_data.window_id {
Some(window_id) => window_id,
_ => return,
};
let scale_factor = match state.windows.get_mut().get_mut(&window_id) {
Some(window) => window.lock().unwrap().scale_factor(),
None => return,
};
let pan_delta =
LogicalPosition::new(dx as f32, dy as f32).to_physical(scale_factor);
let pinch_delta = pinch - pointer_gesture_data.previous_pinch;
pointer_gesture_data.previous_pinch = pinch;
// Wayland provides rotation in degrees cw, opposite of winit's degrees ccw.
let rotation_delta = -rotation as f32;
(window_id, TouchPhase::Moved, pan_delta, pinch_delta, rotation_delta)
},
Event::End { cancelled, .. } => {
let window_id = match pointer_gesture_data.window_id {
Some(window_id) => window_id,
_ => return,
};
// Reset the state.
*pointer_gesture_data = Default::default();
let phase = if cancelled == 0 { TouchPhase::Ended } else { TouchPhase::Cancelled };
(window_id, phase, PhysicalPosition::new(0., 0.), 0., 0.)
},
_ => unreachable!("Unknown event {event:?}"),
};
// The chance of only one of these events being necessary is extremely small,
// so it is easier to just send all three
state.events_sink.push_window_event(
WindowEvent::PanGesture { device_id: None, delta: pan_delta, phase },
window_id,
);
state.events_sink.push_window_event(
WindowEvent::PinchGesture { device_id: None, delta: pinch_delta, phase },
window_id,
);
state.events_sink.push_window_event(
WindowEvent::RotationGesture { device_id: None, delta: rotation_delta, phase },
window_id,
);
}
}
delegate_dispatch!(WinitState: [ZwpPointerGesturesV1: GlobalData] => PointerGesturesState);
delegate_dispatch!(WinitState: [ZwpPointerGesturePinchV1: PointerGestureData] => PointerGesturesState);

View File

@@ -4,14 +4,16 @@ use dpi::{LogicalPosition, LogicalSize};
use sctk::globals::GlobalData;
use sctk::reexports::client::globals::{BindError, GlobalList};
use sctk::reexports::client::protocol::wl_surface::WlSurface;
use sctk::reexports::client::{delegate_dispatch, Connection, Dispatch, Proxy, QueueHandle};
use sctk::reexports::client::{Connection, Dispatch, Proxy, QueueHandle, delegate_dispatch};
use sctk::reexports::protocols::wp::text_input::zv3::client::zwp_text_input_manager_v3::ZwpTextInputManagerV3;
use sctk::reexports::protocols::wp::text_input::zv3::client::zwp_text_input_v3::{
ContentHint, ContentPurpose, Event as TextInputEvent, ZwpTextInputV3,
};
use tracing::warn;
use winit_core::event::{Ime, WindowEvent};
use winit_core::window::{ImeCapabilities, ImePurpose, ImeRequestData, ImeSurroundingText};
use winit_core::window::{
ImeCapabilities, ImeHint, ImePurpose, ImeRequestData, ImeSurroundingText,
};
use crate::state::WinitState;
@@ -82,6 +84,7 @@ impl Dispatch<ZwpTextInputV3, TextInputData, WinitState> for TextInputState {
},
TextInputEvent::Leave { surface } => {
text_input_data.surface = None;
text_input_data.last_preedit_empty = true;
// Always issue a disable.
text_input.disable();
@@ -127,6 +130,13 @@ impl Dispatch<ZwpTextInputV3, TextInputData, WinitState> for TextInputState {
None => return,
};
// Just in case some IME sends an event for the disabled window.
if let Some(window) = windows.get(&window_id) {
if window.lock().unwrap().text_input_state().is_none() {
return;
}
};
// The events are sent to the user separately, so
// CAUTION: events must always arrive in the order compatible with the application
// order specified by the text-input-v3 protocol:
@@ -151,14 +161,17 @@ impl Dispatch<ZwpTextInputV3, TextInputData, WinitState> for TextInputState {
);
}
// Clear preedit, unless all we'll be doing next is sending a new preedit.
// Clear preedit, unless all we'll be doing next is sending a new preedit and
// the last preedit wasn't empty.
if text_input_data.pending_commit.is_some()
|| text_input_data.pending_preedit.is_none()
|| (text_input_data.pending_preedit.is_none()
&& !text_input_data.last_preedit_empty)
{
state.events_sink.push_window_event(
WindowEvent::Ime(Ime::Preedit(String::new(), None)),
window_id,
);
text_input_data.last_preedit_empty = true;
}
// Send `Commit`.
@@ -173,6 +186,7 @@ impl Dispatch<ZwpTextInputV3, TextInputData, WinitState> for TextInputState {
let cursor_range =
preedit.cursor_begin.map(|b| (b, preedit.cursor_end.unwrap_or(b)));
text_input_data.last_preedit_empty = false;
state.events_sink.push_window_event(
WindowEvent::Ime(Ime::Preedit(preedit.text, cursor_range)),
window_id,
@@ -236,7 +250,6 @@ pub struct TextInputData {
inner: std::sync::Mutex<TextInputDataInner>,
}
#[derive(Default)]
pub struct TextInputDataInner {
/// The `WlSurface` we're performing input to.
surface: Option<WlSurface>,
@@ -249,6 +262,21 @@ pub struct TextInputDataInner {
/// The text around the cursor to delete on `done`
pending_delete: Option<DeleteSurroundingText>,
/// Last preedit empty.
last_preedit_empty: bool,
}
impl Default for TextInputDataInner {
fn default() -> Self {
Self {
surface: None,
pending_commit: None,
pending_preedit: None,
pending_delete: None,
last_preedit_empty: true,
}
}
}
/// The state of the preedit.
@@ -278,9 +306,7 @@ struct DeleteSurroundingText {
#[derive(Debug, PartialEq, Clone)]
pub struct ClientState {
capabilities: ImeCapabilities,
content_type: ContentType,
/// The IME cursor area which should not be covered by the input method popup.
cursor_area: (LogicalPosition<u32>, LogicalSize<u32>),
@@ -302,8 +328,10 @@ impl ClientState {
surrounding_text: ImeSurroundingText::new(String::new(), 0, 0).unwrap(),
};
let unsupported_flags =
capabilities.without_purpose().without_cursor_area().without_surrounding_text();
let unsupported_flags = capabilities
.without_hint_and_purpose()
.without_cursor_area()
.without_surrounding_text();
if unsupported_flags != ImeCapabilities::new() {
warn!(
@@ -322,12 +350,10 @@ impl ClientState {
/// Updates the fields of the state which are present in update_fields.
pub fn update(&mut self, request_data: ImeRequestData, scale_factor: f64) {
if let Some(purpose) = request_data.purpose {
if self.capabilities.purpose() {
self.content_type = purpose.into();
} else {
warn!("discarding ImePurpose update without capability enabled.");
}
if let Some((hint, purpose)) =
request_data.hint_and_purpose.filter(|_| self.capabilities.hint_and_purpose())
{
self.content_type = (hint, purpose).into();
}
if let Some((position, size)) = request_data.cursor_area {
@@ -350,7 +376,7 @@ impl ClientState {
}
pub fn content_type(&self) -> Option<ContentType> {
self.capabilities.purpose().then_some(self.content_type)
self.capabilities.hint_and_purpose().then_some(self.content_type)
}
pub fn cursor_area(&self) -> Option<(LogicalPosition<u32>, LogicalSize<u32>)> {
@@ -365,20 +391,69 @@ impl ClientState {
/// Arguments to content_type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ContentType {
/// Text input purpose
purpose: ContentPurpose,
/// Text input hint.
hint: ContentHint,
/// Text input purpose.
purpose: ContentPurpose,
}
impl From<ImePurpose> for ContentType {
fn from(purpose: ImePurpose) -> Self {
let (hint, purpose) = match purpose {
ImePurpose::Password => (ContentHint::SensitiveData, ContentPurpose::Password),
ImePurpose::Terminal => (ContentHint::None, ContentPurpose::Terminal),
_ => return Default::default(),
/// The two options influence each other, so they must be converted together.
impl From<(ImeHint, ImePurpose)> for ContentType {
fn from((hint, purpose): (ImeHint, ImePurpose)) -> Self {
let purpose = match purpose {
ImePurpose::Password => ContentPurpose::Password,
ImePurpose::Terminal => ContentPurpose::Terminal,
ImePurpose::Phone => ContentPurpose::Phone,
ImePurpose::Number => ContentPurpose::Number,
ImePurpose::Url => ContentPurpose::Url,
ImePurpose::Email => ContentPurpose::Email,
ImePurpose::Pin => ContentPurpose::Pin,
ImePurpose::Date => ContentPurpose::Date,
ImePurpose::Time => ContentPurpose::Time,
ImePurpose::DateTime => ContentPurpose::Datetime,
_ => ContentPurpose::Normal,
};
Self { hint, purpose }
let base_hint = match purpose {
// Before the hint API was introduced, password purpose guaranteed the
// sensitive hint. Keep this behaviour for the sake of backwards compatibility.
ContentPurpose::Password | ContentPurpose::Pin => ContentHint::SensitiveData,
_ => ContentHint::None,
};
let mut new_hint = base_hint;
if hint.contains(ImeHint::COMPLETION) {
new_hint |= ContentHint::Completion;
}
if hint.contains(ImeHint::SPELLCHECK) {
new_hint |= ContentHint::Spellcheck;
}
if hint.contains(ImeHint::AUTO_CAPITALIZATION) {
new_hint |= ContentHint::AutoCapitalization;
}
if hint.contains(ImeHint::LOWERCASE) {
new_hint |= ContentHint::Lowercase;
}
if hint.contains(ImeHint::UPPERCASE) {
new_hint |= ContentHint::Uppercase;
}
if hint.contains(ImeHint::TITLECASE) {
new_hint |= ContentHint::Titlecase;
}
if hint.contains(ImeHint::HIDDEN_TEXT) {
new_hint |= ContentHint::HiddenText;
}
if hint.contains(ImeHint::SENSITIVE_DATA) {
new_hint |= ContentHint::SensitiveData;
}
if hint.contains(ImeHint::LATIN) {
new_hint |= ContentHint::Latin;
}
if hint.contains(ImeHint::MULTILINE) {
new_hint |= ContentHint::Multiline;
}
Self { hint: new_hint, purpose }
}
}

View File

@@ -12,29 +12,30 @@ use sctk::reexports::client::protocol::wl_output::WlOutput;
use sctk::reexports::client::protocol::wl_surface::WlSurface;
use sctk::reexports::client::{Connection, Proxy, QueueHandle};
use sctk::registry::{ProvidesRegistryState, RegistryState};
use sctk::seat::pointer::ThemedPointer;
use sctk::seat::SeatState;
use sctk::shell::xdg::window::{Window, WindowConfigure, WindowHandler};
use sctk::shell::xdg::XdgShell;
use sctk::seat::pointer::ThemedPointer;
use sctk::shell::WaylandSurface;
use sctk::shell::xdg::XdgShell;
use sctk::shell::xdg::window::{Window, WindowConfigure, WindowHandler};
use sctk::shm::slot::SlotPool;
use sctk::shm::{Shm, ShmHandler};
use sctk::subcompositor::SubcompositorState;
use winit_core::error::OsError;
use crate::WindowId;
use crate::event_loop::sink::EventSink;
use crate::output::MonitorHandle;
use crate::seat::{
PointerConstraintsState, RelativePointerState, TextInputState, WinitPointerData,
WinitPointerDataExt, WinitSeatState,
PointerConstraintsState, PointerGesturesState, RelativePointerState, TextInputState,
WinitPointerData, WinitPointerDataExt, WinitSeatState,
};
use crate::types::kwin_blur::KWinBlurManager;
use crate::types::wp_fractional_scaling::FractionalScalingManager;
use crate::types::wp_tablet_input_v2::TabletManager;
use crate::types::wp_viewporter::ViewporterState;
use crate::types::xdg_activation::XdgActivationState;
use crate::types::xdg_toplevel_icon_manager::XdgToplevelIconManagerState;
use crate::window::{WindowRequests, WindowState};
use crate::WindowId;
/// Winit's Wayland state.
#[derive(Debug)]
@@ -100,9 +101,15 @@ pub struct WinitState {
/// Relative pointer.
pub relative_pointer: Option<RelativePointerState>,
/// Tablet manager.
pub tablet_state: Option<TabletManager>,
/// Pointer constraints to handle pointer locking and confining.
pub pointer_constraints: Option<Arc<PointerConstraintsState>>,
/// Pointer gestures to handle pinch, rotate, and pan
pub pointer_gestures: Option<PointerGesturesState>,
/// Viewporter state on the given window.
pub viewporter_state: Option<ViewporterState>,
@@ -191,10 +198,12 @@ impl WinitState {
text_input_state: TextInputState::new(globals, queue_handle).ok(),
relative_pointer: RelativePointerState::new(globals, queue_handle).ok(),
tablet_state: TabletManager::new(globals, queue_handle).ok(),
pointer_constraints: PointerConstraintsState::new(globals, queue_handle)
.map(Arc::new)
.ok(),
pointer_surfaces: Default::default(),
pointer_gestures: PointerGesturesState::new(globals, queue_handle).ok(),
monitors: Arc::new(Mutex::new(monitors)),
events_sink: EventSink::new(),

View File

@@ -3,7 +3,7 @@
use sctk::globals::GlobalData;
use sctk::reexports::client::globals::{BindError, GlobalList};
use sctk::reexports::client::protocol::wl_surface::WlSurface;
use sctk::reexports::client::{delegate_dispatch, Connection, Dispatch, Proxy, QueueHandle};
use sctk::reexports::client::{Connection, Dispatch, Proxy, QueueHandle, delegate_dispatch};
use wayland_protocols_plasma::blur::client::org_kde_kwin_blur::OrgKdeKwinBlur;
use wayland_protocols_plasma::blur::client::org_kde_kwin_blur_manager::OrgKdeKwinBlurManager;

View File

@@ -3,6 +3,7 @@
pub mod cursor;
pub mod kwin_blur;
pub mod wp_fractional_scaling;
pub mod wp_tablet_input_v2;
pub mod wp_viewporter;
pub mod xdg_activation;
pub mod xdg_toplevel_icon_manager;

View File

@@ -3,7 +3,7 @@
use sctk::globals::GlobalData;
use sctk::reexports::client::globals::{BindError, GlobalList};
use sctk::reexports::client::protocol::wl_surface::WlSurface;
use sctk::reexports::client::{delegate_dispatch, Connection, Dispatch, Proxy, QueueHandle};
use sctk::reexports::client::{Connection, Dispatch, Proxy, QueueHandle, delegate_dispatch};
use sctk::reexports::protocols::wp::fractional_scale::v1::client::wp_fractional_scale_manager_v1::WpFractionalScaleManagerV1;
use sctk::reexports::protocols::wp::fractional_scale::v1::client::wp_fractional_scale_v1::{
Event as FractionalScalingEvent, WpFractionalScaleV1,

View File

@@ -0,0 +1,343 @@
//! Handling of wp_tablet_input_v2.
use std::sync::Mutex;
use dpi::LogicalPosition;
use sctk::compositor::SurfaceData;
use sctk::globals::GlobalData;
use sctk::reexports::client::backend::smallvec::SmallVec;
use sctk::reexports::client::globals::{BindError, GlobalList};
use sctk::reexports::client::protocol::wl_seat::WlSeat;
use sctk::reexports::client::protocol::wl_surface::WlSurface;
use sctk::reexports::client::{
Connection, Dispatch, Proxy, QueueHandle, WEnum, delegate_dispatch, event_created_child,
};
use sctk::reexports::protocols::wp::tablet::zv2::client::zwp_tablet_manager_v2::ZwpTabletManagerV2;
use sctk::reexports::protocols::wp::tablet::zv2::client::zwp_tablet_pad_v2::ZwpTabletPadV2;
use sctk::reexports::protocols::wp::tablet::zv2::client::zwp_tablet_seat_v2::{
self, ZwpTabletSeatV2,
};
use sctk::reexports::protocols::wp::tablet::zv2::client::zwp_tablet_tool_v2::{
ButtonState, Event as ToolEvent, Type as ToolType, ZwpTabletToolV2,
};
use sctk::reexports::protocols::wp::tablet::zv2::client::zwp_tablet_v2::ZwpTabletV2;
use winit_core::event::{
ButtonSource, ElementState, Force, PointerKind, PointerSource, TabletToolButton,
TabletToolData as CoreTabletToolData, TabletToolKind, TabletToolTilt, WindowEvent,
};
use crate::state::WinitState;
/// KWin blur manager.
#[derive(Debug, Clone)]
pub struct TabletManager {
manager: ZwpTabletManagerV2,
}
impl TabletManager {
pub fn new(
globals: &GlobalList,
queue_handle: &QueueHandle<WinitState>,
) -> Result<Self, BindError> {
// Ignore v2 since we are not interested in its events.
let manager = globals.bind(queue_handle, 1..=1, GlobalData)?;
Ok(Self { manager })
}
pub fn get_tablet_seat(
&self,
seat: &WlSeat,
queue_handle: &QueueHandle<WinitState>,
) -> ZwpTabletSeatV2 {
self.manager.get_tablet_seat(seat, queue_handle, ())
}
}
impl Dispatch<ZwpTabletManagerV2, GlobalData, WinitState> for TabletManager {
fn event(
_: &mut WinitState,
_: &ZwpTabletManagerV2,
_: <ZwpTabletManagerV2 as Proxy>::Event,
_: &GlobalData,
_: &Connection,
_: &QueueHandle<WinitState>,
) {
unreachable!("no events defined for zwp_tablet_manager_v2");
}
}
impl Dispatch<ZwpTabletManagerV2, (), WinitState> for TabletManager {
fn event(
_: &mut WinitState,
_: &ZwpTabletManagerV2,
_: <ZwpTabletManagerV2 as Proxy>::Event,
_: &(),
_: &Connection,
_: &QueueHandle<WinitState>,
) {
unreachable!("no events defined for zwp_tablet_manager_v2");
}
}
impl Dispatch<ZwpTabletSeatV2, (), WinitState> for TabletManager {
event_created_child!(WinitState, ZwpTabletSeatV2, [
zwp_tablet_seat_v2::EVT_TABLET_ADDED_OPCODE => (ZwpTabletV2, Default::default()),
zwp_tablet_seat_v2::EVT_TOOL_ADDED_OPCODE => (ZwpTabletToolV2, Default::default()),
zwp_tablet_seat_v2::EVT_PAD_ADDED_OPCODE => (ZwpTabletPadV2, Default::default())
]);
fn event(
_: &mut WinitState,
_: &ZwpTabletSeatV2,
_: <ZwpTabletSeatV2 as Proxy>::Event,
_: &(),
_: &Connection,
_: &QueueHandle<WinitState>,
) {
}
}
impl Dispatch<ZwpTabletToolV2, TabletToolData, WinitState> for TabletManager {
fn event(
state: &mut WinitState,
_: &ZwpTabletToolV2,
event: <ZwpTabletToolV2 as Proxy>::Event,
data: &TabletToolData,
_: &Connection,
_: &QueueHandle<WinitState>,
) {
let mut data = data.inner.lock().unwrap();
match event {
ToolEvent::Type { tool_type: WEnum::Value(tool_type) } => {
data.ty = match tool_type {
ToolType::Pen => TabletToolKind::Pen,
ToolType::Eraser => TabletToolKind::Eraser,
ToolType::Brush => TabletToolKind::Brush,
ToolType::Pencil => TabletToolKind::Pencil,
ToolType::Airbrush => TabletToolKind::Airbrush,
ToolType::Finger => TabletToolKind::Finger,
ToolType::Mouse => TabletToolKind::Mouse,
ToolType::Lens => TabletToolKind::Lens,
_ => return,
};
},
ToolEvent::Capability { .. } => {},
ToolEvent::Done => (),
ToolEvent::ProximityIn { serial, surface, .. } => {
data.pending.push(TabletEvent::Enter { serial, surface });
},
ToolEvent::ProximityOut => data.pending.push(TabletEvent::Left),
ToolEvent::Down { serial } => {
let event = TabletEvent::Button {
state: ElementState::Pressed,
serial: Some(serial),
button: TabletToolButton::Contact,
};
data.pending.push(event);
},
ToolEvent::Up => {
let event = TabletEvent::Button {
state: ElementState::Released,
serial: None,
button: TabletToolButton::Contact,
};
data.pending.push(event);
},
ToolEvent::Tilt { tilt_x, tilt_y } => {
data.tool_state.tilt = Some(TabletToolTilt { x: tilt_x as i8, y: tilt_y as i8 });
},
ToolEvent::Motion { x, y } => {
data.position = (x, y).into();
data.pending.push(TabletEvent::Moved);
},
ToolEvent::Pressure { pressure } => {
data.tool_state.force = Some(Force::Normalized(pressure as f64 / u16::MAX as f64));
},
ToolEvent::Rotation { degrees } => {
data.tool_state.twist = Some(degrees as u16);
},
ToolEvent::Button { serial, button, state: WEnum::Value(state) } => {
let state = match state {
ButtonState::Released => ElementState::Released,
ButtonState::Pressed => ElementState::Pressed,
_ => return,
};
// Map similar to SDL.
let button = match button {
// BTN_STYLUS.
0x14b => TabletToolButton::Contact,
0x14c => TabletToolButton::Barrel,
// BTN_STYLUS3.
0x149 => TabletToolButton::Other(1),
// There's no defined conversion for any of that.
button => TabletToolButton::Other(button as u16),
};
let event = TabletEvent::Button { button, state, serial: Some(serial) };
data.pending.push(event);
},
ToolEvent::Frame { .. } => {
let kind = data.ty;
for event in std::mem::take(&mut data.pending) {
if let TabletEvent::Enter { surface, serial } = &event {
data.latest_enter_serial = Some(*serial);
data.surface = Some(surface.clone());
}
// Handle events only for top-level surface.
let surface = match data
.surface
.as_ref()
.map(|surface| (surface, surface.data::<SurfaceData>()))
{
Some((surface, Some(surface_data)))
if surface_data.parent_surface().is_none() =>
{
surface
},
_ => continue,
};
let window_id = crate::make_wid(surface);
// Ensure that window exists.
let window = match state.windows.get_mut().get_mut(&window_id) {
Some(window) => window.lock().unwrap(),
None => continue,
};
let position = data.position.to_physical(window.scale_factor());
let window_event = match event {
TabletEvent::Enter { .. } => WindowEvent::PointerEntered {
device_id: None,
position,
primary: true,
kind: PointerKind::TabletTool(kind),
},
TabletEvent::Moved => WindowEvent::PointerMoved {
device_id: None,
position,
primary: true,
source: PointerSource::TabletTool {
kind,
data: data.tool_state.clone(),
},
},
TabletEvent::Button { button, state, serial } => {
// Update serial if we have it.
if let Some(serial) = serial {
data.latest_button_serial = Some(serial);
}
WindowEvent::PointerButton {
device_id: None,
state,
position,
primary: true,
button: ButtonSource::TabletTool {
kind,
button,
data: data.tool_state.clone(),
},
}
},
TabletEvent::Left => WindowEvent::PointerLeft {
device_id: None,
position: Some(position),
primary: true,
kind: PointerKind::TabletTool(kind),
},
};
state.events_sink.push_window_event(window_event, window_id);
// Clear up the surface after we've processed `Left` event.
if matches!(event, TabletEvent::Left) {
data.surface = None;
data.latest_button_serial = None;
data.latest_enter_serial = None;
data.tool_state = Default::default();
}
}
},
_ => (),
}
}
}
#[derive(Debug, Default)]
struct TabletToolData {
inner: Mutex<TabletToolDataInner>,
}
#[derive(Debug, Default)]
pub(crate) struct TabletToolDataInner {
pub(crate) ty: TabletToolKind,
/// Core tablet tool data.
pub(crate) tool_state: CoreTabletToolData,
/// Pending events until the `frame` is received.
pub(crate) pending: SmallVec<[TabletEvent; 4]>,
/// Surface the tablet most recently entered.
pub(crate) surface: Option<WlSurface>,
/// Position relative to the surface.
pub(crate) position: LogicalPosition<f64>,
// NOTE: even though we don't utilize serials
// right now, track them anyway.
/// The serial of the latest enter event for the pointer
pub(crate) latest_enter_serial: Option<u32>,
/// The serial of the latest button event for the pointer
pub(crate) latest_button_serial: Option<u32>,
}
// Due to wayland using logical coordinates,
// delay the conversion to physical until the dispatch actually happens,
// so the scaling is applied at the time of actual dispatch, since it
// can technically change before the `frame` event.
#[derive(Debug, Clone)]
pub(crate) enum TabletEvent {
Enter { serial: u32, surface: WlSurface },
Left,
Moved,
Button { button: TabletToolButton, state: ElementState, serial: Option<u32> },
}
impl Dispatch<ZwpTabletV2, (), WinitState> for TabletManager {
fn event(
_: &mut WinitState,
_: &ZwpTabletV2,
_: <ZwpTabletV2 as Proxy>::Event,
_: &(),
_: &Connection,
_: &QueueHandle<WinitState>,
) {
}
}
impl Dispatch<ZwpTabletPadV2, (), WinitState> for TabletManager {
fn event(
_: &mut WinitState,
_: &ZwpTabletPadV2,
_: <ZwpTabletPadV2 as Proxy>::Event,
_: &(),
_: &Connection,
_: &QueueHandle<WinitState>,
) {
}
}
delegate_dispatch!(WinitState: [ZwpTabletManagerV2: GlobalData] => TabletManager);
delegate_dispatch!(WinitState: [ZwpTabletManagerV2: ()] => TabletManager);
delegate_dispatch!(WinitState: [ZwpTabletSeatV2: ()] => TabletManager);
delegate_dispatch!(WinitState: [ZwpTabletV2: ()] => TabletManager);
delegate_dispatch!(WinitState: [ZwpTabletToolV2: TabletToolData] => TabletManager);
delegate_dispatch!(WinitState: [ZwpTabletPadV2: ()] => TabletManager);

View File

@@ -3,7 +3,7 @@
use sctk::globals::GlobalData;
use sctk::reexports::client::globals::{BindError, GlobalList};
use sctk::reexports::client::protocol::wl_surface::WlSurface;
use sctk::reexports::client::{delegate_dispatch, Connection, Dispatch, Proxy, QueueHandle};
use sctk::reexports::client::{Connection, Dispatch, Proxy, QueueHandle, delegate_dispatch};
use sctk::reexports::protocols::wp::viewporter::client::wp_viewport::WpViewport;
use sctk::reexports::protocols::wp::viewporter::client::wp_viewporter::WpViewporter;

View File

@@ -1,12 +1,12 @@
//! Handling of xdg activation, which is used for user attention requests.
use std::sync::atomic::AtomicBool;
use std::sync::Weak;
use std::sync::atomic::AtomicBool;
use sctk::globals::GlobalData;
use sctk::reexports::client::globals::{BindError, GlobalList};
use sctk::reexports::client::protocol::wl_surface::WlSurface;
use sctk::reexports::client::{delegate_dispatch, Connection, Dispatch, Proxy, QueueHandle};
use sctk::reexports::client::{Connection, Dispatch, Proxy, QueueHandle, delegate_dispatch};
use sctk::reexports::protocols::xdg::activation::v1::client::xdg_activation_token_v1::{
Event as ActivationTokenEvent, XdgActivationTokenV1,
};

View File

@@ -7,7 +7,7 @@ use sctk::globals::GlobalData;
use sctk::shm::slot::{Buffer, SlotPool};
use wayland_client::globals::{BindError, GlobalList};
use wayland_client::protocol::wl_shm::Format;
use wayland_client::{delegate_dispatch, Connection, Dispatch, Proxy, QueueHandle};
use wayland_client::{Connection, Dispatch, Proxy, QueueHandle, delegate_dispatch};
use wayland_protocols::xdg::toplevel_icon::v1::client::xdg_toplevel_icon_manager_v1::XdgToplevelIconManagerV1;
use wayland_protocols::xdg::toplevel_icon::v1::client::xdg_toplevel_icon_v1::XdgToplevelIconV1;
use winit_core::icon::{Icon, RgbaIcon};

View File

@@ -11,8 +11,8 @@ use sctk::reexports::client::protocol::wl_display::WlDisplay;
use sctk::reexports::client::protocol::wl_surface::WlSurface;
use sctk::reexports::client::{Proxy, QueueHandle};
use sctk::reexports::protocols::xdg::activation::v1::client::xdg_activation_v1::XdgActivationV1;
use sctk::shell::xdg::window::{Window as SctkWindow, WindowDecorations};
use sctk::shell::WaylandSurface;
use sctk::shell::xdg::window::{Window as SctkWindow, WindowDecorations};
use tracing::warn;
use winit_core::cursor::Cursor;
use winit_core::error::{NotSupportedError, RequestError};
@@ -25,12 +25,12 @@ use winit_core::window::{
WindowLevel,
};
use super::ActiveEventLoop;
use super::event_loop::sink::EventSink;
use super::output::MonitorHandle;
use super::state::WinitState;
use super::types::xdg_activation::XdgActivationTokenData;
use super::ActiveEventLoop;
use crate::{output, WindowAttributesWayland};
use crate::{WindowAttributesWayland, output};
pub(crate) mod state;
@@ -106,6 +106,12 @@ impl Window {
let window =
state.xdg_shell.create_window(surface.clone(), default_decorations, &queue_handle);
let WindowAttributesWayland { name: app_name, activation_token, prefer_csd } = *attributes
.platform
.take()
.and_then(|p| p.cast::<WindowAttributesWayland>().ok())
.unwrap_or_default();
let mut window_state = WindowState::new(
event_loop_window_target.handle.clone(),
&event_loop_window_target.queue_handle,
@@ -113,6 +119,7 @@ impl Window {
size,
window.clone(),
attributes.preferred_theme,
prefer_csd,
);
window_state.set_window_icon(attributes.window_icon);
@@ -125,13 +132,6 @@ impl Window {
// Set the decorations hint.
window_state.set_decorate(attributes.decorations);
let (app_name, activation_token) =
match attributes.platform.take().and_then(|p| p.cast::<WindowAttributesWayland>().ok())
{
Some(attrs) => (attrs.name, attrs.activation_token),
None => (None, None),
};
// Set the app_id.
if let Some(name) = app_name.map(|name| name.general) {
window.set_app_id(name);
@@ -431,11 +431,7 @@ impl CoreWindow for Window {
}
fn set_maximized(&self, maximized: bool) {
if maximized {
self.window.set_maximized()
} else {
self.window.unset_maximized()
}
if maximized { self.window.set_maximized() } else { self.window.unset_maximized() }
}
fn is_maximized(&self) -> bool {

View File

@@ -21,11 +21,11 @@ use sctk::reexports::protocols::wp::text_input::zv3::client::zwp_text_input_v3::
use sctk::reexports::protocols::wp::viewporter::client::wp_viewport::WpViewport;
use sctk::reexports::protocols::xdg::shell::client::xdg_toplevel::ResizeEdge as XdgResizeEdge;
use sctk::seat::pointer::{PointerDataExt, ThemedPointer};
use sctk::shell::xdg::window::{DecorationMode, Window, WindowConfigure};
use sctk::shell::xdg::XdgSurface;
use sctk::shell::WaylandSurface;
use sctk::shm::slot::SlotPool;
use sctk::shell::xdg::XdgSurface;
use sctk::shell::xdg::window::{DecorationMode, Window, WindowConfigure};
use sctk::shm::Shm;
use sctk::shm::slot::SlotPool;
use sctk::subcompositor::SubcompositorState;
use tracing::{info, warn};
use wayland_protocols::xdg::toplevel_icon::v1::client::xdg_toplevel_icon_manager_v1::XdgToplevelIconManagerV1;
@@ -134,6 +134,9 @@ pub struct WindowState {
/// Whether we should decorate the frame.
decorate: bool,
/// Whether we should tell the compositor that we prefer drawing decorations ourself.
prefer_csd: bool,
/// Min size.
min_surface_size: LogicalSize<u32>,
max_surface_size: Option<LogicalSize<u32>>,
@@ -180,6 +183,7 @@ impl WindowState {
initial_size: Size,
window: Window,
theme: Option<Theme>,
prefer_csd: bool,
) -> Self {
let compositor = winit_state.compositor_state.clone();
let pointer_constraints = winit_state.pointer_constraints.clone();
@@ -209,6 +213,7 @@ impl WindowState {
selected_cursor: Default::default(),
cursor_visible: true,
decorate: true,
prefer_csd,
fractional_scale,
frame: None,
frame_callback_state: FrameCallbackState::None,
@@ -302,7 +307,7 @@ impl WindowState {
subcompositor.clone(),
self.queue_handle.clone(),
#[cfg(feature = "sctk-adwaita")]
into_sctk_adwaita_config(self.theme),
create_sctk_adwaita_config(self.theme),
) {
Ok(mut frame) => {
frame.set_title(&self.title);
@@ -816,7 +821,7 @@ impl WindowState {
self.theme = theme;
#[cfg(feature = "sctk-adwaita")]
if let Some(frame) = self.frame.as_mut() {
frame.set_config(into_sctk_adwaita_config(theme))
frame.set_config(create_sctk_adwaita_config(theme))
}
}
@@ -852,7 +857,7 @@ impl WindowState {
None => {
return Err(
NotSupportedError::new("zwp_pointer_constraints is not available").into()
)
);
},
};
@@ -955,7 +960,7 @@ impl WindowState {
/// Whether show or hide client side decorations.
#[inline]
pub fn set_decorate(&mut self, decorate: bool) {
if decorate == self.decorate {
if decorate == self.decorate && !self.prefer_csd {
return;
}
@@ -966,6 +971,9 @@ impl WindowState {
// To disable decorations we should request client and hide the frame.
self.window.request_decoration_mode(Some(DecorationMode::Client))
},
_ if self.decorate && self.prefer_csd => {
self.window.request_decoration_mode(Some(DecorationMode::Client))
},
_ if self.decorate => self.window.request_decoration_mode(Some(DecorationMode::Server)),
_ => (),
}
@@ -1037,11 +1045,7 @@ impl WindowState {
text_input.set_state(self.text_input_state.as_ref(), state_change);
}
if state_change {
Ok(Some(self.text_input_state.is_some()))
} else {
Ok(None)
}
if state_change { Ok(Some(self.text_input_state.is_some())) } else { Ok(None) }
}
/// Set the scale factor for the given window.
@@ -1228,12 +1232,14 @@ fn resize_direction_to_xdg(direction: ResizeDirection) -> XdgResizeEdge {
}
}
// NOTE: Rust doesn't allow `From<Option<Theme>>`.
#[cfg(feature = "sctk-adwaita")]
fn into_sctk_adwaita_config(theme: Option<Theme>) -> sctk_adwaita::FrameConfig {
match theme {
fn create_sctk_adwaita_config(theme: Option<Theme>) -> sctk_adwaita::FrameConfig {
let config = match theme {
Some(Theme::Light) => sctk_adwaita::FrameConfig::light(),
Some(Theme::Dark) => sctk_adwaita::FrameConfig::dark(),
None => sctk_adwaita::FrameConfig::auto(),
}
};
#[cfg(feature = "csd-adwaita-notitlebar")]
let config = config.hide_titlebar(true);
config
}

View File

@@ -2,8 +2,8 @@ use std::error::Error;
use std::fmt::{self, Display, Formatter};
use std::future::Future;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::task::{Context, Poll};
use pin_project::pin_project;

View File

@@ -1,7 +1,7 @@
use std::future;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, RecvError, SendError, TryRecvError};
use std::sync::Arc;
use std::task::Poll;
use super::AtomicWaker;

View File

@@ -32,13 +32,10 @@ impl<T> ConcurrentQueue<T> {
}
pub fn pop(&self) -> Result<T, PopError> {
self.queue.borrow_mut().pop().ok_or_else(|| {
if self.closed.get() {
PopError::Closed
} else {
PopError::Empty
}
})
self.queue
.borrow_mut()
.pop()
.ok_or_else(|| if self.closed.get() { PopError::Closed } else { PopError::Empty })
}
pub fn close(&self) -> bool {

View File

@@ -6,7 +6,7 @@ use std::rc::Rc;
use std::sync::{Arc, Condvar, Mutex};
use super::super::main_thread::MainThreadMarker;
use super::{channel, Receiver, Sender, Wrapper};
use super::{Receiver, Sender, Wrapper, channel};
pub struct Dispatcher<T: 'static>(Wrapper<T, Arc<Sender<Closure<T>>>, Closure<T>>);

View File

@@ -12,7 +12,7 @@ pub(crate) use atomic_waker::AtomicWaker;
use concurrent_queue::{ConcurrentQueue, PushError};
pub use self::abortable::{AbortHandle, Abortable, DropAbortHandle};
pub use self::channel::{channel, Receiver, Sender};
pub use self::channel::{Receiver, Sender, channel};
pub use self::dispatcher::{DispatchRunner, Dispatcher};
pub use self::notifier::{Notified, Notifier};
pub(crate) use self::wrapper::Wrapper;

View File

@@ -6,14 +6,14 @@ use std::ops::{Deref, DerefMut};
use std::pin::Pin;
use std::rc::Rc;
use std::sync::Arc;
use std::task::{ready, Context, Poll, Waker};
use std::task::{Context, Poll, Waker, ready};
use std::time::Duration;
use cursor_icon::CursorIcon;
use js_sys::{Array, Object};
use wasm_bindgen::JsCast;
use wasm_bindgen::closure::Closure;
use wasm_bindgen::prelude::wasm_bindgen;
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::JsFuture;
use web_sys::{
Blob, Document, DomException, HtmlCanvasElement, HtmlImageElement, ImageBitmap,
@@ -21,11 +21,11 @@ use web_sys::{
};
use winit_core::cursor::{Cursor, CursorImage, CustomCursorProvider, CustomCursorSource};
use crate::CustomCursorError;
use crate::r#async::{AbortHandle, Abortable, DropAbortHandle, Notified, Notifier};
use crate::backend::Style;
use crate::event_loop::ActiveEventLoop;
use crate::main_thread::{MainThreadMarker, MainThreadSafe};
use crate::r#async::{AbortHandle, Abortable, DropAbortHandle, Notified, Notifier};
use crate::CustomCursorError;
#[derive(Clone, Debug)]
pub struct CustomCursor {
@@ -216,7 +216,7 @@ impl CursorHandler {
Cursor::Custom(cursor) => {
let cursor = match cursor.cast_ref::<CustomCursor>() {
Some(cursor) => cursor,
None => todo!(),
None => return,
};
if let SelectedCursor::Loading { cursor: old_cursor, .. }
@@ -487,7 +487,7 @@ fn from_rgba(
window: &Window,
document: Document,
image: &CursorImage,
) -> impl Future<Output = Result<Image, CustomCursorError>> {
) -> impl Future<Output = Result<Image, CustomCursorError>> + use<> {
// 1. Create an `ImageData` from the RGBA data.
// 2. Create an `ImageBitmap` from the `ImageData`.
// 3. Draw `ImageBitmap` on an `HTMLCanvasElement`.

View File

@@ -5,7 +5,7 @@ use winit_core::error::{EventLoopError, NotSupportedError};
use winit_core::event_loop::ActiveEventLoop as RootActiveEventLoop;
use crate::{
backend, HasMonitorPermissionFuture, MonitorPermissionFuture, PollStrategy, WaitUntilStrategy,
HasMonitorPermissionFuture, MonitorPermissionFuture, PollStrategy, WaitUntilStrategy, backend,
};
mod proxy;

View File

@@ -1,13 +1,13 @@
use std::future;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::task::Poll;
use winit_core::event_loop::EventLoopProxyProvider;
use super::super::main_thread::MainThreadMarker;
use crate::event_loop::runner::WeakShared;
use crate::r#async::{AtomicWaker, Wrapper};
use crate::event_loop::runner::WeakShared;
#[derive(Debug)]
pub struct EventLoopProxy(Wrapper<WeakShared, Arc<State>, ()>);

View File

@@ -6,8 +6,8 @@ use std::sync::Arc;
use std::{fmt, iter};
use dpi::PhysicalSize;
use wasm_bindgen::prelude::Closure;
use wasm_bindgen::JsCast;
use wasm_bindgen::prelude::Closure;
use web_sys::{Document, KeyboardEvent, Navigator, PageTransitionEvent, PointerEvent, WheelEvent};
use web_time::{Duration, Instant};
use winit_core::application::ApplicationHandler;
@@ -19,14 +19,14 @@ use winit_core::window::WindowId;
use super::proxy::EventLoopProxy;
use super::state::State;
use crate::r#async::DispatchRunner;
use crate::backend::{EventListenerHandle, SafeAreaHandle};
use crate::event_loop::ActiveEventLoop;
use crate::main_thread::MainThreadMarker;
use crate::monitor::MonitorHandler;
use crate::r#async::DispatchRunner;
use crate::web_sys::event::mouse_button_to_id;
use crate::web_sys::event::ButtonsState;
use crate::window::Inner;
use crate::{backend, event, EventLoop, PollStrategy, WaitUntilStrategy};
use crate::{EventLoop, PollStrategy, WaitUntilStrategy, backend, event};
#[derive(Debug)]
pub struct Shared(Rc<Execution>);
@@ -318,8 +318,10 @@ impl Shared {
// chorded button event
let device_id = event::mkdid(event.pointer_id());
if let Some(button) = backend::event::mouse_button(&event) {
let state = if backend::event::mouse_buttons(&event).contains(button.into()) {
if let Some(button) = backend::event::raw_button(&event) {
let state = if backend::event::pointer_buttons(&event)
.contains(ButtonsState::from_bits_retain(button))
{
ElementState::Pressed
} else {
ElementState::Released
@@ -327,10 +329,7 @@ impl Shared {
runner.send_event(Event::DeviceEvent {
device_id,
event: DeviceEvent::Button {
button: mouse_button_to_id(button).into(),
state,
},
event: DeviceEvent::Button { button: button.into(), state },
});
return;
@@ -338,14 +337,16 @@ impl Shared {
// pointer move event
let mut delta = backend::event::MouseDelta::init(&navigator, &event);
runner.send_events(backend::event::pointer_move_event(event).map(|event| {
let delta = delta.delta(&event).to_physical(backend::scale_factor(&window));
runner.send_events(backend::event::pointer_move_event(event).map(
|event: web_sys::PointerEvent| {
let delta = delta.delta(&event).to_physical(backend::scale_factor(&window));
Event::DeviceEvent {
device_id,
event: DeviceEvent::PointerMotion { delta: (delta.x, delta.y) },
}
}));
Event::DeviceEvent {
device_id,
event: DeviceEvent::PointerMotion { delta: (delta.x, delta.y) },
}
},
));
}),
));
let runner = self.clone();
@@ -375,11 +376,11 @@ impl Shared {
return;
}
let button = backend::event::mouse_button(&event).expect("no mouse button pressed");
let button = backend::event::raw_button(&event).expect("no pointer button pressed");
runner.send_event(Event::DeviceEvent {
device_id: event::mkdid(event.pointer_id()),
event: DeviceEvent::Button {
button: mouse_button_to_id(button).into(),
button: button.into(),
state: ElementState::Pressed,
},
});
@@ -394,11 +395,11 @@ impl Shared {
return;
}
let button = backend::event::mouse_button(&event).expect("no mouse button pressed");
let button = backend::event::raw_button(&event).expect("no pointer button pressed");
runner.send_event(Event::DeviceEvent {
device_id: event::mkdid(event.pointer_id()),
event: DeviceEvent::Button {
button: mouse_button_to_id(button).into(),
button: button.into(),
state: ElementState::Released,
},
});
@@ -801,11 +802,7 @@ impl Shared {
DeviceEvents::Always => true,
DeviceEvents::WhenFocused => {
self.0.all_canvases.borrow().iter().any(|(_, canvas, _)| {
if let Some(canvas) = canvas.upgrade() {
canvas.has_focus.get()
} else {
false
}
if let Some(canvas) = canvas.upgrade() { canvas.has_focus.get() } else { false }
})
},
DeviceEvents::Never => false,

View File

@@ -522,13 +522,8 @@ impl RootActiveEventLoop for ActiveEventLoop {
}
fn system_theme(&self) -> Option<Theme> {
backend::is_dark_mode(self.runner.window()).map(|is_dark_mode| {
if is_dark_mode {
Theme::Dark
} else {
Theme::Light
}
})
backend::is_dark_mode(self.runner.window())
.map(|is_dark_mode| if is_dark_mode { Theme::Dark } else { Theme::Light })
}
fn set_control_flow(&self, control_flow: ControlFlow) {

View File

@@ -61,9 +61,7 @@
// compliant way.
macro_rules! os_error {
($error:expr) => {{
winit_core::error::OsError::new(line!(), file!(), $error)
}};
($error:expr) => {{ winit_core::error::OsError::new(line!(), file!(), $error) }};
}
mod r#async;

View File

@@ -5,7 +5,7 @@ use tracing::error;
use wasm_bindgen::closure::Closure;
use wasm_bindgen::prelude::wasm_bindgen;
use wasm_bindgen::{JsCast, JsValue};
use web_sys::{console, Document, DomException, Element, Navigator};
use web_sys::{Document, DomException, Element, Navigator, console};
pub(crate) fn is_cursor_lock_raw(navigator: &Navigator, document: &Document) -> bool {
thread_local! {

View File

@@ -9,7 +9,7 @@ use std::ops::{Deref, DerefMut};
use std::pin::Pin;
use std::rc::{Rc, Weak};
use std::sync::{Arc, OnceLock};
use std::task::{ready, Context, Poll};
use std::task::{Context, Poll, ready};
use dpi::{LogicalSize, PhysicalPosition, PhysicalSize};
use js_sys::{Object, Promise};
@@ -19,14 +19,14 @@ use wasm_bindgen::prelude::wasm_bindgen;
use wasm_bindgen::{JsCast, JsValue};
use wasm_bindgen_futures::JsFuture;
use web_sys::{
console, DomException, Navigator, OrientationLockType, OrientationType, PermissionState,
PermissionStatus, ScreenOrientation, Window,
DomException, Navigator, OrientationLockType, OrientationType, PermissionState,
PermissionStatus, ScreenOrientation, Window, console,
};
use winit_core::monitor::{MonitorHandle as CoreMonitorHandle, MonitorHandleProvider, VideoMode};
use super::r#async::{Dispatcher, Notified, Notifier};
use super::event_loop::runner::WeakShared;
use super::main_thread::MainThreadMarker;
use super::r#async::{Dispatcher, Notified, Notifier};
use super::web_sys::{Engine, EventListenerHandle};
use crate::{
MonitorPermissionError, Orientation, OrientationData, OrientationLock, OrientationLockError,
@@ -292,11 +292,7 @@ impl Inner {
}
fn name(&self) -> Option<String> {
if let Screen::Detailed { screen, .. } = &self.screen {
Some(screen.label())
} else {
None
}
if let Screen::Detailed { screen, .. } = &self.screen { Some(screen.label()) } else { None }
}
fn orientation_raw(&self) -> &ScreenOrientationExt {
@@ -438,11 +434,7 @@ impl Detailed {
let internal_screen =
internal_screen.upgrade().expect("dropped `MonitorHandle` without cleaning up");
if *internal_screen == screen {
Some((*id, internal_screen))
} else {
None
}
if *internal_screen == screen { Some((*id, internal_screen)) } else { None }
});
let (id, screen) = if let Some((id, screen)) = found_screen {
(id, screen)
@@ -664,7 +656,7 @@ impl MonitorHandler {
State::Unsupported => {
return MonitorPermissionFuture::Ready(Some(Err(
MonitorPermissionError::Unsupported,
)))
)));
},
// If we are currently initializing, wait for initialization to finish before we do our
// thing.
@@ -676,7 +668,7 @@ impl MonitorHandler {
)
.0,
notified: notified.clone(),
}
};
},
// If we finished initialization we at least possess `PermissionStatus`.
State::Permission { permission, .. } => permission,
@@ -688,7 +680,7 @@ impl MonitorHandler {
match permission.state() {
PermissionState::Granted | PermissionState::Prompt => (),
PermissionState::Denied => {
return MonitorPermissionFuture::Ready(Some(Err(MonitorPermissionError::Denied)))
return MonitorPermissionFuture::Ready(Some(Err(MonitorPermissionError::Denied)));
},
_ => {
error!("encountered unknown permission state: {}", permission.state_string());

View File

@@ -1,8 +1,8 @@
use std::cell::Cell;
use std::rc::Rc;
use wasm_bindgen::closure::Closure;
use wasm_bindgen::JsCast;
use wasm_bindgen::closure::Closure;
pub struct AnimationFrameHandler {
window: web_sys::Window,

View File

@@ -5,8 +5,8 @@ use std::sync::{Arc, Mutex};
use dpi::{LogicalPosition, PhysicalPosition, PhysicalSize};
use smol_str::SmolStr;
use wasm_bindgen::closure::Closure;
use wasm_bindgen::JsCast;
use wasm_bindgen::closure::Closure;
use web_sys::{
CssStyleDeclaration, Document, Event, FocusEvent, HtmlCanvasElement, KeyboardEvent, Navigator,
PointerEvent, WheelEvent,
@@ -28,7 +28,7 @@ use super::event_handle::EventListenerHandle;
use super::intersection_handle::IntersectionObserverHandle;
use super::media_query_handle::MediaQueryListHandle;
use super::pointer::PointerHandler;
use super::{event, fullscreen, ResizeScaleHandle};
use super::{ResizeScaleHandle, event, fullscreen};
use crate::WindowAttributesWeb;
#[allow(dead_code)]
@@ -502,8 +502,7 @@ impl Canvas {
surface_size_writer: SurfaceSizeWriter::new(Arc::downgrade(&new_size)),
});
let new_size = *new_size.lock().unwrap();
new_size
*new_size.lock().unwrap()
};
if current_size != new_size {

View File

@@ -1,11 +1,16 @@
use std::cell::OnceCell;
use std::f64;
use dpi::{LogicalPosition, PhysicalPosition, Position};
use smol_str::SmolStr;
use tracing::warn;
use wasm_bindgen::prelude::wasm_bindgen;
use wasm_bindgen::{JsCast, JsValue};
use web_sys::{KeyboardEvent, MouseEvent, Navigator, PointerEvent, WheelEvent};
use winit_core::event::{FingerId, MouseButton, MouseScrollDelta, PointerKind};
use web_sys::{Event, KeyboardEvent, MouseEvent, Navigator, PointerEvent, WheelEvent};
use winit_core::event::{
ButtonSource, FingerId, Force, MouseButton, MouseScrollDelta, PointerKind, PointerSource,
TabletToolAngle, TabletToolButton, TabletToolData, TabletToolKind, TabletToolTilt,
};
use winit_core::keyboard::{
Key, KeyCode, KeyLocation, ModifiersState, NamedKey, NativeKey, NativeKeyCode, PhysicalKey,
};
@@ -16,71 +21,143 @@ bitflags::bitflags! {
// https://www.w3.org/TR/pointerevents3/#the-buttons-property
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ButtonsState: u16 {
const LEFT = 0b00001;
const RIGHT = 0b00010;
const MIDDLE = 0b00100;
const BACK = 0b01000;
const FORWARD = 0b10000;
}
}
const LEFT = 0b000001;
const RIGHT = 0b000010;
const MIDDLE = 0b000100;
const BACK = 0b001000;
const FORWARD = 0b010000;
const ERASER = 0b100000;
}}
impl From<ButtonsState> for MouseButton {
fn from(value: ButtonsState) -> Self {
match value {
ButtonsState::LEFT => MouseButton::Left,
ButtonsState::RIGHT => MouseButton::Right,
ButtonsState::MIDDLE => MouseButton::Middle,
ButtonsState::BACK => MouseButton::Back,
ButtonsState::FORWARD => MouseButton::Forward,
_ => MouseButton::Other(value.bits()),
impl From<TabletToolButton> for ButtonsState {
fn from(tool: TabletToolButton) -> Self {
match tool {
TabletToolButton::Contact => ButtonsState::LEFT,
TabletToolButton::Barrel => ButtonsState::RIGHT,
TabletToolButton::Other(value) => Self::from_bits_retain(value),
}
}
}
impl From<MouseButton> for ButtonsState {
fn from(value: MouseButton) -> Self {
match value {
MouseButton::Left => ButtonsState::LEFT,
MouseButton::Right => ButtonsState::RIGHT,
MouseButton::Middle => ButtonsState::MIDDLE,
MouseButton::Back => ButtonsState::BACK,
MouseButton::Forward => ButtonsState::FORWARD,
MouseButton::Other(value) => ButtonsState::from_bits_retain(value),
}
}
}
pub fn mouse_buttons(event: &MouseEvent) -> ButtonsState {
pub fn pointer_buttons(event: &MouseEvent) -> ButtonsState {
#[allow(clippy::disallowed_methods)]
ButtonsState::from_bits_retain(event.buttons())
}
pub fn mouse_button(event: &MouseEvent) -> Option<MouseButton> {
pub fn raw_button(event: &MouseEvent) -> Option<u16> {
// https://www.w3.org/TR/pointerevents3/#the-button-property
match event.button() {
-1 => None,
0 => Some(MouseButton::Left),
1 => Some(MouseButton::Middle),
2 => Some(MouseButton::Right),
3 => Some(MouseButton::Back),
4 => Some(MouseButton::Forward),
i => {
Some(MouseButton::Other(i.try_into().expect("unexpected negative mouse button value")))
},
#[allow(clippy::disallowed_methods)]
let button = event.button();
if button == -1 {
None
} else {
Some(button.try_into().expect("unexpected negative mouse button value"))
}
}
pub fn mouse_button_to_id(button: MouseButton) -> u16 {
pub fn mouse_button(button: u16) -> ButtonSource {
match button {
MouseButton::Left => 0,
MouseButton::Right => 1,
MouseButton::Middle => 2,
MouseButton::Back => 3,
MouseButton::Forward => 4,
MouseButton::Other(value) => value,
0 => MouseButton::Left.into(),
1 => MouseButton::Middle.into(),
2 => MouseButton::Right.into(),
3 => MouseButton::Back.into(),
4 => MouseButton::Forward.into(),
// Codes above 4 are not observed on Firefox or Chromium. 5 is defined as an eraser,
// which is not a mouse button. No other codes are defined.
i => ButtonSource::Unknown(i),
}
}
pub fn mouse_position(event: &MouseEvent) -> LogicalPosition<f64> {
pub fn tool_button(button: u16) -> TabletToolButton {
match button {
0 => TabletToolButton::Contact,
2 => TabletToolButton::Barrel,
other => TabletToolButton::Other(other),
}
}
#[derive(Clone, Copy)]
pub enum WebPointerType {
Mouse,
Touch,
Pen,
}
impl WebPointerType {
pub fn from_event(event: &PointerEvent) -> Option<Self> {
#[allow(clippy::disallowed_methods)]
let r#type = event.pointer_type();
match r#type.as_ref() {
"mouse" => Some(Self::Mouse),
"touch" => Some(Self::Touch),
"pen" => Some(Self::Pen),
r#type => {
warn!("found unknown pointer type: {type}");
None
},
}
}
}
pub fn pointer_kind(event: &PointerEvent, pointer_id: i32) -> PointerKind {
match WebPointerType::from_event(event) {
Some(WebPointerType::Mouse) => PointerKind::Mouse,
Some(WebPointerType::Touch) => PointerKind::Touch(FingerId::from_raw(pointer_id as usize)),
Some(WebPointerType::Pen) => {
PointerKind::TabletTool(if pointer_buttons(event).contains(ButtonsState::ERASER) {
TabletToolKind::Eraser
} else {
TabletToolKind::Pen
})
},
None => PointerKind::Unknown,
}
}
pub fn pointer_source(event: &PointerEvent, kind: PointerKind) -> PointerSource {
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(extends = PointerEvent, extends = MouseEvent, extends = Event)]
pub type PointerEventExt;
#[wasm_bindgen(method, getter, js_name = altitudeAngle)]
pub fn altitude_angle(this: &PointerEventExt) -> Option<f64>;
#[wasm_bindgen(method, getter, js_name = azimuthAngle)]
pub fn azimuth_angle(this: &PointerEventExt) -> f64;
}
let event: &PointerEventExt = event.unchecked_ref();
match kind {
PointerKind::Mouse => PointerSource::Mouse,
PointerKind::Touch(id) => PointerSource::Touch {
finger_id: id,
force: Some(Force::Normalized(event.pressure().into())),
},
PointerKind::TabletTool(tool) => {
let data = TabletToolData {
force: Some(Force::Normalized(event.pressure().into())),
tangential_force: Some(event.tangential_pressure()),
twist: Some(event.twist().try_into().expect("found invalid `twist`")),
tilt: Some(TabletToolTilt {
x: event.tilt_x().try_into().expect("found invalid `tiltX`"),
y: event.tilt_y().try_into().expect("found invalid `tiltY`"),
}),
angle: event
.altitude_angle()
.map(|altitude| TabletToolAngle { altitude, azimuth: event.azimuth_angle() }),
};
PointerSource::TabletTool { kind: tool, data }
},
PointerKind::Unknown => PointerSource::Unknown,
}
}
pub fn pointer_position(event: &MouseEvent) -> LogicalPosition<f64> {
#[wasm_bindgen]
extern "C" {
type MouseEventExt;
@@ -113,7 +190,7 @@ impl MouseDelta {
Some(Engine::Chromium) => Self::Chromium,
// Firefox has wrong movement values in coalesced events.
Some(Engine::Gecko) if has_coalesced_events_support(event) => Self::Gecko {
old_position: mouse_position(event),
old_position: pointer_position(event),
old_delta: LogicalPosition::new(
event.movement_x() as f64,
event.movement_y() as f64,
@@ -129,7 +206,7 @@ impl MouseDelta {
PhysicalPosition::new(event.movement_x(), event.movement_y()).into()
},
MouseDelta::Gecko { old_position, old_delta } => {
let new_position = mouse_position(event);
let new_position = pointer_position(event);
let x = new_position.x - old_position.x + old_delta.x;
let y = new_position.y - old_position.y + old_delta.y;
*old_position = new_position;
@@ -160,14 +237,6 @@ pub fn mouse_scroll_delta(
}
}
pub fn pointer_type(event: &PointerEvent, pointer_id: i32) -> PointerKind {
match event.pointer_type().as_str() {
"mouse" => PointerKind::Mouse,
"touch" => PointerKind::Touch(FingerId::from_raw(pointer_id as usize)),
_ => PointerKind::Unknown,
}
}
pub fn key_code(event: &KeyboardEvent) -> PhysicalKey {
// Use keyboard-types' parsing (it is based on the W3C standard).
match event.code().parse() {

View File

@@ -1,5 +1,5 @@
use wasm_bindgen::prelude::Closure;
use wasm_bindgen::JsCast;
use wasm_bindgen::prelude::Closure;
use web_sys::EventTarget;
pub struct EventListenerHandle<T: ?Sized> {

View File

@@ -5,7 +5,7 @@ use tracing::error;
use wasm_bindgen::closure::Closure;
use wasm_bindgen::prelude::wasm_bindgen;
use wasm_bindgen::{JsCast, JsValue};
use web_sys::{console, Document, Element, HtmlCanvasElement, Window};
use web_sys::{Document, Element, HtmlCanvasElement, Window, console};
use winit_core::monitor::Fullscreen;
use crate::main_thread::MainThreadMarker;

View File

@@ -1,6 +1,6 @@
use js_sys::Array;
use wasm_bindgen::prelude::Closure;
use wasm_bindgen::JsCast;
use wasm_bindgen::prelude::Closure;
use web_sys::{Element, IntersectionObserver, IntersectionObserverEntry};
pub(super) struct IntersectionObserverHandle {

View File

@@ -1,5 +1,5 @@
use wasm_bindgen::prelude::Closure;
use wasm_bindgen::JsCast;
use wasm_bindgen::prelude::Closure;
use web_sys::MediaQueryList;
pub(super) struct MediaQueryListHandle {

View File

@@ -14,9 +14,9 @@ use std::cell::OnceCell;
use dpi::{LogicalPosition, LogicalSize};
use js_sys::Array;
use wasm_bindgen::JsCast;
use wasm_bindgen::closure::Closure;
use wasm_bindgen::prelude::wasm_bindgen;
use wasm_bindgen::JsCast;
use web_sys::{Document, HtmlCanvasElement, Navigator, PageTransitionEvent, VisibilityState};
pub use self::canvas::{Canvas, Style};

View File

@@ -3,14 +3,13 @@ use std::rc::Rc;
use dpi::PhysicalPosition;
use web_sys::PointerEvent;
use winit_core::event::{ButtonSource, DeviceId, ElementState, Force, PointerKind, PointerSource};
use winit_core::event::{ButtonSource, DeviceId, ElementState, PointerKind, PointerSource};
use winit_core::keyboard::ModifiersState;
use super::canvas::Common;
use super::event;
use super::event::{self, ButtonsState};
use super::event_handle::EventListenerHandle;
use crate::event::mkdid;
use crate::web_sys::event::mouse_button_to_id;
#[allow(dead_code)]
pub(super) struct PointerHandler {
@@ -46,8 +45,8 @@ impl PointerHandler {
let pointer_id = event.pointer_id();
let device_id = mkdid(pointer_id);
let position =
event::mouse_position(&event).to_physical(super::scale_factor(&window));
let kind = event::pointer_type(&event, pointer_id);
event::pointer_position(&event).to_physical(super::scale_factor(&window));
let kind = event::pointer_kind(&event, pointer_id);
handler(modifiers, device_id, event.is_primary(), position, kind);
}));
}
@@ -64,8 +63,8 @@ impl PointerHandler {
let pointer_id = event.pointer_id();
let device_id = mkdid(pointer_id);
let position =
event::mouse_position(&event).to_physical(super::scale_factor(&window));
let kind = event::pointer_type(&event, pointer_id);
event::pointer_position(&event).to_physical(super::scale_factor(&window));
let kind = event::pointer_kind(&event, pointer_id);
handler(modifiers, device_id, event.is_primary(), position, kind);
}));
}
@@ -80,24 +79,25 @@ impl PointerHandler {
Some(canvas_common.add_event("pointerup", move |event: PointerEvent| {
let modifiers = event::mouse_modifiers(&event);
let pointer_id = event.pointer_id();
let kind = event::pointer_type(&event, pointer_id);
let kind = event::pointer_kind(&event, pointer_id);
let button = event::raw_button(&event).expect("no button pressed");
let button = event::mouse_button(&event).expect("no mouse button pressed");
let source = match kind {
PointerKind::Mouse => ButtonSource::Mouse(button),
PointerKind::Touch(finger_id) => ButtonSource::Touch {
finger_id,
force: Some(Force::Normalized(event.pressure().into())),
let source = match event::pointer_source(&event, kind) {
PointerSource::Mouse => event::mouse_button(button),
PointerSource::Touch { finger_id, force } => {
ButtonSource::Touch { finger_id, force }
},
PointerKind::Unknown => ButtonSource::Unknown(mouse_button_to_id(button)),
PointerSource::TabletTool { kind, data } => {
ButtonSource::TabletTool { kind, button: event::tool_button(button), data }
},
PointerSource::Unknown => ButtonSource::Unknown(button),
};
handler(
modifiers,
mkdid(pointer_id),
event.is_primary(),
event::mouse_position(&event).to_physical(super::scale_factor(&window)),
event::pointer_position(&event).to_physical(super::scale_factor(&window)),
source,
)
}));
@@ -125,11 +125,11 @@ impl PointerHandler {
let modifiers = event::mouse_modifiers(&event);
let pointer_id = event.pointer_id();
let kind = event::pointer_type(&event, pointer_id);
let button = event::mouse_button(&event).expect("no mouse button pressed");
let kind = event::pointer_kind(&event, pointer_id);
let button = event::raw_button(&event).expect("no button pressed");
let source = match kind {
PointerKind::Mouse => {
let source = match event::pointer_source(&event, kind) {
PointerSource::Mouse => {
// Error is swallowed here since the error would occur every time the
// mouse is clicked when the cursor is
// grabbed, and there is probably not a
@@ -137,20 +137,29 @@ impl PointerHandler {
// care if it fails.
let _e = canvas.set_pointer_capture(pointer_id);
ButtonSource::Mouse(button)
event::mouse_button(button)
},
PointerKind::Touch(finger_id) => ButtonSource::Touch {
finger_id,
force: Some(Force::Normalized(event.pressure().into())),
PointerSource::Touch { finger_id, force } => {
ButtonSource::Touch { finger_id, force }
},
PointerKind::Unknown => ButtonSource::Unknown(mouse_button_to_id(button)),
PointerSource::TabletTool { kind, data } => {
// Error is swallowed here since the error would occur every time the
// mouse is clicked when the cursor is
// grabbed, and there is probably not a
// situation where this could fail, that we
// care if it fails.
let _e = canvas.set_pointer_capture(pointer_id);
ButtonSource::TabletTool { kind, button: event::tool_button(button), data }
},
PointerSource::Unknown => ButtonSource::Unknown(button),
};
handler(
modifiers,
mkdid(pointer_id),
event.is_primary(),
event::mouse_position(&event).to_physical(super::scale_factor(&window)),
event::pointer_position(&event).to_physical(super::scale_factor(&window)),
source,
)
}));
@@ -186,11 +195,11 @@ impl PointerHandler {
Some(canvas_common.add_event("pointermove", move |event: PointerEvent| {
let pointer_id = event.pointer_id();
let device_id = mkdid(pointer_id);
let kind = event::pointer_type(&event, pointer_id);
let kind = event::pointer_kind(&event, pointer_id);
let primary = event.is_primary();
// chorded button event
if let Some(button) = event::mouse_button(&event) {
if let Some(button) = event::raw_button(&event) {
if prevent_default.get() {
// prevent text selection
event.prevent_default();
@@ -198,34 +207,36 @@ impl PointerHandler {
let _ = canvas.focus();
}
let state = if event::mouse_buttons(&event).contains(button.into()) {
let state = if event::pointer_buttons(&event)
.contains(ButtonsState::from_bits_retain(button))
{
ElementState::Pressed
} else {
ElementState::Released
};
let button = match kind {
PointerKind::Mouse => ButtonSource::Mouse(button),
PointerKind::Touch(finger_id) => {
let button_id = mouse_button_to_id(button);
if button_id != 1 {
tracing::error!("unexpected touch button id: {button_id}");
let button = match event::pointer_source(&event, kind) {
PointerSource::Mouse => event::mouse_button(button),
PointerSource::Touch { finger_id, force } => {
if button != 0 {
tracing::error!("unexpected touch button id: {button}");
}
ButtonSource::Touch {
finger_id,
force: Some(Force::Normalized(event.pressure().into())),
}
ButtonSource::Touch { finger_id, force }
},
PointerKind::Unknown => todo!(),
PointerSource::TabletTool { kind, data } => ButtonSource::TabletTool {
kind,
button: event::tool_button(button),
data,
},
PointerSource::Unknown => ButtonSource::Unknown(button),
};
button_handler(
event::mouse_modifiers(&event),
device_id,
primary,
event::mouse_position(&event).to_physical(super::scale_factor(&window)),
event::pointer_position(&event).to_physical(super::scale_factor(&window)),
state,
button,
);
@@ -242,15 +253,8 @@ impl PointerHandler {
(
event::mouse_modifiers(&event),
event.is_primary(),
event::mouse_position(&event).to_physical(scale),
match kind {
PointerKind::Mouse => PointerSource::Mouse,
PointerKind::Touch(finger_id) => PointerSource::Touch {
finger_id,
force: Some(Force::Normalized(event.pressure().into())),
},
PointerKind::Unknown => PointerSource::Unknown,
},
event::pointer_position(&event).to_physical(scale),
event::pointer_source(&event, kind),
)
}),
);

View File

@@ -4,7 +4,7 @@ use std::rc::Rc;
use dpi::{LogicalSize, PhysicalSize};
use js_sys::{Array, Object};
use tracing::warn;
use wasm_bindgen::prelude::{wasm_bindgen, Closure};
use wasm_bindgen::prelude::{Closure, wasm_bindgen};
use wasm_bindgen::{JsCast, JsValue};
use web_sys::{
Document, HtmlCanvasElement, MediaQueryList, ResizeObserver, ResizeObserverBoxOptions,

View File

@@ -16,10 +16,10 @@ use winit_core::window::{
Window as RootWindow, WindowAttributes, WindowButtons, WindowId, WindowLevel,
};
use crate::r#async::Dispatcher;
use crate::event_loop::ActiveEventLoop;
use crate::main_thread::MainThreadMarker;
use crate::monitor::MonitorHandler;
use crate::r#async::Dispatcher;
use crate::{backend, lock};
pub struct Window {
@@ -284,11 +284,7 @@ impl RootWindow for Window {
fn fullscreen(&self) -> Option<Fullscreen> {
self.inner.queue(|inner| {
if inner.canvas.is_fullscreen() {
Some(Fullscreen::Borderless(None))
} else {
None
}
if inner.canvas.is_fullscreen() { Some(Fullscreen::Borderless(None)) } else { None }
})
}
@@ -334,13 +330,8 @@ impl RootWindow for Window {
fn theme(&self) -> Option<Theme> {
self.inner.queue(|inner| {
backend::is_dark_mode(&inner.window).map(|is_dark_mode| {
if is_dark_mode {
Theme::Dark
} else {
Theme::Light
}
})
backend::is_dark_mode(&inner.window)
.map(|is_dark_mode| if is_dark_mode { Theme::Dark } else { Theme::Light })
})
}
@@ -368,7 +359,7 @@ impl RootWindow for Window {
inner.canvas.raw(),
),
CursorGrabMode::Confined => {
return Err(NotSupportedError::new("confined cursor mode is not supported"))
return Err(NotSupportedError::new("confined cursor mode is not supported"));
},
}

View File

@@ -3,16 +3,16 @@ use std::sync::LazyLock;
/// which is inspired by the solution in https://github.com/ysc3839/win32-darkmode
use std::{ffi::c_void, ptr};
use windows_sys::core::{PCSTR, PCWSTR};
use windows_sys::w;
use windows_sys::Win32::Foundation::{BOOL, HWND, LPARAM, S_OK, WPARAM};
use windows_sys::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryA};
use windows_sys::Win32::UI::Accessibility::{HCF_HIGHCONTRASTON, HIGHCONTRASTA};
use windows_sys::Win32::UI::Controls::SetWindowTheme;
use windows_sys::Win32::UI::Input::KeyboardAndMouse::GetActiveWindow;
use windows_sys::Win32::UI::WindowsAndMessaging::{
DefWindowProcW, SystemParametersInfoA, SPI_GETHIGHCONTRAST, WM_NCACTIVATE,
DefWindowProcW, SPI_GETHIGHCONTRAST, SystemParametersInfoA, WM_NCACTIVATE,
};
use windows_sys::core::{PCSTR, PCWSTR};
use windows_sys::w;
use winit_core::window::Theme;
use super::util;

View File

@@ -3,9 +3,9 @@
use std::ffi::c_void;
use windows_sys::core::{GUID, HRESULT};
use windows_sys::Win32::Foundation::{BOOL, HWND, POINTL};
use windows_sys::Win32::System::Com::{FORMATETC, STGMEDIUM};
use windows_sys::core::{GUID, HRESULT};
pub type IUnknown = *mut c_void;
pub type IAdviseSink = *mut c_void;

View File

@@ -4,7 +4,7 @@ use std::sync::Once;
use windows_sys::Win32::Foundation::{HWND, S_OK};
use windows_sys::Win32::Graphics::Gdi::{
GetDC, GetDeviceCaps, MonitorFromWindow, HMONITOR, LOGPIXELSX, MONITOR_DEFAULTTONEAREST,
GetDC, GetDeviceCaps, HMONITOR, LOGPIXELSX, MONITOR_DEFAULTTONEAREST, MonitorFromWindow,
};
use windows_sys::Win32::UI::HiDpi::{
DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE, DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2,

View File

@@ -1,4 +1,4 @@
use std::ffi::{c_void, OsString};
use std::ffi::{OsString, c_void};
use std::os::windows::ffi::OsStringExt;
use std::path::PathBuf;
use std::ptr;
@@ -6,12 +6,12 @@ use std::sync::atomic::{AtomicUsize, Ordering};
use dpi::PhysicalPosition;
use tracing::debug;
use windows_sys::core::{GUID, HRESULT};
use windows_sys::Win32::Foundation::{DV_E_FORMATETC, HWND, POINT, POINTL, S_OK};
use windows_sys::Win32::Graphics::Gdi::ScreenToClient;
use windows_sys::Win32::System::Com::{DVASPECT_CONTENT, FORMATETC, TYMED_HGLOBAL};
use windows_sys::Win32::System::Ole::{CF_HDROP, DROPEFFECT_COPY, DROPEFFECT_NONE};
use windows_sys::Win32::UI::Shell::{DragFinish, DragQueryFileW, HDROP};
use windows_sys::core::{GUID, HRESULT};
use winit_core::event::WindowEvent;
use crate::definitions::{

View File

@@ -13,21 +13,21 @@ use std::{fmt, mem, panic, ptr};
use dpi::{PhysicalPosition, PhysicalSize};
use windows_sys::Win32::Foundation::{
GetLastError, FALSE, HANDLE, HWND, LPARAM, LRESULT, POINT, RECT, WAIT_FAILED, WPARAM,
FALSE, GetLastError, HANDLE, HWND, LPARAM, LRESULT, POINT, RECT, WAIT_FAILED, WPARAM,
};
use windows_sys::Win32::Graphics::Gdi::{
GetMonitorInfoW, MonitorFromRect, MonitorFromWindow, RedrawWindow, ScreenToClient,
ValidateRect, MONITORINFO, MONITOR_DEFAULTTONULL, RDW_INTERNALPAINT, SC_SCREENSAVE,
GetMonitorInfoW, MONITOR_DEFAULTTONULL, MONITORINFO, MonitorFromRect, MonitorFromWindow,
RDW_INTERNALPAINT, RedrawWindow, SC_SCREENSAVE, ScreenToClient, ValidateRect,
};
use windows_sys::Win32::System::Ole::RevokeDragDrop;
use windows_sys::Win32::System::Threading::{
CreateWaitableTimerExW, GetCurrentThreadId, SetWaitableTimer,
CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, INFINITE, TIMER_ALL_ACCESS,
CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, CreateWaitableTimerExW, GetCurrentThreadId, INFINITE,
SetWaitableTimer, TIMER_ALL_ACCESS,
};
use windows_sys::Win32::UI::Controls::{HOVER_DEFAULT, WM_MOUSELEAVE};
use windows_sys::Win32::UI::Input::Ime::{GCS_COMPSTR, GCS_RESULTSTR, ISC_SHOWUICOMPOSITIONWINDOW};
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{
ReleaseCapture, SetCapture, TrackMouseEvent, TME_LEAVE, TRACKMOUSEEVENT,
ReleaseCapture, SetCapture, TME_LEAVE, TRACKMOUSEEVENT, TrackMouseEvent,
};
use windows_sys::Win32::UI::Input::Pointer::{
POINTER_FLAG_DOWN, POINTER_FLAG_PRIMARY, POINTER_FLAG_UP, POINTER_FLAG_UPDATE,
@@ -40,15 +40,15 @@ use windows_sys::Win32::UI::Input::{
MOUSE_MOVE_RELATIVE, RAWINPUT, RIM_TYPEKEYBOARD, RIM_TYPEMOUSE,
};
use windows_sys::Win32::UI::WindowsAndMessaging::{
CreateWindowExW, DefWindowProcW, DestroyWindow, DispatchMessageW, GetClientRect, GetCursorPos,
GetMenu, LoadCursorW, MsgWaitForMultipleObjectsEx, PeekMessageW, PostMessageW,
RegisterClassExW, RegisterWindowMessageA, SetCursor, SetWindowPos, SystemParametersInfoW,
TranslateMessage, CREATESTRUCTW, GWL_STYLE, GWL_USERDATA, HTCAPTION, HTCLIENT, MINMAXINFO,
MNC_CLOSE, MSG, MWMO_INPUTAVAILABLE, NCCALCSIZE_PARAMS, PM_REMOVE, PT_TOUCH, QS_ALLINPUT,
RI_MOUSE_HWHEEL, RI_MOUSE_WHEEL, SC_MINIMIZE, SC_RESTORE, SIZE_MAXIMIZED,
SPI_GETWHEELSCROLLCHARS, SPI_GETWHEELSCROLLLINES, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOSIZE,
SWP_NOZORDER, WHEEL_DELTA, WINDOWPOS, WMSZ_BOTTOM, WMSZ_BOTTOMLEFT, WMSZ_BOTTOMRIGHT,
WMSZ_LEFT, WMSZ_RIGHT, WMSZ_TOP, WMSZ_TOPLEFT, WMSZ_TOPRIGHT, WM_CAPTURECHANGED, WM_CLOSE,
CREATESTRUCTW, CreateWindowExW, DefWindowProcW, DestroyWindow, DispatchMessageW, GWL_STYLE,
GWL_USERDATA, GetClientRect, GetCursorPos, GetMenu, HTCAPTION, HTCLIENT, LoadCursorW,
MINMAXINFO, MNC_CLOSE, MSG, MWMO_INPUTAVAILABLE, MsgWaitForMultipleObjectsEx,
NCCALCSIZE_PARAMS, PEN_FLAG_BARREL, PEN_FLAG_ERASER, PEN_MASK_PRESSURE, PEN_MASK_ROTATION,
PEN_MASK_TILT_X, PEN_MASK_TILT_Y, PM_REMOVE, PT_PEN, PT_TOUCH, PeekMessageW, PostMessageW,
QS_ALLINPUT, RI_MOUSE_HWHEEL, RI_MOUSE_WHEEL, RegisterClassExW, RegisterWindowMessageA,
SC_MINIMIZE, SC_RESTORE, SIZE_MAXIMIZED, SPI_GETWHEELSCROLLCHARS, SPI_GETWHEELSCROLLLINES,
SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOSIZE, SWP_NOZORDER, SetCursor, SetWindowPos,
SystemParametersInfoW, TranslateMessage, WHEEL_DELTA, WINDOWPOS, WM_CAPTURECHANGED, WM_CLOSE,
WM_CREATE, WM_DESTROY, WM_DPICHANGED, WM_ENTERSIZEMOVE, WM_EXITSIZEMOVE, WM_GETMINMAXINFO,
WM_IME_COMPOSITION, WM_IME_ENDCOMPOSITION, WM_IME_SETCONTEXT, WM_IME_STARTCOMPOSITION,
WM_INPUT, WM_KEYDOWN, WM_KEYUP, WM_KILLFOCUS, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MBUTTONDOWN,
@@ -56,16 +56,17 @@ use windows_sys::Win32::UI::WindowsAndMessaging::{
WM_NCCALCSIZE, WM_NCCREATE, WM_NCDESTROY, WM_NCLBUTTONDOWN, WM_PAINT, WM_POINTERDOWN,
WM_POINTERUP, WM_POINTERUPDATE, WM_RBUTTONDOWN, WM_RBUTTONUP, WM_SETCURSOR, WM_SETFOCUS,
WM_SETTINGCHANGE, WM_SIZE, WM_SIZING, WM_SYSCOMMAND, WM_SYSKEYDOWN, WM_SYSKEYUP, WM_TOUCH,
WM_WINDOWPOSCHANGED, WM_WINDOWPOSCHANGING, WM_XBUTTONDOWN, WM_XBUTTONUP, WNDCLASSEXW,
WS_EX_LAYERED, WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW, WS_EX_TRANSPARENT, WS_OVERLAPPED, WS_POPUP,
WS_VISIBLE,
WM_WINDOWPOSCHANGED, WM_WINDOWPOSCHANGING, WM_XBUTTONDOWN, WM_XBUTTONUP, WMSZ_BOTTOM,
WMSZ_BOTTOMLEFT, WMSZ_BOTTOMRIGHT, WMSZ_LEFT, WMSZ_RIGHT, WMSZ_TOP, WMSZ_TOPLEFT,
WMSZ_TOPRIGHT, WNDCLASSEXW, WS_EX_LAYERED, WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW,
WS_EX_TRANSPARENT, WS_OVERLAPPED, WS_POPUP, WS_VISIBLE,
};
use winit_core::application::ApplicationHandler;
use winit_core::cursor::{CustomCursor, CustomCursorSource};
use winit_core::error::{EventLoopError, NotSupportedError, RequestError};
use winit_core::event::{
DeviceEvent, DeviceId, FingerId, Force, Ime, RawKeyEvent, SurfaceSizeWriter, TouchPhase,
WindowEvent,
DeviceEvent, DeviceId, FingerId, Force, Ime, RawKeyEvent, SurfaceSizeWriter, TabletToolButton,
TabletToolData, TabletToolKind, TabletToolTilt, TouchPhase, WindowEvent,
};
use winit_core::event_loop::pump_events::PumpStatus;
use winit_core::event_loop::{
@@ -78,8 +79,8 @@ use winit_core::monitor::{Fullscreen, MonitorHandle as CoreMonitorHandle};
use winit_core::window::{Theme, Window as CoreWindow, WindowAttributes, WindowId};
pub(super) use self::runner::{Event, EventLoopRunner};
use super::window::set_skip_taskbar;
use super::SelectedCursor;
use super::window::set_skip_taskbar;
use crate::dark_mode::try_theme;
use crate::dpi::{become_dpi_aware, dpi_to_scale_factor};
use crate::drop_handler::FileDropHandler;
@@ -88,7 +89,7 @@ use crate::ime::ImeContext;
use crate::keyboard::KeyEventBuilder;
use crate::keyboard_layout::LAYOUT_CACHE;
use crate::monitor::{self, MonitorHandle};
use crate::util::{wrap_device_id, WIN10_BUILD_VERSION};
use crate::util::{WIN10_BUILD_VERSION, wrap_device_id};
use crate::window::{InitData, Window};
use crate::window_state::{CursorFlags, ImeState, WindowFlags, WindowState};
use crate::{raw_input, util};
@@ -106,6 +107,7 @@ pub(crate) struct WindowData {
pub key_event_builder: KeyEventBuilder,
pub _file_drop_handler: Option<FileDropHandler>,
pub userdata_removed: Cell<bool>,
pub last_tablet_down_button_state: Cell<u32>,
pub recurse_depth: Cell<u32>,
}
@@ -277,11 +279,7 @@ impl EventLoop {
self.runner.reset_runner();
if exit_code == 0 {
Ok(())
} else {
Err(EventLoopError::ExitFailure(exit_code))
}
if exit_code == 0 { Ok(()) } else { Err(EventLoopError::ExitFailure(exit_code)) }
}
pub fn pump_app_events<A: ApplicationHandler>(
@@ -434,7 +432,7 @@ impl RootActiveEventLoop for ActiveEventLoop {
let cursor = match source {
CustomCursorSource::Image(cursor) => cursor,
CustomCursorSource::Animation { .. } | CustomCursorSource::Url { .. } => {
return Err(NotSupportedError::new("unsupported cursor kind").into())
return Err(NotSupportedError::new("unsupported cursor kind").into());
},
};
@@ -533,7 +531,7 @@ fn main_thread_id() -> u32 {
// main entrypoint.
//
// See: https://doc.rust-lang.org/stable/reference/abi.html#the-link_section-attribute
#[link_section = ".CRT$XCU"]
#[unsafe(link_section = ".CRT$XCU")]
static INIT_MAIN_THREAD_ID: unsafe fn() = {
unsafe fn initer() {
unsafe { MAIN_THREAD_ID = GetCurrentThreadId() };
@@ -564,11 +562,7 @@ fn dur2timeout(dur: Duration) -> u32 {
.and_then(|ms| ms.checked_add((dur.subsec_nanos() as u64) / 1_000_000))
.and_then(
|ms| {
if dur.subsec_nanos() % 1_000_000 > 0 {
ms.checked_add(1)
} else {
Some(ms)
}
if dur.subsec_nanos() % 1_000_000 > 0 { ms.checked_add(1) } else { Some(ms) }
},
)
.map(|ms| if ms > u32::MAX as u64 { INFINITE } else { ms as u32 })
@@ -595,11 +589,7 @@ fn create_high_resolution_timer() -> Option<OwnedHandle> {
// CREATE_WAITABLE_TIMER_HIGH_RESOLUTION is supported only after
// Win10 1803 but it is already default option for rustc
// (std uses it to implement `std::thread::sleep`).
if handle.is_null() {
None
} else {
Some(OwnedHandle::from_raw_handle(handle))
}
if handle.is_null() { None } else { Some(OwnedHandle::from_raw_handle(handle)) }
}
}
@@ -621,11 +611,7 @@ unsafe fn set_high_resolution_timer(timer: RawHandle, timeout: Duration) -> Resu
let due_time: i64 = -(intervals_to_wait as i64);
unsafe {
let set_result = SetWaitableTimer(timer as HANDLE, &due_time, 0, None, ptr::null(), FALSE);
if set_result != FALSE {
Ok(())
} else {
Err(GetLastError())
}
if set_result != FALSE { Ok(()) } else { Err(GetLastError()) }
}
}
@@ -1258,7 +1244,7 @@ unsafe fn public_window_callback_inner(
if let Some(new_rect) = new_rect {
let new_monitor = unsafe { MonitorFromRect(&new_rect, MONITOR_DEFAULTTONULL) };
match fullscreen {
Fullscreen::Borderless(ref mut fullscreen_monitor) => {
Fullscreen::Borderless(fullscreen_monitor) => {
if !new_monitor.is_null()
&& fullscreen_monitor
.as_ref()
@@ -1315,7 +1301,6 @@ unsafe fn public_window_callback_inner(
use winit_core::event::WindowEvent::SurfaceResized;
let w = util::loword(lparam as u32) as u32;
let h = util::hiword(lparam as u32) as u32;
let physical_size = PhysicalSize::new(w, h);
{
@@ -1327,7 +1312,14 @@ unsafe fn public_window_callback_inner(
w.set_window_flags_in_place(|f| f.set(WindowFlags::MAXIMIZED, maximized));
}
}
userdata.send_window_event(window, SurfaceResized(physical_size));
let mut state = userdata.window_state_lock();
if (w, h) != (0, 0) && physical_size != state.surface_size {
// WM_SIZE is received with size (0, 0) when a window is minimized; ignore.
state.surface_size = physical_size;
drop(state);
userdata.send_window_event(window, SurfaceResized(physical_size));
}
result = ProcResult::Value(0);
},
@@ -1646,12 +1638,14 @@ unsafe fn public_window_callback_inner(
let scroll_lines_multiplier = if userdata.window_state_lock().use_system_wheel_speed {
let mut scroll_lines = DEFAULT_SCROLL_LINES_PER_WHEEL_DELTA;
let _ = SystemParametersInfoW(
SPI_GETWHEELSCROLLLINES,
0,
&mut scroll_lines as *mut isize as *mut c_void,
0,
);
let _ = unsafe {
SystemParametersInfoW(
SPI_GETWHEELSCROLLLINES,
0,
&mut scroll_lines as *mut isize as *mut c_void,
0,
)
};
if scroll_lines as u32 == WHEEL_PAGESCROLL {
// TODO: figure out how to handle page scrolls
scroll_lines = DEFAULT_SCROLL_LINES_PER_WHEEL_DELTA;
@@ -1681,12 +1675,14 @@ unsafe fn public_window_callback_inner(
let scroll_characters_multiplier =
if userdata.window_state_lock().use_system_wheel_speed {
let mut scroll_characters = DEFAULT_SCROLL_CHARACTERS_PER_WHEEL_DELTA;
let _ = SystemParametersInfoW(
SPI_GETWHEELSCROLLCHARS,
0,
&mut scroll_characters as *mut isize as *mut c_void,
0,
);
let _ = unsafe {
SystemParametersInfoW(
SPI_GETWHEELSCROLLCHARS,
0,
&mut scroll_characters as *mut isize as *mut c_void,
0,
)
};
scroll_characters
} else {
1
@@ -1715,9 +1711,9 @@ unsafe fn public_window_callback_inner(
}
},
WM_LBUTTONDOWN => {
WM_LBUTTONDOWN | WM_RBUTTONDOWN | WM_MBUTTONDOWN => {
use winit_core::event::ElementState::Pressed;
use winit_core::event::MouseButton::Left;
use winit_core::event::MouseButton;
use winit_core::event::WindowEvent::PointerButton;
unsafe { capture_mouse(window, &mut userdata.window_state_lock()) };
@@ -1733,14 +1729,20 @@ unsafe fn public_window_callback_inner(
primary: true,
state: Pressed,
position,
button: Left.into(),
button: match msg {
WM_LBUTTONDOWN => MouseButton::Left,
WM_RBUTTONDOWN => MouseButton::Right,
WM_MBUTTONDOWN => MouseButton::Middle,
_ => unreachable!(),
}
.into(),
});
result = ProcResult::Value(0);
},
WM_LBUTTONUP => {
WM_LBUTTONUP | WM_RBUTTONUP | WM_MBUTTONUP => {
use winit_core::event::ElementState::Released;
use winit_core::event::MouseButton::Left;
use winit_core::event::MouseButton;
use winit_core::event::WindowEvent::PointerButton;
unsafe { release_mouse(userdata.window_state_lock()) };
@@ -1756,106 +1758,20 @@ unsafe fn public_window_callback_inner(
primary: true,
state: Released,
position,
button: Left.into(),
});
result = ProcResult::Value(0);
},
WM_RBUTTONDOWN => {
use winit_core::event::ElementState::Pressed;
use winit_core::event::MouseButton::Right;
use winit_core::event::WindowEvent::PointerButton;
unsafe { capture_mouse(window, &mut userdata.window_state_lock()) };
update_modifiers(window, userdata);
let x = util::get_x_lparam(lparam as u32) as i32;
let y = util::get_y_lparam(lparam as u32) as i32;
let position = PhysicalPosition::new(x as f64, y as f64);
userdata.send_window_event(window, PointerButton {
device_id: None,
primary: true,
state: Pressed,
position,
button: Right.into(),
});
result = ProcResult::Value(0);
},
WM_RBUTTONUP => {
use winit_core::event::ElementState::Released;
use winit_core::event::MouseButton::Right;
use winit_core::event::WindowEvent::PointerButton;
unsafe { release_mouse(userdata.window_state_lock()) };
update_modifiers(window, userdata);
let x = util::get_x_lparam(lparam as u32) as i32;
let y = util::get_y_lparam(lparam as u32) as i32;
let position = PhysicalPosition::new(x as f64, y as f64);
userdata.send_window_event(window, PointerButton {
device_id: None,
primary: true,
state: Released,
position,
button: Right.into(),
});
result = ProcResult::Value(0);
},
WM_MBUTTONDOWN => {
use winit_core::event::ElementState::Pressed;
use winit_core::event::MouseButton::Middle;
use winit_core::event::WindowEvent::PointerButton;
unsafe { capture_mouse(window, &mut userdata.window_state_lock()) };
update_modifiers(window, userdata);
let x = util::get_x_lparam(lparam as u32) as i32;
let y = util::get_y_lparam(lparam as u32) as i32;
let position = PhysicalPosition::new(x as f64, y as f64);
userdata.send_window_event(window, PointerButton {
device_id: None,
primary: true,
state: Pressed,
position,
button: Middle.into(),
});
result = ProcResult::Value(0);
},
WM_MBUTTONUP => {
use winit_core::event::ElementState::Released;
use winit_core::event::MouseButton::Middle;
use winit_core::event::WindowEvent::PointerButton;
unsafe { release_mouse(userdata.window_state_lock()) };
update_modifiers(window, userdata);
let x = util::get_x_lparam(lparam as u32) as i32;
let y = util::get_y_lparam(lparam as u32) as i32;
let position = PhysicalPosition::new(x as f64, y as f64);
userdata.send_window_event(window, PointerButton {
device_id: None,
primary: true,
state: Released,
position,
button: Middle.into(),
button: match msg {
WM_LBUTTONUP => MouseButton::Left,
WM_RBUTTONUP => MouseButton::Right,
WM_MBUTTONUP => MouseButton::Middle,
_ => unreachable!(),
}
.into(),
});
result = ProcResult::Value(0);
},
WM_XBUTTONDOWN => {
use winit_core::event::ElementState::Pressed;
use winit_core::event::MouseButton::{Back, Forward, Other};
use winit_core::event::MouseButton;
use winit_core::event::WindowEvent::PointerButton;
let xbutton = util::get_xbutton_wparam(wparam as u32);
@@ -1867,25 +1783,25 @@ unsafe fn public_window_callback_inner(
let y = util::get_y_lparam(lparam as u32) as i32;
let position = PhysicalPosition::new(x as f64, y as f64);
// 1 is defined as back, 2 as forward; other codes are unexpected.
let b = xbutton as u8 + MouseButton::Back as u8 - 1;
userdata.send_window_event(window, PointerButton {
device_id: None,
primary: true,
state: Pressed,
position,
button: match xbutton {
1 => Back,
2 => Forward,
_ => Other(xbutton),
}
.into(),
// 1 is defined as back, 2 as forward; other codes are unexpected.
button: MouseButton::try_from_u8(b).unwrap().into(),
});
result = ProcResult::Value(0);
},
WM_XBUTTONUP => {
use winit_core::event::ElementState::Released;
use winit_core::event::MouseButton::{Back, Forward, Other};
use winit_core::event::MouseButton;
use winit_core::event::WindowEvent::PointerButton;
let xbutton = util::get_xbutton_wparam(wparam as u32);
unsafe { release_mouse(userdata.window_state_lock()) };
@@ -1896,17 +1812,16 @@ unsafe fn public_window_callback_inner(
let y = util::get_y_lparam(lparam as u32) as i32;
let position = PhysicalPosition::new(x as f64, y as f64);
// 1 is defined as back, 2 as forward; other codes are unexpected.
let b = xbutton as u8 + MouseButton::Back as u8 - 1;
userdata.send_window_event(window, PointerButton {
device_id: None,
primary: true,
state: Released,
position,
button: match xbutton {
1 => Back,
2 => Forward,
_ => Other(xbutton),
}
.into(),
// 1 is defined as back, 2 as forward; other codes are unexpected.
button: MouseButton::try_from_u8(b).unwrap().into(),
});
result = ProcResult::Value(0);
},
@@ -2085,22 +2000,6 @@ unsafe fn public_window_callback_inner(
continue;
}
let force = if let PT_TOUCH = pointer_info.pointerType {
let mut touch_info = mem::MaybeUninit::uninit();
util::GET_POINTER_TOUCH_INFO.and_then(|GetPointerTouchInfo| {
match unsafe {
GetPointerTouchInfo(pointer_info.pointerId, touch_info.as_mut_ptr())
} {
0 => None,
_ => normalize_pointer_pressure(unsafe {
touch_info.assume_init().pressure
}),
}
})
} else {
None
};
let x = location.x as f64 + x.fract();
let y = location.y as f64 + y.fract();
let position = PhysicalPosition::new(x, y);
@@ -2108,60 +2007,83 @@ unsafe fn public_window_callback_inner(
let finger_id = FingerId::from_raw(pointer_info.pointerId as usize);
let primary = util::has_flag(pointer_info.pointerFlags, POINTER_FLAG_PRIMARY);
if util::has_flag(pointer_info.pointerFlags, POINTER_FLAG_DOWN) {
userdata.send_window_event(window, WindowEvent::PointerEntered {
device_id: None,
primary,
position,
kind: if let PT_TOUCH = pointer_info.pointerType {
PointerKind::Touch(finger_id)
} else {
PointerKind::Unknown
let is_down = util::has_flag(pointer_info.pointerFlags, POINTER_FLAG_DOWN);
if is_down || util::has_flag(pointer_info.pointerFlags, POINTER_FLAG_UP) {
let (kind, button) = match pointer_info.pointerType {
PT_TOUCH => (PointerKind::Touch(finger_id), ButtonSource::Touch {
finger_id,
force: force_for_touch(pointer_info.pointerId),
}),
PT_PEN => {
let kind = PointerKind::TabletTool(TabletToolKind::Pen);
let (mut pen_flags, data) =
tablet_tool_info_for_pen(pointer_info.pointerId);
let old_pen_flags =
userdata.last_tablet_down_button_state.replace(pen_flags);
// For release, use a diff.
if !is_down {
pen_flags ^= old_pen_flags;
};
let button = ButtonSource::TabletTool {
kind: TabletToolKind::Pen,
button: pen_flags_to_button(pen_flags),
data,
};
(kind, button)
},
});
userdata.send_window_event(window, WindowEvent::PointerButton {
device_id: None,
primary,
state: Pressed,
position,
button: if let PT_TOUCH = pointer_info.pointerType {
ButtonSource::Touch { finger_id, force }
} else {
ButtonSource::Unknown(0)
},
});
} else if util::has_flag(pointer_info.pointerFlags, POINTER_FLAG_UP) {
userdata.send_window_event(window, WindowEvent::PointerButton {
device_id: None,
primary,
state: Released,
position,
button: if let PT_TOUCH = pointer_info.pointerType {
ButtonSource::Touch { finger_id, force }
} else {
ButtonSource::Unknown(0)
},
});
userdata.send_window_event(window, WindowEvent::PointerLeft {
device_id: None,
primary,
position: Some(position),
kind: if let PT_TOUCH = pointer_info.pointerType {
PointerKind::Touch(finger_id)
} else {
PointerKind::Unknown
},
});
_ => (PointerKind::Unknown, ButtonSource::Unknown(0)),
};
if is_down {
userdata.send_window_event(window, WindowEvent::PointerEntered {
device_id: None,
primary,
position,
kind,
});
userdata.send_window_event(window, WindowEvent::PointerButton {
device_id: None,
primary,
state: Pressed,
position,
button,
});
} else {
userdata.send_window_event(window, WindowEvent::PointerButton {
device_id: None,
primary,
state: Released,
position,
button,
});
userdata.send_window_event(window, WindowEvent::PointerLeft {
device_id: None,
primary,
position: Some(position),
kind,
});
}
} else if util::has_flag(pointer_info.pointerFlags, POINTER_FLAG_UPDATE) {
let source = match pointer_info.pointerType {
PT_TOUCH => PointerSource::Touch {
finger_id,
force: force_for_touch(pointer_info.pointerId),
},
PT_PEN => PointerSource::TabletTool {
kind: TabletToolKind::Pen,
data: tablet_tool_info_for_pen(pointer_info.pointerId).1,
},
_ => PointerSource::Unknown,
};
userdata.send_window_event(window, WindowEvent::PointerMoved {
device_id: None,
primary,
position,
source: if let PT_TOUCH = pointer_info.pointerType {
PointerSource::Touch { finger_id, force }
} else {
PointerSource::Unknown
},
source,
});
} else {
continue;
@@ -2209,11 +2131,7 @@ unsafe fn public_window_callback_inner(
// provided through the low-order word of lParam. We use that here since
// `WM_MOUSEMOVE` seems to come after `WM_SETCURSOR` for a given cursor movement.
let in_client_area = util::loword(lparam as u32) as u32 == HTCLIENT;
if in_client_area {
Some(window_state.mouse.selected_cursor.clone())
} else {
None
}
if in_client_area { Some(window_state.mouse.selected_cursor.clone()) } else { None }
};
match set_cursor_to {
@@ -2553,7 +2471,7 @@ unsafe fn handle_raw_input(userdata: &ThreadMsgTargetData, data: RAWINPUT) {
}
enum PointerMoveKind {
/// Pointer enterd to the window.
/// Pointer entered the window.
Enter,
/// Pointer leaved the window client area.
Leave,
@@ -2691,3 +2609,57 @@ fn apply_win10_dpi_adjustment(
conservative_rect
}
fn force_for_touch(pointer_id: u32) -> Option<Force> {
let mut touch_info = mem::MaybeUninit::uninit();
util::GET_POINTER_TOUCH_INFO.and_then(|GetPointerTouchInfo| {
match unsafe { GetPointerTouchInfo(pointer_id, touch_info.as_mut_ptr()) } {
0 => None,
_ => normalize_pointer_pressure(unsafe { touch_info.assume_init().pressure }),
}
})
}
// Information is stored on the same thing, so we don't save anything by
// splitting the functions.
fn tablet_tool_info_for_pen(pointer_id: u32) -> (u32, TabletToolData) {
let mut tool_data = TabletToolData::default();
let mut tool_button = 0;
let mut tablet_info = mem::MaybeUninit::uninit();
util::GET_POINTER_PEN_INFO.map(|GetPointerPenInfo| {
if unsafe { GetPointerPenInfo(pointer_id, tablet_info.as_mut_ptr()) } == 0 {
return;
}
let pen_info = unsafe { tablet_info.assume_init() };
if pen_info.penMask & PEN_MASK_PRESSURE != 0 {
tool_data.force = normalize_pointer_pressure(pen_info.pressure);
}
if pen_info.penMask & (PEN_MASK_TILT_X | PEN_MASK_TILT_Y) != 0 {
tool_data.tilt =
Some(TabletToolTilt { x: pen_info.tiltX as i8, y: pen_info.tiltY as i8 });
}
if pen_info.penMask & PEN_MASK_ROTATION != 0 {
tool_data.twist = Some(pen_info.rotation as u16);
}
tool_button = pen_info.penFlags;
});
(tool_button, tool_data)
}
// NOTE: According to firefox, the buttons while can be combined, in
// reality they are not.
fn pen_flags_to_button(flags: u32) -> TabletToolButton {
if flags & PEN_FLAG_BARREL != 0 {
TabletToolButton::Barrel
} else if flags & PEN_FLAG_ERASER != 0 {
// NOTE: this is likely not a correct thing to do, but route
// it that way for now.
TabletToolButton::Other(PEN_FLAG_ERASER as u16)
} else {
TabletToolButton::Contact
}
}

View File

@@ -14,7 +14,7 @@ use winit_core::event_loop::ActiveEventLoop as RootActiveEventLoop;
use winit_core::window::WindowId;
use super::{ActiveEventLoop, ControlFlow, EventLoopThreadExecutor};
use crate::event_loop::{WindowData, GWL_USERDATA};
use crate::event_loop::{GWL_USERDATA, WindowData};
use crate::util::get_window_long;
type EventHandler = Cell<Option<&'static mut (dyn ApplicationHandler + 'static)>>;

View File

@@ -5,14 +5,14 @@ use std::{fmt, io, mem, ptr};
use cursor_icon::CursorIcon;
use dpi::PhysicalSize;
use windows_sys::core::PCWSTR;
use windows_sys::Win32::Graphics::Gdi::{
CreateBitmap, CreateCompatibleBitmap, DeleteObject, GetDC, ReleaseDC, SetBitmapBits,
};
use windows_sys::Win32::UI::WindowsAndMessaging::{
CreateIcon, CreateIconIndirect, DestroyCursor, DestroyIcon, LoadImageW, HCURSOR, HICON,
ICONINFO, ICON_BIG, ICON_SMALL, IMAGE_ICON, LR_DEFAULTSIZE, LR_LOADFROMFILE,
CreateIcon, CreateIconIndirect, DestroyCursor, DestroyIcon, HCURSOR, HICON, ICON_BIG,
ICON_SMALL, ICONINFO, IMAGE_ICON, LR_DEFAULTSIZE, LR_LOADFROMFILE, LoadImageW,
};
use windows_sys::core::PCWSTR;
use winit_core::cursor::{CursorImage, CustomCursorProvider};
use winit_core::error::RequestError;
use winit_core::icon::*;

View File

@@ -1,14 +1,14 @@
use std::ffi::{c_void, OsString};
use std::ffi::{OsString, c_void};
use std::os::windows::prelude::OsStringExt;
use std::ptr::null_mut;
use dpi::{Position, Size};
use windows_sys::Win32::Foundation::{POINT, RECT};
use windows_sys::Win32::UI::Input::Ime::{
ImmAssociateContextEx, ImmGetCompositionStringW, ImmGetContext, ImmReleaseContext,
ImmSetCandidateWindow, ImmSetCompositionWindow, ATTR_TARGET_CONVERTED,
ATTR_TARGET_NOTCONVERTED, CANDIDATEFORM, CFS_EXCLUDE, CFS_POINT, COMPOSITIONFORM, GCS_COMPATTR,
GCS_COMPSTR, GCS_CURSORPOS, GCS_RESULTSTR, HIMC, IACE_CHILDREN, IACE_DEFAULT,
ATTR_TARGET_CONVERTED, ATTR_TARGET_NOTCONVERTED, CANDIDATEFORM, CFS_EXCLUDE, CFS_POINT,
COMPOSITIONFORM, GCS_COMPATTR, GCS_COMPSTR, GCS_CURSORPOS, GCS_RESULTSTR, HIMC, IACE_CHILDREN,
IACE_DEFAULT, ImmAssociateContextEx, ImmGetCompositionStringW, ImmGetContext,
ImmReleaseContext, ImmSetCandidateWindow, ImmSetCompositionWindow,
};
use windows_sys::Win32::UI::WindowsAndMessaging::{GetSystemMetrics, SM_IMMENABLED};

Some files were not shown because too many files have changed in this diff Show More