Compare commits
1 Commits
madsmtm/re
...
waker
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2a391b348a |
@@ -1,8 +1,8 @@
|
||||
name: iOS bug
|
||||
description: Create an iOS/UIKit-specific bug report
|
||||
description: Create an iOS-specific bug report
|
||||
labels:
|
||||
- B - bug
|
||||
- DS - uikit
|
||||
- DS - ios
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
@@ -1,8 +1,8 @@
|
||||
name: macOS bug
|
||||
name: MacOS bug
|
||||
description: Create a macOS-specific bug report
|
||||
labels:
|
||||
- B - bug
|
||||
- DS - appkit
|
||||
- DS - macos
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
@@ -2,7 +2,7 @@ name: Windows bug
|
||||
description: Create a Windows-specific bug report
|
||||
labels:
|
||||
- B - bug
|
||||
- DS - win32
|
||||
- DS - windows
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
32
.github/workflows/ci.yml
vendored
@@ -55,7 +55,7 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
toolchain: [stable, nightly, '1.85']
|
||||
toolchain: [stable, nightly, '1.80']
|
||||
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.85'
|
||||
- toolchain: '1.80'
|
||||
platform: { name: 'Android' }
|
||||
# Redox OS doesn't follow MSRV
|
||||
- toolchain: '1.85'
|
||||
- toolchain: '1.80'
|
||||
platform: { name: 'Redox OS' }
|
||||
include:
|
||||
- toolchain: '1.85'
|
||||
- toolchain: '1.80'
|
||||
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 }
|
||||
@@ -124,7 +124,7 @@ jobs:
|
||||
# the cache has been downloaded.
|
||||
#
|
||||
# This could be avoided if we added Cargo.lock to the repository.
|
||||
uses: actions/cache/restore@v5
|
||||
uses: actions/cache/restore@v4
|
||||
with:
|
||||
# https://doc.rust-lang.org/cargo/guide/cargo-home.html#caching-the-cargo-home-in-ci
|
||||
path: |
|
||||
@@ -136,7 +136,7 @@ jobs:
|
||||
|
||||
- name: Generate lockfile
|
||||
# Also updates the crates.io index
|
||||
run: cargo generate-lockfile && cargo update -p smol_str --precise 0.3.2 && cargo update -p unicode-segmentation --precise 1.12.0
|
||||
run: cargo generate-lockfile && cargo update -p ahash --precise 0.8.7 && cargo update -p bumpalo --precise 3.14.0
|
||||
|
||||
- name: Install GCC Multilib
|
||||
if: (matrix.platform.os == 'ubuntu-latest') && contains(matrix.platform.target, 'i686')
|
||||
@@ -145,7 +145,7 @@ jobs:
|
||||
- name: Cache cargo-apk
|
||||
if: contains(matrix.platform.target, 'android')
|
||||
id: cargo-apk-cache
|
||||
uses: actions/cache@v5
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cargo/bin/cargo-apk
|
||||
# Change this key if we update the required cargo-apk version
|
||||
@@ -160,7 +160,7 @@ jobs:
|
||||
if: contains(matrix.platform.target, 'android') && (steps.cargo-apk-cache.outputs.cache-hit != 'true')
|
||||
run: cargo install cargo-apk --version=^0.9.7 --locked
|
||||
|
||||
- uses: taiki-e/cache-cargo-install-action@v3
|
||||
- uses: taiki-e/cache-cargo-install-action@v2
|
||||
if: contains(matrix.platform.target, 'wasm32') && matrix.toolchain == 'nightly'
|
||||
with:
|
||||
tool: wasm-bindgen-cli
|
||||
@@ -230,19 +230,19 @@ jobs:
|
||||
- name: Test dpi crate
|
||||
if: >
|
||||
contains(matrix.platform.name, 'Linux 64bit') &&
|
||||
matrix.toolchain != '1.85'
|
||||
matrix.toolchain != '1.80'
|
||||
run: cargo test -p dpi
|
||||
|
||||
- name: Check dpi crate (no_std)
|
||||
if: >
|
||||
contains(matrix.platform.name, 'Linux 64bit') &&
|
||||
matrix.toolchain != '1.85'
|
||||
matrix.toolchain != '1.80'
|
||||
run: cargo check -p dpi --no-default-features
|
||||
|
||||
- name: Build tests
|
||||
if: >
|
||||
!contains(matrix.platform.target, 'redox') &&
|
||||
matrix.toolchain != '1.85'
|
||||
matrix.toolchain != '1.80'
|
||||
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.85'
|
||||
matrix.toolchain != '1.80'
|
||||
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.85'
|
||||
matrix.toolchain != '1.80'
|
||||
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.85'
|
||||
matrix.toolchain != '1.80'
|
||||
run: cargo $CMD test $OPTIONS $TEST_OPTIONS --features serde
|
||||
|
||||
- name: Check docs.rs documentation
|
||||
@@ -281,7 +281,7 @@ jobs:
|
||||
|
||||
# See restore step above
|
||||
- name: Save cache of cargo folder
|
||||
uses: actions/cache/save@v5
|
||||
uses: actions/cache/save@v4
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry/index/
|
||||
@@ -329,7 +329,7 @@ jobs:
|
||||
- name: Setup NPM
|
||||
run: npm install
|
||||
- name: Run ESLint
|
||||
run: npx eslint@9.38.0
|
||||
run: npx eslint
|
||||
|
||||
swc:
|
||||
name: Minimize JavaScript
|
||||
|
||||
2
.github/workflows/docs.yml
vendored
@@ -19,7 +19,7 @@ jobs:
|
||||
id-token: write
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@v5
|
||||
|
||||
- uses: dtolnay/rust-toolchain@master
|
||||
with:
|
||||
|
||||
57
Cargo.toml
@@ -4,26 +4,26 @@ members = ["dpi", "winit*"]
|
||||
resolver = "2"
|
||||
|
||||
[workspace.package]
|
||||
edition = "2024"
|
||||
edition = "2021"
|
||||
license = "Apache-2.0"
|
||||
repository = "https://github.com/rust-windowing/winit"
|
||||
rust-version = "1.85"
|
||||
version = "0.31.0-beta.2"
|
||||
rust-version = "1.80"
|
||||
version = "0.30.12"
|
||||
|
||||
[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.31.0-beta.2", path = "winit-android" }
|
||||
winit-appkit = { version = "=0.31.0-beta.2", path = "winit-appkit" }
|
||||
winit-common = { version = "=0.31.0-beta.2", path = "winit-common" }
|
||||
winit-core = { version = "=0.31.0-beta.2", path = "winit-core" }
|
||||
winit-orbital = { version = "=0.31.0-beta.2", path = "winit-orbital" }
|
||||
winit-uikit = { version = "=0.31.0-beta.2", path = "winit-uikit" }
|
||||
winit-wayland = { version = "=0.31.0-beta.2", path = "winit-wayland", default-features = false }
|
||||
winit-web = { version = "=0.31.0-beta.2", path = "winit-web" }
|
||||
winit-win32 = { version = "=0.31.0-beta.2", path = "winit-win32" }
|
||||
winit-x11 = { version = "=0.31.0-beta.2", path = "winit-x11" }
|
||||
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" }
|
||||
|
||||
# Core dependencies.
|
||||
bitflags = "2"
|
||||
@@ -39,7 +39,7 @@ tracing = { version = "0.1.40", default-features = false }
|
||||
|
||||
# Dev dependencies.
|
||||
image = { version = "0.25.0", default-features = false }
|
||||
softbuffer = { version = "0.4.8", default-features = false, features = [
|
||||
softbuffer = { version = "0.4.6", default-features = false, features = [
|
||||
"x11",
|
||||
"x11-dlopen",
|
||||
"wayland",
|
||||
@@ -55,33 +55,40 @@ 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.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 }
|
||||
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 }
|
||||
|
||||
# Windows dependencies.
|
||||
unicode-segmentation = "1.7.1"
|
||||
windows-sys = "0.61"
|
||||
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.14.3"
|
||||
foldhash = { version = "0.2.0", default-features = false, features = ["std"] }
|
||||
calloop = "0.13.0"
|
||||
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"
|
||||
|
||||
# Orbital dependencies.
|
||||
libredox = "0.1.12"
|
||||
orbclient = { version = "0.3.47", default-features = false }
|
||||
redox_event = { package = "redox_event", version = "0.4.5" }
|
||||
redox_syscall = "0.5.7"
|
||||
|
||||
# Web dependencies.
|
||||
atomic-waker = "1"
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
winit = "0.31.0-beta.2"
|
||||
winit = "0.30.12"
|
||||
```
|
||||
|
||||
## [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.85**. Changes to
|
||||
This crate's Minimum Supported Rust Version (MSRV) is **1.80**. 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
|
||||
|
||||
10
clippy.toml
@@ -1,11 +1,4 @@
|
||||
# Using allow-invalid because this is platform-specific code
|
||||
disallowed-macros = [
|
||||
{ path = "std::print", reason = "works badly on web", replacement = "tracing::info" },
|
||||
{ path = "std::println", reason = "works badly on web", replacement = "tracing::info" },
|
||||
{ path = "std::eprint", reason = "works badly on web", replacement = "tracing::error" },
|
||||
{ path = "std::eprintln", reason = "works badly on web", replacement = "tracing::error" },
|
||||
{ path = "std::dbg", reason = "leftover debugging aid, remove it or use tracing" },
|
||||
]
|
||||
disallowed-methods = [
|
||||
{ allow-invalid = true, path = "objc2_app_kit::NSView::visibleRect", reason = "We expose a render target to the user, and visibility is not really relevant to that (and can break if you don't use the rectangle position as well). Use `frame` instead." },
|
||||
{ allow-invalid = true, path = "objc2_app_kit::NSWindow::setFrameTopLeftPoint", reason = "Not sufficient when working with Winit's coordinate system, use `flip_window_screen_coordinates` instead" },
|
||||
@@ -17,9 +10,6 @@ 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" },
|
||||
|
||||
12
deny.toml
@@ -32,7 +32,6 @@ allow = [
|
||||
"ISC", # https://tldrlegal.com/license/isc-license
|
||||
"MIT", # https://tldrlegal.com/license/mit-license
|
||||
"Unicode-3.0", # https://spdx.org/licenses/Unicode-3.0.html
|
||||
"Zlib", # https://spdx.org/licenses/Zlib.html
|
||||
]
|
||||
confidence-threshold = 1.0
|
||||
private = { ignore = true }
|
||||
@@ -43,9 +42,6 @@ skip = [
|
||||
{ crate = "bitflags@1", reason = "the ecosystem is in the process of migrating" },
|
||||
{ crate = "rustix@0.38", reason = "the ecosystem is in the process of migrating" },
|
||||
{ crate = "linux-raw-sys@0.4", reason = "the ecosystem is in the process of migrating" },
|
||||
{ crate = "jni-sys@0.3", reason = "uses the semver trick to depend on v0.4, but `ndk` hasn't been updated to v0.4 yet" },
|
||||
{ crate = "thiserror@1.0", reason = "dep of `ndk` crate, yet to be updated" },
|
||||
{ crate = "thiserror-impl@1.0", reason = "dep of `thiserror`" },
|
||||
]
|
||||
wildcards = "allow" # at least until https://github.com/EmbarkStudios/cargo-deny/issues/241 is fixed
|
||||
|
||||
@@ -54,17 +50,15 @@ include-archives = true
|
||||
interpreted = "deny"
|
||||
|
||||
[[bans.build.bypass]]
|
||||
allow-globs = ["android-games-sdk/import-games-sdk.sh"]
|
||||
allow = [
|
||||
{ path = "generate-bindings.sh", checksum = "268ec23248218d779e33853cdc60e2985e70214ff004716cd734270de1f6b561" },
|
||||
]
|
||||
crate = "android-activity"
|
||||
|
||||
[[bans.build.bypass]]
|
||||
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"
|
||||
|
||||
236
dpi/src/lib.rs
@@ -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_cfg), doc(auto_cfg(hide(doc, docsrs))))]
|
||||
#![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg_hide), doc(cfg_hide(doc, docsrs)))]
|
||||
#![cfg_attr(feature = "std", forbid(unsafe_code))]
|
||||
#![no_std]
|
||||
|
||||
@@ -84,18 +84,36 @@ pub trait Pixel: Copy + Into<f64> {
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! pixel_int_impl {
|
||||
($($t:ty),*) => {$(
|
||||
impl Pixel for $t {
|
||||
fn from_f64(f: f64) -> Self {
|
||||
round(f) as $t
|
||||
}
|
||||
}
|
||||
)*}
|
||||
impl Pixel for u8 {
|
||||
fn from_f64(f: f64) -> Self {
|
||||
round(f) as u8
|
||||
}
|
||||
}
|
||||
impl Pixel for u16 {
|
||||
fn from_f64(f: f64) -> Self {
|
||||
round(f) as u16
|
||||
}
|
||||
}
|
||||
impl Pixel for u32 {
|
||||
fn from_f64(f: f64) -> Self {
|
||||
round(f) as u32
|
||||
}
|
||||
}
|
||||
impl Pixel for i8 {
|
||||
fn from_f64(f: f64) -> Self {
|
||||
round(f) as i8
|
||||
}
|
||||
}
|
||||
impl Pixel for i16 {
|
||||
fn from_f64(f: f64) -> Self {
|
||||
round(f) as i16
|
||||
}
|
||||
}
|
||||
impl Pixel for i32 {
|
||||
fn from_f64(f: f64) -> Self {
|
||||
round(f) as i32
|
||||
}
|
||||
}
|
||||
|
||||
pixel_int_impl!(u8, u16, u32, i8, i16, i32);
|
||||
|
||||
impl Pixel for f32 {
|
||||
fn from_f64(f: f64) -> Self {
|
||||
f as f32
|
||||
@@ -360,48 +378,6 @@ impl<P: Pixel> From<LogicalUnit<P>> for PixelUnit {
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! vec2_from_impls {
|
||||
($t:ident, $a:ident, $b:ident, $mint_ty:ident) => {
|
||||
impl<P: Pixel, X: Pixel> From<(X, X)> for $t<P> {
|
||||
fn from(($a, $b): (X, X)) -> Self {
|
||||
Self::new($a.cast(), $b.cast())
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel, X: Pixel> From<$t<P>> for (X, X) {
|
||||
fn from(p: $t<P>) -> Self {
|
||||
(p.$a.cast(), p.$b.cast())
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel, X: Pixel> From<[X; 2]> for $t<P> {
|
||||
fn from([$a, $b]: [X; 2]) -> Self {
|
||||
Self::new($a.cast(), $b.cast())
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel, X: Pixel> From<$t<P>> for [X; 2] {
|
||||
fn from(p: $t<P>) -> Self {
|
||||
[p.$a.cast(), p.$b.cast()]
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "mint")]
|
||||
impl<P: Pixel> From<mint::$mint_ty<P>> for $t<P> {
|
||||
fn from(p: mint::$mint_ty<P>) -> Self {
|
||||
Self::new(p.x, p.y)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "mint")]
|
||||
impl<P: Pixel> From<$t<P>> for mint::$mint_ty<P> {
|
||||
fn from(p: $t<P>) -> Self {
|
||||
Self { x: p.$a, y: p.$b }
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// A position represented in logical pixels.
|
||||
///
|
||||
/// The position is stored as floats, so please be careful. Casting floats to integers truncates the
|
||||
@@ -444,7 +420,43 @@ impl<P: Pixel> LogicalPosition<P> {
|
||||
}
|
||||
}
|
||||
|
||||
vec2_from_impls!(LogicalPosition, x, y, Point2);
|
||||
impl<P: Pixel, X: Pixel> From<(X, X)> for LogicalPosition<P> {
|
||||
fn from((x, y): (X, X)) -> LogicalPosition<P> {
|
||||
LogicalPosition::new(x.cast(), y.cast())
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel, X: Pixel> From<LogicalPosition<P>> for (X, X) {
|
||||
fn from(p: LogicalPosition<P>) -> (X, X) {
|
||||
(p.x.cast(), p.y.cast())
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel, X: Pixel> From<[X; 2]> for LogicalPosition<P> {
|
||||
fn from([x, y]: [X; 2]) -> LogicalPosition<P> {
|
||||
LogicalPosition::new(x.cast(), y.cast())
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel, X: Pixel> From<LogicalPosition<P>> for [X; 2] {
|
||||
fn from(p: LogicalPosition<P>) -> [X; 2] {
|
||||
[p.x.cast(), p.y.cast()]
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "mint")]
|
||||
impl<P: Pixel> From<mint::Point2<P>> for LogicalPosition<P> {
|
||||
fn from(p: mint::Point2<P>) -> Self {
|
||||
Self::new(p.x, p.y)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "mint")]
|
||||
impl<P: Pixel> From<LogicalPosition<P>> for mint::Point2<P> {
|
||||
fn from(p: LogicalPosition<P>) -> Self {
|
||||
mint::Point2 { x: p.x, y: p.y }
|
||||
}
|
||||
}
|
||||
|
||||
/// A position represented in physical pixels.
|
||||
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Default, Hash)]
|
||||
@@ -484,7 +496,43 @@ impl<P: Pixel> PhysicalPosition<P> {
|
||||
}
|
||||
}
|
||||
|
||||
vec2_from_impls!(PhysicalPosition, x, y, Point2);
|
||||
impl<P: Pixel, X: Pixel> From<(X, X)> for PhysicalPosition<P> {
|
||||
fn from((x, y): (X, X)) -> PhysicalPosition<P> {
|
||||
PhysicalPosition::new(x.cast(), y.cast())
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel, X: Pixel> From<PhysicalPosition<P>> for (X, X) {
|
||||
fn from(p: PhysicalPosition<P>) -> (X, X) {
|
||||
(p.x.cast(), p.y.cast())
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel, X: Pixel> From<[X; 2]> for PhysicalPosition<P> {
|
||||
fn from([x, y]: [X; 2]) -> PhysicalPosition<P> {
|
||||
PhysicalPosition::new(x.cast(), y.cast())
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel, X: Pixel> From<PhysicalPosition<P>> for [X; 2] {
|
||||
fn from(p: PhysicalPosition<P>) -> [X; 2] {
|
||||
[p.x.cast(), p.y.cast()]
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "mint")]
|
||||
impl<P: Pixel> From<mint::Point2<P>> for PhysicalPosition<P> {
|
||||
fn from(p: mint::Point2<P>) -> Self {
|
||||
Self::new(p.x, p.y)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "mint")]
|
||||
impl<P: Pixel> From<PhysicalPosition<P>> for mint::Point2<P> {
|
||||
fn from(p: PhysicalPosition<P>) -> Self {
|
||||
mint::Point2 { x: p.x, y: p.y }
|
||||
}
|
||||
}
|
||||
|
||||
/// A size represented in logical pixels.
|
||||
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Default, Hash)]
|
||||
@@ -524,7 +572,43 @@ impl<P: Pixel> LogicalSize<P> {
|
||||
}
|
||||
}
|
||||
|
||||
vec2_from_impls!(LogicalSize, width, height, Vector2);
|
||||
impl<P: Pixel, X: Pixel> From<(X, X)> for LogicalSize<P> {
|
||||
fn from((x, y): (X, X)) -> LogicalSize<P> {
|
||||
LogicalSize::new(x.cast(), y.cast())
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel, X: Pixel> From<LogicalSize<P>> for (X, X) {
|
||||
fn from(s: LogicalSize<P>) -> (X, X) {
|
||||
(s.width.cast(), s.height.cast())
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel, X: Pixel> From<[X; 2]> for LogicalSize<P> {
|
||||
fn from([x, y]: [X; 2]) -> LogicalSize<P> {
|
||||
LogicalSize::new(x.cast(), y.cast())
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel, X: Pixel> From<LogicalSize<P>> for [X; 2] {
|
||||
fn from(s: LogicalSize<P>) -> [X; 2] {
|
||||
[s.width.cast(), s.height.cast()]
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "mint")]
|
||||
impl<P: Pixel> From<mint::Vector2<P>> for LogicalSize<P> {
|
||||
fn from(v: mint::Vector2<P>) -> Self {
|
||||
Self::new(v.x, v.y)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "mint")]
|
||||
impl<P: Pixel> From<LogicalSize<P>> for mint::Vector2<P> {
|
||||
fn from(s: LogicalSize<P>) -> Self {
|
||||
mint::Vector2 { x: s.width, y: s.height }
|
||||
}
|
||||
}
|
||||
|
||||
/// A size represented in physical pixels.
|
||||
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Default, Hash)]
|
||||
@@ -561,7 +645,43 @@ impl<P: Pixel> PhysicalSize<P> {
|
||||
}
|
||||
}
|
||||
|
||||
vec2_from_impls!(PhysicalSize, width, height, Vector2);
|
||||
impl<P: Pixel, X: Pixel> From<(X, X)> for PhysicalSize<P> {
|
||||
fn from((x, y): (X, X)) -> PhysicalSize<P> {
|
||||
PhysicalSize::new(x.cast(), y.cast())
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel, X: Pixel> From<PhysicalSize<P>> for (X, X) {
|
||||
fn from(s: PhysicalSize<P>) -> (X, X) {
|
||||
(s.width.cast(), s.height.cast())
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel, X: Pixel> From<[X; 2]> for PhysicalSize<P> {
|
||||
fn from([x, y]: [X; 2]) -> PhysicalSize<P> {
|
||||
PhysicalSize::new(x.cast(), y.cast())
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Pixel, X: Pixel> From<PhysicalSize<P>> for [X; 2] {
|
||||
fn from(s: PhysicalSize<P>) -> [X; 2] {
|
||||
[s.width.cast(), s.height.cast()]
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "mint")]
|
||||
impl<P: Pixel> From<mint::Vector2<P>> for PhysicalSize<P> {
|
||||
fn from(v: mint::Vector2<P>) -> Self {
|
||||
Self::new(v.x, v.y)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "mint")]
|
||||
impl<P: Pixel> From<PhysicalSize<P>> for mint::Vector2<P> {
|
||||
fn from(s: PhysicalSize<P>) -> Self {
|
||||
mint::Vector2 { x: s.width, y: s.height }
|
||||
}
|
||||
}
|
||||
|
||||
/// A size that's either physical or logical.
|
||||
#[derive(Debug, Copy, Clone, PartialEq)]
|
||||
|
||||
@@ -1,69 +1,72 @@
|
||||
//! Simple winit application.
|
||||
//!
|
||||
//! Note that a real application accepting text input **should** support
|
||||
//! the IME interface. See the `ime` example.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
use std::error::Error;
|
||||
use std::fmt::Debug;
|
||||
#[cfg(not(android_platform))]
|
||||
use std::num::NonZeroU32;
|
||||
use std::sync::Arc;
|
||||
use std::sync::mpsc::{self, Receiver, Sender};
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
use std::sync::Arc;
|
||||
#[cfg(all(not(android_platform), not(web_platform)))]
|
||||
use std::time::Instant;
|
||||
use std::{fmt, mem};
|
||||
use std::{cmp, fmt, mem};
|
||||
|
||||
use ::tracing::{error, info};
|
||||
use cursor_icon::CursorIcon;
|
||||
use dpi::LogicalPosition;
|
||||
#[cfg(not(android_platform))]
|
||||
use rwh_06::{DisplayHandle, HasDisplayHandle};
|
||||
#[cfg(not(android_platform))]
|
||||
use softbuffer::{Context, Surface};
|
||||
use tracing::{error, info};
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[cfg(all(web_platform, not(android_platform)))]
|
||||
use web_time::Instant;
|
||||
use winit::application::ApplicationHandler;
|
||||
use winit::cursor::{Cursor, CustomCursor, CustomCursorSource};
|
||||
use winit::dpi::{LogicalSize, PhysicalPosition, PhysicalSize};
|
||||
use winit::error::RequestError;
|
||||
use winit::event::{DeviceEvent, DeviceId, MouseButton, MouseScrollDelta, WindowEvent};
|
||||
use winit::event::{DeviceEvent, DeviceId, Ime, MouseButton, MouseScrollDelta, WindowEvent};
|
||||
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
||||
use winit::icon::{Icon, RgbaIcon};
|
||||
use winit::keyboard::{Key, ModifiersState};
|
||||
use winit::monitor::Fullscreen;
|
||||
#[cfg(all(target_vendor = "apple", not(target_os = "macos")))]
|
||||
use winit::platform::ios::WindowExtIOS;
|
||||
#[cfg(target_os = "macos")]
|
||||
#[cfg(macos_platform)]
|
||||
use winit::platform::macos::{OptionAsAlt, WindowAttributesMacOS, WindowExtMacOS};
|
||||
#[cfg(any(x11_platform, wayland_platform))]
|
||||
use winit::platform::startup_notify::{self, EventLoopExtStartupNotify, WindowExtStartupNotify};
|
||||
#[cfg(wayland_platform)]
|
||||
use winit::platform::wayland::{ActiveEventLoopExtWayland, WindowAttributesWayland};
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[cfg(web_platform)]
|
||||
use winit::platform::web::{ActiveEventLoopExtWeb, WindowAttributesWeb};
|
||||
#[cfg(x11_platform)]
|
||||
use winit::platform::x11::{ActiveEventLoopExtX11, WindowAttributesX11};
|
||||
use winit::window::{CursorGrabMode, ResizeDirection, Theme, Window, WindowAttributes, WindowId};
|
||||
use winit::window::{
|
||||
CursorGrabMode, ImeCapabilities, ImeEnableRequest, ImePurpose, ImeRequestData,
|
||||
ImeSurroundingText, ResizeDirection, Theme, Window, WindowAttributes, WindowId,
|
||||
};
|
||||
use winit_core::application::macos::ApplicationHandlerExtMacOS;
|
||||
use winit_core::window::ImeRequest;
|
||||
|
||||
#[path = "util/tracing.rs"]
|
||||
mod tracing_init;
|
||||
mod tracing;
|
||||
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
|
||||
/// The amount of points to around the window for drag resize direction calculations.
|
||||
const BORDER_SIZE: f64 = 20.;
|
||||
const IME_CURSOR_SIZE: PhysicalSize<u32> = PhysicalSize::new(20, 20);
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[cfg(web_platform)]
|
||||
console_error_panic_hook::set_once();
|
||||
|
||||
tracing_init::init();
|
||||
tracing::init();
|
||||
|
||||
let event_loop = EventLoop::new()?;
|
||||
let (sender, receiver) = mpsc::channel();
|
||||
|
||||
// Wire the user event from another thread.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
#[cfg(not(web_platform))]
|
||||
{
|
||||
let event_loop_proxy = event_loop.create_proxy();
|
||||
let sender = sender.clone();
|
||||
@@ -96,12 +99,14 @@ struct Application {
|
||||
/// Drawing context.
|
||||
///
|
||||
/// With OpenGL it could be EGLDisplay.
|
||||
#[cfg(not(android_platform))]
|
||||
context: Option<Context<DisplayHandle<'static>>>,
|
||||
}
|
||||
|
||||
impl Application {
|
||||
fn new(event_loop: &EventLoop, receiver: Receiver<Action>, sender: Sender<Action>) -> Self {
|
||||
// SAFETY: we drop the context right before the event loop is stopped, thus making it safe.
|
||||
#[cfg(not(android_platform))]
|
||||
let context = Some(
|
||||
Context::new(unsafe {
|
||||
std::mem::transmute::<DisplayHandle<'_>, DisplayHandle<'static>>(
|
||||
@@ -127,7 +132,15 @@ impl Application {
|
||||
.into_iter()
|
||||
.collect();
|
||||
|
||||
Self { receiver, sender, context, custom_cursors, icon, windows: Default::default() }
|
||||
Self {
|
||||
receiver,
|
||||
sender,
|
||||
#[cfg(not(android_platform))]
|
||||
context,
|
||||
custom_cursors,
|
||||
icon,
|
||||
windows: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn create_window(
|
||||
@@ -145,68 +158,34 @@ impl Application {
|
||||
|
||||
#[cfg(x11_platform)]
|
||||
if event_loop.is_x11() {
|
||||
let mut attrs = WindowAttributesX11::default();
|
||||
|
||||
if let Some(token) = event_loop.read_token_from_env() {
|
||||
startup_notify::reset_activation_token_env();
|
||||
info!("Using token {:?} to activate a window", token);
|
||||
attrs = attrs.with_activation_token(token);
|
||||
}
|
||||
|
||||
match std::env::var("X11_VISUAL_ID") {
|
||||
Ok(visual_id_str) => {
|
||||
info!("Using X11 visual id {visual_id_str}");
|
||||
let visual_id = visual_id_str.parse().expect("invalid X11_VISUAL_ID");
|
||||
attrs = attrs.with_x11_visual(visual_id);
|
||||
},
|
||||
Err(_) => {
|
||||
info!("Set the X11_VISUAL_ID env var to request specific X11 visual")
|
||||
},
|
||||
}
|
||||
|
||||
match std::env::var("X11_SCREEN_ID") {
|
||||
Ok(screen_id_str) => {
|
||||
info!("Placing the window on X11 screen {screen_id_str}");
|
||||
let screen_id = screen_id_str.parse().expect("invalid X11_SCREEN_ID");
|
||||
attrs = attrs.with_x11_screen(screen_id);
|
||||
},
|
||||
Err(_) => {
|
||||
info!("Set the X11_SCREEN_ID env var to place the window on non-default screen")
|
||||
},
|
||||
}
|
||||
|
||||
window_attributes = window_attributes.with_platform_attributes(Box::new(attrs));
|
||||
window_attributes = window_attributes
|
||||
.with_platform_attributes(Box::new(window_attributes_x11(event_loop)?));
|
||||
}
|
||||
|
||||
#[cfg(wayland_platform)]
|
||||
if event_loop.is_wayland() {
|
||||
let mut attrs = WindowAttributesWayland::default();
|
||||
|
||||
if let Some(token) = event_loop.read_token_from_env() {
|
||||
startup_notify::reset_activation_token_env();
|
||||
info!("Using token {:?} to activate a window", token);
|
||||
attrs = attrs.with_activation_token(token);
|
||||
}
|
||||
|
||||
window_attributes = window_attributes.with_platform_attributes(Box::new(attrs));
|
||||
window_attributes = window_attributes
|
||||
.with_platform_attributes(Box::new(window_attributes_wayland(event_loop)));
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[cfg(macos_platform)]
|
||||
if let Some(tab_id) = _tab_id {
|
||||
let attrs = WindowAttributesMacOS::default().with_tabbing_identifier(&tab_id);
|
||||
window_attributes = window_attributes.with_platform_attributes(Box::new(attrs));
|
||||
let window_attributes_macos =
|
||||
Box::new(WindowAttributesMacOS::default().with_tabbing_identifier(&tab_id));
|
||||
window_attributes = window_attributes.with_platform_attributes(window_attributes_macos);
|
||||
}
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[cfg(web_platform)]
|
||||
{
|
||||
let attrs = WindowAttributesWeb::default().with_append(true);
|
||||
window_attributes = window_attributes.with_platform_attributes(Box::new(attrs));
|
||||
window_attributes =
|
||||
window_attributes.with_platform_attributes(Box::new(window_attributes_web()));
|
||||
}
|
||||
|
||||
let window = event_loop.create_window(window_attributes)?;
|
||||
|
||||
#[cfg(all(target_vendor = "apple", not(target_os = "macos")))]
|
||||
#[cfg(ios_platform)]
|
||||
{
|
||||
use winit::platform::ios::WindowExtIOS;
|
||||
window.recognize_doubletap_gesture(true);
|
||||
window.recognize_pinch_gesture(true);
|
||||
window.recognize_rotation_gesture(true);
|
||||
@@ -222,19 +201,10 @@ impl Application {
|
||||
|
||||
fn handle_action_from_proxy(&mut self, _event_loop: &dyn ActiveEventLoop, action: Action) {
|
||||
match action {
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[cfg(web_platform)]
|
||||
Action::DumpMonitors => self.dump_monitors(_event_loop),
|
||||
Action::Message => {
|
||||
info!("User wake up");
|
||||
for (id, window) in self.windows.iter() {
|
||||
if window.emit_surface_size {
|
||||
let size = window.window.surface_size();
|
||||
info!(
|
||||
"Window {id:?} has physical surface size {}x{}",
|
||||
size.width, size.height
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
_ => unreachable!("Tried to execute invalid action without `WindowId`"),
|
||||
}
|
||||
@@ -270,17 +240,12 @@ impl Application {
|
||||
Action::ToggleResizable => window.toggle_resizable(),
|
||||
Action::ToggleDecorations => window.toggle_decorations(),
|
||||
Action::ToggleFullscreen => window.toggle_fullscreen(),
|
||||
#[cfg(target_os = "macos")]
|
||||
#[cfg(macos_platform)]
|
||||
Action::ToggleSimpleFullscreen => {
|
||||
window.window.set_simple_fullscreen(!window.window.simple_fullscreen());
|
||||
},
|
||||
#[cfg(target_os = "macos")]
|
||||
Action::ToggleBorderlessGame => {
|
||||
let current = window.window.is_borderless_game();
|
||||
window.window.set_borderless_game(!current);
|
||||
info!("Borderless game: {}", !current);
|
||||
},
|
||||
Action::ToggleMaximize => window.toggle_maximize(),
|
||||
Action::ToggleImeInput => window.toggle_ime(),
|
||||
Action::Minimize => window.minimize(),
|
||||
Action::NextCursor => window.next_cursor(),
|
||||
Action::NextCustomCursor => {
|
||||
@@ -289,13 +254,13 @@ impl Application {
|
||||
error!("Error creating custom cursor: {err}");
|
||||
}
|
||||
},
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[cfg(web_platform)]
|
||||
Action::UrlCustomCursor => {
|
||||
if let Err(err) = window.url_custom_cursor(event_loop) {
|
||||
error!("Error creating custom cursor from URL: {err}");
|
||||
}
|
||||
},
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[cfg(web_platform)]
|
||||
Action::AnimationCustomCursor => {
|
||||
if let Err(err) = self
|
||||
.custom_cursors
|
||||
@@ -310,7 +275,7 @@ impl Application {
|
||||
Action::DragResizeWindow => window.drag_resize_window(),
|
||||
Action::ShowWindowMenu => window.show_menu(),
|
||||
Action::PrintHelp => self.print_help(),
|
||||
#[cfg(target_os = "macos")]
|
||||
#[cfg(macos_platform)]
|
||||
Action::CycleOptionAsAlt => window.cycle_option_as_alt(),
|
||||
Action::SetTheme(theme) => {
|
||||
window.window.set_theme(theme);
|
||||
@@ -318,7 +283,7 @@ impl Application {
|
||||
let actual_theme = theme.or_else(|| window.window.theme()).unwrap_or(Theme::Dark);
|
||||
window.set_draw_theme(actual_theme);
|
||||
},
|
||||
#[cfg(target_os = "macos")]
|
||||
#[cfg(macos_platform)]
|
||||
Action::CreateNewTab => {
|
||||
let tab_id = window.window.tabbing_identifier();
|
||||
if let Err(err) = self.create_window(event_loop, Some(tab_id)) {
|
||||
@@ -326,7 +291,7 @@ impl Application {
|
||||
}
|
||||
},
|
||||
Action::RequestResize => window.swap_dimensions(),
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[cfg(web_platform)]
|
||||
Action::DumpMonitors => {
|
||||
let future = event_loop.request_detailed_monitor_permission();
|
||||
let proxy = event_loop.create_proxy();
|
||||
@@ -340,7 +305,7 @@ impl Application {
|
||||
proxy.wake_up();
|
||||
});
|
||||
},
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
#[cfg(not(web_platform))]
|
||||
Action::DumpMonitors => self.dump_monitors(event_loop),
|
||||
Action::Message => {
|
||||
self.sender.send(Action::Message).unwrap();
|
||||
@@ -353,9 +318,6 @@ impl Application {
|
||||
window.continuous_redraw = !window.continuous_redraw;
|
||||
window.window.request_redraw();
|
||||
},
|
||||
Action::EmitSurfaceSize => {
|
||||
window.toggle_emit_surface_size();
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -527,9 +489,8 @@ impl ApplicationHandler for Application {
|
||||
let mods = window.modifiers;
|
||||
if let Some(action) = state
|
||||
.is_pressed()
|
||||
.then(|| button.mouse_button())
|
||||
.then(|| Self::process_mouse_binding(button.mouse_button(), &mods))
|
||||
.flatten()
|
||||
.and_then(|button| Self::process_mouse_binding(button, &mods))
|
||||
{
|
||||
self.handle_action_with_window(event_loop, window_id, action);
|
||||
}
|
||||
@@ -551,6 +512,41 @@ impl ApplicationHandler for Application {
|
||||
}
|
||||
}
|
||||
},
|
||||
WindowEvent::Ime(event) => match event {
|
||||
Ime::Enabled => info!("IME enabled for Window={window_id:?}"),
|
||||
Ime::Preedit(text, caret_pos) => {
|
||||
info!("Preedit: {}, with caret at {:?}", text, caret_pos);
|
||||
},
|
||||
Ime::Commit(text) => {
|
||||
window.text_field_contents.0.push_str(&text);
|
||||
window.text_field_contents.1 += text.len();
|
||||
|
||||
info!("Committed: {}", text);
|
||||
let request_data = window.get_ime_update();
|
||||
window.window.request_ime_update(ImeRequest::Update(request_data)).unwrap();
|
||||
},
|
||||
Ime::DeleteSurrounding { before_bytes, after_bytes } => {
|
||||
let (text, cursor) = &window.text_field_contents;
|
||||
|
||||
// To anyone copying this, keep in mind that this doesn't take text selection
|
||||
// into account. The deletion happens *around* the pre-edit,
|
||||
// and may remove the whole selection or a part of it.
|
||||
let delete_start = cursor.saturating_sub(before_bytes);
|
||||
let delete_end = cmp::min(cursor.saturating_add(after_bytes), text.len());
|
||||
if text.is_char_boundary(delete_start) && text.is_char_boundary(delete_end) {
|
||||
let new_text = {
|
||||
let mut t = String::from(&text[..delete_start]);
|
||||
t.push_str(&text[delete_end..]);
|
||||
t
|
||||
};
|
||||
window.text_field_contents = (new_text, delete_start);
|
||||
info!("IME deleted bytes: {before_bytes}, {after_bytes}");
|
||||
} else {
|
||||
error!("Buggy IME tried to delete with indices not on char boundary.");
|
||||
}
|
||||
},
|
||||
Ime::Disabled => info!("IME disabled for Window={window_id:?}"),
|
||||
},
|
||||
WindowEvent::PinchGesture { delta, .. } => {
|
||||
window.zoom += delta;
|
||||
let zoom = window.zoom;
|
||||
@@ -585,7 +581,6 @@ impl ApplicationHandler for Application {
|
||||
| WindowEvent::DragMoved { .. }
|
||||
| WindowEvent::DragDropped { .. }
|
||||
| WindowEvent::Destroyed
|
||||
| WindowEvent::Ime(_)
|
||||
| WindowEvent::Moved(_) => (),
|
||||
}
|
||||
}
|
||||
@@ -640,9 +635,14 @@ impl ApplicationHandlerExtMacOS for Application {
|
||||
|
||||
/// State of the window.
|
||||
struct WindowState {
|
||||
ime_enabled: bool,
|
||||
/// The contents of the emulated text field for IME purposes (not displayed).
|
||||
/// (text, cursor position in bytes).
|
||||
text_field_contents: (String, usize),
|
||||
/// Render surface.
|
||||
///
|
||||
/// NOTE: This surface must be dropped before the `Window`.
|
||||
#[cfg(not(android_platform))]
|
||||
surface: Surface<DisplayHandle<'static>, Arc<dyn Window>>,
|
||||
/// The actual winit Window.
|
||||
window: Arc<dyn Window>,
|
||||
@@ -651,11 +651,10 @@ struct WindowState {
|
||||
/// Fill the window with animated color
|
||||
animated_fill_color: bool,
|
||||
/// The application start time. Used for color fill animation
|
||||
#[cfg(not(android_platform))]
|
||||
start_time: Instant,
|
||||
/// Redraw continuously
|
||||
continuous_redraw: bool,
|
||||
/// Periodically emit the surface size
|
||||
emit_surface_size: bool,
|
||||
/// Cursor position over the window.
|
||||
cursor_position: Option<PhysicalPosition<f64>>,
|
||||
/// Window modifiers state.
|
||||
@@ -671,7 +670,7 @@ struct WindowState {
|
||||
/// The amount of pan of the window.
|
||||
panned: PhysicalPosition<f32>,
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[cfg(macos_platform)]
|
||||
option_as_alt: OptionAsAlt,
|
||||
|
||||
// Cursor states.
|
||||
@@ -686,6 +685,7 @@ impl WindowState {
|
||||
|
||||
// SAFETY: the surface is dropped before the `window` which provided it with handle, thus
|
||||
// it doesn't outlive it.
|
||||
#[cfg(not(android_platform))]
|
||||
let surface = Surface::new(app.context.as_ref().unwrap(), Arc::clone(&window))?;
|
||||
|
||||
let theme = window.theme().unwrap_or(Theme::Dark);
|
||||
@@ -693,20 +693,38 @@ impl WindowState {
|
||||
let named_idx = 0;
|
||||
window.set_cursor(CURSORS[named_idx].into());
|
||||
|
||||
// Allow IME out of the box.
|
||||
let request_data = ImeRequestData::default()
|
||||
.with_purpose(ImePurpose::Normal)
|
||||
.with_cursor_area(LogicalPosition { x: 0, y: 0 }.into(), IME_CURSOR_SIZE.into())
|
||||
.with_surrounding_text(ImeSurroundingText::new(String::new(), 0, 0).unwrap());
|
||||
let enable_request = ImeEnableRequest::new(
|
||||
ImeCapabilities::new().with_purpose().with_cursor_area().with_surrounding_text(),
|
||||
request_data,
|
||||
)
|
||||
.unwrap();
|
||||
let enable_ime = ImeRequest::Enable(enable_request);
|
||||
|
||||
// Initial update
|
||||
window.request_ime_update(enable_ime).unwrap();
|
||||
|
||||
let size = window.surface_size();
|
||||
let mut state = Self {
|
||||
#[cfg(target_os = "macos")]
|
||||
#[cfg(macos_platform)]
|
||||
option_as_alt: window.option_as_alt(),
|
||||
custom_idx: app.custom_cursors.as_ref().map(Vec::len).unwrap_or(1) - 1,
|
||||
cursor_grab: CursorGrabMode::None,
|
||||
named_idx,
|
||||
#[cfg(not(android_platform))]
|
||||
surface,
|
||||
window,
|
||||
theme,
|
||||
animated_fill_color: false,
|
||||
continuous_redraw: false,
|
||||
emit_surface_size: false,
|
||||
#[cfg(not(android_platform))]
|
||||
start_time: Instant::now(),
|
||||
ime_enabled: true,
|
||||
text_field_contents: (String::new(), 0),
|
||||
cursor_position: Default::default(),
|
||||
cursor_hidden: Default::default(),
|
||||
modifiers: Default::default(),
|
||||
@@ -720,12 +738,65 @@ impl WindowState {
|
||||
Ok(state)
|
||||
}
|
||||
|
||||
pub fn get_ime_update(&self) -> ImeRequestData {
|
||||
let (text, cursor) = &self.text_field_contents;
|
||||
// A rudimentary text field emulation: the caret moves right by a constant amount for each
|
||||
// code point.
|
||||
|
||||
let text_before_caret = if text.is_char_boundary(*cursor) { &text[..*cursor] } else { "" };
|
||||
let chars_before_caret = text_before_caret.chars().count();
|
||||
let cursor_pos = LogicalPosition { x: 10 * chars_before_caret as u32, y: 0 }.into();
|
||||
|
||||
// Limit text field size
|
||||
const MAX_BYTES: usize = ImeSurroundingText::MAX_TEXT_BYTES;
|
||||
let minimal_offset = cursor / MAX_BYTES * MAX_BYTES;
|
||||
let first_char_boundary =
|
||||
(minimal_offset..*cursor).find(|off| text.is_char_boundary(*off)).unwrap_or(*cursor);
|
||||
let last_char_boundary = (*cursor..(first_char_boundary + MAX_BYTES))
|
||||
.rev()
|
||||
.find(|off| text.is_char_boundary(*off))
|
||||
.unwrap_or(*cursor);
|
||||
let surrounding_text = &text[first_char_boundary..last_char_boundary];
|
||||
let relative_cursor = cursor - first_char_boundary;
|
||||
let surrounding_text =
|
||||
ImeSurroundingText::new(surrounding_text.into(), relative_cursor, relative_cursor)
|
||||
.expect("Bug in example: bad byte calculations");
|
||||
ImeRequestData::default()
|
||||
.with_purpose(ImePurpose::Normal)
|
||||
.with_cursor_area(cursor_pos, IME_CURSOR_SIZE.into())
|
||||
.with_surrounding_text(surrounding_text)
|
||||
}
|
||||
|
||||
pub fn toggle_ime(&mut self) {
|
||||
if self.ime_enabled {
|
||||
self.window.request_ime_update(ImeRequest::Disable).expect("disable can not fail");
|
||||
} else {
|
||||
let enable_request = ImeEnableRequest::new(
|
||||
ImeCapabilities::new().with_purpose().with_cursor_area().with_surrounding_text(),
|
||||
self.get_ime_update(),
|
||||
)
|
||||
.unwrap();
|
||||
self.window.request_ime_update(ImeRequest::Enable(enable_request)).unwrap();
|
||||
};
|
||||
|
||||
self.ime_enabled = !self.ime_enabled;
|
||||
}
|
||||
|
||||
pub fn minimize(&mut self) {
|
||||
self.window.set_minimized(true);
|
||||
}
|
||||
|
||||
pub fn cursor_moved(&mut self, position: PhysicalPosition<f64>) {
|
||||
// the IME really cares about the caret,
|
||||
// but there's nothing else to demonstrate a position
|
||||
self.cursor_position = Some(position);
|
||||
if self.ime_enabled {
|
||||
let request_data =
|
||||
ImeRequestData::default().with_cursor_area(position.into(), IME_CURSOR_SIZE.into());
|
||||
self.window
|
||||
.request_ime_update(ImeRequest::Update(request_data))
|
||||
.expect("A capability was not initially declared");
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cursor_left(&mut self) {
|
||||
@@ -777,10 +848,6 @@ impl WindowState {
|
||||
self.window.set_fullscreen(fullscreen);
|
||||
}
|
||||
|
||||
fn toggle_emit_surface_size(&mut self) {
|
||||
self.emit_surface_size = !self.emit_surface_size;
|
||||
}
|
||||
|
||||
/// Cycle through the grab modes ignoring errors.
|
||||
fn cycle_cursor_grab(&mut self) {
|
||||
self.cursor_grab = match self.cursor_grab {
|
||||
@@ -794,7 +861,7 @@ impl WindowState {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[cfg(macos_platform)]
|
||||
fn cycle_option_as_alt(&mut self) {
|
||||
self.option_as_alt = match self.option_as_alt {
|
||||
OptionAsAlt::None => OptionAsAlt::OnlyLeft,
|
||||
@@ -840,7 +907,7 @@ impl WindowState {
|
||||
}
|
||||
|
||||
/// Custom cursor from an URL.
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[cfg(web_platform)]
|
||||
fn url_custom_cursor(
|
||||
&mut self,
|
||||
event_loop: &dyn ActiveEventLoop,
|
||||
@@ -853,7 +920,7 @@ impl WindowState {
|
||||
}
|
||||
|
||||
/// Custom cursor from a URL.
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[cfg(web_platform)]
|
||||
fn animation_custom_cursor(
|
||||
&mut self,
|
||||
event_loop: &dyn ActiveEventLoop,
|
||||
@@ -877,12 +944,15 @@ impl WindowState {
|
||||
/// Resize the surface to the new size.
|
||||
fn resize(&mut self, size: PhysicalSize<u32>) {
|
||||
info!("Surface resized to {size:?}");
|
||||
let (width, height) = match (NonZeroU32::new(size.width), NonZeroU32::new(size.height)) {
|
||||
(Some(width), Some(height)) => (width, height),
|
||||
_ => return,
|
||||
};
|
||||
self.surface.resize(width, height).expect("failed to resize inner buffer");
|
||||
|
||||
#[cfg(not(android_platform))]
|
||||
{
|
||||
let (width, height) = match (NonZeroU32::new(size.width), NonZeroU32::new(size.height))
|
||||
{
|
||||
(Some(width), Some(height)) => (width, height),
|
||||
_ => return,
|
||||
};
|
||||
self.surface.resize(width, height).expect("failed to resize inner buffer");
|
||||
}
|
||||
self.window.request_redraw();
|
||||
}
|
||||
|
||||
@@ -967,6 +1037,7 @@ impl WindowState {
|
||||
}
|
||||
|
||||
/// Draw the window contents.
|
||||
#[cfg(not(android_platform))]
|
||||
fn draw(&mut self) -> Result<(), Box<dyn Error>> {
|
||||
if self.occluded {
|
||||
info!("Skipping drawing occluded window={:?}", self.window.id());
|
||||
@@ -1012,6 +1083,12 @@ impl WindowState {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(android_platform)]
|
||||
fn draw(&mut self) -> Result<(), Box<dyn Error>> {
|
||||
info!("Drawing but without rendering...");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct Binding<T: Eq> {
|
||||
@@ -1036,37 +1113,35 @@ enum Action {
|
||||
ToggleCursorVisibility,
|
||||
CreateNewWindow,
|
||||
ToggleResizeIncrements,
|
||||
ToggleImeInput,
|
||||
ToggleDecorations,
|
||||
ToggleResizable,
|
||||
ToggleFullscreen,
|
||||
#[cfg(target_os = "macos")]
|
||||
#[cfg(macos_platform)]
|
||||
ToggleSimpleFullscreen,
|
||||
#[cfg(target_os = "macos")]
|
||||
ToggleBorderlessGame,
|
||||
ToggleMaximize,
|
||||
Minimize,
|
||||
NextCursor,
|
||||
NextCustomCursor,
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[cfg(web_platform)]
|
||||
UrlCustomCursor,
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[cfg(web_platform)]
|
||||
AnimationCustomCursor,
|
||||
CycleCursorGrab,
|
||||
PrintHelp,
|
||||
DragWindow,
|
||||
DragResizeWindow,
|
||||
ShowWindowMenu,
|
||||
#[cfg(target_os = "macos")]
|
||||
#[cfg(macos_platform)]
|
||||
CycleOptionAsAlt,
|
||||
SetTheme(Option<Theme>),
|
||||
#[cfg(target_os = "macos")]
|
||||
#[cfg(macos_platform)]
|
||||
CreateNewTab,
|
||||
RequestResize,
|
||||
DumpMonitors,
|
||||
Message,
|
||||
ToggleAnimatedFillColor,
|
||||
ToggleContinuousRedraw,
|
||||
EmitSurfaceSize,
|
||||
}
|
||||
|
||||
impl Action {
|
||||
@@ -1075,38 +1150,37 @@ impl Action {
|
||||
Action::CloseWindow => "Close window",
|
||||
Action::ToggleCursorVisibility => "Hide cursor",
|
||||
Action::CreateNewWindow => "Create new window",
|
||||
Action::ToggleImeInput => "Toggle IME input",
|
||||
Action::ToggleDecorations => "Toggle decorations",
|
||||
Action::ToggleResizable => "Toggle window resizable state",
|
||||
Action::ToggleFullscreen => "Toggle fullscreen",
|
||||
#[cfg(target_os = "macos")]
|
||||
#[cfg(macos_platform)]
|
||||
Action::ToggleSimpleFullscreen => "Toggle simple fullscreen",
|
||||
#[cfg(target_os = "macos")]
|
||||
Action::ToggleBorderlessGame => "Toggle borderless game mode",
|
||||
Action::ToggleMaximize => "Maximize",
|
||||
Action::Minimize => "Minimize",
|
||||
Action::ToggleResizeIncrements => "Use resize increments when resizing window",
|
||||
Action::NextCursor => "Advance the cursor to the next value",
|
||||
Action::NextCustomCursor => "Advance custom cursor to the next value",
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[cfg(web_platform)]
|
||||
Action::UrlCustomCursor => "Custom cursor from an URL",
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[cfg(web_platform)]
|
||||
Action::AnimationCustomCursor => "Custom cursor from an animation",
|
||||
Action::CycleCursorGrab => "Cycle through cursor grab mode",
|
||||
Action::PrintHelp => "Print help",
|
||||
Action::DragWindow => "Start window drag",
|
||||
Action::DragResizeWindow => "Start window drag-resize",
|
||||
Action::ShowWindowMenu => "Show window menu",
|
||||
#[cfg(target_os = "macos")]
|
||||
#[cfg(macos_platform)]
|
||||
Action::CycleOptionAsAlt => "Cycle option as alt mode",
|
||||
Action::SetTheme(None) => "Change to the system theme",
|
||||
Action::SetTheme(Some(Theme::Light)) => "Change to a light theme",
|
||||
Action::SetTheme(Some(Theme::Dark)) => "Change to a dark theme",
|
||||
#[cfg(target_os = "macos")]
|
||||
#[cfg(macos_platform)]
|
||||
Action::CreateNewTab => "Create new tab",
|
||||
Action::RequestResize => "Request a resize",
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
#[cfg(not(web_platform))]
|
||||
Action::DumpMonitors => "Dump monitor information",
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[cfg(web_platform)]
|
||||
Action::DumpMonitors => {
|
||||
"Request permission to query detailed monitor information and dump monitor \
|
||||
information"
|
||||
@@ -1114,7 +1188,6 @@ impl Action {
|
||||
Action::Message => "Prints a message through a user wake up",
|
||||
Action::ToggleAnimatedFillColor => "Toggle animated fill color",
|
||||
Action::ToggleContinuousRedraw => "Toggle continuous redraw",
|
||||
Action::EmitSurfaceSize => "Periodically print the surface size",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1133,7 +1206,7 @@ fn decode_cursor(bytes: &[u8]) -> CustomCursorSource {
|
||||
CustomCursorSource::from_rgba(samples.samples, w, h, w / 2, h / 2).unwrap()
|
||||
}
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[cfg(web_platform)]
|
||||
fn url_custom_cursor() -> CustomCursorSource {
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
@@ -1186,16 +1259,69 @@ fn modifiers_to_string(mods: ModifiersState) -> String {
|
||||
mods_line
|
||||
}
|
||||
|
||||
fn mouse_button_to_string(button: MouseButton) -> Cow<'static, str> {
|
||||
fn mouse_button_to_string(button: MouseButton) -> &'static str {
|
||||
match button {
|
||||
MouseButton::Left => "LMB",
|
||||
MouseButton::Right => "RMB",
|
||||
MouseButton::Middle => "MMB",
|
||||
MouseButton::Back => "Back",
|
||||
MouseButton::Forward => "Forward",
|
||||
other => return format!("button {}", other as u8 + 1).into(),
|
||||
MouseButton::Other(_) => "",
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
#[cfg(web_platform)]
|
||||
fn window_attributes_web() -> WindowAttributesWeb {
|
||||
WindowAttributesWeb::default().with_append(true)
|
||||
}
|
||||
|
||||
#[cfg(wayland_platform)]
|
||||
fn window_attributes_wayland(event_loop: &dyn ActiveEventLoop) -> WindowAttributesWayland {
|
||||
let mut window_attributes = WindowAttributesWayland::default();
|
||||
|
||||
if let Some(token) = event_loop.read_token_from_env() {
|
||||
startup_notify::reset_activation_token_env();
|
||||
info!("Using token {:?} to activate a window", token);
|
||||
window_attributes = window_attributes.with_activation_token(token);
|
||||
}
|
||||
|
||||
window_attributes
|
||||
}
|
||||
|
||||
#[cfg(x11_platform)]
|
||||
fn window_attributes_x11(
|
||||
event_loop: &dyn ActiveEventLoop,
|
||||
) -> Result<WindowAttributesX11, Box<dyn Error>> {
|
||||
let mut window_attributes = WindowAttributesX11::default();
|
||||
|
||||
#[cfg(any(x11_platform, wayland_platform))]
|
||||
if let Some(token) = event_loop.read_token_from_env() {
|
||||
startup_notify::reset_activation_token_env();
|
||||
info!("Using token {:?} to activate a window", token);
|
||||
window_attributes = window_attributes.with_activation_token(token);
|
||||
}
|
||||
|
||||
match std::env::var("X11_VISUAL_ID") {
|
||||
Ok(visual_id_str) => {
|
||||
info!("Using X11 visual id {visual_id_str}");
|
||||
let visual_id = visual_id_str.parse()?;
|
||||
window_attributes = window_attributes.with_x11_visual(visual_id);
|
||||
},
|
||||
Err(_) => info!("Set the X11_VISUAL_ID env variable to request specific X11 visual"),
|
||||
}
|
||||
|
||||
match std::env::var("X11_SCREEN_ID") {
|
||||
Ok(screen_id_str) => {
|
||||
info!("Placing the window on X11 screen {screen_id_str}");
|
||||
let screen_id = screen_id_str.parse()?;
|
||||
window_attributes = window_attributes.with_x11_screen(screen_id);
|
||||
},
|
||||
Err(_) => {
|
||||
info!("Set the X11_SCREEN_ID env variable to place the window on non-default screen")
|
||||
},
|
||||
}
|
||||
|
||||
Ok(window_attributes)
|
||||
}
|
||||
|
||||
/// Cursor list to cycle through.
|
||||
@@ -1241,9 +1367,10 @@ const KEY_BINDINGS: &[Binding<&'static str>] = &[
|
||||
Binding::new("H", ModifiersState::CONTROL, Action::PrintHelp),
|
||||
Binding::new("F", ModifiersState::SHIFT, Action::ToggleAnimatedFillColor),
|
||||
Binding::new("F", ModifiersState::CONTROL, Action::ToggleFullscreen),
|
||||
#[cfg(target_os = "macos")]
|
||||
#[cfg(macos_platform)]
|
||||
Binding::new("F", ModifiersState::ALT, Action::ToggleSimpleFullscreen),
|
||||
Binding::new("D", ModifiersState::CONTROL, Action::ToggleDecorations),
|
||||
Binding::new("I", ModifiersState::CONTROL, Action::ToggleImeInput),
|
||||
Binding::new("L", ModifiersState::CONTROL, Action::CycleCursorGrab),
|
||||
Binding::new("P", ModifiersState::CONTROL, Action::ToggleResizeIncrements),
|
||||
Binding::new("R", ModifiersState::CONTROL, Action::ToggleResizable),
|
||||
@@ -1258,13 +1385,13 @@ const KEY_BINDINGS: &[Binding<&'static str>] = &[
|
||||
// C.
|
||||
Binding::new("C", ModifiersState::CONTROL, Action::NextCursor),
|
||||
Binding::new("C", ModifiersState::ALT, Action::NextCustomCursor),
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[cfg(web_platform)]
|
||||
Binding::new(
|
||||
"C",
|
||||
ModifiersState::CONTROL.union(ModifiersState::SHIFT),
|
||||
Action::UrlCustomCursor,
|
||||
),
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[cfg(web_platform)]
|
||||
Binding::new(
|
||||
"C",
|
||||
ModifiersState::ALT.union(ModifiersState::SHIFT),
|
||||
@@ -1275,13 +1402,10 @@ const KEY_BINDINGS: &[Binding<&'static str>] = &[
|
||||
Binding::new("K", ModifiersState::empty(), Action::SetTheme(None)),
|
||||
Binding::new("K", ModifiersState::META, Action::SetTheme(Some(Theme::Light))),
|
||||
Binding::new("K", ModifiersState::CONTROL, Action::SetTheme(Some(Theme::Dark))),
|
||||
#[cfg(target_os = "macos")]
|
||||
#[cfg(macos_platform)]
|
||||
Binding::new("T", ModifiersState::META, Action::CreateNewTab),
|
||||
#[cfg(target_os = "macos")]
|
||||
#[cfg(macos_platform)]
|
||||
Binding::new("O", ModifiersState::CONTROL, Action::CycleOptionAsAlt),
|
||||
#[cfg(target_os = "macos")]
|
||||
Binding::new("B", ModifiersState::CONTROL, Action::ToggleBorderlessGame),
|
||||
Binding::new("S", ModifiersState::ALT, Action::EmitSurfaceSize),
|
||||
Binding::new("S", ModifiersState::CONTROL, Action::Message),
|
||||
];
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
#[cfg(any(x11_platform, target_os = "macos", target_os = "windows"))]
|
||||
#[cfg(any(x11_platform, macos_platform, windows_platform))]
|
||||
#[allow(deprecated)]
|
||||
fn main() -> Result<(), impl std::error::Error> {
|
||||
use std::collections::HashMap;
|
||||
|
||||
use tracing::info;
|
||||
use winit::application::ApplicationHandler;
|
||||
use winit::dpi::{LogicalPosition, LogicalSize, Position};
|
||||
use winit::event::{ElementState, KeyEvent, WindowEvent};
|
||||
@@ -39,7 +38,7 @@ fn main() -> Result<(), impl std::error::Error> {
|
||||
.with_position(Position::Logical(LogicalPosition::new(0.0, 0.0)))
|
||||
.with_surface_size(LogicalSize::new(640.0f32, 480.0f32));
|
||||
let window = event_loop.create_window(attributes).unwrap();
|
||||
info!("Parent window id: {:?})", window.id());
|
||||
println!("Parent window id: {:?})", window.id());
|
||||
self.parent_window_id = Some(window.id());
|
||||
|
||||
self.windows.insert(window.id(), WindowData::new(window, 0xffbbbbbb));
|
||||
@@ -57,12 +56,12 @@ fn main() -> Result<(), impl std::error::Error> {
|
||||
event_loop.exit();
|
||||
},
|
||||
WindowEvent::PointerEntered { device_id: _, .. } => {
|
||||
// On x11, log when the cursor entered in a window even if the child window
|
||||
// On x11, println when the cursor entered in a window even if the child window
|
||||
// is created by some key inputs.
|
||||
// the child windows are always placed at (0, 0) with size (200, 200) in the
|
||||
// parent window, so we also can see this log when we move
|
||||
// the cursor around (200, 200) in parent window.
|
||||
info!("cursor entered in the window {window_id:?}");
|
||||
println!("cursor entered in the window {window_id:?}");
|
||||
},
|
||||
WindowEvent::KeyboardInput {
|
||||
event: KeyEvent { state: ElementState::Pressed, .. },
|
||||
@@ -76,7 +75,7 @@ fn main() -> Result<(), impl std::error::Error> {
|
||||
let child_window =
|
||||
spawn_child_window(parent_window.window.as_ref(), event_loop, child_index);
|
||||
let child_id = child_window.id();
|
||||
info!("Child window created with id: {child_id:?}");
|
||||
println!("Child window created with id: {child_id:?}");
|
||||
self.windows.insert(child_id, WindowData::new(child_window, child_color));
|
||||
},
|
||||
WindowEvent::RedrawRequested => {
|
||||
@@ -121,7 +120,7 @@ fn main() -> Result<(), impl std::error::Error> {
|
||||
event_loop.run_app(Application::default())
|
||||
}
|
||||
|
||||
#[cfg(not(any(x11_platform, target_os = "macos", target_os = "windows")))]
|
||||
#[cfg(not(any(x11_platform, macos_platform, windows_platform)))]
|
||||
fn main() {
|
||||
panic!(
|
||||
"This example is supported only on x11, macOS, and Windows, with the `rwh_06` feature \
|
||||
@@ -1,13 +1,12 @@
|
||||
#![allow(clippy::single_match)]
|
||||
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
use std::time::Instant;
|
||||
#[cfg(not(web_platform))]
|
||||
use std::time;
|
||||
|
||||
use tracing::{info, warn};
|
||||
#[cfg(target_family = "wasm")]
|
||||
use web_time::Instant;
|
||||
use ::tracing::{info, warn};
|
||||
#[cfg(web_platform)]
|
||||
use web_time as time;
|
||||
use winit::application::ApplicationHandler;
|
||||
use winit::event::{ElementState, KeyEvent, StartCause, WindowEvent};
|
||||
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
|
||||
@@ -19,8 +18,8 @@ mod fill;
|
||||
#[path = "util/tracing.rs"]
|
||||
mod tracing;
|
||||
|
||||
const WAIT_TIME: Duration = Duration::from_millis(100);
|
||||
const POLL_SLEEP_TIME: Duration = Duration::from_millis(100);
|
||||
const WAIT_TIME: time::Duration = time::Duration::from_millis(100);
|
||||
const POLL_SLEEP_TIME: time::Duration = time::Duration::from_millis(100);
|
||||
|
||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Mode {
|
||||
@@ -31,7 +30,7 @@ enum Mode {
|
||||
}
|
||||
|
||||
fn main() -> Result<(), impl std::error::Error> {
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[cfg(web_platform)]
|
||||
console_error_panic_hook::set_once();
|
||||
|
||||
tracing::init();
|
||||
@@ -130,7 +129,8 @@ impl ApplicationHandler for ControlFlowDemo {
|
||||
Mode::Wait => event_loop.set_control_flow(ControlFlow::Wait),
|
||||
Mode::WaitUntil => {
|
||||
if !self.wait_cancelled {
|
||||
event_loop.set_control_flow(ControlFlow::WaitUntil(Instant::now() + WAIT_TIME));
|
||||
event_loop
|
||||
.set_control_flow(ControlFlow::WaitUntil(time::Instant::now() + WAIT_TIME));
|
||||
}
|
||||
},
|
||||
Mode::Poll => {
|
||||
|
Before Width: | Height: | Size: 159 B After Width: | Height: | Size: 159 B |
|
Before Width: | Height: | Size: 129 B After Width: | Height: | Size: 129 B |
|
Before Width: | Height: | Size: 229 B After Width: | Height: | Size: 229 B |
|
Before Width: | Height: | Size: 2.9 KiB After Width: | Height: | Size: 2.9 KiB |
@@ -1,6 +1,5 @@
|
||||
use std::error::Error;
|
||||
|
||||
use tracing::info;
|
||||
use winit::application::ApplicationHandler;
|
||||
use winit::event::WindowEvent;
|
||||
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
||||
@@ -50,7 +49,7 @@ impl ApplicationHandler for Application {
|
||||
| WindowEvent::DragEntered { .. }
|
||||
| WindowEvent::DragMoved { .. }
|
||||
| WindowEvent::DragDropped { .. } => {
|
||||
info!("{event:?}");
|
||||
println!("{event:?}");
|
||||
},
|
||||
WindowEvent::RedrawRequested => {
|
||||
let window = self.window.as_ref().unwrap();
|
||||
@@ -1,19 +1,12 @@
|
||||
#![allow(clippy::single_match)]
|
||||
|
||||
// Limit this example to only compatible platforms.
|
||||
#[cfg(any(
|
||||
target_os = "windows",
|
||||
target_os = "macos",
|
||||
x11_platform,
|
||||
wayland_platform,
|
||||
target_os = "android",
|
||||
))]
|
||||
#[cfg(any(windows_platform, macos_platform, x11_platform, wayland_platform, android_platform,))]
|
||||
fn main() -> std::process::ExitCode {
|
||||
use std::process::ExitCode;
|
||||
use std::thread::sleep;
|
||||
use std::time::Duration;
|
||||
|
||||
use tracing::info;
|
||||
use winit::application::ApplicationHandler;
|
||||
use winit::event::WindowEvent;
|
||||
use winit::event_loop::pump_events::{EventLoopExtPumpEvents, PumpStatus};
|
||||
@@ -22,8 +15,6 @@ fn main() -> std::process::ExitCode {
|
||||
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
#[path = "util/tracing.rs"]
|
||||
mod tracing;
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
struct PumpDemo {
|
||||
@@ -42,7 +33,7 @@ fn main() -> std::process::ExitCode {
|
||||
_window_id: WindowId,
|
||||
event: WindowEvent,
|
||||
) {
|
||||
info!("{event:?}");
|
||||
println!("{event:?}");
|
||||
|
||||
let window = match self.window.as_ref() {
|
||||
Some(window) => window,
|
||||
@@ -60,10 +51,10 @@ fn main() -> std::process::ExitCode {
|
||||
}
|
||||
}
|
||||
|
||||
tracing::init();
|
||||
|
||||
let mut event_loop = EventLoop::new().unwrap();
|
||||
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
let mut app = PumpDemo::default();
|
||||
|
||||
loop {
|
||||
@@ -78,18 +69,12 @@ fn main() -> std::process::ExitCode {
|
||||
//
|
||||
// Since `pump_events` doesn't block it will be important to
|
||||
// throttle the loop in the app somehow.
|
||||
info!("Update()");
|
||||
println!("Update()");
|
||||
sleep(Duration::from_millis(16));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(any(
|
||||
target_os = "windows",
|
||||
target_os = "macos",
|
||||
x11_platform,
|
||||
wayland_platform,
|
||||
target_os = "android",
|
||||
)))]
|
||||
#[cfg(any(ios_platform, web_platform, orbital_platform))]
|
||||
fn main() {
|
||||
panic!("This platform doesn't support pump_events.")
|
||||
println!("This platform doesn't support pump_events.");
|
||||
}
|
||||
@@ -1,17 +1,10 @@
|
||||
#![allow(clippy::single_match)]
|
||||
|
||||
// Limit this example to only compatible platforms.
|
||||
#[cfg(any(
|
||||
target_os = "windows",
|
||||
target_os = "macos",
|
||||
x11_platform,
|
||||
wayland_platform,
|
||||
target_os = "redox"
|
||||
))]
|
||||
#[cfg(any(windows_platform, macos_platform, x11_platform, wayland_platform,))]
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
use std::time::Duration;
|
||||
|
||||
use tracing::info;
|
||||
use winit::application::ApplicationHandler;
|
||||
use winit::event::WindowEvent;
|
||||
use winit::event_loop::run_on_demand::EventLoopExtRunOnDemand;
|
||||
@@ -20,8 +13,6 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
#[path = "util/tracing.rs"]
|
||||
mod tracing;
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
struct App {
|
||||
@@ -53,7 +44,10 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
event: WindowEvent,
|
||||
) {
|
||||
if event == WindowEvent::Destroyed && self.window_id == Some(window_id) {
|
||||
info!("Window {} Destroyed", self.idx);
|
||||
println!(
|
||||
"--------------------------------------------------------- Window {} Destroyed",
|
||||
self.idx
|
||||
);
|
||||
self.window_id = None;
|
||||
event_loop.exit();
|
||||
return;
|
||||
@@ -66,7 +60,11 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
|
||||
match event {
|
||||
WindowEvent::CloseRequested => {
|
||||
info!("Window {} CloseRequested", self.idx);
|
||||
println!(
|
||||
"--------------------------------------------------------- Window {} \
|
||||
CloseRequested",
|
||||
self.idx
|
||||
);
|
||||
fill::cleanup_window(window.as_ref());
|
||||
self.window = None;
|
||||
},
|
||||
@@ -78,30 +76,24 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
}
|
||||
}
|
||||
|
||||
tracing::init();
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
let mut event_loop = EventLoop::new().unwrap();
|
||||
|
||||
let mut app = App { idx: 1, ..Default::default() };
|
||||
event_loop.run_app_on_demand(&mut app)?;
|
||||
|
||||
info!("Finished first loop");
|
||||
info!("Waiting 5 seconds");
|
||||
println!("--------------------------------------------------------- Finished first loop");
|
||||
println!("--------------------------------------------------------- Waiting 5 seconds");
|
||||
std::thread::sleep(Duration::from_secs(5));
|
||||
|
||||
app.idx += 1;
|
||||
event_loop.run_app_on_demand(&mut app)?;
|
||||
info!("Finished second loop");
|
||||
println!("--------------------------------------------------------- Finished second loop");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(any(
|
||||
target_os = "windows",
|
||||
target_os = "macos",
|
||||
x11_platform,
|
||||
wayland_platform,
|
||||
target_os = "redox"
|
||||
)))]
|
||||
#[cfg(not(any(windows_platform, macos_platform, x11_platform, wayland_platform,)))]
|
||||
fn main() {
|
||||
panic!("This example is not supported on this platform")
|
||||
println!("This example is not supported on this platform");
|
||||
}
|
||||
156
examples/util/fill.rs
Normal file
@@ -0,0 +1,156 @@
|
||||
//! Fill the window buffer with a solid color.
|
||||
//!
|
||||
//! Launching a window without drawing to it has unpredictable results varying from platform to
|
||||
//! platform. In order to have well-defined examples, this module provides an easy way to
|
||||
//! fill the window buffer with a solid color.
|
||||
//!
|
||||
//! The `softbuffer` crate is used, largely because of its ease of use. `glutin` or `wgpu` could
|
||||
//! also be used to fill the window buffer, but they are more complicated to use.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
pub use platform::cleanup_window;
|
||||
#[allow(unused_imports)]
|
||||
pub use platform::fill_window;
|
||||
#[allow(unused_imports)]
|
||||
pub use platform::fill_window_with_animated_color;
|
||||
#[allow(unused_imports)]
|
||||
pub use platform::fill_window_with_color;
|
||||
|
||||
#[cfg(not(any(target_os = "android", target_os = "ios")))]
|
||||
mod platform {
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::mem;
|
||||
use std::mem::ManuallyDrop;
|
||||
use std::num::NonZeroU32;
|
||||
#[cfg(all(not(android_platform), not(web_platform)))]
|
||||
use std::time::Instant;
|
||||
|
||||
use softbuffer::{Context, Surface};
|
||||
#[cfg(all(web_platform, not(android_platform)))]
|
||||
use web_time::Instant;
|
||||
use winit::window::{Window, WindowId};
|
||||
|
||||
thread_local! {
|
||||
// NOTE: You should never do things like that, create context and drop it before
|
||||
// you drop the event loop. We do this for brevity to not blow up examples. We use
|
||||
// ManuallyDrop to prevent destructors from running.
|
||||
//
|
||||
// A static, thread-local map of graphics contexts to open windows.
|
||||
static GC: ManuallyDrop<RefCell<Option<GraphicsContext>>> = const { ManuallyDrop::new(RefCell::new(None)) };
|
||||
}
|
||||
|
||||
/// The graphics context used to draw to a window.
|
||||
struct GraphicsContext {
|
||||
/// The global softbuffer context.
|
||||
context: RefCell<Context<&'static dyn Window>>,
|
||||
|
||||
/// The hash map of window IDs to surfaces.
|
||||
surfaces: HashMap<WindowId, Surface<&'static dyn Window, &'static dyn Window>>,
|
||||
}
|
||||
|
||||
impl GraphicsContext {
|
||||
fn new(w: &dyn Window) -> Self {
|
||||
Self {
|
||||
context: RefCell::new(
|
||||
Context::new(unsafe {
|
||||
mem::transmute::<&'_ dyn Window, &'static dyn Window>(w)
|
||||
})
|
||||
.expect("Failed to create a softbuffer context"),
|
||||
),
|
||||
surfaces: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn create_surface(
|
||||
&mut self,
|
||||
window: &dyn Window,
|
||||
) -> &mut Surface<&'static dyn Window, &'static dyn Window> {
|
||||
self.surfaces.entry(window.id()).or_insert_with(|| {
|
||||
Surface::new(&self.context.borrow(), unsafe {
|
||||
mem::transmute::<&'_ dyn Window, &'static dyn Window>(window)
|
||||
})
|
||||
.expect("Failed to create a softbuffer surface")
|
||||
})
|
||||
}
|
||||
|
||||
fn destroy_surface(&mut self, window: &dyn Window) {
|
||||
self.surfaces.remove(&window.id());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn fill_window_with_color(window: &dyn Window, color: u32) {
|
||||
GC.with(|gc| {
|
||||
let size = window.surface_size();
|
||||
let (Some(width), Some(height)) =
|
||||
(NonZeroU32::new(size.width), NonZeroU32::new(size.height))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
// Either get the last context used or create a new one.
|
||||
let mut gc = gc.borrow_mut();
|
||||
let surface =
|
||||
gc.get_or_insert_with(|| GraphicsContext::new(window)).create_surface(window);
|
||||
|
||||
// Fill a buffer with a solid color
|
||||
|
||||
surface.resize(width, height).expect("Failed to resize the softbuffer surface");
|
||||
|
||||
let mut buffer = surface.buffer_mut().expect("Failed to get the softbuffer buffer");
|
||||
buffer.fill(color);
|
||||
buffer.present().expect("Failed to present the softbuffer buffer");
|
||||
})
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn fill_window(window: &dyn Window) {
|
||||
fill_window_with_color(window, 0xff181818);
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn fill_window_with_animated_color(window: &dyn Window, start: Instant) {
|
||||
let time = start.elapsed().as_secs_f32() * 1.5;
|
||||
let blue = (time.sin() * 255.0) as u32;
|
||||
let green = ((time.cos() * 255.0) as u32) << 8;
|
||||
let red = ((1.0 - time.sin() * 255.0) as u32) << 16;
|
||||
let color = red | green | blue;
|
||||
fill_window_with_color(window, color);
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn cleanup_window(window: &dyn Window) {
|
||||
GC.with(|gc| {
|
||||
let mut gc = gc.borrow_mut();
|
||||
if let Some(context) = gc.as_mut() {
|
||||
context.destroy_surface(window);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "android", target_os = "ios"))]
|
||||
mod platform {
|
||||
#[allow(dead_code)]
|
||||
pub fn fill_window(_window: &dyn winit::window::Window) {
|
||||
// No-op on mobile platforms.
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn fill_window_with_color(_window: &dyn winit::window::Window, _color: u32) {
|
||||
// No-op on mobile platforms.
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn fill_window_with_animated_color(
|
||||
_window: &dyn winit::window::Window,
|
||||
_start: std::time::Instant,
|
||||
) {
|
||||
// No-op on mobile platforms.
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn cleanup_window(_window: &dyn winit::window::Window) {
|
||||
// No-op on mobile platforms.
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
#[cfg(not(web_platform))]
|
||||
pub fn init() {
|
||||
use tracing_subscriber::filter::{EnvFilter, LevelFilter};
|
||||
|
||||
@@ -9,7 +9,7 @@ pub fn init() {
|
||||
.init();
|
||||
}
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[cfg(web_platform)]
|
||||
pub fn init() {
|
||||
use tracing_subscriber::layer::SubscriberExt;
|
||||
use tracing_subscriber::util::SubscriberInitExt;
|
||||
@@ -23,6 +23,3 @@ pub fn init() {
|
||||
)
|
||||
.init();
|
||||
}
|
||||
|
||||
#[allow(unused_imports)]
|
||||
pub use ::tracing::*;
|
||||
@@ -2,10 +2,11 @@
|
||||
|
||||
use std::error::Error;
|
||||
|
||||
use tracing::{error, info};
|
||||
use winit::application::ApplicationHandler;
|
||||
use winit::event::WindowEvent;
|
||||
use winit::event_loop::{ActiveEventLoop, EventLoop};
|
||||
#[cfg(web_platform)]
|
||||
use winit::platform::web::WindowAttributesWeb;
|
||||
use winit::window::{Window, WindowAttributes, WindowId};
|
||||
|
||||
#[path = "util/fill.rs"]
|
||||
@@ -20,15 +21,15 @@ struct App {
|
||||
|
||||
impl ApplicationHandler for App {
|
||||
fn can_create_surfaces(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||
#[cfg(not(web_platform))]
|
||||
let window_attributes = WindowAttributes::default();
|
||||
#[cfg(target_family = "wasm")]
|
||||
let window_attributes = window_attributes.with_platform_attributes(Box::new(
|
||||
winit::platform::web::WindowAttributesWeb::default().with_append(true),
|
||||
));
|
||||
#[cfg(web_platform)]
|
||||
let window_attributes = WindowAttributes::default()
|
||||
.with_platform_attributes(Box::new(WindowAttributesWeb::default().with_append(true)));
|
||||
self.window = match event_loop.create_window(window_attributes) {
|
||||
Ok(window) => Some(window),
|
||||
Err(err) => {
|
||||
error!("error creating window: {err}");
|
||||
eprintln!("error creating window: {err}");
|
||||
event_loop.exit();
|
||||
return;
|
||||
},
|
||||
@@ -36,10 +37,10 @@ impl ApplicationHandler for App {
|
||||
}
|
||||
|
||||
fn window_event(&mut self, event_loop: &dyn ActiveEventLoop, _: WindowId, event: WindowEvent) {
|
||||
info!("{event:?}");
|
||||
println!("{event:?}");
|
||||
match event {
|
||||
WindowEvent::CloseRequested => {
|
||||
info!("Close was requested; stopping");
|
||||
println!("Close was requested; stopping");
|
||||
event_loop.exit();
|
||||
},
|
||||
WindowEvent::SurfaceResized(_) => {
|
||||
@@ -69,7 +70,7 @@ impl ApplicationHandler for App {
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[cfg(web_platform)]
|
||||
console_error_panic_hook::set_once();
|
||||
|
||||
tracing::init();
|
||||
@@ -11,8 +11,6 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
|
||||
#[path = "util/fill.rs"]
|
||||
mod fill;
|
||||
#[path = "util/tracing.rs"]
|
||||
mod tracing;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct XEmbedDemo {
|
||||
@@ -60,7 +58,7 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
.ok_or("Expected a 32-bit X11 window ID as the first argument.")?
|
||||
.parse::<u32>()?;
|
||||
|
||||
tracing::init();
|
||||
tracing_subscriber::fmt::init();
|
||||
let event_loop = EventLoop::new()?;
|
||||
|
||||
Ok(event_loop.run_app(XEmbedDemo { parent_window_id, window: None })?)
|
||||
@@ -68,5 +66,6 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
|
||||
#[cfg(not(x11_platform))]
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
panic!("This example is only supported on X11 platforms.")
|
||||
println!("This example is only supported on X11 platforms.");
|
||||
Ok(())
|
||||
}
|
||||
@@ -473,23 +473,16 @@ impl EventLoop {
|
||||
&mut self.combining_accent,
|
||||
);
|
||||
|
||||
let logical_key = keycodes::to_logical(key_char, keycode);
|
||||
let text = if state == event::ElementState::Pressed {
|
||||
logical_key.to_text().map(smol_str::SmolStr::new)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let event = event::WindowEvent::KeyboardInput {
|
||||
device_id: Some(DeviceId::from_raw(key.device_id() as i64)),
|
||||
event: event::KeyEvent {
|
||||
state,
|
||||
physical_key: keycodes::to_physical_key(keycode),
|
||||
logical_key,
|
||||
logical_key: keycodes::to_logical(key_char, keycode),
|
||||
location: keycodes::to_location(keycode),
|
||||
repeat: key.repeat_count() > 0,
|
||||
text: text.clone(),
|
||||
text_with_all_modifiers: text,
|
||||
text: None,
|
||||
text_with_all_modifiers: None,
|
||||
key_without_modifiers: keycodes::to_logical(key_char, keycode),
|
||||
},
|
||||
is_synthetic: false,
|
||||
@@ -507,6 +500,10 @@ impl EventLoop {
|
||||
input_status
|
||||
}
|
||||
|
||||
pub fn run_app<A: ApplicationHandler>(mut self, app: A) -> Result<(), EventLoopError> {
|
||||
self.run_app_on_demand(app)
|
||||
}
|
||||
|
||||
pub fn run_app_on_demand<A: ApplicationHandler>(
|
||||
&mut self,
|
||||
mut app: A,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use android_activity::AndroidApp;
|
||||
use android_activity::input::{KeyAction, KeyEvent, KeyMapChar, Keycode};
|
||||
use android_activity::AndroidApp;
|
||||
use winit_core::keyboard::{
|
||||
Key, KeyCode, KeyLocation, NamedKey, NativeKey, NativeKeyCode, PhysicalKey,
|
||||
};
|
||||
@@ -109,7 +109,6 @@ pub fn to_physical_key(keycode: Keycode) -> PhysicalKey {
|
||||
Keycode::MediaStop => KeyCode::MediaStop,
|
||||
Keycode::MediaNext => KeyCode::MediaTrackNext,
|
||||
Keycode::MediaPrevious => KeyCode::MediaTrackPrevious,
|
||||
Keycode::MediaEject => KeyCode::Eject,
|
||||
|
||||
Keycode::Plus => KeyCode::Equal,
|
||||
Keycode::Minus => KeyCode::Minus,
|
||||
@@ -132,11 +131,7 @@ pub fn to_physical_key(keycode: Keycode) -> PhysicalKey {
|
||||
// These are exactly the same
|
||||
Keycode::ScrollLock => KeyCode::ScrollLock,
|
||||
|
||||
Keycode::Eisu => KeyCode::Lang2,
|
||||
Keycode::Muhenkan => KeyCode::NonConvert,
|
||||
Keycode::Henkan => KeyCode::Convert,
|
||||
Keycode::Yen => KeyCode::IntlYen,
|
||||
Keycode::Ro => KeyCode::IntlRo,
|
||||
Keycode::Kana => KeyCode::Lang1,
|
||||
Keycode::KatakanaHiragana => KeyCode::KanaMode,
|
||||
|
||||
@@ -159,14 +154,6 @@ pub fn to_physical_key(keycode: Keycode) -> PhysicalKey {
|
||||
Keycode::Sleep => KeyCode::Sleep, // what about SoftSleep?
|
||||
Keycode::Wakeup => KeyCode::WakeUp,
|
||||
|
||||
Keycode::CapsLock => KeyCode::CapsLock,
|
||||
Keycode::Help => KeyCode::Help,
|
||||
|
||||
Keycode::Back => KeyCode::BrowserBack,
|
||||
Keycode::Forward => KeyCode::BrowserForward,
|
||||
Keycode::Refresh => KeyCode::BrowserRefresh,
|
||||
Keycode::Search => KeyCode::BrowserSearch,
|
||||
|
||||
keycode => return PhysicalKey::Unidentified(NativeKeyCode::Android(keycode.into())),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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.31.0-beta.2", features = [ "android-native-activity" ] }`
|
||||
//! 2. Enable the `"android-native-activity"` feature for Winit: `winit = { version = "0.30.12",
|
||||
//! 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).
|
||||
|
||||
@@ -18,6 +18,7 @@ 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
|
||||
@@ -51,7 +52,6 @@ objc2-app-kit = { workspace = true, features = [
|
||||
"NSScreen",
|
||||
"NSTextInputClient",
|
||||
"NSTextInputContext",
|
||||
"NSTrackingArea",
|
||||
"NSToolbar",
|
||||
"NSView",
|
||||
"NSWindow",
|
||||
@@ -107,7 +107,6 @@ objc2-foundation = { workspace = true, features = [
|
||||
"NSThread",
|
||||
"NSValue",
|
||||
] }
|
||||
winit-common = { workspace = true, features = ["core-foundation", "event-handler", "foundation"] }
|
||||
|
||||
[dev-dependencies]
|
||||
winit.workspace = true
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
#![allow(clippy::unnecessary_cast)]
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::mem;
|
||||
use std::rc::Rc;
|
||||
use std::{mem, ptr};
|
||||
|
||||
use dispatch2::MainThreadBound;
|
||||
use objc2::runtime::{Imp, Sel};
|
||||
use objc2::sel;
|
||||
use objc2_app_kit::{NSApplication, NSEvent, NSEventModifierFlags, NSEventType};
|
||||
use objc2_foundation::MainThreadMarker;
|
||||
use tracing::trace_span;
|
||||
use winit_core::event::{DeviceEvent, ElementState};
|
||||
|
||||
use super::app_state::AppState;
|
||||
@@ -22,10 +21,6 @@ static ORIGINAL: MainThreadBound<Cell<Option<SendEvent>>> = {
|
||||
};
|
||||
|
||||
extern "C-unwind" fn send_event(app: &NSApplication, sel: Sel, event: &NSEvent) {
|
||||
// This can be a bit noisy, since `event` is fairly large. Note that you can use
|
||||
// `RUST_LOG='trace,winit_appkit::app=warn'` if you're debugging and want TRACE-level logs but
|
||||
// not this.
|
||||
let _entered = trace_span!("sendEvent:", ?event).entered();
|
||||
let mtm = MainThreadMarker::from(app);
|
||||
|
||||
// Normally, holding Cmd + any key never sends us a `keyUp` event for that key.
|
||||
@@ -35,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 = event.r#type();
|
||||
let modifier_flags = event.modifierFlags();
|
||||
let event_type = unsafe { event.r#type() };
|
||||
let modifier_flags = unsafe { event.modifierFlags() };
|
||||
if event_type == NSEventType::KeyUp && modifier_flags.contains(NSEventModifierFlags::Command) {
|
||||
if let Some(key_window) = app.keyWindow() {
|
||||
key_window.sendEvent(event);
|
||||
@@ -80,7 +75,9 @@ pub(crate) fn override_send_event(global_app: &NSApplication) {
|
||||
let overridden = unsafe { mem::transmute::<SendEvent, Imp>(send_event) };
|
||||
|
||||
// If we've already overridden the method, don't do anything.
|
||||
if ptr::fn_addr_eq(overridden, method.implementation()) {
|
||||
// FIXME(madsmtm): Use `std::ptr::fn_addr_eq` (Rust 1.85) once available in MSRV.
|
||||
#[allow(unknown_lints, unpredictable_function_pointer_comparisons)]
|
||||
if overridden == method.implementation() {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -101,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 = event.r#type();
|
||||
let event_type = unsafe { event.r#type() };
|
||||
#[allow(non_upper_case_globals)]
|
||||
match event_type {
|
||||
NSEventType::MouseMoved
|
||||
| NSEventType::LeftMouseDragged
|
||||
| NSEventType::OtherMouseDragged
|
||||
| NSEventType::RightMouseDragged => {
|
||||
let delta_x = event.deltaX() as f64;
|
||||
let delta_y = event.deltaY() as f64;
|
||||
let delta_x = unsafe { event.deltaX() } as f64;
|
||||
let delta_y = unsafe { event.deltaY() } as f64;
|
||||
|
||||
if delta_x != 0.0 || delta_y != 0.0 {
|
||||
app_state.maybe_queue_with_handler(move |app, event_loop| {
|
||||
@@ -120,7 +117,7 @@ fn maybe_dispatch_device_event(app_state: &Rc<AppState>, event: &NSEvent) {
|
||||
}
|
||||
},
|
||||
NSEventType::LeftMouseDown | NSEventType::RightMouseDown | NSEventType::OtherMouseDown => {
|
||||
let button = event.buttonNumber() as u32;
|
||||
let button = unsafe { event.buttonNumber() } as u32;
|
||||
app_state.maybe_queue_with_handler(move |app, event_loop| {
|
||||
app.device_event(event_loop, None, DeviceEvent::Button {
|
||||
button,
|
||||
@@ -129,7 +126,7 @@ fn maybe_dispatch_device_event(app_state: &Rc<AppState>, event: &NSEvent) {
|
||||
});
|
||||
},
|
||||
NSEventType::LeftMouseUp | NSEventType::RightMouseUp | NSEventType::OtherMouseUp => {
|
||||
let button = event.buttonNumber() as u32;
|
||||
let button = unsafe { event.buttonNumber() } as u32;
|
||||
app_state.maybe_queue_with_handler(move |app, event_loop| {
|
||||
app.device_event(event_loop, None, DeviceEvent::Button {
|
||||
button,
|
||||
@@ -144,7 +141,7 @@ fn maybe_dispatch_device_event(app_state: &Rc<AppState>, event: &NSEvent) {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use objc2::rc::Retained;
|
||||
use objc2::{ClassType, define_class, msg_send};
|
||||
use objc2::{define_class, msg_send, ClassType};
|
||||
use objc2_app_kit::NSResponder;
|
||||
use objc2_foundation::NSObject;
|
||||
|
||||
@@ -156,14 +153,16 @@ mod tests {
|
||||
let Some(mtm) = MainThreadMarker::new() else { return };
|
||||
|
||||
// Create a new application, without making it the shared application.
|
||||
let app = NSApplication::new(mtm);
|
||||
let app = unsafe { 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.
|
||||
// let event = super::super::event::dummy_event().unwrap();
|
||||
// app.sendEvent(&event)
|
||||
// unsafe {
|
||||
// let event = super::super::event::dummy_event().unwrap();
|
||||
// app.sendEvent(&event)
|
||||
// }
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -8,16 +8,16 @@ use dispatch2::MainThreadBound;
|
||||
use objc2::MainThreadMarker;
|
||||
use objc2_app_kit::{NSApplication, NSApplicationActivationPolicy, NSRunningApplication};
|
||||
use objc2_foundation::NSNotification;
|
||||
use winit_common::core_foundation::{EventLoopProxy, MainRunLoop};
|
||||
use winit_common::core_foundation::EventLoopProxy;
|
||||
use winit_common::event_handler::EventHandler;
|
||||
use winit_core::application::ApplicationHandler;
|
||||
use winit_core::event::{StartCause, WindowEvent};
|
||||
use winit_core::event_loop::ControlFlow;
|
||||
use winit_core::window::WindowId;
|
||||
|
||||
use super::event_loop::{ActiveEventLoop, notify_windows_of_exit, stop_app_immediately};
|
||||
use super::event_loop::{notify_windows_of_exit, stop_app_immediately, ActiveEventLoop};
|
||||
use super::menu;
|
||||
use super::observer::EventLoopWaker;
|
||||
use super::observer::{EventLoopWaker, RunLoop};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct AppState {
|
||||
@@ -25,7 +25,7 @@ pub(super) struct AppState {
|
||||
activation_policy: Option<NSApplicationActivationPolicy>,
|
||||
default_menu: bool,
|
||||
activate_ignoring_other_apps: bool,
|
||||
run_loop: MainRunLoop,
|
||||
run_loop: RunLoop,
|
||||
event_loop_proxy: Arc<EventLoopProxy>,
|
||||
event_handler: EventHandler,
|
||||
stop_on_launch: Cell<bool>,
|
||||
@@ -68,7 +68,7 @@ impl AppState {
|
||||
activation_policy,
|
||||
default_menu,
|
||||
activate_ignoring_other_apps,
|
||||
run_loop: MainRunLoop::get(mtm),
|
||||
run_loop: RunLoop::main(mtm),
|
||||
event_loop_proxy,
|
||||
event_handler: EventHandler::new(),
|
||||
stop_on_launch: Cell::new(false),
|
||||
@@ -99,6 +99,7 @@ impl AppState {
|
||||
// NOTE: This notification will, globally, only be emitted once,
|
||||
// no matter how many `EventLoop`s the user creates.
|
||||
pub fn did_finish_launching(self: &Rc<Self>, _notification: &NSNotification) {
|
||||
trace_scope!("NSApplicationDidFinishLaunchingNotification");
|
||||
self.is_launched.set(true);
|
||||
|
||||
let app = NSApplication::sharedApplication(self.mtm);
|
||||
@@ -116,7 +117,7 @@ impl AppState {
|
||||
// - https://github.com/rust-windowing/winit/issues/261
|
||||
// - https://github.com/rust-windowing/winit/issues/3958
|
||||
let is_bundled =
|
||||
NSRunningApplication::currentApplication().bundleIdentifier().is_some();
|
||||
unsafe { NSRunningApplication::currentApplication().bundleIdentifier().is_some() };
|
||||
if !is_bundled {
|
||||
app.setActivationPolicy(NSApplicationActivationPolicy::Regular);
|
||||
}
|
||||
@@ -153,6 +154,7 @@ impl AppState {
|
||||
}
|
||||
|
||||
pub fn will_terminate(self: &Rc<Self>, _notification: &NSNotification) {
|
||||
trace_scope!("NSApplicationWillTerminateNotification");
|
||||
let app = NSApplication::sharedApplication(self.mtm);
|
||||
notify_windows_of_exit(&app);
|
||||
self.event_handler.terminate();
|
||||
@@ -263,7 +265,7 @@ impl AppState {
|
||||
if !pending_redraw.contains(&window_id) {
|
||||
pending_redraw.push(window_id);
|
||||
}
|
||||
self.run_loop.wake_up();
|
||||
self.run_loop.wakeup();
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
@@ -308,7 +310,6 @@ impl AppState {
|
||||
// Called by RunLoopObserver after finishing waiting for new events
|
||||
pub fn wakeup(self: &Rc<Self>) {
|
||||
// Return when in event handler due to https://github.com/rust-windowing/winit/issues/1779
|
||||
// (we have registered to observe all modes, including modal event loops).
|
||||
if !self.event_handler.ready() || !self.is_running() {
|
||||
return;
|
||||
}
|
||||
@@ -337,7 +338,8 @@ impl AppState {
|
||||
// Called by RunLoopObserver before waiting for new events
|
||||
pub fn cleared(self: &Rc<Self>) {
|
||||
// Return when in event handler due to https://github.com/rust-windowing/winit/issues/1779
|
||||
// (we have registered to observe all modes, including modal event loops).
|
||||
// XXX: how does it make sense that `event_handler.ready()` can ever return `false` here if
|
||||
// we're about to return to the `CFRunLoop` to poll for new events?
|
||||
if !self.event_handler.ready() || !self.is_running() {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -4,13 +4,10 @@ use std::sync::OnceLock;
|
||||
|
||||
use objc2::rc::Retained;
|
||||
use objc2::runtime::Sel;
|
||||
use objc2::{AllocAnyThread, ClassType, available, msg_send, sel};
|
||||
use objc2_app_kit::{
|
||||
NSBitmapImageRep, NSCursor, NSCursorFrameResizeDirections, NSCursorFrameResizePosition,
|
||||
NSDeviceRGBColorSpace, NSImage,
|
||||
};
|
||||
use objc2::{available, msg_send, sel, AllocAnyThread, ClassType};
|
||||
use objc2_app_kit::{NSBitmapImageRep, NSCursor, NSDeviceRGBColorSpace, NSImage};
|
||||
use objc2_foundation::{
|
||||
NSData, NSDictionary, NSNumber, NSObject, NSPoint, NSSize, NSString, ns_string,
|
||||
ns_string, NSData, NSDictionary, NSNumber, NSObject, NSPoint, NSSize, NSString,
|
||||
};
|
||||
use winit_core::cursor::{CursorIcon, CursorImage, CustomCursorProvider, CustomCursorSource};
|
||||
use winit_core::error::{NotSupportedError, RequestError};
|
||||
@@ -34,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())
|
||||
},
|
||||
};
|
||||
|
||||
@@ -65,8 +62,10 @@ 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 = NSImage::initWithSize(NSImage::alloc(), NSSize::new(width.into(), height.into()));
|
||||
image.addRepresentation(&bitmap);
|
||||
let image = unsafe {
|
||||
NSImage::initWithSize(NSImage::alloc(), NSSize::new(width.into(), height.into()))
|
||||
};
|
||||
unsafe { image.addRepresentation(&bitmap) };
|
||||
|
||||
let hotspot = NSPoint::new(cursor.hotspot_x() as f64, cursor.hotspot_y() as f64);
|
||||
|
||||
@@ -141,9 +140,12 @@ unsafe fn load_webkit_cursor(name: &NSString) -> Retained<NSCursor> {
|
||||
|
||||
// TODO: Handle PLists better
|
||||
let info_path = cursor_path.stringByAppendingPathComponent(ns_string!("info.plist"));
|
||||
#[allow(deprecated)]
|
||||
let info: Retained<NSDictionary<NSObject, NSObject>> =
|
||||
unsafe { NSDictionary::dictionaryWithContentsOfFile(&info_path) }.unwrap();
|
||||
let info: Retained<NSDictionary<NSObject, NSObject>> = unsafe {
|
||||
msg_send![
|
||||
<NSDictionary<NSObject, NSObject>>::class(),
|
||||
dictionaryWithContentsOfFile: &*info_path,
|
||||
]
|
||||
};
|
||||
let mut x = 0.0;
|
||||
if let Some(n) = info.objectForKey(ns_string!("hotx")) {
|
||||
if let Ok(n) = n.downcast::<NSNumber>() {
|
||||
@@ -207,155 +209,23 @@ pub(crate) fn cursor_from_icon(icon: CursorIcon) -> Retained<NSCursor> {
|
||||
CursorIcon::NotAllowed | CursorIcon::NoDrop => NSCursor::operationNotAllowedCursor(),
|
||||
CursorIcon::ContextMenu => NSCursor::contextualMenuCursor(),
|
||||
CursorIcon::Crosshair => NSCursor::crosshairCursor(),
|
||||
CursorIcon::EResize => {
|
||||
if available!(macos = 15.0) {
|
||||
NSCursor::frameResizeCursorFromPosition_inDirections(
|
||||
NSCursorFrameResizePosition::Right,
|
||||
NSCursorFrameResizeDirections::Outward,
|
||||
)
|
||||
} else {
|
||||
NSCursor::resizeRightCursor()
|
||||
}
|
||||
},
|
||||
CursorIcon::NResize => {
|
||||
if available!(macos = 15.0) {
|
||||
NSCursor::frameResizeCursorFromPosition_inDirections(
|
||||
NSCursorFrameResizePosition::Top,
|
||||
NSCursorFrameResizeDirections::Outward,
|
||||
)
|
||||
} else {
|
||||
NSCursor::resizeUpCursor()
|
||||
}
|
||||
},
|
||||
CursorIcon::WResize => {
|
||||
if available!(macos = 15.0) {
|
||||
NSCursor::frameResizeCursorFromPosition_inDirections(
|
||||
NSCursorFrameResizePosition::Left,
|
||||
NSCursorFrameResizeDirections::Outward,
|
||||
)
|
||||
} else {
|
||||
NSCursor::resizeLeftCursor()
|
||||
}
|
||||
},
|
||||
CursorIcon::SResize => {
|
||||
if available!(macos = 15.0) {
|
||||
NSCursor::frameResizeCursorFromPosition_inDirections(
|
||||
NSCursorFrameResizePosition::Bottom,
|
||||
NSCursorFrameResizeDirections::Outward,
|
||||
)
|
||||
} else {
|
||||
NSCursor::resizeDownCursor()
|
||||
}
|
||||
},
|
||||
CursorIcon::EwResize => {
|
||||
if available!(macos = 15.0) {
|
||||
NSCursor::frameResizeCursorFromPosition_inDirections(
|
||||
NSCursorFrameResizePosition::Right,
|
||||
NSCursorFrameResizeDirections::All,
|
||||
)
|
||||
} else {
|
||||
NSCursor::resizeLeftRightCursor()
|
||||
}
|
||||
},
|
||||
CursorIcon::NsResize => {
|
||||
if available!(macos = 15.0) {
|
||||
NSCursor::frameResizeCursorFromPosition_inDirections(
|
||||
NSCursorFrameResizePosition::Top,
|
||||
NSCursorFrameResizeDirections::All,
|
||||
)
|
||||
} else {
|
||||
NSCursor::resizeUpDownCursor()
|
||||
}
|
||||
},
|
||||
CursorIcon::NeResize => {
|
||||
if available!(macos = 15.0) {
|
||||
NSCursor::frameResizeCursorFromPosition_inDirections(
|
||||
NSCursorFrameResizePosition::TopRight,
|
||||
NSCursorFrameResizeDirections::Outward,
|
||||
)
|
||||
} else {
|
||||
_windowResizeNorthEastCursor()
|
||||
}
|
||||
},
|
||||
CursorIcon::NwResize => {
|
||||
if available!(macos = 15.0) {
|
||||
NSCursor::frameResizeCursorFromPosition_inDirections(
|
||||
NSCursorFrameResizePosition::TopLeft,
|
||||
NSCursorFrameResizeDirections::Outward,
|
||||
)
|
||||
} else {
|
||||
_windowResizeNorthWestCursor()
|
||||
}
|
||||
},
|
||||
CursorIcon::SeResize => {
|
||||
if available!(macos = 15.0) {
|
||||
NSCursor::frameResizeCursorFromPosition_inDirections(
|
||||
NSCursorFrameResizePosition::BottomRight,
|
||||
NSCursorFrameResizeDirections::Outward,
|
||||
)
|
||||
} else {
|
||||
_windowResizeSouthEastCursor()
|
||||
}
|
||||
},
|
||||
CursorIcon::SwResize => {
|
||||
if available!(macos = 15.0) {
|
||||
NSCursor::frameResizeCursorFromPosition_inDirections(
|
||||
NSCursorFrameResizePosition::BottomLeft,
|
||||
NSCursorFrameResizeDirections::Outward,
|
||||
)
|
||||
} else {
|
||||
_windowResizeSouthWestCursor()
|
||||
}
|
||||
},
|
||||
CursorIcon::NeswResize => {
|
||||
if available!(macos = 15.0) {
|
||||
NSCursor::frameResizeCursorFromPosition_inDirections(
|
||||
NSCursorFrameResizePosition::TopRight,
|
||||
NSCursorFrameResizeDirections::All,
|
||||
)
|
||||
} else {
|
||||
_windowResizeNorthEastSouthWestCursor()
|
||||
}
|
||||
},
|
||||
CursorIcon::NwseResize => {
|
||||
if available!(macos = 15.0) {
|
||||
NSCursor::frameResizeCursorFromPosition_inDirections(
|
||||
NSCursorFrameResizePosition::TopLeft,
|
||||
NSCursorFrameResizeDirections::All,
|
||||
)
|
||||
} else {
|
||||
_windowResizeNorthWestSouthEastCursor()
|
||||
}
|
||||
},
|
||||
CursorIcon::ColResize => {
|
||||
if available!(macos = 15.0) {
|
||||
NSCursor::columnResizeCursor()
|
||||
} else {
|
||||
NSCursor::resizeLeftRightCursor()
|
||||
}
|
||||
},
|
||||
CursorIcon::RowResize => {
|
||||
if available!(macos = 15.0) {
|
||||
NSCursor::rowResizeCursor()
|
||||
} else {
|
||||
NSCursor::resizeUpDownCursor()
|
||||
}
|
||||
},
|
||||
CursorIcon::ZoomIn => {
|
||||
if available!(macos = 15.0) {
|
||||
NSCursor::zoomInCursor()
|
||||
} else {
|
||||
_zoomInCursor()
|
||||
}
|
||||
},
|
||||
CursorIcon::ZoomOut => {
|
||||
if available!(macos = 15.0) {
|
||||
NSCursor::zoomOutCursor()
|
||||
} else {
|
||||
_zoomOutCursor()
|
||||
}
|
||||
},
|
||||
CursorIcon::EResize => NSCursor::resizeRightCursor(),
|
||||
CursorIcon::NResize => NSCursor::resizeUpCursor(),
|
||||
CursorIcon::WResize => NSCursor::resizeLeftCursor(),
|
||||
CursorIcon::SResize => NSCursor::resizeDownCursor(),
|
||||
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 => _zoomInCursor(),
|
||||
CursorIcon::ZoomOut if available!(macos = 15.0) => unsafe { NSCursor::zoomOutCursor() },
|
||||
CursorIcon::ZoomOut => _zoomOutCursor(),
|
||||
CursorIcon::NeResize => _windowResizeNorthEastCursor(),
|
||||
CursorIcon::NwResize => _windowResizeNorthWestCursor(),
|
||||
CursorIcon::SeResize => _windowResizeSouthEastCursor(),
|
||||
CursorIcon::SwResize => _windowResizeSouthWestCursor(),
|
||||
CursorIcon::NeswResize => _windowResizeNorthEastSouthWestCursor(),
|
||||
CursorIcon::NwseResize => _windowResizeNorthWestSouthEastCursor(),
|
||||
// This is the wrong semantics for `Wait`, but it's the same as
|
||||
// what's used in Safari and Chrome.
|
||||
CursorIcon::Wait | CursorIcon::Progress => busyButClickableCursor(),
|
||||
|
||||
@@ -67,7 +67,9 @@ 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 = ns_event.charactersIgnoringModifiers().map(|s| s.to_string()).unwrap_or_default();
|
||||
let string = unsafe { 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();
|
||||
@@ -83,7 +85,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 = ns_event.keyCode();
|
||||
let scancode = unsafe { 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.
|
||||
@@ -93,7 +95,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 = ns_event.characters().map(|s| s.to_string()).unwrap_or_default();
|
||||
let characters = unsafe { ns_event.characters() }.map(|s| s.to_string()).unwrap_or_default();
|
||||
let text_with_all_modifiers = if characters.is_empty() {
|
||||
None
|
||||
} else {
|
||||
@@ -109,13 +111,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 = ns_event.modifierFlags();
|
||||
let modifiers = unsafe { 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 German layout- one
|
||||
// include its effect in the key. For example if -on the Germay 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.
|
||||
@@ -300,15 +302,15 @@ const NX_DEVICERALTKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x000000
|
||||
const NX_DEVICERCTLKEYMASK: NSEventModifierFlags = NSEventModifierFlags(0x00002000);
|
||||
|
||||
pub(super) fn lalt_pressed(event: &NSEvent) -> bool {
|
||||
event.modifierFlags().contains(NX_DEVICELALTKEYMASK)
|
||||
unsafe { event.modifierFlags() }.contains(NX_DEVICELALTKEYMASK)
|
||||
}
|
||||
|
||||
pub(super) fn ralt_pressed(event: &NSEvent) -> bool {
|
||||
event.modifierFlags().contains(NX_DEVICERALTKEYMASK)
|
||||
unsafe { event.modifierFlags() }.contains(NX_DEVICERALTKEYMASK)
|
||||
}
|
||||
|
||||
pub(super) fn event_mods(event: &NSEvent) -> Modifiers {
|
||||
let flags = event.modifierFlags();
|
||||
let flags = unsafe { event.modifierFlags() };
|
||||
let mut state = ModifiersState::empty();
|
||||
let mut pressed_mods = ModifiersKeys::empty();
|
||||
|
||||
@@ -332,7 +334,8 @@ pub(super) fn event_mods(event: &NSEvent) -> Modifiers {
|
||||
}
|
||||
|
||||
pub(super) fn dummy_event() -> Option<Retained<NSEvent>> {
|
||||
NSEvent::otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2(
|
||||
unsafe {
|
||||
NSEvent::otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2(
|
||||
NSEventType::ApplicationDefined,
|
||||
NSPoint::new(0.0, 0.0),
|
||||
NSEventModifierFlags(0),
|
||||
@@ -343,6 +346,7 @@ pub(super) fn dummy_event() -> Option<Retained<NSEvent>> {
|
||||
0,
|
||||
0,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn physicalkey_to_scancode(physical_key: PhysicalKey) -> Option<u32> {
|
||||
|
||||
@@ -2,19 +2,15 @@ use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use objc2::rc::{Retained, autoreleasepool};
|
||||
use objc2::rc::{autoreleasepool, Retained};
|
||||
use objc2::runtime::ProtocolObject;
|
||||
use objc2::{MainThreadMarker, available};
|
||||
use objc2::{available, MainThreadMarker};
|
||||
use objc2_app_kit::{
|
||||
NSApplication, NSApplicationActivationPolicy, NSApplicationDidFinishLaunchingNotification,
|
||||
NSApplicationWillTerminateNotification, NSWindow,
|
||||
};
|
||||
use objc2_core_foundation::{CFIndex, CFRunLoopActivity, kCFRunLoopCommonModes};
|
||||
use objc2_foundation::{NSNotificationCenter, NSObjectProtocol};
|
||||
use rwh_06::HasDisplayHandle;
|
||||
use tracing::debug_span;
|
||||
use winit_common::core_foundation::{MainRunLoop, MainRunLoopObserver, tracing_observers};
|
||||
use winit_common::foundation::create_observer;
|
||||
use winit_core::application::ApplicationHandler;
|
||||
use winit_core::cursor::{CustomCursor as CoreCustomCursor, CustomCursorSource};
|
||||
use winit_core::error::{EventLoopError, RequestError};
|
||||
@@ -31,8 +27,10 @@ use super::app_state::AppState;
|
||||
use super::cursor::CustomCursor;
|
||||
use super::event::dummy_event;
|
||||
use super::monitor;
|
||||
use crate::ActivationPolicy;
|
||||
use super::notification_center::create_observer;
|
||||
use super::observer::setup_control_flow_observers;
|
||||
use crate::window::Window;
|
||||
use crate::ActivationPolicy;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ActiveEventLoop {
|
||||
@@ -152,10 +150,6 @@ pub struct EventLoop {
|
||||
// Though we do still need to keep the observers around to prevent them from being deallocated.
|
||||
_did_finish_launching_observer: Retained<ProtocolObject<dyn NSObjectProtocol>>,
|
||||
_will_terminate_observer: Retained<ProtocolObject<dyn NSObjectProtocol>>,
|
||||
|
||||
_tracing_observers: Option<(MainRunLoopObserver, MainRunLoopObserver)>,
|
||||
_before_waiting_observer: MainRunLoopObserver,
|
||||
_after_waiting_observer: MainRunLoopObserver,
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
||||
@@ -197,7 +191,7 @@ impl EventLoop {
|
||||
// Override `sendEvent:` on the application to forward to our application state.
|
||||
override_send_event(&app);
|
||||
|
||||
let center = NSNotificationCenter::defaultCenter();
|
||||
let center = unsafe { NSNotificationCenter::defaultCenter() };
|
||||
|
||||
let weak_app_state = Rc::downgrade(&app_state);
|
||||
let _did_finish_launching_observer = create_observer(
|
||||
@@ -205,7 +199,6 @@ impl EventLoop {
|
||||
// `applicationDidFinishLaunching:`
|
||||
unsafe { NSApplicationDidFinishLaunchingNotification },
|
||||
move |notification| {
|
||||
let _entered = debug_span!("NSApplicationDidFinishLaunchingNotification").entered();
|
||||
if let Some(app_state) = weak_app_state.upgrade() {
|
||||
app_state.did_finish_launching(notification);
|
||||
}
|
||||
@@ -218,45 +211,13 @@ impl EventLoop {
|
||||
// `applicationWillTerminate:`
|
||||
unsafe { NSApplicationWillTerminateNotification },
|
||||
move |notification| {
|
||||
let _entered = debug_span!("NSApplicationWillTerminateNotification").entered();
|
||||
if let Some(app_state) = weak_app_state.upgrade() {
|
||||
app_state.will_terminate(notification);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
let main_loop = MainRunLoop::get(mtm);
|
||||
let mode = unsafe { kCFRunLoopCommonModes }.unwrap();
|
||||
|
||||
// Tracing observers have the lowest and highest orderings.
|
||||
let _tracing_observers = tracing_observers(mtm).inspect(|(start, end)| {
|
||||
main_loop.add_observer(start, mode);
|
||||
main_loop.add_observer(end, mode);
|
||||
});
|
||||
|
||||
let app_state_clone = Rc::clone(&app_state);
|
||||
let _before_waiting_observer = MainRunLoopObserver::new(
|
||||
mtm,
|
||||
CFRunLoopActivity::BeforeWaiting,
|
||||
true,
|
||||
// Queued with the second-lowest priority (tracing observers use the lowest) to ensure
|
||||
// it is processed after other observers.
|
||||
CFIndex::MAX - 1,
|
||||
move |_| app_state_clone.cleared(),
|
||||
);
|
||||
main_loop.add_observer(&_before_waiting_observer, mode);
|
||||
|
||||
let app_state_clone = Rc::clone(&app_state);
|
||||
let _after_waiting_observer = MainRunLoopObserver::new(
|
||||
mtm,
|
||||
CFRunLoopActivity::AfterWaiting,
|
||||
true,
|
||||
// Queued with the second-highest priority (tracing observers use the highest) to
|
||||
// ensure it is processed before other observers.
|
||||
CFIndex::MIN + 1,
|
||||
move |_| app_state_clone.wakeup(),
|
||||
);
|
||||
main_loop.add_observer(&_after_waiting_observer, mode);
|
||||
setup_control_flow_observers(mtm);
|
||||
|
||||
Ok(EventLoop {
|
||||
app,
|
||||
@@ -264,9 +225,6 @@ impl EventLoop {
|
||||
window_target: ActiveEventLoop { app_state, mtm },
|
||||
_did_finish_launching_observer,
|
||||
_will_terminate_observer,
|
||||
_tracing_observers,
|
||||
_before_waiting_observer,
|
||||
_after_waiting_observer,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -274,6 +232,10 @@ impl EventLoop {
|
||||
&self.window_target
|
||||
}
|
||||
|
||||
pub fn run_app<A: ApplicationHandler>(mut self, app: A) -> Result<(), EventLoopError> {
|
||||
self.run_app_on_demand(app)
|
||||
}
|
||||
|
||||
// NB: we don't base this on `pump_events` because for `MacOs` we can't support
|
||||
// `pump_events` elegantly (we just ask to run the loop for a "short" amount of
|
||||
// time and so a layered implementation would end up using a lot of CPU due to
|
||||
|
||||
@@ -6,7 +6,7 @@ use std::ffi::c_void;
|
||||
|
||||
use objc2::ffi::NSInteger;
|
||||
use objc2::runtime::AnyObject;
|
||||
use objc2_core_foundation::{CFString, CFUUID, cf_type};
|
||||
use objc2_core_foundation::{cf_type, CFString, CFUUID};
|
||||
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")]
|
||||
unsafe extern "C" {
|
||||
extern "C" {
|
||||
pub fn CGDisplayCreateUUIDFromDisplayID(display: CGDirectDisplayID) -> *mut CFUUID;
|
||||
|
||||
pub fn CGDisplayGetDisplayIDFromUUID(uuid: &CFUUID) -> CGDirectDisplayID;
|
||||
}
|
||||
|
||||
#[link(name = "CoreGraphics", kind = "framework")]
|
||||
unsafe extern "C" {
|
||||
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")]
|
||||
unsafe extern "C" {
|
||||
extern "C" {
|
||||
pub static kTISPropertyUnicodeKeyLayoutData: &'static CFString;
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
//! ```
|
||||
//! use objc2::rc::Retained;
|
||||
//! use objc2::runtime::ProtocolObject;
|
||||
//! use objc2::{DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send};
|
||||
//! use objc2::{define_class, msg_send, DefinedClass, MainThreadMarker, MainThreadOnly};
|
||||
//! use objc2_app_kit::{NSApplication, NSApplicationDelegate};
|
||||
//! use objc2_foundation::{NSArray, NSObject, NSObjectProtocol, NSURL};
|
||||
//! use winit::event_loop::EventLoop;
|
||||
@@ -76,6 +76,7 @@ mod event_loop;
|
||||
mod ffi;
|
||||
mod menu;
|
||||
mod monitor;
|
||||
mod notification_center;
|
||||
mod observer;
|
||||
mod view;
|
||||
mod window;
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use objc2::rc::Retained;
|
||||
use objc2::runtime::Sel;
|
||||
use objc2::{MainThreadMarker, sel};
|
||||
use objc2::{sel, MainThreadMarker};
|
||||
use objc2_app_kit::{NSApplication, NSEventModifierFlags, NSMenu, NSMenuItem};
|
||||
use objc2_foundation::{NSBundle, NSProcessInfo, NSString, ns_string};
|
||||
use objc2_foundation::{ns_string, NSBundle, NSProcessInfo, NSString};
|
||||
|
||||
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));
|
||||
|
||||
app.setServicesMenu(Some(&services_menu));
|
||||
unsafe { app.setServicesMenu(Some(&services_menu)) };
|
||||
app.setMainMenu(Some(&menubar));
|
||||
}
|
||||
|
||||
|
||||
@@ -7,16 +7,16 @@ use std::{fmt, ptr};
|
||||
|
||||
use dispatch2::run_on_main;
|
||||
use dpi::{LogicalPosition, PhysicalPosition, PhysicalSize};
|
||||
use objc2::MainThreadMarker;
|
||||
use objc2::rc::Retained;
|
||||
use objc2::MainThreadMarker;
|
||||
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::{CVDisplayLink, CVTimeFlags, kCVReturnSuccess};
|
||||
use objc2_foundation::{NSNumber, NSPoint, NSRect, ns_string};
|
||||
use objc2_core_video::{kCVReturnSuccess, CVDisplayLink, CVTimeFlags};
|
||||
use objc2_foundation::{ns_string, NSNumber, NSPoint, NSRect};
|
||||
use tracing::warn;
|
||||
use winit_core::monitor::{MonitorHandleProvider, VideoMode};
|
||||
|
||||
@@ -65,33 +65,35 @@ impl VideoModeHandle {
|
||||
native_mode: NativeDisplayMode,
|
||||
refresh_rate_millihertz: Option<NonZeroU32>,
|
||||
) -> Self {
|
||||
// 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
|
||||
};
|
||||
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
|
||||
};
|
||||
|
||||
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,
|
||||
);
|
||||
|
||||
Self { mode, monitor: monitor.clone(), native_mode }
|
||||
VideoModeHandle { mode, monitor: monitor.clone(), native_mode }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -135,11 +137,11 @@ impl MonitorHandle {
|
||||
|
||||
fn refresh_rate_millihertz(&self) -> Option<NonZeroU32> {
|
||||
let current_display_mode =
|
||||
NativeDisplayMode(CGDisplayCopyDisplayMode(self.display_id()).unwrap());
|
||||
NativeDisplayMode(unsafe { CGDisplayCopyDisplayMode(self.display_id()) }.unwrap());
|
||||
refresh_rate_millihertz(self.display_id(), ¤t_display_mode)
|
||||
}
|
||||
|
||||
pub fn video_mode_handles(&self) -> impl Iterator<Item = VideoModeHandle> + 'static {
|
||||
pub fn video_mode_handles(&self) -> impl Iterator<Item = VideoModeHandle> {
|
||||
let refresh_rate_millihertz = self.refresh_rate_millihertz();
|
||||
let monitor = self.clone();
|
||||
|
||||
@@ -157,7 +159,7 @@ impl MonitorHandle {
|
||||
};
|
||||
|
||||
modes.into_iter().map(move |mode| {
|
||||
let cg_refresh_rate_hertz = CGDisplayMode::refresh_rate(Some(&mode));
|
||||
let cg_refresh_rate_hertz = unsafe { CGDisplayMode::refresh_rate(Some(&mode)) };
|
||||
|
||||
// CGDisplayModeGetRefreshRate returns 0.0 for any display that
|
||||
// isn't a CRT
|
||||
@@ -200,7 +202,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 = CGDisplayModelNumber(self.display_id());
|
||||
let screen_num = unsafe { CGDisplayModelNumber(self.display_id()) };
|
||||
Some(format!("Monitor #{screen_num}").into())
|
||||
}
|
||||
|
||||
@@ -208,7 +210,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 = CGDisplayBounds(self.display_id());
|
||||
let bounds = unsafe { CGDisplayBounds(self.display_id()) };
|
||||
let position = LogicalPosition::new(bounds.origin.x, bounds.origin.y);
|
||||
Some(position.to_physical(self.scale_factor()))
|
||||
}
|
||||
@@ -223,7 +225,8 @@ impl MonitorHandleProvider for MonitorHandle {
|
||||
}
|
||||
|
||||
fn current_video_mode(&self) -> Option<VideoMode> {
|
||||
let mode = NativeDisplayMode(CGDisplayCopyDisplayMode(self.display_id()).unwrap());
|
||||
let mode =
|
||||
NativeDisplayMode(unsafe { 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)
|
||||
}
|
||||
@@ -261,7 +264,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(CGMainDisplayID()).expect("invalid display ID")
|
||||
MonitorHandle::new(unsafe { CGMainDisplayID() }).expect("invalid display ID")
|
||||
}
|
||||
|
||||
impl fmt::Debug for MonitorHandle {
|
||||
@@ -312,38 +315,40 @@ 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 = CGDisplayBounds(CGMainDisplayID()).size.height;
|
||||
let main_screen_height = unsafe { 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> {
|
||||
let refresh_rate = CGDisplayMode::refresh_rate(Some(&mode.0));
|
||||
if refresh_rate > 0.0 {
|
||||
return NonZeroU32::new((refresh_rate * 1000.0).round() as u32);
|
||||
}
|
||||
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 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();
|
||||
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;
|
||||
}
|
||||
// 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)
|
||||
(time.timeScale as i64)
|
||||
.checked_div(time.timeValue)
|
||||
.map(|v| (v * 1000) as u32)
|
||||
.and_then(NonZeroU32::new)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -352,10 +357,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn uuid_stable() {
|
||||
let primary_id = CGMainDisplayID();
|
||||
|
||||
let handle_a = MonitorHandle::new(primary_id).unwrap();
|
||||
let handle_b = MonitorHandle::new(primary_id).unwrap();
|
||||
let handle_a = MonitorHandle::new(1).unwrap();
|
||||
let handle_b = MonitorHandle::new(1).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());
|
||||
@@ -370,10 +373,8 @@ 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(primary_id).unwrap();
|
||||
let handle1 = MonitorHandle::new(1).unwrap();
|
||||
assert_eq!(handle0, handle1);
|
||||
assert_eq!(handle0.display_id(), handle1.display_id());
|
||||
assert_eq!(handle0.uuid(), handle1.uuid());
|
||||
@@ -394,7 +395,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 _ = CGMainDisplayID();
|
||||
let _ = unsafe { CGMainDisplayID() };
|
||||
|
||||
let handle = MonitorHandle(CFUUID::new(None).unwrap());
|
||||
assert_eq!(handle.display_id(), 0);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
// NOTE: This is symlinked to be contained in both the AppKit and UIKit implementations.
|
||||
use std::ptr::NonNull;
|
||||
|
||||
use block2::RcBlock;
|
||||
@@ -11,7 +12,7 @@ use objc2_foundation::{
|
||||
///
|
||||
/// This is used in Winit as an alternative to declaring an application delegate, as we want to
|
||||
/// give the user full control over those.
|
||||
pub fn create_observer(
|
||||
pub(crate) fn create_observer(
|
||||
center: &NSNotificationCenter,
|
||||
name: &NSNotificationName,
|
||||
handler: impl Fn(&NSNotification) + 'static,
|
||||
@@ -1,10 +1,171 @@
|
||||
//! Utilities for working with `CFRunLoop`.
|
||||
//!
|
||||
//! See Apple's documentation on Run Loops for details:
|
||||
//! <https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html>
|
||||
use std::cell::Cell;
|
||||
use std::ffi::c_void;
|
||||
use std::ptr;
|
||||
use std::time::Instant;
|
||||
|
||||
use objc2::MainThreadMarker;
|
||||
use objc2_core_foundation::{
|
||||
CFAbsoluteTimeGetCurrent, CFRetained, CFRunLoop, CFRunLoopTimer, kCFRunLoopCommonModes,
|
||||
kCFRunLoopCommonModes, kCFRunLoopDefaultMode, CFAbsoluteTimeGetCurrent, CFIndex, CFRetained,
|
||||
CFRunLoop, CFRunLoopActivity, CFRunLoopObserver, CFRunLoopObserverCallBack,
|
||||
CFRunLoopObserverContext, CFRunLoopTimer,
|
||||
};
|
||||
use tracing::error;
|
||||
|
||||
use super::app_state::AppState;
|
||||
|
||||
// begin is queued with the highest priority to ensure it is processed before other observers
|
||||
extern "C-unwind" fn control_flow_begin_handler(
|
||||
_: *mut CFRunLoopObserver,
|
||||
activity: CFRunLoopActivity,
|
||||
_info: *mut c_void,
|
||||
) {
|
||||
match activity {
|
||||
CFRunLoopActivity::AfterWaiting => {
|
||||
AppState::get(MainThreadMarker::new().unwrap()).wakeup();
|
||||
},
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
// end is queued with the lowest priority to ensure it is processed after other observers
|
||||
// without that, LoopExiting would get sent after AboutToWait
|
||||
extern "C-unwind" fn control_flow_end_handler(
|
||||
_: *mut CFRunLoopObserver,
|
||||
activity: CFRunLoopActivity,
|
||||
_info: *mut c_void,
|
||||
) {
|
||||
match activity {
|
||||
CFRunLoopActivity::BeforeWaiting => {
|
||||
AppState::get(MainThreadMarker::new().unwrap()).cleared();
|
||||
},
|
||||
CFRunLoopActivity::Exit => (), // unimplemented!(), // not expected to ever happen
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct RunLoop(CFRetained<CFRunLoop>);
|
||||
|
||||
impl RunLoop {
|
||||
pub fn main(mtm: MainThreadMarker) -> Self {
|
||||
// SAFETY: We have a MainThreadMarker here, which means we know we're on the main thread, so
|
||||
// scheduling (and scheduling a non-`Send` block) to that thread is allowed.
|
||||
let _ = mtm;
|
||||
RunLoop(CFRunLoop::main().unwrap())
|
||||
}
|
||||
|
||||
pub fn wakeup(&self) {
|
||||
self.0.wake_up();
|
||||
}
|
||||
|
||||
unsafe fn add_observer(
|
||||
&self,
|
||||
flags: CFRunLoopActivity,
|
||||
// The lower the value, the sooner this will run
|
||||
priority: CFIndex,
|
||||
handler: CFRunLoopObserverCallBack,
|
||||
context: *mut CFRunLoopObserverContext,
|
||||
) {
|
||||
let observer =
|
||||
unsafe { CFRunLoopObserver::new(None, flags.0, true, priority, handler, context) }
|
||||
.unwrap();
|
||||
self.0.add_observer(Some(&observer), unsafe { kCFRunLoopCommonModes });
|
||||
}
|
||||
|
||||
/// Submit a closure to run on the main thread as the next step in the run loop, before other
|
||||
/// event sources are processed.
|
||||
///
|
||||
/// This is used for running event handlers, as those are not allowed to run re-entrantly.
|
||||
///
|
||||
/// # Implementation
|
||||
///
|
||||
/// This queuing could be implemented in the following several ways with subtle differences in
|
||||
/// timing. This list is sorted in rough order in which they are run:
|
||||
///
|
||||
/// 1. Using `CFRunLoopPerformBlock` or `-[NSRunLoop performBlock:]`.
|
||||
///
|
||||
/// 2. Using `-[NSObject performSelectorOnMainThread:withObject:waitUntilDone:]` or wrapping the
|
||||
/// event in `NSEvent` and posting that to `-[NSApplication postEvent:atStart:]` (both
|
||||
/// creates a custom `CFRunLoopSource`, and signals that to wake up the main event loop).
|
||||
///
|
||||
/// a. `atStart = true`.
|
||||
///
|
||||
/// b. `atStart = false`.
|
||||
///
|
||||
/// 3. `dispatch_async` or `dispatch_async_f`. Note that this may appear before 2b, it does not
|
||||
/// respect the ordering that runloop events have.
|
||||
///
|
||||
/// We choose the first one, both for ease-of-implementation, but mostly for consistency, as we
|
||||
/// want the event to be queued in a way that preserves the order the events originally arrived
|
||||
/// in.
|
||||
///
|
||||
/// As an example, let's assume that we receive two events from the user, a mouse click which we
|
||||
/// handled by queuing it, and a window resize which we handled immediately. If we allowed
|
||||
/// AppKit to choose the ordering when queuing the mouse event, it might get put in the back of
|
||||
/// the queue, and the events would appear out of order to the user of Winit. So we must instead
|
||||
/// put the event at the very front of the queue, to be handled as soon as possible after
|
||||
/// handling whatever event it's currently handling.
|
||||
pub fn queue_closure(&self, closure: impl FnOnce() + 'static) {
|
||||
// Convert `FnOnce()` to `Block<dyn Fn()>`.
|
||||
let closure = Cell::new(Some(closure));
|
||||
let block = block2::RcBlock::new(move || {
|
||||
if let Some(closure) = closure.take() {
|
||||
closure()
|
||||
} else {
|
||||
error!("tried to execute queued closure on main thread twice");
|
||||
}
|
||||
});
|
||||
|
||||
// There are a few common modes (`kCFRunLoopCommonModes`) defined by Cocoa:
|
||||
// - `NSDefaultRunLoopMode`, alias of `kCFRunLoopDefaultMode`.
|
||||
// - `NSEventTrackingRunLoopMode`, used when mouse-dragging and live-resizing a window.
|
||||
// - `NSModalPanelRunLoopMode`, used when running a modal inside the Winit event loop.
|
||||
// - `NSConnectionReplyMode`: TODO.
|
||||
//
|
||||
// We only want to run event handlers in the default mode, as we support running a blocking
|
||||
// modal inside a Winit event handler (see [#1779]) which outrules the modal panel mode, and
|
||||
// resizing such panel window enters the event tracking run loop mode, so we can't directly
|
||||
// trigger events inside that mode either.
|
||||
//
|
||||
// Any events that are queued while running a modal or when live-resizing will instead wait,
|
||||
// and be delivered to the application afterwards.
|
||||
//
|
||||
// [#1779]: https://github.com/rust-windowing/winit/issues/1779
|
||||
let mode = unsafe { kCFRunLoopDefaultMode.unwrap() };
|
||||
|
||||
// SAFETY: The runloop is valid, the mode is a `CFStringRef`, and the block is `'static`.
|
||||
unsafe { self.0.perform_block(Some(mode), Some(&block)) }
|
||||
}
|
||||
}
|
||||
|
||||
pub fn setup_control_flow_observers(mtm: MainThreadMarker) {
|
||||
let run_loop = RunLoop::main(mtm);
|
||||
unsafe {
|
||||
let mut context = CFRunLoopObserverContext {
|
||||
info: ptr::null_mut(),
|
||||
version: 0,
|
||||
retain: None,
|
||||
release: None,
|
||||
copyDescription: None,
|
||||
};
|
||||
run_loop.add_observer(
|
||||
CFRunLoopActivity::AfterWaiting,
|
||||
CFIndex::MIN,
|
||||
Some(control_flow_begin_handler),
|
||||
&mut context as *mut _,
|
||||
);
|
||||
run_loop.add_observer(
|
||||
CFRunLoopActivity::Exit | CFRunLoopActivity::BeforeWaiting,
|
||||
CFIndex::MAX,
|
||||
Some(control_flow_end_handler),
|
||||
&mut context as *mut _,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct EventLoopWaker {
|
||||
|
||||
@@ -1,11 +1,44 @@
|
||||
use objc2_core_graphics::CGError;
|
||||
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 {
|
||||
($s:literal) => {
|
||||
let _crate = $crate::util::TraceGuard::new(module_path!(), $s);
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) struct TraceGuard {
|
||||
module_path: &'static str,
|
||||
called_from_fn: &'static str,
|
||||
}
|
||||
|
||||
impl TraceGuard {
|
||||
#[inline]
|
||||
pub(crate) fn new(module_path: &'static str, called_from_fn: &'static str) -> Self {
|
||||
trace!(target = module_path, "Triggered `{}`", called_from_fn);
|
||||
Self { module_path, called_from_fn }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TraceGuard {
|
||||
#[inline]
|
||||
fn drop(&mut self) {
|
||||
trace!(target = self.module_path, "Completed `{}`", self.called_from_fn);
|
||||
}
|
||||
}
|
||||
|
||||
#[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:?}")))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
#![allow(clippy::unnecessary_cast)]
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::ptr;
|
||||
use std::rc::Rc;
|
||||
|
||||
use dpi::{LogicalPosition, LogicalSize};
|
||||
use objc2::rc::Retained;
|
||||
use objc2::runtime::{AnyObject, Sel};
|
||||
use objc2::{AnyThread, DefinedClass, MainThreadMarker, define_class, msg_send};
|
||||
use objc2::{define_class, msg_send, DefinedClass, MainThreadMarker};
|
||||
use objc2_app_kit::{
|
||||
NSApplication, NSCursor, NSEvent, NSEventPhase, NSResponder, NSTextInputClient, NSTrackingArea,
|
||||
NSTrackingAreaOptions, NSView, NSWindow,
|
||||
NSApplication, NSCursor, NSEvent, NSEventPhase, NSResponder, NSTextInputClient,
|
||||
NSTrackingRectTag, NSView, NSWindow,
|
||||
};
|
||||
use objc2_core_foundation::CGRect;
|
||||
use objc2_foundation::{
|
||||
NSArray, NSAttributedString, NSAttributedStringKey, NSCopying, NSMutableAttributedString,
|
||||
NSNotFound, NSObject, NSPoint, NSRange, NSRect, NSSize, NSString, NSUInteger,
|
||||
};
|
||||
use tracing::{debug_span, trace_span};
|
||||
use winit_core::event::{
|
||||
DeviceEvent, ElementState, Ime, KeyEvent, Modifiers, MouseButton, MouseScrollDelta,
|
||||
PointerKind, PointerSource, TouchPhase, WindowEvent,
|
||||
@@ -119,6 +119,7 @@ pub struct ViewState {
|
||||
ime_size: Cell<NSSize>,
|
||||
modifiers: Cell<Modifiers>,
|
||||
phys_modifiers: RefCell<HashMap<Key, ModLocationMask>>,
|
||||
tracking_rect: Cell<Option<NSTrackingRectTag>>,
|
||||
ime_state: Cell<ImeState>,
|
||||
input_source: RefCell<String>,
|
||||
|
||||
@@ -130,6 +131,7 @@ pub struct ViewState {
|
||||
/// True if the current key event should be forwarded
|
||||
/// to the application, even during IME
|
||||
forward_key_to_app: Cell<bool>,
|
||||
|
||||
marked_text: RefCell<Retained<NSMutableAttributedString>>,
|
||||
accepts_first_mouse: bool,
|
||||
|
||||
@@ -151,17 +153,41 @@ define_class!(
|
||||
true
|
||||
}
|
||||
|
||||
#[unsafe(method(viewDidMoveToWindow))]
|
||||
fn view_did_move_to_window(&self) {
|
||||
trace_scope!("viewDidMoveToWindow");
|
||||
if let Some(tracking_rect) = self.ivars().tracking_rect.take() {
|
||||
self.removeTrackingRect(tracking_rect);
|
||||
}
|
||||
|
||||
let rect = self.frame();
|
||||
let tracking_rect = unsafe {
|
||||
self.addTrackingRect_owner_userData_assumeInside(rect, self, ptr::null_mut(), false)
|
||||
};
|
||||
assert_ne!(tracking_rect, 0, "failed adding tracking rect");
|
||||
self.ivars().tracking_rect.set(Some(tracking_rect));
|
||||
}
|
||||
|
||||
// Not a normal method on `NSView`, it's triggered by `NSViewFrameDidChangeNotification`.
|
||||
#[unsafe(method(viewFrameDidChangeNotification:))]
|
||||
fn frame_did_change(&self, _notification: Option<&AnyObject>) {
|
||||
let _entered = debug_span!("NSViewFrameDidChangeNotification").entered();
|
||||
trace_scope!("NSViewFrameDidChangeNotification");
|
||||
if let Some(tracking_rect) = self.ivars().tracking_rect.take() {
|
||||
self.removeTrackingRect(tracking_rect);
|
||||
}
|
||||
|
||||
let rect = self.frame();
|
||||
let tracking_rect = unsafe {
|
||||
self.addTrackingRect_owner_userData_assumeInside(rect, self, ptr::null_mut(), false)
|
||||
};
|
||||
assert_ne!(tracking_rect, 0, "failed adding tracking rect");
|
||||
self.ivars().tracking_rect.set(Some(tracking_rect));
|
||||
|
||||
// Emit resize event here rather than from windowDidResize because:
|
||||
// 1. When a new window is created as a tab, the frame size may change without a window
|
||||
// resize occurring.
|
||||
// 2. Even when a window resize does occur on a new tabbed window, it contains the wrong
|
||||
// size (includes tab height).
|
||||
let rect = self.frame();
|
||||
let logical_size = LogicalSize::new(rect.size.width as f64, rect.size.height as f64);
|
||||
let size = logical_size.to_physical::<u32>(self.scale_factor());
|
||||
self.queue_event(WindowEvent::SurfaceResized(size));
|
||||
@@ -169,7 +195,7 @@ define_class!(
|
||||
|
||||
#[unsafe(method(drawRect:))]
|
||||
fn draw_rect(&self, _rect: NSRect) {
|
||||
let _entered = debug_span!("drawRect:").entered();
|
||||
trace_scope!("drawRect:");
|
||||
|
||||
self.ivars().app_state.handle_redraw(window_id(&self.window()));
|
||||
|
||||
@@ -178,7 +204,7 @@ define_class!(
|
||||
|
||||
#[unsafe(method(acceptsFirstResponder))]
|
||||
fn accepts_first_responder(&self) -> bool {
|
||||
let _entered = trace_span!("acceptsFirstResponder").entered();
|
||||
trace_scope!("acceptsFirstResponder");
|
||||
true
|
||||
}
|
||||
|
||||
@@ -192,13 +218,13 @@ define_class!(
|
||||
// extension for using `NSTouchBar`
|
||||
#[unsafe(method_id(touchBar))]
|
||||
fn touch_bar(&self) -> Option<Retained<NSObject>> {
|
||||
let _entered = debug_span!("touchBar").entered();
|
||||
trace_scope!("touchBar");
|
||||
None
|
||||
}
|
||||
|
||||
#[unsafe(method(resetCursorRects))]
|
||||
fn reset_cursor_rects(&self) {
|
||||
let _entered = debug_span!("resetCursorRects").entered();
|
||||
trace_scope!("resetCursorRects");
|
||||
let bounds = self.bounds();
|
||||
let cursor_state = self.ivars().cursor_state.borrow();
|
||||
// We correctly invoke `addCursorRect` only from inside `resetCursorRects`
|
||||
@@ -213,13 +239,13 @@ define_class!(
|
||||
unsafe impl NSTextInputClient for WinitView {
|
||||
#[unsafe(method(hasMarkedText))]
|
||||
fn has_marked_text(&self) -> bool {
|
||||
let _entered = debug_span!("hasMarkedText").entered();
|
||||
trace_scope!("hasMarkedText");
|
||||
self.ivars().marked_text.borrow().length() > 0
|
||||
}
|
||||
|
||||
#[unsafe(method(markedRange))]
|
||||
fn marked_range(&self) -> NSRange {
|
||||
let _entered = debug_span!("markedRange").entered();
|
||||
trace_scope!("markedRange");
|
||||
let length = self.ivars().marked_text.borrow().length();
|
||||
if length > 0 {
|
||||
NSRange::new(0, length)
|
||||
@@ -231,7 +257,7 @@ define_class!(
|
||||
|
||||
#[unsafe(method(selectedRange))]
|
||||
fn selected_range(&self) -> NSRange {
|
||||
let _entered = debug_span!("selectedRange").entered();
|
||||
trace_scope!("selectedRange");
|
||||
// Documented to return `{NSNotFound, 0}` if there is no selection.
|
||||
NSRange::new(NSNotFound as NSUInteger, 0)
|
||||
}
|
||||
@@ -244,7 +270,7 @@ define_class!(
|
||||
_replacement_range: NSRange,
|
||||
) {
|
||||
// TODO: Use _replacement_range, requires changing the event to report surrounding text.
|
||||
let _entered = debug_span!("setMarkedText:selectedRange:replacementRange:").entered();
|
||||
trace_scope!("setMarkedText:selectedRange:replacementRange:");
|
||||
|
||||
let (marked_text, string) = if let Some(string) =
|
||||
string.downcast_ref::<NSAttributedString>()
|
||||
@@ -266,7 +292,7 @@ define_class!(
|
||||
self.queue_event(WindowEvent::Ime(Ime::Enabled));
|
||||
}
|
||||
|
||||
if self.hasMarkedText() {
|
||||
if unsafe { self.hasMarkedText() } {
|
||||
self.ivars().ime_state.set(ImeState::Preedit);
|
||||
} else {
|
||||
// In case the preedit was cleared, set IME into the Ground state.
|
||||
@@ -278,15 +304,9 @@ define_class!(
|
||||
// sending a `None` cursor range.
|
||||
None
|
||||
} else {
|
||||
// Clamp to string length to avoid NSRangeException from out-of-bounds
|
||||
// indices sent by macOS IME (e.g. native Pinyin, see
|
||||
// https://github.com/alacritty/alacritty/issues/8791).
|
||||
let len = string.length();
|
||||
let location = selected_range.location.min(len);
|
||||
let end = selected_range.end().min(len);
|
||||
// Convert the selected range from UTF-16 indices to UTF-8 indices.
|
||||
let sub_string_a = string.substringToIndex(location);
|
||||
let sub_string_b = string.substringToIndex(end);
|
||||
let sub_string_a = unsafe { string.substringToIndex(selected_range.location) };
|
||||
let sub_string_b = unsafe { string.substringToIndex(selected_range.end()) };
|
||||
let lowerbound_utf8 = sub_string_a.len();
|
||||
let upperbound_utf8 = sub_string_b.len();
|
||||
Some((lowerbound_utf8, upperbound_utf8))
|
||||
@@ -298,7 +318,7 @@ define_class!(
|
||||
|
||||
#[unsafe(method(unmarkText))]
|
||||
fn unmark_text(&self) {
|
||||
let _entered = debug_span!("unmarkText").entered();
|
||||
trace_scope!("unmarkText");
|
||||
*self.ivars().marked_text.borrow_mut() = NSMutableAttributedString::new();
|
||||
|
||||
let input_context = self.inputContext().expect("input context");
|
||||
@@ -315,7 +335,7 @@ define_class!(
|
||||
|
||||
#[unsafe(method_id(validAttributesForMarkedText))]
|
||||
fn valid_attributes_for_marked_text(&self) -> Retained<NSArray<NSAttributedStringKey>> {
|
||||
let _entered = trace_span!("validAttributesForMarkedText").entered();
|
||||
trace_scope!("validAttributesForMarkedText");
|
||||
NSArray::new()
|
||||
}
|
||||
|
||||
@@ -325,14 +345,13 @@ define_class!(
|
||||
_range: NSRange,
|
||||
_actual_range: *mut NSRange,
|
||||
) -> Option<Retained<NSAttributedString>> {
|
||||
let _entered =
|
||||
trace_span!("attributedSubstringForProposedRange:actualRange:").entered();
|
||||
trace_scope!("attributedSubstringForProposedRange:actualRange:");
|
||||
None
|
||||
}
|
||||
|
||||
#[unsafe(method(characterIndexForPoint:))]
|
||||
fn character_index_for_point(&self, _point: NSPoint) -> NSUInteger {
|
||||
let _entered = debug_span!("characterIndexForPoint:").entered();
|
||||
trace_scope!("characterIndexForPoint:");
|
||||
0
|
||||
}
|
||||
|
||||
@@ -342,7 +361,7 @@ define_class!(
|
||||
_range: NSRange,
|
||||
_actual_range: *mut NSRange,
|
||||
) -> NSRect {
|
||||
let _entered = debug_span!("firstRectForCharacterRange:actualRange:").entered();
|
||||
trace_scope!("firstRectForCharacterRange:actualRange:");
|
||||
|
||||
// Guard when the view is no longer in a window during teardown.
|
||||
let Some(window) = (**self).window() else {
|
||||
@@ -358,7 +377,7 @@ define_class!(
|
||||
#[unsafe(method(insertText:replacementRange:))]
|
||||
fn insert_text(&self, string: &NSObject, _replacement_range: NSRange) {
|
||||
// TODO: Use _replacement_range, requires changing the event to report surrounding text.
|
||||
let _entered = debug_span!("insertText:replacementRange:").entered();
|
||||
trace_scope!("insertText:replacementRange:");
|
||||
|
||||
let string = if let Some(string) = string.downcast_ref::<NSAttributedString>() {
|
||||
string.string().to_string()
|
||||
@@ -372,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 self.hasMarkedText() && self.is_ime_enabled() && !is_control {
|
||||
if unsafe { 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);
|
||||
@@ -383,7 +402,7 @@ define_class!(
|
||||
// "human readable" character happens, i.e. newlines, tabs, and Ctrl+C.
|
||||
#[unsafe(method(doCommandBySelector:))]
|
||||
fn do_command_by_selector(&self, command: Sel) {
|
||||
let _entered = debug_span!("doCommandBySelector:").entered();
|
||||
trace_scope!("doCommandBySelector:");
|
||||
|
||||
// We shouldn't forward any character from just committed text, since we'll end up
|
||||
// sending it twice with some IMEs like Korean one. We'll also always send
|
||||
@@ -395,7 +414,8 @@ define_class!(
|
||||
|
||||
self.ivars().forward_key_to_app.set(true);
|
||||
|
||||
if self.hasMarkedText() && self.ivars().ime_state.get() == ImeState::Preedit {
|
||||
if unsafe { 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);
|
||||
}
|
||||
@@ -422,7 +442,7 @@ define_class!(
|
||||
impl WinitView {
|
||||
#[unsafe(method(keyDown:))]
|
||||
fn key_down(&self, event: &NSEvent) {
|
||||
let _entered = debug_span!("keyDown:").entered();
|
||||
trace_scope!("keyDown:");
|
||||
{
|
||||
let mut prev_input_source = self.ivars().input_source.borrow_mut();
|
||||
let current_input_source = self.current_input_source();
|
||||
@@ -447,7 +467,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]);
|
||||
self.interpretKeyEvents(&events_for_nsview);
|
||||
unsafe { 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 {
|
||||
@@ -470,7 +490,7 @@ define_class!(
|
||||
};
|
||||
|
||||
if !had_ime_input || self.ivars().forward_key_to_app.get() {
|
||||
let key_event = create_key_event(&event, true, event.isARepeat());
|
||||
let key_event = create_key_event(&event, true, unsafe { event.isARepeat() });
|
||||
self.queue_event(WindowEvent::KeyboardInput {
|
||||
device_id: None,
|
||||
event: key_event,
|
||||
@@ -481,7 +501,7 @@ define_class!(
|
||||
|
||||
#[unsafe(method(keyUp:))]
|
||||
fn key_up(&self, event: &NSEvent) {
|
||||
let _entered = debug_span!("keyUp:").entered();
|
||||
trace_scope!("keyUp:");
|
||||
|
||||
let event = replace_event(event, self.option_as_alt());
|
||||
self.update_modifiers(&event, false);
|
||||
@@ -498,14 +518,14 @@ define_class!(
|
||||
|
||||
#[unsafe(method(flagsChanged:))]
|
||||
fn flags_changed(&self, event: &NSEvent) {
|
||||
let _entered = debug_span!("flagsChanged:").entered();
|
||||
trace_scope!("flagsChanged:");
|
||||
|
||||
self.update_modifiers(event, true);
|
||||
}
|
||||
|
||||
#[unsafe(method(insertTab:))]
|
||||
fn insert_tab(&self, _sender: Option<&AnyObject>) {
|
||||
let _entered = debug_span!("insertTab:").entered();
|
||||
trace_scope!("insertTab:");
|
||||
let window = self.window();
|
||||
if let Some(first_responder) = window.firstResponder() {
|
||||
if *first_responder == ***self {
|
||||
@@ -516,7 +536,7 @@ define_class!(
|
||||
|
||||
#[unsafe(method(insertBackTab:))]
|
||||
fn insert_back_tab(&self, _sender: Option<&AnyObject>) {
|
||||
let _entered = debug_span!("insertBackTab:").entered();
|
||||
trace_scope!("insertBackTab:");
|
||||
let window = self.window();
|
||||
if let Some(first_responder) = window.firstResponder() {
|
||||
if *first_responder == ***self {
|
||||
@@ -530,14 +550,14 @@ define_class!(
|
||||
#[unsafe(method(cancelOperation:))]
|
||||
fn cancel_operation(&self, _sender: Option<&AnyObject>) {
|
||||
let mtm = MainThreadMarker::from(self);
|
||||
let _entered = debug_span!("cancelOperation:").entered();
|
||||
trace_scope!("cancelOperation:");
|
||||
|
||||
let event = NSApplication::sharedApplication(mtm)
|
||||
.currentEvent()
|
||||
.expect("could not find current event");
|
||||
|
||||
self.update_modifiers(&event, false);
|
||||
let event = create_key_event(&event, true, event.isARepeat());
|
||||
let event = create_key_event(&event, true, unsafe { event.isARepeat() });
|
||||
|
||||
self.queue_event(WindowEvent::KeyboardInput {
|
||||
device_id: None,
|
||||
@@ -559,73 +579,71 @@ define_class!(
|
||||
|
||||
#[unsafe(method(mouseDown:))]
|
||||
fn mouse_down(&self, event: &NSEvent) {
|
||||
let _entered = debug_span!("mouseDown:").entered();
|
||||
trace_scope!("mouseDown:");
|
||||
self.mouse_motion(event);
|
||||
self.mouse_click(event, ElementState::Pressed);
|
||||
}
|
||||
|
||||
#[unsafe(method(mouseUp:))]
|
||||
fn mouse_up(&self, event: &NSEvent) {
|
||||
let _entered = debug_span!("mouseUp:").entered();
|
||||
trace_scope!("mouseUp:");
|
||||
self.mouse_motion(event);
|
||||
self.mouse_click(event, ElementState::Released);
|
||||
}
|
||||
|
||||
#[unsafe(method(rightMouseDown:))]
|
||||
fn right_mouse_down(&self, event: &NSEvent) {
|
||||
let _entered = debug_span!("rightMouseDown:").entered();
|
||||
trace_scope!("rightMouseDown:");
|
||||
self.mouse_motion(event);
|
||||
self.mouse_click(event, ElementState::Pressed);
|
||||
}
|
||||
|
||||
#[unsafe(method(rightMouseUp:))]
|
||||
fn right_mouse_up(&self, event: &NSEvent) {
|
||||
let _entered = debug_span!("rightMouseUp:").entered();
|
||||
trace_scope!("rightMouseUp:");
|
||||
self.mouse_motion(event);
|
||||
self.mouse_click(event, ElementState::Released);
|
||||
}
|
||||
|
||||
#[unsafe(method(otherMouseDown:))]
|
||||
fn other_mouse_down(&self, event: &NSEvent) {
|
||||
let _entered = debug_span!("otherMouseDown:").entered();
|
||||
trace_scope!("otherMouseDown:");
|
||||
self.mouse_motion(event);
|
||||
self.mouse_click(event, ElementState::Pressed);
|
||||
}
|
||||
|
||||
#[unsafe(method(otherMouseUp:))]
|
||||
fn other_mouse_up(&self, event: &NSEvent) {
|
||||
let _entered = debug_span!("otherMouseUp:").entered();
|
||||
trace_scope!("otherMouseUp:");
|
||||
self.mouse_motion(event);
|
||||
self.mouse_click(event, ElementState::Released);
|
||||
}
|
||||
|
||||
// No tracing on these because that would be overly verbose
|
||||
|
||||
#[unsafe(method(mouseMoved:))]
|
||||
fn mouse_moved(&self, event: &NSEvent) {
|
||||
let _entered = debug_span!("mouseMoved:").entered();
|
||||
self.mouse_motion(event);
|
||||
}
|
||||
|
||||
#[unsafe(method(mouseDragged:))]
|
||||
fn mouse_dragged(&self, event: &NSEvent) {
|
||||
let _entered = debug_span!("mouseDragged:").entered();
|
||||
self.mouse_motion(event);
|
||||
}
|
||||
|
||||
#[unsafe(method(rightMouseDragged:))]
|
||||
fn right_mouse_dragged(&self, event: &NSEvent) {
|
||||
let _entered = debug_span!("rightMouseDragged:").entered();
|
||||
self.mouse_motion(event);
|
||||
}
|
||||
|
||||
#[unsafe(method(otherMouseDragged:))]
|
||||
fn other_mouse_dragged(&self, event: &NSEvent) {
|
||||
let _entered = debug_span!("otherMouseDragged:").entered();
|
||||
self.mouse_motion(event);
|
||||
}
|
||||
|
||||
#[unsafe(method(mouseEntered:))]
|
||||
fn mouse_entered(&self, event: &NSEvent) {
|
||||
let _entered = debug_span!("mouseEntered:").entered();
|
||||
trace_scope!("mouseEntered:");
|
||||
|
||||
let position = self.mouse_view_point(event).to_physical(self.scale_factor());
|
||||
|
||||
@@ -639,7 +657,7 @@ define_class!(
|
||||
|
||||
#[unsafe(method(mouseExited:))]
|
||||
fn mouse_exited(&self, event: &NSEvent) {
|
||||
let _entered = debug_span!("mouseExited:").entered();
|
||||
trace_scope!("mouseExited:");
|
||||
|
||||
let position = self.mouse_view_point(event).to_physical(self.scale_factor());
|
||||
|
||||
@@ -653,13 +671,13 @@ define_class!(
|
||||
|
||||
#[unsafe(method(scrollWheel:))]
|
||||
fn scroll_wheel(&self, event: &NSEvent) {
|
||||
let _entered = debug_span!("scrollWheel:").entered();
|
||||
trace_scope!("scrollWheel:");
|
||||
|
||||
self.mouse_motion(event);
|
||||
|
||||
let delta = {
|
||||
let (x, y) = (event.scrollingDeltaX(), event.scrollingDeltaY());
|
||||
if event.hasPreciseScrollingDeltas() {
|
||||
let (x, y) = unsafe { (event.scrollingDeltaX(), event.scrollingDeltaY()) };
|
||||
if unsafe { event.hasPreciseScrollingDeltas() } {
|
||||
let delta = LogicalPosition::new(x, y).to_physical(self.scale_factor());
|
||||
MouseScrollDelta::PixelDelta(delta)
|
||||
} else {
|
||||
@@ -672,10 +690,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 event.momentumPhase() {
|
||||
let phase = match unsafe { event.momentumPhase() } {
|
||||
NSEventPhase::MayBegin | NSEventPhase::Began => TouchPhase::Started,
|
||||
NSEventPhase::Ended | NSEventPhase::Cancelled => TouchPhase::Ended,
|
||||
_ => match event.phase() {
|
||||
_ => match unsafe { event.phase() } {
|
||||
NSEventPhase::MayBegin | NSEventPhase::Began => TouchPhase::Started,
|
||||
NSEventPhase::Ended | NSEventPhase::Cancelled => TouchPhase::Ended,
|
||||
_ => TouchPhase::Moved,
|
||||
@@ -692,12 +710,12 @@ define_class!(
|
||||
|
||||
#[unsafe(method(magnifyWithEvent:))]
|
||||
fn magnify_with_event(&self, event: &NSEvent) {
|
||||
let _entered = debug_span!("magnifyWithEvent:").entered();
|
||||
trace_scope!("magnifyWithEvent:");
|
||||
|
||||
self.mouse_motion(event);
|
||||
|
||||
#[allow(non_upper_case_globals)]
|
||||
let phase = match event.phase() {
|
||||
let phase = match unsafe { event.phase() } {
|
||||
NSEventPhase::Began => TouchPhase::Started,
|
||||
NSEventPhase::Changed => TouchPhase::Moved,
|
||||
NSEventPhase::Cancelled => TouchPhase::Cancelled,
|
||||
@@ -707,14 +725,14 @@ define_class!(
|
||||
|
||||
self.queue_event(WindowEvent::PinchGesture {
|
||||
device_id: None,
|
||||
delta: event.magnification(),
|
||||
delta: unsafe { event.magnification() },
|
||||
phase,
|
||||
});
|
||||
}
|
||||
|
||||
#[unsafe(method(smartMagnifyWithEvent:))]
|
||||
fn smart_magnify_with_event(&self, event: &NSEvent) {
|
||||
let _entered = debug_span!("smartMagnifyWithEvent:").entered();
|
||||
trace_scope!("smartMagnifyWithEvent:");
|
||||
|
||||
self.mouse_motion(event);
|
||||
|
||||
@@ -723,12 +741,12 @@ define_class!(
|
||||
|
||||
#[unsafe(method(rotateWithEvent:))]
|
||||
fn rotate_with_event(&self, event: &NSEvent) {
|
||||
let _entered = debug_span!("rotateWithEvent:").entered();
|
||||
trace_scope!("rotateWithEvent:");
|
||||
|
||||
self.mouse_motion(event);
|
||||
|
||||
#[allow(non_upper_case_globals)]
|
||||
let phase = match event.phase() {
|
||||
let phase = match unsafe { event.phase() } {
|
||||
NSEventPhase::Began => TouchPhase::Started,
|
||||
NSEventPhase::Changed => TouchPhase::Moved,
|
||||
NSEventPhase::Cancelled => TouchPhase::Cancelled,
|
||||
@@ -738,19 +756,19 @@ define_class!(
|
||||
|
||||
self.queue_event(WindowEvent::RotationGesture {
|
||||
device_id: None,
|
||||
delta: event.rotation(),
|
||||
delta: unsafe { event.rotation() },
|
||||
phase,
|
||||
});
|
||||
}
|
||||
|
||||
#[unsafe(method(pressureChangeWithEvent:))]
|
||||
fn pressure_change_with_event(&self, event: &NSEvent) {
|
||||
let _entered = debug_span!("pressureChangeWithEvent:").entered();
|
||||
trace_scope!("pressureChangeWithEvent:");
|
||||
|
||||
self.queue_event(WindowEvent::TouchpadPressure {
|
||||
device_id: None,
|
||||
pressure: event.pressure(),
|
||||
stage: event.stage() as i64,
|
||||
pressure: unsafe { event.pressure() },
|
||||
stage: unsafe { event.stage() } as i64,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -759,13 +777,13 @@ define_class!(
|
||||
// https://github.com/chromium/chromium/blob/a86a8a6bcfa438fa3ac2eba6f02b3ad1f8e0756f/ui/views/cocoa/bridged_content_view.mm#L816
|
||||
#[unsafe(method(_wantsKeyDownForEvent:))]
|
||||
fn wants_key_down_for_event(&self, _event: &NSEvent) -> bool {
|
||||
let _entered = debug_span!("_wantsKeyDownForEvent:").entered();
|
||||
trace_scope!("_wantsKeyDownForEvent:");
|
||||
true
|
||||
}
|
||||
|
||||
#[unsafe(method(acceptsFirstMouse:))]
|
||||
fn accepts_first_mouse(&self, _event: &NSEvent) -> bool {
|
||||
let _entered = debug_span!("acceptsFirstMouse:").entered();
|
||||
trace_scope!("acceptsFirstMouse:");
|
||||
self.ivars().accepts_first_mouse
|
||||
}
|
||||
}
|
||||
@@ -785,6 +803,7 @@ impl WinitView {
|
||||
ime_size: Default::default(),
|
||||
modifiers: Default::default(),
|
||||
phys_modifiers: Default::default(),
|
||||
tracking_rect: Default::default(),
|
||||
ime_state: Default::default(),
|
||||
input_source: Default::default(),
|
||||
ime_capabilities: Default::default(),
|
||||
@@ -794,52 +813,9 @@ impl WinitView {
|
||||
option_as_alt: Cell::new(option_as_alt),
|
||||
});
|
||||
let this: Retained<Self> = unsafe { msg_send![super(this), init] };
|
||||
|
||||
*this.ivars().input_source.borrow_mut() = this.current_input_source();
|
||||
|
||||
// `MouseEnteredAndExited` enables receiving events through `mouseEntered:` and
|
||||
// `mouseExited:`.
|
||||
//
|
||||
// `MouseMoved` enables receiving events through `mouseMoved:`
|
||||
//
|
||||
// We do not set `CursorUpdate` because it is part of the "flexible" alternative to
|
||||
// `cursorRect` based cursor image updates, and we currently still use
|
||||
// `cursorRect`s. We also can't really switch to this approach because "The
|
||||
// cursorUpdate(with:) message is not sent when the NSTrackingCursorUpdate option is
|
||||
// specified along with [`ActiveAlways`]."
|
||||
//
|
||||
// `ActiveAlways` indicates we want to receive events when the window is not
|
||||
// focused ("key window" in Cocoa terms), which matches the behavior on other
|
||||
// platforms.
|
||||
//
|
||||
// We do not set `AssumeInside` because we want to avoid emitting `Left` events without a
|
||||
// correspondering `Entered` to our consumers, and not setting this flag tells AppKit to
|
||||
// handle this for us by synthesizing entry and exit events in some cases.
|
||||
//
|
||||
// `InVisibleRect` instructs the tracking area's `owner` (our `NSView`) to ignore the value
|
||||
// we provide in `rect` and keep the tracking area's bounds up to date with the
|
||||
// current view bounds automatically.
|
||||
//
|
||||
// We do not set `EnabledDuringMouseDrag` to match the platform behavior on Windows
|
||||
// and Wayland, since neither emit events while being dragged over with an empty
|
||||
// cursor without focus.
|
||||
//
|
||||
// See also https://developer.apple.com/documentation/appkit/nstrackingareaoptions.
|
||||
|
||||
// Safety: the type of `owner` should be `NSView` and is.
|
||||
// The type of `user_info` is irrelevant because it is None.
|
||||
this.addTrackingArea(&*unsafe {
|
||||
NSTrackingArea::initWithRect_options_owner_userInfo(
|
||||
NSTrackingArea::alloc(),
|
||||
NSRect::ZERO,
|
||||
NSTrackingAreaOptions::MouseEnteredAndExited
|
||||
| NSTrackingAreaOptions::MouseMoved
|
||||
| NSTrackingAreaOptions::ActiveAlways
|
||||
| NSTrackingAreaOptions::InVisibleRect,
|
||||
Some(&this),
|
||||
None,
|
||||
)
|
||||
});
|
||||
|
||||
this
|
||||
}
|
||||
|
||||
@@ -891,33 +867,24 @@ impl WinitView {
|
||||
false
|
||||
}
|
||||
}
|
||||
pub(super) fn enable_ime(&self, capabilities: ImeCapabilities) {
|
||||
// This seems reasonable but the prior behavior of `set_ime_allowed` doesn't do this
|
||||
// (it was also broken but let's not break things worse)
|
||||
|
||||
// if self.ivars().ime_capabilities.get().is_none() {
|
||||
// self.ivars().ime_state.set(ImeState::Ground);
|
||||
// }
|
||||
pub(super) fn set_ime_allowed(&self, capabilities: Option<ImeCapabilities>) {
|
||||
if self.ivars().ime_capabilities.get().is_some() {
|
||||
return;
|
||||
}
|
||||
self.ivars().ime_capabilities.set(capabilities);
|
||||
|
||||
if capabilities.is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Clear markedText
|
||||
*self.ivars().marked_text.borrow_mut() = NSMutableAttributedString::new();
|
||||
|
||||
// why are we disabling things in an enable fn? who knows. it's what the previous one did
|
||||
// though
|
||||
if self.ivars().ime_state.get() != ImeState::Disabled {
|
||||
self.ivars().ime_state.set(ImeState::Disabled);
|
||||
self.queue_event(WindowEvent::Ime(Ime::Disabled));
|
||||
}
|
||||
self.ivars().ime_capabilities.set(Some(capabilities));
|
||||
*self.ivars().marked_text.borrow_mut() = NSMutableAttributedString::new();
|
||||
}
|
||||
pub(super) fn disable_ime(&self) {
|
||||
// see above
|
||||
self.ivars().ime_capabilities.set(None);
|
||||
if self.ivars().ime_state.get() != ImeState::Disabled {
|
||||
self.ivars().ime_state.set(ImeState::Disabled);
|
||||
self.queue_event(WindowEvent::Ime(Ime::Disabled));
|
||||
}
|
||||
// we probably don't need to do this, but again this mirrors the prior behavior of
|
||||
// `set_ime_allowed`
|
||||
*self.ivars().marked_text.borrow_mut() = NSMutableAttributedString::new();
|
||||
}
|
||||
|
||||
pub(super) fn ime_capabilities(&self) -> Option<ImeCapabilities> {
|
||||
@@ -964,8 +931,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 && ns_event.keyCode() != 0 {
|
||||
let scancode = ns_event.keyCode();
|
||||
if is_flags_changed_event && unsafe { ns_event.keyCode() } != 0 {
|
||||
let scancode = unsafe { ns_event.keyCode() };
|
||||
let physical_key = scancode_to_physicalkey(scancode as u32);
|
||||
|
||||
let logical_key = code_to_key(physical_key, scancode);
|
||||
@@ -1097,7 +1064,7 @@ impl WinitView {
|
||||
|| view_point.x > frame.size.width
|
||||
|| view_point.y > frame.size.height
|
||||
{
|
||||
let mouse_buttons_down = NSEvent::pressedMouseButtons();
|
||||
let mouse_buttons_down = unsafe { NSEvent::pressedMouseButtons() };
|
||||
if mouse_buttons_down == 0 {
|
||||
// Point is outside of the client area (view) and no buttons are pressed
|
||||
return;
|
||||
@@ -1115,7 +1082,7 @@ impl WinitView {
|
||||
}
|
||||
|
||||
fn mouse_view_point(&self, event: &NSEvent) -> LogicalPosition<f64> {
|
||||
let window_point = event.locationInWindow();
|
||||
let window_point = unsafe { event.locationInWindow() };
|
||||
let view_point = self.convertPoint_fromView(window_point, None);
|
||||
|
||||
LogicalPosition::new(view_point.x, view_point.y)
|
||||
@@ -1129,11 +1096,14 @@ 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.
|
||||
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")
|
||||
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),
|
||||
}
|
||||
}
|
||||
|
||||
// NOTE: to get option as alt working we need to rewrite events
|
||||
@@ -1150,10 +1120,12 @@ fn replace_event(event: &NSEvent, option_as_alt: OptionAsAlt) -> Retained<NSEven
|
||||
&& !ev_mods.meta_key();
|
||||
|
||||
if ignore_alt_characters {
|
||||
let ns_chars =
|
||||
event.charactersIgnoringModifiers().expect("expected characters to be non-null");
|
||||
let ns_chars = unsafe {
|
||||
event.charactersIgnoringModifiers().expect("expected characters to be non-null")
|
||||
};
|
||||
|
||||
NSEvent::keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode(
|
||||
unsafe {
|
||||
NSEvent::keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode(
|
||||
event.r#type(),
|
||||
event.locationInWindow(),
|
||||
event.modifierFlags(),
|
||||
@@ -1166,6 +1138,7 @@ fn replace_event(event: &NSEvent, option_as_alt: OptionAsAlt) -> Retained<NSEven
|
||||
event.keyCode(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
} else {
|
||||
event.copy()
|
||||
}
|
||||
|
||||
@@ -4,11 +4,10 @@ use std::sync::Arc;
|
||||
|
||||
use dispatch2::MainThreadBound;
|
||||
use dpi::{Position, Size};
|
||||
use objc2::rc::{Retained, autoreleasepool};
|
||||
use objc2::{MainThreadMarker, Message, define_class};
|
||||
use objc2::rc::{autoreleasepool, Retained};
|
||||
use objc2::{define_class, MainThreadMarker, Message};
|
||||
use objc2_app_kit::{NSPanel, NSResponder, NSWindow};
|
||||
use objc2_foundation::NSObject;
|
||||
use tracing::trace_span;
|
||||
use winit_core::cursor::Cursor;
|
||||
use winit_core::error::RequestError;
|
||||
use winit_core::icon::Icon;
|
||||
@@ -351,13 +350,13 @@ define_class!(
|
||||
impl WinitWindow {
|
||||
#[unsafe(method(canBecomeMainWindow))]
|
||||
fn can_become_main_window(&self) -> bool {
|
||||
let _entered = trace_span!("canBecomeMainWindow").entered();
|
||||
trace_scope!("canBecomeMainWindow");
|
||||
true
|
||||
}
|
||||
|
||||
#[unsafe(method(canBecomeKeyWindow))]
|
||||
fn can_become_key_window(&self) -> bool {
|
||||
let _entered = trace_span!("canBecomeKeyWindow").entered();
|
||||
trace_scope!("canBecomeKeyWindow");
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -375,7 +374,7 @@ define_class!(
|
||||
// it doesn't if window doesn't have NSWindowStyleMask::Titled
|
||||
#[unsafe(method(canBecomeKeyWindow))]
|
||||
fn can_become_key_window(&self) -> bool {
|
||||
let _entered = trace_span!("canBecomeKeyWindow").entered();
|
||||
trace_scope!("canBecomeKeyWindow");
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,39 +10,36 @@ use dpi::{
|
||||
LogicalInsets, LogicalPosition, LogicalSize, PhysicalInsets, PhysicalPosition, PhysicalSize,
|
||||
Position, Size,
|
||||
};
|
||||
use objc2::rc::{Retained, autoreleasepool};
|
||||
use objc2::rc::{autoreleasepool, Retained};
|
||||
use objc2::runtime::{AnyObject, ProtocolObject};
|
||||
use objc2::{
|
||||
ClassType, DefinedClass, MainThreadMarker, MainThreadOnly, Message, available, define_class,
|
||||
msg_send, sel,
|
||||
available, define_class, msg_send, sel, ClassType, DefinedClass, MainThreadMarker,
|
||||
MainThreadOnly, Message,
|
||||
};
|
||||
use objc2_app_kit::{
|
||||
NSAppKitVersionNumber, NSAppKitVersionNumber10_12, NSAppearance, NSAppearanceCustomization,
|
||||
NSAppearanceNameAqua, NSApplication, NSApplicationPresentationOptions, NSBackingStoreType,
|
||||
NSColor, NSDraggingDestination, NSDraggingInfo, NSRequestUserAttentionType, NSScreen,
|
||||
NSToolbar, NSView, NSViewFrameDidChangeNotification, NSWindow, NSWindowButton,
|
||||
NSWindowDelegate, NSWindowLevel, NSWindowOcclusionState, NSWindowOrderingMode,
|
||||
NSWindowSharingType, NSWindowStyleMask, NSWindowTabbingMode, NSWindowTitleVisibility,
|
||||
NSWindowToolbarStyle,
|
||||
NSColor, NSDraggingDestination, NSDraggingInfo, NSFilenamesPboardType,
|
||||
NSRequestUserAttentionType, NSScreen, NSToolbar, NSView, NSViewFrameDidChangeNotification,
|
||||
NSWindow, NSWindowButton, NSWindowDelegate, NSWindowFullScreenButton, 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::{
|
||||
CGAcquireDisplayFadeReservation, CGAssociateMouseAndMouseCursorPosition, CGDisplayCapture,
|
||||
CGDisplayFade, CGDisplayRelease, CGDisplaySetDisplayMode, CGReleaseDisplayFadeReservation,
|
||||
CGRestorePermanentDisplayConfiguration, CGShieldingWindowLevel, CGWarpMouseCursorPosition,
|
||||
kCGDisplayBlendNormal, kCGDisplayBlendSolidColor, kCGDisplayFadeReservationInvalidToken,
|
||||
kCGFloatingWindowLevel, kCGNormalWindowLevel,
|
||||
kCGFloatingWindowLevel, kCGNormalWindowLevel, CGAcquireDisplayFadeReservation,
|
||||
CGAssociateMouseAndMouseCursorPosition, CGDisplayCapture, CGDisplayFade, CGDisplayRelease,
|
||||
CGDisplaySetDisplayMode, CGReleaseDisplayFadeReservation,
|
||||
CGRestorePermanentDisplayConfiguration, CGShieldingWindowLevel, CGWarpMouseCursorPosition,
|
||||
};
|
||||
use objc2_foundation::{
|
||||
NSArray, NSDictionary, NSEdgeInsets, NSKeyValueChangeKey, NSKeyValueChangeNewKey,
|
||||
ns_string, NSArray, NSDictionary, NSEdgeInsets, NSKeyValueChangeKey, NSKeyValueChangeNewKey,
|
||||
NSKeyValueChangeOldKey, NSKeyValueObservingOptions, NSNotificationCenter, NSObject,
|
||||
NSObjectNSDelayedPerforming, NSObjectNSKeyValueObserverRegistration, NSObjectProtocol, NSPoint,
|
||||
NSRect, NSSize, NSString, ns_string,
|
||||
NSRect, NSSize, NSString,
|
||||
};
|
||||
use tracing::{debug_span, trace, warn};
|
||||
use winit_common::core_foundation::MainRunLoop;
|
||||
use tracing::{trace, warn};
|
||||
use winit_core::cursor::Cursor;
|
||||
use winit_core::error::{NotSupportedError, RequestError};
|
||||
use winit_core::event::{SurfaceSizeWriter, WindowEvent};
|
||||
@@ -54,12 +51,13 @@ use winit_core::window::{
|
||||
};
|
||||
|
||||
use super::app_state::AppState;
|
||||
use super::cursor::{CustomCursor, cursor_from_icon};
|
||||
use super::cursor::{cursor_from_icon, CustomCursor};
|
||||
use super::ffi;
|
||||
use super::monitor::{self, MonitorHandle, flip_window_screen_coordinates, get_display_id};
|
||||
use super::monitor::{self, flip_window_screen_coordinates, get_display_id, MonitorHandle};
|
||||
use super::observer::RunLoop;
|
||||
use super::util::cgerr;
|
||||
use super::view::WinitView;
|
||||
use super::window::{WinitPanel, WinitWindow, window_id};
|
||||
use super::window::{window_id, WinitPanel, WinitWindow};
|
||||
use crate::{OptionAsAlt, WindowAttributesMacOS, WindowExtMacOS};
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -121,14 +119,14 @@ define_class!(
|
||||
unsafe impl NSWindowDelegate for WindowDelegate {
|
||||
#[unsafe(method(windowShouldClose:))]
|
||||
fn window_should_close(&self, _: Option<&AnyObject>) -> bool {
|
||||
let _entered = debug_span!("windowShouldClose:").entered();
|
||||
trace_scope!("windowShouldClose:");
|
||||
self.queue_event(WindowEvent::CloseRequested);
|
||||
false
|
||||
}
|
||||
|
||||
#[unsafe(method(windowWillClose:))]
|
||||
fn window_will_close(&self, _: Option<&AnyObject>) {
|
||||
let _entered = debug_span!("windowWillClose:").entered();
|
||||
trace_scope!("windowWillClose:");
|
||||
// `setDelegate:` retains the previous value and then autoreleases it
|
||||
autoreleasepool(|_| {
|
||||
// Since El Capitan, we need to be careful that delegate methods can't
|
||||
@@ -140,14 +138,14 @@ define_class!(
|
||||
|
||||
#[unsafe(method(windowDidResize:))]
|
||||
fn window_did_resize(&self, _: Option<&AnyObject>) {
|
||||
let _entered = debug_span!("windowDidResize:").entered();
|
||||
trace_scope!("windowDidResize:");
|
||||
// NOTE: WindowEvent::SurfaceResized is reported using NSViewFrameDidChangeNotification.
|
||||
self.emit_move_event();
|
||||
}
|
||||
|
||||
#[unsafe(method(windowWillStartLiveResize:))]
|
||||
fn window_will_start_live_resize(&self, _: Option<&AnyObject>) {
|
||||
let _entered = debug_span!("windowWillStartLiveResize:").entered();
|
||||
trace_scope!("windowWillStartLiveResize:");
|
||||
|
||||
let increments = self.ivars().surface_resize_increments.get();
|
||||
self.set_resize_increments_inner(increments);
|
||||
@@ -155,20 +153,20 @@ define_class!(
|
||||
|
||||
#[unsafe(method(windowDidEndLiveResize:))]
|
||||
fn window_did_end_live_resize(&self, _: Option<&AnyObject>) {
|
||||
let _entered = debug_span!("windowDidEndLiveResize:").entered();
|
||||
trace_scope!("windowDidEndLiveResize:");
|
||||
self.set_resize_increments_inner(NSSize::new(1., 1.));
|
||||
}
|
||||
|
||||
// This won't be triggered if the move was part of a resize.
|
||||
#[unsafe(method(windowDidMove:))]
|
||||
fn window_did_move(&self, _: Option<&AnyObject>) {
|
||||
let _entered = debug_span!("windowDidMove:").entered();
|
||||
trace_scope!("windowDidMove:");
|
||||
self.emit_move_event();
|
||||
}
|
||||
|
||||
#[unsafe(method(windowDidChangeBackingProperties:))]
|
||||
fn window_did_change_backing_properties(&self, _: Option<&AnyObject>) {
|
||||
let _entered = debug_span!("windowDidChangeBackingProperties:").entered();
|
||||
trace_scope!("windowDidChangeBackingProperties:");
|
||||
let scale_factor = self.scale_factor();
|
||||
if scale_factor == self.ivars().previous_scale_factor.get() {
|
||||
return;
|
||||
@@ -177,14 +175,14 @@ define_class!(
|
||||
|
||||
let mtm = MainThreadMarker::from(self);
|
||||
let this = self.retain();
|
||||
MainRunLoop::get(mtm).queue_closure(move || {
|
||||
RunLoop::main(mtm).queue_closure(move || {
|
||||
this.handle_scale_factor_changed(scale_factor);
|
||||
});
|
||||
}
|
||||
|
||||
#[unsafe(method(windowDidBecomeKey:))]
|
||||
fn window_did_become_key(&self, _: Option<&AnyObject>) {
|
||||
let _entered = debug_span!("windowDidBecomeKey:").entered();
|
||||
trace_scope!("windowDidBecomeKey:");
|
||||
// TODO: center the cursor if the window had mouse grab when it
|
||||
// lost focus
|
||||
self.queue_event(WindowEvent::Focused(true));
|
||||
@@ -192,7 +190,7 @@ define_class!(
|
||||
|
||||
#[unsafe(method(windowDidResignKey:))]
|
||||
fn window_did_resign_key(&self, _: Option<&AnyObject>) {
|
||||
let _entered = debug_span!("windowDidResignKey:").entered();
|
||||
trace_scope!("windowDidResignKey:");
|
||||
// It happens rather often, e.g. when the user is Cmd+Tabbing, that the
|
||||
// NSWindowDelegate will receive a didResignKey event despite no event
|
||||
// being received when the modifiers are released. This is because
|
||||
@@ -208,7 +206,7 @@ define_class!(
|
||||
/// Invoked when before enter fullscreen
|
||||
#[unsafe(method(windowWillEnterFullScreen:))]
|
||||
fn window_will_enter_fullscreen(&self, _: Option<&AnyObject>) {
|
||||
let _entered = debug_span!("windowWillEnterFullScreen:").entered();
|
||||
trace_scope!("windowWillEnterFullScreen:");
|
||||
|
||||
self.ivars().maximized.set(self.is_zoomed());
|
||||
let mut fullscreen = self.ivars().fullscreen.borrow_mut();
|
||||
@@ -236,7 +234,7 @@ define_class!(
|
||||
/// Invoked when before exit fullscreen
|
||||
#[unsafe(method(windowWillExitFullScreen:))]
|
||||
fn window_will_exit_fullscreen(&self, _: Option<&AnyObject>) {
|
||||
let _entered = debug_span!("windowWillExitFullScreen:").entered();
|
||||
trace_scope!("windowWillExitFullScreen:");
|
||||
|
||||
self.ivars().in_fullscreen_transition.set(true);
|
||||
}
|
||||
@@ -247,7 +245,7 @@ define_class!(
|
||||
_: Option<&AnyObject>,
|
||||
proposed_options: NSApplicationPresentationOptions,
|
||||
) -> NSApplicationPresentationOptions {
|
||||
let _entered = debug_span!("window:willUseFullScreenPresentationOptions:").entered();
|
||||
trace_scope!("window:willUseFullScreenPresentationOptions:");
|
||||
// Generally, games will want to disable the menu bar and the dock. Ideally,
|
||||
// this would be configurable by the user. Unfortunately because of our
|
||||
// `CGShieldingWindowLevel() + 1` hack (see `set_fullscreen`), our window is
|
||||
@@ -270,7 +268,7 @@ define_class!(
|
||||
/// Invoked when entered fullscreen
|
||||
#[unsafe(method(windowDidEnterFullScreen:))]
|
||||
fn window_did_enter_fullscreen(&self, _: Option<&AnyObject>) {
|
||||
let _entered = debug_span!("windowDidEnterFullScreen:").entered();
|
||||
trace_scope!("windowDidEnterFullScreen:");
|
||||
self.ivars().initial_fullscreen.set(false);
|
||||
self.ivars().in_fullscreen_transition.set(false);
|
||||
if let Some(target_fullscreen) = self.ivars().target_fullscreen.take() {
|
||||
@@ -281,7 +279,7 @@ define_class!(
|
||||
/// Invoked when exited fullscreen
|
||||
#[unsafe(method(windowDidExitFullScreen:))]
|
||||
fn window_did_exit_fullscreen(&self, _: Option<&AnyObject>) {
|
||||
let _entered = debug_span!("windowDidExitFullScreen:").entered();
|
||||
trace_scope!("windowDidExitFullScreen:");
|
||||
|
||||
self.restore_state_from_fullscreen();
|
||||
self.ivars().in_fullscreen_transition.set(false);
|
||||
@@ -308,7 +306,7 @@ define_class!(
|
||||
/// work you may have done to prepare to enter full-screen mode.
|
||||
#[unsafe(method(windowDidFailToEnterFullScreen:))]
|
||||
fn window_did_fail_to_enter_fullscreen(&self, _: Option<&AnyObject>) {
|
||||
let _entered = debug_span!("windowDidFailToEnterFullScreen:").entered();
|
||||
trace_scope!("windowDidFailToEnterFullScreen:");
|
||||
self.ivars().in_fullscreen_transition.set(false);
|
||||
self.ivars().target_fullscreen.replace(None);
|
||||
if self.ivars().initial_fullscreen.get() {
|
||||
@@ -327,28 +325,14 @@ define_class!(
|
||||
// Invoked when the occlusion state of the window changes
|
||||
#[unsafe(method(windowDidChangeOcclusionState:))]
|
||||
fn window_did_change_occlusion_state(&self, _: Option<&AnyObject>) {
|
||||
let _entered = debug_span!("windowDidChangeOcclusionState:").entered();
|
||||
trace_scope!("windowDidChangeOcclusionState:");
|
||||
let visible = self.window().occlusionState().contains(NSWindowOcclusionState::Visible);
|
||||
self.queue_event(WindowEvent::Occluded(!visible));
|
||||
|
||||
// We do this here rather than in `window:willUseFullScreenPresentationOptions`
|
||||
// because doing it there leaves the menu bar interactable despite being hidden.
|
||||
// Moving it here produces the most consistent results.
|
||||
if self.is_borderless_game()
|
||||
&& matches!(*self.ivars().fullscreen.borrow(), Some(Fullscreen::Borderless(_)))
|
||||
{
|
||||
let mtm = MainThreadMarker::from(self);
|
||||
let app = NSApplication::sharedApplication(mtm);
|
||||
app.setPresentationOptions(
|
||||
NSApplicationPresentationOptions::HideDock
|
||||
| NSApplicationPresentationOptions::HideMenuBar,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(method(windowDidChangeScreen:))]
|
||||
fn window_did_change_screen(&self, _: Option<&AnyObject>) {
|
||||
let _entered = debug_span!("windowDidChangeScreen:").entered();
|
||||
trace_scope!("windowDidChangeScreen:");
|
||||
let is_simple_fullscreen = self.ivars().is_simple_fullscreen.get();
|
||||
if is_simple_fullscreen {
|
||||
if let Some(screen) = self.window().screen() {
|
||||
@@ -362,26 +346,22 @@ define_class!(
|
||||
/// Invoked when the dragged image enters destination bounds or frame
|
||||
#[unsafe(method(draggingEntered:))]
|
||||
fn dragging_entered(&self, sender: &ProtocolObject<dyn NSDraggingInfo>) -> bool {
|
||||
let _entered = debug_span!("draggingEntered:").entered();
|
||||
trace_scope!("draggingEntered:");
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
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>()
|
||||
let pb = unsafe { sender.draggingPasteboard() };
|
||||
let filenames = pb
|
||||
.propertyListForType(unsafe { NSFilenamesPboardType })
|
||||
.unwrap()
|
||||
.downcast::<NSArray>()
|
||||
.unwrap();
|
||||
let paths = filenames
|
||||
.into_iter()
|
||||
.map(|file| PathBuf::from(file.downcast::<NSString>().unwrap().to_string()))
|
||||
.collect();
|
||||
|
||||
let dl = sender.draggingLocation();
|
||||
let dl = unsafe { sender.draggingLocation() };
|
||||
let dl = self.view().convertPoint_fromView(dl, None);
|
||||
let position =
|
||||
LogicalPosition::<f64>::from((dl.x, dl.y)).to_physical(self.scale_factor());
|
||||
@@ -393,7 +373,7 @@ define_class!(
|
||||
|
||||
#[unsafe(method(wantsPeriodicDraggingUpdates))]
|
||||
fn wants_periodic_dragging_updates(&self) -> bool {
|
||||
let _entered = debug_span!("wantsPeriodicDraggingUpdates:").entered();
|
||||
trace_scope!("wantsPeriodicDraggingUpdates:");
|
||||
true
|
||||
}
|
||||
|
||||
@@ -401,9 +381,9 @@ define_class!(
|
||||
/// modification of the dragging operation or mouse-pointer position.
|
||||
#[unsafe(method(draggingUpdated:))]
|
||||
fn dragging_updated(&self, sender: &ProtocolObject<dyn NSDraggingInfo>) -> bool {
|
||||
let _entered = debug_span!("draggingUpdated:").entered();
|
||||
trace_scope!("draggingUpdated:");
|
||||
|
||||
let dl = sender.draggingLocation();
|
||||
let dl = unsafe { sender.draggingLocation() };
|
||||
let dl = self.view().convertPoint_fromView(dl, None);
|
||||
let position =
|
||||
LogicalPosition::<f64>::from((dl.x, dl.y)).to_physical(self.scale_factor());
|
||||
@@ -416,33 +396,29 @@ define_class!(
|
||||
/// Invoked when the image is released
|
||||
#[unsafe(method(prepareForDragOperation:))]
|
||||
fn prepare_for_drag_operation(&self, _sender: &NSObject) -> bool {
|
||||
let _entered = debug_span!("prepareForDragOperation:").entered();
|
||||
trace_scope!("prepareForDragOperation:");
|
||||
true
|
||||
}
|
||||
|
||||
/// Invoked after the released image has been removed from the screen
|
||||
#[unsafe(method(performDragOperation:))]
|
||||
fn perform_drag_operation(&self, sender: &ProtocolObject<dyn NSDraggingInfo>) -> bool {
|
||||
let _entered = debug_span!("performDragOperation:").entered();
|
||||
trace_scope!("performDragOperation:");
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
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>()
|
||||
let pb = unsafe { sender.draggingPasteboard() };
|
||||
let filenames = pb
|
||||
.propertyListForType(unsafe { NSFilenamesPboardType })
|
||||
.unwrap()
|
||||
.downcast::<NSArray>()
|
||||
.unwrap();
|
||||
let paths = filenames
|
||||
.into_iter()
|
||||
.map(|file| PathBuf::from(file.downcast::<NSString>().unwrap().to_string()))
|
||||
.collect();
|
||||
|
||||
let dl = sender.draggingLocation();
|
||||
let dl = unsafe { sender.draggingLocation() };
|
||||
let dl = self.view().convertPoint_fromView(dl, None);
|
||||
let position =
|
||||
LogicalPosition::<f64>::from((dl.x, dl.y)).to_physical(self.scale_factor());
|
||||
@@ -455,16 +431,16 @@ define_class!(
|
||||
/// Invoked when the dragging operation is complete
|
||||
#[unsafe(method(concludeDragOperation:))]
|
||||
fn conclude_drag_operation(&self, _sender: Option<&NSObject>) {
|
||||
let _entered = debug_span!("concludeDragOperation:").entered();
|
||||
trace_scope!("concludeDragOperation:");
|
||||
}
|
||||
|
||||
/// Invoked when the dragging operation is cancelled
|
||||
#[unsafe(method(draggingExited:))]
|
||||
fn dragging_exited(&self, sender: Option<&ProtocolObject<dyn NSDraggingInfo>>) {
|
||||
let _entered = debug_span!("draggingExited:").entered();
|
||||
trace_scope!("draggingExited:");
|
||||
|
||||
let position = sender.map(|sender| {
|
||||
let dl = sender.draggingLocation();
|
||||
let dl = unsafe { sender.draggingLocation() };
|
||||
let dl = self.view().convertPoint_fromView(dl, None);
|
||||
LogicalPosition::<f64>::from((dl.x, dl.y)).to_physical(self.scale_factor())
|
||||
});
|
||||
@@ -483,7 +459,7 @@ define_class!(
|
||||
change: Option<&NSDictionary<NSKeyValueChangeKey, AnyObject>>,
|
||||
_context: *mut c_void,
|
||||
) {
|
||||
let _entered = debug_span!("observeValueForKeyPath:ofObject:change:context:").entered();
|
||||
trace_scope!("observeValueForKeyPath:ofObject:change:context:");
|
||||
// NOTE: We don't _really_ need to check the key path, as there should only be one, but
|
||||
// in the future we might want to observe other key paths.
|
||||
if key_path == Some(ns_string!("effectiveAppearance")) {
|
||||
@@ -501,12 +477,12 @@ define_class!(
|
||||
let old = old.downcast::<NSAppearance>().unwrap();
|
||||
let new = new.downcast::<NSAppearance>().unwrap();
|
||||
|
||||
trace!(old = %old.name(), new = %new.name(), "effectiveAppearance changed");
|
||||
trace!(old = %unsafe { old.name() }, new = %unsafe { 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 self.window().appearance().is_some() {
|
||||
if unsafe { self.window().appearance() }.is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -529,7 +505,9 @@ 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"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -688,10 +666,12 @@ fn new_window(
|
||||
window.setMovableByWindowBackground(true);
|
||||
}
|
||||
if macos_attrs.unified_titlebar {
|
||||
// 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);
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
if !attrs.enabled_buttons.contains(WindowButtons::MAXIMIZE) {
|
||||
@@ -740,7 +720,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 = NSNotificationCenter::defaultCenter();
|
||||
let notification_center = unsafe { NSNotificationCenter::defaultCenter() };
|
||||
unsafe {
|
||||
notification_center.addObserver_selector_name_object(
|
||||
&view,
|
||||
@@ -753,11 +733,10 @@ fn new_window(
|
||||
if attrs.transparent {
|
||||
window.setOpaque(false);
|
||||
// See `set_transparent` for details on why we do this.
|
||||
window.setBackgroundColor(Some(&NSColor::clearColor()));
|
||||
window.setBackgroundColor(unsafe { Some(&NSColor::clearColor()) });
|
||||
}
|
||||
|
||||
// register for drag and drop operations.
|
||||
#[allow(deprecated)]
|
||||
window.registerForDraggedTypes(&NSArray::from_slice(&[unsafe { NSFilenamesPboardType }]));
|
||||
|
||||
Some(window)
|
||||
@@ -811,7 +790,7 @@ impl WindowDelegate {
|
||||
let scale_factor = window.backingScaleFactor() as _;
|
||||
|
||||
if let Some(appearance) = theme_to_appearance(attrs.preferred_theme) {
|
||||
window.setAppearance(Some(&appearance));
|
||||
unsafe { window.setAppearance(Some(&appearance)) };
|
||||
}
|
||||
|
||||
let delegate = mtm.alloc().set_ivars(State {
|
||||
@@ -966,8 +945,11 @@ 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 { NSColor::clearColor() } else { NSColor::windowBackgroundColor() };
|
||||
let color = if transparent {
|
||||
unsafe { NSColor::clearColor() }
|
||||
} else {
|
||||
unsafe { NSColor::windowBackgroundColor() }
|
||||
};
|
||||
|
||||
self.window().setBackgroundColor(Some(&color));
|
||||
}
|
||||
@@ -976,7 +958,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 = self.window().windowNumber();
|
||||
let window_number = unsafe { self.window().windowNumber() };
|
||||
unsafe {
|
||||
ffi::CGSSetWindowBackgroundBlurRadius(
|
||||
ffi::CGSMainConnectionID(),
|
||||
@@ -1035,7 +1017,7 @@ impl WindowDelegate {
|
||||
NSPoint::new(position.x, position.y),
|
||||
self.window().frame().size,
|
||||
));
|
||||
self.window().setFrameOrigin(point);
|
||||
unsafe { self.window().setFrameOrigin(point) };
|
||||
}
|
||||
|
||||
#[inline]
|
||||
@@ -1057,15 +1039,17 @@ 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`.
|
||||
self.view().safeAreaInsets()
|
||||
unsafe { self.view().safeAreaInsets() }
|
||||
} else {
|
||||
// If `safeAreaInsets` is not available, we'll have to do the calculation ourselves.
|
||||
|
||||
let window_rect = self.window().convertRectFromScreen(
|
||||
self.window().contentRectForFrameRect(self.window().frame()),
|
||||
);
|
||||
let window_rect = unsafe {
|
||||
self.window().convertRectFromScreen(
|
||||
self.window().contentRectForFrameRect(self.window().frame()),
|
||||
)
|
||||
};
|
||||
// This includes NSWindowStyleMask::FullSizeContentView.
|
||||
let layout_rect = self.window().contentLayoutRect();
|
||||
let layout_rect = unsafe { self.window().contentLayoutRect() };
|
||||
|
||||
// Calculate the insets from window coordinates in AppKit's coordinate system.
|
||||
NSEdgeInsets {
|
||||
@@ -1095,7 +1079,7 @@ impl WindowDelegate {
|
||||
let min_size = dimensions.to_logical::<CGFloat>(self.scale_factor());
|
||||
|
||||
let min_size = NSSize::new(min_size.width, min_size.height);
|
||||
self.window().setContentMinSize(min_size);
|
||||
unsafe { self.window().setContentMinSize(min_size) };
|
||||
|
||||
// If necessary, resize the window to match constraint
|
||||
let mut current_size = self.window().contentRectForFrameRect(self.window().frame()).size;
|
||||
@@ -1117,7 +1101,7 @@ impl WindowDelegate {
|
||||
let max_size = dimensions.to_logical::<CGFloat>(scale_factor);
|
||||
|
||||
let max_size = NSSize::new(max_size.width, max_size.height);
|
||||
self.window().setContentMaxSize(max_size);
|
||||
unsafe { self.window().setContentMaxSize(max_size) };
|
||||
|
||||
// If necessary, resize the window to match constraint
|
||||
let mut current_size = self.window().contentRectForFrameRect(self.window().frame()).size;
|
||||
@@ -1257,12 +1241,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(CGAssociateMouseAndMouseCursorPosition(associate_mouse_cursor))?;
|
||||
cgerr(unsafe { CGAssociateMouseAndMouseCursorPosition(associate_mouse_cursor) })?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -1290,8 +1274,8 @@ impl WindowDelegate {
|
||||
x: window_position.x + cursor_position.x,
|
||||
y: window_position.y + cursor_position.y,
|
||||
};
|
||||
cgerr(CGWarpMouseCursorPosition(point))?;
|
||||
cgerr(CGAssociateMouseAndMouseCursorPosition(true))?;
|
||||
cgerr(unsafe { CGWarpMouseCursorPosition(point) })?;
|
||||
cgerr(unsafe { CGAssociateMouseAndMouseCursorPosition(true) })?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -1372,7 +1356,7 @@ impl WindowDelegate {
|
||||
if minimized {
|
||||
self.window().miniaturize(Some(self));
|
||||
} else {
|
||||
self.window().deminiaturize(Some(self));
|
||||
unsafe { self.window().deminiaturize(Some(self)) };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1466,7 +1450,7 @@ impl WindowDelegate {
|
||||
|
||||
let old_screen = self.window().screen().unwrap();
|
||||
if old_screen != new_screen {
|
||||
self.window().setFrameOrigin(new_screen.frame().origin);
|
||||
unsafe { self.window().setFrameOrigin(new_screen.frame().origin) };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1491,22 +1475,24 @@ impl WindowDelegate {
|
||||
self.ivars().save_presentation_opts.replace(Some(app.presentationOptions()));
|
||||
}
|
||||
|
||||
// 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,
|
||||
);
|
||||
}
|
||||
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();
|
||||
cgerr(CGDisplayCapture(display_id)).unwrap();
|
||||
}
|
||||
|
||||
let monitor = monitor.cast_ref::<MonitorHandle>().unwrap();
|
||||
let video_mode =
|
||||
@@ -1515,25 +1501,25 @@ impl WindowDelegate {
|
||||
None => return,
|
||||
};
|
||||
|
||||
cgerr(unsafe {
|
||||
CGDisplaySetDisplayMode(display_id, Some(&video_mode.native_mode.0), None)
|
||||
})
|
||||
.expect("failed to set video mode");
|
||||
unsafe {
|
||||
cgerr(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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1548,7 +1534,7 @@ impl WindowDelegate {
|
||||
}
|
||||
|
||||
match (old_fullscreen, fullscreen) {
|
||||
(None, Some(_)) => {
|
||||
(None, Some(fullscreen)) => {
|
||||
// `toggleFullScreen` doesn't work if the `StyleMask` is none, so we
|
||||
// set a normal style temporarily. The previous state will be
|
||||
// restored in `WindowDelegate::window_did_exit_fullscreen`.
|
||||
@@ -1559,6 +1545,16 @@ impl WindowDelegate {
|
||||
self.ivars().saved_style.set(Some(curr_mask));
|
||||
}
|
||||
|
||||
// In borderless games, we want to disable the dock and menu bar
|
||||
// by setting the presentation options. We do this here rather than in
|
||||
// `window:willUseFullScreenPresentationOptions` because for some reason
|
||||
// the menu bar remains interactable despite being hidden.
|
||||
if self.is_borderless_game() && matches!(fullscreen, Fullscreen::Borderless(_)) {
|
||||
let presentation_options = NSApplicationPresentationOptions::HideDock
|
||||
| NSApplicationPresentationOptions::HideMenuBar;
|
||||
app.setPresentationOptions(presentation_options);
|
||||
}
|
||||
|
||||
toggle_fullscreen(self.window());
|
||||
},
|
||||
(Some(Fullscreen::Borderless(_)), None) => {
|
||||
@@ -1586,7 +1582,7 @@ impl WindowDelegate {
|
||||
| NSApplicationPresentationOptions::HideMenuBar;
|
||||
app.setPresentationOptions(presentation_options);
|
||||
|
||||
let window_level = CGShieldingWindowLevel() as NSWindowLevel + 1;
|
||||
let window_level = unsafe { CGShieldingWindowLevel() } as NSWindowLevel + 1;
|
||||
self.window().setLevel(window_level);
|
||||
},
|
||||
(Some(Fullscreen::Exclusive(monitor, _)), Some(Fullscreen::Borderless(_))) => {
|
||||
@@ -1686,7 +1682,7 @@ impl WindowDelegate {
|
||||
if current_caps.is_some() {
|
||||
return Err(ImeRequestError::AlreadyEnabled);
|
||||
}
|
||||
self.view().enable_ime(capabilities);
|
||||
self.view().set_ime_allowed(Some(capabilities));
|
||||
request_data
|
||||
},
|
||||
ImeRequest::Update(request_data) => {
|
||||
@@ -1696,7 +1692,7 @@ impl WindowDelegate {
|
||||
request_data
|
||||
},
|
||||
ImeRequest::Disable => {
|
||||
self.view().disable_ime();
|
||||
self.view().set_ime_allowed(None);
|
||||
return Ok(());
|
||||
},
|
||||
};
|
||||
@@ -1801,8 +1797,9 @@ impl WindowDelegate {
|
||||
}
|
||||
|
||||
pub fn theme(&self) -> Option<Theme> {
|
||||
self.window().appearance().map(|appearance| appearance_to_theme(&appearance)).or_else(
|
||||
|| {
|
||||
unsafe { self.window().appearance() }
|
||||
.map(|appearance| appearance_to_theme(&appearance))
|
||||
.or_else(|| {
|
||||
let mtm = MainThreadMarker::from(self);
|
||||
let app = NSApplication::sharedApplication(mtm);
|
||||
|
||||
@@ -1811,12 +1808,11 @@ impl WindowDelegate {
|
||||
} else {
|
||||
Some(Theme::Light)
|
||||
}
|
||||
},
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn set_theme(&self, theme: Option<Theme>) {
|
||||
self.window().setAppearance(theme_to_appearance(theme).as_deref());
|
||||
unsafe { self.window().setAppearance(theme_to_appearance(theme).as_deref()) };
|
||||
}
|
||||
|
||||
#[inline]
|
||||
@@ -1840,8 +1836,10 @@ impl WindowDelegate {
|
||||
fn restore_and_release_display(monitor: &MonitorHandle) {
|
||||
let available_monitors = monitor::available_monitors();
|
||||
if available_monitors.contains(monitor) {
|
||||
CGRestorePermanentDisplayConfiguration();
|
||||
cgerr(CGDisplayRelease(monitor.native_id() as _)).unwrap();
|
||||
unsafe {
|
||||
CGRestorePermanentDisplayConfiguration();
|
||||
cgerr(CGDisplayRelease(monitor.native_id() as _)).unwrap();
|
||||
};
|
||||
} else {
|
||||
warn!(
|
||||
monitor = monitor.name().map(|name| name.to_string()),
|
||||
@@ -1903,7 +1901,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)) {
|
||||
self.view().setAdditionalSafeAreaInsets(screen.safeAreaInsets());
|
||||
unsafe { self.view().setAdditionalSafeAreaInsets(screen.safeAreaInsets()) };
|
||||
}
|
||||
|
||||
// Fullscreen windows can't be resized, minimized, or moved
|
||||
@@ -1922,12 +1920,14 @@ impl WindowExtMacOS for WindowDelegate {
|
||||
}
|
||||
|
||||
if NSScreen::class().responds_to(sel!(safeAreaInsets)) {
|
||||
self.view().setAdditionalSafeAreaInsets(NSEdgeInsets {
|
||||
top: 0.0,
|
||||
left: 0.0,
|
||||
bottom: 0.0,
|
||||
right: 0.0,
|
||||
});
|
||||
unsafe {
|
||||
self.view().setAdditionalSafeAreaInsets(NSEdgeInsets {
|
||||
top: 0.0,
|
||||
left: 0.0,
|
||||
bottom: 0.0,
|
||||
right: 0.0,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
self.window().setFrame_display(frame, true);
|
||||
@@ -1965,7 +1965,7 @@ impl WindowExtMacOS for WindowDelegate {
|
||||
|
||||
#[inline]
|
||||
fn select_previous_tab(&self) {
|
||||
self.window().selectPreviousTab(None)
|
||||
unsafe { self.window().selectPreviousTab(None) }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
@@ -1975,7 +1975,7 @@ impl WindowExtMacOS for WindowDelegate {
|
||||
return;
|
||||
}
|
||||
if let Some(group) = self.window().tabGroup() {
|
||||
if let Some(windows) = self.window().tabbedWindows() {
|
||||
if let Some(windows) = unsafe { self.window().tabbedWindows() } {
|
||||
if index < windows.len() {
|
||||
group.setSelectedWindow(Some(&windows.objectAtIndex(index)));
|
||||
}
|
||||
@@ -1985,7 +1985,7 @@ impl WindowExtMacOS for WindowDelegate {
|
||||
|
||||
#[inline]
|
||||
fn num_tabs(&self) -> usize {
|
||||
self.window().tabbedWindows().map(|windows| windows.len()).unwrap_or(1)
|
||||
unsafe { self.window().tabbedWindows() }.map(|windows| windows.len()).unwrap_or(1)
|
||||
}
|
||||
|
||||
fn is_document_edited(&self) -> bool {
|
||||
@@ -2018,20 +2018,26 @@ impl WindowExtMacOS for WindowDelegate {
|
||||
if unified_titlebar {
|
||||
let mtm = MainThreadMarker::from(self);
|
||||
|
||||
// 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);
|
||||
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);
|
||||
}
|
||||
} else {
|
||||
window.setToolbar(None);
|
||||
window.setToolbarStyle(NSWindowToolbarStyle::Automatic);
|
||||
unsafe {
|
||||
window.setToolbar(None);
|
||||
window.setToolbarStyle(NSWindowToolbarStyle::Automatic);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn unified_titlebar(&self) -> bool {
|
||||
let window = self.window();
|
||||
|
||||
window.toolbar().is_some() && window.toolbarStyle() == NSWindowToolbarStyle::Unified
|
||||
unsafe {
|
||||
window.toolbar().is_some() && window.toolbarStyle() == NSWindowToolbarStyle::Unified
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2049,7 +2055,11 @@ 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
|
||||
|
||||
@@ -18,10 +18,7 @@ x11 = ["xkbcommon-dl?/x11", "dep:x11-dl"]
|
||||
xkb = ["dep:xkbcommon-dl", "dep:smol_str"]
|
||||
|
||||
# CoreFoundation
|
||||
core-foundation = ["dep:block2", "dep:objc2", "dep:objc2-core-foundation"]
|
||||
|
||||
# Foundation
|
||||
foundation = ["dep:block2", "dep:objc2", "dep:objc2-foundation"]
|
||||
core-foundation = ["dep:objc2", "dep:objc2-core-foundation"]
|
||||
|
||||
[dependencies]
|
||||
smol_str = { workspace = true, optional = true }
|
||||
@@ -33,23 +30,13 @@ memmap2 = { workspace = true, optional = true }
|
||||
x11-dl = { workspace = true, optional = true }
|
||||
xkbcommon-dl = { workspace = true, optional = true }
|
||||
|
||||
# Foundation / CoreFoundation
|
||||
block2 = { workspace = true, optional = true }
|
||||
# CoreFoundation
|
||||
objc2 = { workspace = true, optional = true }
|
||||
objc2-core-foundation = { workspace = true, optional = true, features = [
|
||||
"std",
|
||||
"block2",
|
||||
"objc2",
|
||||
"CFRunLoop",
|
||||
"CFString",
|
||||
] }
|
||||
objc2-foundation = { workspace = true, optional = true, features = [
|
||||
"std",
|
||||
"block2",
|
||||
"NSNotification",
|
||||
"NSString",
|
||||
"NSOperation",
|
||||
] }
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
use std::os::raw::c_void;
|
||||
use std::ptr::NonNull;
|
||||
use std::sync::Arc;
|
||||
use std::task::{RawWaker, RawWakerVTable, Waker};
|
||||
|
||||
use objc2::MainThreadMarker;
|
||||
use objc2_core_foundation::{
|
||||
CFIndex, CFRetained, CFRunLoop, CFRunLoopSource, CFRunLoopSourceContext, kCFRunLoopCommonModes,
|
||||
kCFRunLoopCommonModes, CFIndex, CFRetained, CFRunLoop, CFRunLoopSource, CFRunLoopSourceContext,
|
||||
Type,
|
||||
};
|
||||
use winit_core::event_loop::EventLoopProxyProvider;
|
||||
|
||||
@@ -119,4 +122,54 @@ impl EventLoopProxyProvider for EventLoopProxy {
|
||||
// main loop may be sleeping (and `CFRunLoopSourceSignal` won't wake it).
|
||||
self.main_loop.wake_up();
|
||||
}
|
||||
|
||||
fn waker(&self) -> Waker {
|
||||
const VTABLE: RawWakerVTable =
|
||||
RawWakerVTable::new(clone_waker, wake, wake_by_ref, drop_waker);
|
||||
|
||||
unsafe fn clone_waker(data: *const ()) -> RawWaker {
|
||||
// SAFETY: The poiner came from `CFRunLoopSource` and is valid and non-null.
|
||||
let source = unsafe { &*data.cast::<CFRunLoopSource>() };
|
||||
|
||||
// Increment reference count.
|
||||
let source = source.retain();
|
||||
|
||||
// Pass ownership to the raw waker.
|
||||
let data: *const CFRunLoopSource = CFRetained::into_raw(source).as_ptr();
|
||||
RawWaker::new(data.cast(), &VTABLE)
|
||||
}
|
||||
|
||||
unsafe fn wake(data: *const ()) {
|
||||
unsafe { wake_by_ref(data) };
|
||||
unsafe { drop_waker(data) };
|
||||
}
|
||||
|
||||
unsafe fn wake_by_ref(data: *const ()) {
|
||||
// SAFETY: The poiner came from `CFRunLoopSource` and is valid and non-null.
|
||||
let source = unsafe { &*data.cast::<CFRunLoopSource>() };
|
||||
|
||||
// Signal the source, which ends up later invoking `perform` on the main thread.
|
||||
//
|
||||
// Multiple signals in quick succession are automatically coalesced into a single
|
||||
// signal.
|
||||
source.signal();
|
||||
|
||||
let main_loop = CFRunLoop::main().unwrap();
|
||||
// Let the main thread know there's a new event.
|
||||
//
|
||||
// This is required since we may be (probably are) running on a different thread, and
|
||||
// the main loop may be sleeping (and `CFRunLoopSourceSignal` won't wake it).
|
||||
main_loop.wake_up();
|
||||
}
|
||||
|
||||
unsafe fn drop_waker(data: *const ()) {
|
||||
let source = data.cast::<CFRunLoopSource>().cast_mut();
|
||||
// SAFETY: The poiner came from `CFRunLoopSource` and is valid and non-null.
|
||||
// We take ownership of a retain count here.
|
||||
let _source = unsafe { CFRetained::from_raw(NonNull::new_unchecked(source)) };
|
||||
}
|
||||
|
||||
let data: *const CFRunLoopSource = CFRetained::into_raw(self.source.clone()).as_ptr();
|
||||
unsafe { Waker::from_raw(RawWaker::new(data.cast(), &VTABLE)) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,136 +0,0 @@
|
||||
//! Various utilities for interfacing with the main run loop.
|
||||
//!
|
||||
//! These allow for using closures without the `Send + Sync` requirement that is otherwise required
|
||||
//! when interfacing with run loops.
|
||||
//!
|
||||
//! See also <https://github.com/madsmtm/objc2/issues/696> for work on this at a lower level.
|
||||
|
||||
use std::cell::Cell;
|
||||
|
||||
use objc2::MainThreadMarker;
|
||||
use objc2_core_foundation::{CFRetained, CFRunLoop, CFRunLoopMode, kCFRunLoopDefaultMode};
|
||||
use tracing::{Span, error};
|
||||
|
||||
use super::MainRunLoopObserver;
|
||||
|
||||
/// Wrapper around [`CFRunLoop::main`].
|
||||
#[derive(Debug)]
|
||||
pub struct MainRunLoop {
|
||||
/// This is on the main thread.
|
||||
_mtm: MainThreadMarker,
|
||||
/// A cached reference to the main run loop.
|
||||
main_run_loop: CFRetained<CFRunLoop>,
|
||||
}
|
||||
|
||||
impl MainRunLoop {
|
||||
/// Get the main run loop.
|
||||
pub fn get(_mtm: MainThreadMarker) -> Self {
|
||||
let main_run_loop = CFRunLoop::main().unwrap();
|
||||
Self { _mtm, main_run_loop }
|
||||
}
|
||||
|
||||
/// Get a reference to the underlying [`CFRunLoop`].
|
||||
pub fn run_loop(&self) -> &CFRunLoop {
|
||||
&self.main_run_loop
|
||||
}
|
||||
|
||||
/// Wake the main run loop.
|
||||
pub fn wake_up(&self) {
|
||||
self.main_run_loop.wake_up();
|
||||
}
|
||||
|
||||
/// Submit a closure to run on the main thread as the next step in the run loop, before other
|
||||
/// event sources are processed.
|
||||
///
|
||||
/// This is used for running event handlers, as those are not allowed to run re-entrantly.
|
||||
///
|
||||
/// # Implementation
|
||||
///
|
||||
/// This queuing could be implemented in the following several ways with subtle differences in
|
||||
/// timing. This list is sorted in rough order in which they are run:
|
||||
///
|
||||
/// 1. Using `CFRunLoopPerformBlock` or `-[NSRunLoop performBlock:]` to queue a closure to run
|
||||
/// the next time runloop sources are processed.
|
||||
///
|
||||
/// 2. Using `-[NSObject performSelectorOnMainThread:withObject:waitUntilDone:]` or wrapping the
|
||||
/// event in `NSEvent` and posting that to `-[NSApplication postEvent:atStart:]` (both
|
||||
/// creates a custom `CFRunLoopSource`, and signals that to wake up the main event loop).
|
||||
///
|
||||
/// a. `atStart = true`.
|
||||
///
|
||||
/// b. `atStart = false`.
|
||||
///
|
||||
/// 3. `dispatch_async` or `dispatch_async_f`. Note that this may appear before 2b, it does not
|
||||
/// respect the ordering that runloop events have.
|
||||
///
|
||||
/// We choose the first one, both for ease-of-implementation, but mostly for consistency, as we
|
||||
/// want the event to be queued in a way that preserves the order the events originally arrived
|
||||
/// in.
|
||||
///
|
||||
/// As an example, let's assume that we receive two events from the user, a mouse click which we
|
||||
/// handled by queuing it, and a window resize which we handled immediately. If we allowed
|
||||
/// AppKit to choose the ordering when queuing the mouse event, it might get put in the back of
|
||||
/// the queue, and the events would appear out of order to the user of Winit. So we must instead
|
||||
/// put the event at the very front of the queue, to be handled as soon as possible after
|
||||
/// handling whatever event it's currently handling.
|
||||
pub fn queue_closure(&self, closure: impl FnOnce() + 'static) {
|
||||
// We use this to run a closure asynchronously at a later point, so it also makes sense to
|
||||
// re-enter the current span when running the queued closure.
|
||||
let span = Span::current();
|
||||
|
||||
// Convert `FnOnce()` to `Block<dyn Fn()>`.
|
||||
let closure = Cell::new(Some(closure));
|
||||
let block = block2::RcBlock::new(move || {
|
||||
// Running this block happens inside a `CFRunLoopSource`, but the spans that we emit for
|
||||
// that are (intentionally) overwritten by entering the span from before.
|
||||
let _enter = span.enter();
|
||||
|
||||
debug_assert!(MainThreadMarker::new().is_some());
|
||||
if let Some(closure) = closure.take() {
|
||||
closure()
|
||||
} else {
|
||||
error!("tried to execute queued closure on main thread twice");
|
||||
}
|
||||
});
|
||||
|
||||
// There are a few common modes (`kCFRunLoopCommonModes`) defined by Cocoa:
|
||||
// - `NSDefaultRunLoopMode`, alias of `kCFRunLoopDefaultMode`.
|
||||
// - `NSEventTrackingRunLoopMode`, used when mouse-dragging and live-resizing a window.
|
||||
// - `NSModalPanelRunLoopMode`, used when running a modal inside the Winit event loop.
|
||||
// - `NSConnectionReplyMode`: TODO.
|
||||
//
|
||||
// We only want to run event handlers in the default mode, as we support running a blocking
|
||||
// modal inside a Winit event handler (see [#1779]) which outrules the modal panel mode, and
|
||||
// resizing such panel window enters the event tracking run loop mode, so we can't directly
|
||||
// trigger events inside that mode either.
|
||||
//
|
||||
// Any events that are queued while running a modal or when live-resizing will instead wait,
|
||||
// and be delivered to the application afterwards.
|
||||
//
|
||||
// [#1779]: https://github.com/rust-windowing/winit/issues/1779
|
||||
let mode = unsafe { kCFRunLoopDefaultMode.unwrap() };
|
||||
|
||||
let _ = self._mtm;
|
||||
// SAFETY: The runloop is valid, the mode is a `CFStringRef`, and the block is `'static`.
|
||||
//
|
||||
// Additionally, we have a `MainThreadMarker` here, which means we know we're on the main
|
||||
// thread. We also know that the run loop is the main-thread run loop, so scheduling a
|
||||
// non-`Send` block to that is allowed.
|
||||
unsafe { self.main_run_loop.perform_block(Some(mode), Some(&block)) }
|
||||
}
|
||||
|
||||
/// Add an observer to the main run loop.
|
||||
pub fn add_observer(&self, observer: &MainRunLoopObserver, mode: &CFRunLoopMode) {
|
||||
// Accessing the `MainObserver`'s observer is fine here, since we're adding it to the main
|
||||
// run loop (which is on the same thread that the observer was created on).
|
||||
self.main_run_loop.add_observer(Some(&observer.observer), Some(mode));
|
||||
}
|
||||
|
||||
/// Remove an observer from the main run loop.
|
||||
///
|
||||
/// This is also done automatically when the [`MainRunLoopObserver`] is dropped.
|
||||
pub fn remove_observer(&self, observer: &MainRunLoopObserver, mode: &CFRunLoopMode) {
|
||||
// Same as in `add_observer`, accessing the main loop's observer is fine.
|
||||
self.main_run_loop.add_observer(Some(&observer.observer), Some(mode));
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
use block2::RcBlock;
|
||||
use objc2::MainThreadMarker;
|
||||
use objc2_core_foundation::{
|
||||
CFIndex, CFRetained, CFRunLoopActivity, CFRunLoopObserver, kCFAllocatorDefault,
|
||||
};
|
||||
|
||||
/// A [`CFRunLoopObserver`] on the main thread.
|
||||
///
|
||||
/// This type has "ownership" semantics, and invalidates the observer when dropped.
|
||||
#[derive(Debug)]
|
||||
pub struct MainRunLoopObserver {
|
||||
/// This must be private, otherwise the user might add it to an arbitrary run loop (but this
|
||||
/// observer is not designed to only be on the main thread).
|
||||
pub(crate) observer: CFRetained<CFRunLoopObserver>,
|
||||
}
|
||||
|
||||
impl MainRunLoopObserver {
|
||||
/// Create a new run loop observer that observes the main run loop.
|
||||
pub fn new(
|
||||
mtm: MainThreadMarker,
|
||||
activities: CFRunLoopActivity,
|
||||
repeats: bool,
|
||||
// The lower the value, the sooner this will run (inverse of a "priority").
|
||||
order: CFIndex,
|
||||
callback: impl Fn(CFRunLoopActivity) + 'static,
|
||||
) -> Self {
|
||||
let block = RcBlock::new(move |_: *mut _, activity| {
|
||||
debug_assert!(MainThreadMarker::new().is_some());
|
||||
callback(activity)
|
||||
});
|
||||
|
||||
let _ = mtm;
|
||||
// SAFETY: The callback is not Send + Sync, which would normally be unsound, but since we
|
||||
// restrict the callback to only ever be on the main thread (by taking `MainThreadMarker`,
|
||||
// and in `MainRunLoop::add_observer`), the callback doesn't have to be thread safe.
|
||||
let observer = unsafe {
|
||||
CFRunLoopObserver::with_handler(
|
||||
kCFAllocatorDefault,
|
||||
activities.0,
|
||||
repeats,
|
||||
order,
|
||||
Some(&block),
|
||||
)
|
||||
}
|
||||
.unwrap();
|
||||
|
||||
Self { observer }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for MainRunLoopObserver {
|
||||
fn drop(&mut self) {
|
||||
self.observer.invalidate();
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,3 @@
|
||||
//! Various wrappers around [`CFRunLoop`][objc2_core_foundation::CFRunLoop].
|
||||
//!
|
||||
//! See Apple's documentation on Run Loops for details:
|
||||
//! <https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html>
|
||||
|
||||
mod event_loop_proxy;
|
||||
mod main_run_loop;
|
||||
mod main_run_loop_observer;
|
||||
mod tracing_observers;
|
||||
|
||||
pub use self::event_loop_proxy::*;
|
||||
pub use self::main_run_loop::*;
|
||||
pub use self::main_run_loop_observer::*;
|
||||
pub use self::tracing_observers::*;
|
||||
pub use event_loop_proxy::*;
|
||||
|
||||
@@ -1,146 +0,0 @@
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use objc2::MainThreadMarker;
|
||||
use objc2_core_foundation::{CFIndex, CFRunLoop, CFRunLoopActivity, kCFRunLoopDefaultMode};
|
||||
use tracing::span::EnteredSpan;
|
||||
use tracing::{Level, error, field, span_enabled, trace_span};
|
||||
|
||||
use crate::core_foundation::MainRunLoopObserver;
|
||||
|
||||
/// Create two run loop observers that add TRACE-level [spans][tracing::span].
|
||||
///
|
||||
/// This is useful when debugging run loops, it makes it easier to see in which run loop activity an
|
||||
/// event is triggered inside (if any).
|
||||
///
|
||||
/// When debugging these interactions, it can also be useful to configure your tracing subscriber
|
||||
/// with `.with_span_events(tracing_subscriber::fmt::format::FmtSpan::ACTIVE)` to emit events upon
|
||||
/// entering and exiting these stages.
|
||||
pub fn tracing_observers(
|
||||
mtm: MainThreadMarker,
|
||||
) -> Option<(MainRunLoopObserver, MainRunLoopObserver)> {
|
||||
// Observers are a bit costly, so don't create them if the tracing-level for this module is
|
||||
// configured to disable them.
|
||||
if !span_enabled!(Level::TRACE) {
|
||||
return None;
|
||||
}
|
||||
|
||||
/// The state that we think the runloop is currently in.
|
||||
///
|
||||
/// The order of activities we observe if waiting twice looks something like:
|
||||
/// - CFRunLoopActivity::Entry
|
||||
/// - CFRunLoopActivity::BeforeTimers
|
||||
/// - CFRunLoopActivity::BeforeSources
|
||||
/// - CFRunLoopActivity::BeforeWaiting
|
||||
/// - CFRunLoopActivity::AfterWaiting
|
||||
/// - CFRunLoopActivity::BeforeTimers
|
||||
/// - CFRunLoopActivity::BeforeSources
|
||||
/// - CFRunLoopActivity::BeforeWaiting
|
||||
/// - CFRunLoopActivity::AfterWaiting
|
||||
/// - CFRunLoopActivity::Exit
|
||||
///
|
||||
/// And if not waiting, it looks something like:
|
||||
/// - CFRunLoopActivity::Entry
|
||||
/// - CFRunLoopActivity::BeforeTimers
|
||||
/// - CFRunLoopActivity::BeforeSources
|
||||
/// - CFRunLoopActivity::Exit
|
||||
#[derive(Default)]
|
||||
#[allow(unused)] // EnteredSpans are kept around
|
||||
enum RunLoopState {
|
||||
/// Currently processing `Entry`/`Exit` observers.
|
||||
#[default]
|
||||
Entered,
|
||||
/// Currently processing timers or `BeforeTimers` observers.
|
||||
Timers(EnteredSpan),
|
||||
/// Currently processing sources or `BeforeSources` observers.
|
||||
Sources(EnteredSpan),
|
||||
/// Currently waiting or processing `BeforeWaiting`/`AfterWaiting` observers.
|
||||
Waiting(EnteredSpan),
|
||||
}
|
||||
|
||||
// A list of currently entered (outer) spans and their state.
|
||||
//
|
||||
// This is a list because runloops can be run recursively.
|
||||
let spans: Rc<RefCell<Vec<(EnteredSpan, RunLoopState)>>> = Rc::new(RefCell::new(Vec::new()));
|
||||
let spans_clone = Rc::clone(&spans);
|
||||
|
||||
// An observer at the start of run loop activities.
|
||||
let activities = CFRunLoopActivity::Entry
|
||||
| CFRunLoopActivity::BeforeTimers
|
||||
| CFRunLoopActivity::BeforeSources
|
||||
| CFRunLoopActivity::BeforeWaiting;
|
||||
let start = MainRunLoopObserver::new(mtm, activities, true, CFIndex::MIN, move |activity| {
|
||||
match activity {
|
||||
// Add an outer span for each runloop iteration.
|
||||
CFRunLoopActivity::Entry => {
|
||||
let span = trace_span!("inside runloop", mode = field::Empty);
|
||||
|
||||
// Get the mode dynamically, the observer may added to multiple different modes.
|
||||
let mode = CFRunLoop::current().unwrap().current_mode().unwrap();
|
||||
// Mode isn't interesting if it's the default mode.
|
||||
if &*mode != unsafe { kCFRunLoopDefaultMode }.unwrap() {
|
||||
span.record("mode", field::display(mode));
|
||||
}
|
||||
|
||||
let entered = span.entered();
|
||||
spans.borrow_mut().push((entered, RunLoopState::Entered));
|
||||
},
|
||||
|
||||
// Add inner spans that help inspecting the state the runloop is in.
|
||||
CFRunLoopActivity::BeforeTimers => {
|
||||
if let Some((_, state)) = spans.borrow_mut().last_mut() {
|
||||
*state = RunLoopState::Entered; // Drop any previous spans.
|
||||
*state = RunLoopState::Timers(trace_span!("processing timers").entered());
|
||||
} else {
|
||||
error!("unbalanced observer invocations");
|
||||
}
|
||||
},
|
||||
CFRunLoopActivity::BeforeSources => {
|
||||
if let Some((_, state)) = spans.borrow_mut().last_mut() {
|
||||
*state = RunLoopState::Entered; // Drop any previous spans.
|
||||
*state = RunLoopState::Sources(trace_span!("processing sources").entered());
|
||||
} else {
|
||||
error!("unbalanced observer invocations");
|
||||
}
|
||||
},
|
||||
CFRunLoopActivity::BeforeWaiting => {
|
||||
if let Some((_, state)) = spans.borrow_mut().last_mut() {
|
||||
*state = RunLoopState::Entered; // Drop any previous spans.
|
||||
*state = RunLoopState::Waiting(trace_span!("waiting").entered());
|
||||
} else {
|
||||
error!("unbalanced observer invocations");
|
||||
}
|
||||
},
|
||||
|
||||
activity => unreachable!("unexpected activity: {activity:?}"),
|
||||
}
|
||||
});
|
||||
|
||||
// An observer at the end of run loop activities.
|
||||
let activities = CFRunLoopActivity::AfterWaiting | CFRunLoopActivity::Exit;
|
||||
let end = MainRunLoopObserver::new(mtm, activities, true, CFIndex::MAX, move |activity| {
|
||||
match activity {
|
||||
CFRunLoopActivity::AfterWaiting => {
|
||||
if let Some((_, state)) = spans_clone.borrow_mut().last_mut() {
|
||||
// Transition from the waiting state to the initial state.
|
||||
*state = RunLoopState::Entered;
|
||||
} else {
|
||||
error!("unbalanced observer invocations");
|
||||
}
|
||||
},
|
||||
|
||||
CFRunLoopActivity::Exit => {
|
||||
if let Some((span, state)) = spans_clone.borrow_mut().pop() {
|
||||
drop(state); // Explicitly exit and drop inner span.
|
||||
drop(span); // Explicitly exit and drop outer span.
|
||||
} else {
|
||||
error!("unbalanced observer invocations");
|
||||
}
|
||||
},
|
||||
|
||||
activity => unreachable!("unexpected activity: {activity:?}"),
|
||||
}
|
||||
});
|
||||
|
||||
Some((start, end))
|
||||
}
|
||||
@@ -79,10 +79,6 @@ impl EventHandler {
|
||||
// Allowed, happens if the handler was cleared manually
|
||||
// elsewhere (such as in `applicationWillTerminate:`).
|
||||
},
|
||||
// We use `eprintln!` here over `tracing::error!`, since we're going to abort
|
||||
// immediately after this, and it'd be annoying for the user if they didn't get
|
||||
// any feedback on that if they don't have a tracing subscriber.
|
||||
#[allow(clippy::disallowed_macros)]
|
||||
Err(_) => {
|
||||
// Note: This is not expected to ever happen, this
|
||||
// module generally controls the `RefCell`, and
|
||||
@@ -118,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(user_app)) => {
|
||||
Ok(Some(ref mut 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.
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
mod notification_center;
|
||||
|
||||
pub use self::notification_center::*;
|
||||
@@ -4,7 +4,5 @@
|
||||
pub mod core_foundation;
|
||||
#[cfg(feature = "event-handler")]
|
||||
pub mod event_handler;
|
||||
#[cfg(feature = "foundation")]
|
||||
pub mod foundation;
|
||||
#[cfg(feature = "xkb")]
|
||||
pub mod xkb;
|
||||
|
||||
@@ -12,7 +12,7 @@ use xkbcommon_dl::{
|
||||
xkb_compose_status, xkb_compose_table, xkb_keysym_t,
|
||||
};
|
||||
|
||||
use super::{XKBCH, XkbContext};
|
||||
use super::{XkbContext, XKBCH};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct XkbComposeTable {
|
||||
|
||||
@@ -19,7 +19,7 @@ use {memmap2::MmapOptions, std::os::unix::io::OwnedFd};
|
||||
|
||||
#[cfg(feature = "x11")]
|
||||
use super::XKBXH;
|
||||
use super::{XKBH, XkbContext};
|
||||
use super::{XkbContext, XKBH};
|
||||
|
||||
/// Map the raw X11-style keycode to the `KeyCode` enum.
|
||||
///
|
||||
@@ -37,9 +37,8 @@ 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' 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
|
||||
// The mapping here is heavily influenced by Firefox' source:
|
||||
// https://searchfox.org/mozilla-central/rev/c597e9c789ad36af84a0370d395be066b7dc94f4/widget/NativeKeyToDOMCodeName.h
|
||||
//
|
||||
// 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
|
||||
@@ -160,11 +159,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::ShowAllWindows,
|
||||
// 120 => KeyCode::SCALE,
|
||||
121 => KeyCode::NumpadComma,
|
||||
122 => KeyCode::Lang1,
|
||||
123 => KeyCode::Lang2,
|
||||
@@ -186,7 +185,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,
|
||||
@@ -211,8 +210,8 @@ pub fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
||||
164 => KeyCode::MediaPlayPause,
|
||||
165 => KeyCode::MediaTrackPrevious,
|
||||
166 => KeyCode::MediaStop,
|
||||
167 => KeyCode::MediaRecord,
|
||||
168 => KeyCode::MediaRewind,
|
||||
// 167 => KeyCode::RECORD,
|
||||
// 168 => KeyCode::REWIND,
|
||||
// 169 => KeyCode::PHONE,
|
||||
// 170 => KeyCode::ISO,
|
||||
171 => KeyCode::MediaSelect, // CONFIG
|
||||
@@ -223,8 +222,8 @@ pub fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
||||
// 176 => KeyCode::EDIT,
|
||||
// 177 => KeyCode::SCROLLUP,
|
||||
// 178 => KeyCode::SCROLLDOWN,
|
||||
179 => KeyCode::NumpadParenLeft,
|
||||
180 => KeyCode::NumpadParenRight,
|
||||
// 179 => KeyCode::KPLEFTPAREN,
|
||||
// 180 => KeyCode::KPRIGHTPAREN,
|
||||
// 181 => KeyCode::NEW,
|
||||
// 182 => KeyCode::REDO,
|
||||
183 => KeyCode::F13,
|
||||
@@ -240,14 +239,14 @@ pub fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
||||
193 => KeyCode::F23,
|
||||
194 => KeyCode::F24,
|
||||
// 200 => KeyCode::PLAYCD,
|
||||
201 => KeyCode::MediaPause,
|
||||
// 201 => KeyCode::PAUSECD,
|
||||
// 202 => KeyCode::PROG3,
|
||||
// 203 => KeyCode::PROG4,
|
||||
// 204 => KeyCode::DASHBOARD,
|
||||
// 205 => KeyCode::SUSPEND,
|
||||
// 206 => KeyCode::CLOSE,
|
||||
207 => KeyCode::MediaPlay,
|
||||
208 => KeyCode::MediaFastForward,
|
||||
// 207 => KeyCode::PLAY,
|
||||
// 208 => KeyCode::FASTFORWARD,
|
||||
// 209 => KeyCode::BASSBOOST,
|
||||
// 210 => KeyCode::PRINT,
|
||||
// 211 => KeyCode::HP,
|
||||
@@ -263,16 +262,16 @@ pub fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
||||
// 221 => KeyCode::SHOP,
|
||||
// 222 => KeyCode::ALTERASE,
|
||||
// 223 => KeyCode::CANCEL,
|
||||
224 => KeyCode::BrightnessDown,
|
||||
225 => KeyCode::BrightnessUp,
|
||||
// 224 => KeyCode::BRIGHTNESSDOW,
|
||||
// 225 => KeyCode::BRIGHTNESSU,
|
||||
// 226 => KeyCode::MEDIA,
|
||||
227 => KeyCode::DisplayToggleIntExt,
|
||||
228 => KeyCode::KeyboardBacklightToggle,
|
||||
// 227 => KeyCode::SWITCHVIDEOMODE,
|
||||
// 228 => KeyCode::KBDILLUMTOGGLE,
|
||||
// 229 => KeyCode::KBDILLUMDOWN,
|
||||
// 230 => KeyCode::KBDILLUMUP,
|
||||
231 => KeyCode::MailSend,
|
||||
232 => KeyCode::MailReply,
|
||||
233 => KeyCode::MailForward,
|
||||
// 231 => KeyCode::SEND,
|
||||
// 232 => KeyCode::REPLY,
|
||||
// 233 => KeyCode::FORWARDMAIL,
|
||||
// 234 => KeyCode::SAVE,
|
||||
// 235 => KeyCode::DOCUMENTS,
|
||||
// 236 => KeyCode::BATTERY,
|
||||
@@ -287,14 +286,7 @@ pub fn scancode_to_physicalkey(scancode: u32) -> PhysicalKey {
|
||||
// 245 => KeyCode::DISPLAY_OFF,
|
||||
// 246 => KeyCode::WWAN,
|
||||
// 247 => KeyCode::RFKILL,
|
||||
248 => KeyCode::MicrophoneMuteToggle,
|
||||
372 => KeyCode::ZoomToggle,
|
||||
579 => KeyCode::LaunchControlPanel,
|
||||
580 => KeyCode::SelectTask,
|
||||
581 => KeyCode::LaunchScreenSaver,
|
||||
583 => KeyCode::LaunchAssistant,
|
||||
584 => KeyCode::KeyboardLayoutSelect,
|
||||
633 => KeyCode::PrivacyScreenToggle,
|
||||
// 248 => KeyCode::KEY_MICMUTE,
|
||||
_ => return PhysicalKey::Unidentified(NativeKeyCode::Xkb(scancode)),
|
||||
})
|
||||
}
|
||||
@@ -423,10 +415,8 @@ 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),
|
||||
@@ -446,7 +436,6 @@ 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),
|
||||
@@ -458,13 +447,9 @@ 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),
|
||||
@@ -477,26 +462,7 @@ 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,
|
||||
}
|
||||
}
|
||||
@@ -1052,7 +1018,11 @@ impl XkbKeymap {
|
||||
&mut keysyms,
|
||||
);
|
||||
|
||||
if count == 1 { *keysyms } else { 0 }
|
||||
if count == 1 {
|
||||
*keysyms
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1096,6 +1066,10 @@ 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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::LazyLock;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::LazyLock;
|
||||
|
||||
use smol_str::SmolStr;
|
||||
use winit_core::event::{ElementState, KeyEvent};
|
||||
use winit_core::keyboard::{Key, KeyLocation};
|
||||
use xkbcommon_dl::{
|
||||
self as xkb, XkbCommon, XkbCommonCompose, xkb_compose_status, xkb_context, xkb_context_flags,
|
||||
xkbcommon_compose_handle, xkbcommon_handle,
|
||||
self as xkb, xkb_compose_status, xkb_context, xkb_context_flags, xkbcommon_compose_handle,
|
||||
xkbcommon_handle, XkbCommon, XkbCommonCompose,
|
||||
};
|
||||
#[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,7 +310,11 @@ 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> {
|
||||
|
||||
@@ -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::keymap::XkbKeymap;
|
||||
use super::{XKBH, make_string_with};
|
||||
use super::{make_string_with, XKBH};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct XkbState {
|
||||
|
||||
@@ -8,7 +8,7 @@ use std::time::Duration;
|
||||
#[doc(inline)]
|
||||
pub use cursor_icon::CursorIcon;
|
||||
|
||||
use crate::as_any::AsAny;
|
||||
use crate::as_any::{impl_dyn_casting, AsAny};
|
||||
|
||||
/// The maximum width and height for a cursor when using [`CustomCursorSource::from_rgba`].
|
||||
pub const MAX_CURSOR_SIZE: u16 = 2048;
|
||||
|
||||
@@ -35,7 +35,11 @@ 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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,7 +78,11 @@ 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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,5 +149,7 @@ 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)
|
||||
}};
|
||||
}
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
//! 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};
|
||||
|
||||
@@ -10,13 +7,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)]
|
||||
@@ -156,8 +153,6 @@ pub enum WindowEvent {
|
||||
Ime(Ime),
|
||||
|
||||
/// The pointer has moved on the window.
|
||||
///
|
||||
/// Should be emitted regardless of window focus.
|
||||
PointerMoved {
|
||||
device_id: Option<DeviceId>,
|
||||
|
||||
@@ -186,8 +181,6 @@ pub enum WindowEvent {
|
||||
},
|
||||
|
||||
/// The pointer has entered the window.
|
||||
///
|
||||
/// Should be emitted regardless of window focus.
|
||||
PointerEntered {
|
||||
device_id: Option<DeviceId>,
|
||||
|
||||
@@ -213,8 +206,6 @@ pub enum WindowEvent {
|
||||
},
|
||||
|
||||
/// The pointer has left the window.
|
||||
///
|
||||
/// Should be emitted regardless of window focus.
|
||||
PointerLeft {
|
||||
device_id: Option<DeviceId>,
|
||||
|
||||
@@ -273,7 +264,7 @@ pub enum WindowEvent {
|
||||
///
|
||||
/// ## Platform-specific
|
||||
///
|
||||
/// - Only available on **macOS**, **iOS**, and **Wayland**.
|
||||
/// - Only available on **macOS** and **iOS**.
|
||||
/// - On iOS, not recognized by default. It must be enabled when needed.
|
||||
PinchGesture {
|
||||
device_id: Option<DeviceId>,
|
||||
@@ -289,7 +280,7 @@ pub enum WindowEvent {
|
||||
///
|
||||
/// ## Platform-specific
|
||||
///
|
||||
/// - Only available on **iOS** and **Wayland**.
|
||||
/// - Only available on **iOS**.
|
||||
/// - On iOS, not recognized by default. It must be enabled when needed.
|
||||
PanGesture {
|
||||
device_id: Option<DeviceId>,
|
||||
@@ -325,7 +316,7 @@ pub enum WindowEvent {
|
||||
///
|
||||
/// ## Platform-specific
|
||||
///
|
||||
/// - Only available on **macOS**, **iOS**, and **Wayland**.
|
||||
/// - Only available on **macOS** and **iOS**.
|
||||
/// - On iOS, not recognized by default. It must be enabled when needed.
|
||||
RotationGesture {
|
||||
device_id: Option<DeviceId>,
|
||||
@@ -444,7 +435,6 @@ pub enum PointerKind {
|
||||
///
|
||||
/// **macOS:** Unsupported.
|
||||
Touch(FingerId),
|
||||
TabletTool(TabletToolKind),
|
||||
Unknown,
|
||||
}
|
||||
|
||||
@@ -495,13 +485,6 @@ 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,
|
||||
}
|
||||
|
||||
@@ -510,7 +493,6 @@ 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,
|
||||
}
|
||||
}
|
||||
@@ -520,21 +502,8 @@ impl From<PointerSource> for PointerKind {
|
||||
///
|
||||
/// **Wayland/X11:** [`Unknown`](Self::Unknown) device types are converted to known variants by the
|
||||
/// system.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum ButtonSource {
|
||||
/// ## Platform-specific
|
||||
///
|
||||
/// ### macOS
|
||||
///
|
||||
/// Users may expect holding [<kbd>CTRL</kbd>](ModifiersState::CONTROL) while
|
||||
/// clicking [`MouseButton::Left`] to result in a "secondary" click, but the way these
|
||||
/// clicks behave natively is slightly different from how a physical secondary
|
||||
/// button press would, depending on the content under the cursor when clicked. If
|
||||
/// applications want this behavior they should implement it themselves by interpreting
|
||||
/// [`Left`](MouseButton::Left) clicks as secondary when
|
||||
/// [<kbd>CTRL</kbd>](ModifiersState::CONTROL) is held and their internal logic deems it
|
||||
/// appropriate for the content under the pointer.
|
||||
/// See also https://github.com/rust-windowing/winit/issues/4469.
|
||||
Mouse(MouseButton),
|
||||
/// See [`PointerSource::Touch`] for more details.
|
||||
///
|
||||
@@ -545,27 +514,25 @@ 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 {
|
||||
/// Try to convert a [`ButtonSource`] to an equivalent [`MouseButton`]. If a pointer type has no
|
||||
/// Convert any [`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) -> Option<MouseButton> {
|
||||
pub fn mouse_button(self) -> MouseButton {
|
||||
match self {
|
||||
ButtonSource::Mouse(mouse) => Some(mouse),
|
||||
ButtonSource::Touch { .. } => Some(MouseButton::Left),
|
||||
ButtonSource::TabletTool { button, .. } => button.into(),
|
||||
ButtonSource::Unknown(_) => None,
|
||||
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),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -778,7 +745,7 @@ pub struct KeyEvent {
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// In games, you often want to ignore repeated key events - this can be
|
||||
/// In games, you often want to ignore repated key events - this can be
|
||||
/// done by ignoring events where this property is set.
|
||||
///
|
||||
/// ```no_run
|
||||
@@ -803,14 +770,13 @@ pub struct KeyEvent {
|
||||
/// ```
|
||||
pub repeat: bool,
|
||||
|
||||
/// Similar to [`text`][Self::text], except that this is affected by <kbd>Ctrl</kbd> and may
|
||||
/// produce ASCII control characters.
|
||||
/// Similar to [`text`][Self::text], except that this is affected by <kbd>Ctrl</kbd>.
|
||||
///
|
||||
/// For example, pressing <kbd>Ctrl</kbd>+<kbd>space</kbd> produces `Some("\x00")`.
|
||||
/// For example, pressing <kbd>Ctrl</kbd>+<kbd>a</kbd> produces `Some("\x01")`.
|
||||
///
|
||||
/// ## Platform-specific
|
||||
///
|
||||
/// - **Android:** This field is always the same value as `text`.
|
||||
/// - **Android:** Unimplemented, this field is always the same value as `text`.
|
||||
/// - **iOS:** Unimplemented, this field is always the same value as `text`.
|
||||
/// - **Web:** Unsupported, this field is always the same value as `text`.
|
||||
pub text_with_all_modifiers: Option<SmolStr>,
|
||||
@@ -1015,7 +981,6 @@ 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
|
||||
@@ -1026,7 +991,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 [`TabletToolAngle::altitude`] value.
|
||||
/// calculate this value using the `altitude_angle` value.
|
||||
force: f64,
|
||||
/// The maximum possible force for a touch.
|
||||
///
|
||||
@@ -1047,17 +1012,9 @@ 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.
|
||||
///
|
||||
/// Passing in a [`TabletToolAngle`], returns the perpendicular force.
|
||||
pub fn normalized(&self, angle: Option<TabletToolAngle>) -> f64 {
|
||||
pub fn normalized(&self) -> f64 {
|
||||
match self {
|
||||
Force::Calibrated { force, max_possible_force } => {
|
||||
let force = match angle {
|
||||
Some(TabletToolAngle { altitude, .. }) => force / altitude.sin(),
|
||||
None => *force,
|
||||
};
|
||||
force / max_possible_force
|
||||
},
|
||||
Force::Calibrated { force, max_possible_force } => force / max_possible_force,
|
||||
Force::Normalized(force) => *force,
|
||||
}
|
||||
}
|
||||
@@ -1069,260 +1026,6 @@ 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.
|
||||
///
|
||||
/// 
|
||||
///
|
||||
/// <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.
|
||||
///
|
||||
/// 
|
||||
///
|
||||
/// <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.
|
||||
///
|
||||
/// 
|
||||
///
|
||||
/// <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.
|
||||
///
|
||||
/// 
|
||||
///
|
||||
/// <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))]
|
||||
@@ -1338,138 +1041,23 @@ impl ElementState {
|
||||
}
|
||||
}
|
||||
|
||||
/// Identifies a button of a mouse controller.
|
||||
/// Describes a button of a mouse controller.
|
||||
///
|
||||
/// ## Platform-specific
|
||||
///
|
||||
/// 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`.
|
||||
/// **macOS:** `Back` and `Forward` might not work with all hardware.
|
||||
/// **Orbital:** `Back` and `Forward` are unsupported due to orbital not supporting them.
|
||||
#[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
#[repr(u8)]
|
||||
pub enum MouseButton {
|
||||
/// 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,
|
||||
Left,
|
||||
Right,
|
||||
Middle,
|
||||
Back,
|
||||
Forward,
|
||||
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))]
|
||||
@@ -1600,7 +1188,7 @@ mod tests {
|
||||
primary: true,
|
||||
state: event::ElementState::Pressed,
|
||||
position: (0, 0).into(),
|
||||
button: event::ButtonSource::Unknown(0),
|
||||
button: event::MouseButton::Other(0).into(),
|
||||
});
|
||||
with_window_event(PointerButton {
|
||||
device_id: None,
|
||||
@@ -1653,85 +1241,16 @@ 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(None), 0.0);
|
||||
assert_eq!(force.normalized(), 0.0);
|
||||
|
||||
let force2 = event::Force::Calibrated { force: 5.0, max_possible_force: 2.5 };
|
||||
assert_eq!(force2.normalized(None), 2.0);
|
||||
assert_eq!(force2.normalized(), 2.0);
|
||||
|
||||
let force3 = event::Force::Calibrated { force: 5.0, max_possible_force: 2.5 };
|
||||
assert_eq!(
|
||||
force3.normalized(Some(event::TabletToolAngle {
|
||||
altitude: std::f64::consts::PI / 2.0,
|
||||
azimuth: 0.
|
||||
})),
|
||||
2.0
|
||||
);
|
||||
assert_eq!(force3.normalized(), 2.0);
|
||||
}
|
||||
|
||||
#[allow(clippy::clone_on_copy)]
|
||||
|
||||
@@ -1,21 +1,20 @@
|
||||
pub mod never_return;
|
||||
pub mod pump_events;
|
||||
pub mod register;
|
||||
pub mod run_on_demand;
|
||||
|
||||
use std::fmt::{self, Debug};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::task::Waker;
|
||||
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
|
||||
@@ -152,6 +151,13 @@ impl EventLoopProxy {
|
||||
self.proxy.wake_up();
|
||||
}
|
||||
|
||||
/// Get a [`Waker`] that calls [`wake_up`] on the proxy when awoken.
|
||||
///
|
||||
/// This may be useful to `async` code or otherwise interoperating with `std`.
|
||||
pub fn waker(&self) -> Waker {
|
||||
self.proxy.waker()
|
||||
}
|
||||
|
||||
pub fn new(proxy: Arc<dyn EventLoopProxyProvider>) -> Self {
|
||||
Self { proxy }
|
||||
}
|
||||
@@ -160,6 +166,9 @@ impl EventLoopProxy {
|
||||
pub trait EventLoopProxyProvider: Send + Sync + Debug {
|
||||
/// See [`EventLoopProxy::wake_up`] for details.
|
||||
fn wake_up(&self);
|
||||
|
||||
/// See [`EventLoopProxy::waker`] for details.
|
||||
fn waker(&self) -> Waker;
|
||||
}
|
||||
|
||||
/// A proxy for the underlying display handle.
|
||||
@@ -176,11 +185,11 @@ pub trait EventLoopProxyProvider: Send + Sync + Debug {
|
||||
/// - A reference-counted pointer to the underlying type.
|
||||
#[derive(Clone)]
|
||||
pub struct OwnedDisplayHandle {
|
||||
pub(crate) handle: Arc<dyn HasDisplayHandle + Send + Sync>,
|
||||
pub(crate) handle: Arc<dyn HasDisplayHandle>,
|
||||
}
|
||||
|
||||
impl OwnedDisplayHandle {
|
||||
pub fn new(handle: Arc<dyn HasDisplayHandle + Send + Sync>) -> Self {
|
||||
pub fn new(handle: Arc<dyn HasDisplayHandle>) -> Self {
|
||||
Self { handle }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
use crate::application::ApplicationHandler;
|
||||
|
||||
/// Additional methods on `EventLoop` for platforms whose run method never return.
|
||||
pub trait EventLoopExtNeverReturn {
|
||||
/// Run the event loop and call `process::exit` once finished.
|
||||
///
|
||||
/// ## Platform-specific
|
||||
///
|
||||
/// - **iOS**: This registers the callbacks with the system and calls `UIApplicationMain`.
|
||||
/// - **macOS**: Unimplemented (TODO: Should call `NSApplicationMain`).
|
||||
/// - **Android/Orbital/Wayland/Windows/X11**: Unsupported.
|
||||
/// - **Web**: Impossible to support properly.
|
||||
fn run_app_never_return<A: ApplicationHandler + 'static>(self, app: A) -> !;
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
use crate::application::ApplicationHandler;
|
||||
|
||||
/// Additional methods on `EventLoop` that registers it with the system event loop.
|
||||
pub trait EventLoopExtRegister {
|
||||
/// Initialize and register the application with the system's event loop, such that the
|
||||
/// callbacks will be run later.
|
||||
///
|
||||
/// ## Platform-specific
|
||||
///
|
||||
/// - **Web**: Once the event loop has been destroyed, it's possible to reinitialize another
|
||||
/// event loop by calling this function again. This can be useful if you want to recreate the
|
||||
/// event loop while the WebAssembly module is still loaded. For example, this can be used to
|
||||
/// recreate the event loop when switching between tabs on a single page application.
|
||||
/// - **iOS/macOS**: Unimplemented.
|
||||
/// - **Android/Orbital/Wayland/Windows/X11**: Unsupported.
|
||||
fn register_app<A: ApplicationHandler + 'static>(self, app: A);
|
||||
}
|
||||
@@ -2,17 +2,19 @@ use crate::application::ApplicationHandler;
|
||||
use crate::error::EventLoopError;
|
||||
#[cfg(doc)]
|
||||
use crate::{
|
||||
event_loop::{ActiveEventLoop, pump_events::EventLoopExtPumpEvents},
|
||||
event_loop::{pump_events::EventLoopExtPumpEvents, ActiveEventLoop},
|
||||
window::Window,
|
||||
};
|
||||
|
||||
#[allow(rustdoc::broken_intra_doc_links)] // FIXME(madsmtm): Fix these.
|
||||
/// Additional methods on [`EventLoop`] to return control flow to the caller.
|
||||
pub trait EventLoopExtRunOnDemand {
|
||||
/// Run the application with the event loop on the calling thread.
|
||||
///
|
||||
/// Unlike [`EventLoop::run_app`], this function accepts non-`'static` (i.e. non-`move`)
|
||||
/// state and it is possible to return control back to the caller without consuming the
|
||||
/// `EventLoop` (by using [`exit()`]) and so the event loop can be re-run after it has exit.
|
||||
/// closures and it is possible to return control back to the caller without
|
||||
/// consuming the `EventLoop` (by using [`exit()`]) and
|
||||
/// so the event loop can be re-run after it has exit.
|
||||
///
|
||||
/// It's expected that each run of the loop will be for orthogonal instantiations of your
|
||||
/// Winit application, but internally each instantiation may re-use some common window
|
||||
@@ -29,7 +31,8 @@ pub trait EventLoopExtRunOnDemand {
|
||||
///
|
||||
/// # Caveats
|
||||
/// - This extension isn't available on all platforms, since it's not always possible to return
|
||||
/// to the caller (specifically this is impossible on iOS and Web).
|
||||
/// to the caller (specifically this is impossible on iOS and Web - though with the Web
|
||||
/// backend it is possible to use `EventLoopExtWeb::spawn_app()`[^1] more than once instead).
|
||||
/// - No [`Window`] state can be carried between separate runs of the event loop.
|
||||
///
|
||||
/// You are strongly encouraged to use [`EventLoop::run_app()`] for portability, unless you
|
||||
@@ -48,6 +51,8 @@ pub trait EventLoopExtRunOnDemand {
|
||||
/// are delivered via callbacks based on an event loop that is internal to the browser itself.
|
||||
/// - **iOS:** It's not possible to stop and start an `UIApplication` repeatedly on iOS.
|
||||
///
|
||||
/// [^1]: `spawn_app()` is only available on the Web platforms.
|
||||
///
|
||||
/// [`exit()`]: ActiveEventLoop::exit()
|
||||
/// [`set_control_flow()`]: ActiveEventLoop::set_control_flow()
|
||||
fn run_app_on_demand<A: ApplicationHandler>(&mut self, app: A) -> Result<(), EventLoopError>;
|
||||
|
||||
@@ -3,7 +3,7 @@ use std::ops::Deref;
|
||||
use std::sync::Arc;
|
||||
use std::{fmt, io, mem};
|
||||
|
||||
use crate::as_any::AsAny;
|
||||
use crate::as_any::{impl_dyn_casting, AsAny};
|
||||
|
||||
pub(crate) const PIXEL_SIZE: usize = mem::size_of::<u32>();
|
||||
|
||||
|
||||
@@ -29,13 +29,11 @@ pub enum NativeKeyCode {
|
||||
Windows(u16),
|
||||
/// An XKB "keycode".
|
||||
Xkb(u32),
|
||||
/// An OpenHarmony "scancode".
|
||||
Ohos(u32),
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for NativeKeyCode {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
use NativeKeyCode::{Android, MacOS, Ohos, Unidentified, Windows, Xkb};
|
||||
use NativeKeyCode::{Android, MacOS, Unidentified, Windows, Xkb};
|
||||
let mut debug_tuple;
|
||||
match self {
|
||||
Unidentified => {
|
||||
@@ -57,10 +55,6 @@ impl std::fmt::Debug for NativeKeyCode {
|
||||
debug_tuple = f.debug_tuple("Xkb");
|
||||
debug_tuple.field(&format_args!("0x{code:04X}"));
|
||||
},
|
||||
Ohos(code) => {
|
||||
debug_tuple = f.debug_tuple("OpenHarmony");
|
||||
debug_tuple.field(&format_args!("0x{code:04X}"));
|
||||
},
|
||||
}
|
||||
debug_tuple.finish()
|
||||
}
|
||||
@@ -91,13 +85,11 @@ pub enum NativeKey {
|
||||
Xkb(u32),
|
||||
/// A "key value string".
|
||||
Web(SmolStr),
|
||||
/// An OpenHarmony "keycode", which is similar to a "virtual-key code" on Windows.
|
||||
Ohos(u32),
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for NativeKey {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
use NativeKey::{Android, MacOS, Ohos, Unidentified, Web, Windows, Xkb};
|
||||
use NativeKey::{Android, MacOS, Unidentified, Web, Windows, Xkb};
|
||||
let mut debug_tuple;
|
||||
match self {
|
||||
Unidentified => {
|
||||
@@ -123,10 +115,6 @@ impl std::fmt::Debug for NativeKey {
|
||||
debug_tuple = f.debug_tuple("Web");
|
||||
debug_tuple.field(code);
|
||||
},
|
||||
Ohos(code) => {
|
||||
debug_tuple = f.debug_tuple("OpenHarmony");
|
||||
debug_tuple.field(code);
|
||||
},
|
||||
}
|
||||
debug_tuple.finish()
|
||||
}
|
||||
@@ -141,7 +129,6 @@ impl From<NativeKeyCode> for NativeKey {
|
||||
NativeKeyCode::MacOS(x) => NativeKey::MacOS(x),
|
||||
NativeKeyCode::Windows(x) => NativeKey::Windows(x),
|
||||
NativeKeyCode::Xkb(x) => NativeKey::Xkb(x),
|
||||
NativeKeyCode::Ohos(x) => NativeKey::Ohos(x),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -206,7 +193,7 @@ impl PartialEq<KeyCode> for PhysicalKey {
|
||||
#[inline]
|
||||
fn eq(&self, rhs: &KeyCode) -> bool {
|
||||
match self {
|
||||
PhysicalKey::Code(code) => code == rhs,
|
||||
PhysicalKey::Code(ref code) => code == rhs,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -223,7 +210,7 @@ impl PartialEq<NativeKeyCode> for PhysicalKey {
|
||||
#[inline]
|
||||
fn eq(&self, rhs: &NativeKeyCode) -> bool {
|
||||
match self {
|
||||
PhysicalKey::Unidentified(code) => code == rhs,
|
||||
PhysicalKey::Unidentified(ref code) => code == rhs,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -288,7 +275,7 @@ impl<Str> PartialEq<NamedKey> for Key<Str> {
|
||||
#[inline]
|
||||
fn eq(&self, rhs: &NamedKey) -> bool {
|
||||
match self {
|
||||
Key::Named(a) => a == rhs,
|
||||
Key::Named(ref a) => a == rhs,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -298,7 +285,7 @@ impl<Str: PartialEq<str>> PartialEq<str> for Key<Str> {
|
||||
#[inline]
|
||||
fn eq(&self, rhs: &str) -> bool {
|
||||
match self {
|
||||
Key::Character(s) => s == rhs,
|
||||
Key::Character(ref s) => s == rhs,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -315,7 +302,7 @@ impl<Str> PartialEq<NativeKey> for Key<Str> {
|
||||
#[inline]
|
||||
fn eq(&self, rhs: &NativeKey) -> bool {
|
||||
match self {
|
||||
Key::Unidentified(code) => code == rhs,
|
||||
Key::Unidentified(ref code) => code == rhs,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ use std::sync::Arc;
|
||||
|
||||
use dpi::{PhysicalPosition, PhysicalSize};
|
||||
|
||||
use crate::as_any::AsAny;
|
||||
use crate::as_any::{impl_dyn_casting, AsAny};
|
||||
|
||||
/// Handle to a monitor.
|
||||
///
|
||||
|
||||
@@ -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;
|
||||
@@ -834,7 +834,7 @@ pub trait Window: AsAny + Send + Sync + fmt::Debug {
|
||||
///
|
||||
/// ## Platform-specific
|
||||
///
|
||||
/// - **iOS / Android / Web / Orbital:** Always returns [`None`].
|
||||
/// - **iOS / Android / Web / Wayland / Orbital:** Always returns [`None`].
|
||||
fn surface_resize_increments(&self) -> Option<PhysicalSize<u32>>;
|
||||
|
||||
/// Sets resize increments of the surface.
|
||||
@@ -846,6 +846,7 @@ pub trait Window: AsAny + Send + Sync + fmt::Debug {
|
||||
///
|
||||
/// - **macOS:** Increments are converted to logical size and then macOS rounds them to whole
|
||||
/// numbers.
|
||||
/// - **Wayland:** Not implemented.
|
||||
/// - **iOS / Android / Web / Orbital:** Unsupported.
|
||||
fn set_surface_resize_increments(&self, increments: Option<Size>);
|
||||
|
||||
@@ -995,8 +996,7 @@ 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.
|
||||
/// - **Orbital / Wayland:** Does not support exclusive fullscreen mode and will no-op a
|
||||
/// request.
|
||||
/// - **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 +1009,9 @@ pub trait Window: AsAny + Send + Sync + fmt::Debug {
|
||||
///
|
||||
/// ## Platform-specific
|
||||
///
|
||||
/// - **Android:** Will always return `None`.
|
||||
/// - **Orbital / Web:** Can only return `None` or `Borderless(None)`.
|
||||
/// - **Android / Orbital:** Will always return `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 +1135,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_hint_and_purpose().with_cursor_area();
|
||||
let ime_caps = ImeCapabilities::new().with_purpose().with_cursor_area();
|
||||
let request_data = ImeRequestData {
|
||||
hint_and_purpose: Some((ImeHint::NONE, ImePurpose::Normal)),
|
||||
purpose: Some(ImePurpose::Normal),
|
||||
// WARNING: there's nothing sensible to use here by default.
|
||||
cursor_area: Some((position.into(), size.into())),
|
||||
..ImeRequestData::default()
|
||||
@@ -1159,9 +1159,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.hint_and_purpose()).unwrap_or(false) {
|
||||
if self.ime_capabilities().map(|caps| caps.purpose()).unwrap_or(false) {
|
||||
let _ = self.request_ime_update(ImeRequest::Update(ImeRequestData {
|
||||
hint_and_purpose: Some((ImeHint::NONE, purpose)),
|
||||
purpose: Some(purpose),
|
||||
..ImeRequestData::default()
|
||||
}));
|
||||
}
|
||||
@@ -1185,14 +1185,14 @@ pub trait Window: AsAny + Send + Sync + fmt::Debug {
|
||||
///
|
||||
/// ```no_run
|
||||
/// # use dpi::{Position, Size};
|
||||
/// # use winit_core::window::{Window, ImeHint, ImePurpose, ImeRequest, ImeCapabilities, ImeRequestData, ImeEnableRequest};
|
||||
/// # use winit_core::window::{Window, 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_hint_and_purpose();
|
||||
/// let ime_caps = ImeCapabilities::new().with_cursor_area().with_purpose();
|
||||
/// let request_data = ImeRequestData::default()
|
||||
/// .with_hint_and_purpose(ImeHint::NONE, ImePurpose::Normal)
|
||||
/// .with_purpose(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,86 +1597,29 @@ 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, Default)]
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub enum ImePurpose {
|
||||
/// No special purpose for the IME (default).
|
||||
#[default]
|
||||
/// No special hints for the IME (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,
|
||||
}
|
||||
|
||||
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;
|
||||
impl Default for ImePurpose {
|
||||
fn default() -> Self {
|
||||
Self::Normal
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1690,22 +1633,6 @@ pub enum ImeSurroundingTextError {
|
||||
AnchorBadPosition,
|
||||
}
|
||||
|
||||
impl fmt::Display for ImeSurroundingTextError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
ImeSurroundingTextError::TextTooLong => write!(f, "text exceeds maximum length"),
|
||||
ImeSurroundingTextError::CursorBadPosition => {
|
||||
write!(f, "cursor is not at a valid text index")
|
||||
},
|
||||
ImeSurroundingTextError::AnchorBadPosition => {
|
||||
write!(f, "anchor is not at a valid text index")
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ImeSurroundingTextError {}
|
||||
|
||||
/// Defines the text surrounding the caret
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
@@ -1800,7 +1727,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
|
||||
/// applies to both [`ImeRequest::Enable`] and [`ImeRequest::Update`]. For details on
|
||||
/// appiles 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.
|
||||
@@ -1831,7 +1758,7 @@ impl ImeEnableRequest {
|
||||
return None;
|
||||
}
|
||||
|
||||
if capabilities.hint_and_purpose() ^ request_data.hint_and_purpose.is_some() {
|
||||
if capabilities.purpose() ^ request_data.purpose.is_some() {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -1876,23 +1803,23 @@ impl ImeCapabilities {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Marks `hint and purpose` as supported.
|
||||
/// Marks `purpose` as supported.
|
||||
///
|
||||
/// 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))
|
||||
/// For more details see [`ImeRequestData::with_purpose`].
|
||||
pub const fn with_purpose(self) -> Self {
|
||||
Self(self.0.union(ImeCapabilitiesFlags::PURPOSE))
|
||||
}
|
||||
|
||||
/// Marks `hint and purpose` as unsupported.
|
||||
/// Marks `purpose` as unsupported.
|
||||
///
|
||||
/// 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))
|
||||
/// For more details see [`ImeRequestData::with_purpose`].
|
||||
pub const fn without_purpose(self) -> Self {
|
||||
Self(self.0.difference(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)
|
||||
/// Returns `true` if `purpose` is supported.
|
||||
pub const fn purpose(&self) -> bool {
|
||||
self.0.contains(ImeCapabilitiesFlags::PURPOSE)
|
||||
}
|
||||
|
||||
/// Marks `cursor_area` as supported.
|
||||
@@ -1937,8 +1864,8 @@ impl ImeCapabilities {
|
||||
bitflags! {
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
|
||||
pub(crate) struct ImeCapabilitiesFlags : u8 {
|
||||
/// Client supports setting IME hint and purpose.
|
||||
const HINT_AND_PURPOSE = 1 << 0;
|
||||
/// Client supports setting IME purpose.
|
||||
const PURPOSE = 1 << 0;
|
||||
/// Client supports reporting cursor area for IME popup to
|
||||
/// appear.
|
||||
const CURSOR_AREA = 1 << 1;
|
||||
@@ -1956,24 +1883,24 @@ bitflags! {
|
||||
#[derive(Debug, PartialEq, Clone, Default)]
|
||||
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||
pub struct ImeRequestData {
|
||||
/// Text input hint and purpose.
|
||||
/// Text input purpose.
|
||||
///
|
||||
/// To support updating it, enable [`ImeCapabilities::hint_and_purpose()`].
|
||||
pub hint_and_purpose: Option<(ImeHint, ImePurpose)>,
|
||||
/// To support updating it, enable [`ImeCapabilities::PURPOSE`].
|
||||
pub purpose: Option<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 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 purpose hint of the current text input.
|
||||
pub fn with_purpose(self, purpose: ImePurpose) -> Self {
|
||||
Self { purpose: Some(purpose), ..self }
|
||||
}
|
||||
|
||||
/// Sets the IME cursor editing area.
|
||||
@@ -2099,73 +2026,59 @@ mod tests {
|
||||
ImeCapabilities, ImeEnableRequest, ImeRequestData, ImeSurroundingText,
|
||||
ImeSurroundingTextError,
|
||||
};
|
||||
use crate::window::{ImeHint, ImePurpose};
|
||||
use crate::window::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_hint_and_purpose(),
|
||||
ImeRequestData::default()
|
||||
)
|
||||
.is_none()
|
||||
);
|
||||
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().with_hint_and_purpose(ImeHint::NONE, ImePurpose::Normal)
|
||||
)
|
||||
.is_none()
|
||||
);
|
||||
assert!(ImeEnableRequest::new(
|
||||
ImeCapabilities::new().with_cursor_area(),
|
||||
ImeRequestData::default().with_purpose(ImePurpose::Normal)
|
||||
)
|
||||
.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(),
|
||||
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_purpose(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_hint_and_purpose().with_cursor_area(),
|
||||
ImeRequestData::default()
|
||||
.with_hint_and_purpose(ImeHint::NONE, ImePurpose::Normal)
|
||||
.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());
|
||||
|
||||
let text: &[u8] = ['a' as u8; 8000].as_slice();
|
||||
let text = std::str::from_utf8(text).unwrap();
|
||||
|
||||
@@ -21,6 +21,5 @@ tracing.workspace = true
|
||||
winit-core.workspace = true
|
||||
|
||||
# Platform-specific
|
||||
libredox.workspace = true
|
||||
orbclient.workspace = true
|
||||
redox_event.workspace = true
|
||||
redox_syscall.workspace = true
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
use std::cell::Cell;
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex, mpsc};
|
||||
use std::sync::{mpsc, Arc, Mutex};
|
||||
use std::task::Waker;
|
||||
use std::time::Instant;
|
||||
use std::{iter, mem, slice};
|
||||
|
||||
@@ -10,7 +11,6 @@ use orbclient::{
|
||||
ButtonEvent, EventOption, FocusEvent, HoverEvent, KeyEvent, MouseEvent, MouseRelativeEvent,
|
||||
MoveEvent, QuitEvent, ResizeEvent, ScrollEvent, TextInputEvent,
|
||||
};
|
||||
use redox_event::{EventFlags, EventQueue};
|
||||
use smol_str::SmolStr;
|
||||
use winit_core::application::ApplicationHandler;
|
||||
use winit_core::cursor::{CustomCursor, CustomCursorSource};
|
||||
@@ -101,7 +101,6 @@ fn convert_scancode(scancode: u8) -> (PhysicalKey, Option<NamedKey>) {
|
||||
orbclient::K_LEFT => (KeyCode::ArrowLeft, Some(NamedKey::ArrowLeft)),
|
||||
orbclient::K_LEFT_SHIFT => (KeyCode::ShiftLeft, Some(NamedKey::Shift)),
|
||||
orbclient::K_MINUS => (KeyCode::Minus, None),
|
||||
|
||||
orbclient::K_NUM_0 => (KeyCode::Numpad0, None),
|
||||
orbclient::K_NUM_1 => (KeyCode::Numpad1, None),
|
||||
orbclient::K_NUM_2 => (KeyCode::Numpad2, None),
|
||||
@@ -112,20 +111,12 @@ fn convert_scancode(scancode: u8) -> (PhysicalKey, Option<NamedKey>) {
|
||||
orbclient::K_NUM_7 => (KeyCode::Numpad7, None),
|
||||
orbclient::K_NUM_8 => (KeyCode::Numpad8, None),
|
||||
orbclient::K_NUM_9 => (KeyCode::Numpad9, None),
|
||||
orbclient::K_NUM_ASTERISK => (KeyCode::NumpadMultiply, None),
|
||||
orbclient::K_NUM_ENTER => (KeyCode::NumpadEnter, Some(NamedKey::Enter)),
|
||||
orbclient::K_NUM_MINUS => (KeyCode::NumpadSubtract, None),
|
||||
orbclient::K_NUM_PLUS => (KeyCode::NumpadAdd, None),
|
||||
orbclient::K_NUM_SLASH => (KeyCode::NumpadDivide, None),
|
||||
orbclient::K_NUM_PERIOD => (KeyCode::NumpadDecimal, None),
|
||||
|
||||
orbclient::K_PERIOD => (KeyCode::Period, None),
|
||||
orbclient::K_PGDN => (KeyCode::PageDown, Some(NamedKey::PageDown)),
|
||||
orbclient::K_PGUP => (KeyCode::PageUp, Some(NamedKey::PageUp)),
|
||||
orbclient::K_QUOTE => (KeyCode::Quote, None),
|
||||
orbclient::K_RIGHT => (KeyCode::ArrowRight, Some(NamedKey::ArrowRight)),
|
||||
orbclient::K_RIGHT_SHIFT => (KeyCode::ShiftRight, Some(NamedKey::Shift)),
|
||||
orbclient::K_RIGHT_SUPER => (KeyCode::MetaRight, Some(NamedKey::Meta)),
|
||||
orbclient::K_SEMICOLON => (KeyCode::Semicolon, None),
|
||||
orbclient::K_SLASH => (KeyCode::Slash, None),
|
||||
orbclient::K_SPACE => (KeyCode::Space, None),
|
||||
@@ -137,27 +128,17 @@ fn convert_scancode(scancode: u8) -> (PhysicalKey, Option<NamedKey>) {
|
||||
orbclient::K_VOLUME_TOGGLE => (KeyCode::AudioVolumeMute, Some(NamedKey::AudioVolumeMute)),
|
||||
orbclient::K_VOLUME_UP => (KeyCode::AudioVolumeUp, Some(NamedKey::AudioVolumeUp)),
|
||||
|
||||
orbclient::K_INS => (KeyCode::Insert, Some(NamedKey::Insert)),
|
||||
orbclient::K_PRTSC => (KeyCode::PrintScreen, Some(NamedKey::PrintScreen)),
|
||||
orbclient::K_NUM => (KeyCode::NumLock, Some(NamedKey::NumLock)),
|
||||
orbclient::K_SCROLL => (KeyCode::ScrollLock, Some(NamedKey::ScrollLock)),
|
||||
orbclient::K_APP => (KeyCode::ContextMenu, Some(NamedKey::ContextMenu)),
|
||||
|
||||
orbclient::K_MEDIA_FAST_FORWARD => {
|
||||
(KeyCode::MediaFastForward, Some(NamedKey::MediaFastForward))
|
||||
},
|
||||
orbclient::K_MEDIA_REWIND => (KeyCode::MediaRewind, Some(NamedKey::MediaRewind)),
|
||||
orbclient::K_MEDIA_STOP => (KeyCode::MediaStop, Some(NamedKey::MediaStop)),
|
||||
|
||||
orbclient::K_POWER => (KeyCode::Power, Some(NamedKey::Power)),
|
||||
|
||||
_ => return (PhysicalKey::Unidentified(NativeKeyCode::Unidentified), None),
|
||||
};
|
||||
(PhysicalKey::Code(key_code), named_key_opt)
|
||||
}
|
||||
|
||||
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! {
|
||||
@@ -296,7 +277,6 @@ impl EventState {
|
||||
pub struct EventLoop {
|
||||
windows: Vec<(Arc<RedoxSocket>, EventState)>,
|
||||
window_target: ActiveEventLoop,
|
||||
user_events_receiver: mpsc::Receiver<()>,
|
||||
}
|
||||
|
||||
impl EventLoop {
|
||||
@@ -312,12 +292,16 @@ impl EventLoop {
|
||||
let (user_events_sender, user_events_receiver) = mpsc::sync_channel(1);
|
||||
|
||||
let event_socket =
|
||||
Arc::new(EventQueue::new().map_err(|error| os_error!(format!("{error}")))?);
|
||||
Arc::new(RedoxSocket::event().map_err(|error| os_error!(format!("{error}")))?);
|
||||
|
||||
let wake_socket = TimeSocket::open().map_err(|error| os_error!(format!("{error}")))?;
|
||||
|
||||
event_socket
|
||||
.subscribe(wake_socket.0.fd(), EventSource::Time, EventFlags::READ)
|
||||
.write(&syscall::Event {
|
||||
id: wake_socket.0.fd,
|
||||
flags: syscall::EventFlags::EVENT_READ,
|
||||
data: wake_socket.0.fd,
|
||||
})
|
||||
.map_err(|error| os_error!(format!("{error}")))?;
|
||||
|
||||
Ok(Self {
|
||||
@@ -501,10 +485,7 @@ impl EventLoop {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run_app_on_demand<A: ApplicationHandler>(
|
||||
&mut self,
|
||||
mut app: A,
|
||||
) -> Result<(), EventLoopError> {
|
||||
pub fn run_app<A: ApplicationHandler>(mut self, mut app: A) -> Result<(), EventLoopError> {
|
||||
let mut start_cause = StartCause::Init;
|
||||
loop {
|
||||
app.new_events(&self.window_target, start_cause);
|
||||
@@ -518,7 +499,7 @@ impl EventLoop {
|
||||
let mut creates = self.window_target.creates.lock().unwrap();
|
||||
creates.pop_front()
|
||||
} {
|
||||
let window_id = WindowId::from_raw(window.fd());
|
||||
let window_id = WindowId::from_raw(window.fd);
|
||||
|
||||
let mut buf: [u8; 4096] = [0; 4096];
|
||||
let path = window.fpath(&mut buf).expect("failed to read properties");
|
||||
@@ -542,18 +523,18 @@ impl EventLoop {
|
||||
} {
|
||||
app.window_event(&self.window_target, destroy_id, event::WindowEvent::Destroyed);
|
||||
self.windows
|
||||
.retain(|(window, _event_state)| WindowId::from_raw(window.fd()) != destroy_id);
|
||||
.retain(|(window, _event_state)| WindowId::from_raw(window.fd) != destroy_id);
|
||||
}
|
||||
|
||||
// Handle window events.
|
||||
let mut i = 0;
|
||||
// While loop is used here because the same window may be processed more than once.
|
||||
while let Some((window, event_state)) = self.windows.get_mut(i) {
|
||||
let window_id = WindowId::from_raw(window.fd());
|
||||
let window_id = WindowId::from_raw(window.fd);
|
||||
|
||||
let mut event_buf = [0u8; 16 * mem::size_of::<orbclient::Event>()];
|
||||
let count = libredox::call::read(window.fd(), &mut event_buf)
|
||||
.expect("failed to read window events");
|
||||
let count =
|
||||
syscall::read(window.fd, &mut event_buf).expect("failed to read window events");
|
||||
// Safety: orbclient::Event is a packed struct designed to be transferred over a
|
||||
// socket.
|
||||
let events = unsafe {
|
||||
@@ -596,7 +577,7 @@ impl EventLoop {
|
||||
i += 1;
|
||||
}
|
||||
|
||||
while self.user_events_receiver.try_recv().is_ok() {
|
||||
if self.wake_up.swap(false, Ordering::Relaxed) {
|
||||
app.proxy_wake_up(&self.window_target);
|
||||
}
|
||||
|
||||
@@ -633,7 +614,11 @@ impl EventLoop {
|
||||
|
||||
self.window_target
|
||||
.event_socket
|
||||
.subscribe(timeout_socket.0.fd(), EventSource::Time, EventFlags::READ)
|
||||
.write(&syscall::Event {
|
||||
id: timeout_socket.0.fd,
|
||||
flags: syscall::EventFlags::EVENT_READ,
|
||||
data: 0,
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let start = Instant::now();
|
||||
@@ -642,7 +627,7 @@ impl EventLoop {
|
||||
|
||||
if let Some(duration) = instant.checked_duration_since(start) {
|
||||
time.tv_sec += duration.as_secs() as i64;
|
||||
time.tv_nsec += duration.subsec_nanos() as i64;
|
||||
time.tv_nsec += duration.subsec_nanos() as i32;
|
||||
// Normalize timespec so tv_nsec is not greater than one second.
|
||||
while time.tv_nsec >= 1_000_000_000 {
|
||||
time.tv_sec += 1;
|
||||
@@ -654,22 +639,12 @@ impl EventLoop {
|
||||
}
|
||||
|
||||
// Wait for event if needed.
|
||||
let event = loop {
|
||||
match self.window_target.event_socket.next_event() {
|
||||
Ok(event) => break event,
|
||||
Err(err) if err.is_interrupt() => continue,
|
||||
Err(err) => {
|
||||
return Err(os_error!(format!("failed to read event: {err}")).into());
|
||||
},
|
||||
}
|
||||
};
|
||||
let mut event = syscall::Event::default();
|
||||
self.window_target.event_socket.read(&mut event).unwrap();
|
||||
|
||||
// TODO: handle spurious wakeups (redraw caused wakeup but redraw already handled)
|
||||
match requested_resume {
|
||||
Some(requested_resume)
|
||||
if event.fd == timeout_socket.0.fd()
|
||||
&& matches!(event.user_data, EventSource::Time) =>
|
||||
{
|
||||
Some(requested_resume) if event.id == timeout_socket.0.fd => {
|
||||
// If the event is from the special timeout socket, report that resume
|
||||
// time was reached.
|
||||
start_cause = StartCause::ResumeTimeReached { start, requested_resume };
|
||||
@@ -691,29 +666,31 @@ impl EventLoop {
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct EventLoopProxy {
|
||||
user_events_sender: mpsc::SyncSender<()>,
|
||||
pub(super) wake_socket: TimeSocket,
|
||||
waker: Waker,
|
||||
}
|
||||
|
||||
impl EventLoopProxyProvider for EventLoopProxy {
|
||||
fn wake_up(&self) {
|
||||
// When we fail to send the event it means that we haven't woken up to read the previous
|
||||
// event.
|
||||
if self.user_events_sender.try_send(()).is_ok() {
|
||||
self.wake_socket.wake().unwrap();
|
||||
}
|
||||
self.waker.wake_by_ref();
|
||||
}
|
||||
|
||||
fn into_waker(self) -> Waker {
|
||||
self.waker
|
||||
}
|
||||
}
|
||||
|
||||
impl std::task::Wake for TimeSocket {
|
||||
fn wake(self: Arc<TimeSocket>) {
|
||||
TimeSocket::wake(&*self).unwrap();
|
||||
}
|
||||
|
||||
fn wake_by_ref(self: &Arc<TimeSocket>) {
|
||||
TimeSocket::wake(&**self).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
impl Unpin for EventLoopProxy {}
|
||||
|
||||
redox_event::user_data! {
|
||||
pub enum EventSource {
|
||||
Orbital,
|
||||
Time,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ActiveEventLoop {
|
||||
control_flow: Cell<ControlFlow>,
|
||||
@@ -721,7 +698,7 @@ pub struct ActiveEventLoop {
|
||||
pub(super) creates: Mutex<VecDeque<Arc<RedoxSocket>>>,
|
||||
pub(super) redraws: Arc<Mutex<VecDeque<WindowId>>>,
|
||||
pub(super) destroys: Arc<Mutex<VecDeque<WindowId>>>,
|
||||
pub(super) event_socket: Arc<EventQueue<EventSource>>,
|
||||
pub(super) event_socket: Arc<RedoxSocket>,
|
||||
pub(super) event_loop_proxy: Arc<EventLoopProxy>,
|
||||
}
|
||||
|
||||
|
||||
@@ -3,17 +3,14 @@
|
||||
//! Redox OS has some functionality not yet present that will be implemented
|
||||
//! when its orbital display server provides it.
|
||||
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{Read, Result, Write};
|
||||
use std::os::fd::AsRawFd;
|
||||
use std::{fmt, mem, slice, str};
|
||||
|
||||
use libredox::data::TimeSpec;
|
||||
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;
|
||||
@@ -21,11 +18,15 @@ pub mod window;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct RedoxSocket {
|
||||
fd: File,
|
||||
fd: usize,
|
||||
}
|
||||
|
||||
impl RedoxSocket {
|
||||
fn orbital(properties: &WindowProperties<'_>) -> Result<Self> {
|
||||
fn event() -> syscall::Result<Self> {
|
||||
Self::open_raw("/scheme/event")
|
||||
}
|
||||
|
||||
fn orbital(properties: &WindowProperties<'_>) -> syscall::Result<Self> {
|
||||
Self::open_raw(&format!("{properties}"))
|
||||
}
|
||||
|
||||
@@ -33,27 +34,38 @@ impl RedoxSocket {
|
||||
// non-socket path is used, it could cause read and write to not function as expected. For
|
||||
// example, the seek would change in a potentially unpredictable way if either read or write
|
||||
// were called at the same time by multiple threads.
|
||||
fn open_raw(path: &str) -> Result<Self> {
|
||||
let fd = OpenOptions::new().read(true).write(true).open(path)?;
|
||||
fn open_raw(path: &str) -> syscall::Result<Self> {
|
||||
let fd = syscall::open(path, syscall::O_RDWR | syscall::O_CLOEXEC)?;
|
||||
Ok(Self { fd })
|
||||
}
|
||||
|
||||
fn fd(&self) -> usize {
|
||||
self.fd.as_raw_fd() as usize
|
||||
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))
|
||||
}
|
||||
}
|
||||
|
||||
fn read(&self, buf: &mut [u8]) -> Result<()> {
|
||||
(&self.fd).read_exact(buf)
|
||||
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))
|
||||
}
|
||||
}
|
||||
|
||||
fn write(&self, buf: &[u8]) -> Result<()> {
|
||||
(&self.fd).write_all(buf)
|
||||
fn fpath<'a>(&self, buf: &'a mut [u8]) -> syscall::Result<&'a str> {
|
||||
let count = syscall::fpath(self.fd, buf)?;
|
||||
str::from_utf8(&buf[..count]).map_err(|_err| syscall::Error::new(syscall::EINVAL))
|
||||
}
|
||||
}
|
||||
|
||||
fn fpath<'a>(&self, buf: &'a mut [u8]) -> Result<&'a str> {
|
||||
let count = libredox::call::fpath(self.fd(), buf)?;
|
||||
str::from_utf8(&buf[..count])
|
||||
.map_err(|_| std::io::Error::from(std::io::ErrorKind::InvalidData))
|
||||
impl Drop for RedoxSocket {
|
||||
fn drop(&mut self) {
|
||||
let _ = syscall::close(self.fd);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,36 +73,26 @@ impl RedoxSocket {
|
||||
struct TimeSocket(RedoxSocket);
|
||||
|
||||
impl TimeSocket {
|
||||
fn open() -> Result<Self> {
|
||||
fn open() -> syscall::Result<Self> {
|
||||
RedoxSocket::open_raw("/scheme/time/4").map(Self)
|
||||
}
|
||||
|
||||
// Read current time.
|
||||
fn current_time(&self) -> Result<TimeSpec> {
|
||||
let mut timespec: libredox::data::TimeSpec = unsafe { mem::zeroed() };
|
||||
let timespec_bytes = unsafe {
|
||||
slice::from_raw_parts_mut(
|
||||
&mut timespec as *mut _ as *mut u8,
|
||||
mem::size_of::<TimeSpec>(),
|
||||
)
|
||||
};
|
||||
self.0.read(timespec_bytes)?;
|
||||
fn current_time(&self) -> syscall::Result<syscall::TimeSpec> {
|
||||
let mut timespec = syscall::TimeSpec::default();
|
||||
self.0.read(&mut timespec)?;
|
||||
Ok(timespec)
|
||||
}
|
||||
|
||||
// Write a timeout.
|
||||
fn timeout(&self, timespec: &TimeSpec) -> Result<()> {
|
||||
let timespec_bytes = unsafe {
|
||||
slice::from_raw_parts(timespec as *const _ as *const u8, mem::size_of::<TimeSpec>())
|
||||
};
|
||||
self.0.write(timespec_bytes)
|
||||
fn timeout(&self, timespec: &syscall::TimeSpec) -> syscall::Result<()> {
|
||||
self.0.write(timespec)
|
||||
}
|
||||
|
||||
// Wake immediately.
|
||||
fn wake(&self) -> Result<()> {
|
||||
fn wake(&self) -> syscall::Result<()> {
|
||||
// Writing a default TimeSpec will always trigger a time event.
|
||||
let timespec: TimeSpec = unsafe { mem::zeroed() };
|
||||
self.timeout(×pec)
|
||||
self.timeout(&syscall::TimeSpec::default())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,7 +107,7 @@ struct WindowProperties<'a> {
|
||||
|
||||
impl<'a> WindowProperties<'a> {
|
||||
fn new(path: &'a str) -> Self {
|
||||
// /scheme/orbital/flags/x/y/w/h/t
|
||||
// orbital:flags/x/y/w/h/t
|
||||
let mut parts = path.splitn(6, '/');
|
||||
let flags = parts.next().unwrap_or("");
|
||||
let x = parts.next().map_or(0, |part| part.parse::<i32>().unwrap_or(0));
|
||||
|
||||
@@ -3,13 +3,12 @@ use std::iter;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use dpi::{PhysicalInsets, PhysicalPosition, PhysicalSize, Position, Size};
|
||||
use redox_event::EventFlags;
|
||||
use winit_core::cursor::Cursor;
|
||||
use winit_core::error::{NotSupportedError, RequestError};
|
||||
use winit_core::monitor::{Fullscreen, MonitorHandle as CoreMonitorHandle};
|
||||
use winit_core::window::{self, Window as CoreWindow, WindowId};
|
||||
|
||||
use crate::event_loop::{ActiveEventLoop, EventLoopProxy, EventSource};
|
||||
use crate::event_loop::{ActiveEventLoop, EventLoopProxy};
|
||||
use crate::{RedoxSocket, WindowProperties};
|
||||
|
||||
// These values match the values uses in the `window_new` function in orbital:
|
||||
@@ -20,7 +19,6 @@ 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';
|
||||
|
||||
@@ -57,10 +55,7 @@ impl Window {
|
||||
// Async by default.
|
||||
let mut flag_str = ORBITAL_FLAG_ASYNC.to_string();
|
||||
|
||||
// Fullscreen takes precedence over maximize
|
||||
if let Some(Fullscreen::Borderless(_)) = attrs.fullscreen {
|
||||
flag_str.push(ORBITAL_FLAG_FULLSCREEN);
|
||||
} else if attrs.maximized {
|
||||
if attrs.maximized {
|
||||
flag_str.push(ORBITAL_FLAG_MAXIMIZED);
|
||||
}
|
||||
|
||||
@@ -68,6 +63,8 @@ impl Window {
|
||||
flag_str.push(ORBITAL_FLAG_RESIZABLE);
|
||||
}
|
||||
|
||||
// TODO: fullscreen
|
||||
|
||||
if attrs.transparent {
|
||||
flag_str.push(ORBITAL_FLAG_TRANSPARENT);
|
||||
}
|
||||
@@ -104,7 +101,13 @@ impl Window {
|
||||
.expect("failed to open window");
|
||||
|
||||
// Add to event socket.
|
||||
el.event_socket.subscribe(window.fd(), EventSource::Orbital, EventFlags::READ).unwrap();
|
||||
el.event_socket
|
||||
.write(&syscall::Event {
|
||||
id: window.fd,
|
||||
flags: syscall::EventFlags::EVENT_READ,
|
||||
data: window.fd,
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let window_socket = Arc::new(window);
|
||||
|
||||
@@ -141,7 +144,7 @@ impl Window {
|
||||
#[inline]
|
||||
fn raw_window_handle_rwh_06(&self) -> Result<rwh_06::RawWindowHandle, rwh_06::HandleError> {
|
||||
let handle = rwh_06::OrbitalWindowHandle::new({
|
||||
let window = self.window_socket.fd() as *mut _;
|
||||
let window = self.window_socket.fd as *mut _;
|
||||
std::ptr::NonNull::new(window).expect("orbital fd should never be null")
|
||||
});
|
||||
Ok(rwh_06::RawWindowHandle::Orbital(handle))
|
||||
@@ -155,7 +158,7 @@ impl Window {
|
||||
|
||||
impl CoreWindow for Window {
|
||||
fn id(&self) -> WindowId {
|
||||
WindowId::from_raw(self.window_socket.fd())
|
||||
WindowId::from_raw(self.window_socket.fd)
|
||||
}
|
||||
|
||||
fn ime_capabilities(&self) -> Option<window::ImeCapabilities> {
|
||||
@@ -320,28 +323,10 @@ impl CoreWindow for Window {
|
||||
self.get_flag(ORBITAL_FLAG_MAXIMIZED).unwrap_or(false)
|
||||
}
|
||||
|
||||
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 set_fullscreen(&self, _monitor: Option<Fullscreen>) {}
|
||||
|
||||
fn fullscreen(&self) -> Option<Fullscreen> {
|
||||
if self.get_flag(ORBITAL_FLAG_FULLSCREEN).unwrap_or(false) {
|
||||
// TODO: monitor selection not supported on orbital
|
||||
Some(Fullscreen::Borderless(None))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[inline]
|
||||
|
||||
@@ -18,6 +18,7 @@ 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
|
||||
@@ -69,7 +70,6 @@ objc2-ui-kit = { workspace = true, features = [
|
||||
"UIViewController",
|
||||
"UIWindow",
|
||||
] }
|
||||
winit-common = { workspace = true, features = ["core-foundation", "event-handler", "foundation"] }
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
|
||||
@@ -9,11 +9,11 @@ use std::{fmt, ptr};
|
||||
|
||||
use dispatch2::MainThreadBound;
|
||||
use dpi::PhysicalSize;
|
||||
use objc2::MainThreadMarker;
|
||||
use objc2::rc::Retained;
|
||||
use objc2::MainThreadMarker;
|
||||
use objc2_core_foundation::{
|
||||
CFAbsoluteTimeGetCurrent, CFRetained, CFRunLoop, CFRunLoopTimer, CGRect, CGSize,
|
||||
kCFRunLoopCommonModes,
|
||||
kCFRunLoopCommonModes, CFAbsoluteTimeGetCurrent, CFRetained, CFRunLoop, CFRunLoopTimer, CGRect,
|
||||
CGSize,
|
||||
};
|
||||
use objc2_ui_kit::{UIApplication, UICoordinateSpace, UIView};
|
||||
use winit_common::core_foundation::EventLoopProxy;
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
use std::ffi::c_void;
|
||||
use std::ptr;
|
||||
use std::sync::Arc;
|
||||
|
||||
use objc2::rc::Retained;
|
||||
use objc2::runtime::ProtocolObject;
|
||||
use objc2::{ClassType, MainThreadMarker, msg_send};
|
||||
use objc2_core_foundation::{CFIndex, CFRunLoopActivity, kCFRunLoopDefaultMode};
|
||||
use objc2::{msg_send, ClassType, MainThreadMarker};
|
||||
use objc2_core_foundation::{
|
||||
kCFRunLoopDefaultMode, CFIndex, CFRunLoop, CFRunLoopActivity, CFRunLoopObserver,
|
||||
};
|
||||
use objc2_foundation::{NSNotificationCenter, NSObjectProtocol};
|
||||
use objc2_ui_kit::{
|
||||
UIApplication, UIApplicationDidBecomeActiveNotification,
|
||||
@@ -12,9 +16,6 @@ use objc2_ui_kit::{
|
||||
UIApplicationWillResignActiveNotification, UIApplicationWillTerminateNotification, UIScreen,
|
||||
};
|
||||
use rwh_06::HasDisplayHandle;
|
||||
use tracing::debug_span;
|
||||
use winit_common::core_foundation::{MainRunLoop, MainRunLoopObserver, tracing_observers};
|
||||
use winit_common::foundation::create_observer;
|
||||
use winit_core::application::ApplicationHandler;
|
||||
use winit_core::cursor::{CustomCursor, CustomCursorSource};
|
||||
use winit_core::error::{EventLoopError, NotSupportedError, RequestError};
|
||||
@@ -25,7 +26,8 @@ use winit_core::event_loop::{
|
||||
use winit_core::monitor::MonitorHandle as CoreMonitorHandle;
|
||||
use winit_core::window::{Theme, Window as CoreWindow};
|
||||
|
||||
use super::app_state::{AppState, send_occluded_event_for_all_windows};
|
||||
use super::app_state::{send_occluded_event_for_all_windows, AppState};
|
||||
use super::notification_center::create_observer;
|
||||
use crate::monitor::MonitorHandle;
|
||||
use crate::window::Window;
|
||||
use crate::{app_state, monitor};
|
||||
@@ -134,11 +136,6 @@ pub struct EventLoop {
|
||||
_did_enter_background_observer: Retained<ProtocolObject<dyn NSObjectProtocol>>,
|
||||
_will_terminate_observer: Retained<ProtocolObject<dyn NSObjectProtocol>>,
|
||||
_did_receive_memory_warning_observer: Retained<ProtocolObject<dyn NSObjectProtocol>>,
|
||||
|
||||
_tracing_observers: Option<(MainRunLoopObserver, MainRunLoopObserver)>,
|
||||
_wakeup_observer: MainRunLoopObserver,
|
||||
_main_events_cleared_observer: MainRunLoopObserver,
|
||||
_events_cleared_observer: MainRunLoopObserver,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
||||
@@ -154,14 +151,16 @@ impl EventLoop {
|
||||
return Err(EventLoopError::RecreationAttempt);
|
||||
}
|
||||
|
||||
let center = NSNotificationCenter::defaultCenter();
|
||||
// this line sets up the main run loop before `UIApplicationMain`
|
||||
setup_control_flow_observers();
|
||||
|
||||
let center = unsafe { NSNotificationCenter::defaultCenter() };
|
||||
|
||||
let _did_finish_launching_observer = create_observer(
|
||||
¢er,
|
||||
// `application:didFinishLaunchingWithOptions:`
|
||||
unsafe { UIApplicationDidFinishLaunchingNotification },
|
||||
move |_| {
|
||||
let _entered = debug_span!("UIApplicationDidFinishLaunchingNotification").entered();
|
||||
app_state::did_finish_launching(mtm);
|
||||
},
|
||||
);
|
||||
@@ -169,28 +168,20 @@ impl EventLoop {
|
||||
¢er,
|
||||
// `applicationDidBecomeActive:`
|
||||
unsafe { UIApplicationDidBecomeActiveNotification },
|
||||
move |_| {
|
||||
let _entered = debug_span!("UIApplicationDidBecomeActiveNotification").entered();
|
||||
app_state::handle_resumed(mtm)
|
||||
},
|
||||
move |_| app_state::handle_resumed(mtm),
|
||||
);
|
||||
let _will_resign_active_observer = create_observer(
|
||||
¢er,
|
||||
// `applicationWillResignActive:`
|
||||
unsafe { UIApplicationWillResignActiveNotification },
|
||||
move |_| {
|
||||
let _entered = debug_span!("UIApplicationWillResignActiveNotification").entered();
|
||||
app_state::handle_suspended(mtm)
|
||||
},
|
||||
move |_| app_state::handle_suspended(mtm),
|
||||
);
|
||||
let _will_enter_foreground_observer = create_observer(
|
||||
¢er,
|
||||
// `applicationWillEnterForeground:`
|
||||
unsafe { UIApplicationWillEnterForegroundNotification },
|
||||
move |notification| {
|
||||
let _entered =
|
||||
debug_span!("UIApplicationWillEnterForegroundNotification").entered();
|
||||
let app = notification.object().expect(
|
||||
let app = unsafe { notification.object() }.expect(
|
||||
"UIApplicationWillEnterForegroundNotification to have application object",
|
||||
);
|
||||
// The `object` in `UIApplicationWillEnterForegroundNotification` is documented to
|
||||
@@ -204,8 +195,7 @@ impl EventLoop {
|
||||
// `applicationDidEnterBackground:`
|
||||
unsafe { UIApplicationDidEnterBackgroundNotification },
|
||||
move |notification| {
|
||||
let _entered = debug_span!("UIApplicationDidEnterBackgroundNotification").entered();
|
||||
let app = notification.object().expect(
|
||||
let app = unsafe { notification.object() }.expect(
|
||||
"UIApplicationDidEnterBackgroundNotification to have application object",
|
||||
);
|
||||
// The `object` in `UIApplicationDidEnterBackgroundNotification` is documented to be
|
||||
@@ -219,9 +209,7 @@ impl EventLoop {
|
||||
// `applicationWillTerminate:`
|
||||
unsafe { UIApplicationWillTerminateNotification },
|
||||
move |notification| {
|
||||
let _entered = debug_span!("UIApplicationWillTerminateNotification").entered();
|
||||
let app = notification
|
||||
.object()
|
||||
let app = unsafe { notification.object() }
|
||||
.expect("UIApplicationWillTerminateNotification to have application object");
|
||||
// The `object` in `UIApplicationWillTerminateNotification` is (somewhat) documented
|
||||
// to be `UIApplication`.
|
||||
@@ -233,65 +221,9 @@ impl EventLoop {
|
||||
¢er,
|
||||
// `applicationDidReceiveMemoryWarning:`
|
||||
unsafe { UIApplicationDidReceiveMemoryWarningNotification },
|
||||
move |_| {
|
||||
let _entered =
|
||||
debug_span!("UIApplicationDidReceiveMemoryWarningNotification").entered();
|
||||
app_state::handle_memory_warning(mtm)
|
||||
},
|
||||
move |_| app_state::handle_memory_warning(mtm),
|
||||
);
|
||||
|
||||
let main_loop = MainRunLoop::get(mtm);
|
||||
let mode = unsafe { kCFRunLoopDefaultMode }.unwrap();
|
||||
|
||||
// Tracing observers have the lowest and highest orderings.
|
||||
let _tracing_observers = tracing_observers(mtm).inspect(|(start, end)| {
|
||||
main_loop.add_observer(start, mode);
|
||||
main_loop.add_observer(end, mode);
|
||||
});
|
||||
|
||||
let _wakeup_observer = MainRunLoopObserver::new(
|
||||
mtm,
|
||||
CFRunLoopActivity::AfterWaiting,
|
||||
true,
|
||||
// Queued with the second-highest priority (tracing observers use the highest) to
|
||||
// ensure it is processed before other observers.
|
||||
CFIndex::MIN + 1,
|
||||
move |_| app_state::handle_wakeup_transition(mtm),
|
||||
);
|
||||
main_loop.add_observer(&_wakeup_observer, mode);
|
||||
|
||||
let _main_events_cleared_observer = MainRunLoopObserver::new(
|
||||
mtm,
|
||||
CFRunLoopActivity::BeforeWaiting,
|
||||
true,
|
||||
// Core Animation registers its `CFRunLoopObserver` that performs drawing operations in
|
||||
// `CA::Transaction::ensure_implicit` with a priority of `2000000`. We set the
|
||||
// main_end priority to be 0, in order to send `AboutToWait` before `RedrawRequested`.
|
||||
// This value was chosen conservatively to guard against apple using different
|
||||
// priorities for their redraw observers in different OS's or on different devices. If
|
||||
// it so happens that it's too conservative, the main symptom would be non-redraw
|
||||
// events coming in after `AboutToWait`.
|
||||
//
|
||||
// The value of `2000000` was determined by inspecting stack traces and the associated
|
||||
// registers for every `CFRunLoopAddObserver` call on an iPad Air 2 running iOS 11.4.
|
||||
//
|
||||
// Also tested to be `2000000` on iPhone 8, iOS 13 beta 4.
|
||||
0,
|
||||
move |_| app_state::handle_main_events_cleared(mtm),
|
||||
);
|
||||
main_loop.add_observer(&_main_events_cleared_observer, mode);
|
||||
|
||||
let _events_cleared_observer = MainRunLoopObserver::new(
|
||||
mtm,
|
||||
CFRunLoopActivity::BeforeWaiting,
|
||||
true,
|
||||
// Queued with the second-lowest priority (tracing observers use the lowest) to ensure
|
||||
// it is processed after other observers.
|
||||
CFIndex::MAX - 1,
|
||||
move |_| app_state::handle_events_cleared(mtm),
|
||||
);
|
||||
main_loop.add_observer(&_events_cleared_observer, mode);
|
||||
|
||||
Ok(EventLoop {
|
||||
mtm,
|
||||
window_target: ActiveEventLoop { mtm },
|
||||
@@ -302,15 +234,10 @@ impl EventLoop {
|
||||
_did_enter_background_observer,
|
||||
_will_terminate_observer,
|
||||
_did_receive_memory_warning_observer,
|
||||
_tracing_observers,
|
||||
_wakeup_observer,
|
||||
_main_events_cleared_observer,
|
||||
_events_cleared_observer,
|
||||
})
|
||||
}
|
||||
|
||||
// Require `'static` for correctness, we won't be able to `Drop` the user's state otherwise.
|
||||
pub fn run_app_never_return<A: ApplicationHandler + 'static>(self, app: A) -> ! {
|
||||
pub fn run_app<A: ApplicationHandler>(self, app: A) -> ! {
|
||||
let application: Option<Retained<UIApplication>> =
|
||||
unsafe { msg_send![UIApplication::class(), sharedApplication] };
|
||||
assert!(
|
||||
@@ -322,10 +249,6 @@ impl EventLoop {
|
||||
|
||||
// We intentionally override neither the application nor the delegate,
|
||||
// to allow the user to do so themselves!
|
||||
//
|
||||
// NOTE: `UIApplicationMain` is _the only way_ to start the event loop on iOS/UIKit, there
|
||||
// are no other feasible options. See also:
|
||||
// <https://github.com/rust-windowing/winit/pull/4165#issuecomment-2760514167>
|
||||
app_state::launch(self.mtm, app, || UIApplication::main(None, None, self.mtm))
|
||||
}
|
||||
|
||||
@@ -333,3 +256,97 @@ impl EventLoop {
|
||||
&self.window_target
|
||||
}
|
||||
}
|
||||
|
||||
fn setup_control_flow_observers() {
|
||||
unsafe {
|
||||
// begin is queued with the highest priority to ensure it is processed before other
|
||||
// observers
|
||||
extern "C-unwind" fn control_flow_begin_handler(
|
||||
_: *mut CFRunLoopObserver,
|
||||
activity: CFRunLoopActivity,
|
||||
_: *mut c_void,
|
||||
) {
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
#[allow(non_upper_case_globals)]
|
||||
match activity {
|
||||
CFRunLoopActivity::AfterWaiting => app_state::handle_wakeup_transition(mtm),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
// Core Animation registers its `CFRunLoopObserver` that performs drawing operations in
|
||||
// `CA::Transaction::ensure_implicit` with a priority of `0x1e8480`. We set the main_end
|
||||
// priority to be 0, in order to send AboutToWait before RedrawRequested. This value was
|
||||
// chosen conservatively to guard against apple using different priorities for their redraw
|
||||
// observers in different OS's or on different devices. If it so happens that it's too
|
||||
// conservative, the main symptom would be non-redraw events coming in after `AboutToWait`.
|
||||
//
|
||||
// The value of `0x1e8480` was determined by inspecting stack traces and the associated
|
||||
// registers for every `CFRunLoopAddObserver` call on an iPad Air 2 running iOS 11.4.
|
||||
//
|
||||
// Also tested to be `0x1e8480` on iPhone 8, iOS 13 beta 4.
|
||||
extern "C-unwind" fn control_flow_main_end_handler(
|
||||
_: *mut CFRunLoopObserver,
|
||||
activity: CFRunLoopActivity,
|
||||
_: *mut c_void,
|
||||
) {
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
#[allow(non_upper_case_globals)]
|
||||
match activity {
|
||||
CFRunLoopActivity::BeforeWaiting => app_state::handle_main_events_cleared(mtm),
|
||||
CFRunLoopActivity::Exit => {}, // may happen when running on macOS
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
// end is queued with the lowest priority to ensure it is processed after other observers
|
||||
extern "C-unwind" fn control_flow_end_handler(
|
||||
_: *mut CFRunLoopObserver,
|
||||
activity: CFRunLoopActivity,
|
||||
_: *mut c_void,
|
||||
) {
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
#[allow(non_upper_case_globals)]
|
||||
match activity {
|
||||
CFRunLoopActivity::BeforeWaiting => app_state::handle_events_cleared(mtm),
|
||||
CFRunLoopActivity::Exit => {}, // may happen when running on macOS
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
let main_loop = CFRunLoop::main().unwrap();
|
||||
|
||||
let begin_observer = CFRunLoopObserver::new(
|
||||
None,
|
||||
CFRunLoopActivity::AfterWaiting.0,
|
||||
true,
|
||||
CFIndex::MIN,
|
||||
Some(control_flow_begin_handler),
|
||||
ptr::null_mut(),
|
||||
)
|
||||
.unwrap();
|
||||
main_loop.add_observer(Some(&begin_observer), kCFRunLoopDefaultMode);
|
||||
|
||||
let main_end_observer = CFRunLoopObserver::new(
|
||||
None,
|
||||
(CFRunLoopActivity::Exit | CFRunLoopActivity::BeforeWaiting).0,
|
||||
true,
|
||||
0, // see comment on `control_flow_main_end_handler`
|
||||
Some(control_flow_main_end_handler),
|
||||
ptr::null_mut(),
|
||||
)
|
||||
.unwrap();
|
||||
main_loop.add_observer(Some(&main_end_observer), kCFRunLoopDefaultMode);
|
||||
|
||||
let end_observer = CFRunLoopObserver::new(
|
||||
None,
|
||||
(CFRunLoopActivity::Exit | CFRunLoopActivity::BeforeWaiting).0,
|
||||
true,
|
||||
CFIndex::MAX,
|
||||
Some(control_flow_end_handler),
|
||||
ptr::null_mut(),
|
||||
)
|
||||
.unwrap();
|
||||
main_loop.add_observer(Some(&end_observer), kCFRunLoopDefaultMode);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,6 +103,7 @@
|
||||
mod app_state;
|
||||
mod event_loop;
|
||||
mod monitor;
|
||||
mod notification_center;
|
||||
mod view;
|
||||
mod view_controller;
|
||||
mod window;
|
||||
|
||||
@@ -4,10 +4,10 @@ use std::collections::VecDeque;
|
||||
use std::num::NonZeroU32;
|
||||
use std::{fmt, hash, ptr};
|
||||
|
||||
use dispatch2::{MainThreadBound, run_on_main};
|
||||
use dispatch2::{run_on_main, MainThreadBound};
|
||||
use dpi::PhysicalPosition;
|
||||
use objc2::rc::Retained;
|
||||
use objc2::{MainThreadMarker, Message, available};
|
||||
use objc2::{available, MainThreadMarker, Message};
|
||||
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> + 'static {
|
||||
pub fn video_modes_handles(&self) -> impl Iterator<Item = VideoModeHandle> {
|
||||
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> + 'static {
|
||||
pub fn video_modes(&self) -> impl Iterator<Item = VideoMode> {
|
||||
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!(
|
||||
assert!(unsafe {
|
||||
NSSet::setWithArray(&UIScreen::screens(mtm)).containsObject(&UIScreen::mainScreen(mtm))
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
1
winit-uikit/src/notification_center.rs
Symbolic link
@@ -0,0 +1 @@
|
||||
../../winit-appkit/src/notification_center.rs
|
||||
@@ -4,7 +4,7 @@ use std::cell::{Cell, RefCell};
|
||||
use dpi::PhysicalPosition;
|
||||
use objc2::rc::Retained;
|
||||
use objc2::runtime::{NSObjectProtocol, ProtocolObject};
|
||||
use objc2::{DefinedClass, MainThreadMarker, available, define_class, msg_send, sel};
|
||||
use objc2::{available, define_class, msg_send, sel, DefinedClass, MainThreadMarker};
|
||||
use objc2_core_foundation::{CGFloat, CGPoint, CGRect};
|
||||
use objc2_foundation::{NSObject, NSSet, NSString};
|
||||
use objc2_ui_kit::{
|
||||
@@ -13,10 +13,10 @@ use objc2_ui_kit::{
|
||||
UIResponder, UIRotationGestureRecognizer, UITapGestureRecognizer, UITextInputTraits, UITouch,
|
||||
UITouchPhase, UITouchType, UITraitEnvironment, UIView,
|
||||
};
|
||||
use tracing::{debug, debug_span, trace_span};
|
||||
use tracing::debug;
|
||||
use winit_core::event::{
|
||||
ButtonSource, ElementState, FingerId, Force, KeyEvent, PointerKind, PointerSource,
|
||||
TabletToolAngle, TabletToolButton, TabletToolData, TabletToolKind, TouchPhase, WindowEvent,
|
||||
ButtonSource, ElementState, FingerId, Force, KeyEvent, PointerKind, PointerSource, TouchPhase,
|
||||
WindowEvent,
|
||||
};
|
||||
use winit_core::keyboard::{Key, KeyCode, KeyLocation, NamedKey, NativeKeyCode, PhysicalKey};
|
||||
|
||||
@@ -48,7 +48,6 @@ define_class!(
|
||||
impl WinitView {
|
||||
#[unsafe(method(drawRect:))]
|
||||
fn draw_rect(&self, rect: CGRect) {
|
||||
let _entered = debug_span!("drawRect:").entered();
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
let window = self.window().unwrap();
|
||||
app_state::handle_nonuser_event(mtm, EventWrapper::Window {
|
||||
@@ -60,7 +59,6 @@ define_class!(
|
||||
|
||||
#[unsafe(method(layoutSubviews))]
|
||||
fn layout_subviews(&self) {
|
||||
let _entered = debug_span!("layoutSubviews").entered();
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
let _: () = unsafe { msg_send![super(self), layoutSubviews] };
|
||||
|
||||
@@ -81,7 +79,6 @@ define_class!(
|
||||
|
||||
#[unsafe(method(setContentScaleFactor:))]
|
||||
fn set_content_scale_factor(&self, untrusted_scale_factor: CGFloat) {
|
||||
let _entered = debug_span!("setContentScaleFactor:").entered();
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
let _: () =
|
||||
unsafe { msg_send![super(self), setContentScaleFactor: untrusted_scale_factor] };
|
||||
@@ -127,7 +124,6 @@ define_class!(
|
||||
|
||||
#[unsafe(method(safeAreaInsetsDidChange))]
|
||||
fn safe_area_changed(&self) {
|
||||
let _entered = debug_span!("safeAreaInsetsDidChange").entered();
|
||||
debug!("safeAreaInsetsDidChange was called, requesting redraw");
|
||||
// When the safe area changes we want to make sure to emit a redraw event
|
||||
self.setNeedsDisplay();
|
||||
@@ -135,31 +131,26 @@ define_class!(
|
||||
|
||||
#[unsafe(method(touchesBegan:withEvent:))]
|
||||
fn touches_began(&self, touches: &NSSet<UITouch>, _event: Option<&UIEvent>) {
|
||||
let _entered = debug_span!("touchesBegan:withEvent:").entered();
|
||||
self.handle_touches(touches)
|
||||
}
|
||||
|
||||
#[unsafe(method(touchesMoved:withEvent:))]
|
||||
fn touches_moved(&self, touches: &NSSet<UITouch>, _event: Option<&UIEvent>) {
|
||||
let _entered = debug_span!("touchesMoved:withEvent:").entered();
|
||||
self.handle_touches(touches)
|
||||
}
|
||||
|
||||
#[unsafe(method(touchesEnded:withEvent:))]
|
||||
fn touches_ended(&self, touches: &NSSet<UITouch>, _event: Option<&UIEvent>) {
|
||||
let _entered = debug_span!("touchesEnded:withEvent:").entered();
|
||||
self.handle_touches(touches)
|
||||
}
|
||||
|
||||
#[unsafe(method(touchesCancelled:withEvent:))]
|
||||
fn touches_cancelled(&self, touches: &NSSet<UITouch>, _event: Option<&UIEvent>) {
|
||||
let _entered = debug_span!("touchesCancelled:withEvent:").entered();
|
||||
self.handle_touches(touches)
|
||||
}
|
||||
|
||||
#[unsafe(method(pinchGesture:))]
|
||||
fn pinch_gesture(&self, recognizer: &UIPinchGestureRecognizer) {
|
||||
let _entered = debug_span!("pinchGesture:").entered();
|
||||
let window = self.window().unwrap();
|
||||
|
||||
let (phase, delta) = match recognizer.state() {
|
||||
@@ -194,7 +185,6 @@ define_class!(
|
||||
|
||||
#[unsafe(method(doubleTapGesture:))]
|
||||
fn double_tap_gesture(&self, recognizer: &UITapGestureRecognizer) {
|
||||
let _entered = debug_span!("doubleTapGesture:").entered();
|
||||
let window = self.window().unwrap();
|
||||
|
||||
if recognizer.state() == UIGestureRecognizerState::Ended {
|
||||
@@ -210,7 +200,6 @@ define_class!(
|
||||
|
||||
#[unsafe(method(rotationGesture:))]
|
||||
fn rotation_gesture(&self, recognizer: &UIRotationGestureRecognizer) {
|
||||
let _entered = debug_span!("rotationGesture:").entered();
|
||||
let window = self.window().unwrap();
|
||||
|
||||
let (phase, delta) = match recognizer.state() {
|
||||
@@ -255,7 +244,6 @@ define_class!(
|
||||
|
||||
#[unsafe(method(panGesture:))]
|
||||
fn pan_gesture(&self, recognizer: &UIPanGestureRecognizer) {
|
||||
let _entered = debug_span!("panGesture:").entered();
|
||||
let window = self.window().unwrap();
|
||||
|
||||
let translation = recognizer.translationInView(Some(self));
|
||||
@@ -308,7 +296,6 @@ define_class!(
|
||||
|
||||
#[unsafe(method(canBecomeFirstResponder))]
|
||||
fn can_become_first_responder(&self) -> bool {
|
||||
let _entered = trace_span!("canBecomeFirstResponder").entered();
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -322,10 +309,6 @@ define_class!(
|
||||
_gesture_recognizer: &UIGestureRecognizer,
|
||||
_other_gesture_recognizer: &UIGestureRecognizer,
|
||||
) -> bool {
|
||||
let _entered = trace_span!(
|
||||
"gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:"
|
||||
)
|
||||
.entered();
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -335,19 +318,16 @@ define_class!(
|
||||
unsafe impl UIKeyInput for WinitView {
|
||||
#[unsafe(method(hasText))]
|
||||
fn has_text(&self) -> bool {
|
||||
let _entered = debug_span!("hasText").entered();
|
||||
true
|
||||
}
|
||||
|
||||
#[unsafe(method(insertText:))]
|
||||
fn insert_text(&self, text: &NSString) {
|
||||
let _entered = debug_span!("insertText:").entered();
|
||||
self.handle_insert_text(text)
|
||||
}
|
||||
|
||||
#[unsafe(method(deleteBackward))]
|
||||
fn delete_backward(&self) {
|
||||
let _entered = debug_span!("deleteBackward").entered();
|
||||
self.handle_delete_backward()
|
||||
}
|
||||
}
|
||||
@@ -483,16 +463,13 @@ impl WinitView {
|
||||
for touch in touches {
|
||||
let logical_location = touch.locationInView(None);
|
||||
let touch_type = touch.r#type();
|
||||
let force = if available!(ios = 9.0, tvos = 9.0, visionos = 1.0) {
|
||||
let use_force = match touch_type {
|
||||
UITouchType::Pencil => true,
|
||||
_ => {
|
||||
let trait_collection = self.traitCollection();
|
||||
trait_collection.forceTouchCapability() == UIForceTouchCapability::Available
|
||||
},
|
||||
};
|
||||
|
||||
if use_force {
|
||||
let force = if let UITouchType::Pencil = touch_type {
|
||||
None
|
||||
} else if available!(ios = 9.0, tvos = 9.0, visionos = 1.0) {
|
||||
let trait_collection = self.traitCollection();
|
||||
let touch_capability = trait_collection.forceTouchCapability();
|
||||
// Both the OS _and_ the device need to be checked for force touch support.
|
||||
if touch_capability == UIForceTouchCapability::Available {
|
||||
let force = touch.force();
|
||||
let max_possible_force = touch.maximumPossibleForce();
|
||||
Some(Force::Calibrated {
|
||||
@@ -548,7 +525,7 @@ impl WinitView {
|
||||
primary,
|
||||
position,
|
||||
kind: if let UITouchType::Pencil = touch_type {
|
||||
PointerKind::TabletTool(TabletToolKind::Pencil)
|
||||
PointerKind::Unknown
|
||||
} else {
|
||||
PointerKind::Touch(finger_id)
|
||||
},
|
||||
@@ -562,12 +539,7 @@ impl WinitView {
|
||||
state: ElementState::Pressed,
|
||||
position,
|
||||
button: if let UITouchType::Pencil = touch_type {
|
||||
let tool_data = self.tablet_tool_data_for_pencil(&touch);
|
||||
ButtonSource::TabletTool {
|
||||
kind: TabletToolKind::Pencil,
|
||||
button: TabletToolButton::Contact,
|
||||
data: tool_data,
|
||||
}
|
||||
ButtonSource::Unknown(0)
|
||||
} else {
|
||||
ButtonSource::Touch { finger_id, force }
|
||||
},
|
||||
@@ -576,11 +548,7 @@ impl WinitView {
|
||||
},
|
||||
UITouchPhase::Moved => {
|
||||
let (primary, source) = if let UITouchType::Pencil = touch_type {
|
||||
let tool_data = self.tablet_tool_data_for_pencil(&touch);
|
||||
(true, PointerSource::TabletTool {
|
||||
kind: TabletToolKind::Pencil,
|
||||
data: tool_data,
|
||||
})
|
||||
(true, PointerSource::Unknown)
|
||||
} else {
|
||||
(ivars.primary_finger.get().unwrap() == finger_id, PointerSource::Touch {
|
||||
finger_id,
|
||||
@@ -620,12 +588,7 @@ impl WinitView {
|
||||
state: ElementState::Released,
|
||||
position,
|
||||
button: if let UITouchType::Pencil = touch_type {
|
||||
let tool_data = self.tablet_tool_data_for_pencil(&touch);
|
||||
ButtonSource::TabletTool {
|
||||
kind: TabletToolKind::Pencil,
|
||||
button: TabletToolButton::Contact,
|
||||
data: tool_data,
|
||||
}
|
||||
ButtonSource::Unknown(0)
|
||||
} else {
|
||||
ButtonSource::Touch { finger_id, force }
|
||||
},
|
||||
@@ -640,7 +603,7 @@ impl WinitView {
|
||||
primary,
|
||||
position: Some(position),
|
||||
kind: if let UITouchType::Pencil = touch_type {
|
||||
PointerKind::TabletTool(TabletToolKind::Pencil)
|
||||
PointerKind::Unknown
|
||||
} else {
|
||||
PointerKind::Touch(finger_id)
|
||||
},
|
||||
@@ -654,32 +617,6 @@ impl WinitView {
|
||||
app_state::handle_nonuser_events(mtm, touch_events);
|
||||
}
|
||||
|
||||
fn tablet_tool_data_for_pencil(&self, touch: &UITouch) -> TabletToolData {
|
||||
let force = if available!(ios = 9.0, tvos = 9.0, visionos = 1.0) {
|
||||
let force_val = touch.force();
|
||||
let max_force = touch.maximumPossibleForce();
|
||||
Some(Force::Calibrated { force: force_val as _, max_possible_force: max_force as _ })
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let angle = if available!(ios = 9.1, tvos = 9.0, visionos = 1.0) {
|
||||
let altitude = touch.altitudeAngle();
|
||||
let azimuth = touch.azimuthAngleInView(Some(self));
|
||||
Some(TabletToolAngle { altitude: altitude as _, azimuth: azimuth as _ })
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
TabletToolData {
|
||||
force,
|
||||
tangential_force: None, // iOS doesn't provide barrel pressure
|
||||
twist: None, // iOS doesn't provide rotation/twist
|
||||
tilt: None, // Will be calculated from angle if needed
|
||||
angle,
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_insert_text(&self, text: &NSString) {
|
||||
let window = self.window().unwrap();
|
||||
let window_id = window.id();
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
use std::cell::Cell;
|
||||
|
||||
use objc2::rc::Retained;
|
||||
use objc2::{DefinedClass, MainThreadMarker, available, define_class, msg_send};
|
||||
use objc2::{available, define_class, msg_send, DefinedClass, MainThreadMarker};
|
||||
use objc2_foundation::NSObject;
|
||||
use objc2_ui_kit::{
|
||||
UIDevice, UIInterfaceOrientationMask, UIRectEdge, UIResponder, UIStatusBarStyle,
|
||||
UIUserInterfaceIdiom, UIView, UIViewController,
|
||||
};
|
||||
use tracing::trace_span;
|
||||
|
||||
use crate::{ScreenEdge, StatusBarStyle, ValidOrientations, WindowAttributesIos};
|
||||
|
||||
@@ -29,37 +28,31 @@ define_class!(
|
||||
impl WinitViewController {
|
||||
#[unsafe(method(shouldAutorotate))]
|
||||
fn should_autorotate(&self) -> bool {
|
||||
let _entered = trace_span!("shouldAutorotate").entered();
|
||||
true
|
||||
}
|
||||
|
||||
#[unsafe(method(prefersStatusBarHidden))]
|
||||
fn prefers_status_bar_hidden(&self) -> bool {
|
||||
let _entered = trace_span!("prefersStatusBarHidden").entered();
|
||||
self.ivars().prefers_status_bar_hidden.get()
|
||||
}
|
||||
|
||||
#[unsafe(method(preferredStatusBarStyle))]
|
||||
fn preferred_status_bar_style(&self) -> UIStatusBarStyle {
|
||||
let _entered = trace_span!("preferredStatusBarStyle").entered();
|
||||
self.ivars().preferred_status_bar_style.get()
|
||||
}
|
||||
|
||||
#[unsafe(method(prefersHomeIndicatorAutoHidden))]
|
||||
fn prefers_home_indicator_auto_hidden(&self) -> bool {
|
||||
let _entered = trace_span!("prefersHomeIndicatorAutoHidden").entered();
|
||||
self.ivars().prefers_home_indicator_auto_hidden.get()
|
||||
}
|
||||
|
||||
#[unsafe(method(supportedInterfaceOrientations))]
|
||||
fn supported_orientations(&self) -> UIInterfaceOrientationMask {
|
||||
let _entered = trace_span!("supportedInterfaceOrientations").entered();
|
||||
self.ivars().supported_orientations.get()
|
||||
}
|
||||
|
||||
#[unsafe(method(preferredScreenEdgesDeferringSystemGestures))]
|
||||
fn preferred_screen_edges_deferring_system_gestures(&self) -> UIRectEdge {
|
||||
let _entered = trace_span!("preferredScreenEdgesDeferringSystemGestures").entered();
|
||||
self.ivars().preferred_screen_edges_deferring_system_gestures.get()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,14 +9,14 @@ use dpi::{
|
||||
Position, Size,
|
||||
};
|
||||
use objc2::rc::Retained;
|
||||
use objc2::{MainThreadMarker, available, class, define_class, msg_send};
|
||||
use objc2::{available, class, define_class, msg_send, MainThreadMarker};
|
||||
use objc2_core_foundation::{CGFloat, CGPoint, CGRect, CGSize};
|
||||
use objc2_foundation::{NSObject, NSObjectProtocol};
|
||||
use objc2_ui_kit::{
|
||||
UIApplication, UICoordinateSpace, UIEdgeInsets, UIResponder, UIScreen,
|
||||
UIScreenOverscanCompensation, UIViewController, UIWindow,
|
||||
};
|
||||
use tracing::{debug, debug_span, warn};
|
||||
use tracing::{debug, warn};
|
||||
use winit_core::cursor::Cursor;
|
||||
use winit_core::error::{NotSupportedError, RequestError};
|
||||
use winit_core::event::WindowEvent;
|
||||
@@ -46,7 +46,6 @@ define_class!(
|
||||
impl WinitUIWindow {
|
||||
#[unsafe(method(becomeKeyWindow))]
|
||||
fn become_key_window(&self) {
|
||||
let _entered = debug_span!("becomeKeyWindow").entered();
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
app_state::handle_nonuser_event(mtm, EventWrapper::Window {
|
||||
window_id: self.id(),
|
||||
@@ -57,7 +56,6 @@ define_class!(
|
||||
|
||||
#[unsafe(method(resignKeyWindow))]
|
||||
fn resign_key_window(&self) {
|
||||
let _entered = debug_span!("resignKeyWindow").entered();
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
app_state::handle_nonuser_event(mtm, EventWrapper::Window {
|
||||
window_id: self.id(),
|
||||
@@ -163,7 +161,8 @@ impl Inner {
|
||||
|
||||
pub fn surface_position(&self) -> PhysicalPosition<i32> {
|
||||
let view_position = self.view.frame().origin;
|
||||
let position = self.window.convertPoint_fromView(view_position, Some(&self.view));
|
||||
let position =
|
||||
unsafe { self.window.convertPoint_fromView(view_position, Some(&self.view)) };
|
||||
let position = LogicalPosition::new(position.x, position.y);
|
||||
position.to_physical(self.scale_factor())
|
||||
}
|
||||
@@ -394,7 +393,9 @@ impl Inner {
|
||||
}
|
||||
*current_caps = Some(capabilities);
|
||||
|
||||
self.view.becomeFirstResponder();
|
||||
unsafe {
|
||||
self.view.becomeFirstResponder();
|
||||
}
|
||||
},
|
||||
ImeRequest::Update(_) => {
|
||||
if current_caps.is_none() {
|
||||
@@ -403,7 +404,9 @@ impl Inner {
|
||||
},
|
||||
ImeRequest::Disable => {
|
||||
*current_caps = None;
|
||||
self.view.resignFirstResponder();
|
||||
unsafe {
|
||||
self.view.resignFirstResponder();
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,6 @@ 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"]
|
||||
|
||||
@@ -29,19 +28,17 @@ tracing.workspace = true
|
||||
winit-core.workspace = true
|
||||
|
||||
# Platform-specific
|
||||
ahash.workspace = true
|
||||
calloop.workspace = true
|
||||
foldhash.workspace = true
|
||||
libc.workspace = true
|
||||
memmap2.workspace = true
|
||||
rustix = { workspace = true, features = ["std", "system", "thread", "process", "event", "pipe"] }
|
||||
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"] }
|
||||
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
|
||||
winit-common = { workspace = true, features = ["xkb", "wayland"] }
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
|
||||
@@ -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::{Connection, QueueHandle, globals};
|
||||
use sctk::reexports::client::{globals, Connection, QueueHandle};
|
||||
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::{WindowId, logical_to_physical_rounded};
|
||||
use super::{logical_to_physical_rounded, WindowId};
|
||||
|
||||
type WaylandDispatcher = calloop::Dispatcher<'static, WaylandSource<WinitState>, WinitState>;
|
||||
|
||||
@@ -169,6 +169,10 @@ impl EventLoop {
|
||||
Ok(event_loop)
|
||||
}
|
||||
|
||||
pub fn run_app<A: ApplicationHandler>(mut self, app: A) -> Result<(), EventLoopError> {
|
||||
self.run_app_on_demand(app)
|
||||
}
|
||||
|
||||
pub fn run_app_on_demand<A: ApplicationHandler>(
|
||||
&mut self,
|
||||
mut app: A,
|
||||
@@ -635,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())
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -13,16 +13,12 @@
|
||||
//! * `wayland-csd-adwaita` (default).
|
||||
//! * `wayland-csd-adwaita-crossfont`.
|
||||
//! * `wayland-csd-adwaita-notitle`.
|
||||
//! * `wayland-csd-adwaita-notitlebar`.
|
||||
|
||||
#![allow(clippy::mutable_key_type)]
|
||||
|
||||
use std::ffi::c_void;
|
||||
use std::ptr::NonNull;
|
||||
|
||||
use dpi::{LogicalSize, PhysicalSize};
|
||||
use sctk::reexports::client::Proxy;
|
||||
use sctk::reexports::client::protocol::wl_surface::WlSurface;
|
||||
use sctk::reexports::client::Proxy;
|
||||
use sctk::shm::slot::{Buffer, CreateBufferError, SlotPool};
|
||||
use wayland_client::protocol::wl_shm::Format;
|
||||
use winit_core::event_loop::ActiveEventLoop as CoreActiveEventLoop;
|
||||
@@ -31,7 +27,9 @@ 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;
|
||||
@@ -63,7 +61,7 @@ pub trait EventLoopExtWayland {
|
||||
fn is_wayland(&self) -> bool;
|
||||
}
|
||||
|
||||
/// Additional methods when building event loop that are specific to Wayland.
|
||||
/// Additional methods on [`EventLoopBuilder`] that are specific to Wayland.
|
||||
pub trait EventLoopBuilderExtWayland {
|
||||
/// Force using Wayland.
|
||||
fn with_wayland(&mut self) -> &mut Self;
|
||||
@@ -101,7 +99,6 @@ 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 {
|
||||
@@ -123,18 +120,6 @@ 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 {
|
||||
|
||||
@@ -3,8 +3,8 @@ use std::num::NonZeroU32;
|
||||
|
||||
use dpi::{LogicalPosition, PhysicalPosition};
|
||||
use sctk::output::{Mode, OutputData};
|
||||
use sctk::reexports::client::Proxy;
|
||||
use sctk::reexports::client::protocol::wl_output::WlOutput;
|
||||
use sctk::reexports::client::Proxy;
|
||||
use winit_core::monitor::{MonitorHandleProvider as CoreMonitorHandle, VideoMode};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
|
||||
@@ -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,23 +129,20 @@ impl Dispatch<WlKeyboard, KeyboardData, WinitState> for WinitState {
|
||||
state.events_sink.push_window_event(WindowEvent::Focused(false), window_id);
|
||||
}
|
||||
},
|
||||
WlKeyboardEvent::Key { key, state: WEnum::Value(key_state), .. }
|
||||
if matches!(key_state, WlKeyState::Repeated | WlKeyState::Pressed) =>
|
||||
{
|
||||
WlKeyboardEvent::Key { key, state: WEnum::Value(WlKeyState::Pressed), .. } => {
|
||||
let key = key + 8;
|
||||
|
||||
key_input(
|
||||
keyboard_state,
|
||||
&mut state.events_sink,
|
||||
data,
|
||||
key,
|
||||
ElementState::Pressed,
|
||||
key_state == WlKeyState::Repeated,
|
||||
false,
|
||||
);
|
||||
|
||||
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,
|
||||
};
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use foldhash::HashMap;
|
||||
use ahash::AHashMap;
|
||||
use sctk::reexports::client::backend::ObjectId;
|
||||
use sctk::reexports::client::protocol::wl_seat::WlSeat;
|
||||
use sctk::reexports::client::protocol::wl_touch::WlTouch;
|
||||
@@ -12,8 +12,6 @@ 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;
|
||||
|
||||
@@ -25,7 +23,6 @@ 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;
|
||||
@@ -43,7 +40,7 @@ pub struct WinitSeatState {
|
||||
touch: Option<WlTouch>,
|
||||
|
||||
/// The mapping from touched points to the surfaces they're present.
|
||||
touch_map: HashMap<i32, TouchPoint>,
|
||||
touch_map: AHashMap<i32, TouchPoint>,
|
||||
|
||||
/// Id of the first touch event.
|
||||
first_touch_id: Option<i32>,
|
||||
@@ -51,15 +48,9 @@ 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>,
|
||||
|
||||
@@ -133,14 +124,6 @@ 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.
|
||||
@@ -160,12 +143,6 @@ 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(
|
||||
@@ -187,11 +164,6 @@ 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() {
|
||||
@@ -205,10 +177,6 @@ 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();
|
||||
|
||||
|
||||
@@ -30,13 +30,12 @@ use sctk::seat::SeatState;
|
||||
use dpi::{LogicalPosition, PhysicalPosition};
|
||||
use winit_core::event::{
|
||||
ElementState, MouseButton, MouseScrollDelta, PointerKind, PointerSource, TouchPhase,
|
||||
WindowEvent, ButtonSource,
|
||||
WindowEvent,
|
||||
};
|
||||
|
||||
use crate::state::WinitState;
|
||||
use crate::WindowId;
|
||||
|
||||
pub mod pointer_gesture;
|
||||
pub mod relative_pointer;
|
||||
|
||||
impl PointerHandler for WinitState {
|
||||
@@ -108,8 +107,8 @@ impl PointerHandler for WinitState {
|
||||
if parent_surface != surface =>
|
||||
{
|
||||
let click = match wayland_button_to_winit(button) {
|
||||
ButtonSource::Mouse(MouseButton::Left) => FrameClick::Normal,
|
||||
ButtonSource::Mouse(MouseButton::Right) => FrameClick::Alternate,
|
||||
MouseButton::Left => FrameClick::Normal,
|
||||
MouseButton::Right => FrameClick::Alternate,
|
||||
_ => continue,
|
||||
};
|
||||
let pressed = matches!(kind, PointerEventKind::Press { .. });
|
||||
@@ -186,7 +185,7 @@ impl PointerHandler for WinitState {
|
||||
device_id: None,
|
||||
state,
|
||||
position,
|
||||
button,
|
||||
button: button.into(),
|
||||
},
|
||||
window_id,
|
||||
);
|
||||
@@ -195,7 +194,6 @@ 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.
|
||||
@@ -207,7 +205,7 @@ impl PointerHandler for WinitState {
|
||||
} else {
|
||||
match pointer_data.phase {
|
||||
// Discrete scroll only results in moved events.
|
||||
_ if has_value120_scroll || has_discrete_scroll => TouchPhase::Moved,
|
||||
_ if has_discrete_scroll => TouchPhase::Moved,
|
||||
TouchPhase::Started | TouchPhase::Moved => TouchPhase::Moved,
|
||||
_ => TouchPhase::Started,
|
||||
}
|
||||
@@ -218,13 +216,7 @@ 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_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 {
|
||||
let delta = if has_discrete_scroll {
|
||||
// NOTE: Wayland sign convention is the inverse of winit.
|
||||
MouseScrollDelta::LineDelta(
|
||||
(-horizontal.discrete) as f32,
|
||||
@@ -409,16 +401,23 @@ impl Default for WinitPointerDataInner {
|
||||
}
|
||||
|
||||
/// Convert the Wayland button into winit.
|
||||
fn wayland_button_to_winit(button: u32) -> ButtonSource {
|
||||
fn wayland_button_to_winit(button: u32) -> MouseButton {
|
||||
// These values are coming from <linux/input-event-codes.h>.
|
||||
const BTN_MOUSE: u32 = 0x110;
|
||||
const BTN_JOYSTICK: u32 = 0x120;
|
||||
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;
|
||||
|
||||
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)
|
||||
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),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,157 +0,0 @@
|
||||
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);
|
||||
@@ -4,16 +4,14 @@ 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::{Connection, Dispatch, Proxy, QueueHandle, delegate_dispatch};
|
||||
use sctk::reexports::client::{delegate_dispatch, Connection, Dispatch, Proxy, QueueHandle};
|
||||
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, ImeHint, ImePurpose, ImeRequestData, ImeSurroundingText,
|
||||
};
|
||||
use winit_core::window::{ImeCapabilities, ImePurpose, ImeRequestData, ImeSurroundingText};
|
||||
|
||||
use crate::state::WinitState;
|
||||
|
||||
@@ -84,7 +82,6 @@ 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();
|
||||
@@ -130,13 +127,6 @@ 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:
|
||||
@@ -150,7 +140,7 @@ impl Dispatch<ZwpTextInputV3, TextInputData, WinitState> for TextInputState {
|
||||
// 6. Place cursor inside preedit text.
|
||||
|
||||
if let Some(DeleteSurroundingText { before, after }) =
|
||||
text_input_data.pending_delete.take()
|
||||
text_input_data.pending_delete
|
||||
{
|
||||
state.events_sink.push_window_event(
|
||||
WindowEvent::Ime(Ime::DeleteSurrounding {
|
||||
@@ -161,17 +151,14 @@ impl Dispatch<ZwpTextInputV3, TextInputData, WinitState> for TextInputState {
|
||||
);
|
||||
}
|
||||
|
||||
// Clear preedit, unless all we'll be doing next is sending a new preedit and
|
||||
// the last preedit wasn't empty.
|
||||
// Clear preedit, unless all we'll be doing next is sending a new preedit.
|
||||
if text_input_data.pending_commit.is_some()
|
||||
|| (text_input_data.pending_preedit.is_none()
|
||||
&& !text_input_data.last_preedit_empty)
|
||||
|| text_input_data.pending_preedit.is_none()
|
||||
{
|
||||
state.events_sink.push_window_event(
|
||||
WindowEvent::Ime(Ime::Preedit(String::new(), None)),
|
||||
window_id,
|
||||
);
|
||||
text_input_data.last_preedit_empty = true;
|
||||
}
|
||||
|
||||
// Send `Commit`.
|
||||
@@ -186,7 +173,6 @@ 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,
|
||||
@@ -250,6 +236,7 @@ pub struct TextInputData {
|
||||
inner: std::sync::Mutex<TextInputDataInner>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct TextInputDataInner {
|
||||
/// The `WlSurface` we're performing input to.
|
||||
surface: Option<WlSurface>,
|
||||
@@ -262,21 +249,6 @@ 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.
|
||||
@@ -306,7 +278,9 @@ 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>),
|
||||
|
||||
@@ -328,10 +302,8 @@ impl ClientState {
|
||||
surrounding_text: ImeSurroundingText::new(String::new(), 0, 0).unwrap(),
|
||||
};
|
||||
|
||||
let unsupported_flags = capabilities
|
||||
.without_hint_and_purpose()
|
||||
.without_cursor_area()
|
||||
.without_surrounding_text();
|
||||
let unsupported_flags =
|
||||
capabilities.without_purpose().without_cursor_area().without_surrounding_text();
|
||||
|
||||
if unsupported_flags != ImeCapabilities::new() {
|
||||
warn!(
|
||||
@@ -350,10 +322,12 @@ 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((hint, purpose)) =
|
||||
request_data.hint_and_purpose.filter(|_| self.capabilities.hint_and_purpose())
|
||||
{
|
||||
self.content_type = (hint, purpose).into();
|
||||
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((position, size)) = request_data.cursor_area {
|
||||
@@ -376,7 +350,7 @@ impl ClientState {
|
||||
}
|
||||
|
||||
pub fn content_type(&self) -> Option<ContentType> {
|
||||
self.capabilities.hint_and_purpose().then_some(self.content_type)
|
||||
self.capabilities.purpose().then_some(self.content_type)
|
||||
}
|
||||
|
||||
pub fn cursor_area(&self) -> Option<(LogicalPosition<u32>, LogicalSize<u32>)> {
|
||||
@@ -391,69 +365,20 @@ impl ClientState {
|
||||
/// Arguments to content_type
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct ContentType {
|
||||
/// Text input hint.
|
||||
hint: ContentHint,
|
||||
/// Text input purpose.
|
||||
/// Text input purpose
|
||||
purpose: ContentPurpose,
|
||||
hint: ContentHint,
|
||||
}
|
||||
|
||||
/// 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,
|
||||
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(),
|
||||
};
|
||||
|
||||
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 }
|
||||
Self { hint, purpose }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ use std::cell::RefCell;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use foldhash::HashMap;
|
||||
use ahash::AHashMap;
|
||||
use sctk::compositor::{CompositorHandler, CompositorState};
|
||||
use sctk::output::{OutputHandler, OutputState};
|
||||
use sctk::reexports::calloop::LoopHandle;
|
||||
@@ -12,30 +12,29 @@ 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::SeatState;
|
||||
use sctk::seat::pointer::ThemedPointer;
|
||||
use sctk::shell::WaylandSurface;
|
||||
use sctk::shell::xdg::XdgShell;
|
||||
use sctk::seat::SeatState;
|
||||
use sctk::shell::xdg::window::{Window, WindowConfigure, WindowHandler};
|
||||
use sctk::shell::xdg::XdgShell;
|
||||
use sctk::shell::WaylandSurface;
|
||||
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, PointerGesturesState, RelativePointerState, TextInputState,
|
||||
WinitPointerData, WinitPointerDataExt, WinitSeatState,
|
||||
PointerConstraintsState, 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)]
|
||||
@@ -62,10 +61,10 @@ pub struct WinitState {
|
||||
pub xdg_shell: XdgShell,
|
||||
|
||||
/// The currently present windows.
|
||||
pub windows: RefCell<HashMap<WindowId, Arc<Mutex<WindowState>>>>,
|
||||
pub windows: RefCell<AHashMap<WindowId, Arc<Mutex<WindowState>>>>,
|
||||
|
||||
/// The requests from the `Window` to EventLoop, such as close operations and redraw requests.
|
||||
pub window_requests: RefCell<HashMap<WindowId, Arc<WindowRequests>>>,
|
||||
pub window_requests: RefCell<AHashMap<WindowId, Arc<WindowRequests>>>,
|
||||
|
||||
/// The events that were generated directly from the window.
|
||||
pub window_events_sink: Arc<Mutex<EventSink>>,
|
||||
@@ -74,10 +73,10 @@ pub struct WinitState {
|
||||
pub window_compositor_updates: Vec<WindowCompositorUpdate>,
|
||||
|
||||
/// Currently handled seats.
|
||||
pub seats: HashMap<ObjectId, WinitSeatState>,
|
||||
pub seats: AHashMap<ObjectId, WinitSeatState>,
|
||||
|
||||
/// Currently present cursor surfaces.
|
||||
pub pointer_surfaces: HashMap<ObjectId, Arc<ThemedPointer<WinitPointerData>>>,
|
||||
pub pointer_surfaces: AHashMap<ObjectId, Arc<ThemedPointer<WinitPointerData>>>,
|
||||
|
||||
/// The state of the text input on the client.
|
||||
pub text_input_state: Option<TextInputState>,
|
||||
@@ -101,15 +100,9 @@ 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>,
|
||||
|
||||
@@ -156,7 +149,7 @@ impl WinitState {
|
||||
|
||||
let seat_state = SeatState::new(globals, queue_handle);
|
||||
|
||||
let mut seats = HashMap::default();
|
||||
let mut seats = AHashMap::default();
|
||||
for seat in seat_state.seats() {
|
||||
seats.insert(seat.id(), WinitSeatState::new());
|
||||
}
|
||||
@@ -198,12 +191,10 @@ 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(),
|
||||
|
||||
@@ -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::{Connection, Dispatch, Proxy, QueueHandle, delegate_dispatch};
|
||||
use sctk::reexports::client::{delegate_dispatch, Connection, Dispatch, Proxy, QueueHandle};
|
||||
use wayland_protocols_plasma::blur::client::org_kde_kwin_blur::OrgKdeKwinBlur;
|
||||
use wayland_protocols_plasma::blur::client::org_kde_kwin_blur_manager::OrgKdeKwinBlurManager;
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
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;
|
||||
|
||||
@@ -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::{Connection, Dispatch, Proxy, QueueHandle, delegate_dispatch};
|
||||
use sctk::reexports::client::{delegate_dispatch, Connection, Dispatch, Proxy, QueueHandle};
|
||||
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,
|
||||
|
||||
@@ -1,412 +0,0 @@
|
||||
//! 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 wayland_protocols::wp::tablet::zv2::client::zwp_tablet_pad_dial_v2::ZwpTabletPadDialV2;
|
||||
use wayland_protocols::wp::tablet::zv2::client::zwp_tablet_pad_group_v2::{
|
||||
self, ZwpTabletPadGroupV2,
|
||||
};
|
||||
use wayland_protocols::wp::tablet::zv2::client::zwp_tablet_pad_ring_v2::ZwpTabletPadRingV2;
|
||||
use wayland_protocols::wp::tablet::zv2::client::zwp_tablet_pad_strip_v2::ZwpTabletPadStripV2;
|
||||
use wayland_protocols::wp::tablet::zv2::client::zwp_tablet_pad_v2;
|
||||
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 {
|
||||
event_created_child!(WinitState, ZwpTabletPadV2, [
|
||||
zwp_tablet_pad_v2::EVT_GROUP_OPCODE => (ZwpTabletPadGroupV2, Default::default()),
|
||||
]);
|
||||
|
||||
fn event(
|
||||
_: &mut WinitState,
|
||||
_: &ZwpTabletPadV2,
|
||||
_: <ZwpTabletPadV2 as Proxy>::Event,
|
||||
_: &(),
|
||||
_: &Connection,
|
||||
_: &QueueHandle<WinitState>,
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
||||
impl Dispatch<ZwpTabletPadGroupV2, (), WinitState> for TabletManager {
|
||||
event_created_child!(WinitState, ZwpTabletPadGroupV2, [
|
||||
zwp_tablet_pad_group_v2::EVT_RING_OPCODE => (ZwpTabletPadRingV2, Default::default()),
|
||||
zwp_tablet_pad_group_v2::EVT_STRIP_OPCODE => (ZwpTabletPadStripV2, Default::default()),
|
||||
zwp_tablet_pad_group_v2::EVT_DIAL_OPCODE => (ZwpTabletPadDialV2, Default::default()),
|
||||
]);
|
||||
|
||||
fn event(
|
||||
_: &mut WinitState,
|
||||
_: &ZwpTabletPadGroupV2,
|
||||
_: <ZwpTabletPadGroupV2 as Proxy>::Event,
|
||||
_: &(),
|
||||
_: &Connection,
|
||||
_: &QueueHandle<WinitState>,
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
||||
impl Dispatch<ZwpTabletPadRingV2, (), WinitState> for TabletManager {
|
||||
fn event(
|
||||
_: &mut WinitState,
|
||||
_: &ZwpTabletPadRingV2,
|
||||
_: <ZwpTabletPadRingV2 as Proxy>::Event,
|
||||
_: &(),
|
||||
_: &Connection,
|
||||
_: &QueueHandle<WinitState>,
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
||||
impl Dispatch<ZwpTabletPadStripV2, (), WinitState> for TabletManager {
|
||||
fn event(
|
||||
_: &mut WinitState,
|
||||
_: &ZwpTabletPadStripV2,
|
||||
_: <ZwpTabletPadStripV2 as Proxy>::Event,
|
||||
_: &(),
|
||||
_: &Connection,
|
||||
_: &QueueHandle<WinitState>,
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
||||
impl Dispatch<ZwpTabletPadDialV2, (), WinitState> for TabletManager {
|
||||
fn event(
|
||||
_: &mut WinitState,
|
||||
_: &ZwpTabletPadDialV2,
|
||||
_: <ZwpTabletPadDialV2 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);
|
||||
delegate_dispatch!(WinitState: [ZwpTabletPadGroupV2: ()] => TabletManager);
|
||||
delegate_dispatch!(WinitState: [ZwpTabletPadRingV2: ()] => TabletManager);
|
||||
delegate_dispatch!(WinitState: [ZwpTabletPadStripV2: ()] => TabletManager);
|
||||
delegate_dispatch!(WinitState: [ZwpTabletPadDialV2: ()] => TabletManager);
|
||||
@@ -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::{Connection, Dispatch, Proxy, QueueHandle, delegate_dispatch};
|
||||
use sctk::reexports::client::{delegate_dispatch, Connection, Dispatch, Proxy, QueueHandle};
|
||||
use sctk::reexports::protocols::wp::viewporter::client::wp_viewport::WpViewport;
|
||||
use sctk::reexports::protocols::wp::viewporter::client::wp_viewporter::WpViewporter;
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
//! Handling of xdg activation, which is used for user attention requests.
|
||||
|
||||
use std::sync::Weak;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::Weak;
|
||||
|
||||
use sctk::globals::GlobalData;
|
||||
use sctk::reexports::client::globals::{BindError, GlobalList};
|
||||
use sctk::reexports::client::protocol::wl_surface::WlSurface;
|
||||
use sctk::reexports::client::{Connection, Dispatch, Proxy, QueueHandle, delegate_dispatch};
|
||||
use sctk::reexports::client::{delegate_dispatch, Connection, Dispatch, Proxy, QueueHandle};
|
||||
use sctk::reexports::protocols::xdg::activation::v1::client::xdg_activation_token_v1::{
|
||||
Event as ActivationTokenEvent, XdgActivationTokenV1,
|
||||
};
|
||||
|
||||
@@ -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::{Connection, Dispatch, Proxy, QueueHandle, delegate_dispatch};
|
||||
use wayland_client::{delegate_dispatch, Connection, Dispatch, Proxy, QueueHandle};
|
||||
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};
|
||||
|
||||
@@ -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::WaylandSurface;
|
||||
use sctk::shell::xdg::window::{Window as SctkWindow, WindowDecorations};
|
||||
use sctk::shell::WaylandSurface;
|
||||
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 crate::{WindowAttributesWayland, output};
|
||||
use super::ActiveEventLoop;
|
||||
use crate::{output, WindowAttributesWayland};
|
||||
|
||||
pub(crate) mod state;
|
||||
|
||||
@@ -106,12 +106,6 @@ 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,
|
||||
@@ -119,7 +113,6 @@ impl Window {
|
||||
size,
|
||||
window.clone(),
|
||||
attributes.preferred_theme,
|
||||
prefer_csd,
|
||||
);
|
||||
|
||||
window_state.set_window_icon(attributes.window_icon);
|
||||
@@ -132,6 +125,13 @@ 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);
|
||||
@@ -171,12 +171,6 @@ impl Window {
|
||||
Cursor::Custom(cursor) => window_state.set_custom_cursor(cursor),
|
||||
}
|
||||
|
||||
// Apply resize increments.
|
||||
if let Some(increments) = attributes.surface_resize_increments {
|
||||
let increments = increments.to_logical(window_state.scale_factor());
|
||||
window_state.set_resize_increments(Some(increments));
|
||||
}
|
||||
|
||||
// Activate the window when the token is passed.
|
||||
if let (Some(xdg_activation), Some(token)) = (xdg_activation.as_ref(), activation_token) {
|
||||
xdg_activation.activate(token.into_raw(), &surface);
|
||||
@@ -376,18 +370,11 @@ impl CoreWindow for Window {
|
||||
}
|
||||
|
||||
fn surface_resize_increments(&self) -> Option<PhysicalSize<u32>> {
|
||||
let window_state = self.window_state.lock().unwrap();
|
||||
let scale_factor = window_state.scale_factor();
|
||||
window_state
|
||||
.resize_increments()
|
||||
.map(|size| super::logical_to_physical_rounded(size, scale_factor))
|
||||
None
|
||||
}
|
||||
|
||||
fn set_surface_resize_increments(&self, increments: Option<Size>) {
|
||||
let mut window_state = self.window_state.lock().unwrap();
|
||||
let scale_factor = window_state.scale_factor();
|
||||
let increments = increments.map(|size| size.to_logical(scale_factor));
|
||||
window_state.set_resize_increments(increments);
|
||||
fn set_surface_resize_increments(&self, _increments: Option<Size>) {
|
||||
warn!("`set_surface_resize_increments` is not implemented for Wayland");
|
||||
}
|
||||
|
||||
fn set_title(&self, title: &str) {
|
||||
@@ -444,7 +431,11 @@ 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 {
|
||||
|
||||
@@ -4,8 +4,8 @@ use std::num::NonZeroU32;
|
||||
use std::sync::{Arc, Mutex, Weak};
|
||||
use std::time::Duration;
|
||||
|
||||
use ahash::HashSet;
|
||||
use dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize, Size};
|
||||
use foldhash::HashSet;
|
||||
use sctk::compositor::{CompositorState, Region, SurfaceData, SurfaceDataExt};
|
||||
use sctk::globals::GlobalData;
|
||||
use sctk::reexports::client::backend::ObjectId;
|
||||
@@ -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::WaylandSurface;
|
||||
use sctk::shell::xdg::XdgSurface;
|
||||
use sctk::shell::xdg::window::{DecorationMode, Window, WindowConfigure};
|
||||
use sctk::shm::Shm;
|
||||
use sctk::shell::xdg::XdgSurface;
|
||||
use sctk::shell::WaylandSurface;
|
||||
use sctk::shm::slot::SlotPool;
|
||||
use sctk::shm::Shm;
|
||||
use sctk::subcompositor::SubcompositorState;
|
||||
use tracing::{info, warn};
|
||||
use wayland_protocols::xdg::toplevel_icon::v1::client::xdg_toplevel_icon_manager_v1::XdgToplevelIconManagerV1;
|
||||
@@ -134,13 +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>>,
|
||||
resize_increments: Option<LogicalSize<u32>>,
|
||||
|
||||
/// The size of the window when no states were applied to it. The primary use for it
|
||||
/// is to fallback to original window size, before it was maximized, if the compositor
|
||||
@@ -184,7 +180,6 @@ 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();
|
||||
@@ -214,7 +209,6 @@ impl WindowState {
|
||||
selected_cursor: Default::default(),
|
||||
cursor_visible: true,
|
||||
decorate: true,
|
||||
prefer_csd,
|
||||
fractional_scale,
|
||||
frame: None,
|
||||
frame_callback_state: FrameCallbackState::None,
|
||||
@@ -224,7 +218,6 @@ impl WindowState {
|
||||
last_configure: None,
|
||||
max_surface_size: None,
|
||||
min_surface_size: MIN_WINDOW_SIZE,
|
||||
resize_increments: None,
|
||||
pointer_constraints,
|
||||
pointers: Default::default(),
|
||||
queue_handle: queue_handle.clone(),
|
||||
@@ -309,7 +302,7 @@ impl WindowState {
|
||||
subcompositor.clone(),
|
||||
self.queue_handle.clone(),
|
||||
#[cfg(feature = "sctk-adwaita")]
|
||||
create_sctk_adwaita_config(self.theme),
|
||||
into_sctk_adwaita_config(self.theme),
|
||||
) {
|
||||
Ok(mut frame) => {
|
||||
frame.set_title(&self.title);
|
||||
@@ -363,42 +356,6 @@ impl WindowState {
|
||||
.unwrap_or(new_size.height);
|
||||
}
|
||||
|
||||
// Apply size increments.
|
||||
//
|
||||
// We conditionally apply increments to avoid conflicts with the compositor's layout rules:
|
||||
// 1. If the window is floating (constrain == true), we snap to increments to ensure the
|
||||
// app's grid alignment.
|
||||
// 2. If the user is interactively resizing (is_resizing), we snap the size to provide
|
||||
// feedback.
|
||||
//
|
||||
// However, we MUST NOT snap if the compositor enforces a specific size (constrain == false,
|
||||
// or states like Maximized/Tiled). Snapping in these cases (e.g. corner tiling) would
|
||||
// shrink the window below the allocated area, creating visible gaps between valid
|
||||
// windows or screen edges.
|
||||
if (constrain || configure.is_resizing())
|
||||
&& !configure.is_maximized()
|
||||
&& !configure.is_fullscreen()
|
||||
&& !configure.is_tiled()
|
||||
{
|
||||
if let Some(increments) = self.resize_increments {
|
||||
// We use min size as a base size for the increments, similar to how X11 does it.
|
||||
//
|
||||
// This ensures that we can always reach the min size and the increments are
|
||||
// calculated from it.
|
||||
let (delta_width, delta_height) = (
|
||||
new_size.width.saturating_sub(self.min_surface_size.width),
|
||||
new_size.height.saturating_sub(self.min_surface_size.height),
|
||||
);
|
||||
|
||||
let width = self.min_surface_size.width
|
||||
+ (delta_width / increments.width) * increments.width;
|
||||
let height = self.min_surface_size.height
|
||||
+ (delta_height / increments.height) * increments.height;
|
||||
|
||||
new_size = (width, height).into();
|
||||
}
|
||||
}
|
||||
|
||||
let new_state = configure.state;
|
||||
let old_state = self.last_configure.as_ref().map(|configure| configure.state);
|
||||
|
||||
@@ -787,18 +744,6 @@ impl WindowState {
|
||||
self.selected_cursor = SelectedCursor::Custom(cursor);
|
||||
}
|
||||
|
||||
/// Set the resize increments of the window.
|
||||
pub fn set_resize_increments(&mut self, increments: Option<LogicalSize<u32>>) {
|
||||
self.resize_increments = increments;
|
||||
// NOTE: We don't update the window size here, because it will be done on the next resize
|
||||
// or configure event.
|
||||
}
|
||||
|
||||
/// Get the resize increments of the window.
|
||||
pub fn resize_increments(&self) -> Option<LogicalSize<u32>> {
|
||||
self.resize_increments
|
||||
}
|
||||
|
||||
fn apply_custom_cursor(&self, cursor: &CustomCursor) {
|
||||
self.apply_on_pointer(|pointer, data| {
|
||||
let surface = pointer.surface();
|
||||
@@ -871,7 +816,7 @@ impl WindowState {
|
||||
self.theme = theme;
|
||||
#[cfg(feature = "sctk-adwaita")]
|
||||
if let Some(frame) = self.frame.as_mut() {
|
||||
frame.set_config(create_sctk_adwaita_config(theme))
|
||||
frame.set_config(into_sctk_adwaita_config(theme))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -907,7 +852,7 @@ impl WindowState {
|
||||
None => {
|
||||
return Err(
|
||||
NotSupportedError::new("zwp_pointer_constraints is not available").into()
|
||||
);
|
||||
)
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1010,7 +955,7 @@ impl WindowState {
|
||||
/// Whether show or hide client side decorations.
|
||||
#[inline]
|
||||
pub fn set_decorate(&mut self, decorate: bool) {
|
||||
if decorate == self.decorate && !self.prefer_csd {
|
||||
if decorate == self.decorate {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1021,9 +966,6 @@ 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)),
|
||||
_ => (),
|
||||
}
|
||||
@@ -1095,7 +1037,11 @@ 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.
|
||||
@@ -1282,14 +1228,12 @@ fn resize_direction_to_xdg(direction: ResizeDirection) -> XdgResizeEdge {
|
||||
}
|
||||
}
|
||||
|
||||
// NOTE: Rust doesn't allow `From<Option<Theme>>`.
|
||||
#[cfg(feature = "sctk-adwaita")]
|
||||
fn create_sctk_adwaita_config(theme: Option<Theme>) -> sctk_adwaita::FrameConfig {
|
||||
let config = match theme {
|
||||
fn into_sctk_adwaita_config(theme: Option<Theme>) -> sctk_adwaita::FrameConfig {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||